python.js 289 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337
  1. // Experimental Python Execution
  2. var python = python || {};
  3. python.Parser = class {
  4. constructor(text, file, debug) {
  5. this._tokenizer = new python.Tokenizer(text, file);
  6. this._debug = debug;
  7. python.Parser._precedence = python.Parser._precedence || {
  8. 'or': 2, 'and': 3, 'not' : 4,
  9. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  10. '|': 6, '^' : 7, '&' : 8,
  11. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  12. // '+': 12, '-': 12,
  13. '~': 13, '**': 14
  14. };
  15. }
  16. parse() {
  17. const node = this._node('program');
  18. node.body = [];
  19. while (!this._tokenizer.match('eof')) {
  20. const statement = this._statement();
  21. if (statement) {
  22. node.body.push(statement);
  23. continue;
  24. }
  25. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type == 'eof') {
  26. continue;
  27. }
  28. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type == 'eof') {
  29. continue;
  30. }
  31. throw new python.Error('Unsupported statement' + this._tokenizer.location());
  32. }
  33. return node;
  34. }
  35. _suite() {
  36. const node = this._node('block');
  37. node.statements = [];
  38. let statement = null;
  39. if (this._tokenizer.eat('\n')) {
  40. if (this._tokenizer.eat('indent')) {
  41. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  42. if (this._tokenizer.eat(';')) {
  43. continue;
  44. }
  45. statement = this._statement();
  46. if (statement) {
  47. node.statements.push(statement);
  48. continue;
  49. }
  50. if (this._tokenizer.eat('\n')) {
  51. continue;
  52. }
  53. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  54. continue;
  55. }
  56. throw new python.Error('Empty statement' + this._tokenizer.location());
  57. }
  58. }
  59. }
  60. else if (!this._tokenizer.eat('eof')) {
  61. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  62. if (this._tokenizer.eat(';')) {
  63. continue;
  64. }
  65. statement = this._statement();
  66. if (statement) {
  67. node.statements.push(statement);
  68. continue;
  69. }
  70. throw new python.Error('Empty statement' + this._tokenizer.location());
  71. }
  72. this._tokenizer.eat('\n');
  73. }
  74. return node;
  75. }
  76. _statement() {
  77. let node = this._eat('id', 'break');
  78. if (node) {
  79. return node;
  80. }
  81. node = this._eat('id', 'continue');
  82. if (node) {
  83. return node;
  84. }
  85. node = this._eat('id', 'return');
  86. if (node) {
  87. node.expression = this._expression(-1, [], true);
  88. return node;
  89. }
  90. node = this._eat('id', 'raise');
  91. if (node) {
  92. node.exception = this._expression(-1, [ 'from' ]);
  93. if (this._tokenizer.eat('id', 'from')) {
  94. node.from = this._expression();
  95. }
  96. else if (this._tokenizer.eat(',')) {
  97. node.exception = [ node.exception ];
  98. node.exception.push(this._expression());
  99. if (this._tokenizer.eat(',')) {
  100. node.exception.push(this._expression());
  101. }
  102. }
  103. return node;
  104. }
  105. node = this._eat('id', 'assert');
  106. if (node) {
  107. node.condition = this._expression(-1, [ ',' ]);
  108. if (this._tokenizer.eat(',')) {
  109. node.message = this._expression();
  110. }
  111. return node;
  112. }
  113. node = this._eat('id', 'exec');
  114. if (node) {
  115. node.variable = this._expression(-1, [ 'in' ]);
  116. if (this._tokenizer.eat('in')) {
  117. do {
  118. node.target = node.target || [];
  119. node.target.push(this._expression(-1, [ 'in' ], false));
  120. }
  121. while (this._tokenizer.eat(','));
  122. }
  123. return node;
  124. }
  125. node = this._eat('id', 'global');
  126. if (node) {
  127. node.names = [];
  128. do {
  129. node.names.push(this._name(true).value);
  130. }
  131. while (this._tokenizer.eat(','));
  132. return node;
  133. }
  134. node = this._eat('id', 'nonlocal');
  135. if (node) {
  136. node.names = [];
  137. do {
  138. node.names.push(this._name(true).value);
  139. }
  140. while (this._tokenizer.eat(','));
  141. return node;
  142. }
  143. node = this._eat('id', 'import');
  144. if (node) {
  145. node.names = [];
  146. do {
  147. const alias = this._node('alias');
  148. alias.name = this._dottedName();
  149. if (this._tokenizer.eat('id', 'as')) {
  150. alias.asname = this._name(true).value;
  151. }
  152. node.names.push(alias);
  153. }
  154. while (this._tokenizer.eat(','));
  155. return node;
  156. }
  157. node = this._eat('id', 'from');
  158. if (node) {
  159. node.type = 'import_from';
  160. node.level = 0;
  161. const dots = this._tokenizer.peek();
  162. if (dots && Array.from(dots.type).every((c) => c == '.')) {
  163. this._eat(dots.type);
  164. node.level = Array.from(dots.type).length;
  165. }
  166. node.module = this._dottedName();
  167. this._tokenizer.expect('id', 'import');
  168. node.names = [];
  169. const close = this._tokenizer.eat('(');
  170. do {
  171. const alias = this._node('alias');
  172. alias.name = this._name(true).value;
  173. if (this._tokenizer.eat('id', 'as')) {
  174. alias.asname = this._name(true).value;
  175. }
  176. node.names.push(alias);
  177. }
  178. while (this._tokenizer.eat(','));
  179. if (close) {
  180. this._tokenizer.expect(')');
  181. }
  182. return node;
  183. }
  184. let decorator_list = this._decorator();
  185. node = this._eat('id', 'class');
  186. if (node) {
  187. node.name = this._name(true).value;
  188. if (decorator_list) {
  189. node.decorator_list = Array.from(decorator_list);
  190. decorator_list = null;
  191. }
  192. if (this._tokenizer.peek().value === '(') {
  193. node.bases = this._arguments();
  194. }
  195. this._tokenizer.expect(':');
  196. node.body = this._suite();
  197. return node;
  198. }
  199. const async = this._eat('id', 'async');
  200. if (async &&
  201. !this._tokenizer.match('id', 'def') &&
  202. !this._tokenizer.match('id', 'with') &&
  203. !this._tokenizer.match('id', 'for')) {
  204. throw new python.Error("Expected 'def', 'with' or 'for'" + this._tokenizer.location());
  205. }
  206. node = this._eat('id', 'def');
  207. if (node) {
  208. if (async) {
  209. node.async = async;
  210. }
  211. node.name = this._name(true).value;
  212. if (decorator_list) {
  213. node.decorator_list = Array.from(decorator_list);
  214. decorator_list = null;
  215. }
  216. this._tokenizer.expect('(');
  217. node.parameters = this._parameters(')');
  218. if (this._tokenizer.eat('->')) {
  219. node.returnType = this._type();
  220. }
  221. this._tokenizer.expect(':');
  222. node.body = this._suite();
  223. return node;
  224. }
  225. if (decorator_list && decorator_list.length > 0) {
  226. throw new python.Error('Unexpected decorator.');
  227. }
  228. node = this._eat('id', 'del');
  229. if (node) {
  230. node.expression = this._expression(-1, [], true);
  231. return node;
  232. }
  233. node = this._eat('id', 'print');
  234. if (node) {
  235. node.expression = this._expression(-1, [], true);
  236. return node;
  237. }
  238. node = this._eat('id', 'if');
  239. if (node) {
  240. node.condition = this._expression();
  241. this._tokenizer.expect(':');
  242. node.then = this._suite();
  243. let current = node;
  244. this._tokenizer.eat('\n');
  245. while (this._tokenizer.eat('id', 'elif')) {
  246. current.else = this._node('if');
  247. current = current.else;
  248. current.condition = this._expression();
  249. this._tokenizer.expect(':');
  250. current.then = this._suite();
  251. this._tokenizer.eat('\n');
  252. }
  253. if (this._tokenizer.eat('id', 'else')) {
  254. this._tokenizer.expect(':');
  255. current.else = this._suite();
  256. }
  257. return node;
  258. }
  259. node = this._eat('id', 'while');
  260. if (node) {
  261. node.condition = this._expression();
  262. this._tokenizer.expect(':');
  263. node.body = this._suite();
  264. if (this._tokenizer.eat('id', 'else')) {
  265. this._tokenizer.expect(':');
  266. node.else = this._suite();
  267. }
  268. return node;
  269. }
  270. node = this._eat('id', 'pass');
  271. if (node) {
  272. return node;
  273. }
  274. node = this._eat('id', 'for');
  275. if (node) {
  276. node.variable = [];
  277. node.variable.push(this._expression(-1, [ 'in' ]));
  278. while (this._tokenizer.eat(',')) {
  279. if (this._tokenizer.match('id', 'in')) {
  280. node.variable.push({});
  281. break;
  282. }
  283. node.variable.push(this._expression(-1, [ 'in' ]));
  284. }
  285. this._tokenizer.expect('id', 'in');
  286. node.target = [];
  287. node.target.push(this._expression());
  288. while (this._tokenizer.eat(',')) {
  289. if (this._tokenizer.match(':')) {
  290. node.target.push({});
  291. break;
  292. }
  293. node.target.push(this._expression(-1, [ 'in' ]));
  294. }
  295. this._tokenizer.expect(':');
  296. node.body = this._suite();
  297. if (this._tokenizer.eat('id', 'else')) {
  298. this._tokenizer.expect(':');
  299. node.else = this._suite();
  300. }
  301. return node;
  302. }
  303. node = this._eat('id', 'with');
  304. if (node) {
  305. if (async) {
  306. node.async = async;
  307. }
  308. node.item = [];
  309. do {
  310. const item = this._node();
  311. item.type = 'with_item';
  312. item.expression = this._expression();
  313. if (this._tokenizer.eat('id', 'as')) {
  314. item.variable = this._expression();
  315. }
  316. node.item.push(item);
  317. }
  318. while (this._tokenizer.eat(','));
  319. this._tokenizer.expect(':');
  320. node.body = this._suite();
  321. return node;
  322. }
  323. node = this._eat('id', 'try');
  324. if (node) {
  325. this._tokenizer.expect(':');
  326. node.body = this._suite();
  327. node.except = [];
  328. while (this._tokenizer.match('id', 'except')) {
  329. const except = this._node('except');
  330. this._tokenizer.expect('id', 'except');
  331. except.clause = [];
  332. except.clause.push(this._expression());
  333. while (this._tokenizer.eat(',')) {
  334. if (this._tokenizer.match(':') || this._tokenizer.match('as')) {
  335. except.clause.push({});
  336. break;
  337. }
  338. except.clause.push(this._expression());
  339. }
  340. if (this._tokenizer.eat('id', 'as')) {
  341. except.variable = this._expression();
  342. }
  343. this._tokenizer.expect(':');
  344. except.body = this._suite();
  345. node.except.push(except);
  346. }
  347. if (this._tokenizer.match('id', 'else')) {
  348. node.else = this._node('else');
  349. this._tokenizer.expect('id', 'else');
  350. this._tokenizer.expect(':');
  351. node.else.body = this._suite();
  352. }
  353. if (this._tokenizer.match('id', 'finally')) {
  354. node.finally = this._node('finally');
  355. this._tokenizer.expect('id', 'finally');
  356. this._tokenizer.expect(':');
  357. node.finally.body = this._suite();
  358. }
  359. return node;
  360. }
  361. const expression = this._expression(-1, [], true);
  362. if (expression) {
  363. if (expression.type == 'id' && this._tokenizer.eat(':')) {
  364. node = this._node('var');
  365. node.name = expression.value;
  366. node.location = expression.location;
  367. node.variableType = this._expression(-1, [ '=' ]);
  368. if (this._tokenizer.eat('=')) {
  369. node.initializer = this._expression();
  370. }
  371. return node;
  372. }
  373. switch (expression.type) {
  374. case '=':
  375. case ':=':
  376. case '==':
  377. case '!=':
  378. case '+=':
  379. case '-=':
  380. case '*=':
  381. case '@=':
  382. case '/=':
  383. case '//=':
  384. case '**=':
  385. case '&=':
  386. case '|=':
  387. case '%=':
  388. case '>>=':
  389. case '<<=':
  390. case '>>':
  391. case '<<':
  392. case '>=':
  393. case '<=':
  394. case '<':
  395. case '>':
  396. case '%':
  397. case '^=':
  398. case '...':
  399. case 'call':
  400. case 'assert':
  401. case 'raise':
  402. case 'string':
  403. case 'list':
  404. case 'var':
  405. case '.':
  406. case '[]':
  407. case 'yield':
  408. case '+':
  409. case '-':
  410. case '*':
  411. case '**':
  412. case '@':
  413. case '/':
  414. case '//':
  415. case '~':
  416. case '&':
  417. case '^':
  418. case '|':
  419. case 'not':
  420. case 'id':
  421. case 'number':
  422. case 'in':
  423. case 'and':
  424. case 'or':
  425. case 'if':
  426. case 'for':
  427. case 'tuple':
  428. case 'lambda':
  429. case 'await':
  430. return expression;
  431. default:
  432. throw new python.Error("Unhandled expression" + this._tokenizer.location());
  433. }
  434. }
  435. return null;
  436. }
  437. _expression(minPrecedence, terminal, tuple) {
  438. minPrecedence = minPrecedence || -1;
  439. const terminalSet = new Set(terminal);
  440. const stack = [];
  441. for (;;) {
  442. let node = this._node();
  443. const token = this._tokenizer.peek();
  444. if (stack.length == 1 && terminalSet.has(token.value)) {
  445. break;
  446. }
  447. const precedence = python.Parser._precedence[token.value];
  448. if (precedence) {
  449. if (precedence >= minPrecedence) {
  450. this._tokenizer.read();
  451. node.type = token.value;
  452. if (token.type == 'id' && (token.value === 'in' || token.value === 'not')) {
  453. if (token.value === 'in') {
  454. node.type = 'in';
  455. }
  456. else if (this._tokenizer.eat('id', 'in')) {
  457. node.type = 'not in';
  458. }
  459. else {
  460. node.type = 'not';
  461. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  462. stack.push(node);
  463. continue;
  464. }
  465. }
  466. else if (token.value == '~') {
  467. node.type = '~';
  468. node.expression = this._expression(precedence, terminal, tuple === false ? false : true);
  469. stack.push(node);
  470. continue;
  471. }
  472. else if (token.type == 'id' && token.value == 'is') {
  473. if (this._tokenizer.eat('id', 'not')) {
  474. node.type = 'is not';
  475. }
  476. }
  477. if (stack.length > 0) {
  478. node.op = node.type;
  479. node.type = 'binary';
  480. node.left = stack.pop();
  481. node.right = this._expression(precedence, terminal, tuple === true ? true : false);
  482. }
  483. else {
  484. node.op = node.type;
  485. node.type = 'unary';
  486. node.operand = this._expression(precedence, terminal, tuple === true ? true : false);
  487. }
  488. stack.push(node);
  489. continue;
  490. }
  491. }
  492. if (this._tokenizer.eat(':=')) {
  493. node.type = ':=';
  494. node.target = stack.pop();
  495. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  496. stack.push(node);
  497. continue;
  498. }
  499. if (this._tokenizer.eat('=')) {
  500. node.type = '=';
  501. node.target = stack.pop();
  502. node.expression = this._expression(-1, terminal, tuple === false ? false : true);
  503. stack.push(node);
  504. continue;
  505. }
  506. switch (token.type) {
  507. case '-=':
  508. case '**=':
  509. case '*=':
  510. case '//=':
  511. case '/=':
  512. case '&=':
  513. case '%=':
  514. case '^=':
  515. case '+=':
  516. case '<<=':
  517. case '>>=':
  518. case '|=':
  519. case '@=':
  520. node = this._node(token.type);
  521. this._tokenizer.expect(token.type);
  522. node.target = stack.pop();
  523. node.expression = this._expression(-1, terminal, true);
  524. stack.push(node);
  525. continue;
  526. default:
  527. break;
  528. }
  529. node = this._eat('id', 'if');
  530. if (node) {
  531. node.then = stack.pop();
  532. node.condition = this._expression();
  533. this._tokenizer.expect('id', 'else');
  534. node.else = this._expression();
  535. stack.push(node);
  536. continue;
  537. }
  538. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  539. const async = this._eat('id', 'async');
  540. if (async && !this._tokenizer.match('id', 'for')) {
  541. throw new python.Error("Expected 'for'" + this._tokenizer.location());
  542. }
  543. node = this._eat('id', 'for');
  544. if (node) {
  545. if (async) {
  546. node.async = async;
  547. }
  548. node.expression = stack.pop();
  549. node.variable = this._expression(-1, [ 'in' ], true);
  550. this._tokenizer.expect('id', 'in');
  551. node.target = this._expression(-1, [ 'for', 'if' ], true);
  552. while (this._tokenizer.eat('id', 'if')) {
  553. node.condition = node.condition || [];
  554. node.condition.push(this._expression(-1, [ 'for', 'if' ]));
  555. }
  556. stack.push(node);
  557. }
  558. }
  559. node = this._eat('id', 'lambda');
  560. if (node) {
  561. node.parameters = this._parameters(':');
  562. node.body = this._expression(-1, terminal, false);
  563. stack.push(node);
  564. continue;
  565. }
  566. node = this._eat('id', 'yield');
  567. if (node) {
  568. if (this._tokenizer.eat('id', 'from')) {
  569. node.from = this._expression(-1, [], true);
  570. }
  571. else {
  572. node.expression = [];
  573. do {
  574. node.expression.push(this._expression(-1, [], false));
  575. }
  576. while (this._tokenizer.eat(','));
  577. }
  578. stack.push(node);
  579. continue;
  580. }
  581. node = this._eat('id', 'await');
  582. if (node) {
  583. node.expression = this._expression(minPrecedence, terminal, tuple);
  584. stack.push(node);
  585. continue;
  586. }
  587. node = this._eat('.');
  588. if (node) {
  589. this._tokenizer.eat('\n');
  590. node.target = stack.pop();
  591. node.member = this._name();
  592. stack.push(node);
  593. continue;
  594. }
  595. if (this._tokenizer.peek().value === '(') {
  596. if (stack.length == 0) {
  597. node = this._node('tuple');
  598. const args = this._arguments();
  599. if (args.length == 1) {
  600. stack.push(args[0]);
  601. }
  602. else {
  603. node.value = args;
  604. stack.push(node);
  605. }
  606. }
  607. else {
  608. node = this._node('call');
  609. node.target = stack.pop();
  610. node.arguments = this._arguments();
  611. stack.push(node);
  612. }
  613. continue;
  614. }
  615. if (this._tokenizer.peek().value === '[') {
  616. if (stack.length == 0) {
  617. stack.push(this._expressions());
  618. }
  619. else {
  620. node = this._node('[]');
  621. node.target = stack.pop();
  622. node.arguments = this._slice();
  623. stack.push(node);
  624. }
  625. continue;
  626. }
  627. if (this._tokenizer.peek().value == '{') {
  628. stack.push(this._dictOrSetMaker());
  629. continue;
  630. }
  631. node = this._node();
  632. const literal = this._literal();
  633. if (literal) {
  634. if (stack.length > 0 && literal.type == 'number' &&
  635. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  636. node.type = literal.value.substring(0, 1);
  637. literal.value = literal.value.substring(1);
  638. node.left = stack.pop();
  639. node.right = literal;
  640. stack.push(node);
  641. }
  642. else if (stack.length == 1 && literal.type == 'string' && stack[0].type == 'string') {
  643. stack[0].value += literal.value;
  644. }
  645. else {
  646. if (literal.type === 'number') {
  647. switch (literal.value) {
  648. case 'inf': literal.value = Infinity; break;
  649. case '-inf': literal.value = -Infinity; break;
  650. default: break;
  651. }
  652. }
  653. stack.push(literal);
  654. }
  655. continue;
  656. }
  657. if (this._tokenizer.peek().keyword) {
  658. break;
  659. }
  660. node = this._eat('...');
  661. if (node) {
  662. stack.push(node);
  663. continue;
  664. }
  665. const identifier = this._name();
  666. if (identifier) {
  667. stack.push(identifier);
  668. continue;
  669. }
  670. if (tuple === true && stack.length == 1 && this._tokenizer.eat(',')) {
  671. if (stack[0].type === 'tuple') {
  672. node = stack[0];
  673. }
  674. else {
  675. node = this._node('tuple');
  676. node.value = [ stack.pop() ];
  677. stack.push(node);
  678. }
  679. // for, bar, = <expr>
  680. if (this._tokenizer.peek().value === '=') {
  681. continue;
  682. }
  683. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  684. const nextTerminal = terminal.slice(0).concat([ ',', '=' ]);
  685. const expression = this._expression(minPrecedence, nextTerminal, tuple);
  686. if (expression) {
  687. node.value.push(expression);
  688. continue;
  689. }
  690. }
  691. break;
  692. }
  693. break;
  694. }
  695. if (stack.length == 1) {
  696. return stack.pop();
  697. }
  698. if (stack.length != 0) {
  699. throw new python.Error('Unexpected expression' + this._tokenizer.location());
  700. }
  701. return null;
  702. }
  703. _decorator() {
  704. let list = null;
  705. while (this._tokenizer.eat('@')) {
  706. const node = this._node('decorator');
  707. node.value = this._expression();
  708. if (!node.value || (node.value.type !== 'call' && node.value.type !== 'id' && node.value.type !== '.')) {
  709. throw new python.Error('Invalid decorator' + this._tokenizer.location());
  710. }
  711. this._tokenizer.eat('\n');
  712. list = list !== null ? list : [];
  713. list.push(node);
  714. }
  715. return list;
  716. }
  717. _dictOrSetMaker() {
  718. const list = [];
  719. this._tokenizer.expect('{');
  720. let dict = true;
  721. while (!this._tokenizer.eat('}')) {
  722. const item = this._expression(-1, [], false);
  723. if (item == null) {
  724. throw new python.Error('Expected expression' + this._tokenizer.location());
  725. }
  726. if (!this._tokenizer.eat(':')) {
  727. dict = false;
  728. }
  729. if (dict) {
  730. const value = this._expression(-1, [], false);
  731. if (value == null) {
  732. throw new python.Error('Expected expression' + this._tokenizer.location());
  733. }
  734. list.push({ type: 'pair', key: item, value: value });
  735. }
  736. else {
  737. list.push(item);
  738. }
  739. this._tokenizer.eat(',');
  740. this._tokenizer.eat('\n');
  741. if (this._tokenizer.eat('}')) {
  742. break;
  743. }
  744. }
  745. if (dict) {
  746. return { type: 'dict', value: list };
  747. }
  748. return { type: 'set', value: list };
  749. }
  750. _expressions() {
  751. const list = [];
  752. this._tokenizer.expect('[');
  753. while (!this._tokenizer.eat(']')) {
  754. const expression = this._expression();
  755. if (expression == null) {
  756. throw new python.Error('Expected expression' + this._tokenizer.location());
  757. }
  758. list.push(expression);
  759. this._tokenizer.eat(',');
  760. while (this._tokenizer.eat('\n')) {
  761. // continue
  762. }
  763. if (this._tokenizer.eat(']')) {
  764. break;
  765. }
  766. }
  767. return { type: 'list', value: list };
  768. }
  769. _slice() {
  770. let node = { type: '::' };
  771. let list = [];
  772. const group = [ 'start', 'stop', 'step' ];
  773. this._tokenizer.expect('[');
  774. while (!this._tokenizer.eat(']')) {
  775. if (this._tokenizer.eat(':')) {
  776. node[group.shift()] = { type: 'list', value: list };
  777. list = [];
  778. continue;
  779. }
  780. if (this._tokenizer.eat(',')) {
  781. // list.push({});
  782. continue;
  783. }
  784. if (this._tokenizer.peek().value != ']') {
  785. const expression = this._expression();
  786. if (expression == null) {
  787. throw new python.Error('Expected expression' + this._tokenizer.location());
  788. }
  789. list.push(expression);
  790. }
  791. }
  792. if (list.length > 0) {
  793. node[group.shift()] = { type: 'list', value: list };
  794. }
  795. if (node.start && !node.stop && !node.step) {
  796. node = node.start;
  797. }
  798. return node;
  799. }
  800. _name(required) {
  801. const token = this._tokenizer.peek();
  802. if (token.type == 'id' && !token.keyword) {
  803. this._tokenizer.read();
  804. return token;
  805. }
  806. if (required) {
  807. throw new python.Error("Invalid syntax" + this._tokenizer.location());
  808. }
  809. return null;
  810. }
  811. _dottedName() {
  812. const list = [];
  813. do {
  814. list.push(this._name(true).value);
  815. }
  816. while (this._tokenizer.eat('.'));
  817. return list.join('.');
  818. }
  819. _literal() {
  820. const token = this._tokenizer.peek();
  821. if (token.type == 'string' || token.type == 'number' || token.type == 'boolean') {
  822. this._tokenizer.read();
  823. return token;
  824. }
  825. return null;
  826. }
  827. _typeArguments() {
  828. const list = [];
  829. this._tokenizer.expect('[');
  830. while (!this._tokenizer.eat(']')) {
  831. const type = this._type();
  832. if (type == null) {
  833. throw new python.Error('Expected type ' + this._tokenizer.location());
  834. }
  835. list.push(type);
  836. if (!this._tokenizer.eat(',')) {
  837. this._tokenizer.expect(']');
  838. break;
  839. }
  840. }
  841. return list;
  842. }
  843. _type() {
  844. const type = this._node();
  845. type.type = 'type';
  846. type.name = this._expression(-1, [ '[', '=' ]);
  847. if (type.name) {
  848. if (this._tokenizer.peek().value === '[') {
  849. type.arguments = this._typeArguments();
  850. }
  851. return type;
  852. }
  853. return null;
  854. }
  855. _parameter(terminal) {
  856. const node = this._node('parameter');
  857. if (this._tokenizer.eat('/')) {
  858. node.name = '/';
  859. return node;
  860. }
  861. if (this._tokenizer.eat('**')) {
  862. node.parameterType = '**';
  863. }
  864. if (this._tokenizer.eat('*')) {
  865. node.parameterType = '*';
  866. }
  867. const identifier = this._name();
  868. if (identifier !== null) {
  869. node.name = identifier.value;
  870. if (terminal !== ':' && this._tokenizer.eat(':')) {
  871. node.parameterType = this._type();
  872. }
  873. if (this._tokenizer.eat('=')) {
  874. node.initializer = this._expression();
  875. }
  876. return node;
  877. }
  878. return null;
  879. }
  880. _parameters(terminal) {
  881. const list = [];
  882. while (!this._tokenizer.eat(terminal)) {
  883. this._tokenizer.eat('\n');
  884. if (this._tokenizer.eat('(')) {
  885. list.push(this._parameters(')'));
  886. }
  887. else {
  888. list.push(this._parameter(terminal));
  889. }
  890. this._tokenizer.eat('\n');
  891. if (!this._tokenizer.eat(',')) {
  892. this._tokenizer.expect(terminal);
  893. break;
  894. }
  895. }
  896. return list;
  897. }
  898. _arguments() {
  899. const list = [];
  900. this._tokenizer.expect('(');
  901. while (!this._tokenizer.eat(')')) {
  902. if (this._tokenizer.eat('\n')) {
  903. continue;
  904. }
  905. const expression = this._expression(-1, [], false);
  906. if (expression == null) {
  907. throw new python.Error('Expected expression ' + this._tokenizer.location());
  908. }
  909. list.push(expression);
  910. if (!this._tokenizer.eat(',')) {
  911. this._tokenizer.eat('\n');
  912. this._tokenizer.expect(')');
  913. break;
  914. }
  915. }
  916. return list;
  917. }
  918. _node(type) {
  919. const node = {};
  920. node.location = this._tokenizer.location();
  921. if (type) {
  922. node.type = type;
  923. }
  924. return node;
  925. }
  926. _eat(type, value) {
  927. if (this._tokenizer.match(type, value)) {
  928. const node = this._node(type === 'id' ? value : type);
  929. this._tokenizer.expect(type, value);
  930. return node;
  931. }
  932. return null;
  933. }
  934. };
  935. python.Tokenizer = class {
  936. constructor(text, file) {
  937. this._text = text;
  938. this._file = file;
  939. this._position = 0;
  940. this._lineStart = 0;
  941. this._line = 0;
  942. this._token = { type: '', value: '' };
  943. this._brackets = 0;
  944. this._indentation = [];
  945. this._outdent = 0;
  946. if (!python.Tokenizer._whitespace) {
  947. python.Tokenizer._whitespace = new RegExp('[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]');
  948. const identifierStartChars = '\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc';
  949. const identifierChars = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f';
  950. python.Tokenizer._identifierStart = new RegExp('[' + identifierStartChars + ']');
  951. /* eslint-disable */
  952. python.Tokenizer._identifierChar = new RegExp('[' + identifierStartChars + identifierChars + ']');
  953. /* eslint-enable */
  954. }
  955. }
  956. peek() {
  957. if (!this._cache) {
  958. this._token = this._tokenize(this._token);
  959. this._cache = true;
  960. }
  961. return this._token;
  962. }
  963. read() {
  964. if (!this._cache) {
  965. this._token = this._tokenize(this._token);
  966. }
  967. const next = this._position + this._token.value.length;
  968. while (this._position < next) {
  969. if (python.Tokenizer._isNewline(this._get(this._position))) {
  970. this._position = this._newLine(this._position);
  971. this._lineStart = this._position;
  972. this._line++;
  973. }
  974. else {
  975. this._position++;
  976. }
  977. }
  978. this._cache = false;
  979. return this._token;
  980. }
  981. match(type, value) {
  982. const token = this.peek();
  983. if (token.type === type && (!value || token.value === value)) {
  984. return true;
  985. }
  986. return false;
  987. }
  988. eat(type, value) {
  989. const token = this.peek();
  990. if (token.type === type && (!value || token.value === value)) {
  991. this.read();
  992. return true;
  993. }
  994. return false;
  995. }
  996. expect(type, value) {
  997. const token = this.peek();
  998. if (token.type !== type) {
  999. throw new python.Error("Unexpected '" + token.value + "' instead of '" + type + "'" + this.location());
  1000. }
  1001. if (value && token.value !== value) {
  1002. throw new python.Error("Unexpected '" + token.value + "' instead of '" + value + "'" + this.location());
  1003. }
  1004. this.read();
  1005. }
  1006. location() {
  1007. return ' at ' + this._file + ':' + (this._line + 1).toString() + ':' + (this._position - this._lineStart + 1).toString();
  1008. }
  1009. static _isSpace(c) {
  1010. switch (c) {
  1011. case ' ':
  1012. case '\t':
  1013. case '\v': // 11
  1014. case '\f': // 12
  1015. case '\xA0': // 160
  1016. return true;
  1017. default:
  1018. if (c.charCodeAt(0) >= 0x1680) {
  1019. return python.Tokenizer._whitespace.test(c);
  1020. }
  1021. return false;
  1022. }
  1023. }
  1024. static _isNewline(c) {
  1025. switch(c) {
  1026. case '\n':
  1027. case '\r':
  1028. case '\u2028': // 8232
  1029. case '\u2029': // 8233
  1030. return true;
  1031. default:
  1032. return false;
  1033. }
  1034. }
  1035. static _isIdentifierStartChar(c) {
  1036. if (c < 'A') {
  1037. return c === '$';
  1038. }
  1039. if (c <= 'Z') {
  1040. return true;
  1041. }
  1042. if (c < 'a') {
  1043. return c === '_';
  1044. }
  1045. if (c <= 'z') {
  1046. return true;
  1047. }
  1048. const code = c.charCodeAt(0);
  1049. if (code >= 0xAA) {
  1050. return python.Tokenizer._identifierStart.test(c);
  1051. }
  1052. return false;
  1053. }
  1054. static _isIdentifierChar(c) {
  1055. if (c < '0') {
  1056. return c === '$';
  1057. }
  1058. if (c <= '9') {
  1059. return true;
  1060. }
  1061. if (c < 'A') {
  1062. return false;
  1063. }
  1064. if (c <= 'Z') {
  1065. return true;
  1066. }
  1067. if (c < 'a') {
  1068. return c === '_';
  1069. }
  1070. if (c <= 'z') {
  1071. return true;
  1072. }
  1073. const code = c.charCodeAt(0);
  1074. if (code >= 0xAA) {
  1075. return python.Tokenizer._identifierChar.test(c);
  1076. }
  1077. return false;
  1078. }
  1079. _get(position) {
  1080. return position >= this._text.length ? '\0' : this._text[position];
  1081. }
  1082. _skipLine() {
  1083. while (this._position < this._text.length) {
  1084. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1085. break;
  1086. }
  1087. this._position++;
  1088. }
  1089. }
  1090. _skipWhitespace() {
  1091. while (this._position < this._text.length) {
  1092. const c = this._text[this._position];
  1093. if (c == '#') {
  1094. this._skipLine();
  1095. }
  1096. else if (python.Tokenizer._isSpace(c)) {
  1097. this._position++;
  1098. }
  1099. else if (c == '\\') {
  1100. // Explicit Line Continuation
  1101. this._position++;
  1102. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1103. this._position = this._newLine(this._position);
  1104. this._lineStart = this._position;
  1105. this._line++;
  1106. }
  1107. else {
  1108. throw new python.Error("Unexpected '" + this._text[this._position] + "' after line continuation" + this.location());
  1109. }
  1110. }
  1111. else if (this._brackets > 0 && python.Tokenizer._isNewline(c)) {
  1112. // Implicit Line Continuation
  1113. this._position = this._newLine(this._position);
  1114. this._lineStart = this._position;
  1115. this._line++;
  1116. }
  1117. else {
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. _newLine(position) {
  1123. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') ||
  1124. (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1125. return position + 2;
  1126. }
  1127. return position + 1;
  1128. }
  1129. _tokenize(token) {
  1130. if (this._token.type !== '\n') {
  1131. this._skipWhitespace();
  1132. }
  1133. if (this._token.type === 'dedent') {
  1134. this._indentation.pop();
  1135. this._outdent--;
  1136. if (this._outdent > 0) {
  1137. return { type: 'dedent', value: '' };
  1138. }
  1139. }
  1140. if (token.type == '\n') {
  1141. let indent = '';
  1142. let i = this._position;
  1143. while (i < this._text.length) {
  1144. const c = this._text[i];
  1145. if (python.Tokenizer._isSpace(c)) {
  1146. indent += c;
  1147. i++;
  1148. }
  1149. else if (python.Tokenizer._isNewline(c)) {
  1150. indent = '';
  1151. i = this._newLine(i);
  1152. this._position = i;
  1153. this._lineStart = i;
  1154. this._line++;
  1155. }
  1156. else if (c == '#') {
  1157. indent = '';
  1158. while (i < this._text.length && !python.Tokenizer._isNewline(this._text[i])) {
  1159. i++;
  1160. }
  1161. continue;
  1162. }
  1163. else {
  1164. break;
  1165. }
  1166. }
  1167. let type = null;
  1168. if (indent.length > 0) {
  1169. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1170. if (indent.length > current.length) {
  1171. type = 'indent';
  1172. this._indentation.push(indent);
  1173. }
  1174. else if (indent.length > 0 && indent.length < current.length) {
  1175. type = 'dedent';
  1176. this._outdent = 0;
  1177. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1178. this._outdent++;
  1179. }
  1180. }
  1181. else {
  1182. this._position += indent.length;
  1183. }
  1184. }
  1185. else if (i >= this._text.length) {
  1186. return { type: 'eof', value: '' };
  1187. }
  1188. else if (this._indentation.length > 0) {
  1189. type = 'dedent';
  1190. this._outdent = this._indentation.length;
  1191. }
  1192. if (type === 'indent' || type === 'dedent') {
  1193. return { type: type, value: indent };
  1194. }
  1195. }
  1196. if (this._position >= this._text.length) {
  1197. return { type: 'eof', value: '' };
  1198. }
  1199. const c = this._get(this._position);
  1200. const string = this._string();
  1201. if (string) {
  1202. return string;
  1203. }
  1204. switch (c) {
  1205. case '(':
  1206. case '[':
  1207. case '{':
  1208. this._brackets++;
  1209. return { type: c, value: c };
  1210. case ')':
  1211. case ']':
  1212. case '}':
  1213. if (this._brackets === 0) {
  1214. throw new python.Error("Unexpected '" + c + "'" + this.location);
  1215. }
  1216. this._brackets--;
  1217. return { type: c, value: c };
  1218. case ',':
  1219. case ';':
  1220. case '?':
  1221. return { type: c, value: c };
  1222. default: {
  1223. const number = this._number();
  1224. if (number) {
  1225. return number;
  1226. }
  1227. if (c === '.') {
  1228. let end = this._position + 1;
  1229. while (this._get(end) === '.') {
  1230. end++;
  1231. }
  1232. const text = this._text.substring(this._position, end);
  1233. return { type: text, value: text };
  1234. }
  1235. const identifier = this._identifier();
  1236. if (identifier) {
  1237. return identifier;
  1238. }
  1239. const operator = this._operator();
  1240. if (operator) {
  1241. return operator;
  1242. }
  1243. break;
  1244. }
  1245. }
  1246. if (c === '.') {
  1247. return { type: c, value: c };
  1248. }
  1249. if (c === '\\') {
  1250. return { type: '\\', value: c };
  1251. }
  1252. if (python.Tokenizer._isNewline(c)) {
  1253. return { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  1254. }
  1255. throw new python.Error("Unexpected token '" + c + "'" + this.location());
  1256. }
  1257. _number() {
  1258. const octal = (c) => c >= '0' && c <= '7' || c === '_';
  1259. const binary = (c) => c === '0' || c === '1' || c === '_';
  1260. const decimal = (c) => c >= '0' && c <= '9' || c === '_';
  1261. const hex = (c) => decimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  1262. let c = this._get(this._position);
  1263. const sign = (c === '-' || c === '+') ? 1 : 0;
  1264. let i = this._position + sign;
  1265. c = this._get(i);
  1266. if (c === '0') {
  1267. let radix = 0;
  1268. const n = this._get(i + 1);
  1269. if ((n === 'x' || n === 'X') && hex(this._get(i + 2))) {
  1270. i += 2;
  1271. while (hex(this._get(i))) {
  1272. i += 1;
  1273. }
  1274. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1275. i += 1;
  1276. }
  1277. radix = 16;
  1278. }
  1279. else if ((n === 'b' || n === 'B') && binary(this._get(i + 2))) {
  1280. i += 2;
  1281. while (binary(this._get(i))) {
  1282. i++;
  1283. }
  1284. radix = 2;
  1285. }
  1286. else if ((n === 'o' || n === 'O') && octal(this._get(i + 2))) {
  1287. i += 2;
  1288. while (octal(this._get(i))) {
  1289. i++;
  1290. }
  1291. radix = 8;
  1292. }
  1293. else if (n >= '0' && n <= '7') {
  1294. i++;
  1295. while (octal(this._get(i))) {
  1296. i += 1;
  1297. }
  1298. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1299. i += 1;
  1300. }
  1301. radix = 8;
  1302. }
  1303. if (radix > 0 && this._get(i) !== '.') {
  1304. const radixText = this._text.substring(this._position, i);
  1305. const radixParseText = radixText.indexOf('_') !== -1 ? radixText.split('_').join('') : radixText;
  1306. if (!isNaN(parseInt(radixParseText, radix))) {
  1307. return { type: 'number', value: radixText };
  1308. }
  1309. }
  1310. }
  1311. i = this._position + sign;
  1312. let isDecimal = false;
  1313. if (this._get(i) >= '1' && this._get(i) <= '9') {
  1314. while (decimal(this._get(i))) {
  1315. i++;
  1316. }
  1317. c = this._get(i).toLowerCase();
  1318. isDecimal = c !== '.' && c !== 'e';
  1319. }
  1320. if (this._get(i) === '0') {
  1321. i++;
  1322. c = this._get(i).toLowerCase();
  1323. isDecimal = !decimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  1324. }
  1325. if (isDecimal) {
  1326. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  1327. return { 'type': 'number', value: this._text.substring(this._position, i + 1) };
  1328. }
  1329. const intText = this._text.substring(this._position, i);
  1330. if (!isNaN(parseInt(intText, 10))) {
  1331. return { type: 'number', value: intText };
  1332. }
  1333. }
  1334. i = this._position + sign;
  1335. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  1336. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  1337. while (decimal(this._get(i))) {
  1338. i++;
  1339. }
  1340. if (this._get(i) === '.') {
  1341. i++;
  1342. }
  1343. while (decimal(this._get(i))) {
  1344. i++;
  1345. }
  1346. if (i > (this._position + sign)) {
  1347. if (this._get(i) === 'e' || this._get(i) === 'E') {
  1348. i++;
  1349. if (this._get(i) == '-' || this._get(i) == '+') {
  1350. i++;
  1351. }
  1352. if (!decimal(this._get(i))) {
  1353. i = this._position;
  1354. }
  1355. else {
  1356. while (decimal(this._get(i))) {
  1357. i++;
  1358. }
  1359. }
  1360. }
  1361. else {
  1362. while (decimal(this._get(i))) {
  1363. i++;
  1364. }
  1365. }
  1366. }
  1367. if (i > (this._position + sign)) {
  1368. if (this._get(i) === 'j' || this._get(i) === 'J') {
  1369. return { type: 'number', value: this._text.substring(this._position, i + 1) };
  1370. }
  1371. const floatText = this._text.substring(this._position, i);
  1372. const floatParseText = floatText.indexOf('_') != -1 ? floatText.split('_').join('') : floatText;
  1373. if (!isNaN(parseFloat(floatParseText))) {
  1374. return { type: 'number', value: floatText };
  1375. }
  1376. }
  1377. }
  1378. return null;
  1379. }
  1380. _identifier() {
  1381. let i = this._position;
  1382. if (python.Tokenizer._isIdentifierStartChar(this._get(i))) {
  1383. i++;
  1384. while (python.Tokenizer._isIdentifierChar(this._get(i))) {
  1385. i++;
  1386. }
  1387. }
  1388. if (i > this._position) {
  1389. const text = this._text.substring(this._position, i);
  1390. let keyword = false;
  1391. switch (text) {
  1392. case 'and':
  1393. case 'as':
  1394. case 'else':
  1395. case 'for':
  1396. case 'if':
  1397. case 'import':
  1398. case 'in':
  1399. case 'is':
  1400. case 'not':
  1401. case 'or':
  1402. keyword = true;
  1403. break;
  1404. default:
  1405. keyword = false;
  1406. break;
  1407. }
  1408. return { type: 'id', value: text, keyword: keyword };
  1409. }
  1410. return null;
  1411. }
  1412. _operator() {
  1413. let length = 0;
  1414. const c0 = this._get(this._position);
  1415. const c1 = this._get(this._position + 1);
  1416. const c2 = this._get(this._position + 2);
  1417. switch (c0) {
  1418. case '+':
  1419. case '&':
  1420. case '|':
  1421. case '^':
  1422. case '=':
  1423. case '!':
  1424. case '%':
  1425. case '~':
  1426. length = c1 === '=' ? 2 : 1;
  1427. break;
  1428. case '-':
  1429. length = c1 === '=' || c1 === '>' ? 2 : 1;
  1430. break;
  1431. case '*':
  1432. length = c1 === '*' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1433. break;
  1434. case '/':
  1435. length = c1 === '/' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1436. break;
  1437. case '<':
  1438. length = c1 === '>' ? 2 : (c1 === '<' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1));
  1439. break;
  1440. case '>':
  1441. length = c1 === '>' ? (c2 === '=' ? 3 : 2) : (c1 === '=' ? 2 : 1);
  1442. break;
  1443. case '@':
  1444. length = c1 === '=' ? 2 : 1;
  1445. break;
  1446. case ':':
  1447. length = c1 === '=' ? 2 : 1;
  1448. break;
  1449. default:
  1450. return null;
  1451. }
  1452. const text = this._text.substring(this._position, this._position + length);
  1453. return { type: text, value: text };
  1454. }
  1455. _string() {
  1456. let i = this._position;
  1457. let prefix = -1;
  1458. if (this._get(i) === "'" || this._get(i) === '"') {
  1459. prefix = '';
  1460. }
  1461. else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  1462. const c = this._get(i);
  1463. switch (c.toLowerCase()) {
  1464. case 'b':
  1465. case 'f':
  1466. case 'r':
  1467. case 'u':
  1468. prefix = c;
  1469. break;
  1470. default:
  1471. break;
  1472. }
  1473. }
  1474. else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  1475. const cc = this._text.substr(this._position, 2);
  1476. switch (cc.toLowerCase()) {
  1477. case 'br':
  1478. case 'fr':
  1479. case 'rb':
  1480. case 'rf':
  1481. case 'ur':
  1482. prefix = cc;
  1483. break;
  1484. default:
  1485. break;
  1486. }
  1487. }
  1488. if (prefix.length >= 0) {
  1489. i += prefix.length;
  1490. let quote = '';
  1491. let count = 0;
  1492. const q0 = this._get(i);
  1493. const q1 = this._get(i + 1);
  1494. const q2 = this._get(i + 2);
  1495. switch (q0) {
  1496. case "'":
  1497. quote = q0;
  1498. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  1499. break;
  1500. case '"':
  1501. quote = q0;
  1502. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  1503. break;
  1504. default:
  1505. throw new python.Error("Unsupported string quote '" + q0 + "'.");
  1506. }
  1507. i += count;
  1508. if (count == 1) {
  1509. while (i < this._text.length) {
  1510. if (this._text[i] === quote) {
  1511. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1512. }
  1513. else if (this._text[i] === '\\' &&
  1514. (this._get(i + 1) == quote || this._get(i + 1) == '\n' || this._get(i + 1) == '\\')) {
  1515. i += 2;
  1516. }
  1517. else if (this._text[i] === '\r' || this._text[i] === '\n') {
  1518. break;
  1519. }
  1520. else {
  1521. i++;
  1522. }
  1523. }
  1524. }
  1525. else if (count == 3) {
  1526. while (i < this._text.length) {
  1527. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  1528. return { type: 'string', value: this._text.substring(this._position, i + 3) };
  1529. }
  1530. else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  1531. i += 2;
  1532. continue;
  1533. }
  1534. i++;
  1535. }
  1536. }
  1537. }
  1538. i = this._position;
  1539. if (this._get(i) === '`') {
  1540. i++;
  1541. while (i < this._text.length) {
  1542. if (this._text[i] === '`') {
  1543. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1544. }
  1545. i++;
  1546. }
  1547. }
  1548. return null;
  1549. }
  1550. };
  1551. python.Execution = class {
  1552. constructor(sources, exceptionCallback) {
  1553. const self = this;
  1554. const execution = self;
  1555. this._sources = sources || new Map();
  1556. this._exceptionCallback = exceptionCallback;
  1557. this._utf8Decoder = new TextDecoder('utf-8');
  1558. this._unresolved = new Map();
  1559. const dict = class extends Map {};
  1560. this._modules = new dict();
  1561. this._registry = new Map();
  1562. const module = class {
  1563. constructor(name) {
  1564. this.__name__ = name;
  1565. }
  1566. };
  1567. this._builtins = this.register('builtins', new module('builtins'));
  1568. this._registry.set('__builtin__', this._builtins);
  1569. this.registerType('builtins.type', class {}).__class__ = this._builtins.type;
  1570. this.registerType('builtins.module', module);
  1571. this.registerType('builtins.method', class {});
  1572. this.registerType('builtins.function', class {});
  1573. this.import('builtins');
  1574. this.registerType('builtins.builtin_function_or_method', class {});
  1575. this._typing = this.register('typing');
  1576. this.register('_codecs');
  1577. this.register('argparse');
  1578. this.register('collections');
  1579. this.register('copy_reg');
  1580. this.register('cuml');
  1581. this.register('gensim');
  1582. this.register('io');
  1583. this.register('joblib');
  1584. this.register('keras');
  1585. this.register('lightgbm');
  1586. this.register('nolearn');
  1587. const math = this.register('math');
  1588. math.inf = Infinity;
  1589. const numpy = this.register('numpy');
  1590. this.register('pickle');
  1591. this.register('sklearn');
  1592. const torch = this.register('torch');
  1593. const torch_storage = this.register('torch.storage');
  1594. const torch_nn_parameter = this.register('torch.nn.parameter');
  1595. this.register('torch.ops');
  1596. this.register('torch.ops.torchvision');
  1597. this.register('torch.ops.torchaudio');
  1598. this.register('torch.ops._caffe2');
  1599. this.register('torchvision');
  1600. this.register('__torch__');
  1601. this.register('sys').modules = this._modules;
  1602. this.register('xgboost');
  1603. this.registerType('builtins.dict', dict);
  1604. this.registerType('builtins.list', class {});
  1605. this.registerType('builtins.number', class {});
  1606. this.registerFunction('builtins.__import__', function(name, globals, locals, fromlist, level) {
  1607. return execution.__import__(name, globals, locals, fromlist, level);
  1608. });
  1609. this.registerFunction('builtins.bool', function(value) {
  1610. if (value) {
  1611. if (value.__bool__) {
  1612. return value.__bool__();
  1613. }
  1614. if (value.__len__) {
  1615. return value.__len__() > 0;
  1616. }
  1617. }
  1618. return false;
  1619. });
  1620. this.registerFunction('builtins.int', function(value) {
  1621. if (value) {
  1622. if (value.__int__) {
  1623. return value.__int__();
  1624. }
  1625. if (Number.isInteger(value)) {
  1626. return value;
  1627. }
  1628. }
  1629. return NaN;
  1630. });
  1631. this.registerFunction('builtins.float', function(value) {
  1632. if (value) {
  1633. if (value.__float__) {
  1634. return value.__float__();
  1635. }
  1636. if (Number(value) === value) {
  1637. return value;
  1638. }
  1639. }
  1640. return NaN;
  1641. });
  1642. this.registerFunction('builtins.str', function(value) {
  1643. if (value) {
  1644. if (value.__str__) {
  1645. return value.__str__();
  1646. }
  1647. }
  1648. return JSON.stringify(value);
  1649. });
  1650. this.registerType('builtins.object', class {});
  1651. this.registerType('builtins.tuple', class extends Array {
  1652. constructor(items) {
  1653. super(items ? items.length : 0);
  1654. if (items) {
  1655. for (let i = 0; i < items.length; i++) {
  1656. this[i] = items[i];
  1657. }
  1658. }
  1659. }
  1660. });
  1661. this.registerFunction('builtins.long', this.builtins.int);
  1662. this.registerFunction('builtins.print', function() {});
  1663. this.registerFunction('builtins.unicode', function(/* value */) {
  1664. throw new python.Error('Not implemented.');
  1665. });
  1666. this.registerType('builtins.Warning', class {});
  1667. this.registerType('builtins.FutureWarning', class extends this._builtins.Warning {});
  1668. this.registerType('typing._Final', class {});
  1669. this.registerType('typing._SpecialForm', class extends this._typing._Final {});
  1670. this.registerType('typing._BaseGenericAlias', class extends this._typing._Final {});
  1671. this.registerType('typing._GenericAlias', class extends this._typing._BaseGenericAlias {});
  1672. this.registerType('typing._SpecialGenericAlias', class extends this._typing._BaseGenericAlias {});
  1673. this.registerType('typing._TupleType', class extends this._typing._SpecialGenericAlias {});
  1674. this._typing.Optional = Reflect.construct(this._typing._SpecialForm, []);
  1675. this._typing.List = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1676. this._typing.Dict = Reflect.construct(this._typing._SpecialGenericAlias, []);
  1677. this._typing.Tuple = Reflect.construct(this._typing._TupleType, []);
  1678. this._typing.Any = Reflect.construct(this._typing._SpecialForm, []);
  1679. this.registerType('argparse.Namespace', class {
  1680. constructor(args) {
  1681. this.args = args;
  1682. }
  1683. });
  1684. this.registerType('collections.deque', class extends Array {
  1685. constructor(iterable) {
  1686. super();
  1687. if (Array.isArray(iterable)) {
  1688. for (const value of iterable) {
  1689. this.push(value);
  1690. }
  1691. }
  1692. }
  1693. });
  1694. this.registerType('collections.OrderedDict', class extends Map {
  1695. constructor(items) {
  1696. super();
  1697. if (items) {
  1698. for (const pair of items) {
  1699. this.__setitem__(pair[0], pair[1]);
  1700. }
  1701. }
  1702. }
  1703. __setitem__(key, value) {
  1704. this.set(key, value);
  1705. }
  1706. });
  1707. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  1708. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  1709. this.registerType('cuml.raft.common.handle.Handle', class {
  1710. __setstate__(state) {
  1711. this._handle = state;
  1712. }
  1713. });
  1714. this.registerType('dnnlib.util.EasyDict', class extends dict {});
  1715. this.registerType('haiku._src.data_structures.FlatMapping', class {
  1716. constructor(dict) {
  1717. Object.assign(this, dict);
  1718. }
  1719. });
  1720. this.registerType('haiku._src.data_structures.frozendict', class {
  1721. constructor(obj) {
  1722. Object.assign(this, obj);
  1723. }
  1724. });
  1725. this.registerType('hmmlearn.hmm.MultinomialHMM', class {
  1726. __setstate__(state) {
  1727. Object.assign(this, state);
  1728. }
  1729. });
  1730. this.registerType('hmmlearn.base.ConvergenceMonitor', class {
  1731. __setstate__(state) {
  1732. Object.assign(this, state);
  1733. }
  1734. });
  1735. this.registerType('io.BytesIO', class {
  1736. constructor(buf, mode) {
  1737. this.mode = mode || 'r';
  1738. this._buf = this.mode === 'w' ? null : buf;
  1739. this._point = 0;
  1740. }
  1741. seek(offset) {
  1742. this._point = offset;
  1743. }
  1744. read(size) {
  1745. const start = this._point;
  1746. this._point = size !== undefined ? start + size : this._buf.length;
  1747. return this._buf.subarray(start, this._point);
  1748. }
  1749. write(data) {
  1750. const src = this._buf || new Uint8Array();
  1751. this._point = src.length + data.length;
  1752. this._buf = new Uint8Array(this._point);
  1753. this._buf.set(src, 0);
  1754. this._buf.set(data, src.length);
  1755. }
  1756. });
  1757. this.registerType('numpy.dtype', class {
  1758. constructor(obj, align, copy) {
  1759. switch (obj) {
  1760. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  1761. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  1762. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  1763. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  1764. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  1765. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  1766. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  1767. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  1768. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  1769. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  1770. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  1771. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  1772. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  1773. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  1774. case 'M8': case 'M': this.itemsize = 8; this.kind = 'M'; break;
  1775. default:
  1776. if (obj.startsWith('V')) {
  1777. this.itemsize = parseInt(obj.substring(1), 10);
  1778. this.kind = 'V';
  1779. }
  1780. else if (obj.startsWith('O')) {
  1781. this.itemsize = obj === 'O' ? 8 : parseInt(obj.substring(1), 10);
  1782. this.kind = 'O';
  1783. }
  1784. else if (obj.startsWith('S')) {
  1785. this.itemsize = parseInt(obj.substring(1), 10);
  1786. this.kind = 'S';
  1787. }
  1788. else if (obj.startsWith('U')) { // Unicode string
  1789. this.kind = 'U';
  1790. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  1791. }
  1792. else {
  1793. throw new python.Error("Unsupported dtype '" + obj.toString() + "'.");
  1794. }
  1795. break;
  1796. }
  1797. this.byteorder = '=';
  1798. if (align) {
  1799. this.align = align;
  1800. }
  1801. if (copy) {
  1802. this.copy = copy;
  1803. }
  1804. }
  1805. get str() {
  1806. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  1807. }
  1808. get name() {
  1809. switch (this.kind) {
  1810. case 'V': return 'void' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1811. case 'S': return 'bytes' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1812. case 'U': return 'str' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1813. case 'M': return 'datetime64';
  1814. case 'b': return 'bool';
  1815. default: return this.__name__;
  1816. }
  1817. }
  1818. __setstate__(state) {
  1819. switch (state.length) {
  1820. case 8:
  1821. this.version = state[0];
  1822. this.byteorder = state[1];
  1823. this.subarray = state[2];
  1824. this.names = state[3];
  1825. this.fields = state[4];
  1826. this.elsize = state[5];
  1827. this.alignment = state[6];
  1828. this.int_dtypeflags = state[7];
  1829. break;
  1830. case 9:
  1831. this.version = state[0];
  1832. this.byteorder = state[1];
  1833. this.subarray = state[2];
  1834. this.names = state[3];
  1835. this.fields = state[4];
  1836. this.elsize = state[5];
  1837. this.alignment = state[6];
  1838. this.int_dtypeflags = state[7];
  1839. this.metadata = state[8];
  1840. break;
  1841. default:
  1842. throw new python.Error("Unsupported numpy.dtype setstate length '" + state.length.toString() + "'.");
  1843. }
  1844. }
  1845. get __name__() {
  1846. switch (this.kind) {
  1847. case 'b':
  1848. switch (this.itemsize) {
  1849. case 1: return 'boolean';
  1850. default: throw new python.Error("Unsupported boolean itemsize '" + this.itemsize + "'.");
  1851. }
  1852. case 'i':
  1853. switch (this.itemsize) {
  1854. case 1: return 'int8';
  1855. case 2: return 'int16';
  1856. case 4: return 'int32';
  1857. case 8: return 'int64';
  1858. default: throw new python.Error("Unsupported int itemsize '" + this.itemsize + "'.");
  1859. }
  1860. case 'u':
  1861. switch (this.itemsize) {
  1862. case 1: return 'uint8';
  1863. case 2: return 'uint16';
  1864. case 4: return 'uint32';
  1865. case 8: return 'uint64';
  1866. default: throw new python.Error("Unsupported uint itemsize '" + this.itemsize + "'.");
  1867. }
  1868. case 'f':
  1869. switch (this.itemsize) {
  1870. case 2: return 'float16';
  1871. case 4: return 'float32';
  1872. case 8: return 'float64';
  1873. default: throw new python.Error("Unsupported float itemsize '" + this.itemsize + "'.");
  1874. }
  1875. case 'c':
  1876. switch (this.itemsize) {
  1877. case 8: return 'complex64';
  1878. case 16: return 'complex128';
  1879. default: throw new python.Error("Unsupported complex itemsize '" + this.itemsize + "'.");
  1880. }
  1881. case 'S':
  1882. case 'U':
  1883. return 'string';
  1884. case 'M':
  1885. return 'datetime';
  1886. case 'O':
  1887. return 'object';
  1888. case 'V':
  1889. return 'void';
  1890. default:
  1891. throw new python.Error("Unsupported dtype kind '" + this.kind + "'.");
  1892. }
  1893. }
  1894. });
  1895. this.registerType('numpy.generic', class {});
  1896. this.registerType('numpy.inexact', class {});
  1897. this.registerType('numpy.number', class extends numpy.generic {});
  1898. this.registerType('numpy.integer', class extends numpy.number {});
  1899. this.registerType('numpy.floating', class extends numpy.inexact {});
  1900. this.registerType('numpy.float32', class extends numpy.floating {});
  1901. this.registerType('numpy.float64', class extends numpy.floating {});
  1902. this.registerType('numpy.signedinteger', class extends numpy.integer {});
  1903. this.registerType('numpy.int8', class extends numpy.signedinteger {});
  1904. this.registerType('numpy.int16', class extends numpy.signedinteger {});
  1905. this.registerType('numpy.int32', class extends numpy.signedinteger {});
  1906. this.registerType('numpy.int64', class extends numpy.signedinteger {});
  1907. this.registerType('numpy.unsignedinteger', class extends numpy.integer {});
  1908. this.registerType('numpy.uint8', class extends numpy.unsignedinteger {});
  1909. this.registerType('numpy.uint16', class extends numpy.unsignedinteger {});
  1910. this.registerType('numpy.uint32', class extends numpy.unsignedinteger {});
  1911. this.registerType('numpy.uint64', class extends numpy.unsignedinteger {});
  1912. this.registerType('fastai.callback.core.TrainEvalCallback', class {});
  1913. this.registerType('fastai.callback.hook._hook_inner', class {});
  1914. this.registerType('fastai.callback.hook.Hook', class {});
  1915. this.registerType('fastai.callback.hook.Hooks', class {});
  1916. this.registerType('fastai.callback.progress.ProgressCallback', class {});
  1917. this.registerType('fastai.data.core.DataLoaders', class {});
  1918. this.registerType('fastai.data.core.Datasets', class {});
  1919. this.registerType('fastai.data.core.TfmdDL', class {});
  1920. this.registerType('fastai.data.core.TfmdLists', class {});
  1921. this.registerType('fastai.data.load._FakeLoader', class {});
  1922. this.registerType('fastai.data.load._wif', class {});
  1923. this.registerType('fastai.data.transforms.Categorize', class {});
  1924. this.registerType('fastai.data.transforms.CategoryMap', class {});
  1925. this.registerType('fastai.data.transforms.IntToFloatTensor', class {});
  1926. this.registerType('fastai.data.transforms.Normalize', class {});
  1927. this.registerType('fastai.data.transforms.parent_label', class {});
  1928. this.registerType('fastai.data.transforms.ToTensor', class {});
  1929. this.registerType('fastai.imports.noop', class {});
  1930. this.registerType('fastai.layers.AdaptiveConcatPool2d', class {});
  1931. this.registerType('fastai.layers.ConvLayer', class {});
  1932. this.registerType('fastai.layers.Flatten', class {});
  1933. this.registerType('fastai.layers.MergeLayer', class {});
  1934. this.registerType('fastai.layers.PixelShuffle_ICNR', class {});
  1935. this.registerType('fastai.layers.ResBlock', class {});
  1936. this.registerType('fastai.layers.SelfAttention', class {});
  1937. this.registerType('fastai.learner.AvgLoss', class {});
  1938. this.registerType('fastai.learner.AvgMetric', class {});
  1939. this.registerType('fastai.learner.AvgSmoothLoss', class {});
  1940. this.registerType('fastai.learner.Learner', class {});
  1941. this.registerType('fastai.learner.Recorder', class {});
  1942. this.registerType('fastai.losses.CrossEntropyLossFlat', class {});
  1943. this.registerType('fastai.metrics.error_rate', class {});
  1944. this.registerType('fastai.optimizer.Adam', class {});
  1945. this.registerType('fastai.torch_core._fa_rebuild_tensor', class {});
  1946. this.registerType('fastai.torch_core.TensorBase', class {});
  1947. this.registerType('fastai.torch_core.TensorCategory', class {});
  1948. this.registerType('fastai.torch_core.TensorImage', class {});
  1949. this.registerType('fastai.vision.augment._BrightnessLogit', class {});
  1950. this.registerType('fastai.vision.augment._ContrastLogit', class {});
  1951. this.registerType('fastai.vision.augment._WarpCoord', class {});
  1952. this.registerType('fastai.vision.augment.Brightness', class {});
  1953. this.registerType('fastai.vision.augment.flip_mat', class {});
  1954. this.registerType('fastai.vision.augment.Flip', class {});
  1955. this.registerType('fastai.vision.augment.RandomResizedCropGPU', class {});
  1956. this.registerType('fastai.vision.augment.Resize', class {});
  1957. this.registerType('fastai.vision.augment.rotate_mat', class {});
  1958. this.registerType('fastai.vision.augment.zoom_mat', class {});
  1959. this.registerType('fastai.vision.core.PILImage', class {});
  1960. this.registerType('fastai.vision.learner._resnet_split', class {});
  1961. this.registerType('fastai.vision.models.unet.DynamicUnet', class {});
  1962. this.registerType('fastai.vision.models.unet.ResizeToOrig', class {});
  1963. this.registerType('fastai.vision.models.unet.UnetBlock', class {});
  1964. this.registerType('fastcore.basics.fastuple', class {});
  1965. this.registerType('fastcore.dispatch._TypeDict', class {});
  1966. this.registerType('fastcore.dispatch.TypeDispatch', class {});
  1967. this.registerType('fastcore.foundation.L', class {});
  1968. this.registerType('fastcore.transform.Pipeline', class {});
  1969. this.registerType('fastcore.transform.Transform', class {});
  1970. this.registerType('functools.partial', class {});
  1971. this.registerType('gensim.models.doc2vec.Doctag', class {});
  1972. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  1973. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  1974. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  1975. this.registerType('gensim.models.fasttext.FastText', class {});
  1976. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  1977. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  1978. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  1979. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  1980. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  1981. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  1982. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  1983. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  1984. this.registerType('gensim.models.phrases.Phrases', class {});
  1985. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  1986. this.registerType('gensim.models.word2vec.Vocab', class {});
  1987. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  1988. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  1989. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  1990. this.registerType('google3.learning.deepmind.research.nbr.pbl_jax.clean_jaxline.utils.optimizers.ScaleByLarsState', class {
  1991. constructor(obj) {
  1992. Object.assign(this, obj);
  1993. }
  1994. });
  1995. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  1996. constructor(/* subtype, shape, dtype */) {
  1997. }
  1998. __setstate__(state) {
  1999. this.subclass = state.subclass;
  2000. this.dtype = state.dtype;
  2001. this.shape = state.shape;
  2002. this.order = state.order;
  2003. this.allow_mmap = state.allow_mmap;
  2004. }
  2005. __read__(unpickler) {
  2006. if (this.dtype.__name__ == 'object') {
  2007. return unpickler.load();
  2008. }
  2009. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2010. this.data = unpickler.read(size);
  2011. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2012. }
  2013. });
  2014. this.registerType('keras.engine.sequential.Sequential', class {});
  2015. this.registerType('lasagne.layers.conv.Conv2DLayer', class {});
  2016. this.registerType('lasagne.layers.dense.DenseLayer', class {});
  2017. this.registerType('lasagne.layers.input.InputLayer', class {});
  2018. this.registerType('lasagne.layers.pool.MaxPool2DLayer', class {});
  2019. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  2020. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  2021. this.registerType('lightgbm.basic.Booster', class {
  2022. constructor() {
  2023. this.average_output = false;
  2024. this.models = [];
  2025. this.loaded_parameter = '';
  2026. }
  2027. __setstate__(state) {
  2028. if (typeof state.handle === 'string') {
  2029. this.LoadModelFromString(state.handle);
  2030. return;
  2031. }
  2032. Object.assign(this, state);
  2033. }
  2034. LoadModelFromString(model_str) {
  2035. const lines = model_str.split('\n');
  2036. const signature = lines.shift() || '?';
  2037. if (signature.trim() !== 'tree') {
  2038. throw new python.Error("Invalid signature '" + signature.trim() + "'.");
  2039. }
  2040. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  2041. const key_vals = new Map();
  2042. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  2043. const cur_line = lines.shift().trim();
  2044. if (cur_line.length > 0) {
  2045. const strs = cur_line.split('=');
  2046. if (strs.length === 1) {
  2047. key_vals.set(strs[0], '');
  2048. }
  2049. else if (strs.length === 2) {
  2050. key_vals.set(strs[0], strs[1]);
  2051. }
  2052. else if (strs.length > 2) {
  2053. if (strs[0] === "feature_names") {
  2054. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  2055. }
  2056. else if (strs[0] == 'monotone_constraints') {
  2057. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  2058. }
  2059. else {
  2060. throw new python.Error('Wrong line: ' + cur_line.substring(0, Math.min(128, cur_line.length)));
  2061. }
  2062. }
  2063. }
  2064. }
  2065. const atoi = (key, value) => {
  2066. if (key_vals.has(key)) {
  2067. return parseInt(key_vals.get(key), 10);
  2068. }
  2069. if (value !== undefined) {
  2070. return value;
  2071. }
  2072. throw new python.Error('Model file does not specify ' + key + '.');
  2073. };
  2074. const list = (key, size) => {
  2075. if (key_vals.has(key)) {
  2076. const value = key_vals.get(key).split(' ');
  2077. if (value.length !== size) {
  2078. throw new python.Error('Wrong size of ' + key + '.');
  2079. }
  2080. return value;
  2081. }
  2082. throw new python.Error('Model file does not contain ' + key + '.');
  2083. };
  2084. this.version = key_vals.get('version') || '';
  2085. this.num_class = atoi('num_class');
  2086. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  2087. this.label_index = atoi('label_index');
  2088. this.max_feature_idx = atoi('max_feature_idx');
  2089. if (key_vals.has('average_output')) {
  2090. this.average_output = true;
  2091. }
  2092. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  2093. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  2094. if (key_vals.has('monotone_constraints')) {
  2095. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1);
  2096. }
  2097. if (key_vals.has('objective')) {
  2098. this.objective = key_vals.get('objective');
  2099. }
  2100. let tree = null;
  2101. while (lines.length > 0) {
  2102. const text = lines.shift();
  2103. const line = text.trim();
  2104. if (line.length === 0) {
  2105. continue;
  2106. }
  2107. if (line.startsWith('Tree=')) {
  2108. tree = { index: parseInt(line.split('=').pop(), 10) };
  2109. this.models.push(tree);
  2110. continue;
  2111. }
  2112. if (line === 'end of trees') {
  2113. break;
  2114. }
  2115. const param = line.split('=');
  2116. if (param.length !== 2) {
  2117. throw new python.Error("Invalid property '" + line + "'.");
  2118. }
  2119. const name = param[0].trim();
  2120. const value = param[1].trim();
  2121. tree[name] = value;
  2122. }
  2123. const ss = [];
  2124. let is_inparameter = false;
  2125. while (lines.length > 0) {
  2126. const text = lines.shift();
  2127. const line = text.trim();
  2128. if (line === 'parameters:') {
  2129. is_inparameter = true;
  2130. continue;
  2131. }
  2132. else if (line === 'end of parameters') {
  2133. break;
  2134. }
  2135. else if (is_inparameter) {
  2136. ss.push(line);
  2137. }
  2138. }
  2139. if (ss.length > 0) {
  2140. this.loaded_parameter = ss.join('\n');
  2141. }
  2142. }
  2143. });
  2144. this.registerFunction('megengine.functional.nn.conv2d', function() {});
  2145. this.registerFunction('megengine.functional.nn.relu', function() {});
  2146. this.registerFunction('megengine.module.qat.module.QATModule._apply_fakequant_with_observer', function() {});
  2147. this.registerFunction('megengine.functional.tensor.concat', function() {});
  2148. this.registerFunction('megengine.functional.tensor.flatten', function() {});
  2149. this.registerType('megengine.core._imperative_rt.common.CompNode', class {});
  2150. this.registerType('megengine.core._imperative_rt.ops.FakeQuant', class {});
  2151. this.registerType('megengine.core._imperative_rt.ops.GetVarShape', class {});
  2152. this.registerType('megengine.core.ops._internal.param_defs.ConvolutionV0.Mode', class {});
  2153. this.registerType('megengine.core.ops._internal.param_defs.Convolution.ComputeMode', class {});
  2154. this.registerType('megengine.module.activation.ReLU', class {});
  2155. this.registerType('megengine.module.batchnorm.BatchNorm1d', class {});
  2156. this.registerType('megengine.module.batchnorm.BatchNorm2d', class {});
  2157. this.registerType('megengine.module.conv.Conv2d', class {});
  2158. this.registerType('megengine.module.conv.ConvTranspose2d', class {});
  2159. this.registerType('megengine.module.identity.Identity', class {});
  2160. this.registerType('megengine.module.linear.Linear', class {});
  2161. this.registerType('megengine.module.module.Module', class {});
  2162. this.registerType('megengine.module.pooling.AvgPool2d', class {});
  2163. this.registerType('megengine.module.pooling.MaxPool2d', class {});
  2164. this.registerType('megengine.module.qat.concat.Concat', class {});
  2165. this.registerType('megengine.module.qat.elemwise.Elemwise', class {});
  2166. this.registerType('megengine.module.sequential.Sequential', class {});
  2167. this.registerType('megengine.quantization.fake_quant.FakeQuantize', class {});
  2168. this.registerType('megengine.quantization.utils.QParams', class {});
  2169. this.registerType('megengine.quantization.utils.QuantMode', class {});
  2170. this.registerType('megengine.quantization.observer.PassiveObserver', class {});
  2171. this.registerType('megengine.quantization.observer.MinMaxObserver', class {});
  2172. this.registerType('megengine.traced_module.expr.Apply', class {});
  2173. this.registerType('megengine.traced_module.expr.CallFunction', class {});
  2174. this.registerType('megengine.traced_module.expr.CallMethod', class {});
  2175. this.registerType('megengine.traced_module.expr.Constant', class {});
  2176. this.registerType('megengine.traced_module.expr.GetAttr', class {});
  2177. this.registerType('megengine.traced_module.expr.Input', class {});
  2178. this.registerType('megengine.traced_module.fake_quant.FakeQuantize', class {});
  2179. this.registerType('megengine.traced_module.node.ModuleNode', class {});
  2180. this.registerType('megengine.traced_module.node.NodeMixin', class {});
  2181. this.registerType('megengine.traced_module.node.TensorNode', class {});
  2182. this.registerType('megengine.traced_module.pytree.ArgsIndex', class {});
  2183. this.registerType('megengine.traced_module.serialization._ModuleState', class {});
  2184. this.registerType('megengine.traced_module.traced_module.InternalGraph', class {});
  2185. this.registerType('megengine.traced_module.traced_module.NameSpace', class {});
  2186. this.registerType('megengine.traced_module.traced_module.TracedModule', class {});
  2187. this.registerType('megengine.tensor.Parameter', class {
  2188. constructor(data, dtype, device) {
  2189. this.data = data;
  2190. this.dtype = dtype;
  2191. this.device = device;
  2192. }
  2193. });
  2194. this.registerType('megengine.traced_module.pytree.TreeDef', class {
  2195. toString() {
  2196. let content = '';
  2197. for (const child of this.children_defs) {
  2198. content += child.toString() + ",";
  2199. }
  2200. if (typeof this.type === "string") {
  2201. return this.type.split(".").slice(-1) + '(' + content + ')';
  2202. }
  2203. return this.type.__name__ + '(' + content + ')';
  2204. }
  2205. });
  2206. this.registerType('megengine.traced_module.pytree.LeafDef', class {
  2207. toString() {
  2208. let content = '';
  2209. if (this.const_val !== null) {
  2210. content += this.const_val;
  2211. }
  2212. else {
  2213. content += '[';
  2214. }
  2215. for (var t of Object.values(this.type)) {
  2216. content += t.__name__;
  2217. }
  2218. content += ']';
  2219. return content;
  2220. }
  2221. });
  2222. this.registerType('megengine.tensor.Tensor', class {
  2223. constructor(data, dtype, device) {
  2224. this.data = data;
  2225. this.dtype = dtype;
  2226. this.device = device;
  2227. }
  2228. });
  2229. this.registerType('megengine.core.tensor.dtype.QuantDtypeMeta', class {
  2230. constructor(name, cname, np_dtype, qmin, qmax, is_signed) {
  2231. this.name = name;
  2232. this.cname = cname;
  2233. this.np_dtype = np_dtype;
  2234. this.qmin = qmin;
  2235. this.qmax = qmax;
  2236. this.is_signed = is_signed;
  2237. }
  2238. });
  2239. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  2240. this.registerType('nolearn.lasagne.base.Layers', class {});
  2241. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  2242. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  2243. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  2244. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  2245. this.registerType('numpy.ndarray', class {
  2246. constructor(shape, dtype, buffer, offset, strides, order) {
  2247. this.shape = shape;
  2248. this.dtype = dtype;
  2249. this.data = buffer !== undefined ? buffer : null;
  2250. this.offset = offset !== undefined ? offset : 0;
  2251. this.strides = strides !== undefined ? strides : null;
  2252. this.order = offset !== undefined ? order : null;
  2253. this.flags = {};
  2254. this._read();
  2255. }
  2256. __setstate__(state) {
  2257. this.version = state[0];
  2258. this.shape = state[1];
  2259. this.dtype = state[2];
  2260. this.flags.fnc = state[3];
  2261. this.data = state[4];
  2262. this._read();
  2263. }
  2264. tobytes() {
  2265. return this.data;
  2266. }
  2267. get size() {
  2268. return (this.shape || []).reduce((a, b) => a * b, 1);
  2269. }
  2270. _read() {
  2271. if (this.data) {
  2272. const length = this.dtype.itemsize * this.size;
  2273. if (typeof this.data == 'string') {
  2274. this.data = this._unescape(this.data, length);
  2275. if (this.data.length != length) {
  2276. throw new python.Error('Invalid string array data size.');
  2277. }
  2278. }
  2279. else if (this.data.length != length) {
  2280. // throw new python.Error('Invalid array data size.');
  2281. }
  2282. }
  2283. }
  2284. _unescape(token, size) {
  2285. const length = token.length;
  2286. const a = new Uint8Array(length);
  2287. if (size && size == length) {
  2288. for (let p = 0; p < size; p++) {
  2289. a[p] = token.charCodeAt(p);
  2290. }
  2291. return a;
  2292. }
  2293. let i = 0;
  2294. let o = 0;
  2295. while (i < length) {
  2296. let c = token.charCodeAt(i++);
  2297. if (c !== 0x5C || i >= length) {
  2298. a[o++] = c;
  2299. }
  2300. else {
  2301. c = token.charCodeAt(i++);
  2302. switch (c) {
  2303. case 0x27: a[o++] = 0x27; break; // '
  2304. case 0x5C: a[o++] = 0x5C; break; // \\
  2305. case 0x22: a[o++] = 0x22; break; // "
  2306. case 0x72: a[o++] = 0x0D; break; // \r
  2307. case 0x6E: a[o++] = 0x0A; break; // \n
  2308. case 0x74: a[o++] = 0x09; break; // \t
  2309. case 0x62: a[o++] = 0x08; break; // \b
  2310. case 0x58: // x
  2311. case 0x78: { // X
  2312. const xsi = i - 1;
  2313. const xso = o;
  2314. for (let xi = 0; xi < 2; xi++) {
  2315. if (i >= length) {
  2316. i = xsi;
  2317. o = xso;
  2318. a[o] = 0x5c;
  2319. break;
  2320. }
  2321. let xd = token.charCodeAt(i++);
  2322. xd = xd >= 65 && xd <= 70 ? xd - 55 : xd >= 97 && xd <= 102 ? xd - 87 : xd >= 48 && xd <= 57 ? xd - 48 : -1;
  2323. if (xd === -1) {
  2324. i = xsi;
  2325. o = xso;
  2326. a[o] = 0x5c;
  2327. break;
  2328. }
  2329. a[o] = a[o] << 4 | xd;
  2330. }
  2331. o++;
  2332. break;
  2333. }
  2334. default:
  2335. if (c < 48 || c > 57) { // 0-9
  2336. a[o++] = 0x5c;
  2337. a[o++] = c;
  2338. }
  2339. else {
  2340. i--;
  2341. const osi = i;
  2342. const oso = o;
  2343. for (let oi = 0; oi < 3; oi++) {
  2344. if (i >= length) {
  2345. i = osi;
  2346. o = oso;
  2347. a[o] = 0x5c;
  2348. break;
  2349. }
  2350. const od = token.charCodeAt(i++);
  2351. if (od < 48 || od > 57) {
  2352. i = osi;
  2353. o = oso;
  2354. a[o] = 0x5c;
  2355. break;
  2356. }
  2357. a[o] = a[o] << 3 | od - 48;
  2358. }
  2359. o++;
  2360. }
  2361. break;
  2362. }
  2363. }
  2364. }
  2365. return a.slice(0, o);
  2366. }
  2367. });
  2368. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  2369. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  2370. super(data.shape, data.dtype, data.data);
  2371. }
  2372. });
  2373. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  2374. constructor(shape, dtype) {
  2375. super(shape, dtype);
  2376. }
  2377. });
  2378. this.registerType('pathlib.Path', class {});
  2379. this.registerType('pathlib.PosixPath', class {});
  2380. this.registerType('pathlib.WindowsPath', class {});
  2381. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  2382. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  2383. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  2384. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  2385. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  2386. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  2387. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  2388. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  2389. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  2390. this.registerType('sklearn.decomposition._pca.PCA', class {});
  2391. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  2392. this.registerType('sklearn.decomposition.PCA', class {});
  2393. this.registerType('sklearn.decomposition.pca.PCA', class {});
  2394. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  2395. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  2396. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  2397. this.registerType('sklearn.dummy.DummyClassifier', class {});
  2398. this.registerType('sklearn.dummy.DummyRegressor', class {});
  2399. this.registerType('sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper', class {
  2400. constructor(/* subtype, shape, dtype */) {
  2401. }
  2402. __setstate__(state) {
  2403. this.subclass = state.subclass;
  2404. this.dtype = state.dtype;
  2405. this.shape = state.shape;
  2406. this.order = state.order;
  2407. this.allow_mmap = state.allow_mmap;
  2408. }
  2409. __read__(unpickler) {
  2410. if (this.dtype.__name__ == 'object') {
  2411. return unpickler.load();
  2412. }
  2413. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2414. this.data = unpickler.read(size);
  2415. return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2416. }
  2417. });
  2418. this.registerType('sklearn.externals.joblib.numpy_pickle.NDArrayWrapper', class {
  2419. constructor(/* subtype, shape, dtype */) {
  2420. }
  2421. __setstate__(state) {
  2422. this.subclass = state.subclass;
  2423. this.filename = state.state;
  2424. this.allow_mmap = state.allow_mmap;
  2425. }
  2426. __read__(/* unpickler */) {
  2427. return this; // return execution.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2428. }
  2429. });
  2430. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  2431. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  2432. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  2433. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  2434. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  2435. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  2436. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  2437. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  2438. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  2439. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  2440. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  2441. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  2442. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  2443. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  2444. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  2445. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  2446. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  2447. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  2448. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  2449. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  2450. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  2451. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  2452. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  2453. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  2454. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  2455. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  2456. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  2457. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  2458. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  2459. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  2460. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  2461. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  2462. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  2463. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  2464. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  2465. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  2466. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  2467. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  2468. this.registerType('sklearn.gaussian_process._gpr.GaussianProcessRegressor', class {});
  2469. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  2470. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  2471. this.registerType('sklearn.gaussian_process.kernels.DotProduct', class {});
  2472. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  2473. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  2474. this.registerType('sklearn.gaussian_process.kernels.Sum', class {});
  2475. this.registerType('sklearn.gaussian_process.kernels.WhiteKernel', class {});
  2476. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  2477. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  2478. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  2479. this.registerType('sklearn.impute.SimpleImputer', class {});
  2480. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  2481. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  2482. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  2483. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  2484. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  2485. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  2486. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  2487. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  2488. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  2489. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  2490. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  2491. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  2492. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  2493. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  2494. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  2495. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  2496. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  2497. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  2498. this.registerType('sklearn.linear_model.LassoLars​', class {});
  2499. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  2500. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  2501. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  2502. this.registerType('sklearn.metrics._classification.accuracy_score', class {});
  2503. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  2504. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  2505. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  2506. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  2507. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  2508. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  2509. this.registerType('sklearn.model_selection._split.KFold', class {});
  2510. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  2511. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  2512. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  2513. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  2514. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  2515. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  2516. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  2517. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  2518. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  2519. this.registerType('sklearn.neighbors._dist_metrics.newObj', class {});
  2520. this.registerType('sklearn.neighbors._dist_metrics.EuclideanDistance', class {});
  2521. this.registerType('sklearn.neighbors._kd_tree.KDTree', class {});
  2522. this.registerType('sklearn.neighbors._kd_tree.newObj', class {});
  2523. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  2524. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  2525. this.registerType('sklearn.neighbors.dist_metrics.newObj', class {});
  2526. this.registerType('sklearn.neighbors.dist_metrics.EuclideanDistance', class {});
  2527. this.registerType('sklearn.neighbors.kd_tree.newObj', class {});
  2528. this.registerType('sklearn.neighbors.kd_tree.KDTree', class {});
  2529. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  2530. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  2531. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  2532. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  2533. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  2534. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  2535. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  2536. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  2537. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  2538. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  2539. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  2540. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  2541. this.registerType('sklearn.pipeline.Pipeline', class {});
  2542. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  2543. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  2544. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  2545. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  2546. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  2547. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  2548. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  2549. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  2550. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  2551. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  2552. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  2553. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  2554. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  2555. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  2556. this.registerType('sklearn.preprocessing._label.MultiLabelBinarizer', class {});
  2557. this.registerType('sklearn.preprocessing._polynomial.PolynomialFeatures', class {});
  2558. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  2559. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  2560. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  2561. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  2562. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  2563. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  2564. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  2565. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  2566. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  2567. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  2568. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  2569. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  2570. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  2571. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  2572. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  2573. this.registerType('sklearn.svm._classes.NuSVC', class {});
  2574. this.registerType('sklearn.svm._classes.OneClassSVM', class {});
  2575. this.registerType('sklearn.svm._classes.SVC', class {});
  2576. this.registerType('sklearn.svm._classes.SVR', class {});
  2577. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  2578. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  2579. this.registerType('sklearn.svm.classes.SVC', class {});
  2580. this.registerType('sklearn.svm.classes.SVR', class {});
  2581. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  2582. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  2583. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  2584. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  2585. this.registerType('sklearn.tree._tree.Tree', class {
  2586. constructor(n_features, n_classes, n_outputs) {
  2587. this.n_features = n_features;
  2588. this.n_classes = n_classes;
  2589. this.n_outputs = n_outputs;
  2590. }
  2591. __setstate__(state) {
  2592. this.max_depth = state.max_depth;
  2593. this.node_count = state.node_count;
  2594. this.nodes = state.nodes;
  2595. this.values = state.values;
  2596. }
  2597. });
  2598. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  2599. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  2600. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  2601. this.registerType('sklearn.utils.Bunch', class {});
  2602. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  2603. this.registerType('pickle.Unpickler', class {
  2604. constructor(data) {
  2605. this._reader = data instanceof Uint8Array ? new python.Unpickler.BinaryReader(data) : new python.Unpickler.StreamReader(data);
  2606. this.persistent_load = () => {
  2607. throw new python.Error('Unsupported persistent id.');
  2608. };
  2609. }
  2610. load() {
  2611. const reader = this._reader;
  2612. const marker = [];
  2613. let stack = [];
  2614. const memo = new Map();
  2615. const OpCode = python.Unpickler.OpCode;
  2616. while (reader.position < reader.length) {
  2617. const opcode = reader.byte();
  2618. // console.log((reader.position - 1).toString() + ' ' + Object.entries(OpCode).find((entry) => entry[1] === opcode)[0]);
  2619. switch (opcode) {
  2620. case OpCode.PROTO: {
  2621. const version = reader.byte();
  2622. if (version > 5) {
  2623. throw new python.Error("Unsupported protocol version '" + version + "'.");
  2624. }
  2625. break;
  2626. }
  2627. case OpCode.GLOBAL: {
  2628. const module = reader.line();
  2629. const name = reader.line();
  2630. stack.push(this.find_class(module, name));
  2631. break;
  2632. }
  2633. case OpCode.STACK_GLOBAL: {
  2634. const name = stack.pop();
  2635. const module = stack.pop();
  2636. stack.push(this.find_class(module, name));
  2637. break;
  2638. }
  2639. case OpCode.PUT: {
  2640. const index = parseInt(reader.line(), 10);
  2641. memo.set(index, stack[stack.length - 1]);
  2642. break;
  2643. }
  2644. case OpCode.OBJ: {
  2645. const args = stack;
  2646. const cls = args.pop();
  2647. stack = marker.pop();
  2648. const obj = this._instantiate(cls, args);
  2649. stack.push(obj);
  2650. break;
  2651. }
  2652. case OpCode.GET: {
  2653. const index = parseInt(reader.line(), 10);
  2654. stack.push(memo.get(index));
  2655. break;
  2656. }
  2657. case OpCode.POP:
  2658. stack.pop();
  2659. break;
  2660. case OpCode.POP_MARK:
  2661. stack = marker.pop();
  2662. break;
  2663. case OpCode.DUP:
  2664. stack.push(stack[stack.length-1]);
  2665. break;
  2666. case OpCode.PERSID:
  2667. stack.push(this.persistent_load(reader.line()));
  2668. break;
  2669. case OpCode.BINPERSID:
  2670. stack.push(this.persistent_load(stack.pop()));
  2671. break;
  2672. case OpCode.REDUCE: {
  2673. const args = stack.pop();
  2674. const func = stack.pop();
  2675. stack.push(execution.invoke(func, args));
  2676. break;
  2677. }
  2678. case OpCode.NEWOBJ: {
  2679. const args = stack.pop();
  2680. const cls = stack.pop();
  2681. // TODO resolved
  2682. // cls.__new__(cls, args)
  2683. stack.push(execution.invoke(cls, args));
  2684. break;
  2685. }
  2686. case OpCode.BINGET:
  2687. stack.push(memo.get(reader.byte()));
  2688. break;
  2689. case OpCode.INST: {
  2690. const module = reader.line();
  2691. const name = reader.line();
  2692. const args = stack;
  2693. const cls = module + '.' + name;
  2694. stack = marker.pop();
  2695. // TODO
  2696. // cls = this.find_class(module, name)
  2697. const obj = this._instantiate(cls, args);
  2698. stack.push(obj);
  2699. break;
  2700. }
  2701. case OpCode.LONG_BINGET:
  2702. stack.push(memo.get(reader.uint32()));
  2703. break;
  2704. case OpCode.BINPUT:
  2705. memo.set(reader.byte(), stack[stack.length - 1]);
  2706. break;
  2707. case OpCode.LONG_BINPUT:
  2708. memo.set(reader.uint32(), stack[stack.length - 1]);
  2709. break;
  2710. case OpCode.BININT:
  2711. stack.push(reader.int32());
  2712. break;
  2713. case OpCode.BININT1:
  2714. stack.push(reader.byte());
  2715. break;
  2716. case OpCode.LONG:
  2717. stack.push(parseInt(reader.line(), 10));
  2718. break;
  2719. case OpCode.BININT2:
  2720. stack.push(reader.uint16());
  2721. break;
  2722. case OpCode.BINBYTES:
  2723. stack.push(reader.read(reader.int32()));
  2724. break;
  2725. case OpCode.BINBYTES8:
  2726. stack.push(reader.read(reader.int64()));
  2727. break;
  2728. case OpCode.SHORT_BINBYTES:
  2729. stack.push(reader.read(reader.byte()));
  2730. break;
  2731. case OpCode.FLOAT:
  2732. stack.push(parseFloat(reader.line()));
  2733. break;
  2734. case OpCode.BINFLOAT:
  2735. stack.push(reader.float64());
  2736. break;
  2737. case OpCode.INT: {
  2738. const value = reader.line();
  2739. if (value == '01') {
  2740. stack.push(true);
  2741. }
  2742. else if (value == '00') {
  2743. stack.push(false);
  2744. }
  2745. else {
  2746. stack.push(parseInt(value, 10));
  2747. }
  2748. break;
  2749. }
  2750. case OpCode.EMPTY_LIST:
  2751. stack.push([]);
  2752. break;
  2753. case OpCode.EMPTY_TUPLE:
  2754. stack.push([]);
  2755. break;
  2756. case OpCode.EMPTY_SET:
  2757. stack.push([]);
  2758. break;
  2759. case OpCode.ADDITEMS: {
  2760. const items = stack;
  2761. stack = marker.pop();
  2762. const obj = stack[stack.length - 1];
  2763. for (let i = 0; i < items.length; i++) {
  2764. obj.push(items[i]);
  2765. }
  2766. break;
  2767. }
  2768. case OpCode.FROZENSET: {
  2769. const items = stack;
  2770. stack = marker.pop();
  2771. stack.push(items);
  2772. break;
  2773. }
  2774. case OpCode.DICT: {
  2775. const items = stack;
  2776. stack = marker.pop();
  2777. const dict = {};
  2778. for (let i = 0; i < items.length; i += 2) {
  2779. dict[items[i]] = items[i + 1];
  2780. }
  2781. stack.push(dict);
  2782. break;
  2783. }
  2784. case OpCode.LIST: {
  2785. const items = stack;
  2786. stack = marker.pop();
  2787. stack.push(items);
  2788. break;
  2789. }
  2790. case OpCode.TUPLE: {
  2791. const items = stack;
  2792. stack = marker.pop();
  2793. stack.push(items);
  2794. break;
  2795. }
  2796. case OpCode.SETITEM: {
  2797. const value = stack.pop();
  2798. const key = stack.pop();
  2799. const obj = stack[stack.length - 1];
  2800. if (obj.__setitem__) {
  2801. obj.__setitem__(key, value);
  2802. }
  2803. else {
  2804. obj[key] = value;
  2805. }
  2806. break;
  2807. }
  2808. case OpCode.SETITEMS: {
  2809. const items = stack;
  2810. stack = marker.pop();
  2811. const obj = stack[stack.length - 1];
  2812. for (let i = 0; i < items.length; i += 2) {
  2813. if (obj.__setitem__) {
  2814. obj.__setitem__(items[i], items[i + 1]);
  2815. }
  2816. else {
  2817. obj[items[i]] = items[i + 1];
  2818. }
  2819. }
  2820. break;
  2821. }
  2822. case OpCode.EMPTY_DICT:
  2823. stack.push({});
  2824. break;
  2825. case OpCode.APPEND: {
  2826. const append = stack.pop();
  2827. stack[stack.length-1].push(append);
  2828. break;
  2829. }
  2830. case OpCode.APPENDS: {
  2831. const appends = stack;
  2832. stack = marker.pop();
  2833. const list = stack[stack.length - 1];
  2834. list.push.apply(list, appends);
  2835. break;
  2836. }
  2837. case OpCode.STRING: {
  2838. const str = reader.line();
  2839. stack.push(str.substr(1, str.length - 2));
  2840. break;
  2841. }
  2842. case OpCode.BINSTRING:
  2843. stack.push(reader.string(reader.uint32()));
  2844. break;
  2845. case OpCode.SHORT_BINSTRING:
  2846. stack.push(reader.string(reader.byte()));
  2847. break;
  2848. case OpCode.UNICODE:
  2849. stack.push(reader.line());
  2850. break;
  2851. case OpCode.BINUNICODE:
  2852. stack.push(reader.string(reader.uint32(), 'utf-8'));
  2853. break;
  2854. case OpCode.SHORT_BINUNICODE:
  2855. stack.push(reader.string(reader.byte(), 'utf-8'));
  2856. break;
  2857. case OpCode.BUILD: {
  2858. const state = stack.pop();
  2859. let obj = stack.pop();
  2860. if (obj.__setstate__) {
  2861. if (obj.__setstate__.__call__) {
  2862. obj.__setstate__.__call__([ obj, state ]);
  2863. }
  2864. else {
  2865. obj.__setstate__(state);
  2866. }
  2867. }
  2868. else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  2869. obj.__state__ = state;
  2870. }
  2871. else if (obj instanceof Map) {
  2872. for (const key in state) {
  2873. obj.set(key, state[key]);
  2874. }
  2875. }
  2876. else {
  2877. Object.assign(obj, state);
  2878. }
  2879. if (obj.__read__) {
  2880. obj = obj.__read__(this);
  2881. }
  2882. stack.push(obj);
  2883. break;
  2884. }
  2885. case OpCode.MARK:
  2886. marker.push(stack);
  2887. stack = [];
  2888. break;
  2889. case OpCode.NEWTRUE:
  2890. stack.push(true);
  2891. break;
  2892. case OpCode.NEWFALSE:
  2893. stack.push(false);
  2894. break;
  2895. case OpCode.LONG1: {
  2896. const data = reader.read(reader.byte());
  2897. let number = 0;
  2898. switch (data.length) {
  2899. case 0: number = 0; break;
  2900. case 1: number = data[0]; break;
  2901. case 2: number = data[1] << 8 | data[0]; break;
  2902. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  2903. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  2904. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  2905. default: number = Array.prototype.slice.call(data, 0); break;
  2906. }
  2907. stack.push(number);
  2908. break;
  2909. }
  2910. case OpCode.LONG4:
  2911. // TODO decode LONG4
  2912. stack.push(reader.read(reader.uint32()));
  2913. break;
  2914. case OpCode.TUPLE1:
  2915. stack.push([ stack.pop() ]);
  2916. break;
  2917. case OpCode.TUPLE2: {
  2918. const b = stack.pop();
  2919. const a = stack.pop();
  2920. stack.push([ a, b ]);
  2921. break;
  2922. }
  2923. case OpCode.TUPLE3: {
  2924. const c = stack.pop();
  2925. const b = stack.pop();
  2926. const a = stack.pop();
  2927. stack.push([ a, b, c ]);
  2928. break;
  2929. }
  2930. case OpCode.MEMOIZE:
  2931. memo.set(memo.size, stack[stack.length - 1]);
  2932. break;
  2933. case OpCode.FRAME:
  2934. reader.read(8);
  2935. break;
  2936. case OpCode.BYTEARRAY8: {
  2937. stack.push(reader.read(reader.int64()));
  2938. break;
  2939. }
  2940. case OpCode.NONE:
  2941. stack.push(null);
  2942. break;
  2943. case OpCode.STOP:
  2944. return stack.pop();
  2945. default:
  2946. throw new python.Error('Unknown opcode ' + opcode + ' at position ' + (reader.position - 1).toString() + '.');
  2947. }
  2948. }
  2949. throw new python.Error('Unexpected end of file.');
  2950. }
  2951. find_class(module, name) {
  2952. execution.__import__(module);
  2953. return execution.resolve(module + '.' + name);
  2954. }
  2955. _instantiate(cls, args) {
  2956. return execution.invoke(cls, args);
  2957. }
  2958. read(size) {
  2959. return this._reader.read(size);
  2960. }
  2961. stream(size) {
  2962. return this._reader.stream(size);
  2963. }
  2964. });
  2965. this.registerType('random.Random', class {});
  2966. this.registerType('re.Pattern', class {
  2967. constructor(pattern, flags) {
  2968. this.pattern = pattern;
  2969. this.flags = flags;
  2970. }
  2971. });
  2972. this.registerType('spacy._ml.PrecomputableAffine', class {
  2973. __setstate__(state) {
  2974. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  2975. }
  2976. });
  2977. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  2978. __setstate__(state) {
  2979. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  2980. }
  2981. });
  2982. this.registerType('theano.compile.function_module._constructor_Function', class {});
  2983. this.registerType('theano.compile.function_module._constructor_FunctionMaker', class {});
  2984. this.registerType('theano.compile.function_module.Function', class {});
  2985. this.registerType('theano.compile.function_module.Supervisor', class {});
  2986. this.registerType('theano.compile.io.In', class {});
  2987. this.registerType('theano.compile.io.SymbolicOutput', class {});
  2988. this.registerType('theano.compile.mode.Mode', class {});
  2989. this.registerType('theano.compile.ops.OutputGuard', class {});
  2990. this.registerType('theano.compile.ops.Shape', class {});
  2991. this.registerType('theano.compile.ops.Shape_i', class {});
  2992. this.registerType('theano.gof.destroyhandler.DestroyHandler', class {});
  2993. this.registerType('theano.gof.fg.FunctionGraph', class {});
  2994. this.registerType('theano.gof.graph.Apply', class {});
  2995. this.registerType('theano.gof.link.Container', class {});
  2996. this.registerType('theano.gof.opt._metadict', class {});
  2997. this.registerType('theano.gof.opt.ChangeTracker', class {});
  2998. this.registerType('theano.gof.opt.MergeFeature', class {});
  2999. this.registerType('theano.gof.optdb.Query', class {});
  3000. this.registerType('theano.gof.toolbox.PreserveVariableAttributes', class {});
  3001. this.registerType('theano.gof.toolbox.ReplaceValidate', class {});
  3002. this.registerType('theano.gof.utils.scratchpad', class {});
  3003. this.registerType('theano.misc.ordered_set.Link', class {});
  3004. this.registerType('theano.misc.ordered_set.OrderedSet', class {});
  3005. this.registerType('theano.sandbox.cuda.basic_ops.HostFromGpu', class {});
  3006. this.registerType('theano.sandbox.cuda.type.CudaNdarray_unpickler', class {});
  3007. this.registerType('theano.sandbox.cuda.type.CudaNdarrayType', class {});
  3008. this.registerType('theano.sandbox.cuda.var.CudaNdarraySharedVariable', class {});
  3009. this.registerType('theano.scalar.basic.Abs', class {});
  3010. this.registerType('theano.scalar.basic.Add', class {});
  3011. this.registerType('theano.scalar.basic.Cast', class {});
  3012. this.registerType('theano.scalar.basic.Composite', class {});
  3013. this.registerType('theano.scalar.basic.EQ', class {});
  3014. this.registerType('theano.scalar.basic.GE', class {});
  3015. this.registerType('theano.scalar.basic.Identity', class {});
  3016. this.registerType('theano.scalar.basic.IntDiv', class {});
  3017. this.registerType('theano.scalar.basic.Inv', class {});
  3018. this.registerType('theano.scalar.basic.LE', class {});
  3019. this.registerType('theano.scalar.basic.LT', class {});
  3020. this.registerType('theano.scalar.basic.Mul', class {});
  3021. this.registerType('theano.scalar.basic.Neg', class {});
  3022. this.registerType('theano.scalar.basic.Scalar', class {});
  3023. this.registerType('theano.scalar.basic.ScalarConstant', class {});
  3024. this.registerType('theano.scalar.basic.ScalarVariable', class {});
  3025. this.registerType('theano.scalar.basic.Second', class {});
  3026. this.registerType('theano.scalar.basic.Sgn', class {});
  3027. this.registerType('theano.scalar.basic.specific_out', class {});
  3028. this.registerType('theano.scalar.basic.Sub', class {});
  3029. this.registerType('theano.scalar.basic.Switch', class {});
  3030. this.registerType('theano.scalar.basic.Tanh', class {});
  3031. this.registerType('theano.scalar.basic.transfer_type', class {});
  3032. this.registerType('theano.scalar.basic.TrueDiv', class {});
  3033. this.registerType('theano.tensor.basic.Alloc', class {});
  3034. this.registerType('theano.tensor.basic.Dot', class {});
  3035. this.registerType('theano.tensor.basic.MaxAndArgmax', class {});
  3036. this.registerType('theano.tensor.basic.Reshape', class {});
  3037. this.registerType('theano.tensor.basic.ScalarFromTensor', class {});
  3038. this.registerType('theano.tensor.blas.Dot22', class {});
  3039. this.registerType('theano.tensor.blas.Dot22Scalar', class {});
  3040. this.registerType('theano.tensor.blas.Gemm', class {});
  3041. this.registerType('theano.tensor.elemwise.DimShuffle', class {});
  3042. this.registerType('theano.tensor.elemwise.Elemwise', class {});
  3043. this.registerType('theano.tensor.elemwise.Sum', class {});
  3044. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d', class {});
  3045. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradInputs', class {});
  3046. this.registerType('theano.tensor.nnet.abstract_conv.AbstractConv2d_gradWeights', class {});
  3047. this.registerType('theano.tensor.nnet.corr.CorrMM', class {});
  3048. this.registerType('theano.tensor.nnet.corr.CorrMM_gradInputs', class {});
  3049. this.registerType('theano.tensor.nnet.corr.CorrMM_gradWeights', class {});
  3050. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1Hot', class {});
  3051. this.registerType('theano.tensor.nnet.nnet.CrossentropyCategorical1HotGrad', class {});
  3052. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmax1HotWithBiasDx', class {});
  3053. this.registerType('theano.tensor.nnet.nnet.CrossentropySoftmaxArgmax1HotWithBias', class {});
  3054. this.registerType('theano.tensor.nnet.nnet.Softmax', class {});
  3055. this.registerType('theano.tensor.nnet.nnet.SoftmaxGrad', class {});
  3056. this.registerType('theano.tensor.nnet.nnet.SoftmaxWithBias', class {});
  3057. this.registerType('theano.tensor.opt.MakeVector', class {});
  3058. this.registerType('theano.tensor.opt.ShapeFeature', class {});
  3059. this.registerType('theano.tensor.sharedvar.TensorSharedVariable', class {});
  3060. this.registerType('theano.tensor.signal.pool.MaxPoolGrad', class {});
  3061. this.registerType('theano.tensor.signal.pool.Pool', class {});
  3062. this.registerType('theano.tensor.subtensor.Subtensor', class {});
  3063. this.registerType('theano.tensor.type.TensorType', class {});
  3064. this.registerType('theano.tensor.var.TensorConstant', class {});
  3065. this.registerType('theano.tensor.var.TensorConstantSignature', class {});
  3066. this.registerType('theano.tensor.var.TensorVariable', class {});
  3067. this.registerType('thinc.describe.Biases', class {
  3068. __setstate__(state) {
  3069. Object.assign(this, state);
  3070. }
  3071. });
  3072. this.registerType('thinc.describe.Dimension', class {
  3073. __setstate__(state) {
  3074. Object.assign(this, state);
  3075. }
  3076. });
  3077. this.registerType('thinc.describe.Gradient', class {
  3078. __setstate__(state) {
  3079. Object.assign(this, state);
  3080. }
  3081. });
  3082. this.registerType('thinc.describe.Weights', class {
  3083. __setstate__(state) {
  3084. Object.assign(this, state);
  3085. }
  3086. });
  3087. this.registerType('thinc.describe.Synapses', class {
  3088. __setstate__(state) {
  3089. Object.assign(this, state);
  3090. }
  3091. });
  3092. this.registerType('thinc.neural._classes.affine.Affine', class {
  3093. __setstate__(state) {
  3094. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3095. }
  3096. });
  3097. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  3098. __setstate__(state) {
  3099. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3100. }
  3101. });
  3102. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  3103. __setstate__(state) {
  3104. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3105. }
  3106. });
  3107. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  3108. __setstate__(state) {
  3109. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3110. }
  3111. });
  3112. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  3113. __setstate__(state) {
  3114. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3115. }
  3116. });
  3117. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  3118. __setstate__(state) {
  3119. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3120. }
  3121. });
  3122. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  3123. __setstate__(state) {
  3124. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3125. }
  3126. });
  3127. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  3128. __setstate__(state) {
  3129. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3130. }
  3131. });
  3132. this.registerType('thinc.neural._classes.resnet.Residual', class {
  3133. __setstate__(state) {
  3134. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3135. }
  3136. });
  3137. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  3138. __setstate__(state) {
  3139. Object.assign(this, execution.invoke('pickle.Unpickler', [ state ]).load());
  3140. }
  3141. });
  3142. this.registerType('thinc.neural.mem.Memory', class {
  3143. });
  3144. this.registerType('thinc.neural.ops.NumpyOps', class {
  3145. });
  3146. this.registerType('__main__.BYOLState', class {
  3147. constructor(dict) {
  3148. Object.assign(this, dict);
  3149. }
  3150. });
  3151. this.registerType('types.CodeType', class {});
  3152. this.register('types').ObjectType = this._builtins.object;
  3153. this.register('types').ModuleType = this._builtins.module;
  3154. this.register('types').MethodType = this._builtins.method;
  3155. this.register('types').FunctionType = this._builtins.function;
  3156. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  3157. this.registerType('xgboost.core.Booster', class {});
  3158. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  3159. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  3160. this.registerFunction('_codecs.encode', function(obj, encoding) {
  3161. return execution.invoke('builtins.bytearray', [ obj, encoding ]);
  3162. });
  3163. this.registerFunction('builtins.bytearray', function(source, encoding /*, errors */) {
  3164. if (source) {
  3165. if (Array.isArray(source) || source instanceof Uint8Array) {
  3166. const target = new Uint8Array(source.length);
  3167. for (let i = 0; i < source.length; i++) {
  3168. target[i] = source[i];
  3169. }
  3170. return target;
  3171. }
  3172. if (encoding === 'latin-1' || encoding === 'latin1') {
  3173. const target = new Uint8Array(source.length);
  3174. const length = source.length;
  3175. for (let i = 0; i < length; i++) {
  3176. target[i] = source.charCodeAt(i);
  3177. }
  3178. return target;
  3179. }
  3180. throw new python.Error("Unsupported bytearray encoding '" + JSON.stringify(encoding) + "'.");
  3181. }
  3182. return [];
  3183. });
  3184. this.registerFunction('builtins.bytes', function(source, encoding /*, errors */) {
  3185. if (source) {
  3186. if (Array.isArray(source) || source instanceof Uint8Array) {
  3187. const target = new Uint8Array(source.length);
  3188. for (let i = 0; i < source.length; i++) {
  3189. target[i] = source[i];
  3190. }
  3191. return target;
  3192. }
  3193. if (encoding === 'latin-1') {
  3194. const array = new Uint8Array(source.length);
  3195. for (let i = 0; i < source.length; i++) {
  3196. array[i] = source.charCodeAt(i);
  3197. }
  3198. return array;
  3199. }
  3200. throw new python.Error("Unsupported bytes encoding '" + JSON.stringify(encoding) + "'.");
  3201. }
  3202. return [];
  3203. });
  3204. this.registerFunction('builtins.frozenset', function(iterable) {
  3205. return iterable ? iterable : [];
  3206. });
  3207. this.registerFunction('builtins.getattr', function(obj, name, defaultValue) {
  3208. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  3209. return obj[name];
  3210. }
  3211. return defaultValue;
  3212. });
  3213. this.registerFunction('builtins.set', function(iterable) {
  3214. return iterable ? iterable : [];
  3215. });
  3216. this.registerFunction('builtins.slice', function(start, stop, step) {
  3217. return [ start, stop, step ];
  3218. });
  3219. this.registerFunction('cloudpickle.cloudpickle._builtin_type', function(name) {
  3220. return name;
  3221. });
  3222. this.registerFunction('collections.Counter', function(/* iterable */) {
  3223. return { __module__: 'collections', __name__: 'Counter' };
  3224. });
  3225. this.registerFunction('collections.defaultdict', function(/* default_factory */) {
  3226. return {};
  3227. });
  3228. this.registerFunction('copy_reg._reconstructor', function(cls, base, state) {
  3229. // copyreg._reconstructor in Python 3
  3230. if (base === '__builtin__.object' || base === self._builtins.object) {
  3231. return self.invoke(cls, []);
  3232. }
  3233. else if (base === '__builtin__.tuple' || base === self._builtins.tuple) {
  3234. const obj = self.invoke(cls, []);
  3235. for (let i = 0; i < state.length; i++) {
  3236. obj[i] = state[i];
  3237. }
  3238. return obj;
  3239. }
  3240. throw new python.Error("Unsupported copy_reg._reconstructor base type '" + base + "'.");
  3241. });
  3242. this.registerFunction('copy.deepcopy', function(/* x */) {
  3243. throw new python.Error('Unsupported copy.deepcopy().');
  3244. });
  3245. this.registerFunction('dill._dill._create_cell', function(/* args */) {
  3246. return function() {
  3247. // TODO
  3248. };
  3249. });
  3250. this.registerFunction('dill._dill._create_code', function(args) {
  3251. return self.invoke('types.CodeType', [ args ]);
  3252. });
  3253. this.registerFunction('dill._dill._create_function', function(/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) {
  3254. return function() {
  3255. // TODO
  3256. };
  3257. });
  3258. this.registerFunction('dill._dill._create_namedtuple', function(name, fieldnames, modulename /*, defaults */) {
  3259. const obj = execution.invoke('dill._dill._import_module', [ modulename + '.' + name ]);
  3260. if (obj) {
  3261. return obj;
  3262. }
  3263. return undefined;
  3264. });
  3265. this.registerFunction('dill._dill._get_attr', function(self, name) {
  3266. if (Object.prototype.hasOwnProperty.call(self, name)) {
  3267. return self[name];
  3268. }
  3269. return undefined;
  3270. });
  3271. this.registerFunction('dill._dill._import_module', function(import_name, safe) {
  3272. try {
  3273. if (import_name.startsWith('__runtime__.')) {
  3274. return execution.module(import_name);
  3275. }
  3276. else if (import_name.indexOf('.') === -1) {
  3277. return execution.__import__(import_name);
  3278. }
  3279. return execution.resolve(import_name);
  3280. }
  3281. catch (err) {
  3282. if (safe) {
  3283. return null;
  3284. }
  3285. throw err;
  3286. }
  3287. });
  3288. this.registerFunction('dill._dill._load_type', function(name) {
  3289. return self.resolve('types.' + name);
  3290. });
  3291. this.registerFunction('lasagne.nonlinearities.rectify', function() {
  3292. throw new python.Error('Function not implemented.');
  3293. });
  3294. this.registerFunction('lasagne.nonlinearities.softmax', function() {
  3295. throw new python.Error('Function not implemented.');
  3296. });
  3297. this.registerFunction('lasagne.objectives.categorical_crossentropy', function() {
  3298. throw new python.Error('Function not implemented.');
  3299. });
  3300. this.registerFunction('lasagne.updates.nesterov_momentum', function() {
  3301. throw new python.Error('Function not implemented.');
  3302. });
  3303. this.registerFunction('msgpack.unpackb', function(packed, ext_hook) {
  3304. const BinaryReader = class {
  3305. constructor(buffer, ext_hook) {
  3306. // https://github.com/msgpack/msgpack-javascript/blob/master/src/Decoder.ts
  3307. // https://github.com/msgpack/msgpack-python/blob/main/msgpack/_unpacker.pyx
  3308. this._buffer = buffer;
  3309. this._position = 0;
  3310. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3311. this._ext_hook = ext_hook;
  3312. }
  3313. value() {
  3314. const c = this._view.getUint8(this.skip(1));
  3315. if (c >= 0xe0) {
  3316. return c - 0x100;
  3317. }
  3318. if (c < 0xC0) {
  3319. if (c < 0x80) {
  3320. return c;
  3321. }
  3322. if (c < 0x90) {
  3323. return this.map(c - 0x80);
  3324. }
  3325. if (c < 0xa0) {
  3326. return this.array(c - 0x90);
  3327. }
  3328. return this.string(c - 0xa0);
  3329. }
  3330. switch (c) {
  3331. case 0xC0: return null;
  3332. case 0xC2: return false;
  3333. case 0xC3: return true;
  3334. case 0xC4: return this.read(this._view.getUint8(this.skip(1)));
  3335. case 0xC5: return this.read(this._view.getUint16(this.skip(2)));
  3336. case 0xC6: return this.read(this._view.getUint32(this.skip(4)));
  3337. case 0xC7: return this.extension(this._view.getUint8(this.skip(1)));
  3338. case 0xC8: return this.extension(this._view.getUint16(this.skip(2)));
  3339. case 0xC9: return this.extension(this._view.getUint32(this.skip(4)));
  3340. case 0xCA: return this._view.getFloat32(this.skip(4));
  3341. case 0xCB: return this._view.getFloat64(this.skip(8));
  3342. case 0xCC: return this._view.getUint8(this.skip(1));
  3343. case 0xCD: return this._view.getUint16(this.skip(2));
  3344. case 0xCE: return this._view.getUint32(this.skip(4));
  3345. case 0xCF: return this._view.getUint64(this.skip(8));
  3346. case 0xD0: return this._view.getInt8(this.skip(1));
  3347. case 0xD1: return this._view.getInt16(this.skip(2));
  3348. case 0xD2: return this._view.getInt32(this.skip(4));
  3349. case 0xD3: return this._view.getInt64(this.skip(8));
  3350. case 0xD4: return this.extension(1);
  3351. case 0xD5: return this.extension(2);
  3352. case 0xD6: return this.extension(4);
  3353. case 0xD7: return this.extension(8);
  3354. case 0xD8: return this.extension(16);
  3355. case 0xD9: return this.string(this._view.getUint8(this.skip(1)));
  3356. case 0xDA: return this.string(this._view.getUint16(this.skip(2)));
  3357. case 0xDB: return this.string(this._view.getUint32(this.skip(4)));
  3358. case 0xDC: return this.array(this._view.getUint16(this.skip(2)));
  3359. case 0xDD: return this.array(this._view.getUint32(this.skip(4)));
  3360. case 0xDE: return this.map(this._view.getUint16(this.skip(2)));
  3361. case 0xDF: return this.map(this._view.getUint32(this.skip(4)));
  3362. default: throw new python.Error("Invalid code '" + c + "'.");
  3363. }
  3364. }
  3365. map(size) {
  3366. const map = {};
  3367. for (let i = 0; i < size; i++) {
  3368. const key = this.value();
  3369. const value = this.value();
  3370. map[key] = value;
  3371. }
  3372. return map;
  3373. }
  3374. array(size) {
  3375. const array = new Array(size);
  3376. for (let i = 0; i < size; i++) {
  3377. array[i] = this.value();
  3378. }
  3379. return array;
  3380. }
  3381. extension(size) {
  3382. const code = this._view.getUint8(this.skip(1));
  3383. const data = this.read(size);
  3384. return this._ext_hook(code, data);
  3385. }
  3386. skip(offset) {
  3387. const position = this._position;
  3388. this._position += offset;
  3389. if (this._position > this._buffer.length) {
  3390. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3391. }
  3392. return position;
  3393. }
  3394. read(size) {
  3395. const data = this._buffer.subarray(this._position, this._position + size);
  3396. this._position += size;
  3397. return data;
  3398. }
  3399. string(size) {
  3400. const buffer = this.read(size);
  3401. this._decoder = this._decoder || new TextDecoder('utf8');
  3402. return this._decoder.decode(buffer);
  3403. }
  3404. };
  3405. return new BinaryReader(packed, ext_hook).value();
  3406. });
  3407. this.registerFunction('nolearn.lasagne.base.objective', function() {
  3408. throw new python.Error('Function not implemented.');
  3409. });
  3410. this.registerFunction('numpy._reconstruct', function(subtype, shape, dtype) {
  3411. return self.invoke(subtype, [ shape, dtype ]);
  3412. });
  3413. this.registerFunction('numpy.core._multiarray_umath._reconstruct', function(subtype, shape, dtype) {
  3414. return self.invoke(subtype, [ shape, dtype ]);
  3415. });
  3416. this.registerFunction('numpy.core.multiarray._reconstruct', function(subtype, shape, dtype) {
  3417. return self.invoke(subtype, [ shape, dtype ]);
  3418. });
  3419. this.registerFunction('numpy.core.multiarray.scalar', function(dtype, rawData) {
  3420. let data = rawData;
  3421. if (typeof rawData === 'string' || rawData instanceof String) {
  3422. data = new Uint8Array(rawData.length);
  3423. for (let i = 0; i < rawData.length; i++) {
  3424. data[i] = rawData.charCodeAt(i);
  3425. }
  3426. }
  3427. switch (dtype.kind) {
  3428. case 'b': {
  3429. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3430. switch (dtype.itemsize) {
  3431. case 1: return view.getInt8(0) ? true : false;
  3432. default: throw new python.Error("Unsupported scalar dtype boolean itemsize '" + dtype.itemsize + "'.");
  3433. }
  3434. }
  3435. case 'f': {
  3436. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3437. switch (dtype.itemsize) {
  3438. case 4: return view.getFloat32(0, dtype.byteorder === '<');
  3439. case 8: return view.getFloat64(0, dtype.byteorder === '<');
  3440. default: throw new python.Error("Unsupported scalar dtype float itemsize '" + dtype.itemsize + "'.");
  3441. }
  3442. }
  3443. case 'i': {
  3444. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3445. switch (dtype.itemsize) {
  3446. case 1: return view.getInt8(0);
  3447. case 2: return view.getInt16(0, dtype.byteorder === '<');
  3448. case 4: return view.getInt32(0, dtype.byteorder === '<');
  3449. case 8: return view.getInt64(0, dtype.byteorder === '<');
  3450. default: throw new python.Error("Unsupported scalar dtype int itemsize '" + dtype.itemsize + "'.");
  3451. }
  3452. }
  3453. case 'u': {
  3454. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3455. switch (dtype.itemsize) {
  3456. case 1: return view.getUint8(0);
  3457. case 2: return view.getUint16(0, dtype.byteorder === '<');
  3458. case 4: return view.getUint32(0, dtype.byteorder === '<');
  3459. case 8: return view.getUint64(0, dtype.byteorder === '<');
  3460. default: throw new python.Error("Unsupported scalar dtype uint itemsize '" + dtype.itemsize + "'.");
  3461. }
  3462. }
  3463. case 'U': {
  3464. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3465. const list = [];
  3466. for (let i = 0; i < dtype.itemsize; i += 4) {
  3467. list.push(String.fromCodePoint(view.getUint32(i, true)));
  3468. }
  3469. return list.join('');
  3470. }
  3471. default: {
  3472. throw new python.Error("Unsupported scalar dtype kind '" + dtype.kind + "'.");
  3473. }
  3474. }
  3475. });
  3476. this.registerFunction('numpy.core._multiarray_umath.scalar', function(dtype, rawData) {
  3477. let data = rawData;
  3478. if (typeof rawData === 'string') {
  3479. data = new Uint8Array(rawData.length);
  3480. for (let i = 0; i < rawData.length; i++) {
  3481. data[i] = rawData.charCodeAt(i);
  3482. }
  3483. }
  3484. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  3485. switch (dtype.__name__) {
  3486. case 'uint8':
  3487. return dataView.getUint8(0);
  3488. case 'float32':
  3489. return dataView.getFloat32(0, true);
  3490. case 'float64':
  3491. return dataView.getFloat64(0, true);
  3492. case 'int8':
  3493. return dataView.getInt8(0, true);
  3494. case 'int16':
  3495. return dataView.getInt16(0, true);
  3496. case 'int32':
  3497. return dataView.getInt32(0, true);
  3498. case 'int64':
  3499. return dataView.getInt64(0, true);
  3500. default:
  3501. throw new python.Error("Unsupported scalar type '" + dtype.__name__ + "'.");
  3502. }
  3503. });
  3504. this.registerFunction('numpy.load', function(file) {
  3505. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  3506. const signature = [ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59 ];
  3507. if (!file.read(6).every((v, i) => v == signature[i])) {
  3508. throw new python.Error('Invalid signature.');
  3509. }
  3510. const major = file.read(1)[0];
  3511. const minor = file.read(1)[0];
  3512. if (major > 3) {
  3513. throw new python.Error("Invalid version '" + [ major, minor ].join('.') + "'.");
  3514. }
  3515. const buffer = new Uint8Array([ 0, 0, 0, 0 ]);
  3516. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  3517. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  3518. let header = file.read(header_length);
  3519. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  3520. header = decoder.decode(header);
  3521. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',',1]').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  3522. if (!header.descr || header.descr.length < 2) {
  3523. throw new python.Error("Missing property 'descr'.");
  3524. }
  3525. if (!header.shape) {
  3526. throw new python.Error("Missing property 'shape'.");
  3527. }
  3528. const shape = header.shape;
  3529. const dtype = self.invoke('numpy.dtype', [ header.descr.substring(1) ]);
  3530. dtype.byteorder = header.descr[0];
  3531. let data = null;
  3532. switch (dtype.byteorder) {
  3533. case '|': {
  3534. data = file.read();
  3535. if (dtype.kind === 'O') {
  3536. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  3537. return unpickler.load();
  3538. }
  3539. break;
  3540. }
  3541. case '>':
  3542. case '<': {
  3543. if (header.descr.length !== 3) {
  3544. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3545. }
  3546. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  3547. data = file.read(dtype.itemsize * count);
  3548. break;
  3549. }
  3550. default: {
  3551. throw new python.Error("Unsupported data type '" + header.descr + "'.");
  3552. }
  3553. }
  3554. if (header.fortran_order) {
  3555. data = null;
  3556. }
  3557. return self.invoke('numpy.ndarray', [ shape, dtype, data ]);
  3558. });
  3559. this.registerFunction('numpy.save', function(file, arr) {
  3560. const descr = arr.dtype.str;
  3561. if (descr[0] !== '<' && descr[0] !== '>') {
  3562. throw new python.Error("Unsupported byte order '" + descr + "'.");
  3563. }
  3564. if (descr.length !== 3 || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  3565. throw new python.Error("Unsupported data type '" + descr + "'.");
  3566. }
  3567. let shape = '';
  3568. switch (arr.shape.length) {
  3569. case 0: shape = '()'; break;
  3570. case 1: shape = '(' + arr.shape[0].toString() + ',)'; break;
  3571. default: shape = '(' + arr.shape.map((dimension) => dimension.toString()).join(', ') + ')'; break;
  3572. }
  3573. const properties = [
  3574. "'descr': '" + descr + "'",
  3575. "'fortran_order': False",
  3576. "'shape': " + shape
  3577. ];
  3578. let header = '{ ' + properties.join(', ') + ' }';
  3579. header += ' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f)) + '\n';
  3580. const encoder = new TextEncoder('ascii');
  3581. file.write([ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00 ]); // '\\x93NUMPY' + version
  3582. file.write([ header.length & 0xff, (header.length >> 8) & 0xff ]);
  3583. file.write(encoder.encode(header));
  3584. file.write(arr.tobytes());
  3585. });
  3586. this.registerFunction('numpy.asarray', function(a, dtype) {
  3587. const encode = (context, data, dim) => {
  3588. const size = context.shape[dim];
  3589. const littleendian = context.littleendian;
  3590. if (dim == context.shape.length - 1) {
  3591. for (let i = 0; i < size; i++) {
  3592. switch (context.dtype) {
  3593. case 'f2':
  3594. context.view.setFloat16(context.position, data[i], littleendian);
  3595. break;
  3596. case 'f4':
  3597. context.view.setFloat32(context.position, data[i], littleendian);
  3598. break;
  3599. case 'f8':
  3600. context.view.setFloat64(context.position, data[i], littleendian);
  3601. break;
  3602. case 'i1':
  3603. context.view.setInt8(context.position, data[i], littleendian);
  3604. break;
  3605. case 'i2':
  3606. context.view.setInt16(context.position, data[i], littleendian);
  3607. break;
  3608. case 'i4':
  3609. context.view.setInt32(context.position, data[i], littleendian);
  3610. break;
  3611. case 'i8':
  3612. context.view.setInt64(context.position, data[i], littleendian);
  3613. break;
  3614. case 'u1':
  3615. context.view.setUint8(context.position, data[i], littleendian);
  3616. break;
  3617. case 'u2':
  3618. context.view.setUint16(context.position, data[i], littleendian);
  3619. break;
  3620. case 'u4':
  3621. context.view.setUint32(context.position, data[i], littleendian);
  3622. break;
  3623. case 'u8':
  3624. context.view.setUint64(context.position, data[i], littleendian);
  3625. break;
  3626. case 'c8':
  3627. context.view.setComplex64(context.position, data[i], littleendian);
  3628. break;
  3629. case 'c16':
  3630. context.view.setComplex128(context.position, data[i], littleendian);
  3631. break;
  3632. default:
  3633. throw new python.Error("Unsupported tensor data type '" + context.dtype + "'.");
  3634. }
  3635. context.position += context.itemsize;
  3636. }
  3637. }
  3638. else {
  3639. for (let j = 0; j < size; j++) {
  3640. encode(context, data[j], dim + 1);
  3641. }
  3642. }
  3643. };
  3644. const array_size = (value) => {
  3645. if (value.every((item) => Array.isArray(item))) {
  3646. const dims = value.map((item) => array_size(item));
  3647. const dim = dims[0];
  3648. for (let i = 1; i < dims.length; i++) {
  3649. if (dim.length === dims[i].length) {
  3650. if (!dims[i].every((value, i) => value ===dim[i])) {
  3651. throw new python.Error('Invalid array shape.');
  3652. }
  3653. }
  3654. }
  3655. return [ value.length ].concat(dim);
  3656. }
  3657. return [ value.length ];
  3658. };
  3659. const shape = Array.isArray(a) ? array_size(a) : [];
  3660. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  3661. const context = {
  3662. position: 0,
  3663. itemsize: dtype.itemsize,
  3664. dtype: dtype.str.substring(1),
  3665. littleendian: dtype.str[0],
  3666. shape: shape,
  3667. data: new Uint8Array(size)
  3668. };
  3669. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  3670. encode(context, a, 0);
  3671. return self.invoke('numpy.ndarray', [ shape, dtype, context.data ]);
  3672. });
  3673. this.registerFunction('numpy.ma.core._mareconstruct', function(subtype, baseclass, baseshape, basetype) {
  3674. const data = self.invoke(baseclass, [ baseshape, basetype ]);
  3675. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  3676. const mask = self.invoke('numpy.ndarray', [ baseshape, '' ]);
  3677. return self.invoke(subtype, [ data, mask, basetype ]);
  3678. });
  3679. this.registerFunction('numpy.random.__RandomState_ctor', function() {
  3680. return {};
  3681. });
  3682. this.registerFunction('numpy.random._pickle.__randomstate_ctor', function() {
  3683. return {};
  3684. });
  3685. this.registerFunction('numpy.core.numeric._frombuffer', function(/* buf, dtype, shape, order */) {
  3686. return {};
  3687. });
  3688. this.registerFunction('sklearn.metrics.scorer._passthrough_scorer', function() {
  3689. throw new python.Error("Function not implemented.");
  3690. });
  3691. this.registerFunction('sklearn.feature_selection._univariate_selection.f_classif', function() {
  3692. throw new python.Error("Function not implemented.");
  3693. });
  3694. this.registerFunction('re._compile', function(pattern, flags) {
  3695. return self.invoke('re.Pattern', [ pattern, flags ]);
  3696. });
  3697. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', function(name) {
  3698. return function() {
  3699. return self.invoke('types.' + name, arguments);
  3700. };
  3701. });
  3702. this.registerFunction('theano.scalar.basic.same_out', function() {
  3703. throw new python.Error('Function not implemented.');
  3704. });
  3705. this.registerFunction('theano.scalar.basic.same_out_nocomplex', function() {
  3706. throw new python.Error('Function not implemented.');
  3707. });
  3708. this.registerFunction('theano.scalar.basic.upcast_out', function() {
  3709. throw new python.Error('Function not implemented.');
  3710. });
  3711. this.registerFunction('theano.scalar.basic.upgrade_to_float', function() {
  3712. throw new python.Error('Function not implemented.');
  3713. });
  3714. this.registerFunction('theano.tensor.nnet.conv2d', function() {
  3715. throw new python.Error('Function not implemented.');
  3716. });
  3717. this.registerFunction('theano.tensor.type.values_eq_approx_remove_inf_nan', function() {
  3718. throw new python.Error('Function not implemented.');
  3719. });
  3720. this.registerFunction('theano.tensor.type.values_eq_approx_remove_nan', function() {
  3721. throw new python.Error('Function not implemented.');
  3722. });
  3723. this.registerType('torch.ao.quantization.observer._PartialWrapper', class {});
  3724. this.registerType('torch.ao.quantization.observer.HistogramObserver', class {});
  3725. this.registerType('torch.ao.quantization.observer.PerChannelMinMaxObserver', class {});
  3726. this.registerType('torch.ao.quantization.qconfig.QConfig', class {});
  3727. this.registerType('torch.ao.quantization.stubs.DeQuantStub', class {});
  3728. this.registerType('torch.ao.quantization.stubs.QuantStub', class {});
  3729. this.registerType('torch.autograd.variable.Variable', class {});
  3730. this.registerType('torch.backends.cudnn.rnn.Unserializable', class {});
  3731. this.registerType('torch.distributions.bernoulli.Bernoulli', class {});
  3732. this.registerType('torch.distributions.constraints._LowerCholesky', class {});
  3733. this.registerType('torch.distributions.constraints._Real', class {});
  3734. this.registerType('torch.distributions.multivariate_normal.MultivariateNormal', class {});
  3735. this.registerType('torch.distributions.normal.Normal', class {});
  3736. this.registerType('torch.distributions.transforms.LowerCholeskyTransform', class {});
  3737. this.registerType('torch.distributions.uniform.Uniform', class {});
  3738. this.registerType('torch.nn.backends.thnn._get_thnn_function_backend', class {});
  3739. this.registerType('torch.nn.intrinsic.modules.fused.ConvBnReLU2d', class {});
  3740. this.registerType('torch.nn.intrinsic.modules.fused.ConvReLU2d', class {});
  3741. this.registerType('torch.nn.intrinsic.modules.fused.BNReLU2d', class {});
  3742. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d', class {});
  3743. this.registerType('torch.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d', class {});
  3744. this.registerType('torch.nn.intrinsic.quantized.modules.conv_relu.ConvReLU2d', class {});
  3745. this.registerType('torch.nn.intrinsic.quantized.modules.linear_relu.LinearReLU', class {});
  3746. this.registerType('torch.nn.modules.activation.CELU', class {});
  3747. this.registerType('torch.nn.modules.activation.ELU', class {});
  3748. this.registerType('torch.nn.modules.activation.GELU', class {});
  3749. this.registerType('torch.nn.modules.activation.GLU', class {});
  3750. this.registerType('torch.nn.modules.activation.Hardtanh', class {});
  3751. this.registerType('torch.nn.modules.activation.Hardswish', class {});
  3752. this.registerType('torch.nn.modules.activation.Hardsigmoid', class {});
  3753. this.registerType('torch.nn.modules.activation.LeakyReLU', class {});
  3754. this.registerType('torch.nn.modules.activation.LogSigmoid', class {});
  3755. this.registerType('torch.nn.modules.activation.LogSoftmax', class {});
  3756. this.registerType('torch.nn.modules.activation.Mish', class {});
  3757. this.registerType('torch.nn.modules.activation.MultiheadAttention', class {});
  3758. this.registerType('torch.nn.modules.activation.ReLU', class {});
  3759. this.registerType('torch.nn.modules.activation.ReLU6', class {});
  3760. this.registerType('torch.nn.modules.activation.PReLU', class {});
  3761. this.registerType('torch.nn.modules.activation.RReLU', class {});
  3762. this.registerType('torch.nn.modules.activation.SELU', class {});
  3763. this.registerType('torch.nn.modules.activation.Sigmoid', class {});
  3764. this.registerType('torch.nn.modules.activation.SiLU', class {});
  3765. this.registerType('torch.nn.modules.activation.Softmax', class {});
  3766. this.registerType('torch.nn.modules.activation.Softmax2d', class {});
  3767. this.registerType('torch.nn.modules.activation.Softplus', class {});
  3768. this.registerType('torch.nn.modules.activation.Tanh', class {});
  3769. this.registerType('torch.nn.modules.activation.Tanhshrink', class {});
  3770. this.registerType('torch.nn.modules.activation.Threshold', class {});
  3771. this.registerType('torch.nn.modules.batchnorm.BatchNorm1d', class {});
  3772. this.registerType('torch.nn.modules.batchnorm.BatchNorm2d', class {});
  3773. this.registerType('torch.nn.modules.batchnorm.BatchNorm3d', class {});
  3774. this.registerType('torch.nn.modules.batchnorm.LazyBatchNorm1d', class {});
  3775. this.registerType('torch.nn.modules.batchnorm.SyncBatchNorm', class {});
  3776. this.registerType('torch.nn.modules.container.ModuleDict', class {});
  3777. this.registerType('torch.nn.modules.container.ModuleList', class {});
  3778. this.registerType('torch.nn.modules.container.ParameterDict', class {});
  3779. this.registerType('torch.nn.modules.container.ParameterList', class {});
  3780. this.registerType('torch.nn.modules.container.Sequential', class {});
  3781. this.registerType('torch.nn.modules.conv.Conv1d', class {});
  3782. this.registerType('torch.nn.modules.conv.Conv2d', class {});
  3783. this.registerType('torch.nn.modules.conv.Conv3d', class {});
  3784. this.registerType('torch.nn.modules.conv.ConvTranspose1d', class {});
  3785. this.registerType('torch.nn.modules.conv.ConvTranspose2d', class {});
  3786. this.registerType('torch.nn.modules.conv.ConvTranspose3d', class {});
  3787. this.registerType('torch.nn.modules.distance.CosineSimilarity', class {});
  3788. this.registerType('torch.nn.modules.dropout.AlphaDropout', class {});
  3789. this.registerType('torch.nn.modules.dropout.Dropout', class {});
  3790. this.registerType('torch.nn.modules.dropout.Dropout2d', class {});
  3791. this.registerType('torch.nn.modules.dropout.Dropout3d', class {});
  3792. this.registerType('torch.nn.modules.fold.Fold', class {});
  3793. this.registerType('torch.nn.modules.fold.Unfold', class {});
  3794. this.registerType('torch.nn.modules.flatten.Flatten', class {});
  3795. this.registerType('torch.nn.modules.flatten.Unflatten', class {});
  3796. this.registerType('torch.nn.modules.instancenorm.InstanceNorm1d', class {});
  3797. this.registerType('torch.nn.modules.instancenorm.InstanceNorm2d', class {});
  3798. this.registerType('torch.nn.modules.instancenorm.InstanceNorm3d', class {});
  3799. this.registerType('torch.nn.modules.linear._LinearWithBias', class {});
  3800. this.registerType('torch.nn.modules.linear.Bilinear', class {});
  3801. this.registerType('torch.nn.modules.linear.Identity', class {});
  3802. this.registerType('torch.nn.modules.linear.LazyLinear', class {});
  3803. this.registerType('torch.nn.modules.linear.Linear', class {});
  3804. this.registerType('torch.nn.modules.linear.NonDynamicallyQuantizableLinear', class {});
  3805. this.registerType('torch.nn.modules.loss.BCELoss', class {});
  3806. this.registerType('torch.nn.modules.loss.BCEWithLogitsLoss', class {});
  3807. this.registerType('torch.nn.modules.loss.CrossEntropyLoss', class {});
  3808. this.registerType('torch.nn.modules.loss.CTCLoss', class {});
  3809. this.registerType('torch.nn.modules.loss.KLDivLoss', class {});
  3810. this.registerType('torch.nn.modules.loss.L1Loss', class {});
  3811. this.registerType('torch.nn.modules.loss.MarginRankingLoss', class {});
  3812. this.registerType('torch.nn.modules.loss.MSELoss', class {});
  3813. this.registerType('torch.nn.modules.loss.NLLLoss', class {});
  3814. this.registerType('torch.nn.modules.loss.NLLLoss2d', class {});
  3815. this.registerType('torch.nn.modules.loss.SmoothL1Loss', class {});
  3816. this.registerType('torch.nn.modules.module._IncompatibleKeys', class {});
  3817. this.registerType('torch.nn.modules.module.Module', class {});
  3818. this.registerType('torch.nn.modules.module.PatchForward', class {});
  3819. this.registerType('torch.nn.modules.normalization.CrossMapLRN2d', class {});
  3820. this.registerType('torch.nn.modules.normalization.GroupNorm', class {});
  3821. this.registerType('torch.nn.modules.normalization.LayerNorm', class {});
  3822. this.registerType('torch.nn.modules.normalization.LocalResponseNorm', class {});
  3823. this.registerType('torch.nn.modules.padding.ReflectionPad1d', class {});
  3824. this.registerType('torch.nn.modules.padding.ReflectionPad2d', class {});
  3825. this.registerType('torch.nn.modules.padding.ReplicationPad1d', class {});
  3826. this.registerType('torch.nn.modules.padding.ReplicationPad2d', class {});
  3827. this.registerType('torch.nn.modules.padding.ReplicationPad3d', class {});
  3828. this.registerType('torch.nn.modules.padding.ZeroPad2d', class {});
  3829. this.registerType('torch.nn.modules.padding.ConstantPad1d', class {});
  3830. this.registerType('torch.nn.modules.padding.ConstantPad2d', class {});
  3831. this.registerType('torch.nn.modules.padding.ConstantPad3d', class {});
  3832. this.registerType('torch.nn.modules.pixelshuffle.PixelShuffle', class {});
  3833. this.registerType('torch.nn.modules.pixelshuffle.PixelUnshuffle', class {});
  3834. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool1d', class {});
  3835. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool2d', class {});
  3836. this.registerType('torch.nn.modules.pooling.AdaptiveAvgPool3d', class {});
  3837. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool1d', class {});
  3838. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool2d', class {});
  3839. this.registerType('torch.nn.modules.pooling.AdaptiveMaxPool3d', class {});
  3840. this.registerType('torch.nn.modules.pooling.AvgPool1d', class {});
  3841. this.registerType('torch.nn.modules.pooling.AvgPool2d', class {});
  3842. this.registerType('torch.nn.modules.pooling.AvgPool3d', class {});
  3843. this.registerType('torch.nn.modules.pooling.FractionalMaxPool2d', class {});
  3844. this.registerType('torch.nn.modules.pooling.LPPool2d', class {});
  3845. this.registerType('torch.nn.modules.pooling.MaxPool1d', class {});
  3846. this.registerType('torch.nn.modules.pooling.MaxPool2d', class {});
  3847. this.registerType('torch.nn.modules.pooling.MaxPool3d', class {});
  3848. this.registerType('torch.nn.modules.pooling.MaxUnpool1d', class {});
  3849. this.registerType('torch.nn.modules.pooling.MaxUnpool2d', class {});
  3850. this.registerType('torch.nn.modules.pooling.MaxUnpool3d', class {});
  3851. this.registerType('torch.nn.modules.rnn.GRU', class {});
  3852. this.registerType('torch.nn.modules.rnn.GRUCell', class {});
  3853. this.registerType('torch.nn.modules.rnn.LSTM', class {});
  3854. this.registerType('torch.nn.modules.rnn.LSTMCell', class {});
  3855. this.registerType('torch.nn.modules.rnn.RNN', class {});
  3856. this.registerType('torch.nn.modules.rnn.RNNCell', class {});
  3857. this.registerType('torch.nn.modules.sparse.Embedding', class {});
  3858. this.registerType('torch.nn.modules.sparse.EmbeddingBag', class {});
  3859. this.registerType('torch.nn.modules.transformer.Transformer', class {});
  3860. this.registerType('torch.nn.modules.transformer.TransformerDecoder', class {});
  3861. this.registerType('torch.nn.modules.transformer.TransformerDecoderLayer', class {});
  3862. this.registerType('torch.nn.modules.transformer.TransformerEncoder', class {});
  3863. this.registerType('torch.nn.modules.transformer.TransformerEncoderLayer', class {});
  3864. this.registerType('torch.nn.modules.upsampling.Upsample', class {});
  3865. this.registerType('torch.nn.modules.upsampling.UpsamplingBilinear2d', class {});
  3866. this.registerType('torch.nn.modules.upsampling.UpsamplingNearest2d', class {});
  3867. this.registerType('torch.nn.parallel.data_parallel.DataParallel', class {});
  3868. this.registerType('torch.nn.parallel.distributed._DDPUnevenInputsConfig', class {});
  3869. this.registerType('torch.nn.parallel.distributed.DistributedDataParallel', class {});
  3870. this.registerType('torch.nn.qat.modules.conv.Conv2d', class {});
  3871. this.registerType('torch.nn.qat.modules.linear.Linear', class {});
  3872. this.registerType('torch.nn.quantized.modules.activation.ReLU', class {});
  3873. this.registerType('torch.nn.quantized.modules.activation.LeakyReLU', class {});
  3874. this.registerType('torch.nn.quantized.dynamic.modules.linear.Linear', class {});
  3875. this.registerType('torch.nn.quantized.dynamic.modules.rnn.GRU', class {});
  3876. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTM', class {});
  3877. this.registerType('torch.nn.quantized.dynamic.modules.rnn.LSTMCell', class {});
  3878. this.registerType('torch.nn.quantized.dynamic.modules.rnn.PackedParameter', class {});
  3879. this.registerType('torch.nn.quantized.modules.activation.ReLU6', class {});
  3880. this.registerType('torch.nn.quantized.modules.batchnorm.BatchNorm2d', class {});
  3881. this.registerType('torch.nn.quantized.modules.conv.Conv1d', class {});
  3882. this.registerType('torch.nn.quantized.modules.conv.Conv2d', class {});
  3883. this.registerType('torch.nn.quantized.modules.conv.ConvTranspose2d', class {});
  3884. this.registerType('torch.nn.quantized.modules.DeQuantize', class {});
  3885. this.registerType('torch.nn.quantized.modules.dropout.Dropout', class {});
  3886. this.registerType('torch.nn.quantized.modules.embedding_ops.Embedding', class {});
  3887. this.registerType('torch.nn.quantized.modules.embedding_ops.EmbeddingPackedParams', class {});
  3888. this.registerType('torch.nn.quantized.modules.functional_modules.FloatFunctional', class {});
  3889. this.registerType('torch.nn.quantized.modules.functional_modules.QFunctional', class {});
  3890. this.registerType('torch.nn.quantized.modules.linear.Linear', class {});
  3891. this.registerType('torch.nn.quantized.modules.linear.LinearPackedParams', class {});
  3892. this.registerType('torch.nn.quantized.modules.normalization.InstanceNorm2d', class {});
  3893. this.registerType('torch.nn.quantized.modules.normalization.LayerNorm', class {});
  3894. this.registerType('torch.nn.quantized.modules.Quantize', class {});
  3895. this.registerType('torch.nn.utils.prune.L1Unstructured', class {});
  3896. this.registerType('torch.nn.utils.spectral_norm.SpectralNorm', class {});
  3897. this.registerType('torch.nn.utils.spectral_norm.SpectralNormStateDictHook', class {});
  3898. this.registerType('torch.nn.utils.spectral_norm.SpectralNormLoadStateDictPreHook', class {});
  3899. this.registerType('torch.nn.utils.weight_norm.WeightNorm', class {});
  3900. this.registerType('torch.torch_version.TorchVersion', class extends String {});
  3901. this.registerType('torch.optim.adam.Adam', class {});
  3902. this.register('torch.optim').Adam = this._registry.get('torch.optim.adam').Adam;
  3903. this.registerType('torch.optim.adamw.AdamW', class {});
  3904. this.registerType('torch.optim.adagrad.Adagrad', class {});
  3905. this.registerType('torch.optim.adadelta.Adadelta', class {});
  3906. this.registerType('torch.optim.lr_scheduler.CosineAnnealingLR', class {});
  3907. this.registerType('torch.optim.lr_scheduler.CyclicLR', class {});
  3908. this.registerType('torch.optim.lr_scheduler.ExponentialLR', class {});
  3909. this.registerType('torch.optim.lr_scheduler.LambdaLR', class {});
  3910. this.registerType('torch.optim.lr_scheduler.MultiStepLR', class {});
  3911. this.registerType('torch.optim.lr_scheduler.OneCycleLR', class {});
  3912. this.registerType('torch.optim.lr_scheduler.ReduceLROnPlateau', class {});
  3913. this.registerType('torch.optim.lr_scheduler.StepLR', class {});
  3914. this.registerType('torch.optim.optimizer._RequiredParameter', class {});
  3915. this.registerType('torch.optim.rmsprop.RMSprop', class {});
  3916. this.registerType('torch.optim.sgd.SGD', class {});
  3917. this.registerType('torch.optim.sparse_adam.SparseAdam', class {});
  3918. this.registerType('torch.quantization.fake_quantize.FakeQuantize', class {});
  3919. this.registerType('torch.quantization.observer._PartialWrapper', class {});
  3920. this.registerType('torch.quantization.observer.MinMaxObserver', class {});
  3921. this.registerType('torch.quantization.observer.MovingAverageMinMaxObserver', class {});
  3922. this.registerType('torch.quantization.observer.MovingAveragePerChannelMinMaxObserver', class {});
  3923. this.registerType('torch.quantization.qconfig.QConfig', class {});
  3924. this.registerType('torch.quantization.stubs.DeQuantStub', class {});
  3925. this.registerType('torch.quantization.stubs.QuantStub', class {});
  3926. this.registerType('torch.utils.data.dataloader._MultiProcessingDataLoaderIter', class {});
  3927. this.registerType('torch.utils.data.dataloader.DataLoader', class {});
  3928. this.registerType('torch.utils.data.dataset.Subset', class {});
  3929. this.registerType('torch.utils.data.dataset.ConcatDataset', class {});
  3930. this.registerType('torch.utils.data.dataset.TensorDataset', class {});
  3931. this.registerType('torch.utils.data.sampler.BatchSampler', class {});
  3932. this.registerType('torch.utils.data.sampler.RandomSampler', class {});
  3933. this.registerType('torch.utils.data.sampler.SequentialSampler', class {});
  3934. this.registerType('torchvision.datasets.folder.ImageFolder', class {});
  3935. this.registerType('torchvision.datasets.mnist.MNIST', class {});
  3936. this.registerType('torchvision.datasets.vision.StandardTransform', class {});
  3937. this.registerType('torchvision.models.alexnet.AlexNet', class {});
  3938. this.registerType('torchvision.models.densenet.DenseNet', class {});
  3939. this.registerType('torchvision.models.densenet._DenseBlock', class {});
  3940. this.registerType('torchvision.models.densenet._DenseLayer', class {});
  3941. this.registerType('torchvision.models.densenet._Transition', class {});
  3942. this.registerType('torchvision.models.detection._utils.BalancedPositiveNegativeSampler', class {});
  3943. this.registerType('torchvision.models.detection._utils.BoxCoder', class {});
  3944. this.registerType('torchvision.models.detection._utils.Matcher', class {});
  3945. this.registerType('torchvision.models.detection._utils.SSDMatcher', class {});
  3946. this.registerType('torchvision.models.detection.anchor_utils.AnchorGenerator', class {});
  3947. this.registerType('torchvision.models.detection.anchor_utils.DefaultBoxGenerator', class {});
  3948. this.registerType('torchvision.models.detection.backbone_utils.BackboneWithFPN', class {});
  3949. this.registerType('torchvision.models.detection.faster_rcnn.FasterRCNN', class {});
  3950. this.registerType('torchvision.models.detection.faster_rcnn.FastRCNNPredictor', class {});
  3951. this.registerType('torchvision.models.detection.faster_rcnn.TwoMLPHead', class {});
  3952. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNN', class {});
  3953. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNHeads', class {});
  3954. this.registerType('torchvision.models.detection.keypoint_rcnn.KeypointRCNNPredictor', class {});
  3955. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNN', class {});
  3956. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNHeads', class {});
  3957. this.registerType('torchvision.models.detection.mask_rcnn.MaskRCNNPredictor', class {});
  3958. this.registerType('torchvision.models.detection.retinanet.RetinaNet', class {});
  3959. this.registerType('torchvision.models.detection.retinanet.RetinaNetClassificationHead', class {});
  3960. this.registerType('torchvision.models.detection.retinanet.RetinaNetHead', class {});
  3961. this.registerType('torchvision.models.detection.retinanet.RetinaNetRegressionHead', class {});
  3962. this.registerType('torchvision.models.detection.roi_heads.RoIHeads', class {});
  3963. this.registerType('torchvision.models.detection.rpn.AnchorGenerator', class {});
  3964. this.registerType('torchvision.models.detection.rpn.RegionProposalNetwork', class {});
  3965. this.registerType('torchvision.models.detection.rpn.RPNHead', class {});
  3966. this.registerType('torchvision.models.detection.ssd.SSD', class {});
  3967. this.registerType('torchvision.models.detection.ssdlite.SSDLiteClassificationHead', class {});
  3968. this.registerType('torchvision.models.detection.ssdlite.SSDLiteFeatureExtractorMobileNet', class {});
  3969. this.registerType('torchvision.models.detection.ssdlite.SSDLiteHead', class {});
  3970. this.registerType('torchvision.models.detection.ssdlite.SSDLiteRegressionHead', class {});
  3971. this.registerType('torchvision.models.detection.transform.GeneralizedRCNNTransform', class {});
  3972. this.registerType('torchvision.models.efficientnet.EfficientNet', class {});
  3973. this.registerType('torchvision.models.efficientnet.MBConv', class {});
  3974. this.registerType('torchvision.models.googlenet.BasicConv2d', class {});
  3975. this.registerType('torchvision.models.googlenet.GoogLeNet', class {});
  3976. this.registerType('torchvision.models.googlenet.Inception', class {});
  3977. this.registerType('torchvision.models.googlenet.InceptionAux', class {});
  3978. this.registerType('torchvision.models.inception.BasicConv2d', class {});
  3979. this.registerType('torchvision.models.inception.Inception3', class {});
  3980. this.registerType('torchvision.models.inception.InceptionAux', class {});
  3981. this.registerType('torchvision.models.inception.InceptionA', class {});
  3982. this.registerType('torchvision.models.inception.InceptionB', class {});
  3983. this.registerType('torchvision.models.inception.InceptionC', class {});
  3984. this.registerType('torchvision.models.inception.InceptionD', class {});
  3985. this.registerType('torchvision.models.inception.InceptionE', class {});
  3986. this.registerType('torchvision.models.mnasnet._InvertedResidual', class {});
  3987. this.registerType('torchvision.models.mnasnet.MNASNet', class {});
  3988. this.registerType('torchvision.models.mobilenet.ConvBNReLU', class {});
  3989. this.registerType('torchvision.models.mobilenet.MobileNetV2', class {});
  3990. this.registerType('torchvision.models.mobilenet.InvertedResidual', class {});
  3991. this.registerType('torchvision.models.mobilenetv2.ConvBNActivation', class {});
  3992. this.registerType('torchvision.models.mobilenetv2.InvertedResidual', class {});
  3993. this.registerType('torchvision.models.mobilenetv2.MobileNetV2', class {});
  3994. this.registerType('torchvision.models.mobilenetv3.InvertedResidual', class {});
  3995. this.registerType('torchvision.models.mobilenetv3.MobileNetV3', class {});
  3996. this.registerType('torchvision.models.mobilenetv3.SqueezeExcitation', class {});
  3997. this.registerType('torchvision.models.resnet.Bottleneck', class {});
  3998. this.registerType('torchvision.models.resnet.BasicBlock', class {});
  3999. this.registerType('torchvision.models.quantization.mobilenet.QuantizableInvertedResidual', class {});
  4000. this.registerType('torchvision.models.quantization.mobilenet.QuantizableMobileNetV2', class {});
  4001. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableInvertedResidual', class {});
  4002. this.registerType('torchvision.models.quantization.mobilenetv2.QuantizableMobileNetV2', class {});
  4003. this.registerType('torchvision.models.quantization.resnet.QuantizableBasicBlock', class {});
  4004. this.registerType('torchvision.models.quantization.resnet.QuantizableBottleneck', class {});
  4005. this.registerType('torchvision.models.quantization.resnet.QuantizableResNet', class {});
  4006. this.registerType('torchvision.models.segmentation.deeplabv3.ASPP', class {});
  4007. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPConv', class {});
  4008. this.registerType('torchvision.models.segmentation.deeplabv3.ASPPPooling', class {});
  4009. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabHead', class {});
  4010. this.registerType('torchvision.models.segmentation.deeplabv3.DeepLabV3', class {});
  4011. this.registerType('torchvision.models.segmentation.fcn.FCN', class {});
  4012. this.registerType('torchvision.models.segmentation.fcn.FCNHead', class {});
  4013. this.registerType('torchvision.models.shufflenetv2.ShuffleNetV2', class {});
  4014. this.registerType('torchvision.models.shufflenetv2.InvertedResidual', class {});
  4015. this.registerType('torchvision.models.squeezenet.Fire', class {});
  4016. this.registerType('torchvision.models.squeezenet.SqueezeNet', class {});
  4017. this.registerType('torchvision.models.resnet.ResNet', class {});
  4018. this.registerType('torchvision.models.vgg.VGG', class {});
  4019. this.registerType('torchvision.models.video.resnet.BasicBlock', class {});
  4020. this.registerType('torchvision.models.video.resnet.BasicStem', class {});
  4021. this.registerType('torchvision.models.video.resnet.Conv2Plus1D', class {});
  4022. this.registerType('torchvision.models.video.resnet.Conv3DNoTemporal', class {});
  4023. this.registerType('torchvision.models.video.resnet.Conv3DSimple', class {});
  4024. this.registerType('torchvision.models.video.resnet.R2Plus1dStem', class {});
  4025. this.registerType('torchvision.models.video.resnet.VideoResNet', class {});
  4026. this.registerType('torchvision.models._utils.IntermediateLayerGetter', class {});
  4027. this.registerType('torchvision.ops.deform_conv.DeformConv2d', class {});
  4028. this.registerType('torchvision.ops.feature_pyramid_network.FeaturePyramidNetwork', class {});
  4029. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelMaxPool', class {});
  4030. this.registerType('torchvision.ops.feature_pyramid_network.LastLevelP6P7', class {});
  4031. this.registerType('torchvision.ops.misc.Conv2dNormActivation', class {});
  4032. this.registerType('torchvision.ops.misc.ConvNormActivation', class {});
  4033. this.registerType('torchvision.ops.misc.ConvTranspose2d', class {});
  4034. this.registerType('torchvision.ops.misc.FrozenBatchNorm2d', class {});
  4035. this.registerType('torchvision.ops.misc.SqueezeExcitation', class {});
  4036. this.registerType('torchvision.ops.poolers.LevelMapper', class {});
  4037. this.registerType('torchvision.ops.poolers.MultiScaleRoIAlign', class {});
  4038. this.registerType('torchvision.ops.stochastic_depth.StochasticDepth', class {});
  4039. this.registerType('torchvision.transforms.functional.InterpolationMode', class {});
  4040. this.registerType('torchvision.transforms.transforms.Compose', class {});
  4041. this.registerType('torchvision.transforms.transforms.CenterCrop', class {});
  4042. this.registerType('torchvision.transforms.transforms.Grayscale', class {});
  4043. this.registerType('torchvision.transforms.transforms.Normalize', class {});
  4044. this.registerType('torchvision.transforms.transforms.RandomAffine', class {});
  4045. this.registerType('torchvision.transforms.transforms.RandomCrop', class {});
  4046. this.registerType('torchvision.transforms.transforms.RandomHorizontalFlip', class {});
  4047. this.registerType('torchvision.transforms.transforms.Resize', class {});
  4048. this.registerType('torchvision.transforms.transforms.Scale', class {});
  4049. this.registerType('torchvision.transforms.transforms.ToPILImage', class {});
  4050. this.registerType('torchvision.transforms.transforms.ToTensor', class {});
  4051. this.registerFunction('torchvision.models.resnet.resnet34', function() {});
  4052. this.registerFunction('builtins.annotate', function(type, value) {
  4053. if (type === self._builtins.int) {
  4054. return Number.isInteger(value) ? value : NaN;
  4055. }
  4056. if (type === self._builtins.float) {
  4057. return typeof value === 'number' ? value : NaN;
  4058. }
  4059. if (type === self._builtins.number) {
  4060. // if (pytorch.Utility.isTensor(value)) {
  4061. // value.resize_([]);
  4062. // }
  4063. }
  4064. return value;
  4065. });
  4066. this.registerFunction('builtins.unchecked_cast', function(type, value) {
  4067. return value;
  4068. });
  4069. this.registerFunction('builtins.uninitialized', function(/* type */) {
  4070. return undefined;
  4071. });
  4072. this.registerFunction('ops.prim.data', function(tensor) {
  4073. return tensor;
  4074. });
  4075. this.registerFunction('ops.prim.device', function(tensor) {
  4076. return tensor.device;
  4077. });
  4078. this.registerFunction('ops.prim.dtype', function(tensor) {
  4079. return tensor.dtype.scalar_type();
  4080. });
  4081. this.registerFunction('ops.prim.is_quantized', function(tensor) {
  4082. return tensor && tensor.__quantized__ === true;
  4083. });
  4084. this.registerFunction('ops.prim.is_cuda', function(/* tensor */) {
  4085. return false;
  4086. });
  4087. this.registerFunction('ops.prim.unchecked_unwrap_optional', function(value) {
  4088. return value;
  4089. });
  4090. this.registerFunction('ops.prim.NumToTensor', function(value) {
  4091. const tensor = self.invoke('torch.Tensor', []);
  4092. tensor.value = value; // TODO
  4093. return tensor;
  4094. });
  4095. this.registerFunction('ops.prim.min', function(value) {
  4096. if (Array.isArray(value)) {
  4097. return Math.min.apply(null, value);
  4098. }
  4099. return Math.min.apply(null, arguments);
  4100. });
  4101. this.registerFunction('ops.prim.max', function(value) {
  4102. if (Array.isArray(value)) {
  4103. return Math.max.apply(null, value);
  4104. }
  4105. return Math.max.apply(null, arguments);
  4106. });
  4107. this.registerFunction('ops.prim.shape', function(tensor) {
  4108. return tensor && tensor.size ? tensor.size() : undefined;
  4109. });
  4110. this.registerFunction('ops.quantized.conv_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4111. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4112. params.weight = weight;
  4113. params.bias = bias;
  4114. params.stride = stride;
  4115. params.padding =padding;
  4116. params.dilation = dilation;
  4117. params.groups = groups;
  4118. return params;
  4119. });
  4120. this.registerFunction('ops.quantized.conv1d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4121. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4122. params.weight = weight;
  4123. params.bias = bias;
  4124. params.stride = stride;
  4125. params.padding =padding;
  4126. params.dilation = dilation;
  4127. params.groups = groups;
  4128. return params;
  4129. });
  4130. this.registerFunction('ops.quantized.conv2d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4131. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4132. params.weight = weight;
  4133. params.bias = bias;
  4134. params.stride = stride;
  4135. params.padding =padding;
  4136. params.dilation = dilation;
  4137. params.groups = groups;
  4138. return params;
  4139. });
  4140. this.registerFunction('ops.quantized.conv3d_prepack', function(weight, bias, stride, padding, dilation, groups) {
  4141. const params = self.invoke('__torch__.torch.classes.quantized.Conv3dPackedParamsBase', []);
  4142. params.weight = weight;
  4143. params.bias = bias;
  4144. params.stride = stride;
  4145. params.padding =padding;
  4146. params.dilation = dilation;
  4147. params.groups = groups;
  4148. return params;
  4149. });
  4150. this.registerFunction('ops.quantized.conv_transpose2d_prepack', function(weight, bias, stride, padding, output_padding, dilation, groups) {
  4151. const params = self.invoke('__torch__.torch.classes.quantized.Conv2dPackedParamsBase', []);
  4152. params.weight = weight;
  4153. params.bias = bias;
  4154. params.stride = stride;
  4155. params.padding =padding;
  4156. params.output_padding = output_padding;
  4157. params.dilation = dilation;
  4158. params.groups = groups;
  4159. return params;
  4160. });
  4161. this.registerFunction('ops.quantized.linear_prepack', function(weight, bias) {
  4162. const params = self.invoke('__torch__.torch.classes.quantized.LinearPackedParamsBase', []);
  4163. params.weight = weight;
  4164. params.bias = bias;
  4165. return params;
  4166. });
  4167. this.registerFunction('ops.prim.RaiseException', function(message) {
  4168. throw new python.Error(message);
  4169. });
  4170. this.registerFunction('builtins.range', function(start, stop, step) {
  4171. if (stop === undefined && step === undefined) {
  4172. if (Number.isInteger(start)) {
  4173. return Array(start).keys();
  4174. }
  4175. if (isNaN(start)) {
  4176. return [];
  4177. }
  4178. }
  4179. throw new python.Error('Unsupported range(' + JSON.stringify(start) + ', ' + JSON.stringify(stop) + ', ' + JSON.stringify(step) + ')');
  4180. });
  4181. this.registerFunction('torch._utils._rebuild_sparse_tensor', function(layout, data) {
  4182. if (layout === torch.sparse_coo) {
  4183. return self.invoke('torch._sparse_coo_tensor_unsafe', data);
  4184. }
  4185. throw new python.Error("Unsupported sparse tensor layout '" + (layout ? layout.__str__() : '') + "'.");
  4186. });
  4187. this.registerFunction('torch.from_numpy', function(obj) {
  4188. const dtypes = new Map([
  4189. [ '<f2', torch.float16 ],
  4190. [ '<f4', torch.float32 ],
  4191. [ '<f8', torch.float64 ],
  4192. [ '<i2', torch.int16 ],
  4193. [ '<i4', torch.int32 ],
  4194. [ '<i8', torch.int64 ],
  4195. ]);
  4196. if (!dtypes.has(obj.dtype.str)) {
  4197. throw new python.Error("Unsupported numpy.ndarray type '" + obj.dtype.str + "'.");
  4198. }
  4199. const dtype = dtypes.get(obj.dtype.str);
  4200. const storage = execution.invoke('torch.storage._TypedStorage', [ obj.size, dtype ]);
  4201. storage._set_cdata(obj.data);
  4202. const tensor = execution.invoke('torch.Tensor', []);
  4203. tensor.__setstate__([ storage, 0, obj.shape, null ]);
  4204. return tensor;
  4205. });
  4206. this.registerFunction('torch._utils._rebuild_device_tensor_from_numpy', function(data, dtype, device, requires_grad) {
  4207. const tensor = execution.invoke('torch.from_numpy', [ data ]);
  4208. // tensor = tensor.to(dtype, device)
  4209. tensor.requires_grad = requires_grad;
  4210. return tensor;
  4211. });
  4212. this.registerFunction('torch._sparse_coo_tensor_unsafe', function(indices, values, size) {
  4213. const tensor = self.invoke('torch.Tensor', []);
  4214. tensor._layout = torch.sparse_coo;
  4215. tensor._indices = indices;
  4216. tensor._values = values;
  4217. tensor._shape = size;
  4218. return tensor;
  4219. });
  4220. this.registerFunction('torch._utils._rebuild_tensor', function (storage, storage_offset, size, stride) {
  4221. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  4222. const tensor = self.invoke(name, []);
  4223. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  4224. return tensor;
  4225. });
  4226. this.registerFunction('torch._utils._rebuild_tensor_v2', function (storage, storage_offset, size, stride, requires_grad, backward_hooks) {
  4227. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  4228. const tensor = self.invoke(name, []);
  4229. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  4230. tensor.requires_grad = requires_grad;
  4231. tensor.backward_hooks = backward_hooks;
  4232. return tensor;
  4233. });
  4234. this.registerFunction('torch._utils._rebuild_parameter', function(data, requires_grad, backward_hooks) {
  4235. const obj = self.invoke('torch.nn.parameter.Parameter', [ data, requires_grad ]);
  4236. obj.backward_hooks = backward_hooks;
  4237. return obj;
  4238. });
  4239. this.registerFunction('torch._utils._rebuild_qtensor', function(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks) {
  4240. const name = storage.__class__.__module__ + '.' + storage.__class__.__name__.replace('Storage', 'Tensor');
  4241. const tensor = self.invoke(name, []);
  4242. tensor.__setstate__([ storage, storage_offset, size, stride ]);
  4243. tensor.quantizer_params = quantizer_params;
  4244. tensor.requires_grad = requires_grad;
  4245. tensor.backward_hooks = backward_hooks;
  4246. return tensor;
  4247. });
  4248. this.registerFunction('torch._set_item', function(dict, key, value) {
  4249. dict[key] = value;
  4250. });
  4251. this.registerFunction('torch.__and__', function(left, right) {
  4252. return left && right;
  4253. });
  4254. this.registerFunction('torch.__contains__', function(dict, key) {
  4255. return dict[key] !== undefined;
  4256. });
  4257. this.registerFunction('torch.__derive_index', function(index, start, step) {
  4258. return start + index * step;
  4259. });
  4260. this.registerFunction('torch.__is__', function(left, right) {
  4261. if (left === null && right === null) {
  4262. return true;
  4263. }
  4264. if ((left !== null && right === null) || (left === null && right !== null)) {
  4265. return false;
  4266. }
  4267. throw new python.Error("Unsupported 'torch.__is__' expression type.");
  4268. });
  4269. this.registerFunction('torch.__isnot__', function(left, right) {
  4270. if (left === null && right === null) {
  4271. return false;
  4272. }
  4273. if ((left !== null && right === null) || (left === null && right !== null)) {
  4274. return true;
  4275. }
  4276. throw new python.Error("Unsupported 'torch.__isnot__' expression type.");
  4277. });
  4278. this.registerFunction('torch.__not__', function(value) {
  4279. if (typeof value === 'boolean') {
  4280. return !value;
  4281. }
  4282. throw new python.Error("Unsupported 'torch.__not__' expression type.");
  4283. });
  4284. this.registerFunction('torch.__range_length', function(lo, hi, step) {
  4285. if (step === 0) {
  4286. throw new python.Error('range() arg 3 must not be zero');
  4287. }
  4288. if (step > 0 && lo < hi) {
  4289. return 1 + (hi - 1 - lo) / step;
  4290. }
  4291. else if (step < 0 && lo > hi) {
  4292. return 1 + (lo - 1 - hi) / (0 - step);
  4293. }
  4294. return 0;
  4295. });
  4296. this.registerFunction('torch._unwrap_optional', function(value) {
  4297. return value; // TODO
  4298. });
  4299. this.registerFunction('torch.add', function(left, right) {
  4300. if (typeof left === 'number' && typeof right === 'number') {
  4301. return left * right;
  4302. }
  4303. if (Array.isArray(left) && Array.isArray(right)) {
  4304. return left.concat(right);
  4305. }
  4306. if (typeof left === 'string' && typeof right === 'string') {
  4307. return left + right;
  4308. }
  4309. throw new python.Error('Unsupported torch.add expression type.');
  4310. });
  4311. this.registerFunction('torch.append', function(list, value) {
  4312. list.push(value);
  4313. return value;
  4314. });
  4315. this.registerFunction('torch.extend', function(list, value) {
  4316. list.push(...value);
  4317. });
  4318. this.registerFunction('torch.insert', function(list, index, value) {
  4319. list.splice(index, 0, value);
  4320. return value;
  4321. });
  4322. this.registerFunction('torch.clear', function(value) {
  4323. if (Object(value) === value) {
  4324. for (const key of Object.keys(value)) {
  4325. delete value[key];
  4326. }
  4327. }
  4328. });
  4329. this.registerFunction('torch.replace', function(value) {
  4330. return value;
  4331. });
  4332. this.registerFunction('torch.dict', function(args) {
  4333. const obj = {};
  4334. if (args) {
  4335. if (Array.isArray(args)) {
  4336. for (const pair of args) {
  4337. const key = pair[0];
  4338. const value = pair[1];
  4339. obj[key] = value;
  4340. }
  4341. }
  4342. else {
  4343. throw new python.Error("'torch.dict' arguments not supported.");
  4344. }
  4345. }
  4346. return obj;
  4347. });
  4348. this.registerFunction('torch.dim', function(tensor) {
  4349. if (tensor && tensor.size) {
  4350. const size = tensor.size();
  4351. if (size) {
  4352. return size.length;
  4353. }
  4354. }
  4355. return NaN; // TODO
  4356. });
  4357. this.registerFunction('torch.numel', function(tensor) {
  4358. if (tensor && tensor.size) {
  4359. const size = tensor.size();
  4360. if (size) {
  4361. return size.reduce((a, b) => a * b, 1);
  4362. }
  4363. }
  4364. return NaN;
  4365. });
  4366. this.registerFunction('torch.eq', function(left, right) {
  4367. if (typeof left === 'string' && typeof right === 'string') {
  4368. return left === right;
  4369. }
  4370. if (typeof left === 'number' && typeof right === 'number') {
  4371. if (isNaN(left) && isNaN(right)) {
  4372. return true;
  4373. }
  4374. return left === right;
  4375. }
  4376. if (left === undefined || right === undefined) {
  4377. return true;
  4378. }
  4379. if (Array.isArray(left) && Array.isArray(right)) {
  4380. return left.length === right.length && left.every((item, index) => item === right[index]);
  4381. }
  4382. throw new python.Error("Unsupported 'torch.eq' expression type.");
  4383. });
  4384. this.registerFunction('torch.floor', function(value) {
  4385. return Math.floor(value);
  4386. });
  4387. this.registerFunction('torch.ceil', function(value) {
  4388. return Math.ceil(value);
  4389. });
  4390. this.registerFunction('torch.floordiv', function(left, right) {
  4391. return Math.floor(left / right);
  4392. });
  4393. this.registerFunction('torch.format', function() {
  4394. const args = Array.from(arguments);
  4395. const list = args.shift().split(/({}D?)/);
  4396. return list.map((text) => {
  4397. if (text === '{}' || text === '{}D') {
  4398. const arg = args.shift();
  4399. return Array.isArray(arg) ? '[' + arg.map((item) => item.toString()).join(', ') + ']' : arg ? arg.toString() : '?';
  4400. }
  4401. return text;
  4402. }).join('');
  4403. });
  4404. this.registerFunction('torch.gt', function(left, right) {
  4405. if (typeof left === 'number' && typeof right === 'number') {
  4406. if (!isNaN(left) && !isNaN(right)) {
  4407. return left > right;
  4408. }
  4409. }
  4410. if (isNaN(left) && !isNaN(right)) {
  4411. return true;
  4412. }
  4413. throw new python.Error("Unsupported 'torch.gt' expression type.");
  4414. });
  4415. this.registerFunction('torch.ge', function(left, right) {
  4416. if (typeof left === 'number' && typeof right === 'number') {
  4417. if (!isNaN(left) && !isNaN(right)) {
  4418. return left > right;
  4419. }
  4420. }
  4421. if (isNaN(left) && !isNaN(right)) {
  4422. return true;
  4423. }
  4424. throw new python.Error("Unsupported 'torch.ge' expression type.");
  4425. });
  4426. this.registerFunction('torch.is_floating_point', function(tensor) {
  4427. const type = tensor.dtype.scalar_type();
  4428. return (type === 5 || type === 6 || type === 7);
  4429. });
  4430. this.registerFunction('torch.is_grad_enabled', function() {
  4431. return false;
  4432. });
  4433. this.registerFunction('torch.set_grad_enabled', function(/* value */) {
  4434. });
  4435. this.registerFunction('torch.serialization._get_layout', function(name) {
  4436. const value = name.startsWith('torch.') ? torch[name.split('.')[1]] : null;
  4437. return value instanceof torch.layout ? value : null;
  4438. });
  4439. this.registerFunction('torch.storage._load_from_bytes', function(b) {
  4440. return execution.invoke('torch.load', [ b ]);
  4441. });
  4442. this.registerFunction('torch.jit._pickle.build_boollist', function(data) {
  4443. return data;
  4444. });
  4445. this.registerFunction('torch.jit._pickle.build_doublelist', function(data) {
  4446. return data;
  4447. });
  4448. this.registerFunction('torch.jit._pickle.build_intlist', function(data) {
  4449. return data;
  4450. });
  4451. this.registerFunction('torch.jit._pickle.build_tensorlist', function(data) {
  4452. return data;
  4453. });
  4454. this.registerFunction('torch.jit._pickle.build_tensor_from_id', function(data) {
  4455. return self.builtins.CONSTANTS['c' + data.toString()];
  4456. });
  4457. this.registerFunction('torch.jit._pickle.restore_type_tag', function(value /*, type_str */) {
  4458. return value;
  4459. });
  4460. this.registerFunction('torch.keys', function(dict) {
  4461. return Object.keys(dict);
  4462. });
  4463. this.registerFunction('torch.len', function(value) {
  4464. if (Array.isArray(value)) {
  4465. return value.length;
  4466. }
  4467. if (value && value.shape && value.__len__) {
  4468. return value.__len__();
  4469. }
  4470. return NaN;
  4471. });
  4472. this.registerFunction('torch.le', function(left, right) {
  4473. if (typeof left === 'number' && typeof right === 'number') {
  4474. if (isNaN(left) || isNaN(right)) {
  4475. return false;
  4476. }
  4477. return left <= right;
  4478. }
  4479. if (left === undefined || right === undefined) {
  4480. return true;
  4481. }
  4482. throw new python.Error("Unsupported 'torch.le' expression type.");
  4483. });
  4484. this.registerFunction('torch.list', function(args) {
  4485. return args;
  4486. });
  4487. this.registerFunction('torch.list_with_default', function(size /*, defaults */) {
  4488. return size;
  4489. });
  4490. this.registerFunction('torch.load', function(f) {
  4491. const legacy_load = (entries) => {
  4492. const deserialized_objects = {};
  4493. if (entries.has('storages')) {
  4494. const data = entries.get('storages');
  4495. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4496. const num_storages = unpickler.load();
  4497. for (let i = 0; i < num_storages; i++) {
  4498. const args = unpickler.load();
  4499. const key = args[0];
  4500. const storage_type = args[2];
  4501. const obj = storage_type._new_with_file(unpickler);
  4502. deserialized_objects[key] = obj;
  4503. }
  4504. /*
  4505. let storage_views = unpickler.load();
  4506. for target_cdata, root_cdata, offset, size in storage_views:
  4507. root = deserialized_objects[root_cdata]
  4508. deserialized_objects[target_cdata] = root[offset:offset + size]
  4509. */
  4510. }
  4511. if (entries.has('tensors')) {
  4512. const data = entries.get('tensors');
  4513. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4514. const num_tensors = unpickler.load();
  4515. const int32 = (unpickler) => {
  4516. const buffer = unpickler.read(4);
  4517. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
  4518. };
  4519. const int64 = (unpickler) => {
  4520. const buffer = unpickler.read(8);
  4521. if (buffer[6] !== 0 && buffer[7] !== 0) {
  4522. throw new python.Error('Unsigned 64-bit value exceeds 32-bit range.');
  4523. }
  4524. return buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24) + (buffer[4] * 4294967296) + (buffer[5] * 1099511627776);
  4525. };
  4526. for (let i = 0; i < num_tensors; i++) {
  4527. const args = unpickler.load();
  4528. const key = args[0];
  4529. const storage_id = args[1];
  4530. const storage = deserialized_objects[storage_id];
  4531. const ndim = int32(unpickler);
  4532. unpickler.read(4);
  4533. const shape = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4534. const stride = Array.from(new Array(ndim)).map(() => int64(unpickler));
  4535. const storage_offset = int64(unpickler);
  4536. const tensor = execution.invoke('torch._utils._rebuild_tensor', [ storage, storage_offset, shape, stride ]);
  4537. deserialized_objects[key] = tensor;
  4538. }
  4539. }
  4540. const data = entries.get('pickle');
  4541. const unpickler = execution.invoke('pickle.Unpickler', [ data ]);
  4542. unpickler.persistent_load = (saved_id) => deserialized_objects[saved_id];
  4543. return unpickler.load();
  4544. };
  4545. if (f instanceof Map) {
  4546. if (f.has('pickle')) {
  4547. return legacy_load(f);
  4548. }
  4549. throw new python.Error("Unsupported 'torch.load' input '" + JSON.stringify(Array.from(f.keys())) + "'.");
  4550. }
  4551. const unpickler = execution.invoke('pickle.Unpickler', [ f ]);
  4552. unpickler.load(); // magic_number
  4553. const protocol_version = unpickler.load();
  4554. if (protocol_version != 1001) {
  4555. throw new python.Error("Unsupported protocol version '" + protocol_version + "'.");
  4556. }
  4557. const sys_info = unpickler.load();
  4558. if (sys_info.protocol_version != 1001) {
  4559. throw new python.Error("Unsupported protocol version '" + sys_info.protocol_version + "'.");
  4560. }
  4561. if (sys_info.little_endian === false) {
  4562. throw new python.Error("Unsupported big-endian storage data.");
  4563. }
  4564. const module_source_map = new Map();
  4565. const deserialized_objects = new Map();
  4566. unpickler.persistent_load = (saved_id) => {
  4567. const typename = saved_id.shift();
  4568. const data = saved_id;
  4569. switch (typename) {
  4570. case 'module': {
  4571. const module = data[0];
  4572. const source = data[2];
  4573. module_source_map.set(module, source);
  4574. return data[0];
  4575. }
  4576. case 'storage': {
  4577. const storage_type = data.shift();
  4578. const root_key = data.shift();
  4579. data.shift(); // location
  4580. const size = data.shift();
  4581. const view_metadata = data.shift();
  4582. if (!deserialized_objects.has(root_key)) {
  4583. const obj = new storage_type(size);
  4584. deserialized_objects.set(root_key, obj);
  4585. }
  4586. if (view_metadata) {
  4587. const view_key = view_metadata.shift();
  4588. view_metadata.shift(); // view_offset
  4589. view_metadata.shift(); // view_size
  4590. if (!deserialized_objects.has(view_key)) {
  4591. const view = null; // storage.slice(view_offset, view_offset + view_size);
  4592. deserialized_objects.set(view_key, view);
  4593. }
  4594. return deserialized_objects.get(view_key);
  4595. }
  4596. return deserialized_objects.get(root_key);
  4597. }
  4598. default: {
  4599. throw new python.Error("Unsupported persistent load type '" + typename + "'.");
  4600. }
  4601. }
  4602. };
  4603. const obj = unpickler.load();
  4604. const deserialized_storage_keys = unpickler.load();
  4605. for (const deserialized_storage_key of deserialized_storage_keys) {
  4606. const storage = deserialized_objects.get(deserialized_storage_key);
  4607. storage._set_from_file(unpickler);
  4608. }
  4609. if (!obj) {
  4610. throw new python.Error('File format is not PyTorch.');
  4611. }
  4612. if (obj === 'None') {
  4613. throw new python.Error("File contains 'None' root object.");
  4614. }
  4615. return obj;
  4616. });
  4617. this.registerFunction('torch.lt', function(left, right) {
  4618. if (typeof left === 'number' && typeof right === 'number') {
  4619. return left < right;
  4620. }
  4621. throw new python.Error("Unsupported 'torch.lt' expression type.");
  4622. });
  4623. this.registerFunction('torch.mul', function(left, right) {
  4624. if (typeof left === 'number' && typeof right === 'number') {
  4625. return left * right;
  4626. }
  4627. if (isNaN(left) || isNaN(right)) {
  4628. return NaN;
  4629. }
  4630. if (Array.isArray(left) && left.every((value) => typeof value === 'number') && typeof right === 'number') {
  4631. return left.map((value) => value * right);
  4632. }
  4633. throw new python.Error("Unsupported 'torch.mul' expression type.");
  4634. });
  4635. this.registerFunction('torch.div', function(left, right) {
  4636. if (typeof left === 'number' && typeof right === 'number') {
  4637. return left / right;
  4638. }
  4639. if (isNaN(left) || isNaN(right)) {
  4640. return NaN;
  4641. }
  4642. throw new python.Error("Unsupported 'torch.div' expression type.");
  4643. });
  4644. this.registerFunction('torch.round', function(value) {
  4645. if (typeof value === 'number') {
  4646. return Math.round(value);
  4647. }
  4648. if (isNaN(value)) {
  4649. return value;
  4650. }
  4651. throw new python.Error("Unsupported 'torch.round' expression type.");
  4652. });
  4653. this.registerFunction('torch.remainder', function(left, right) {
  4654. if (typeof left === 'number' && typeof right === 'number') {
  4655. return left % right;
  4656. }
  4657. if (isNaN(left) || isNaN(right)) {
  4658. return NaN;
  4659. }
  4660. throw new python.Error("Unsupported 'torch.remainder' expression type.");
  4661. });
  4662. this.registerFunction('torch.ne', function(left, right) {
  4663. if (typeof left === 'boolean' && typeof right === 'boolean') {
  4664. return left !== right;
  4665. }
  4666. if (typeof left === 'number' && typeof right === 'number') {
  4667. if (isNaN(left) || isNaN(right)) {
  4668. return false;
  4669. }
  4670. return left !== right;
  4671. }
  4672. if (Array.isArray(left) && Array.isArray(right) && left.length === right.length) {
  4673. return false;
  4674. }
  4675. if (typeof left === 'string' && typeof right === 'string') {
  4676. return left !== right;
  4677. }
  4678. if (left === undefined || right === undefined) {
  4679. return true;
  4680. }
  4681. throw new python.Error("Unsupported 'torch.ne' expression type.");
  4682. });
  4683. this.registerFunction('torch.neg', function(value) {
  4684. if (typeof value === 'number') {
  4685. return -value;
  4686. }
  4687. throw new python.Error("Unsupported 'torch.neg' expression type.");
  4688. });
  4689. this.registerFunction('torch.q_scale', function(/* tensor */) {
  4690. return -1; // TODO
  4691. });
  4692. this.registerFunction('torch.t', function(tensor) {
  4693. return tensor;
  4694. });
  4695. this.registerFunction('torch.size', function(tensor, dim) {
  4696. if (tensor && tensor.size) {
  4697. const size = tensor.size();
  4698. if (Array.isArray(size)) {
  4699. if (dim === undefined) {
  4700. return size;
  4701. }
  4702. if (Number.isInteger(dim)) {
  4703. if (dim >= 0 && dim < size.length) {
  4704. return size[dim];
  4705. }
  4706. if (dim < 0 && -dim < size.length) {
  4707. return size[size.length + dim];
  4708. }
  4709. }
  4710. throw new python.Error('Dimension out of range (expected to be in range of ' + JSON.stringify(size) + ', but got ' + JSON.stringify(dim) + ').');
  4711. }
  4712. }
  4713. if (Number.isInteger(dim)) {
  4714. return NaN;
  4715. }
  4716. return [];
  4717. });
  4718. this.registerFunction('torch.slice', function(l, start, end, step) {
  4719. if (!Array.isArray(l)) {
  4720. throw new python.Error('Slicing expected array');
  4721. }
  4722. step = step || 1;
  4723. if (step !== 1) {
  4724. throw new python.Error('Slicing only supports step=1');
  4725. }
  4726. start = Math.max(0, start >= 0 ? start : l.length + start);
  4727. end = Math.min(l.length, end || Number.MAX_SAFE_INTEGER);
  4728. return l.slice(start, end);
  4729. });
  4730. this.registerFunction('torch.sub', function(left, right) {
  4731. if (typeof left === 'number' && typeof right === 'number') {
  4732. return left - right;
  4733. }
  4734. throw new python.Error("Unsupported 'torch.sub' expression type.");
  4735. });
  4736. this.registerFunction('torch.nn.functional.gelu', function(/* input */) {
  4737. throw new python.Error("Function not implemented.");
  4738. });
  4739. this.registerFunction('torch.nn.functional.interpolate', function(/* input */) {
  4740. throw new python.Error("Function not implemented.");
  4741. });
  4742. this.registerFunction('torch.nn.functional.leaky_relu', function(/* input */) {
  4743. throw new python.Error("Function not implemented.");
  4744. });
  4745. this.registerFunction('torch.nn.functional.linear', function(/* input */) {
  4746. throw new python.Error("Function not implemented.");
  4747. });
  4748. this.registerFunction('torch.nn.functional.relu', function(/* input */) {
  4749. throw new python.Error("Function not implemented.");
  4750. });
  4751. this.registerFunction('torch.nn.functional.tanh', function(/* input */) {
  4752. throw new python.Error("Function not implemented.");
  4753. });
  4754. this.registerFunction('torch.values', function(dict) {
  4755. return Object.keys(dict).map((key) => dict[key]);
  4756. });
  4757. this.registerFunction('torch.warn', function() {
  4758. });
  4759. this.registerFunction('torch.fx.graph_module.reduce_graph_module', function(body /*, import_block */) {
  4760. // https://github.com/pytorch/pytorch/blob/master/torch/fx/graph_module.py
  4761. return body;
  4762. });
  4763. this.registerFunction('torch_utils.persistence._reconstruct_persistent_obj', function(meta) {
  4764. const name = '_imported_module_' + Math.floor(Math.random() * 10000).toString();
  4765. const module = execution.invoke('types.ModuleType', [ name ]);
  4766. execution.register('sys').modules.set(name, module);
  4767. const context = new python.Execution.Context(module, null);
  4768. execution.exec(meta.module_src, context);
  4769. const obj = execution.invoke(name + '.' + meta.class_name, []);
  4770. if (meta.state) {
  4771. if (obj.__setstate__) {
  4772. obj.__setstate__(meta.state);
  4773. }
  4774. else {
  4775. Object.assign(obj, meta.state);
  4776. }
  4777. }
  4778. return obj;
  4779. });
  4780. this.registerFunction('torch_utils.misc.assert_shape', function(/* tensor, ref_shape */) {});
  4781. this.registerFunction('torch_utils.ops.conv2d_resample.conv2d_resample', function(/* x, w, f, up, down, padding, groups, flip_weight, flip_filter */) {});
  4782. this.registerFunction('torch_utils.ops.upfirdn2d.setup_filter', function(/* x, f, up, down, padding, flip_filter, gain, impl */) {});
  4783. this.registerFunction('torch_utils.ops.bias_act', function(/* x, b, dim, act, alpha, gain, clamp, impl */) {});
  4784. this.registerFunction('torch_utils.ops.fma.fma', function(/* a, b, c */) {});
  4785. this.registerType('torch.device', class {
  4786. constructor(type, index) {
  4787. this.type = type;
  4788. if (index) {
  4789. this.index = index;
  4790. }
  4791. }
  4792. });
  4793. this.registerType('torch.dtype', class {
  4794. constructor(data) {
  4795. this._type = data.type;
  4796. this._data = data;
  4797. }
  4798. scalar_type() {
  4799. return this._type;
  4800. }
  4801. itemsize() {
  4802. return this._data.itemsize;
  4803. }
  4804. __reduce__() {
  4805. return this._data.name;
  4806. }
  4807. __str__() {
  4808. return 'torch.' + this._data.name;
  4809. }
  4810. toString() {
  4811. return this.__str__();
  4812. }
  4813. });
  4814. this.registerType('torch.layout', class {
  4815. constructor(name) {
  4816. this._name = name;
  4817. }
  4818. __str__() {
  4819. return this._name;
  4820. }
  4821. toString() {
  4822. return this.__str__();
  4823. }
  4824. });
  4825. this.registerType('torch.qscheme', class {
  4826. constructor(name) {
  4827. this._name = name;
  4828. }
  4829. __str__() {
  4830. return this._name;
  4831. }
  4832. toString() {
  4833. return this.__str__();
  4834. }
  4835. });
  4836. this.registerType('torch.utils.hooks.RemovableHandle', class {
  4837. __setstate__(state) {
  4838. this.hooks_dict_ref = state[0] || new Map();
  4839. this.id = state[1];
  4840. }
  4841. });
  4842. this.registerType('torch.storage._StorageBase', class {
  4843. constructor(size, dtype) {
  4844. this._size = size;
  4845. this._dtype = dtype;
  4846. this._device = null;
  4847. }
  4848. get device() {
  4849. return this._device;
  4850. }
  4851. get dtype() {
  4852. return this._dtype;
  4853. }
  4854. element_size() {
  4855. return this._dtype.element_size;
  4856. }
  4857. size() {
  4858. return this._size;
  4859. }
  4860. get data() {
  4861. return this._cdata;
  4862. }
  4863. _set_cdata(data) {
  4864. const length = this.size() * this.dtype.itemsize();
  4865. if (length !== data.length) {
  4866. throw new python.Error('Storage data size mismatch.');
  4867. }
  4868. this._cdata = data;
  4869. }
  4870. _set_from_file(unpickler) {
  4871. const buffer = unpickler.read(8);
  4872. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4873. if (size !== this.size()) {
  4874. throw new python.Error('Storage size mismatch.');
  4875. }
  4876. const itemsize = this.dtype.itemsize();
  4877. const data = unpickler.stream(itemsize * size);
  4878. this._set_cdata(data);
  4879. }
  4880. static _new_with_file(unpickler) {
  4881. const buffer = unpickler.read(8);
  4882. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4883. const storage = new this(size);
  4884. const itemsize = storage.dtype.itemsize();
  4885. const data = unpickler.stream(itemsize * size);
  4886. storage._set_cdata(data);
  4887. return storage;
  4888. }
  4889. });
  4890. this.registerType('torch.storage._UntypedStorage', class extends torch_storage._StorageBase {
  4891. constructor() {
  4892. super();
  4893. throw new python.Error('_UntypedStorage not implemented.');
  4894. }
  4895. });
  4896. this.registerType('torch.storage._TypedStorage', class {
  4897. constructor() {
  4898. if (arguments.length >= 2 && Number.isInteger(arguments[0]) && arguments[1] instanceof torch.dtype) {
  4899. this._size = arguments[0];
  4900. this._dtype = arguments[1];
  4901. if (arguments[3] instanceof torch.device) {
  4902. this._device = arguments[3];
  4903. }
  4904. }
  4905. else {
  4906. throw new python.Error("Unsupported _TypedStorage arguments '" + JSON.stringify(arguments) + "'.");
  4907. }
  4908. }
  4909. get device() {
  4910. return this._device;
  4911. }
  4912. get dtype() {
  4913. return this._dtype;
  4914. }
  4915. element_size() {
  4916. return this._dtype.element_size;
  4917. }
  4918. size() {
  4919. return this._size;
  4920. }
  4921. get data() {
  4922. return this._cdata;
  4923. }
  4924. _set_cdata(data) {
  4925. const length = this.size() * this.dtype.itemsize();
  4926. if (length !== data.length) {
  4927. throw new python.Error('Storage data size mismatch.');
  4928. }
  4929. this._cdata = data;
  4930. }
  4931. _set_from_file(unpickler) {
  4932. const buffer = unpickler.read(8);
  4933. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4934. if (size !== this.size()) {
  4935. throw new python.Error('Storage size mismatch.');
  4936. }
  4937. const itemsize = this.dtype.itemsize();
  4938. const data = unpickler.stream(itemsize * size);
  4939. this._set_cdata(data);
  4940. }
  4941. static _new_with_file(unpickler) {
  4942. const buffer = unpickler.read(8);
  4943. const size = buffer.reverse().reduce((a, b) => (a*256)+b, 0);
  4944. const storage = new this(size);
  4945. const itemsize = storage.dtype.itemsize();
  4946. const data = unpickler.stream(itemsize * size);
  4947. storage._set_cdata(data);
  4948. return storage;
  4949. }
  4950. });
  4951. this.registerType('torch.storage._LegacyStorage', class extends torch_storage._TypedStorage {
  4952. constructor() {
  4953. super();
  4954. throw new python.Error('_LegacyStorage not implemented.');
  4955. }
  4956. });
  4957. this.registerType('torch.BoolStorage', class extends torch_storage._StorageBase {
  4958. constructor(size) {
  4959. super(size, torch.bool);
  4960. }
  4961. });
  4962. this.registerType('torch.ByteStorage', class extends torch_storage._StorageBase {
  4963. constructor(size) {
  4964. super(size, torch.uint8);
  4965. }
  4966. });
  4967. this.registerType('torch.CharStorage', class extends torch_storage._StorageBase {
  4968. constructor(size) {
  4969. super(size, torch.int8);
  4970. }
  4971. });
  4972. this.registerType('torch.ShortStorage', class extends torch_storage._StorageBase {
  4973. constructor(size) {
  4974. super(size, torch.int16);
  4975. }
  4976. });
  4977. this.registerType('torch.IntStorage', class extends torch_storage._StorageBase {
  4978. constructor(size) {
  4979. super(size, torch.int32);
  4980. }
  4981. });
  4982. this.registerType('torch.LongStorage', class extends torch_storage._StorageBase {
  4983. constructor(size) {
  4984. super(size, torch.int64);
  4985. }
  4986. });
  4987. this.registerType('torch.HalfStorage', class extends torch_storage._StorageBase {
  4988. constructor(size) {
  4989. super(size, torch.float16);
  4990. }
  4991. });
  4992. this.registerType('torch.FloatStorage', class extends torch_storage._StorageBase {
  4993. constructor(size) {
  4994. super(size, torch.float32);
  4995. }
  4996. });
  4997. this.registerType('torch.DoubleStorage', class extends torch_storage._StorageBase {
  4998. constructor(size) {
  4999. super(size, torch.float64);
  5000. }
  5001. });
  5002. this.registerType('torch.ComplexHalfStorage', class extends torch_storage._StorageBase {
  5003. constructor(size) {
  5004. super(size, torch.complex32);
  5005. }
  5006. });
  5007. this.registerType('torch.ComplexFloatStorage', class extends torch_storage._StorageBase {
  5008. constructor(size) {
  5009. super(size, torch.complex64);
  5010. }
  5011. });
  5012. this.registerType('torch.ComplexDoubleStorage', class extends torch_storage._StorageBase {
  5013. constructor(size) {
  5014. super(size, torch.complex128);
  5015. }
  5016. });
  5017. this.registerType('torch.QInt8Storage', class extends torch_storage._StorageBase {
  5018. constructor(size) {
  5019. super(size, torch.qint8);
  5020. }
  5021. });
  5022. this.registerType('torch.QUInt8Storage', class extends torch_storage._StorageBase {
  5023. constructor(size) {
  5024. super(size, torch.quint8);
  5025. }
  5026. });
  5027. this.registerType('torch.QInt32Storage', class extends torch_storage._StorageBase {
  5028. constructor(size) {
  5029. super(size, torch.qint32);
  5030. }
  5031. });
  5032. this.registerType('torch.BFloat16Storage', class extends torch_storage._StorageBase {
  5033. constructor(size) {
  5034. super(size, torch.bfloat16);
  5035. }
  5036. });
  5037. this.registerType('torch.Size', class extends Array {
  5038. constructor(size) {
  5039. super(size.length);
  5040. for (let i = 0; i < size.length; i++) {
  5041. this[i] = size[i];
  5042. }
  5043. }
  5044. __len__() {
  5045. return this.length;
  5046. }
  5047. });
  5048. this.registerType('torch.Tensor', class {
  5049. constructor() {
  5050. this._layout = torch.strided;
  5051. }
  5052. get device() {
  5053. return this.storage().device;
  5054. }
  5055. get dtype() {
  5056. if (this._layout === torch.sparse_coo) {
  5057. return this._values.dtype();
  5058. }
  5059. return this.storage().dtype;
  5060. }
  5061. get shape() {
  5062. return this._shape;
  5063. }
  5064. get layout() {
  5065. return this._layout;
  5066. }
  5067. get values() {
  5068. if (this._layout === torch.sparse_coo) {
  5069. return this._values;
  5070. }
  5071. throw new python.Error("Unsupported values in layout'" + this._layout.__str__() + "'.");
  5072. }
  5073. get indices() {
  5074. if (this._layout === torch.sparse_coo) {
  5075. return this._indices;
  5076. }
  5077. throw new python.Error("Unsupported indices in layout'" + this._indices.__str__() + "'.");
  5078. }
  5079. size() {
  5080. return this._shape;
  5081. }
  5082. storage() {
  5083. if (!this._storage) {
  5084. const name = this.__class__.__name__ == 'Tensor' ? 'FloatStorage' : this.__storage__.__name__.replace('Tensor', 'Storage');
  5085. this._storage = self.invoke(this.__class__.__module__ + '.' + name, []);
  5086. }
  5087. return this._storage;
  5088. }
  5089. storage_offset() {
  5090. return this._storage_offset;
  5091. }
  5092. stride() {
  5093. return this._stride;
  5094. }
  5095. resize_(shape) {
  5096. this._shape = shape;
  5097. }
  5098. __len__() {
  5099. return this._shape[0];
  5100. }
  5101. __setstate__(state) {
  5102. this._storage = state[0];
  5103. this._storage_offset = state[1];
  5104. this._shape = state[2];
  5105. this._stride = state[3];
  5106. }
  5107. __bool__() {
  5108. return true;
  5109. }
  5110. __int__() {
  5111. const storage = this.storage();
  5112. if (storage && storage.dtype.__reduce__() === 'int64' && storage.data.length === 8) {
  5113. const buffer = storage.data;
  5114. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5115. return view.getInt64(0, true);
  5116. }
  5117. return NaN;
  5118. }
  5119. __float__() {
  5120. const storage = this.storage();
  5121. if (storage && storage.dtype.__reduce__() === 'float32') {
  5122. if (storage.size() !== undefined && storage.data.length === 4) {
  5123. const buffer = storage.data;
  5124. const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  5125. return view.getFloat32(0, true);
  5126. }
  5127. }
  5128. return NaN;
  5129. }
  5130. __str__() {
  5131. return 'tensor(...)';
  5132. }
  5133. });
  5134. this.registerType('torch.nn.parameter.Parameter', class extends torch.Tensor {
  5135. constructor(data, requires_grad) {
  5136. super();
  5137. if (!data) {
  5138. data = self.invoke('torch.Tensor', [[]]);
  5139. }
  5140. this.data = data;
  5141. this.requires_grad = requires_grad !== undefined ? requires_grad : true;
  5142. }
  5143. __setstate__(state) {
  5144. switch (state.length) {
  5145. case 3:
  5146. this.data = null;
  5147. break;
  5148. case 4:
  5149. this.data = state[0];
  5150. break;
  5151. case 5:
  5152. this.data = state[0];
  5153. break;
  5154. default:
  5155. throw new python.Error("Unsupported parameter state length '" + state.length + "'.");
  5156. }
  5157. }
  5158. });
  5159. this.registerType('torch.nn.parameter.UninitializedParameter', class extends torch_nn_parameter.Parameter {
  5160. constructor(requires_grad /*, device, dtype */) {
  5161. super(undefined, requires_grad);
  5162. }
  5163. });
  5164. this.registerType('torch.BoolTensor', class extends torch.Tensor {});
  5165. this.registerType('torch.ByteTensor', class extends torch.Tensor {});
  5166. this.registerType('torch.CharTensor', class extends torch.Tensor {});
  5167. this.registerType('torch.ShortTensor', class extends torch.Tensor {});
  5168. this.registerType('torch.IntTensor', class extends torch.Tensor {});
  5169. this.registerType('torch.LongTensor', class extends torch.Tensor {});
  5170. this.registerType('torch.HalfTensor', class extends torch.Tensor {});
  5171. this.registerType('torch.FloatTensor', class extends torch.Tensor {});
  5172. this.registerType('torch.DoubleTensor', class extends torch.Tensor {});
  5173. this.registerType('torch.ComplexFloatTensor', class extends torch.Tensor {});
  5174. this.registerType('torch.ComplexDoubleTensor', class extends torch.Tensor {});
  5175. this.registerType('torch.QInt8Tensor', class extends torch.Tensor {});
  5176. this.registerType('torch.QUInt8Tensor', class extends torch.Tensor {});
  5177. this.registerType('torch.QInt32Tensor', class extends torch.Tensor {});
  5178. this.registerType('torch.BFloat16Tensor', class extends torch.Tensor {});
  5179. this.registerType('torch.cuda.FloatTensor', class extends torch.Tensor {});
  5180. this.registerType('torch.cuda.DoubleTensor', class extends torch.Tensor {});
  5181. torch.uint8 = torch.ByteStorage.dtype = new torch.dtype({ type: 0, name: 'uint8', itemsize: 1 });
  5182. torch.int8 = torch.CharStorage.dtype = new torch.dtype({ type: 1, name: 'int8', itemsize: 1 });
  5183. torch.int16 = torch.ShortStorage.dtype = new torch.dtype({ type: 2, name: 'int16', itemsize: 2 });
  5184. torch.int32 = torch.IntStorage.dtype = new torch.dtype({ type: 3, name: 'int32', itemsize: 4 });
  5185. torch.int64 = torch.LongStorage.dtype = new torch.dtype({ type: 4, name: 'int64', itemsize: 8 });
  5186. torch.float16 = torch.HalfStorage.dtype = new torch.dtype({ type: 5, name: 'float16', itemsize: 2 });
  5187. torch.float32 = torch.FloatStorage.dtype = new torch.dtype({ type: 6, name: 'float32', itemsize: 4 });
  5188. torch.float64 = torch.DoubleStorage.dtype = new torch.dtype({ type: 7, name: 'float64', itemsize: 8 });
  5189. torch.complex32 = torch.ComplexHalfStorage.dtype = new torch.dtype({ type: 8, name: 'complex32', itemsize: 4 });
  5190. torch.complex64 = torch.ComplexFloatStorage.dtype = new torch.dtype({ type: 9, name: 'complex64', itemsize: 8 });
  5191. torch.complex128 = torch.ComplexDoubleStorage.dtype = new torch.dtype({ type: 10, name: 'complex128', itemsize: 16 });
  5192. torch.bool = torch.BoolStorage.dtype = new torch.dtype({ type: 11, name: 'boolean', itemsize: 1 });
  5193. torch.qint8 = torch.QInt8Storage.dtype = new torch.dtype({ type: 12, name: 'qint8', itemsize: 1 });
  5194. torch.quint8 = torch.QUInt8Storage.dtype = new torch.dtype({ type: 13, name: 'quint8', itemsize: 1 });
  5195. torch.qint32 = torch.QInt32Storage.dtype = new torch.dtype({ type: 14, name: 'qint32', itemsize: 4 });
  5196. torch.bfloat16 = torch.BFloat16Storage.dtype = new torch.dtype({ type: 15, name: 'bfloat16', itemsize: 2 });
  5197. torch.quint4x2 = new torch.dtype({ type: 16, name: 'quint4x2' });
  5198. torch.strided = new torch.layout('torch.strided');
  5199. torch.sparse_coo = new torch.layout('torch.sparse_coo');
  5200. torch.sparse_csr = new torch.layout('torch.sparse_csr');
  5201. torch.sparse_csc = new torch.layout('torch.sparse_csc');
  5202. torch.sparse_bsr = new torch.layout('torch.sparse_bsr');
  5203. torch.sparse_bsc = new torch.layout('torch.sparse_bsc');
  5204. torch._mkldnn = new torch.layout('torch._mkldnn');
  5205. torch.per_tensor_affine = new torch.qscheme('torch.per_tensor_affine');
  5206. torch.per_channel_affine = new torch.qscheme('torch.per_channel_affine');
  5207. torch.per_tensor_symmetric = new torch.qscheme('torch.per_tensor_symmetric');
  5208. torch.per_channel_symmetric = new torch.qscheme('torch.per_channel_symmetric');
  5209. torch.per_channel_affine_float_qparams = new torch.qscheme('torch.per_channel_affine_float_qparams');
  5210. torch.inf = this.register('math').inf;
  5211. }
  5212. get builtins() {
  5213. return this._builtins;
  5214. }
  5215. source(file) {
  5216. return this._sources.has(file) ? this._sources.get(file) : null;
  5217. }
  5218. debug(/* file */) {
  5219. }
  5220. exec(code , context) {
  5221. const reader = new python.Parser(code, null, null);
  5222. const program = reader.parse();
  5223. if (!program) {
  5224. throw new python.Error("Module '" + '?' + "' parse error.");
  5225. }
  5226. this.block(program.body, context);
  5227. }
  5228. parse(file) {
  5229. const buffer = this.source(file);
  5230. if (buffer) {
  5231. const debug = this.debug(file);
  5232. const code = this._utf8Decoder.decode(buffer);
  5233. const reader = new python.Parser(code, file, debug);
  5234. const program = reader.parse();
  5235. if (!program) {
  5236. throw new python.Error("Module '" + file + "' parse error.");
  5237. }
  5238. return program;
  5239. }
  5240. return null;
  5241. }
  5242. import(name, current, level) {
  5243. if (level) {
  5244. let bits = current.split('.');
  5245. if (bits.length < level) {
  5246. throw new python.Error('Invalid relative import beyond top-level package.');
  5247. }
  5248. bits = bits.slice(0, bits.length - level);
  5249. const base = bits.join('.');
  5250. name = name ? [ base, name ].join('.') : base;
  5251. }
  5252. const index = name.lastIndexOf('.');
  5253. let parent = null;
  5254. let child = null;
  5255. if (index > 0) {
  5256. parent = name.substring(0, index);
  5257. child = name.substring(index + 1);
  5258. this.import(parent);
  5259. }
  5260. if (!this._modules.has(name)) {
  5261. const module = this._registry.get(name) || new this._builtins.module(name);
  5262. module.__package__ = name;
  5263. this._modules.set(name, module);
  5264. const path = name.split('.').join('/');
  5265. module.__path__ = [ path ];
  5266. const file = path + '.py';
  5267. const program = this.parse(file);
  5268. if (program) {
  5269. module.__file__ = file;
  5270. for (const entry of Object.entries(this.builtins)) {
  5271. switch (entry[0]) {
  5272. case '__class__':
  5273. case '__package__':
  5274. case '__module__':
  5275. case '__name__':
  5276. case '__path__':
  5277. case '__file__':
  5278. break;
  5279. default:
  5280. module[entry[0]] = entry[1];
  5281. break;
  5282. }
  5283. }
  5284. const context = new python.Execution.Context(module, null);
  5285. if (name !== 'builtins') {
  5286. context.set('__builtins__', this._modules.get('builtins'));
  5287. }
  5288. this.block(program.body, context);
  5289. }
  5290. if (parent) {
  5291. const parent_module = this._modules.get(parent);
  5292. parent_module[child] = module;
  5293. }
  5294. }
  5295. return this._modules.get(name);
  5296. }
  5297. __import__(name, globals, locals, fromlist, level) {
  5298. let module = null;
  5299. level = level || 0;
  5300. if (level === 0) {
  5301. module = this.import(name);
  5302. }
  5303. else {
  5304. globals = globals || {};
  5305. let current = globals.__package__;
  5306. if (!current) {
  5307. const spec = globals.__spec__;
  5308. if (spec) {
  5309. current = spec.parent;
  5310. }
  5311. else {
  5312. const name = globals.__name__;
  5313. const bits = name.split('.');
  5314. bits.pop();
  5315. current = bits.join('.');
  5316. }
  5317. }
  5318. module = this.import(name, current, level);
  5319. }
  5320. if (!fromlist) {
  5321. if (level === 0) {
  5322. return this.import(name.split('.')[0]);
  5323. }
  5324. else if (name) {
  5325. throw new python.Error("Unsupported relative import '" + name + "'.");
  5326. // cut_off = len(name) - len(name.partition('.')[0])
  5327. // return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  5328. }
  5329. }
  5330. else if (module.__path__) {
  5331. const handle_fromlist = (module, fromlist, recursive) => {
  5332. for (const name of fromlist) {
  5333. if (name == '*') {
  5334. if (!recursive && module.__all__) {
  5335. handle_fromlist(module, module.__all__, true);
  5336. }
  5337. }
  5338. else if (!module[name]) {
  5339. this.import(module.__name__ + '.' + name);
  5340. }
  5341. }
  5342. return module;
  5343. };
  5344. handle_fromlist(module, fromlist);
  5345. }
  5346. return module;
  5347. }
  5348. module(name) {
  5349. return this._modules.get(name);
  5350. }
  5351. resolve(name) {
  5352. const index = name.lastIndexOf('.');
  5353. const memberName = index === -1 ? name : name.substring(index + 1, name.length);
  5354. const moduleName = index === -1 ? '' : name.substring(0, index);
  5355. const module = this.import(moduleName);
  5356. let type = module ? module[memberName] : null;
  5357. if (!type) {
  5358. if (!this._unresolved.has(name)) {
  5359. const moduleName = name.split('.').shift();
  5360. if (this._registry.has(moduleName) && moduleName !== '__main__') {
  5361. this._exceptionCallback(new python.Error("Unknown type name '" + name + "'."), false);
  5362. }
  5363. const type = this._createType(name, class {});
  5364. this._unresolved.set(name, type);
  5365. }
  5366. type = this._unresolved.get(name);
  5367. }
  5368. return type;
  5369. }
  5370. invoke(target, args) {
  5371. if (typeof target === 'string') {
  5372. target = this.resolve(target);
  5373. }
  5374. if (target) {
  5375. if (target.__class__ === this._builtins.type) {
  5376. if (target.prototype && target.prototype.__class__ === target) {
  5377. return Reflect.construct(target, args);
  5378. }
  5379. const obj = Object.create(target);
  5380. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5381. obj.__init__.apply(obj, args);
  5382. }
  5383. return obj;
  5384. }
  5385. else if (target.__class__ === this._builtins.function) {
  5386. if (target.__call__) {
  5387. return target.__call__(args);
  5388. }
  5389. return target.apply(null, args);
  5390. }
  5391. }
  5392. throw new python.Error('Unsupported invoke target.');
  5393. }
  5394. call(target, name, args, context) {
  5395. const callTarget = this.target(target, context);
  5396. const callArguments = args.map((argument) => this.expression(argument, context));
  5397. if (!callTarget || (name !== null && !callTarget[name])) {
  5398. if (name === '__new__' && callArguments.length === 1 && callArguments[0] == callTarget) {
  5399. name = null;
  5400. callArguments.shift();
  5401. }
  5402. else {
  5403. const format = (expression) => {
  5404. if (expression.type == 'id') {
  5405. return expression.value;
  5406. }
  5407. if (expression.type == '.') {
  5408. return format(expression.target) + '.' + format(expression.member);
  5409. }
  5410. return null;
  5411. };
  5412. const targetName = format(target) + '.' + name;
  5413. throw new python.Error("Unknown function '" + targetName + "'.");
  5414. }
  5415. }
  5416. const func = name ? callTarget[name] : callTarget;
  5417. if (func.__class__ === this._builtins.type) {
  5418. if (func.prototype && func.prototype.__class__ === func) {
  5419. return Reflect.construct(func, args);
  5420. }
  5421. const obj = Object.create(func);
  5422. obj.__class__ = func;
  5423. if (obj.__init__ && typeof obj.__init__ === 'function') {
  5424. obj.__init__.apply(obj, args);
  5425. }
  5426. return obj;
  5427. }
  5428. if (func.__class__ === this._builtins.function) {
  5429. if (func.__call__) {
  5430. return func.__call__(callArguments);
  5431. }
  5432. }
  5433. if (func.__class__ === this._builtins.method) {
  5434. if (func.__call__) {
  5435. return func.__call__([ callTarget ].concat(callArguments));
  5436. }
  5437. }
  5438. if (typeof func === 'function') {
  5439. return func.apply(callTarget, callArguments);
  5440. }
  5441. throw new python.Error("Unsupported call expression.");
  5442. }
  5443. apply(method, args, context) {
  5444. const locals = Array.prototype.slice.call(args);
  5445. context = new python.Execution.Context(context.globals, {});
  5446. for (const parameter of method.parameters) {
  5447. let value = locals.shift();
  5448. if (value === undefined && parameter.initializer) {
  5449. value = this.expression(parameter.initializer, context);
  5450. }
  5451. context.set(parameter.name, value);
  5452. }
  5453. return this.block(method.body.statements, context);
  5454. }
  5455. block(statements, context) {
  5456. statements = Array.prototype.slice.call(statements);
  5457. while (statements.length > 0) {
  5458. const statement = statements.shift();
  5459. const value = this.statement(statement, context);
  5460. if (value !== undefined) {
  5461. return value;
  5462. }
  5463. }
  5464. return undefined;
  5465. }
  5466. statement(statement, context) {
  5467. switch (statement.type) {
  5468. case 'pass': {
  5469. break;
  5470. }
  5471. case 'return': {
  5472. return this.expression(statement.expression, context);
  5473. }
  5474. case 'def': {
  5475. const module = context.get('__name__');
  5476. const self = this;
  5477. const parent = context.get('__class__');
  5478. const type = (parent === this._builtins.module) ? this._builtins.function : this._builtins.method;
  5479. const func = {
  5480. __class__: type,
  5481. __globals__: context,
  5482. __module__: module,
  5483. __name__: statement.name,
  5484. __code__: statement,
  5485. __call__: function(args) {
  5486. return self.apply(this.__code__, args, this.__globals__);
  5487. }
  5488. };
  5489. context.set(statement.name, func);
  5490. break;
  5491. }
  5492. case 'class': {
  5493. const value = this._createType(context.get('__name__') + '.' + statement.name, class {});
  5494. context.set(statement.name, value);
  5495. this.block(statement.body.statements, new python.Execution.Context(context.globals, value.prototype));
  5496. break;
  5497. }
  5498. case 'var': {
  5499. context.set(statement.name, statement.initializer ? this.expression(statement.initializer, context) : undefined);
  5500. break;
  5501. }
  5502. case '=': {
  5503. this.expression(statement, context);
  5504. break;
  5505. }
  5506. case 'if': {
  5507. const condition = this.expression(statement.condition, context);
  5508. if (condition === true || condition) {
  5509. const value = this.block(statement.then.statements, context);
  5510. if (value !== undefined) {
  5511. return value;
  5512. }
  5513. break;
  5514. }
  5515. else if (condition === false) {
  5516. const value = this.block(statement.else.statements, context);
  5517. if (value !== undefined) {
  5518. return value;
  5519. }
  5520. break;
  5521. }
  5522. throw new python.Error("Unsupported condition.");
  5523. }
  5524. case 'for': {
  5525. if (statement.target.length == 1 &&
  5526. statement.variable.length === 1 && statement.variable[0].type === 'id') {
  5527. const range = this.expression(statement.target[0], context);
  5528. const variable = statement.variable[0];
  5529. for (const current of range) {
  5530. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current }}, context);
  5531. const value = this.block(statement.body.statements, context);
  5532. if (value !== undefined) {
  5533. return value;
  5534. }
  5535. }
  5536. break;
  5537. }
  5538. throw new python.Error("Unsupported 'for' statement.");
  5539. }
  5540. case 'while': {
  5541. const condition = this.expression(statement.condition, context);
  5542. if (condition) {
  5543. const value = this.block(statement.body.statements, context);
  5544. if (value !== undefined) {
  5545. return value;
  5546. }
  5547. }
  5548. break;
  5549. }
  5550. case 'with': {
  5551. const items = [];
  5552. for (const item of statement.item) {
  5553. items.push(this.expression(item.expression, context));
  5554. }
  5555. for (const item of items) {
  5556. if (item.__enter__ && item.__enter__.__call__) {
  5557. item.__enter__.__call__([ item ]);
  5558. }
  5559. }
  5560. const value = this.block(statement.body.statements, context);
  5561. for (const item of items) {
  5562. if (item.__exit__ && item.__exit__.__call__) {
  5563. item.__exit__.__call__([ item ]);
  5564. }
  5565. }
  5566. if (value !== undefined) {
  5567. return value;
  5568. }
  5569. break;
  5570. }
  5571. case 'call': {
  5572. this.expression(statement, context);
  5573. break;
  5574. }
  5575. case 'import': {
  5576. for (const alias of statement.names) {
  5577. let module = this.__import__(alias.name, context);
  5578. if (alias.asname) {
  5579. const bits = alias.name.split('.').reverse();
  5580. bits.pop();
  5581. while (bits.length > 0) {
  5582. module = module[bits.pop()];
  5583. }
  5584. context.set(alias.asname, module);
  5585. }
  5586. else {
  5587. context.set(alias.name.split('.')[0], module);
  5588. }
  5589. }
  5590. break;
  5591. }
  5592. case 'import_from': {
  5593. const fromlist = statement.names.map((name) => name.name);
  5594. const module = this.__import__(statement.module, context.globals, context.locals, fromlist, statement.level);
  5595. for (const entry of statement.names) {
  5596. const name = entry.name;
  5597. const asname = entry.asname ? entry.asname : null;
  5598. if (!module[name]) {
  5599. throw new python.Error("Cannot import '" + name + "' from '" + statement.module + "'.");
  5600. }
  5601. context.set(asname ? asname : name, module[name]);
  5602. }
  5603. break;
  5604. }
  5605. case 'string': {
  5606. break;
  5607. }
  5608. default: {
  5609. throw new python.Error("Unsupported statement '" + statement.type + "'.");
  5610. }
  5611. }
  5612. return undefined;
  5613. }
  5614. expression(expression, context) {
  5615. const self = context.get('self');
  5616. switch (expression.type) {
  5617. case '=': {
  5618. const target = expression.target;
  5619. if (target.type === 'id') {
  5620. context.set(target.value, this.expression(expression.expression, context));
  5621. return undefined;
  5622. }
  5623. else if (target.type === '[]') {
  5624. if (target.target.type === 'id' &&
  5625. target.arguments.type === 'list' &&
  5626. target.arguments.value.length === 1) {
  5627. const index = this.expression(target.arguments.value[0], context);
  5628. if (target.target.value === '__annotations__') {
  5629. context.set(target.target.value, context.get(target.target.value) || {});
  5630. }
  5631. const obj = context.get(target.target.value);
  5632. const value = this.expression(expression.expression, context);
  5633. if (obj instanceof Map) {
  5634. obj.set(index, value);
  5635. }
  5636. else {
  5637. obj[index] = value;
  5638. }
  5639. return undefined;
  5640. }
  5641. }
  5642. else if (target.type === '.' &&
  5643. target.member.type === 'id') {
  5644. this.expression(target.target, context)[target.member.value] = this.expression(expression.expression, context);
  5645. return undefined;
  5646. }
  5647. else if (target.type === 'tuple') {
  5648. context.target.push(target.value);
  5649. const value = this.expression(expression.expression, context);
  5650. context.target.pop();
  5651. if (target.value.every((item) => item.type === 'id')) {
  5652. if (target.value.length < value.length) {
  5653. throw new python.Error('ValueError: too many values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5654. }
  5655. if (target.value.length > value.length) {
  5656. throw new python.Error('ValueError: not enough values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  5657. }
  5658. for (let i = 0; i < value.length; i++) {
  5659. context.set(target.value[i].value, value[i]);
  5660. }
  5661. return undefined;
  5662. }
  5663. }
  5664. break;
  5665. }
  5666. case 'list': {
  5667. return expression.value.map((item) => this.expression(item, context));
  5668. }
  5669. case 'string': {
  5670. return expression.value.substring(1, expression.value.length - 1);
  5671. }
  5672. case 'number': {
  5673. return Number(expression.value);
  5674. }
  5675. case '[]': {
  5676. if (expression.target.type === 'id' &&
  5677. expression.arguments.type === 'list' &&
  5678. expression.arguments.value.length === 1) {
  5679. if (context.get(expression.target.value)) {
  5680. const index = this.expression(expression.arguments.value[0], context);
  5681. const target = context.get(expression.target.value);
  5682. if (target instanceof Map) {
  5683. return target.get(index);
  5684. }
  5685. return target[index < 0 ? target.length + index : index];
  5686. }
  5687. }
  5688. const target = this.expression(expression.target, context);
  5689. if (target && expression.arguments.type === 'list' &&
  5690. (target.__class__ === this._typing._TupleType ||
  5691. target.__class__ === this._typing._SpecialGenericAlias ||
  5692. target.__class__ === this._typing._SpecialForm)) {
  5693. const type = Object.assign({}, target);
  5694. type.__args__ = expression.arguments.value.map((arg) => this.expression(arg, context));
  5695. return type;
  5696. }
  5697. if (expression.arguments.type === 'list' && expression.arguments.value.length === 1) {
  5698. const index = this.expression(expression.arguments.value[0], context);
  5699. if (target instanceof Map) {
  5700. return target.get(index);
  5701. }
  5702. return target[index < 0 ? target.length + index : index];
  5703. }
  5704. break;
  5705. }
  5706. case '.': {
  5707. if (expression.member.type == 'id') {
  5708. const target = this.target(expression.target, context);
  5709. return target[expression.member.value];
  5710. }
  5711. throw new python.Error("Unsupported field expression.");
  5712. }
  5713. case 'call': {
  5714. if (expression.target.type === 'id' && expression.target.value === 'unchecked_cast' && expression.arguments.length === 2) {
  5715. return this.expression(expression.arguments[1], context);
  5716. }
  5717. if (expression.target.type === '.') {
  5718. return this.call(expression.target.target, expression.target.member.value, expression.arguments, context);
  5719. }
  5720. return this.call(expression.target, null, expression.arguments, context);
  5721. }
  5722. case 'id': {
  5723. switch (expression.value) {
  5724. case 'self': return self;
  5725. case 'None': return null;
  5726. case 'True': return true;
  5727. case 'False': return false;
  5728. default: {
  5729. const type = (value) => {
  5730. return value &&
  5731. (value.__class__ === this._builtins.type ||
  5732. value.__class__ === this._typing._TupleType ||
  5733. value.__class__ === this._typing._SpecialGenericAlias ||
  5734. value.__class__ === this._typing._SpecialForm);
  5735. };
  5736. const builtin = this._builtins[expression.value];
  5737. if (type(builtin)) {
  5738. return builtin;
  5739. }
  5740. const value = context.get(expression.value);
  5741. if (value === undefined) {
  5742. const typing = this._typing[expression.value];
  5743. if (type(typing)) {
  5744. return typing;
  5745. }
  5746. const torch = this._registry.get('torch');
  5747. if (torch) {
  5748. const value = torch[expression.value]; // TODO
  5749. if (type(value)) {
  5750. return value;
  5751. }
  5752. }
  5753. }
  5754. return value;
  5755. }
  5756. }
  5757. }
  5758. case 'tuple': {
  5759. return expression.value.map((expression) => this.expression(expression, context));
  5760. }
  5761. case 'dict': {
  5762. const dict = {};
  5763. for (const pair of expression.value) {
  5764. if (pair.type !== 'pair') {
  5765. throw new python.Error("Unsupported dict item type '" + pair.type + "'.");
  5766. }
  5767. const key = this.expression(pair.key, context);
  5768. const value = this.expression(pair.value, context);
  5769. dict[key] = value;
  5770. }
  5771. return dict;
  5772. }
  5773. case 'unary': {
  5774. switch (expression.op) {
  5775. case '-': {
  5776. return -this.expression(expression.operand, context);
  5777. }
  5778. default: {
  5779. throw new python.Error("Unsupported unary expression '" + expression.op + "'.");
  5780. }
  5781. }
  5782. }
  5783. default: {
  5784. throw new python.Error("Unsupported expression '" + expression.type + "'.");
  5785. }
  5786. }
  5787. return undefined;
  5788. }
  5789. target(expression, context) {
  5790. let current = expression;
  5791. let path = [];
  5792. for (;;) {
  5793. if (current.type === '.' && current.member && current.member.type === 'id') {
  5794. path.push(current.member.value);
  5795. current = current.target;
  5796. }
  5797. else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  5798. path.push(current.value);
  5799. break;
  5800. }
  5801. else {
  5802. path = null;
  5803. break;
  5804. }
  5805. }
  5806. if (path) {
  5807. let target = null;
  5808. for (let i = path.length - 1; i >= 0; i--) {
  5809. target = target ? target[path[i]] : context.get(path[i]);
  5810. if (!target) {
  5811. break;
  5812. }
  5813. }
  5814. if (!target) {
  5815. path.reverse();
  5816. const name = path.join('.');
  5817. const file = path.join('/') + '.py';
  5818. if (this._sources.has(file)) {
  5819. target = this.import(name);
  5820. }
  5821. else {
  5822. target = this.resolve(name);
  5823. }
  5824. }
  5825. return target;
  5826. }
  5827. return this.expression(expression, context);
  5828. }
  5829. add(name, source) {
  5830. this._sources.set(name, source);
  5831. }
  5832. register(name, value) {
  5833. if (!this._registry.has(name)) {
  5834. value = value || new (this._registry.get('builtins').module)(name);
  5835. this._registry.set(name, value);
  5836. let current = name;
  5837. for (;;) {
  5838. const index = current.lastIndexOf('.');
  5839. if (index === -1) {
  5840. break;
  5841. }
  5842. const child = current.substring(index + 1);
  5843. current = current.substring(0, index);
  5844. const parent = this.register(current);
  5845. parent[child] = value;
  5846. }
  5847. }
  5848. return this._registry.get(name);
  5849. }
  5850. registerFunction(name, value) {
  5851. const parts = name.split('.');
  5852. value.__class__ = this._builtins.function;
  5853. value.__name__ = parts.pop();
  5854. value.__module__ = parts.join('.');
  5855. const module = this.register(value.__module__);
  5856. if (module[name]) {
  5857. throw new python.Error("Function '" + name + "' is already registered.");
  5858. }
  5859. module[value.__name__] = value;
  5860. return value;
  5861. }
  5862. _createType(name, value) {
  5863. const parts = name.split('.');
  5864. value.__class__ = this._builtins.type;
  5865. value.__name__ = parts.pop();
  5866. value.__module__ = parts.join('.');
  5867. value.prototype.__class__ = value;
  5868. return value;
  5869. }
  5870. registerType(name, value) {
  5871. value = this._createType(name, value);
  5872. const parts = name.split('.');
  5873. const memberName = parts.pop();
  5874. const moduleName = parts.join('.');
  5875. const module = this.register(moduleName);
  5876. if (module[memberName]) {
  5877. throw new python.Error("Class '" + memberName + "' is already registered.");
  5878. }
  5879. module[memberName] = value;
  5880. return value;
  5881. }
  5882. };
  5883. python.Execution.Context = class {
  5884. constructor(globals, locals) {
  5885. this.globals = globals;
  5886. this.locals = locals;
  5887. }
  5888. set(name, value) {
  5889. if (this.locals) {
  5890. this.locals[name] = value;
  5891. }
  5892. else {
  5893. this.globals[name] = value;
  5894. }
  5895. }
  5896. get(name) {
  5897. if (this.locals && name in this.locals) {
  5898. return this.locals[name];
  5899. }
  5900. if (name in this.globals) {
  5901. return this.globals[name];
  5902. }
  5903. return undefined;
  5904. }
  5905. get target() {
  5906. this._target = this._target || [];
  5907. return this._target;
  5908. }
  5909. };
  5910. python.Unpickler = class {
  5911. static open(data, execution) {
  5912. const reader = data instanceof Uint8Array ? new python.Unpickler.BinaryReader(data) : new python.Unpickler.StreamReader(data);
  5913. if (reader.length > 2) {
  5914. const head = reader.peek(2);
  5915. if (head[0] === 0x80 && head[1] < 7) {
  5916. execution = typeof execution === 'function' ? execution() : execution;
  5917. return execution.invoke('pickle.Unpickler', [ data ]);
  5918. }
  5919. reader.seek(-1);
  5920. const tail = reader.peek(1);
  5921. reader.seek(0);
  5922. if (tail[0] === 0x2e) {
  5923. execution = typeof execution === 'function' ? execution() : execution;
  5924. return execution.invoke('pickle.Unpickler', [ data ]);
  5925. }
  5926. }
  5927. return null;
  5928. }
  5929. };
  5930. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  5931. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  5932. python.Unpickler.OpCode = {
  5933. MARK: 40, // '('
  5934. EMPTY_TUPLE: 41, // ')'
  5935. STOP: 46, // '.'
  5936. POP: 48, // '0'
  5937. POP_MARK: 49, // '1'
  5938. DUP: 50, // '2'
  5939. BINBYTES: 66, // 'B' (Protocol 3)
  5940. SHORT_BINBYTES: 67, // 'C' (Protocol 3)
  5941. FLOAT: 70, // 'F'
  5942. BINFLOAT: 71, // 'G'
  5943. INT: 73, // 'I'
  5944. BININT: 74, // 'J'
  5945. BININT1: 75, // 'K'
  5946. LONG: 76, // 'L'
  5947. BININT2: 77, // 'M'
  5948. NONE: 78, // 'N'
  5949. PERSID: 80, // 'P'
  5950. BINPERSID: 81, // 'Q'
  5951. REDUCE: 82, // 'R'
  5952. STRING: 83, // 'S'
  5953. BINSTRING: 84, // 'T'
  5954. SHORT_BINSTRING: 85, // 'U'
  5955. UNICODE: 86, // 'V'
  5956. BINUNICODE: 88, // 'X'
  5957. EMPTY_LIST: 93, // ']'
  5958. APPEND: 97, // 'a'
  5959. BUILD: 98, // 'b'
  5960. GLOBAL: 99, // 'c'
  5961. DICT: 100, // 'd'
  5962. APPENDS: 101, // 'e'
  5963. GET: 103, // 'g'
  5964. BINGET: 104, // 'h'
  5965. INST: 105, // 'i'
  5966. LONG_BINGET: 106, // 'j'
  5967. LIST: 108, // 'l'
  5968. OBJ: 111, // 'o'
  5969. PUT: 112, // 'p'
  5970. BINPUT: 113, // 'q'
  5971. LONG_BINPUT: 114, // 'r'
  5972. SETITEM: 115, // 's'
  5973. TUPLE: 116, // 't'
  5974. SETITEMS: 117, // 'u'
  5975. EMPTY_DICT: 125, // '}'
  5976. PROTO: 128,
  5977. NEWOBJ: 129,
  5978. TUPLE1: 133, // '\x85'
  5979. TUPLE2: 134, // '\x86'
  5980. TUPLE3: 135, // '\x87'
  5981. NEWTRUE: 136, // '\x88'
  5982. NEWFALSE: 137, // '\x89'
  5983. LONG1: 138, // '\x8a'
  5984. LONG4: 139, // '\x8b'
  5985. SHORT_BINUNICODE: 140, // '\x8c' (Protocol 4)
  5986. BINUNICODE8: 141, // '\x8d' (Protocol 4)
  5987. BINBYTES8: 142, // '\x8e' (Protocol 4)
  5988. EMPTY_SET: 143, // '\x8f' (Protocol 4)
  5989. ADDITEMS: 144, // '\x90' (Protocol 4)
  5990. FROZENSET: 145, // '\x91' (Protocol 4)
  5991. NEWOBJ_EX: 146, // '\x92' (Protocol 4)
  5992. STACK_GLOBAL: 147, // '\x93' (Protocol 4)
  5993. MEMOIZE: 148, // '\x94' (Protocol 4)
  5994. FRAME: 149, // '\x95' (Protocol 4)
  5995. BYTEARRAY8: 150, // '\x96' (Protocol 5)
  5996. NEXT_BUFFER: 151, // '\x97' (Protocol 5)
  5997. READONLY_BUFFER: 152 // '\x98' (Protocol 5)
  5998. };
  5999. python.Unpickler.BinaryReader = class {
  6000. constructor(buffer) {
  6001. this._buffer = buffer;
  6002. this._length = buffer.length;
  6003. this._position = 0;
  6004. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  6005. this._utf8Decoder = new TextDecoder('utf-8');
  6006. this._asciiDecoder = new TextDecoder('ascii');
  6007. }
  6008. get position() {
  6009. return this._position;
  6010. }
  6011. get length() {
  6012. return this._length;
  6013. }
  6014. seek(position) {
  6015. this._position = position >= 0 ? position : this._length + position;
  6016. if (this._position > this._buffer.length) {
  6017. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6018. }
  6019. }
  6020. skip(offset) {
  6021. this._position += offset;
  6022. if (this._position > this._buffer.length) {
  6023. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6024. }
  6025. }
  6026. stream(length) {
  6027. const buffer = this.read(length);
  6028. return new python.Unpickler.BinaryReader(buffer);
  6029. }
  6030. peek(length) {
  6031. const position = this._position;
  6032. length = length !== undefined ? length : this._length - this._position;
  6033. this.skip(length);
  6034. const end = this._position;
  6035. this.skip(-length);
  6036. if (position === 0 && length === this._length) {
  6037. return this._buffer;
  6038. }
  6039. return this._buffer.subarray(position, end);
  6040. }
  6041. read(length) {
  6042. const position = this._position;
  6043. length = length !== undefined ? length : this._length - this._position;
  6044. this.skip(length);
  6045. if (position === 0 && length === this._length) {
  6046. return this._buffer;
  6047. }
  6048. return this._buffer.subarray(position, this._position);
  6049. }
  6050. byte() {
  6051. const position = this._position;
  6052. this.skip(1);
  6053. return this._view.getUint8(position);
  6054. }
  6055. uint16() {
  6056. const position = this._position;
  6057. this.skip(2);
  6058. return this._view.getUint16(position, true);
  6059. }
  6060. int32() {
  6061. const position = this._position;
  6062. this.skip(4);
  6063. return this._view.getInt32(position, true);
  6064. }
  6065. uint32() {
  6066. const position = this._position;
  6067. this.skip(4);
  6068. return this._view.getUint32(position, true);
  6069. }
  6070. int64() {
  6071. const position = this._position;
  6072. this.skip(8);
  6073. return this._view.getInt64(position, true).toNumber();
  6074. }
  6075. float64() {
  6076. const position = this._position;
  6077. this.skip(8);
  6078. return this._view.getFloat64(position, false);
  6079. }
  6080. string(size, encoding) {
  6081. const data = this.read(size);
  6082. return (encoding == 'utf-8') ?
  6083. this._utf8Decoder.decode(data) :
  6084. this._asciiDecoder.decode(data);
  6085. }
  6086. line() {
  6087. const index = this._buffer.indexOf(0x0A, this._position);
  6088. if (index == -1) {
  6089. throw new python.Error("Could not find end of line.");
  6090. }
  6091. const size = index - this._position;
  6092. const text = this.string(size, 'ascii');
  6093. this.skip(1);
  6094. return text;
  6095. }
  6096. };
  6097. python.Unpickler.StreamReader = class {
  6098. constructor(stream) {
  6099. this._stream = stream;
  6100. this._length = stream.length;
  6101. this._position = 0;
  6102. this._utf8Decoder = new TextDecoder('utf-8');
  6103. this._asciiDecoder = new TextDecoder('ascii');
  6104. }
  6105. get position() {
  6106. return this._position;
  6107. }
  6108. get length() {
  6109. return this._length;
  6110. }
  6111. seek(position) {
  6112. this._stream.seek(position);
  6113. this._position = this._stream.position;
  6114. }
  6115. skip(offset) {
  6116. this._position += offset;
  6117. if (this._position > this._length) {
  6118. throw new python.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6119. }
  6120. }
  6121. stream(length) {
  6122. this._stream.seek(this._position);
  6123. this.skip(length);
  6124. return this._stream.stream(length);
  6125. }
  6126. peek(length) {
  6127. this._stream.seek(this._position);
  6128. return this._stream.peek(length);
  6129. }
  6130. read(length) {
  6131. this._stream.seek(this._position);
  6132. this.skip(length);
  6133. return this._stream.read(length);
  6134. }
  6135. byte() {
  6136. const position = this._fill(1);
  6137. return this._view.getUint8(position);
  6138. }
  6139. uint16() {
  6140. const position = this._fill(2);
  6141. return this._view.getUint16(position, true);
  6142. }
  6143. int32() {
  6144. const position = this._fill(4);
  6145. return this._view.getInt32(position, true);
  6146. }
  6147. uint32() {
  6148. const position = this._fill(4);
  6149. return this._view.getUint32(position, true);
  6150. }
  6151. int64() {
  6152. const position = this._fill(8);
  6153. return this._view.getInt64(position, true).toNumber();
  6154. }
  6155. float64() {
  6156. const position = this._fill(8);
  6157. return this._view.getFloat64(position, true);
  6158. }
  6159. string(size, encoding) {
  6160. const data = this.read(size);
  6161. return (encoding == 'utf-8') ?
  6162. this._utf8Decoder.decode(data) :
  6163. this._asciiDecoder.decode(data);
  6164. }
  6165. line() {
  6166. let position = this._fill(0);
  6167. let index = this._buffer.indexOf(0x0A, position);
  6168. if (index == -1) {
  6169. const size = Math.min(0x1000000, this._stream.length - this._position);
  6170. this._fill(size);
  6171. this.skip(-size);
  6172. position = this._fill(0);
  6173. index = this._buffer.indexOf(0x0A, position);
  6174. if (index == -1) {
  6175. throw new python.Error("Could not find end of line.");
  6176. }
  6177. }
  6178. const size = index - position;
  6179. const text = this.string(size, 'ascii');
  6180. this.skip(1);
  6181. return text;
  6182. }
  6183. _fill(length) {
  6184. if (this._position + length > this._length) {
  6185. throw new Error('Expected ' + (this._position + length - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  6186. }
  6187. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  6188. this._offset = this._position;
  6189. this._stream.seek(this._offset);
  6190. this._buffer = this._stream.read(Math.min(0x10000000, this._length - this._offset));
  6191. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  6192. }
  6193. const position = this._position;
  6194. this._position += length;
  6195. return position - this._offset;
  6196. }
  6197. };
  6198. python.Error = class extends Error {
  6199. constructor(message) {
  6200. super(message);
  6201. this.name = 'Error loading Python module.';
  6202. }
  6203. };
  6204. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  6205. module.exports.Execution = python.Execution;
  6206. module.exports.Unpickler = python.Unpickler;
  6207. }