python.js 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214
  1. // Experimental Python parser
  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. if (!python.Parser._precedence) {
  8. python.Parser._precedence = {
  9. 'or': 2, 'and': 3, 'not' : 4,
  10. 'in': 5, 'instanceof': 5, 'is': 5, '<': 5, '>': 5, '<=': 5, '>=': 5, '<>': 5, '==': 5, '!=': 5,
  11. '|': 6, '^' : 7, '&' : 8,
  12. '<<': 9, '>>': 9, '+': 10, '-': 10, '*': 11, '@': 11, '/': 11, '//': 11, '%': 11,
  13. // '+': 12, '-': 12,
  14. '~': 13, '**': 14
  15. };
  16. }
  17. }
  18. parse() {
  19. const node = this._node('program');
  20. node.body = [];
  21. while (!this._tokenizer.match('eof')) {
  22. const statement = this._parseStatement();
  23. if (statement) {
  24. node.body.push(statement);
  25. continue;
  26. }
  27. if (this._tokenizer.eat('\n') || this._tokenizer.eat(';') || this._tokenizer.peek().type == 'eof') {
  28. continue;
  29. }
  30. if (this._tokenizer.eat('indent') && this._tokenizer.peek().type == 'eof') {
  31. continue;
  32. }
  33. throw new python.Error('Unsupported statement' + this._tokenizer.location());
  34. }
  35. return node;
  36. }
  37. _parseSuite() {
  38. const node = this._node('block');
  39. node.statements = [];
  40. let statement = null;
  41. if (this._tokenizer.eat('\n')) {
  42. if (this._tokenizer.eat('indent')) {
  43. while (!this._tokenizer.eat('eof') && !this._tokenizer.eat('dedent')) {
  44. if (this._tokenizer.eat(';')) {
  45. continue;
  46. }
  47. statement = this._parseStatement();
  48. if (statement) {
  49. node.statements.push(statement);
  50. continue;
  51. }
  52. if (this._tokenizer.eat('\n')) {
  53. continue;
  54. }
  55. if (this._tokenizer.match('dedent') || this._tokenizer.match('eof')) {
  56. continue;
  57. }
  58. throw new python.Error('Empty statement' + this._tokenizer.location());
  59. }
  60. }
  61. }
  62. else if (!this._tokenizer.eat('eof')) {
  63. while (!this._tokenizer.match('\n') && !this._tokenizer.match('eof') && !this._tokenizer.match('dedent')) {
  64. if (this._tokenizer.eat(';')) {
  65. continue;
  66. }
  67. statement = this._parseStatement();
  68. if (statement) {
  69. node.statements.push(statement);
  70. continue;
  71. }
  72. throw new python.Error('Empty statement' + this._tokenizer.location());
  73. }
  74. this._tokenizer.eat('\n');
  75. }
  76. return node;
  77. }
  78. _parseStatement() {
  79. let node = this._node();
  80. node = this._eat('id', 'break');
  81. if (node) {
  82. return node;
  83. }
  84. node = this._eat('id', 'continue');
  85. if (node) {
  86. return node;
  87. }
  88. node = this._eat('id', 'return');
  89. if (node) {
  90. node.expression = this._parseExpression(-1, [], true);
  91. return node;
  92. }
  93. node = this._eat('id', 'raise');
  94. if (node) {
  95. node.exception = this._parseExpression(-1, [ 'from' ]);
  96. if (this._tokenizer.eat('id', 'from')) {
  97. node.from = this._parseExpression();
  98. }
  99. else if (this._tokenizer.eat(',')) {
  100. node.exception = [ node.exception ];
  101. node.exception.push(this._parseExpression());
  102. if (this._tokenizer.eat(',')) {
  103. node.exception.push(this._parseExpression());
  104. }
  105. }
  106. return node;
  107. }
  108. node = this._eat('id', 'assert');
  109. if (node) {
  110. node.condition = this._parseExpression();
  111. while (this._tokenizer.eat(',')) {
  112. node.condition = { type: 'list', value: [ node.condition ] };
  113. node.condition.value.push(this._parseExpression());
  114. }
  115. return node;
  116. }
  117. node = this._eat('id', 'exec');
  118. if (node) {
  119. node.variable = this._parseExpression(-1, [ 'in' ]);
  120. if (this._tokenizer.eat('in')) {
  121. do {
  122. node.target = node.target || [];
  123. node.target.push(this._parseExpression(-1, [ 'in' ], false));
  124. }
  125. while (this._tokenizer.eat(','));
  126. }
  127. return node;
  128. }
  129. node = this._eat('id', 'global');
  130. if (node) {
  131. node.variable = [];
  132. do {
  133. node.variable.push(this._parseName());
  134. }
  135. while (this._tokenizer.eat(','));
  136. return node;
  137. }
  138. node = this._eat('id', 'nonlocal');
  139. if (node) {
  140. node.variable = [];
  141. do {
  142. node.variable.push(this._parseName());
  143. }
  144. while (this._tokenizer.eat(','));
  145. return node;
  146. }
  147. node = this._eat('id', 'import');
  148. if (node) {
  149. node.modules = [];
  150. do {
  151. const module = this._node('module');
  152. module.name = this._parseExpression(-1, [], false);
  153. if (this._tokenizer.eat('id', 'as')) {
  154. module.as = this._parseExpression(-1, [], false);
  155. }
  156. node.modules.push(module);
  157. }
  158. while (this._tokenizer.eat(','));
  159. return node;
  160. }
  161. node = this._eat('id', 'from');
  162. if (node) {
  163. const dots = this._tokenizer.peek();
  164. if (dots && Array.from(dots.type).every((c) => c == '.')) {
  165. node.from = this._eat(dots.type);
  166. node.from.expression = this._parseExpression();
  167. }
  168. else {
  169. node.from = this._parseExpression();
  170. }
  171. this._tokenizer.expect('id', 'import');
  172. node.import = [];
  173. const close = this._tokenizer.eat('(');
  174. do {
  175. const symbol = this._node();
  176. symbol.symbol = this._parseExpression(-1, [], false);
  177. if (this._tokenizer.eat('id', 'as')) {
  178. symbol.as = this._parseExpression(-1, [], false);
  179. }
  180. node.import.push(symbol);
  181. }
  182. while (this._tokenizer.eat(','));
  183. if (close) {
  184. this._tokenizer.expect(')');
  185. }
  186. return node;
  187. }
  188. node = this._eat('id', 'class');
  189. if (node) {
  190. node.name = this._parseName().value;
  191. if (this._tokenizer.peek().value === '(') {
  192. node.base = this._parseArguments();
  193. }
  194. this._tokenizer.expect(':');
  195. node.body = this._parseSuite();
  196. return node;
  197. }
  198. const async = this._eat('id', 'async');
  199. if (async &&
  200. !this._tokenizer.match('id', 'def') &&
  201. !this._tokenizer.match('id', 'with') &&
  202. !this._tokenizer.match('id', 'for')) {
  203. throw new python.Error("Expected 'def', 'with' or 'for'" + this._tokenizer.location());
  204. }
  205. node = this._eat('id', 'def');
  206. if (node) {
  207. if (async) {
  208. node.async = async;
  209. }
  210. node.name = this._parseName().value;
  211. this._tokenizer.expect('(');
  212. node.parameters = this._parseParameters(')');
  213. if (this._tokenizer.eat('->')) {
  214. node.returnType = this._parseType();
  215. }
  216. this._tokenizer.expect(':');
  217. node.body = this._parseSuite();
  218. return node;
  219. }
  220. node = this._eat('id', 'del');
  221. if (node) {
  222. node.expression = this._parseExpression(-1, [], true);
  223. return node;
  224. }
  225. node = this._eat('id', 'print');
  226. if (node) {
  227. node.expression = this._parseExpression(-1, [], true);
  228. return node;
  229. }
  230. node = this._eat('id', 'if');
  231. if (node) {
  232. node.condition = this._parseExpression();
  233. this._tokenizer.expect(':');
  234. node.then = this._parseSuite();
  235. let current = node;
  236. this._tokenizer.eat('\n');
  237. while (this._tokenizer.eat('id', 'elif')) {
  238. current.else = this._node('if');
  239. current = current.else;
  240. current.condition = this._parseExpression();
  241. this._tokenizer.expect(':');
  242. current.then = this._parseSuite();
  243. this._tokenizer.eat('\n');
  244. }
  245. if (this._tokenizer.eat('id', 'else')) {
  246. this._tokenizer.expect(':');
  247. current.else = this._parseSuite();
  248. }
  249. return node;
  250. }
  251. node = this._eat('id', 'while');
  252. if (node) {
  253. node.condition = this._parseExpression();
  254. this._tokenizer.expect(':');
  255. node.body = this._parseSuite();
  256. if (this._tokenizer.eat('id', 'else')) {
  257. this._tokenizer.expect(':');
  258. node.else = this._parseSuite();
  259. }
  260. return node;
  261. }
  262. node = this._eat('id', 'pass');
  263. if (node) {
  264. return node;
  265. }
  266. node = this._eat('id', 'for');
  267. if (node) {
  268. node.variable = [];
  269. node.variable.push(this._parseExpression(-1, [ 'in' ]));
  270. while (this._tokenizer.eat(',')) {
  271. if (this._tokenizer.match('id', 'in')) {
  272. node.variable.push({});
  273. break;
  274. }
  275. node.variable.push(this._parseExpression(-1, [ 'in' ]));
  276. }
  277. this._tokenizer.expect('id', 'in');
  278. node.target = [];
  279. node.target.push(this._parseExpression());
  280. while (this._tokenizer.eat(',')) {
  281. if (this._tokenizer.match(':')) {
  282. node.target.push({});
  283. break;
  284. }
  285. node.target.push(this._parseExpression(-1, [ 'in' ]));
  286. }
  287. this._tokenizer.expect(':');
  288. node.body = this._parseSuite();
  289. if (this._tokenizer.eat('id', 'else')) {
  290. this._tokenizer.expect(':');
  291. node.else = this._parseSuite();
  292. }
  293. return node;
  294. }
  295. node = this._eat('id', 'with');
  296. if (node) {
  297. if (async) {
  298. node.async = async;
  299. }
  300. node.item = [];
  301. do {
  302. const item = this._node();
  303. item.type = 'with_item';
  304. item.expression = this._parseExpression();
  305. if (this._tokenizer.eat('id', 'as')) {
  306. item.variable = this._parseExpression();
  307. }
  308. node.item.push(item);
  309. }
  310. while (this._tokenizer.eat(','));
  311. this._tokenizer.expect(':');
  312. node.body = this._parseSuite();
  313. return node;
  314. }
  315. node = this._eat('id', 'try');
  316. if (node) {
  317. this._tokenizer.expect(':');
  318. node.body = this._parseSuite();
  319. node.except = [];
  320. while (this._tokenizer.match('id', 'except')) {
  321. const except = this._node('except');
  322. this._tokenizer.expect('id', 'except');
  323. except.clause = [];
  324. except.clause.push(this._parseExpression());
  325. while (this._tokenizer.eat(',')) {
  326. if (this._tokenizer.match(':') || this._tokenizer.match('as')) {
  327. except.clause.push({});
  328. break;
  329. }
  330. except.clause.push(this._parseExpression());
  331. }
  332. if (this._tokenizer.eat('id', 'as')) {
  333. except.variable = this._parseExpression();
  334. }
  335. this._tokenizer.expect(':');
  336. except.body = this._parseSuite();
  337. node.except.push(except);
  338. }
  339. if (this._tokenizer.match('id', 'else')) {
  340. node.else = this._node('else');
  341. this._tokenizer.expect('id', 'else');
  342. this._tokenizer.expect(':');
  343. node.else.body = this._parseSuite();
  344. }
  345. if (this._tokenizer.match('id', 'finally')) {
  346. node.finally = this._node('finally');
  347. this._tokenizer.expect('id', 'finally');
  348. this._tokenizer.expect(':');
  349. node.finally.body = this._parseSuite();
  350. }
  351. return node;
  352. }
  353. if (this._tokenizer.match('@')) {
  354. node = this._node('decorator');
  355. this._tokenizer.expect('@');
  356. node.value = this._parseExpression();
  357. if (!node.value || (node.value.type !== 'call' && node.value.type !== 'id' && node.value.type !== '.')) {
  358. throw new python.Error('Invalid decorator' + this._tokenizer.location());
  359. }
  360. return node;
  361. }
  362. const expression = this._parseExpression(-1, [], true);
  363. if (expression) {
  364. if (expression.type == 'id' && this._tokenizer.eat(':')) {
  365. node = this._node('var');
  366. node.name = expression.value;
  367. node.location = expression.location;
  368. node.variableType = this._parseExpression(-1, [ '=' ]);
  369. if (this._tokenizer.eat('=')) {
  370. node.initializer = this._parseExpression();
  371. }
  372. return node;
  373. }
  374. switch (expression.type) {
  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 '...':
  400. case 'call':
  401. case 'assert':
  402. case 'raise':
  403. case 'string':
  404. case 'list':
  405. case 'var':
  406. case '.':
  407. case '[]':
  408. case 'yield':
  409. case '+':
  410. case '-':
  411. case '*':
  412. case '**':
  413. case '@':
  414. case '/':
  415. case '//':
  416. case '~':
  417. case '&':
  418. case '^':
  419. case '|':
  420. case 'not':
  421. case 'id':
  422. case 'number':
  423. case 'in':
  424. case 'and':
  425. case 'or':
  426. case 'if':
  427. case 'for':
  428. case 'tuple':
  429. case 'lambda':
  430. case 'await':
  431. return expression;
  432. default:
  433. throw new python.Error("Unhandled expression" + this._tokenizer.location());
  434. }
  435. }
  436. return null;
  437. }
  438. _parseExpression(minPrecedence, terminal, tuple) {
  439. minPrecedence = minPrecedence || -1;
  440. const terminalSet = new Set(terminal);
  441. const stack = [];
  442. for (;;) {
  443. let node = this._node();
  444. const token = this._tokenizer.peek();
  445. if (stack.length == 1 && terminalSet.has(token.value)) {
  446. break;
  447. }
  448. const precedence = python.Parser._precedence[token.value];
  449. if (precedence) {
  450. if (precedence >= minPrecedence) {
  451. this._tokenizer.read();
  452. node.type = token.value;
  453. if (token.type == 'id' && (token.value === 'in' || token.value === 'not')) {
  454. if (token.value === 'in') {
  455. node.type = 'in';
  456. }
  457. else if (this._tokenizer.eat('id', 'in')) {
  458. node.type = 'not in';
  459. }
  460. else {
  461. node.type = 'not';
  462. node.expression = this._parseExpression(precedence, terminal, tuple === false ? false : true);
  463. stack.push(node);
  464. continue;
  465. }
  466. }
  467. else if (token.value == '~') {
  468. node.type = '~';
  469. node.expression = this._parseExpression(precedence, terminal, tuple === false ? false : true);
  470. stack.push(node);
  471. continue;
  472. }
  473. else if (token.type == 'id' && token.value == 'is') {
  474. if (this._tokenizer.eat('id', 'not')) {
  475. node.type = 'is not';
  476. }
  477. }
  478. node.left = stack.pop();
  479. node.right = this._parseExpression(precedence, terminal, tuple === false ? false : true);
  480. stack.push(node);
  481. continue;
  482. }
  483. }
  484. if (this._tokenizer.eat(':=')) {
  485. node.type = ':=';
  486. node.target = stack.pop();
  487. node.expression = this._parseExpression(-1, terminal, tuple === false ? false : true);
  488. stack.push(node);
  489. continue;
  490. }
  491. if (this._tokenizer.eat('=')) {
  492. node.type = '=';
  493. node.target = stack.pop();
  494. node.expression = this._parseExpression(-1, terminal, tuple === false ? false : true);
  495. stack.push(node);
  496. continue;
  497. }
  498. switch (token.type) {
  499. case '-=':
  500. case '**=':
  501. case '*=':
  502. case '//=':
  503. case '/=':
  504. case '&=':
  505. case '%=':
  506. case '^=':
  507. case '+=':
  508. case '<<=':
  509. case '>>=':
  510. case '|=':
  511. case '@=':
  512. node = this._node(token.type);
  513. this._tokenizer.expect(token.type);
  514. node.target = stack.pop();
  515. node.expression = this._parseExpression(-1, terminal, true);
  516. stack.push(node);
  517. continue;
  518. default:
  519. break;
  520. }
  521. node = this._eat('id', 'if');
  522. if (node) {
  523. node.then = stack.pop();
  524. node.condition = this._parseExpression();
  525. this._tokenizer.expect('id', 'else');
  526. node.else = this._parseExpression();
  527. stack.push(node);
  528. continue;
  529. }
  530. while (this._tokenizer.match('id', 'for') || this._tokenizer.match('id', 'async')) {
  531. const async = this._eat('id', 'async');
  532. if (async && !this._tokenizer.match('id', 'for')) {
  533. throw new python.Error("Expected 'for'" + this._tokenizer.location());
  534. }
  535. node = this._eat('id', 'for');
  536. if (node) {
  537. if (async) {
  538. node.async = async;
  539. }
  540. node.expression = stack.pop();
  541. node.variable = this._parseExpression(-1, [ 'in' ], true);
  542. this._tokenizer.expect('id', 'in');
  543. node.target = this._parseExpression(-1, [ 'for', 'if' ], true);
  544. while (this._tokenizer.eat('id', 'if')) {
  545. node.condition = node.condition || [];
  546. node.condition.push(this._parseExpression(-1, [ 'for', 'if' ]));
  547. }
  548. stack.push(node);
  549. }
  550. }
  551. node = this._eat('id', 'lambda');
  552. if (node) {
  553. node.parameters = this._parseParameters(':');
  554. node.body = this._parseExpression(-1, terminal, false);
  555. stack.push(node);
  556. continue;
  557. }
  558. node = this._eat('id', 'yield');
  559. if (node) {
  560. if (this._tokenizer.eat('id', 'from')) {
  561. node.from = this._parseExpression(-1, [], true);
  562. }
  563. else {
  564. node.expression = [];
  565. do {
  566. node.expression.push(this._parseExpression(-1, [], false));
  567. }
  568. while (this._tokenizer.eat(','));
  569. }
  570. stack.push(node);
  571. continue;
  572. }
  573. node = this._eat('id', 'await');
  574. if (node) {
  575. node.expression = this._parseExpression(minPrecedence, terminal, tuple);
  576. stack.push(node);
  577. continue;
  578. }
  579. node = this._eat('.');
  580. if (node) {
  581. this._tokenizer.eat('\n');
  582. node.target = stack.pop();
  583. node.member = this._parseName();
  584. stack.push(node);
  585. continue;
  586. }
  587. if (this._tokenizer.peek().value === '(') {
  588. if (stack.length == 0) {
  589. node = this._node('tuple');
  590. const args = this._parseArguments();
  591. if (args.length == 1) {
  592. stack.push(args[0]);
  593. }
  594. else {
  595. node.value = args;
  596. stack.push(node);
  597. }
  598. }
  599. else {
  600. node = this._node('call');
  601. node.target = stack.pop();
  602. node.arguments = this._parseArguments();
  603. stack.push(node);
  604. }
  605. continue;
  606. }
  607. if (this._tokenizer.peek().value === '[') {
  608. if (stack.length == 0) {
  609. stack.push(this._parseExpressions());
  610. }
  611. else {
  612. node = this._node('[]');
  613. node.target = stack.pop();
  614. node.arguments = this._parseSlice();
  615. stack.push(node);
  616. }
  617. continue;
  618. }
  619. if (this._tokenizer.peek().value == '{') {
  620. stack.push(this._parseDictOrSetMaker());
  621. continue;
  622. }
  623. node = this._node();
  624. const literal = this._parseLiteral();
  625. if (literal) {
  626. if (stack.length > 0 && literal.type == 'number' &&
  627. (literal.value.startsWith('-') || literal.value.startsWith('+'))) {
  628. node.type = literal.value.substring(0, 1);
  629. literal.value = literal.value.substring(1);
  630. node.left = stack.pop();
  631. node.right = literal;
  632. stack.push(node);
  633. }
  634. else if (stack.length == 1 && literal.type == 'string' && stack[0].type == 'string') {
  635. stack[0].value += literal.value;
  636. }
  637. else {
  638. if (literal.type === 'number') {
  639. switch (literal.value) {
  640. case 'inf': literal.value = Infinity; break;
  641. case '-inf': literal.value = -Infinity; break;
  642. default: break;
  643. }
  644. }
  645. stack.push(literal);
  646. }
  647. continue;
  648. }
  649. if (this._tokenizer.peek().keyword) {
  650. break;
  651. }
  652. node = this._eat('...');
  653. if (node) {
  654. stack.push(node);
  655. continue;
  656. }
  657. const identifier = this._parseName();
  658. if (identifier) {
  659. stack.push(identifier);
  660. continue;
  661. }
  662. if (tuple === true && stack.length == 1 && this._tokenizer.eat(',')) {
  663. if (stack[0].type === 'tuple') {
  664. node = stack[0];
  665. }
  666. else {
  667. node = this._node('tuple');
  668. node.value = [ stack.pop() ];
  669. stack.push(node);
  670. }
  671. // for, bar, = <expr>
  672. if (this._tokenizer.peek().value === '=') {
  673. continue;
  674. }
  675. if (!this._tokenizer.match('=') && !terminalSet.has(this._tokenizer.peek().value)) {
  676. const nextTerminal = terminal.slice(0).concat([ ',', '=' ]);
  677. const expression = this._parseExpression(minPrecedence, nextTerminal, tuple);
  678. if (expression) {
  679. node.value.push(expression);
  680. continue;
  681. }
  682. }
  683. break;
  684. }
  685. break;
  686. }
  687. if (stack.length == 1) {
  688. return stack.pop();
  689. }
  690. if (stack.length != 0) {
  691. throw new python.Error('Unexpected expression' + this._tokenizer.location());
  692. }
  693. return null;
  694. }
  695. _parseDictOrSetMaker() {
  696. const list = [];
  697. this._tokenizer.expect('{');
  698. let dict = true;
  699. while (!this._tokenizer.eat('}')) {
  700. const item = this._parseExpression(-1, [], false);
  701. if (item == null) {
  702. throw new python.Error('Expected expression' + this._tokenizer.location());
  703. }
  704. if (!this._tokenizer.eat(':')) {
  705. dict = false;
  706. }
  707. if (dict) {
  708. const value = this._parseExpression(-1, [], false);
  709. if (value == null) {
  710. throw new python.Error('Expected expression' + this._tokenizer.location());
  711. }
  712. list.push({ type: 'pair', key: item, value: value });
  713. }
  714. else {
  715. list.push(item);
  716. }
  717. this._tokenizer.eat(',');
  718. this._tokenizer.eat('\n');
  719. if (this._tokenizer.eat('}')) {
  720. break;
  721. }
  722. }
  723. if (dict) {
  724. return { type: 'dict', value: list };
  725. }
  726. return { type: 'set', value: list };
  727. }
  728. _parseExpressions() {
  729. const list = [];
  730. this._tokenizer.expect('[');
  731. while (!this._tokenizer.eat(']')) {
  732. const expression = this._parseExpression();
  733. if (expression == null) {
  734. throw new python.Error('Expected expression' + this._tokenizer.location());
  735. }
  736. list.push(expression);
  737. this._tokenizer.eat(',');
  738. while (this._tokenizer.eat('\n')) {
  739. // continue
  740. }
  741. if (this._tokenizer.eat(']')) {
  742. break;
  743. }
  744. }
  745. return { type: 'list', value: list };
  746. }
  747. _parseSlice() {
  748. let node = { type: '::' };
  749. let list = [];
  750. const group = [ 'start', 'stop', 'step' ];
  751. this._tokenizer.expect('[');
  752. while (!this._tokenizer.eat(']')) {
  753. if (this._tokenizer.eat(':')) {
  754. node[group.shift()] = { type: 'list', value: list };
  755. list = [];
  756. continue;
  757. }
  758. if (this._tokenizer.eat(',')) {
  759. // list.push({});
  760. continue;
  761. }
  762. if (this._tokenizer.peek().value != ']') {
  763. const expression = this._parseExpression();
  764. if (expression == null) {
  765. throw new python.Error('Expected expression' + this._tokenizer.location());
  766. }
  767. list.push(expression);
  768. }
  769. }
  770. if (list.length > 0) {
  771. node[group.shift()] = { type: 'list', value: list };
  772. }
  773. if (node.start && !node.stop && !node.step) {
  774. node = node.start;
  775. }
  776. return node;
  777. }
  778. _parseName() {
  779. const token = this._tokenizer.peek();
  780. if (token.type == 'id' && !token.keyword) {
  781. this._tokenizer.read();
  782. return token;
  783. }
  784. return null;
  785. }
  786. _parseLiteral() {
  787. const token = this._tokenizer.peek();
  788. if (token.type == 'string' || token.type == 'number' || token.type == 'boolean') {
  789. this._tokenizer.read();
  790. return token;
  791. }
  792. return null;
  793. }
  794. _parseTypeArguments() {
  795. const list = [];
  796. this._tokenizer.expect('[');
  797. while (!this._tokenizer.eat(']')) {
  798. const type = this._parseType();
  799. if (type == null) {
  800. throw new python.Error('Expected type ' + this._tokenizer.location());
  801. }
  802. list.push(type);
  803. if (!this._tokenizer.eat(',')) {
  804. this._tokenizer.expect(']');
  805. break;
  806. }
  807. }
  808. return list;
  809. }
  810. _parseType() {
  811. const type = this._node();
  812. type.type = 'type';
  813. type.name = this._parseExpression(-1, [ '[', '=' ]);
  814. if (type.name) {
  815. if (this._tokenizer.peek().value === '[') {
  816. type.arguments = this._parseTypeArguments();
  817. }
  818. return type;
  819. }
  820. return null;
  821. }
  822. _parseParameter(terminal) {
  823. const node = this._node('parameter');
  824. if (this._tokenizer.eat('/')) {
  825. node.name = '/';
  826. return node;
  827. }
  828. if (this._tokenizer.eat('**')) {
  829. node.parameterType = '**';
  830. }
  831. if (this._tokenizer.eat('*')) {
  832. node.parameterType = '*';
  833. }
  834. const identifier = this._parseName();
  835. if (identifier !== null) {
  836. node.name = identifier.value;
  837. if (terminal !== ':' && this._tokenizer.eat(':')) {
  838. node.parameterType = this._parseType();
  839. }
  840. if (this._tokenizer.eat('=')) {
  841. node.initializer = this._parseExpression();
  842. }
  843. return node;
  844. }
  845. return null;
  846. }
  847. _parseParameters(terminal) {
  848. const list = [];
  849. while (!this._tokenizer.eat(terminal)) {
  850. this._tokenizer.eat('\n');
  851. if (this._tokenizer.eat('(')) {
  852. list.push(this._parseParameters(')'));
  853. }
  854. else {
  855. list.push(this._parseParameter(terminal));
  856. }
  857. this._tokenizer.eat('\n');
  858. if (!this._tokenizer.eat(',')) {
  859. this._tokenizer.expect(terminal);
  860. break;
  861. }
  862. }
  863. return list;
  864. }
  865. _parseArguments() {
  866. const list = [];
  867. this._tokenizer.expect('(');
  868. while (!this._tokenizer.eat(')')) {
  869. if (this._tokenizer.eat('\n')) {
  870. continue;
  871. }
  872. const expression = this._parseExpression(-1, [], false);
  873. if (expression == null) {
  874. throw new python.Error('Expected expression ' + this._tokenizer.location());
  875. }
  876. list.push(expression);
  877. if (!this._tokenizer.eat(',')) {
  878. this._tokenizer.eat('\n');
  879. this._tokenizer.expect(')');
  880. break;
  881. }
  882. }
  883. return list;
  884. }
  885. _node(type) {
  886. const node = {};
  887. node.location = this._tokenizer.location();
  888. if (type) {
  889. node.type = type;
  890. }
  891. return node;
  892. }
  893. _eat(type, value) {
  894. if (this._tokenizer.match(type, value)) {
  895. const node = this._node(type === 'id' ? value : type);
  896. this._tokenizer.expect(type, value);
  897. return node;
  898. }
  899. return null;
  900. }
  901. };
  902. python.Tokenizer = class {
  903. constructor(text, file) {
  904. this._text = text;
  905. this._file = file;
  906. this._position = 0;
  907. this._lineStart = 0;
  908. this._line = 0;
  909. this._token = { type: '', value: '' };
  910. this._brackets = 0;
  911. this._indentation = [];
  912. this._outdent = 0;
  913. if (!python.Tokenizer._whitespace) {
  914. python.Tokenizer._whitespace = new RegExp('[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]');
  915. 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';
  916. 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';
  917. python.Tokenizer._identifierStart = new RegExp('[' + identifierStartChars + ']');
  918. /* eslint-disable */
  919. python.Tokenizer._identifierChar = new RegExp('[' + identifierStartChars + identifierChars + ']');
  920. /* eslint-enable */
  921. }
  922. }
  923. peek() {
  924. if (!this._cache) {
  925. this._token = this._tokenize(this._token);
  926. this._cache = true;
  927. }
  928. return this._token;
  929. }
  930. read() {
  931. if (!this._cache) {
  932. this._token = this._tokenize(this._token);
  933. }
  934. const next = this._position + this._token.value.length;
  935. while (this._position < next) {
  936. if (python.Tokenizer._isNewline(this._get(this._position))) {
  937. this._position = this._newLine(this._position);
  938. this._lineStart = this._position;
  939. this._line++;
  940. }
  941. else {
  942. this._position++;
  943. }
  944. }
  945. this._cache = false;
  946. return this._token;
  947. }
  948. match(type, value) {
  949. const token = this.peek();
  950. if (token.type === type && (!value || token.value === value)) {
  951. return true;
  952. }
  953. return false;
  954. }
  955. eat(type, value) {
  956. const token = this.peek();
  957. if (token.type === type && (!value || token.value === value)) {
  958. this.read();
  959. return true;
  960. }
  961. return false;
  962. }
  963. expect(type, value) {
  964. const token = this.peek();
  965. if (token.type !== type) {
  966. throw new python.Error("Unexpected '" + token.value + "' instead of '" + type + "'" + this.location());
  967. }
  968. if (value && token.value !== value) {
  969. throw new python.Error("Unexpected '" + token.value + "' instead of '" + value + "'" + this.location());
  970. }
  971. this.read();
  972. }
  973. location() {
  974. return ' at ' + this._file + ':' + (this._line + 1).toString() + ':' + (this._position - this._lineStart + 1).toString();
  975. }
  976. static _isSpace(c) {
  977. switch (c) {
  978. case ' ':
  979. case '\t':
  980. case '\v': // 11
  981. case '\f': // 12
  982. case '\xA0': // 160
  983. return true;
  984. default:
  985. if (c.charCodeAt(0) >= 0x1680) {
  986. return python.Tokenizer._whitespace.test(c);
  987. }
  988. return false;
  989. }
  990. }
  991. static _isNewline(c) {
  992. switch(c) {
  993. case '\n':
  994. case '\r':
  995. case '\u2028': // 8232
  996. case '\u2029': // 8233
  997. return true;
  998. default:
  999. return false;
  1000. }
  1001. }
  1002. static _isIdentifierStartChar(c) {
  1003. if (c < 'A') {
  1004. return c === '$';
  1005. }
  1006. if (c <= 'Z') {
  1007. return true;
  1008. }
  1009. if (c < 'a') {
  1010. return c === '_';
  1011. }
  1012. if (c <= 'z') {
  1013. return true;
  1014. }
  1015. const code = c.charCodeAt(0);
  1016. if (code >= 0xAA) {
  1017. return python.Tokenizer._identifierStart.test(c);
  1018. }
  1019. return false;
  1020. }
  1021. static _isIdentifierChar(c) {
  1022. if (c < '0') {
  1023. return c === '$';
  1024. }
  1025. if (c <= '9') {
  1026. return true;
  1027. }
  1028. if (c < 'A') {
  1029. return false;
  1030. }
  1031. if (c <= 'Z') {
  1032. return true;
  1033. }
  1034. if (c < 'a') {
  1035. return c === '_';
  1036. }
  1037. if (c <= 'z') {
  1038. return true;
  1039. }
  1040. const code = c.charCodeAt(0);
  1041. if (code >= 0xAA) {
  1042. return python.Tokenizer._identifierChar.test(c);
  1043. }
  1044. return false;
  1045. }
  1046. static _isDecimal(c) {
  1047. return c >= '0' && c <= '9' || c === '_';
  1048. }
  1049. static _isHex(c) {
  1050. return python.Tokenizer._isDecimal(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || c === '_';
  1051. }
  1052. static _isOctal(c) {
  1053. return c >= '0' && c <= '7' || c === '_';
  1054. }
  1055. static _isBinary(c) {
  1056. return c === '0' || c === '1' || c === '_';
  1057. }
  1058. _get(position) {
  1059. return position >= this._text.length ? '\0' : this._text[position];
  1060. }
  1061. _skipLine() {
  1062. while (this._position < this._text.length) {
  1063. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1064. break;
  1065. }
  1066. this._position++;
  1067. }
  1068. }
  1069. _skipWhitespace() {
  1070. while (this._position < this._text.length) {
  1071. const c = this._text[this._position];
  1072. if (c == '#') {
  1073. this._skipLine();
  1074. }
  1075. else if (python.Tokenizer._isSpace(c)) {
  1076. this._position++;
  1077. }
  1078. else if (c == '\\') {
  1079. // Explicit Line Continuation
  1080. this._position++;
  1081. if (python.Tokenizer._isNewline(this._get(this._position))) {
  1082. this._position = this._newLine(this._position);
  1083. this._lineStart = this._position;
  1084. this._line++;
  1085. }
  1086. else {
  1087. throw new python.Error("Unexpected '" + this._text[this._position] + "' after line continuation" + this.location());
  1088. }
  1089. }
  1090. else if (this._brackets > 0 && python.Tokenizer._isNewline(c)) {
  1091. // Implicit Line Continuation
  1092. this._position = this._newLine(this._position);
  1093. this._lineStart = this._position;
  1094. this._line++;
  1095. }
  1096. else {
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. _newLine(position) {
  1102. if ((this._get(position) === '\n' && this._get(position + 1) === '\r') ||
  1103. (this._get(position) === '\r' && this._get(position + 1) === '\n')) {
  1104. return position + 2;
  1105. }
  1106. return position + 1;
  1107. }
  1108. _tokenize(token) {
  1109. if (this._token.type !== '\n') {
  1110. this._skipWhitespace();
  1111. }
  1112. if (this._token.type === 'dedent') {
  1113. this._indentation.pop();
  1114. this._outdent--;
  1115. if (this._outdent > 0) {
  1116. return { type: 'dedent', value: '' };
  1117. }
  1118. }
  1119. if (token.type == '\n') {
  1120. let indent = '';
  1121. let i = this._position;
  1122. while (i < this._text.length) {
  1123. const c = this._text[i];
  1124. if (python.Tokenizer._isSpace(c)) {
  1125. indent += c;
  1126. i++;
  1127. }
  1128. else if (python.Tokenizer._isNewline(c)) {
  1129. indent = '';
  1130. i = this._newLine(i);
  1131. this._position = i;
  1132. this._lineStart = i;
  1133. this._line++;
  1134. }
  1135. else if (c == '#') {
  1136. indent = '';
  1137. while (i < this._text.length && !python.Tokenizer._isNewline(this._text[i])) {
  1138. i++;
  1139. }
  1140. continue;
  1141. }
  1142. else {
  1143. break;
  1144. }
  1145. }
  1146. let type = null;
  1147. if (indent.length > 0) {
  1148. const current = this._indentation.length > 0 ? this._indentation[this._indentation.length - 1] : '';
  1149. if (indent.length > current.length) {
  1150. type = 'indent';
  1151. this._indentation.push(indent);
  1152. }
  1153. else if (indent.length > 0 && indent.length < current.length) {
  1154. type = 'dedent';
  1155. this._outdent = 0;
  1156. for (let j = this._indentation.length - 1; j >= 0 && indent.length < this._indentation[j].length; j--) {
  1157. this._outdent++;
  1158. }
  1159. }
  1160. else {
  1161. this._position += indent.length;
  1162. }
  1163. }
  1164. else if (i >= this._text.length) {
  1165. return { type: 'eof', value: '' };
  1166. }
  1167. else if (this._indentation.length > 0) {
  1168. type = 'dedent';
  1169. this._outdent = this._indentation.length;
  1170. }
  1171. if (type === 'indent' || type === 'dedent') {
  1172. return { type: type, value: indent };
  1173. }
  1174. }
  1175. if (this._position >= this._text.length) {
  1176. return { type: 'eof', value: '' };
  1177. }
  1178. const c = this._get(this._position);
  1179. const string = this._string();
  1180. if (string) {
  1181. return string;
  1182. }
  1183. switch (c) {
  1184. case '(':
  1185. case '[':
  1186. case '{':
  1187. this._brackets++;
  1188. return { type: c, value: c };
  1189. case ')':
  1190. case ']':
  1191. case '}':
  1192. if (this._brackets === 0) {
  1193. throw new python.Error("Unexpected '" + c + "'" + this.location);
  1194. }
  1195. this._brackets--;
  1196. return { type: c, value: c };
  1197. case ',':
  1198. case ';':
  1199. case '?':
  1200. return { type: c, value: c };
  1201. default: {
  1202. const number = this._number();
  1203. if (number) {
  1204. return number;
  1205. }
  1206. if (c === '.') {
  1207. let end = this._position + 1;
  1208. while (this._get(end) === '.') {
  1209. end++;
  1210. }
  1211. const text = this._text.substring(this._position, end);
  1212. return { type: text, value: text };
  1213. }
  1214. const identifier = this._identifier();
  1215. if (identifier) {
  1216. return identifier;
  1217. }
  1218. const operator = this._operator();
  1219. if (operator) {
  1220. return operator;
  1221. }
  1222. break;
  1223. }
  1224. }
  1225. if (c === '.') {
  1226. return { type: c, value: c };
  1227. }
  1228. if (c === '\\') {
  1229. return { type: '\\', value: c };
  1230. }
  1231. if (python.Tokenizer._isNewline(c)) {
  1232. return { type: '\n', value: this._text.substring(this._position, this._newLine(this._position)) };
  1233. }
  1234. throw new python.Error("Unexpected token '" + c + "'" + this.location());
  1235. }
  1236. _number() {
  1237. let c = this._get(this._position);
  1238. const sign = (c === '-' || c === '+') ? 1 : 0;
  1239. let i = this._position + sign;
  1240. c = this._get(i);
  1241. if (c === '0') {
  1242. let radix = 0;
  1243. const n = this._get(i + 1);
  1244. if ((n === 'x' || n === 'X') && python.Tokenizer._isHex(this._get(i + 2))) {
  1245. i += 2;
  1246. while (python.Tokenizer._isHex(this._get(i))) {
  1247. i += 1;
  1248. }
  1249. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1250. i += 1;
  1251. }
  1252. radix = 16;
  1253. }
  1254. else if ((n === 'b' || n === 'B') && python.Tokenizer._isBinary(this._get(i + 2))) {
  1255. i += 2;
  1256. while (python.Tokenizer._isBinary(this._get(i))) {
  1257. i++;
  1258. }
  1259. radix = 2;
  1260. }
  1261. else if ((n === 'o' || n === 'O') && python.Tokenizer._isOctal(this._get(i + 2))) {
  1262. i += 2;
  1263. while (python.Tokenizer._isOctal(this._get(i))) {
  1264. i++;
  1265. }
  1266. radix = 8;
  1267. }
  1268. else if (n >= '0' && n <= '7') {
  1269. i++;
  1270. while (python.Tokenizer._isOctal(this._get(i))) {
  1271. i += 1;
  1272. }
  1273. if (this._get(i) === 'l' || this._get(i) === 'L') {
  1274. i += 1;
  1275. }
  1276. radix = 8;
  1277. }
  1278. if (radix > 0 && this._get(i) !== '.') {
  1279. const radixText = this._text.substring(this._position, i);
  1280. const radixParseText = radixText.indexOf('_') !== -1 ? radixText.split('_').join('') : radixText;
  1281. if (!isNaN(parseInt(radixParseText, radix))) {
  1282. return { type: 'number', value: radixText };
  1283. }
  1284. }
  1285. }
  1286. i = this._position + sign;
  1287. let decimal = false;
  1288. if (this._get(i) >= '1' && this._get(i) <= '9') {
  1289. while (python.Tokenizer._isDecimal(this._get(i))) {
  1290. i++;
  1291. }
  1292. c = this._get(i).toLowerCase();
  1293. decimal = c !== '.' && c !== 'e';
  1294. }
  1295. if (this._get(i) === '0') {
  1296. i++;
  1297. c = this._get(i).toLowerCase();
  1298. decimal = !python.Tokenizer._isDecimal(c) && c !== '.' && c !== 'e' && c !== 'j';
  1299. }
  1300. if (decimal) {
  1301. if (this._get(i) === 'j' || this._get(i) === 'J' || this._get(i) === 'l' || this._get(i) === 'L') {
  1302. return { 'type': 'number', value: this._text.substring(this._position, i + 1) };
  1303. }
  1304. const intText = this._text.substring(this._position, i);
  1305. if (!isNaN(parseInt(intText, 10))) {
  1306. return { type: 'number', value: intText };
  1307. }
  1308. }
  1309. i = this._position + sign;
  1310. if ((this._get(i) >= '0' && this._get(i) <= '9') ||
  1311. (this._get(i) === '.' && this._get(i + 1) >= '0' && this._get(i + 1) <= '9')) {
  1312. while (python.Tokenizer._isDecimal(this._get(i))) {
  1313. i++;
  1314. }
  1315. if (this._get(i) === '.') {
  1316. i++;
  1317. }
  1318. while (python.Tokenizer._isDecimal(this._get(i))) {
  1319. i++;
  1320. }
  1321. if (i > (this._position + sign)) {
  1322. if (this._get(i) === 'e' || this._get(i) === 'E') {
  1323. i++;
  1324. if (this._get(i) == '-' || this._get(i) == '+') {
  1325. i++;
  1326. }
  1327. if (!python.Tokenizer._isDecimal(this._get(i))) {
  1328. i = this._position;
  1329. }
  1330. else {
  1331. while (python.Tokenizer._isDecimal(this._get(i))) {
  1332. i++;
  1333. }
  1334. }
  1335. }
  1336. else {
  1337. while (python.Tokenizer._isDecimal(this._get(i))) {
  1338. i++;
  1339. }
  1340. }
  1341. }
  1342. if (i > (this._position + sign)) {
  1343. if (this._get(i) === 'j' || this._get(i) === 'J') {
  1344. return { type: 'number', value: this._text.substring(this._position, i + 1) };
  1345. }
  1346. const floatText = this._text.substring(this._position, i);
  1347. const floatParseText = floatText.indexOf('_') != -1 ? floatText.split('_').join('') : floatText;
  1348. if (!isNaN(parseFloat(floatParseText))) {
  1349. return { type: 'number', value: floatText };
  1350. }
  1351. }
  1352. }
  1353. i = this._position + sign;
  1354. if (this._get(i) === 'i' && this._get(i + 1) === 'n' && this._get(i + 2) === 'f' && !python.Tokenizer._isIdentifierChar(this._get(i + 3))) {
  1355. return { type: 'number', value: this._text.substring(this._position, i + 3) };
  1356. }
  1357. return null;
  1358. }
  1359. _identifier() {
  1360. let i = this._position;
  1361. if (python.Tokenizer._isIdentifierStartChar(this._get(i))) {
  1362. i++;
  1363. while (python.Tokenizer._isIdentifierChar(this._get(i))) {
  1364. i++;
  1365. }
  1366. }
  1367. if (i > this._position) {
  1368. const text = this._text.substring(this._position, i);
  1369. return { type: 'id', value: text, keyword: python.Tokenizer._isKeyword(text) };
  1370. }
  1371. return null;
  1372. }
  1373. _operator() {
  1374. let length = 0;
  1375. const c0 = this._get(this._position);
  1376. const c1 = this._get(this._position + 1);
  1377. const c2 = this._get(this._position + 2);
  1378. switch (c0) {
  1379. case '+':
  1380. case '&':
  1381. case '|':
  1382. case '^':
  1383. case '=':
  1384. case '!':
  1385. case '%':
  1386. case '~':
  1387. length = c1 === '=' ? 2 : 1;
  1388. break;
  1389. case '-':
  1390. length = c1 === '=' || c1 === '>' ? 2 : 1;
  1391. break;
  1392. case '*':
  1393. if (c1 === '*') {
  1394. length = c2 === '=' ? 3 : 2;
  1395. }
  1396. else {
  1397. length = c1 === '=' ? 2 : 1;
  1398. }
  1399. break;
  1400. case '/':
  1401. if (c1 === '/') {
  1402. length = c2 === '=' ? 3 : 2;
  1403. }
  1404. else {
  1405. length = c1 === '=' ? 2 : 1;
  1406. }
  1407. break;
  1408. case '<':
  1409. if (c1 === '>') {
  1410. length = 2;
  1411. }
  1412. else if (c1 === '<') {
  1413. length = c2 === '=' ? 3 : 2;
  1414. }
  1415. else {
  1416. length = c1 === '=' ? 2 : 1;
  1417. }
  1418. break;
  1419. case '>':
  1420. if (c1 === '>') {
  1421. length = c2 === '=' ? 3 : 2;
  1422. }
  1423. else {
  1424. length = c1 === '=' ? 2 : 1;
  1425. }
  1426. break;
  1427. case '@':
  1428. length = c1 === '=' ? 2 : 1;
  1429. break;
  1430. case ':':
  1431. length = c1 === '=' ? 2 : 1;
  1432. break;
  1433. default:
  1434. return null;
  1435. }
  1436. const text = this._text.substring(this._position, this._position + length);
  1437. return { type: text, value: text };
  1438. }
  1439. _string() {
  1440. let i = this._position;
  1441. let prefix = -1;
  1442. if (this._get(i) === "'" || this._get(i) === '"') {
  1443. prefix = '';
  1444. }
  1445. else if (this._get(i + 1) === "'" || this._get(i + 1) === '"') {
  1446. const c = this._get(i);
  1447. switch (c.toLowerCase()) {
  1448. case 'b':
  1449. case 'f':
  1450. case 'r':
  1451. case 'u':
  1452. prefix = c;
  1453. break;
  1454. default:
  1455. break;
  1456. }
  1457. }
  1458. else if (this._get(i + 2) === "'" || this._get(i + 2) === '"') {
  1459. const cc = this._text.substr(this._position, 2);
  1460. switch (cc.toLowerCase()) {
  1461. case 'br':
  1462. case 'fr':
  1463. case 'rb':
  1464. case 'rf':
  1465. case 'ur':
  1466. prefix = cc;
  1467. break;
  1468. default:
  1469. break;
  1470. }
  1471. }
  1472. if (prefix.length >= 0) {
  1473. i += prefix.length;
  1474. let quote = '';
  1475. let count = 0;
  1476. const q0 = this._get(i);
  1477. const q1 = this._get(i + 1);
  1478. const q2 = this._get(i + 2);
  1479. switch (q0) {
  1480. case "'":
  1481. quote = q0;
  1482. count = (q1 === "'" && q2 === "'") ? 3 : 1;
  1483. break;
  1484. case '"':
  1485. quote = q0;
  1486. count = (q1 === '"' && q2 === '"') ? 3 : 1;
  1487. break;
  1488. default:
  1489. throw new python.Error("Unsupported string quote '" + q0 + "'.");
  1490. }
  1491. i += count;
  1492. if (count == 1) {
  1493. while (i < this._text.length) {
  1494. if (this._text[i] === quote) {
  1495. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1496. }
  1497. else if (this._text[i] === '\\' &&
  1498. (this._get(i + 1) == quote || this._get(i + 1) == '\n' || this._get(i + 1) == '\\')) {
  1499. i += 2;
  1500. }
  1501. else if (this._text[i] === '\r' || this._text[i] === '\n') {
  1502. break;
  1503. }
  1504. else {
  1505. i++;
  1506. }
  1507. }
  1508. }
  1509. else if (count == 3) {
  1510. while (i < this._text.length) {
  1511. if (this._get(i) === quote && this._get(i + 1) === quote && this._get(i + 2) === quote) {
  1512. return { type: 'string', value: this._text.substring(this._position, i + 3) };
  1513. }
  1514. else if (this._get(i) === '\\' && this._get(i + 1) === quote) {
  1515. i += 2;
  1516. continue;
  1517. }
  1518. i++;
  1519. }
  1520. }
  1521. }
  1522. i = this._position;
  1523. if (this._get(i) === '`') {
  1524. i++;
  1525. while (i < this._text.length) {
  1526. if (this._text[i] === '`') {
  1527. return { type: 'string', value: this._text.substring(this._position, i + 1) };
  1528. }
  1529. i++;
  1530. }
  1531. }
  1532. return null;
  1533. }
  1534. static _isKeyword(value) {
  1535. switch (value) {
  1536. case 'and':
  1537. case 'as':
  1538. case 'else':
  1539. case 'for':
  1540. case 'if':
  1541. case 'import':
  1542. case 'in':
  1543. case 'is':
  1544. case 'not':
  1545. case 'or':
  1546. return true;
  1547. default:
  1548. return false;
  1549. }
  1550. }
  1551. };
  1552. python.Execution = class {
  1553. constructor(sources, exceptionCallback) {
  1554. const self = this;
  1555. this._sources = sources || new Map();
  1556. this._exceptionCallback = exceptionCallback;
  1557. this._utf8Decoder = new TextDecoder('utf-8');
  1558. this._packages = new Map();
  1559. this._unknownNameMap = new Set();
  1560. this._context = new python.Execution.Context();
  1561. this._context.scope.builtins = {};
  1562. this._context.scope.builtins.type = { __module__: 'builtins', __name__: 'type' };
  1563. this._context.scope.builtins.type.__class__ = this._context.scope.builtins.type;
  1564. this._context.scope.builtins.module = { __module__: 'builtins', __name__: 'module', __class__: this._context.scope.builtins.type };
  1565. this._context.scope.builtins.module.__type__ = this._context.scope.builtins.module;
  1566. this.registerModule('__builtin__');
  1567. this.registerModule('_codecs');
  1568. this.registerModule('argparse');
  1569. this.registerModule('collections');
  1570. this.registerModule('copy_reg');
  1571. this.registerModule('cuml');
  1572. this.registerModule('gensim');
  1573. this.registerModule('io');
  1574. this.registerModule('joblib');
  1575. this.registerModule('keras');
  1576. this.registerModule('lightgbm');
  1577. this.registerModule('numpy');
  1578. this.registerModule('nolearn');
  1579. this.registerModule('sklearn');
  1580. this.registerModule('typing');
  1581. this.registerModule('xgboost');
  1582. const builtins = this._context.scope.builtins;
  1583. const numpy = this._context.scope.numpy;
  1584. const typing = this._context.scope.typing;
  1585. this.registerType('builtins.function', class {});
  1586. this.registerType('builtins.method', class {});
  1587. this.registerType('builtins.dict', class {});
  1588. this.registerType('builtins.list', class {});
  1589. this.registerType('builtins.bool', class {});
  1590. this.registerType('builtins.int', class {});
  1591. this.registerType('builtins.float', class {});
  1592. this.registerType('builtins.object', class {});
  1593. this.registerType('builtins.str', class {});
  1594. this.registerType('builtins.tuple', class {});
  1595. this.registerType('typing._Final', class {});
  1596. this.registerType('typing._SpecialForm', class extends typing._Final {});
  1597. this.registerType('typing._BaseGenericAlias', class extends typing._Final {});
  1598. this.registerType('typing._GenericAlias', class extends typing._BaseGenericAlias {});
  1599. this.registerType('typing._SpecialGenericAlias', class extends typing._BaseGenericAlias {});
  1600. this.registerType('typing._TupleType', class extends typing._SpecialGenericAlias {});
  1601. typing.Optional = self.invoke('typing._SpecialForm', []);
  1602. typing.List = self.invoke('typing._SpecialGenericAlias', []);
  1603. typing.Dict = self.invoke('typing._SpecialGenericAlias', []);
  1604. typing.Tuple = self.invoke('typing._TupleType', []);
  1605. this.registerType('argparse.Namespace', class {
  1606. constructor(args) {
  1607. this.args = args;
  1608. }
  1609. });
  1610. this.registerType('collections.deque', class {
  1611. constructor(iterable) {
  1612. if (iterable) {
  1613. let i = 0;
  1614. for (const value of iterable) {
  1615. this[i++] = value;
  1616. }
  1617. this.length = i;
  1618. }
  1619. }
  1620. });
  1621. this.registerType('collections.OrderedDict', class extends Map {
  1622. constructor(items) {
  1623. super();
  1624. if (items) {
  1625. for (const pair of items) {
  1626. this.__setitem__(pair[0], pair[1]);
  1627. }
  1628. }
  1629. }
  1630. __setitem__(key, value) {
  1631. this.set(key, value);
  1632. }
  1633. });
  1634. this.registerType('cuml.common.array_descriptor.CumlArrayDescriptorMeta', class {});
  1635. this.registerType('cuml.ensemble.randomforestclassifier.RandomForestClassifier', class {});
  1636. this.registerType('cuml.raft.common.handle.Handle', class {
  1637. __setstate__(state) {
  1638. this._handle = state;
  1639. }
  1640. });
  1641. this.registerType('haiku._src.data_structures.FlatMapping', class {
  1642. constructor(dict) {
  1643. for (const key of Object.keys(dict)) {
  1644. this[key] = dict[key];
  1645. }
  1646. }
  1647. });
  1648. this.registerType('io.BytesIO', class {
  1649. constructor(buf, mode) {
  1650. this.mode = mode || 'r';
  1651. this._buf = this.mode === 'w' ? null : buf;
  1652. this._point = 0;
  1653. }
  1654. seek(offset) {
  1655. this._point = offset;
  1656. }
  1657. read(size) {
  1658. const start = this._point;
  1659. this._point = size !== undefined ? start + size : this._buf.length;
  1660. return this._buf.subarray(start, this._point);
  1661. }
  1662. write(data) {
  1663. const src = this._buf || new Uint8Array();
  1664. this._point = src.length + data.length;
  1665. this._buf = new Uint8Array(this._point);
  1666. this._buf.set(src, 0);
  1667. this._buf.set(data, src.length);
  1668. }
  1669. });
  1670. this.registerType('numpy.dtype', class {
  1671. constructor(obj, align, copy) {
  1672. switch (obj) {
  1673. case 'b1': case 'bool': this.itemsize = 1; this.kind = 'b'; break;
  1674. case 'i1': case 'int8': this.itemsize = 1; this.kind = 'i'; break;
  1675. case 'i2': case 'int16': this.itemsize = 2; this.kind = 'i'; break;
  1676. case 'i4': case 'int32': this.itemsize = 4; this.kind = 'i'; break;
  1677. case 'i8': case 'int64': case 'int': this.itemsize = 8; this.kind = 'i'; break;
  1678. case 'u1': case 'uint8': this.itemsize = 1; this.kind = 'u'; break;
  1679. case 'u2': case 'uint16': this.itemsize = 2; this.kind = 'u'; break;
  1680. case 'u4': case 'uint32': this.itemsize = 4; this.kind = 'u'; break;
  1681. case 'u8': case 'uint64': case 'uint': this.itemsize = 8; this.kind = 'u'; break;
  1682. case 'f2': case 'float16': this.itemsize = 2; this.kind = 'f'; break;
  1683. case 'f4': case 'float32': this.itemsize = 4; this.kind = 'f'; break;
  1684. case 'f8': case 'float64': case 'float': this.itemsize = 8; this.kind = 'f'; break;
  1685. case 'c8': case 'complex64': this.itemsize = 8; this.kind = 'c'; break;
  1686. case 'c16': case 'complex128': case 'complex': this.itemsize = 16; this.kind = 'c'; break;
  1687. case 'M': this.itemsize = 8; this.kind = 'M'; break;
  1688. default:
  1689. if (obj.startsWith('V')) {
  1690. this.itemsize = parseInt(obj.substring(1), 10);
  1691. this.kind = 'V';
  1692. }
  1693. else if (obj.startsWith('O')) {
  1694. this.itemsize = parseInt(obj.substring(1), 10);
  1695. this.kind = 'O';
  1696. }
  1697. else if (obj.startsWith('S')) {
  1698. this.itemsize = parseInt(obj.substring(1), 10);
  1699. this.kind = 'S';
  1700. }
  1701. else if (obj.startsWith('U')) { // Unicode string
  1702. this.kind = 'U';
  1703. this.itemsize = 4 * parseInt(obj.substring(1), 10);
  1704. }
  1705. else {
  1706. throw new python.Error("Unsupported dtype '" + obj.toString() + "'.");
  1707. }
  1708. break;
  1709. }
  1710. this.byteorder = '=';
  1711. if (align) {
  1712. this.align = align;
  1713. }
  1714. if (copy) {
  1715. this.copy = copy;
  1716. }
  1717. }
  1718. get str() {
  1719. return (this.byteorder === '=' ? '<' : this.byteorder) + this.kind + this.itemsize.toString();
  1720. }
  1721. get name() {
  1722. switch (this.kind) {
  1723. case 'V': return 'void' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1724. case 'S': return 'bytes' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1725. case 'U': return 'str' + (this.itemsize === 0 ? '' : (this.itemsize * 8).toString());
  1726. case 'M': return 'datetime64';
  1727. default: return this.name;
  1728. }
  1729. }
  1730. __setstate__(state) {
  1731. switch (state.length) {
  1732. case 8:
  1733. this.version = state[0];
  1734. this.byteorder = state[1];
  1735. this.subarray = state[2];
  1736. this.names = state[3];
  1737. this.fields = state[4];
  1738. this.elsize = state[5];
  1739. this.alignment = state[6];
  1740. this.int_dtypeflags = state[7];
  1741. break;
  1742. case 9:
  1743. this.version = state[0];
  1744. this.byteorder = state[1];
  1745. this.subarray = state[2];
  1746. this.names = state[3];
  1747. this.fields = state[4];
  1748. this.elsize = state[5];
  1749. this.alignment = state[6];
  1750. this.int_dtypeflags = state[7];
  1751. this.metadata = state[8];
  1752. break;
  1753. default:
  1754. throw new python.Error("Unsupported numpy.dtype setstate length '" + state.length.toString() + "'.");
  1755. }
  1756. }
  1757. get __name__() {
  1758. switch (this.kind) {
  1759. case 'b':
  1760. switch (this.itemsize) {
  1761. case 1: return 'boolean';
  1762. default: throw new python.Error("Unsupported boolean itemsize '" + this.itemsize + "'.");
  1763. }
  1764. case 'i':
  1765. switch (this.itemsize) {
  1766. case 1: return 'int8';
  1767. case 2: return 'int16';
  1768. case 4: return 'int32';
  1769. case 8: return 'int64';
  1770. default: throw new python.Error("Unsupported int itemsize '" + this.itemsize + "'.");
  1771. }
  1772. case 'u':
  1773. switch (this.itemsize) {
  1774. case 1: return 'uint8';
  1775. case 2: return 'uint16';
  1776. case 4: return 'uint32';
  1777. case 8: return 'uint64';
  1778. default: throw new python.Error("Unsupported uint itemsize '" + this.itemsize + "'.");
  1779. }
  1780. case 'f':
  1781. switch (this.itemsize) {
  1782. case 2: return 'float16';
  1783. case 4: return 'float32';
  1784. case 8: return 'float64';
  1785. default: throw new python.Error("Unsupported float itemsize '" + this.itemsize + "'.");
  1786. }
  1787. case 'c':
  1788. switch (this.itemsize) {
  1789. case 8: return 'complex64';
  1790. case 16: return 'complex128';
  1791. default: throw new python.Error("Unsupported complex itemsize '" + this.itemsize + "'.");
  1792. }
  1793. case 'S':
  1794. case 'U':
  1795. return 'string';
  1796. case 'M':
  1797. return 'datetime';
  1798. case 'O':
  1799. return 'object';
  1800. case 'V':
  1801. return 'void';
  1802. default:
  1803. throw new python.Error("Unsupported dtype kind '" + this.kind + "'.");
  1804. }
  1805. }
  1806. });
  1807. this.registerType('gensim.models.doc2vec.Doctag', class {});
  1808. this.registerType('gensim.models.doc2vec.Doc2Vec', class {});
  1809. this.registerType('gensim.models.doc2vec.Doc2VecTrainables', class {});
  1810. this.registerType('gensim.models.doc2vec.Doc2VecVocab', class {});
  1811. this.registerType('gensim.models.fasttext.FastText', class {});
  1812. this.registerType('gensim.models.fasttext.FastTextTrainables', class {});
  1813. this.registerType('gensim.models.fasttext.FastTextVocab', class {});
  1814. this.registerType('gensim.models.fasttext.FastTextKeyedVectors', class {});
  1815. this.registerType('gensim.models.keyedvectors.Doc2VecKeyedVectors', class {});
  1816. this.registerType('gensim.models.keyedvectors.FastTextKeyedVectors', class {});
  1817. this.registerType('gensim.models.keyedvectors.KeyedVectors', class {});
  1818. this.registerType('gensim.models.keyedvectors.Vocab', class {});
  1819. this.registerType('gensim.models.keyedvectors.Word2VecKeyedVectors', class {});
  1820. this.registerType('gensim.models.phrases.Phrases', class {});
  1821. this.registerType('gensim.models.tfidfmodel.TfidfModel', class {});
  1822. this.registerType('gensim.models.word2vec.Vocab', class {});
  1823. this.registerType('gensim.models.word2vec.Word2Vec', class {});
  1824. this.registerType('gensim.models.word2vec.Word2VecTrainables', class {});
  1825. this.registerType('gensim.models.word2vec.Word2VecVocab', class {});
  1826. this.registerType('joblib.numpy_pickle.NumpyArrayWrapper', class {
  1827. constructor(/* subtype, shape, dtype */) {
  1828. }
  1829. __setstate__(state) {
  1830. this.subclass = state.subclass;
  1831. this.dtype = state.dtype;
  1832. this.shape = state.shape;
  1833. this.order = state.order;
  1834. this.allow_mmap = state.allow_mmap;
  1835. }
  1836. __read__(unpickler) {
  1837. if (this.dtype.__name__ == 'object') {
  1838. return unpickler.load((name, args) => self.invoke(name, args), null);
  1839. }
  1840. else {
  1841. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  1842. this.data = unpickler.read(size);
  1843. }
  1844. return self.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  1845. }
  1846. });
  1847. this.registerType('keras.engine.sequential.Sequential', class {});
  1848. this.registerType('lightgbm.sklearn.LGBMRegressor', class {});
  1849. this.registerType('lightgbm.sklearn.LGBMClassifier', class {});
  1850. this.registerType('lightgbm.basic.Booster', class {
  1851. constructor() {
  1852. this.average_output = false;
  1853. this.models = [];
  1854. this.loaded_parameter = '';
  1855. }
  1856. __setstate__(state) {
  1857. if (typeof state.handle === 'string') {
  1858. this.LoadModelFromString(state.handle);
  1859. return;
  1860. }
  1861. Object.assign(this, state);
  1862. }
  1863. LoadModelFromString(model_str) {
  1864. const lines = model_str.split('\n');
  1865. const signature = lines.shift() || '?';
  1866. if (signature.trim() !== 'tree') {
  1867. throw new python.Error("Invalid signature '" + signature.trim() + "'.");
  1868. }
  1869. // GBDT::LoadModelFromString() in https://github.com/microsoft/LightGBM/blob/master/src/boosting/gbdt_model_text.cpp
  1870. const key_vals = new Map();
  1871. while (lines.length > 0 && !lines[0].startsWith('Tree=')) {
  1872. const cur_line = lines.shift().trim();
  1873. if (cur_line.length > 0) {
  1874. const strs = cur_line.split('=');
  1875. if (strs.length === 1) {
  1876. key_vals.set(strs[0], '');
  1877. }
  1878. else if (strs.length === 2) {
  1879. key_vals.set(strs[0], strs[1]);
  1880. }
  1881. else if (strs.length > 2) {
  1882. if (strs[0] === "feature_names") {
  1883. key_vals.set(strs[0], cur_line.substring("feature_names=".length));
  1884. }
  1885. else if (strs[0] == 'monotone_constraints') {
  1886. key_vals.set(strs[0], cur_line.substring('monotone_constraints='.length));
  1887. }
  1888. else {
  1889. throw new python.Error('Wrong line: ' + cur_line.substring(0, Math.min(128, cur_line.length)));
  1890. }
  1891. }
  1892. }
  1893. }
  1894. const atoi = (key, value) => {
  1895. if (key_vals.has(key)) {
  1896. return parseInt(key_vals.get(key), 10);
  1897. }
  1898. if (value !== undefined) {
  1899. return value;
  1900. }
  1901. throw new python.Error('Model file does not specify ' + key + '.');
  1902. };
  1903. const list = (key, size) => {
  1904. if (key_vals.has(key)) {
  1905. const value = key_vals.get(key).split(' ');
  1906. if (value.length !== size) {
  1907. throw new python.Error('Wrong size of ' + key + '.');
  1908. }
  1909. return value;
  1910. }
  1911. throw new python.Error('Model file does not contain ' + key + '.');
  1912. };
  1913. this.version = key_vals.get('version') || '';
  1914. this.num_class = atoi('num_class');
  1915. this.num_tree_per_iteration = atoi('num_tree_per_iteration', this.num_class);
  1916. this.label_index = atoi('label_index');
  1917. this.max_feature_idx = atoi('max_feature_idx');
  1918. if (key_vals.has('average_output')) {
  1919. this.average_output = true;
  1920. }
  1921. this.feature_names = list('feature_names', this.max_feature_idx + 1);
  1922. this.feature_infos = list('feature_infos', this.max_feature_idx + 1);
  1923. if (key_vals.has('monotone_constraints')) {
  1924. this.monotone_constraints = list('monotone_constraints', this.max_feature_idx + 1, true);
  1925. }
  1926. if (key_vals.has('objective')) {
  1927. this.objective = key_vals.get('objective');
  1928. }
  1929. let tree = null;
  1930. // let lineNumber = 0;
  1931. while (lines.length > 0) {
  1932. // lineNumber++;
  1933. const text = lines.shift();
  1934. const line = text.trim();
  1935. if (line.length === 0) {
  1936. continue;
  1937. }
  1938. if (line.startsWith('Tree=')) {
  1939. tree = { index: parseInt(line.split('=').pop(), 10) };
  1940. this.models.push(tree);
  1941. continue;
  1942. }
  1943. if (line === 'end of trees') {
  1944. break;
  1945. }
  1946. const param = line.split('=');
  1947. if (param.length !== 2) {
  1948. throw new python.Error("Invalid property '" + line + "'.");
  1949. }
  1950. const name = param[0].trim();
  1951. const value = param[1].trim();
  1952. tree[name] = value;
  1953. }
  1954. const ss = [];
  1955. let is_inparameter = false;
  1956. while (lines.length > 0) {
  1957. const text = lines.shift();
  1958. const line = text.trim();
  1959. if (line === 'parameters:') {
  1960. is_inparameter = true;
  1961. continue;
  1962. }
  1963. else if (line === 'end of parameters') {
  1964. break;
  1965. }
  1966. else if (is_inparameter) {
  1967. ss.push(line);
  1968. }
  1969. }
  1970. if (ss.length > 0) {
  1971. this.loaded_parameter = ss.join('\n');
  1972. }
  1973. }
  1974. });
  1975. this.registerType('nolearn.lasagne.base.BatchIterator', class {});
  1976. this.registerType('nolearn.lasagne.base.Layers', class {});
  1977. this.registerType('nolearn.lasagne.base.NeuralNet', class {});
  1978. this.registerType('nolearn.lasagne.base.TrainSplit', class {});
  1979. this.registerType('nolearn.lasagne.handlers.PrintLayerInfo', class {});
  1980. this.registerType('nolearn.lasagne.handlers.PrintLog', class {});
  1981. this.registerType('numpy.ndarray', class {
  1982. constructor(shape, dtype, buffer, offset, strides, order) {
  1983. this.shape = shape;
  1984. this.dtype = dtype;
  1985. this.data = buffer !== undefined ? buffer : null;
  1986. this.offset = offset !== undefined ? offset : 0;
  1987. this.strides = strides !== undefined ? strides : null;
  1988. this.order = offset !== undefined ? order : null;
  1989. this.flags = {};
  1990. }
  1991. __setstate__(state) {
  1992. this.version = state[0];
  1993. this.shape = state[1];
  1994. this.dtype = state[2];
  1995. this.flags.fnc = state[3];
  1996. this.data = state[4];
  1997. }
  1998. __read__(unpickler) {
  1999. const dims = (this.shape || []).reduce((a, b) => a * b, 1);
  2000. const size = this.dtype.itemsize * dims;
  2001. if (typeof this.data == 'string') {
  2002. this.data = unpickler.unescape(this.data, size);
  2003. if (this.data.length != size) {
  2004. throw new python.Error('Invalid string array data size.');
  2005. }
  2006. }
  2007. else {
  2008. if (this.data.length != size) {
  2009. // throw new pytorch.Error('Invalid array data size.');
  2010. }
  2011. }
  2012. return this;
  2013. }
  2014. tobytes() {
  2015. return this.data;
  2016. }
  2017. });
  2018. this.registerType('numpy.ma.core.MaskedArray', class extends numpy.ndarray {
  2019. constructor(data /*, mask, dtype, copy, subok, ndmin, fill_value, keep_mask, hard_mask, shrink, order */) {
  2020. super(data.shape, data.dtype, data.data);
  2021. }
  2022. });
  2023. this.registerType('numpy.core.memmap.memmap', class extends numpy.ndarray {
  2024. constructor(shape, dtype) {
  2025. super(shape, dtype);
  2026. }
  2027. });
  2028. this.registerType('pathlib.PosixPath', class {
  2029. constructor() {
  2030. this.path = Array.from(arguments).join('/');
  2031. }
  2032. });
  2033. this.registerType('sklearn.calibration._CalibratedClassifier', class {});
  2034. this.registerType('sklearn.calibration._SigmoidCalibration', class {});
  2035. this.registerType('sklearn.calibration.CalibratedClassifierCV', class {});
  2036. this.registerType('sklearn.compose._column_transformer.ColumnTransformer', class {});
  2037. this.registerType('sklearn.compose._target.TransformedTargetRegressor', class {});
  2038. this.registerType('sklearn.cluster._agglomerative.FeatureAgglomeration', class {});
  2039. this.registerType('sklearn.cluster._dbscan.DBSCAN', class {});
  2040. this.registerType('sklearn.cluster._kmeans.KMeans', class {});
  2041. this.registerType('sklearn.decomposition._fastica.FastICA', class {});
  2042. this.registerType('sklearn.decomposition._pca.PCA', class {});
  2043. this.registerType('sklearn.decomposition._truncated_svd.TruncatedSVD', class {});
  2044. this.registerType('sklearn.decomposition.PCA', class {});
  2045. this.registerType('sklearn.decomposition.pca.PCA', class {});
  2046. this.registerType('sklearn.decomposition.truncated_svd.TruncatedSVD', class {});
  2047. this.registerType('sklearn.discriminant_analysis.LinearDiscriminantAnalysis', class {});
  2048. this.registerType('sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis', class {});
  2049. this.registerType('sklearn.dummy.DummyClassifier', class {});
  2050. this.registerType('sklearn.dummy.DummyRegressor', class {});
  2051. this.registerType('sklearn.externals.joblib.numpy_pickle.NumpyArrayWrapper', class {
  2052. constructor(/* subtype, shape, dtype */) {
  2053. }
  2054. __setstate__(state) {
  2055. this.subclass = state.subclass;
  2056. this.dtype = state.dtype;
  2057. this.shape = state.shape;
  2058. this.order = state.order;
  2059. this.allow_mmap = state.allow_mmap;
  2060. }
  2061. __read__(unpickler) {
  2062. if (this.dtype.__name__ == 'object') {
  2063. return unpickler.load((name, args) => self.invoke(name, args), null);
  2064. }
  2065. else {
  2066. const size = this.dtype.itemsize * this.shape.reduce((a, b) => a * b, 1);
  2067. this.data = unpickler.read(size);
  2068. }
  2069. return self.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2070. }
  2071. });
  2072. this.registerType('sklearn.externals.joblib.numpy_pickle.NDArrayWrapper', class {
  2073. constructor(/* subtype, shape, dtype */) {
  2074. }
  2075. __setstate__(state) {
  2076. this.subclass = state.subclass;
  2077. this.filename = state.state;
  2078. this.allow_mmap = state.allow_mmap;
  2079. }
  2080. __read__(/* unpickler */) {
  2081. return this; // return self.invoke(this.subclass, [ this.shape, this.dtype, this.data ]);
  2082. }
  2083. });
  2084. this.registerType('sklearn.ensemble._bagging.BaggingClassifier', class {});
  2085. this.registerType('sklearn.ensemble._forest.RandomForestRegressor', class {});
  2086. this.registerType('sklearn.ensemble._forest.RandomForestClassifier', class {});
  2087. this.registerType('sklearn.ensemble._forest.ExtraTreesClassifier', class {});
  2088. this.registerType('sklearn.ensemble._gb_losses.BinomialDeviance', class {});
  2089. this.registerType('sklearn.ensemble._gb_losses.LeastSquaresError', class {});
  2090. this.registerType('sklearn.ensemble._gb_losses.MultinomialDeviance', class {});
  2091. this.registerType('sklearn.ensemble._gb.GradientBoostingClassifier', class {});
  2092. this.registerType('sklearn.ensemble._gb.GradientBoostingRegressor', class {});
  2093. this.registerType('sklearn.ensemble._hist_gradient_boosting.binning._BinMapper', class {});
  2094. this.registerType('sklearn.ensemble._hist_gradient_boosting.gradient_boosting.HistGradientBoostingRegressor', class {});
  2095. this.registerType('sklearn.ensemble._hist_gradient_boosting.loss.LeastSquares', class {});
  2096. this.registerType('sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor', class {});
  2097. this.registerType('sklearn.ensemble._iforest.IsolationForest', class {});
  2098. this.registerType('sklearn.ensemble._stacking.StackingClassifier', class {});
  2099. this.registerType('sklearn.ensemble._voting.VotingClassifier', class {});
  2100. this.registerType('sklearn.ensemble._weight_boosting.AdaBoostClassifier', class {});
  2101. this.registerType('sklearn.ensemble.forest.RandomForestClassifier', class {});
  2102. this.registerType('sklearn.ensemble.forest.RandomForestRegressor', class {});
  2103. this.registerType('sklearn.ensemble.forest.ExtraTreesClassifier', class {});
  2104. this.registerType('sklearn.ensemble.gradient_boosting.BinomialDeviance', class {});
  2105. this.registerType('sklearn.ensemble.gradient_boosting.GradientBoostingClassifier', class {});
  2106. this.registerType('sklearn.ensemble.gradient_boosting.LogOddsEstimator', class {});
  2107. this.registerType('sklearn.ensemble.gradient_boosting.MultinomialDeviance', class {});
  2108. this.registerType('sklearn.ensemble.gradient_boosting.PriorProbabilityEstimator', class {});
  2109. this.registerType('sklearn.ensemble.weight_boosting.AdaBoostClassifier', class {});
  2110. this.registerType('sklearn.feature_extraction._hashing.FeatureHasher', class {});
  2111. this.registerType('sklearn.feature_extraction.text.CountVectorizer', class {});
  2112. this.registerType('sklearn.feature_extraction.text.HashingVectorizer', class {});
  2113. this.registerType('sklearn.feature_extraction.text.TfidfTransformer', class {});
  2114. this.registerType('sklearn.feature_extraction.text.TfidfVectorizer', class {});
  2115. this.registerType('sklearn.feature_selection._from_model.SelectFromModel', class {});
  2116. this.registerType('sklearn.feature_selection._univariate_selection.GenericUnivariateSelect', class {});
  2117. this.registerType('sklearn.feature_selection._univariate_selection.SelectKBest', class {});
  2118. this.registerType('sklearn.feature_selection._univariate_selection.SelectPercentile', class {});
  2119. this.registerType('sklearn.feature_selection._variance_threshold.VarianceThreshold', class {});
  2120. this.registerType('sklearn.feature_selection.univariate_selection.SelectKBest', class {});
  2121. this.registerType('sklearn.feature_selection.variance_threshold.VarianceThreshold', class {});
  2122. this.registerType('sklearn.gaussian_process.gpc.GaussianProcessClassifier', class {});
  2123. this.registerType('sklearn.gaussian_process.kernels.ConstantKernel', class {});
  2124. this.registerType('sklearn.gaussian_process.kernels.Product', class {});
  2125. this.registerType('sklearn.gaussian_process.kernels.RBF', class {});
  2126. this.registerType('sklearn.grid_search._CVScoreTuple', class {});
  2127. this.registerType('sklearn.grid_search.GridSearchCV', class {});
  2128. this.registerType('sklearn.impute._base.SimpleImputer', class {});
  2129. this.registerType('sklearn.impute.SimpleImputer', class {});
  2130. this.registerType('sklearn.isotonic.IsotonicRegression', class {});
  2131. this.registerType('sklearn.linear_model._base.LinearRegression', class {});
  2132. this.registerType('sklearn.linear_model._bayes.BayesianRidge', class {});
  2133. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNetCV', class {});
  2134. this.registerType('sklearn.linear_model._coordinate_descent.ElasticNet', class {});
  2135. this.registerType('sklearn.linear_model._logistic.LogisticRegression', class {});
  2136. this.registerType('sklearn.linear_model._ridge.Ridge', class {});
  2137. this.registerType('sklearn.linear_model._ridge.RidgeClassifier', class {});
  2138. this.registerType('sklearn.linear_model._sgd_fast.Hinge', class {});
  2139. this.registerType('sklearn.linear_model._sgd_fast.Log', class {});
  2140. this.registerType('sklearn.linear_model._sgd_fast.ModifiedHuber', class {});
  2141. this.registerType('sklearn.linear_model._sgd_fast.SquaredHinge', class {});
  2142. this.registerType('sklearn.linear_model._stochastic_gradient.SGDClassifier', class {});
  2143. this.registerType('sklearn.linear_model.base.LinearRegression', class {});
  2144. this.registerType('sklearn.linear_model.sgd_fast.Hinge', class {});
  2145. this.registerType('sklearn.linear_model.LogisticRegression', class {});
  2146. this.registerType('sklearn.linear_model.logistic.LogisticRegression', class {});
  2147. this.registerType('sklearn.linear_model.logistic.LogisticRegressionCV', class {});
  2148. this.registerType('sklearn.linear_model.LassoLars​', class {});
  2149. this.registerType('sklearn.linear_model.ridge.Ridge', class {});
  2150. this.registerType('sklearn.linear_model.sgd_fast.Log', class {});
  2151. this.registerType('sklearn.linear_model.stochastic_gradient.SGDClassifier', class {});
  2152. this.registerType('sklearn.metrics._scorer._PredictScorer', class {});
  2153. this.registerType('sklearn.metrics.scorer._PredictScorer', class {});
  2154. this.registerType('sklearn.metrics._scorer._ThresholdScorer', class {});
  2155. this.registerType('sklearn.mixture._bayesian_mixture.BayesianGaussianMixture', class {});
  2156. this.registerType('sklearn.model_selection._search.GridSearchCV', class {});
  2157. this.registerType('sklearn.model_selection._search.RandomizedSearchCV', class {});
  2158. this.registerType('sklearn.model_selection._split.KFold', class {});
  2159. this.registerType('sklearn.model_selection._split.StratifiedKFold', class {});
  2160. this.registerType('sklearn.multiclass.OneVsRestClassifier', class {});
  2161. this.registerType('sklearn.multioutput.MultiOutputClassifier', class {});
  2162. this.registerType('sklearn.multioutput.MultiOutputRegressor', class {});
  2163. this.registerType('sklearn.naive_bayes.BernoulliNB', class {});
  2164. this.registerType('sklearn.naive_bayes.ComplementNB', class {});
  2165. this.registerType('sklearn.naive_bayes.GaussianNB', class {});
  2166. this.registerType('sklearn.naive_bayes.MultinomialNB', class {});
  2167. this.registerType('sklearn.neighbors._classification.KNeighborsClassifier', class {});
  2168. this.registerType('sklearn.neighbors._dist_metrics.newObj', class {});
  2169. this.registerType('sklearn.neighbors._kd_tree.newObj', class {});
  2170. this.registerType('sklearn.neighbors._regression.KNeighborsRegressor', class {});
  2171. this.registerType('sklearn.neighbors.classification.KNeighborsClassifier', class {});
  2172. this.registerType('sklearn.neighbors.dist_metrics.newObj', class {});
  2173. this.registerType('sklearn.neighbors.kd_tree.newObj', class {});
  2174. this.registerType('sklearn.neighbors.KNeighborsClassifier', class {});
  2175. this.registerType('sklearn.neighbors.KNeighborsRegressor', class {});
  2176. this.registerType('sklearn.neighbors.regression.KNeighborsRegressor', class {});
  2177. this.registerType('sklearn.neighbors.unsupervised.NearestNeighbors', class {});
  2178. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPClassifier', class {});
  2179. this.registerType('sklearn.neural_network._multilayer_perceptron.MLPRegressor', class {});
  2180. this.registerType('sklearn.neural_network._stochastic_optimizers.AdamOptimizer', class {});
  2181. this.registerType('sklearn.neural_network._stochastic_optimizers.SGDOptimizer', class {});
  2182. this.registerType('sklearn.neural_network.rbm.BernoulliRBM', class {});
  2183. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPClassifier', class {});
  2184. this.registerType('sklearn.neural_network.multilayer_perceptron.MLPRegressor', class {});
  2185. this.registerType('sklearn.neural_network.stochastic_gradient.SGDClassifier', class {});
  2186. this.registerType('sklearn.pipeline.Pipeline', class {});
  2187. this.registerType('sklearn.pipeline.FeatureUnion', class {});
  2188. this.registerType('sklearn.preprocessing._data.MinMaxScaler', class {});
  2189. this.registerType('sklearn.preprocessing._data.MaxAbsScaler', class {});
  2190. this.registerType('sklearn.preprocessing._data.Normalizer', class {});
  2191. this.registerType('sklearn.preprocessing._data.PolynomialFeatures', class {});
  2192. this.registerType('sklearn.preprocessing._data.PowerTransformer', class {});
  2193. this.registerType('sklearn.preprocessing._data.QuantileTransformer', class {});
  2194. this.registerType('sklearn.preprocessing._data.RobustScaler', class {});
  2195. this.registerType('sklearn.preprocessing._data.StandardScaler', class {});
  2196. this.registerType('sklearn.preprocessing._discretization.KBinsDiscretizer', class {});
  2197. this.registerType('sklearn.preprocessing._encoders.OneHotEncoder', class {});
  2198. this.registerType('sklearn.preprocessing._function_transformer.FunctionTransformer', class {});
  2199. this.registerType('sklearn.preprocessing._label.LabelBinarizer', class {});
  2200. this.registerType('sklearn.preprocessing._label.LabelEncoder', class {});
  2201. this.registerType('sklearn.preprocessing.data.Binarizer', class {});
  2202. this.registerType('sklearn.preprocessing.data.MaxAbsScaler', class {});
  2203. this.registerType('sklearn.preprocessing.data.MinMaxScaler', class {});
  2204. this.registerType('sklearn.preprocessing.data.Normalizer', class {});
  2205. this.registerType('sklearn.preprocessing.data.OneHotEncoder', class {});
  2206. this.registerType('sklearn.preprocessing.data.PolynomialFeatures', class {});
  2207. this.registerType('sklearn.preprocessing.data.PowerTransformer', class {});
  2208. this.registerType('sklearn.preprocessing.data.RobustScaler', class {});
  2209. this.registerType('sklearn.preprocessing.data.QuantileTransformer', class {});
  2210. this.registerType('sklearn.preprocessing.data.StandardScaler', class {});
  2211. this.registerType('sklearn.preprocessing.imputation.Imputer', class {});
  2212. this.registerType('sklearn.preprocessing.label.LabelBinarizer', class {});
  2213. this.registerType('sklearn.preprocessing.label.LabelEncoder', class {});
  2214. this.registerType('sklearn.preprocessing.label.MultiLabelBinarizer', class {});
  2215. this.registerType('sklearn.svm._classes.LinearSVC', class {});
  2216. this.registerType('sklearn.svm._classes.SVC', class {});
  2217. this.registerType('sklearn.svm._classes.SVR', class {});
  2218. this.registerType('sklearn.svm.classes.LinearSVC', class {});
  2219. this.registerType('sklearn.svm.classes.OneClassSVM', class {});
  2220. this.registerType('sklearn.svm.classes.SVC', class {});
  2221. this.registerType('sklearn.svm.classes.SVR', class {});
  2222. this.registerType('sklearn.tree._classes.DecisionTreeClassifier', class {});
  2223. this.registerType('sklearn.tree._classes.DecisionTreeRegressor', class {});
  2224. this.registerType('sklearn.tree._classes.ExtraTreeClassifier', class {});
  2225. this.registerType('sklearn.tree._classes.ExtraTreeRegressor', class {});
  2226. this.registerType('sklearn.tree._tree.Tree', class {
  2227. constructor(n_features, n_classes, n_outputs) {
  2228. this.n_features = n_features;
  2229. this.n_classes = n_classes;
  2230. this.n_outputs = n_outputs;
  2231. }
  2232. __setstate__(state) {
  2233. this.max_depth = state.max_depth;
  2234. this.node_count = state.node_count;
  2235. this.nodes = state.nodes;
  2236. this.values = state.values;
  2237. }
  2238. });
  2239. this.registerType('sklearn.tree.tree.DecisionTreeClassifier', class {});
  2240. this.registerType('sklearn.tree.tree.DecisionTreeRegressor', class {});
  2241. this.registerType('sklearn.tree.tree.ExtraTreeClassifier', class {});
  2242. this.registerType('sklearn.utils.Bunch', class {});
  2243. this.registerType('sklearn.utils.deprecation.DeprecationDict', class {});
  2244. this.registerType('re.Pattern', function(pattern, flags) {
  2245. this.pattern = pattern;
  2246. this.flags = flags;
  2247. });
  2248. this.registerType('spacy._ml.PrecomputableAffine', class {
  2249. __setstate__(state) {
  2250. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2251. }
  2252. });
  2253. this.registerType('spacy.syntax._parser_model.ParserModel', class {
  2254. __setstate__(state) {
  2255. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2256. }
  2257. });
  2258. this.registerType('thinc.describe.Biases', class {
  2259. __setstate__(state) {
  2260. Object.assign(this, state);
  2261. }
  2262. });
  2263. this.registerType('thinc.describe.Dimension', class {
  2264. __setstate__(state) {
  2265. Object.assign(this, state);
  2266. }
  2267. });
  2268. this.registerType('thinc.describe.Gradient', class {
  2269. __setstate__(state) {
  2270. Object.assign(this, state);
  2271. }
  2272. });
  2273. this.registerType('thinc.describe.Weights', class {
  2274. __setstate__(state) {
  2275. Object.assign(this, state);
  2276. }
  2277. });
  2278. this.registerType('thinc.describe.Synapses', class {
  2279. __setstate__(state) {
  2280. Object.assign(this, state);
  2281. }
  2282. });
  2283. this.registerType('thinc.neural._classes.affine.Affine', class {
  2284. __setstate__(state) {
  2285. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2286. }
  2287. });
  2288. this.registerType('thinc.neural._classes.convolution.ExtractWindow', class {
  2289. __setstate__(state) {
  2290. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2291. }
  2292. });
  2293. this.registerType('thinc.neural._classes.feature_extracter.FeatureExtracter', class {
  2294. __setstate__(state) {
  2295. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2296. }
  2297. });
  2298. this.registerType('thinc.neural._classes.feed_forward.FeedForward', class {
  2299. __setstate__(state) {
  2300. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2301. }
  2302. });
  2303. this.registerType('thinc.neural._classes.function_layer.FunctionLayer', class {
  2304. __setstate__(state) {
  2305. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2306. }
  2307. });
  2308. this.registerType('thinc.neural._classes.hash_embed.HashEmbed', class {
  2309. __setstate__(state) {
  2310. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2311. }
  2312. });
  2313. this.registerType('thinc.neural._classes.layernorm.LayerNorm', class {
  2314. __setstate__(state) {
  2315. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2316. }
  2317. });
  2318. this.registerType('thinc.neural._classes.maxout.Maxout', class {
  2319. __setstate__(state) {
  2320. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2321. }
  2322. });
  2323. this.registerType('thinc.neural._classes.resnet.Residual', class {
  2324. __setstate__(state) {
  2325. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2326. }
  2327. });
  2328. this.registerType('thinc.neural._classes.softmax.Softmax', class {
  2329. __setstate__(state) {
  2330. Object.assign(this, python.Unpickler.open(state).load((name, args) => self.invoke(name, args), null));
  2331. }
  2332. });
  2333. this.registerType('thinc.neural.mem.Memory', class {
  2334. });
  2335. this.registerType('thinc.neural.ops.NumpyOps', class {
  2336. });
  2337. this.registerType('types.CodeType', class {
  2338. constructor(/* args */) {
  2339. }
  2340. });
  2341. this.registerType('types.MethodType', class {
  2342. constructor(/* args */) {
  2343. }
  2344. });
  2345. this.registerType('types.ObjectType', builtins.object);
  2346. this.registerType('xgboost.compat.XGBoostLabelEncoder', class {});
  2347. this.registerType('xgboost.core.Booster', class {});
  2348. this.registerType('xgboost.sklearn.XGBClassifier', class {});
  2349. this.registerType('xgboost.sklearn.XGBRegressor', class {});
  2350. this.registerFunction('__builtin__.bytearray', function(source, encoding /*, errors */) {
  2351. if (source) {
  2352. if (Array.isArray(source) || source instanceof Uint8Array) {
  2353. const target = new Uint8Array(source.length);
  2354. for (let i = 0; i < source.length; i++) {
  2355. target[i] = source[i];
  2356. }
  2357. return target;
  2358. }
  2359. if (encoding === 'latin-1') {
  2360. const target = new Uint8Array(source.length);
  2361. for (let i = 0; i < source.length; i++) {
  2362. target[i] = source.charCodeAt(i);
  2363. }
  2364. return target;
  2365. }
  2366. throw new python.Error("Unsupported bytearray encoding '" + JSON.stringify(encoding) + "'.");
  2367. }
  2368. return [];
  2369. });
  2370. this.registerFunction('__builtin__.bytes', function(source, encoding /*, errors */) {
  2371. if (source) {
  2372. if (Array.isArray(source) || source instanceof Uint8Array) {
  2373. const target = new Uint8Array(source.length);
  2374. for (let i = 0; i < source.length; i++) {
  2375. target[i] = source[i];
  2376. }
  2377. return target;
  2378. }
  2379. if (encoding === 'latin-1') {
  2380. const array = new Uint8Array(source.length);
  2381. for (let i = 0; i < source.length; i++) {
  2382. array[i] = source.charCodeAt(i);
  2383. }
  2384. return array;
  2385. }
  2386. throw new python.Error("Unsupported bytes encoding '" + JSON.stringify(encoding) + "'.");
  2387. }
  2388. return [];
  2389. });
  2390. this.registerFunction('__builtin__.set', function(iterable) {
  2391. return iterable ? iterable : [];
  2392. });
  2393. this.registerFunction('__builtin__.frozenset', function(iterable) {
  2394. return iterable ? iterable : [];
  2395. });
  2396. this.registerFunction('__builtin__.getattr', function(obj, name, defaultValue) {
  2397. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  2398. return obj[name];
  2399. }
  2400. return defaultValue;
  2401. });
  2402. this.registerFunction('__builtin__.slice', function(start, stop , step) {
  2403. return [ start, stop, step ];
  2404. });
  2405. this.registerFunction('__builtin__.type', function(obj) {
  2406. return obj ? obj.__class__ : undefined;
  2407. });
  2408. this.registerFunction('_codecs.encode', function(obj /*, econding */) {
  2409. return obj;
  2410. });
  2411. this.registerFunction('builtins.bytearray', function(data) {
  2412. return { data: data };
  2413. });
  2414. this.registerFunction('builtins.getattr', function(obj, name, defaultValue) {
  2415. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  2416. return obj[name];
  2417. }
  2418. return defaultValue;
  2419. });
  2420. this.registerFunction('builtins.set', function(iterable) {
  2421. return iterable ? iterable : [];
  2422. });
  2423. this.registerFunction('builtins.slice', function(start, stop, step) {
  2424. return { start: start, stop: stop, step: step };
  2425. });
  2426. this.registerFunction('cloudpickle.cloudpickle._builtin_type', function(name) {
  2427. return name;
  2428. });
  2429. this.registerFunction('collections.Counter', function(/* iterable */) {
  2430. return { __module__: 'collections', __name__: 'Counter' };
  2431. });
  2432. this.registerFunction('collections.defaultdict', function(/* default_factory */) {
  2433. return {};
  2434. });
  2435. this.registerFunction('copy_reg._reconstructor', function(cls, base, state) {
  2436. // copyreg._reconstructor in Python 3
  2437. if (base === '__builtin__.object' || base === builtins.object) {
  2438. return self.invoke(cls, []);
  2439. }
  2440. else if (base === '__builtin__.tuple' || base === builtins.tuple) {
  2441. const obj = self.invoke(cls, []);
  2442. for (let i = 0; i < state.length; i++) {
  2443. obj[i] = state[i];
  2444. }
  2445. return obj;
  2446. }
  2447. throw new python.Error("Unsupported copy_reg._reconstructor base type '" + base + "'.");
  2448. });
  2449. this.registerFunction('dill._dill._create_cell', function(/* args */) {
  2450. return function() {
  2451. // TODO
  2452. };
  2453. });
  2454. this.registerFunction('dill._dill._create_code', function(args) {
  2455. return self.invoke('types.CodeType', [ args ]);
  2456. });
  2457. this.registerFunction('dill._dill._create_function', function(/* fcode, fglobals, fname, fdefaults, fclosure, fdict, fkwdefaults */) {
  2458. return function() {
  2459. // TODO
  2460. };
  2461. });
  2462. this.registerFunction('dill._dill._get_attr', function(self, name) {
  2463. if (Object.prototype.hasOwnProperty.call(self, name)) {
  2464. return self[name];
  2465. }
  2466. return undefined;
  2467. });
  2468. this.registerFunction('dill._dill._import_module', function(import_name, safe) {
  2469. try {
  2470. return self.context.getx(import_name);
  2471. }
  2472. catch (err) {
  2473. if (safe) {
  2474. return null;
  2475. }
  2476. throw err;
  2477. }
  2478. });
  2479. this.registerFunction('dill.dill._load_type', function(name) {
  2480. return self.context.getx('types.' + name);
  2481. });
  2482. this.registerFunction('dill._dill._load_type', function(name) {
  2483. return self.context.getx('types.' + name);
  2484. });
  2485. this.registerFunction('getattr', function(obj, name, defaultValue) {
  2486. if (Object.prototype.hasOwnProperty.call(obj, name)) {
  2487. return obj[name];
  2488. }
  2489. return defaultValue;
  2490. });
  2491. this.registerFunction('numpy.core._multiarray_umath._reconstruct', function(subtype, shape, dtype) {
  2492. return self.invoke(subtype, [ shape, dtype ]);
  2493. });
  2494. this.registerFunction('numpy.core.multiarray._reconstruct', function(subtype, shape, dtype) {
  2495. return self.invoke(subtype, [ shape, dtype ]);
  2496. });
  2497. this.registerFunction('numpy.core.multiarray.scalar', function(dtype, rawData) {
  2498. let data = rawData;
  2499. if (typeof rawData === 'string' || rawData instanceof String) {
  2500. data = new Uint8Array(rawData.length);
  2501. for (let i = 0; i < rawData.length; i++) {
  2502. data[i] = rawData.charCodeAt(i);
  2503. }
  2504. }
  2505. switch (dtype.kind) {
  2506. case 'b': {
  2507. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2508. switch (dtype.itemsize) {
  2509. case 1: return view.getInt8(0, true) ? true : false;
  2510. default: throw new python.Error("Unsupported scalar dtype boolean itemsize '" + this.itemsize + "'.");
  2511. }
  2512. }
  2513. case 'f': {
  2514. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2515. switch (dtype.itemsize) {
  2516. case 4: return view.getFloat32(0, true);
  2517. case 8: return view.getFloat64(0, true);
  2518. default: throw new python.Error("Unsupported scalar dtype float itemsize '" + this.itemsize + "'.");
  2519. }
  2520. }
  2521. case 'i': {
  2522. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2523. switch (dtype.itemsize) {
  2524. case 1: return view.getInt8(0, true);
  2525. case 2: return view.getInt16(0, true);
  2526. case 4: return view.getInt32(0, true);
  2527. case 8: return view.getInt64(0, true);
  2528. default: throw new python.Error("Unsupported scalar dtype int itemsize '" + this.itemsize + "'.");
  2529. }
  2530. }
  2531. case 'u': {
  2532. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2533. switch (dtype.itemsize) {
  2534. case 1: return view.getUint8(0, true);
  2535. case 2: return view.getUint16(0, true);
  2536. case 4: return view.getUint32(0, true);
  2537. case 8: return view.getUint64(0, true);
  2538. default: throw new python.Error("Unsupported scalar dtype uint itemsize '" + this.itemsize + "'.");
  2539. }
  2540. }
  2541. case 'U': {
  2542. const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2543. const list = [];
  2544. for (let i = 0; i < dtype.itemsize; i += 4) {
  2545. list.push(String.fromCodePoint(view.getUint32(i, true)));
  2546. }
  2547. return list.join('');
  2548. }
  2549. default: {
  2550. throw new python.Error("Unsupported scalar dtype kind '" + dtype.kind + "'.");
  2551. }
  2552. }
  2553. });
  2554. this.registerFunction('numpy.core._multiarray_umath.scalar', function(dtype, rawData) {
  2555. let data = rawData;
  2556. if (typeof rawData === 'string') {
  2557. data = new Uint8Array(rawData.length);
  2558. for (let i = 0; i < rawData.length; i++) {
  2559. data[i] = rawData.charCodeAt(i);
  2560. }
  2561. }
  2562. const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  2563. switch (dtype.__name__) {
  2564. case 'uint8':
  2565. return dataView.getUint8(0);
  2566. case 'float32':
  2567. return dataView.getFloat32(0, true);
  2568. case 'float64':
  2569. return dataView.getFloat64(0, true);
  2570. case 'int8':
  2571. return dataView.getInt8(0, true);
  2572. case 'int16':
  2573. return dataView.getInt16(0, true);
  2574. case 'int32':
  2575. return dataView.getInt32(0, true);
  2576. case 'int64':
  2577. return dataView.getInt64(0, true);
  2578. default:
  2579. throw new python.Error("Unsupported scalar type '" + dtype.__name__ + "'.");
  2580. }
  2581. });
  2582. this.registerFunction('numpy.load', function(file) {
  2583. // https://github.com/numpy/numpy/blob/main/numpy/lib/format.py
  2584. const signature = [ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59 ];
  2585. if (!file.read(6).every((v, i) => v == signature[i])) {
  2586. throw new numpy.Error('Invalid signature.');
  2587. }
  2588. const major = file.read(1)[0];
  2589. const minor = file.read(1)[0];
  2590. if (major > 3) {
  2591. throw new python.Error("Invalid version '" + [ major, minor ].join('.') + "'.");
  2592. }
  2593. const buffer = new Uint8Array([ 0, 0, 0, 0 ]);
  2594. buffer.set(file.read(major >= 2 ? 4 : 2), 0);
  2595. const header_length = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];
  2596. let header = file.read(header_length);
  2597. const decoder = new TextDecoder(major >= 3 ? 'utf-8' : 'ascii');
  2598. header = decoder.decode(header);
  2599. header = JSON.parse(header.replace(/\(/,'[').replace(/\)/,']').replace('[,','[1,]').replace(',]',',1]').replace(/'/g, '"').replace(/:\s*False\s*,/,':false,').replace(/:\s*True\s*,/,':true,').replace(/,\s*\}/, ' }'));
  2600. if (!header.descr || header.descr.length < 2) {
  2601. throw new numpy.Error("Missing property 'descr'.");
  2602. }
  2603. if (!header.shape) {
  2604. throw new numpy.Error("Missing property 'shape'.");
  2605. }
  2606. const shape = header.shape;
  2607. const dtype = self.invoke('numpy.dtype', [ header.descr.substring(1) ]);
  2608. dtype.byteorder = header.descr[0];
  2609. let data = null;
  2610. switch (dtype.byteorder) {
  2611. case '|': {
  2612. data = file.read();
  2613. break;
  2614. }
  2615. case '>':
  2616. case '<': {
  2617. if (header.descr.length !== 3) {
  2618. throw new numpy.Error("Unsupported data type '" + header.descr + "'.");
  2619. }
  2620. const count = shape.length === 0 ? 1 : shape.reduce((a, b) => a * b, 1);
  2621. data = file.read(dtype.itemsize * count);
  2622. break;
  2623. }
  2624. default: {
  2625. throw new numpy.Error("Unsupported data type '" + header.descr + "'.");
  2626. }
  2627. }
  2628. if (header.fortran_order) {
  2629. data = null;
  2630. }
  2631. return self.invoke('numpy.ndarray', [ shape, dtype, data ]);
  2632. });
  2633. this.registerFunction('numpy.save', function(file, arr) {
  2634. const descr = arr.dtype.str;
  2635. if (descr[0] !== '<' && descr[0] !== '>') {
  2636. throw new numpy.Error("Unsupported byte order '" + descr + "'.");
  2637. }
  2638. if (descr.length !== 3 || (descr[1] !== 'f' && descr[1] !== 'i' && descr[1] !== 'u' && descr[1] !== 'c' && descr.substring(1) !== 'b1')) {
  2639. throw new numpy.Error("Unsupported data type '" + descr + "'.");
  2640. }
  2641. let shape = '';
  2642. switch (arr.shape.length) {
  2643. case 0: shape = '()'; break;
  2644. case 1: shape = '(' + arr.shape[0].toString() + ',)'; break;
  2645. default: shape = '(' + arr.shape.map((dimension) => dimension.toString()).join(', ') + ')'; break;
  2646. }
  2647. const properties = [
  2648. "'descr': '" + descr + "'",
  2649. "'fortran_order': False",
  2650. "'shape': " + shape
  2651. ];
  2652. let header = '{ ' + properties.join(', ') + ' }';
  2653. header += ' '.repeat(64 - ((header.length + 2 + 8 + 1) & 0x3f)) + '\n';
  2654. const encoder = new TextEncoder('ascii');
  2655. file.write([ 0x93, 0x4E, 0x55, 0x4D, 0x50, 0x59, 0x01, 0x00 ]); // '\\x93NUMPY' + version
  2656. file.write([ header.length & 0xff, (header.length >> 8) & 0xff ]);
  2657. file.write(encoder.encode(header));
  2658. file.write(arr.tobytes());
  2659. });
  2660. this.registerFunction('numpy.asarray', function(a, dtype) {
  2661. const encode = (context, data, dim) => {
  2662. const size = context.shape[dim];
  2663. const littleendian = context.littleendian;
  2664. if (dim == context.shape.length - 1) {
  2665. for (let i = 0; i < size; i++) {
  2666. switch (context.dtype) {
  2667. case 'f2':
  2668. context.view.setFloat16(context.position, data[i], littleendian);
  2669. break;
  2670. case 'f4':
  2671. context.view.setFloat32(context.position, data[i], littleendian);
  2672. break;
  2673. case 'f8':
  2674. context.view.setFloat64(context.position, data[i], littleendian);
  2675. break;
  2676. case 'i1':
  2677. context.view.setInt8(context.position, data[i], littleendian);
  2678. break;
  2679. case 'i2':
  2680. context.view.setInt16(context.position, data[i], littleendian);
  2681. break;
  2682. case 'i4':
  2683. context.view.setInt32(context.position, data[i], littleendian);
  2684. break;
  2685. case 'i8':
  2686. context.view.setInt64(context.position, data[i], littleendian);
  2687. break;
  2688. case 'u1':
  2689. context.view.setUint8(context.position, data[i], littleendian);
  2690. break;
  2691. case 'u2':
  2692. context.view.setUint16(context.position, data[i], littleendian);
  2693. break;
  2694. case 'u4':
  2695. context.view.setUint32(context.position, data[i], littleendian);
  2696. break;
  2697. case 'u8':
  2698. context.view.setUint64(context.position, data[i], littleendian);
  2699. break;
  2700. case 'c8':
  2701. context.view.setComplex64(context.position, data[i], littleendian);
  2702. break;
  2703. case 'c16':
  2704. context.view.setComplex128(context.position, data[i], littleendian);
  2705. break;
  2706. default:
  2707. throw new numpy.Error("Unsupported tensor data type '" + context.dtype + "'.");
  2708. }
  2709. context.position += context.itemsize;
  2710. }
  2711. }
  2712. else {
  2713. for (let j = 0; j < size; j++) {
  2714. encode(context, data[j], dim + 1);
  2715. }
  2716. }
  2717. };
  2718. const array_size = (value) => {
  2719. if (value.every((item) => Array.isArray(item))) {
  2720. const dims = value.map((item) => array_size(item));
  2721. const dim = dims[0];
  2722. for (let i = 1; i < dims.length; i++) {
  2723. if (dim.length === dims[i].length) {
  2724. if (!dims[i].every((value, i) => value ===dim[i])) {
  2725. throw new python.Error('Invalid array shape.');
  2726. }
  2727. }
  2728. }
  2729. return [ value.length ].concat(dim);
  2730. }
  2731. return [ value.length ];
  2732. };
  2733. const shape = Array.isArray(a) ? array_size(a) : [];
  2734. const size = dtype.itemsize * shape.reduce((a, b) => a * b, 1);
  2735. const context = {
  2736. position: 0,
  2737. itemsize: dtype.itemsize,
  2738. dtype: dtype.str.substring(1),
  2739. littleendian: dtype.str[0],
  2740. shape: shape,
  2741. data: new Uint8Array(size)
  2742. };
  2743. context.view = new DataView(context.data.buffer, context.data.byteOffset, size);
  2744. encode(context, a, 0);
  2745. return self.invoke('numpy.ndarray', [ shape, dtype, context.data ]);
  2746. });
  2747. this.registerFunction('numpy.ma.core._mareconstruct', function(subtype, baseclass, baseshape, basetype) {
  2748. const data = self.invoke(baseclass, [ baseshape, basetype ]);
  2749. // = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  2750. const mask = self.invoke('numpy.ndarray', [ baseshape, '' ]);
  2751. return self.invoke(subtype, [ data, mask, basetype ]);
  2752. });
  2753. this.registerFunction('numpy.random.__RandomState_ctor', function() {
  2754. return {};
  2755. });
  2756. this.registerFunction('numpy.random._pickle.__randomstate_ctor', function() {
  2757. return {};
  2758. });
  2759. this.registerFunction('numpy.core.numeric._frombuffer', function(/* buf, dtype, shape, order */) {
  2760. return {};
  2761. });
  2762. this.registerFunction('re._compile', function(pattern, flags) {
  2763. return self.invoke('re.Pattern', [ pattern, flags ]);
  2764. });
  2765. this.registerFunction('srsly.cloudpickle.cloudpickle._builtin_type', function(name) {
  2766. return function() {
  2767. return self.invoke('types.' + name, arguments);
  2768. };
  2769. });
  2770. }
  2771. get context() {
  2772. return this._context;
  2773. }
  2774. source(file) {
  2775. return this._sources.has(file) ? this._sources.get(file) : null;
  2776. }
  2777. debug(/* file */) {
  2778. }
  2779. parse(file) {
  2780. const buffer = this.source(file);
  2781. if (buffer) {
  2782. const debug = this.debug(file);
  2783. const code = this._utf8Decoder.decode(buffer);
  2784. const reader = new python.Parser(code, file, debug);
  2785. const program = reader.parse();
  2786. if (!program) {
  2787. throw new python.Error("Module '" + file + "' parse error.");
  2788. }
  2789. return program;
  2790. }
  2791. return null;
  2792. }
  2793. package(name) {
  2794. const index = name.lastIndexOf('.');
  2795. if (index > 0) {
  2796. this.package(name.substring(0, index));
  2797. }
  2798. if (!this._packages.has(name)) {
  2799. const file = 'code/' + name.split('.').join('/') + '.py';
  2800. const program = this.parse(file);
  2801. if (program) {
  2802. let globals = this._context.getx(name);
  2803. if (globals === undefined) {
  2804. globals = {};
  2805. this._context.setx(name, globals);
  2806. }
  2807. globals.__class__ = this._context.scope.builtins.module;
  2808. globals.__name__ = name;
  2809. globals.__file__ = file;
  2810. this._packages.set(name, globals);
  2811. const context = this._context.push(globals);
  2812. this.block(program.body, context);
  2813. }
  2814. }
  2815. return this._packages.get(name);
  2816. }
  2817. type(name) {
  2818. const type = this._context.getx(name);
  2819. if (type !== undefined) {
  2820. return type;
  2821. }
  2822. const parts = name.split('.');
  2823. const className = parts.pop();
  2824. const moduleName = parts.join('.');
  2825. const module = this.package(moduleName);
  2826. if (module) {
  2827. return module[className];
  2828. }
  2829. return null;
  2830. }
  2831. invoke(name, args) {
  2832. const target = name.__class__ ? name : this.type(name);
  2833. if (target) {
  2834. if (target.__class__ === this._context.scope.builtins.type) {
  2835. if (target.prototype && target.prototype.__class__ === target) {
  2836. return Reflect.construct(target, args);
  2837. }
  2838. const obj = {};
  2839. obj.__proto__ = target;
  2840. if (obj.__init__ && typeof obj.__init__ === 'function') {
  2841. obj.__init__.apply(obj, args);
  2842. }
  2843. return obj;
  2844. }
  2845. else if (target.__class__ === this._context.scope.builtins.function) {
  2846. if (target.__call__) {
  2847. return target.__call__(args);
  2848. }
  2849. else {
  2850. return target.apply(null, args);
  2851. }
  2852. }
  2853. }
  2854. this._raiseUnkownName(name);
  2855. this.registerType(name, class {});
  2856. return this.invoke(name, []);
  2857. }
  2858. call(target, name, args, context) {
  2859. const callTarget = this._target(target, context);
  2860. const callArguments = args.map((argument) => this.expression(argument, context));
  2861. if (!callTarget || (name !== null && !callTarget[name])) {
  2862. if (name === '__new__' && callArguments.length === 1 && callArguments[0] == callTarget) {
  2863. name = null;
  2864. callArguments.shift();
  2865. }
  2866. else {
  2867. const targetName = python.Utility.target(target) + '.' + name;
  2868. if (this.type(targetName)) {
  2869. return this.invoke(targetName, callArguments);
  2870. }
  2871. throw new python.Error("Unsupported function '" + targetName + "'.");
  2872. }
  2873. }
  2874. const func = name ? callTarget[name] : callTarget;
  2875. if (func.__class__ === this._context.scope.builtins.type) {
  2876. if (func.prototype && func.prototype.__class__ === func) {
  2877. return Reflect.construct(func, args);
  2878. }
  2879. const obj = {};
  2880. obj.__proto__ = func;
  2881. obj.__class__ = func;
  2882. if (obj.__init__ && typeof obj.__init__ === 'function') {
  2883. obj.__init__.apply(obj, args);
  2884. }
  2885. return obj;
  2886. }
  2887. if (func.__class__ === this._context.scope.builtins.function) {
  2888. if (func.__call__) {
  2889. return func.__call__(callArguments);
  2890. }
  2891. }
  2892. if (func.__class__ === this._context.scope.builtins.method) {
  2893. if (func.__call__) {
  2894. return func.__call__([ callTarget ].concat(callArguments));
  2895. }
  2896. }
  2897. if (typeof func === 'function') {
  2898. return func.apply(callTarget, callArguments);
  2899. }
  2900. throw new python.Error("Unsupported call expression.");
  2901. }
  2902. apply(method, args, context) {
  2903. const locals = Array.prototype.slice.call(args);
  2904. context = context.push();
  2905. for (const parameter of method.parameters) {
  2906. let value = locals.shift();
  2907. if (value === undefined && parameter.initializer) {
  2908. value = this.expression(parameter.initializer, context);
  2909. }
  2910. context.set(parameter.name, value);
  2911. }
  2912. return this.block(method.body.statements, context);
  2913. }
  2914. block(statements, context) {
  2915. statements = Array.prototype.slice.call(statements);
  2916. while (statements.length > 0) {
  2917. const statement = statements.shift();
  2918. const value = this.statement(statement, context);
  2919. if (value !== undefined) {
  2920. return value;
  2921. }
  2922. }
  2923. return undefined;
  2924. }
  2925. statement(statement, context) {
  2926. switch (statement.type) {
  2927. case 'pass': {
  2928. break;
  2929. }
  2930. case 'return': {
  2931. return this.expression(statement.expression, context);
  2932. }
  2933. case 'def': {
  2934. const module = context.get('__name__');
  2935. const self = this;
  2936. const parent = context.get('__class__');
  2937. let type = null;
  2938. if (parent === this._context.scope.builtins.type) {
  2939. type = this._context.scope.builtins.method;
  2940. }
  2941. else if (parent === this._context.scope.builtins.module) {
  2942. type = this._context.scope.builtins.function;
  2943. }
  2944. else {
  2945. throw new python.Error('Invalid function scope.');
  2946. }
  2947. const func = {
  2948. __class__: type,
  2949. __globals__: context,
  2950. __module__: module,
  2951. __name__: statement.name,
  2952. __code__: statement,
  2953. __call__: function(args) {
  2954. return self.apply(this.__code__, args, this.__globals__);
  2955. }
  2956. };
  2957. context.set(statement.name, func);
  2958. break;
  2959. }
  2960. case 'class': {
  2961. const scope = {
  2962. __class__:this._context.scope.builtins.type,
  2963. __module__: context.get('__name__'),
  2964. __name__: statement.name,
  2965. };
  2966. context.set(statement.name, scope);
  2967. context = context.push(scope);
  2968. this.block(statement.body.statements, context);
  2969. context = context.pop();
  2970. break;
  2971. }
  2972. case 'var': {
  2973. context.set(statement.name, statement.initializer ? this.expression(statement.initializer, context) : undefined);
  2974. break;
  2975. }
  2976. case '=': {
  2977. this.expression(statement, context);
  2978. break;
  2979. }
  2980. case 'if': {
  2981. const condition = this.expression(statement.condition, context);
  2982. if (condition === true || condition) {
  2983. const value = this.block(statement.then.statements, context);
  2984. if (value !== undefined) {
  2985. return value;
  2986. }
  2987. break;
  2988. }
  2989. else if (condition === false) {
  2990. const value = this.block(statement.else.statements, context);
  2991. if (value !== undefined) {
  2992. return value;
  2993. }
  2994. break;
  2995. }
  2996. throw new python.Error("Unsupported condition.");
  2997. }
  2998. case 'for': {
  2999. if (statement.target.length == 1 &&
  3000. statement.variable.length === 1 && statement.variable[0].type === 'id') {
  3001. const range = this.expression(statement.target[0], context);
  3002. const variable = statement.variable[0];
  3003. for (const current of range) {
  3004. this.statement({ type: '=', target: variable, expression: { type: 'number', value: current }}, context);
  3005. const value = this.block(statement.body.statements, context);
  3006. if (value !== undefined) {
  3007. return value;
  3008. }
  3009. }
  3010. break;
  3011. }
  3012. throw new python.Error("Unsupported 'for' statement.");
  3013. }
  3014. case 'while': {
  3015. const condition = this.expression(statement.condition, context);
  3016. if (condition) {
  3017. const value = this.block(statement.body.statements, context);
  3018. if (value !== undefined) {
  3019. return value;
  3020. }
  3021. }
  3022. break;
  3023. }
  3024. case 'call': {
  3025. this.expression(statement, context);
  3026. break;
  3027. }
  3028. case 'import': {
  3029. for (const module of statement.modules) {
  3030. const moduleName = python.Utility.target(module.name);
  3031. const globals = this.package(moduleName);
  3032. if (module.as) {
  3033. context.set(module.as, globals);
  3034. }
  3035. }
  3036. break;
  3037. }
  3038. default: {
  3039. throw new python.Error("Unsupported statement '" + statement.type + "'.");
  3040. }
  3041. }
  3042. return undefined;
  3043. }
  3044. expression(expression, context) {
  3045. const self = context.getx('self');
  3046. switch (expression.type) {
  3047. case '=': {
  3048. const target = expression.target;
  3049. if (target.type === 'id') {
  3050. context.set(target.value, this.expression(expression.expression, context));
  3051. return undefined;
  3052. }
  3053. else if (target.type === '[]') {
  3054. if (target.target.type === 'id' &&
  3055. target.arguments.type === 'list' &&
  3056. target.arguments.value.length === 1) {
  3057. const index = this.expression(target.arguments.value[0], context);
  3058. if (target.target.value === '__annotations__') {
  3059. context.set(target.target.value, context.get(target.target.value) || {});
  3060. }
  3061. context.get(target.target.value)[index] = this.expression(expression.expression, context);
  3062. return undefined;
  3063. }
  3064. }
  3065. else if (target.type === '.' &&
  3066. target.member.type === 'id') {
  3067. this.expression(target.target, context)[target.member.value] = this.expression(expression.expression, context);
  3068. return undefined;
  3069. }
  3070. else if (target.type === 'tuple') {
  3071. context.target.push(target.value);
  3072. const value = this.expression(expression.expression, context);
  3073. context.target.pop();
  3074. if (target.value.every((item) => item.type === 'id')) {
  3075. if (target.value.length < value.length) {
  3076. throw new python.Error('ValueError: too many values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  3077. }
  3078. if (target.value.length > value.length) {
  3079. throw new python.Error('ValueError: not enough values to unpack (expected ' + target.value.length + ', actual ' + value.length + ').');
  3080. }
  3081. for (let i = 0; i < value.length; i++) {
  3082. context.set(target.value[i].value, value[i]);
  3083. }
  3084. return undefined;
  3085. }
  3086. }
  3087. break;
  3088. }
  3089. case 'list': {
  3090. return expression.value.map((item) => this.expression(item, context));
  3091. }
  3092. case 'string': {
  3093. return expression.value.substring(1, expression.value.length - 1);
  3094. }
  3095. case 'number': {
  3096. return Number(expression.value);
  3097. }
  3098. case '[]': {
  3099. if (expression.target.type === 'id' &&
  3100. expression.arguments.type === 'list' &&
  3101. expression.arguments.value.length === 1) {
  3102. if (context.get(expression.target.value)) {
  3103. const index = this.expression(expression.arguments.value[0], context);
  3104. const target = context.get(expression.target.value);
  3105. return target[index < 0 ? target.length + index : index];
  3106. }
  3107. }
  3108. const target = this.expression(expression.target, context);
  3109. if (target && expression.arguments.type === 'list' &&
  3110. (target.__class__ === this.context.scope.typing._TupleType ||
  3111. target.__class__ === this.context.scope.typing._SpecialGenericAlias ||
  3112. target.__class__ === this.context.scope.typing._SpecialForm)) {
  3113. const type = Object.assign({}, target);
  3114. type.__args__ = expression.arguments.value.map((arg) => this.expression(arg, context));
  3115. return type;
  3116. }
  3117. if (expression.arguments.type === 'list' && expression.arguments.value.length === 1) {
  3118. const index = this.expression(expression.arguments.value[0], context);
  3119. return target[index < 0 ? target.length + index : index];
  3120. }
  3121. break;
  3122. }
  3123. case '.': {
  3124. if (expression.member.type == 'id') {
  3125. const target = this._target(expression.target, context);
  3126. return target[expression.member.value];
  3127. }
  3128. throw new python.Error("Unsupported field expression.");
  3129. }
  3130. case 'call': {
  3131. if (expression.target.type === 'id' && expression.target.value === 'unchecked_cast' && expression.arguments.length === 2) {
  3132. return this.expression(expression.arguments[1], context);
  3133. }
  3134. if (expression.target.type === '.') {
  3135. return this.call(expression.target.target, expression.target.member.value, expression.arguments, context);
  3136. }
  3137. return this.call(expression.target, null, expression.arguments, context);
  3138. }
  3139. case 'id': {
  3140. switch (expression.value) {
  3141. case 'self': return self;
  3142. case 'None': return null;
  3143. case 'True': return true;
  3144. case 'False': return false;
  3145. default: {
  3146. const type = (value) => {
  3147. return value &&
  3148. (value.__class__ === this._context.scope.builtins.type ||
  3149. value.__class__ === this._context.scope.typing._TupleType ||
  3150. value.__class__ === this._context.scope.typing._SpecialGenericAlias ||
  3151. value.__class__ === this._context.scope.typing._SpecialForm);
  3152. };
  3153. const builtin = this._context.scope.builtins[expression.value];
  3154. if (type(builtin)) {
  3155. return builtin;
  3156. }
  3157. const value = context.get(expression.value);
  3158. if (value === undefined) {
  3159. const typing = this._context.scope.typing[expression.value];
  3160. if (type(typing)) {
  3161. return typing;
  3162. }
  3163. const torch = this._context.scope.torch[expression.value];
  3164. if (type(torch)) {
  3165. return torch;
  3166. }
  3167. }
  3168. return value;
  3169. }
  3170. }
  3171. }
  3172. case 'tuple': {
  3173. return expression.value.map((expression) => this.expression(expression, context));
  3174. }
  3175. case 'dict': {
  3176. const dict = {};
  3177. for (const pair of expression.value) {
  3178. if (pair.type !== 'pair') {
  3179. throw new python.Error("Unsupported dict item type '" + pair.type + "'.");
  3180. }
  3181. const key = this.expression(pair.key, context);
  3182. const value = this.expression(pair.value, context);
  3183. dict[key] = value;
  3184. }
  3185. return dict;
  3186. }
  3187. default: {
  3188. throw new python.Error("Unsupported expression '" + expression.type + "'.");
  3189. }
  3190. }
  3191. return undefined;
  3192. }
  3193. _target(expression, context) {
  3194. let current = expression;
  3195. let packageName = '';
  3196. for (;;) {
  3197. if (current.type === '.' && current.member && current.member.type === 'id') {
  3198. packageName = '.' + current.member.value + packageName;
  3199. current = current.target;
  3200. }
  3201. else if (current.type === 'id' && current.value !== 'self' && current.value !== 'CONSTANTS') {
  3202. packageName = current.value + packageName;
  3203. break;
  3204. }
  3205. else {
  3206. packageName = null;
  3207. break;
  3208. }
  3209. }
  3210. if (packageName) {
  3211. let target = context.getx(packageName);
  3212. if (!target) {
  3213. target = this.package(packageName);
  3214. if (!target) {
  3215. target = context.getx(packageName);
  3216. if (!target) {
  3217. throw new python.Error("Failed to resolve module '" + packageName + "'.");
  3218. }
  3219. }
  3220. }
  3221. return target;
  3222. }
  3223. return this.expression(expression, context);
  3224. }
  3225. registerFunction(name, callback) {
  3226. if (this._context.getx(name)) {
  3227. throw new python.Error("Function '" + name + "' is already registered.");
  3228. }
  3229. const parts = name.split('.');
  3230. callback.__class__ = this._context.scope.builtins.function;
  3231. callback.__name__ = parts.pop();
  3232. callback.__module__ = parts.join('.');
  3233. this._context.setx(name, callback);
  3234. }
  3235. registerType(name, type) {
  3236. if (this._context.getx(name)) {
  3237. throw new python.Error("Class '" + name + "' is already registered.");
  3238. }
  3239. const parts = name.split('.');
  3240. type.__class__ = this._context.scope.builtins.type;
  3241. type.__name__ = parts.pop();
  3242. type.__module__ = parts.join('.');
  3243. type.prototype.__class__ = type;
  3244. this._context.setx(name, type);
  3245. }
  3246. registerModule(name) {
  3247. let scope = this._context.scope;
  3248. const items = name.split('.');
  3249. while (items.length > 0) {
  3250. const item = items.shift();
  3251. scope[item] = { __name__: name, __class__: this._context.scope.builtins.module };
  3252. scope = scope[item];
  3253. }
  3254. }
  3255. _raiseUnkownName(name) {
  3256. if (name && !this._unknownNameMap.has(name)) {
  3257. this._unknownNameMap.add(name);
  3258. const module = name.split('.').shift();
  3259. if (this._context.scope[module] && this._context.scope[module].__class__ == this._context.scope.builtins.module) {
  3260. this._exceptionCallback(new python.Error("Unsupported function '" + name + "'."), false);
  3261. }
  3262. }
  3263. }
  3264. };
  3265. python.Execution.Context = class {
  3266. constructor(parent, scope) {
  3267. this._parent = parent || null;
  3268. this._scope = scope || {};
  3269. }
  3270. push(scope) {
  3271. return new python.Execution.Context(this, scope);
  3272. }
  3273. pop() {
  3274. return this._parent;
  3275. }
  3276. get scope() {
  3277. return this._scope;
  3278. }
  3279. set(name, value) {
  3280. this._scope[name] = value;
  3281. }
  3282. get(name) {
  3283. if (name in this._scope) {
  3284. return this._scope[name];
  3285. }
  3286. if (this._parent) {
  3287. return this._parent.get(name);
  3288. }
  3289. return undefined;
  3290. }
  3291. setx(name, value) {
  3292. if (typeof name !== 'string' || !name.split) {
  3293. throw new python.Error("Invalid name '" + JSON.stringify(name) + "'.");
  3294. }
  3295. const parts = name.split('.');
  3296. if (parts.length == 1) {
  3297. this.set(parts[0], value);
  3298. }
  3299. else {
  3300. let parent = this.get(parts[0]);
  3301. if (!parent) {
  3302. parent = {};
  3303. this.set(parts[0], parent);
  3304. }
  3305. parts.shift();
  3306. while (parts.length > 1) {
  3307. const part = parts.shift();
  3308. parent[part] = parent[part] || {};
  3309. parent = parent[part];
  3310. }
  3311. parent[parts[0]] = value;
  3312. }
  3313. }
  3314. getx(name) {
  3315. const parts = name.split('.');
  3316. let value = this.get(parts[0]);
  3317. if (value !== undefined) {
  3318. parts.shift();
  3319. while (parts.length > 0 && value[parts[0]]) {
  3320. value = value[parts[0]];
  3321. parts.shift();
  3322. }
  3323. if (parts.length === 0) {
  3324. return value;
  3325. }
  3326. }
  3327. return undefined;
  3328. }
  3329. get target() {
  3330. this._target = this._target || [];
  3331. return this._target;
  3332. }
  3333. };
  3334. python.Utility = class {
  3335. static target(expression) {
  3336. if (expression.type == 'id') {
  3337. return expression.value;
  3338. }
  3339. if (expression.type == '.') {
  3340. return python.Utility.target(expression.target) + '.' + python.Utility.target(expression.member);
  3341. }
  3342. return null;
  3343. }
  3344. };
  3345. python.Unpickler = class {
  3346. static open(data) {
  3347. const reader = data instanceof Uint8Array ? new python.Unpickler.BinaryReader(data) : new python.Unpickler.StreamReader(data);
  3348. if (reader.length > 2) {
  3349. const head = reader.peek(2);
  3350. if (head[0] === 0x80 && head[1] < 7) {
  3351. return new python.Unpickler(reader);
  3352. }
  3353. reader.seek(-1);
  3354. const tail = reader.peek(1);
  3355. reader.seek(0);
  3356. if (tail[0] === 0x2e) {
  3357. return new python.Unpickler(reader);
  3358. }
  3359. }
  3360. return null;
  3361. }
  3362. constructor(reader) {
  3363. this._reader = reader;
  3364. }
  3365. load(function_call, persistent_load) {
  3366. const reader = this._reader;
  3367. const marker = [];
  3368. let stack = [];
  3369. const memo = new Map();
  3370. const OpCode = python.Unpickler.OpCode;
  3371. while (reader.position < reader.length) {
  3372. const opcode = reader.byte();
  3373. switch (opcode) {
  3374. case OpCode.PROTO: {
  3375. const version = reader.byte();
  3376. if (version > 5) {
  3377. throw new python.Error("Unsupported protocol version '" + version + "'.");
  3378. }
  3379. break;
  3380. }
  3381. case OpCode.GLOBAL:
  3382. stack.push([ reader.line(), reader.line() ].join('.'));
  3383. break;
  3384. case OpCode.STACK_GLOBAL:
  3385. stack.push([ stack.pop(), stack.pop() ].reverse().join('.'));
  3386. break;
  3387. case OpCode.PUT: {
  3388. const index = parseInt(reader.line(), 10);
  3389. memo.set(index, stack[stack.length - 1]);
  3390. break;
  3391. }
  3392. case OpCode.OBJ: {
  3393. const items = stack;
  3394. stack = marker.pop();
  3395. stack.push(function_call(items.pop(), items));
  3396. break;
  3397. }
  3398. case OpCode.GET: {
  3399. const index = parseInt(reader.line(), 10);
  3400. stack.push(memo.get(index));
  3401. break;
  3402. }
  3403. case OpCode.POP:
  3404. stack.pop();
  3405. break;
  3406. case OpCode.POP_MARK:
  3407. stack = marker.pop();
  3408. break;
  3409. case OpCode.DUP:
  3410. stack.push(stack[stack.length-1]);
  3411. break;
  3412. case OpCode.PERSID:
  3413. stack.push(persistent_load(reader.line()));
  3414. break;
  3415. case OpCode.BINPERSID:
  3416. stack.push(persistent_load(stack.pop()));
  3417. break;
  3418. case OpCode.REDUCE: {
  3419. const items = stack.pop();
  3420. const type = stack.pop();
  3421. stack.push(function_call(type, items));
  3422. break;
  3423. }
  3424. case OpCode.NEWOBJ: {
  3425. const items = stack.pop();
  3426. const type = stack.pop();
  3427. stack.push(function_call(type, items));
  3428. break;
  3429. }
  3430. case OpCode.BINGET:
  3431. stack.push(memo.get(reader.byte()));
  3432. break;
  3433. case OpCode.INST: {
  3434. const module = reader.line();
  3435. const name = reader.line();
  3436. const type = module + '.' + name;
  3437. const items = stack;
  3438. stack = marker.pop();
  3439. stack.push(function_call(type, items));
  3440. break;
  3441. }
  3442. case OpCode.LONG_BINGET:
  3443. stack.push(memo.get(reader.uint32()));
  3444. break;
  3445. case OpCode.BINPUT:
  3446. memo.set(reader.byte(), stack[stack.length - 1]);
  3447. break;
  3448. case OpCode.LONG_BINPUT:
  3449. memo.set(reader.uint32(), stack[stack.length - 1]);
  3450. break;
  3451. case OpCode.BININT:
  3452. stack.push(reader.int32());
  3453. break;
  3454. case OpCode.BININT1:
  3455. stack.push(reader.byte());
  3456. break;
  3457. case OpCode.LONG:
  3458. stack.push(parseInt(reader.line(), 10));
  3459. break;
  3460. case OpCode.BININT2:
  3461. stack.push(reader.uint16());
  3462. break;
  3463. case OpCode.BINBYTES:
  3464. stack.push(reader.read(reader.int32()));
  3465. break;
  3466. case OpCode.BINBYTES8:
  3467. stack.push(reader.read(reader.int64()));
  3468. break;
  3469. case OpCode.SHORT_BINBYTES:
  3470. stack.push(reader.read(reader.byte()));
  3471. break;
  3472. case OpCode.FLOAT:
  3473. stack.push(parseFloat(reader.line()));
  3474. break;
  3475. case OpCode.BINFLOAT:
  3476. stack.push(reader.float64());
  3477. break;
  3478. case OpCode.INT: {
  3479. const value = reader.line();
  3480. if (value == '01') {
  3481. stack.push(true);
  3482. }
  3483. else if (value == '00') {
  3484. stack.push(false);
  3485. }
  3486. else {
  3487. stack.push(parseInt(value, 10));
  3488. }
  3489. break;
  3490. }
  3491. case OpCode.EMPTY_LIST:
  3492. stack.push([]);
  3493. break;
  3494. case OpCode.EMPTY_TUPLE:
  3495. stack.push([]);
  3496. break;
  3497. case OpCode.EMPTY_SET:
  3498. stack.push([]);
  3499. break;
  3500. case OpCode.ADDITEMS: {
  3501. const items = stack;
  3502. stack = marker.pop();
  3503. const obj = stack[stack.length - 1];
  3504. for (let i = 0; i < items.length; i++) {
  3505. obj.push(items[i]);
  3506. }
  3507. break;
  3508. }
  3509. case OpCode.FROZENSET: {
  3510. const items = stack;
  3511. stack = marker.pop();
  3512. stack.push(items);
  3513. break;
  3514. }
  3515. case OpCode.DICT: {
  3516. const items = stack;
  3517. stack = marker.pop();
  3518. const dict = {};
  3519. for (let i = 0; i < items.length; i += 2) {
  3520. dict[items[i]] = items[i + 1];
  3521. }
  3522. stack.push(dict);
  3523. break;
  3524. }
  3525. case OpCode.LIST: {
  3526. const items = stack;
  3527. stack = marker.pop();
  3528. stack.push(items);
  3529. break;
  3530. }
  3531. case OpCode.TUPLE: {
  3532. const items = stack;
  3533. stack = marker.pop();
  3534. stack.push(items);
  3535. break;
  3536. }
  3537. case OpCode.SETITEM: {
  3538. const value = stack.pop();
  3539. const key = stack.pop();
  3540. const obj = stack[stack.length - 1];
  3541. if (obj.__setitem__) {
  3542. obj.__setitem__(key, value);
  3543. }
  3544. else {
  3545. obj[key] = value;
  3546. }
  3547. break;
  3548. }
  3549. case OpCode.SETITEMS: {
  3550. const items = stack;
  3551. stack = marker.pop();
  3552. const obj = stack[stack.length - 1];
  3553. for (let i = 0; i < items.length; i += 2) {
  3554. if (obj.__setitem__) {
  3555. obj.__setitem__(items[i], items[i + 1]);
  3556. }
  3557. else {
  3558. obj[items[i]] = items[i + 1];
  3559. }
  3560. }
  3561. break;
  3562. }
  3563. case OpCode.EMPTY_DICT:
  3564. stack.push({});
  3565. break;
  3566. case OpCode.APPEND: {
  3567. const append = stack.pop();
  3568. stack[stack.length-1].push(append);
  3569. break;
  3570. }
  3571. case OpCode.APPENDS: {
  3572. const appends = stack;
  3573. stack = marker.pop();
  3574. const list = stack[stack.length - 1];
  3575. list.push.apply(list, appends);
  3576. break;
  3577. }
  3578. case OpCode.STRING: {
  3579. const str = reader.line();
  3580. stack.push(str.substr(1, str.length - 2));
  3581. break;
  3582. }
  3583. case OpCode.BINSTRING:
  3584. stack.push(reader.string(reader.uint32()));
  3585. break;
  3586. case OpCode.SHORT_BINSTRING:
  3587. stack.push(reader.string(reader.byte()));
  3588. break;
  3589. case OpCode.UNICODE:
  3590. stack.push(reader.line());
  3591. break;
  3592. case OpCode.BINUNICODE:
  3593. stack.push(reader.string(reader.uint32(), 'utf-8'));
  3594. break;
  3595. case OpCode.SHORT_BINUNICODE:
  3596. stack.push(reader.string(reader.byte(), 'utf-8'));
  3597. break;
  3598. case OpCode.BUILD: {
  3599. const state = stack.pop();
  3600. let obj = stack.pop();
  3601. if (obj.__setstate__) {
  3602. if (obj.__setstate__.__call__) {
  3603. obj.__setstate__.__call__([ obj, state ]);
  3604. }
  3605. else {
  3606. obj.__setstate__(state);
  3607. }
  3608. }
  3609. else if (ArrayBuffer.isView(state) || Object(state) !== state) {
  3610. obj.__state__ = state;
  3611. }
  3612. else if (obj instanceof Map) {
  3613. for (const key in state) {
  3614. obj.set(key, state[key]);
  3615. }
  3616. }
  3617. else {
  3618. Object.assign(obj, state);
  3619. }
  3620. if (obj.__read__) {
  3621. obj = obj.__read__(this);
  3622. }
  3623. stack.push(obj);
  3624. break;
  3625. }
  3626. case OpCode.MARK:
  3627. marker.push(stack);
  3628. stack = [];
  3629. break;
  3630. case OpCode.NEWTRUE:
  3631. stack.push(true);
  3632. break;
  3633. case OpCode.NEWFALSE:
  3634. stack.push(false);
  3635. break;
  3636. case OpCode.LONG1: {
  3637. const data = reader.read(reader.byte());
  3638. let number = 0;
  3639. switch (data.length) {
  3640. case 0: number = 0; break;
  3641. case 1: number = data[0]; break;
  3642. case 2: number = data[1] << 8 | data[0]; break;
  3643. case 3: number = data[2] << 16 | data[1] << 8 | data[0]; break;
  3644. case 4: number = data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]; break;
  3645. case 5: number = data[4] * 0x100000000 + ((data[3] << 24 | data[2] << 16 | data[1] << 8 | data[0]) >>> 0); break;
  3646. default: number = Array.prototype.slice.call(data, 0); break;
  3647. }
  3648. stack.push(number);
  3649. break;
  3650. }
  3651. case OpCode.LONG4:
  3652. // TODO decode LONG4
  3653. stack.push(reader.read(reader.uint32()));
  3654. break;
  3655. case OpCode.TUPLE1:
  3656. stack.push([ stack.pop() ]);
  3657. break;
  3658. case OpCode.TUPLE2: {
  3659. const b = stack.pop();
  3660. const a = stack.pop();
  3661. stack.push([ a, b ]);
  3662. break;
  3663. }
  3664. case OpCode.TUPLE3: {
  3665. const c = stack.pop();
  3666. const b = stack.pop();
  3667. const a = stack.pop();
  3668. stack.push([ a, b, c ]);
  3669. break;
  3670. }
  3671. case OpCode.MEMOIZE:
  3672. memo.set(memo.size, stack[stack.length - 1]);
  3673. break;
  3674. case OpCode.FRAME:
  3675. reader.read(8);
  3676. break;
  3677. case OpCode.BYTEARRAY8: {
  3678. stack.push(reader.read(reader.int64()));
  3679. break;
  3680. }
  3681. case OpCode.NONE:
  3682. stack.push(null);
  3683. break;
  3684. case OpCode.STOP:
  3685. return stack.pop();
  3686. default:
  3687. throw new python.Error('Unknown opcode ' + opcode + ' at position ' + (reader.position - 1).toString() + '.');
  3688. }
  3689. }
  3690. throw new python.Error('Unexpected end of file.');
  3691. }
  3692. read(size) {
  3693. return this._reader.read(size);
  3694. }
  3695. stream(size) {
  3696. return this._reader.stream(size);
  3697. }
  3698. int32() {
  3699. return this._reader.int32();
  3700. }
  3701. int64() {
  3702. return this._reader.int64();
  3703. }
  3704. unescape(token, size) {
  3705. const length = token.length;
  3706. const a = new Uint8Array(length);
  3707. if (size && size == length) {
  3708. for (let p = 0; p < size; p++) {
  3709. a[p] = token.charCodeAt(p);
  3710. }
  3711. return a;
  3712. }
  3713. let i = 0;
  3714. let o = 0;
  3715. while (i < length) {
  3716. let c = token.charCodeAt(i++);
  3717. if (c !== 0x5C || i >= length) {
  3718. a[o++] = c;
  3719. }
  3720. else {
  3721. c = token.charCodeAt(i++);
  3722. switch (c) {
  3723. case 0x27: a[o++] = 0x27; break; // '
  3724. case 0x5C: a[o++] = 0x5C; break; // \\
  3725. case 0x22: a[o++] = 0x22; break; // "
  3726. case 0x72: a[o++] = 0x0D; break; // \r
  3727. case 0x6E: a[o++] = 0x0A; break; // \n
  3728. case 0x74: a[o++] = 0x09; break; // \t
  3729. case 0x62: a[o++] = 0x08; break; // \b
  3730. case 0x58: // x
  3731. case 0x78: { // X
  3732. const xsi = i - 1;
  3733. const xso = o;
  3734. for (let xi = 0; xi < 2; xi++) {
  3735. if (i >= length) {
  3736. i = xsi;
  3737. o = xso;
  3738. a[o] = 0x5c;
  3739. break;
  3740. }
  3741. let xd = token.charCodeAt(i++);
  3742. xd = xd >= 65 && xd <= 70 ? xd - 55 : xd >= 97 && xd <= 102 ? xd - 87 : xd >= 48 && xd <= 57 ? xd - 48 : -1;
  3743. if (xd === -1) {
  3744. i = xsi;
  3745. o = xso;
  3746. a[o] = 0x5c;
  3747. break;
  3748. }
  3749. a[o] = a[o] << 4 | xd;
  3750. }
  3751. o++;
  3752. break;
  3753. }
  3754. default:
  3755. if (c < 48 || c > 57) { // 0-9
  3756. a[o++] = 0x5c;
  3757. a[o++] = c;
  3758. }
  3759. else {
  3760. i--;
  3761. const osi = i;
  3762. const oso = o;
  3763. for (let oi = 0; oi < 3; oi++) {
  3764. if (i >= length) {
  3765. i = osi;
  3766. o = oso;
  3767. a[o] = 0x5c;
  3768. break;
  3769. }
  3770. const od = token.charCodeAt(i++);
  3771. if (od < 48 || od > 57) {
  3772. i = osi;
  3773. o = oso;
  3774. a[o] = 0x5c;
  3775. break;
  3776. }
  3777. a[o] = a[o] << 3 | od - 48;
  3778. }
  3779. o++;
  3780. }
  3781. break;
  3782. }
  3783. }
  3784. }
  3785. return a.slice(0, o);
  3786. }
  3787. };
  3788. // https://svn.python.org/projects/python/trunk/Lib/pickletools.py
  3789. // https://github.com/python/cpython/blob/master/Lib/pickle.py
  3790. python.Unpickler.OpCode = {
  3791. MARK: 40, // '('
  3792. EMPTY_TUPLE: 41, // ')'
  3793. STOP: 46, // '.'
  3794. POP: 48, // '0'
  3795. POP_MARK: 49, // '1'
  3796. DUP: 50, // '2'
  3797. BINBYTES: 66, // 'B' (Protocol 3)
  3798. SHORT_BINBYTES: 67, // 'C' (Protocol 3)
  3799. FLOAT: 70, // 'F'
  3800. BINFLOAT: 71, // 'G'
  3801. INT: 73, // 'I'
  3802. BININT: 74, // 'J'
  3803. BININT1: 75, // 'K'
  3804. LONG: 76, // 'L'
  3805. BININT2: 77, // 'M'
  3806. NONE: 78, // 'N'
  3807. PERSID: 80, // 'P'
  3808. BINPERSID: 81, // 'Q'
  3809. REDUCE: 82, // 'R'
  3810. STRING: 83, // 'S'
  3811. BINSTRING: 84, // 'T'
  3812. SHORT_BINSTRING: 85, // 'U'
  3813. UNICODE: 86, // 'V'
  3814. BINUNICODE: 88, // 'X'
  3815. EMPTY_LIST: 93, // ']'
  3816. APPEND: 97, // 'a'
  3817. BUILD: 98, // 'b'
  3818. GLOBAL: 99, // 'c'
  3819. DICT: 100, // 'd'
  3820. APPENDS: 101, // 'e'
  3821. GET: 103, // 'g'
  3822. BINGET: 104, // 'h'
  3823. INST: 105, // 'i'
  3824. LONG_BINGET: 106, // 'j'
  3825. LIST: 108, // 'l'
  3826. OBJ: 111, // 'o'
  3827. PUT: 112, // 'p'
  3828. BINPUT: 113, // 'q'
  3829. LONG_BINPUT: 114, // 'r'
  3830. SETITEM: 115, // 's'
  3831. TUPLE: 116, // 't'
  3832. SETITEMS: 117, // 'u'
  3833. EMPTY_DICT: 125, // '}'
  3834. PROTO: 128,
  3835. NEWOBJ: 129,
  3836. TUPLE1: 133, // '\x85'
  3837. TUPLE2: 134, // '\x86'
  3838. TUPLE3: 135, // '\x87'
  3839. NEWTRUE: 136, // '\x88'
  3840. NEWFALSE: 137, // '\x89'
  3841. LONG1: 138, // '\x8a'
  3842. LONG4: 139, // '\x8b'
  3843. SHORT_BINUNICODE: 140, // '\x8c' (Protocol 4)
  3844. BINUNICODE8: 141, // '\x8d' (Protocol 4)
  3845. BINBYTES8: 142, // '\x8e' (Protocol 4)
  3846. EMPTY_SET: 143, // '\x8f' (Protocol 4)
  3847. ADDITEMS: 144, // '\x90' (Protocol 4)
  3848. FROZENSET: 145, // '\x91' (Protocol 4)
  3849. NEWOBJ_EX: 146, // '\x92' (Protocol 4)
  3850. STACK_GLOBAL: 147, // '\x93' (Protocol 4)
  3851. MEMOIZE: 148, // '\x94' (Protocol 4)
  3852. FRAME: 149, // '\x95' (Protocol 4)
  3853. BYTEARRAY8: 150, // '\x96' (Protocol 5)
  3854. NEXT_BUFFER: 151, // '\x97' (Protocol 5)
  3855. READONLY_BUFFER: 152 // '\x98' (Protocol 5)
  3856. };
  3857. python.Unpickler.BinaryReader = class {
  3858. constructor(buffer) {
  3859. this._buffer = buffer;
  3860. this._length = buffer.length;
  3861. this._position = 0;
  3862. this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  3863. this._utf8Decoder = new TextDecoder('utf-8');
  3864. this._asciiDecoder = new TextDecoder('ascii');
  3865. }
  3866. get position() {
  3867. return this._position;
  3868. }
  3869. get length() {
  3870. return this._length;
  3871. }
  3872. seek(position) {
  3873. this._position = position >= 0 ? position : this._length + position;
  3874. if (this._position > this._buffer.length) {
  3875. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3876. }
  3877. }
  3878. skip(offset) {
  3879. this._position += offset;
  3880. if (this._position > this._buffer.length) {
  3881. throw new python.Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3882. }
  3883. }
  3884. stream(length) {
  3885. const buffer = this.read(length);
  3886. return new python.Unpickler.BinaryReader(buffer);
  3887. }
  3888. peek(length) {
  3889. const position = this._position;
  3890. length = length !== undefined ? length : this._length - this._position;
  3891. this.skip(length);
  3892. const end = this._position;
  3893. this.skip(-length);
  3894. if (position === 0 && length === this._length) {
  3895. return this._buffer;
  3896. }
  3897. return this._buffer.subarray(position, end);
  3898. }
  3899. read(length) {
  3900. const position = this._position;
  3901. length = length !== undefined ? length : this._length - this._position;
  3902. this.skip(length);
  3903. if (position === 0 && length === this._length) {
  3904. return this._buffer;
  3905. }
  3906. return this._buffer.subarray(position, this._position);
  3907. }
  3908. byte() {
  3909. const position = this._position;
  3910. this.skip(1);
  3911. return this._view.getUint8(position);
  3912. }
  3913. uint16() {
  3914. const position = this._position;
  3915. this.skip(2);
  3916. return this._view.getUint16(position, true);
  3917. }
  3918. int32() {
  3919. const position = this._position;
  3920. this.skip(4);
  3921. return this._view.getInt32(position, true);
  3922. }
  3923. uint32() {
  3924. const position = this._position;
  3925. this.skip(4);
  3926. return this._view.getUint32(position, true);
  3927. }
  3928. int64() {
  3929. const position = this._position;
  3930. this.skip(8);
  3931. return this._view.getInt64(position, true).toNumber();
  3932. }
  3933. float32() {
  3934. const position = this._position;
  3935. this.skip(4);
  3936. return this._view.getFloat32(position, true);
  3937. }
  3938. float64() {
  3939. const position = this._position;
  3940. this.skip(8);
  3941. return this._view.getFloat64(position, true);
  3942. }
  3943. string(size, encoding) {
  3944. const data = this.read(size);
  3945. return (encoding == 'utf-8') ?
  3946. this._utf8Decoder.decode(data) :
  3947. this._asciiDecoder.decode(data);
  3948. }
  3949. line() {
  3950. const index = this._buffer.indexOf(0x0A, this._position);
  3951. if (index == -1) {
  3952. throw new python.Error("Could not find end of line.");
  3953. }
  3954. const size = index - this._position;
  3955. const text = this.string(size, 'ascii');
  3956. this.skip(1);
  3957. return text;
  3958. }
  3959. };
  3960. python.Unpickler.StreamReader = class {
  3961. constructor(stream) {
  3962. this._stream = stream;
  3963. this._length = stream.length;
  3964. this._position = 0;
  3965. this._utf8Decoder = new TextDecoder('utf-8');
  3966. this._asciiDecoder = new TextDecoder('ascii');
  3967. }
  3968. get position() {
  3969. return this._position;
  3970. }
  3971. get length() {
  3972. return this._length;
  3973. }
  3974. seek(position) {
  3975. this._stream.seek(position);
  3976. this._position = this._stream.position;
  3977. }
  3978. skip(offset) {
  3979. this._position += offset;
  3980. if (this._position > this._length) {
  3981. throw new python.Error('Expected ' + (this._position - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  3982. }
  3983. }
  3984. stream(length) {
  3985. this._stream.seek(this._position);
  3986. this.skip(length);
  3987. return this._stream.stream(length);
  3988. }
  3989. peek(length) {
  3990. this._stream.seek(this._position);
  3991. return this._stream.peek(length);
  3992. }
  3993. read(length) {
  3994. this._stream.seek(this._position);
  3995. this.skip(length);
  3996. return this._stream.read(length);
  3997. }
  3998. byte() {
  3999. const position = this._fill(1);
  4000. return this._view.getUint8(position);
  4001. }
  4002. uint16() {
  4003. const position = this._fill(2);
  4004. return this._view.getUint16(position, true);
  4005. }
  4006. int32() {
  4007. const position = this._fill(4);
  4008. return this._view.getInt32(position, true);
  4009. }
  4010. uint32() {
  4011. const position = this._fill(4);
  4012. return this._view.getUint32(position, true);
  4013. }
  4014. int64() {
  4015. const position = this._fill(8);
  4016. return this._view.getInt64(position, true).toNumber();
  4017. }
  4018. float32() {
  4019. const position = this._fill(4);
  4020. return this._view.getFloat32(position, true);
  4021. }
  4022. float64() {
  4023. const position = this._fill(8);
  4024. return this._view.getFloat64(position, true);
  4025. }
  4026. string(size, encoding) {
  4027. const data = this.read(size);
  4028. return (encoding == 'utf-8') ?
  4029. this._utf8Decoder.decode(data) :
  4030. this._asciiDecoder.decode(data);
  4031. }
  4032. line() {
  4033. let position = this._fill(0);
  4034. let index = this._buffer.indexOf(0x0A, position);
  4035. if (index == -1) {
  4036. const size = Math.min(0x1000000, this._stream.length - this._position);
  4037. this._fill(size);
  4038. this.skip(-size);
  4039. position = this._fill(0);
  4040. index = this._buffer.indexOf(0x0A, position);
  4041. if (index == -1) {
  4042. throw new python.Error("Could not find end of line.");
  4043. }
  4044. }
  4045. const size = index - position;
  4046. const text = this.string(size, 'ascii');
  4047. this.skip(1);
  4048. return text;
  4049. }
  4050. _fill(length) {
  4051. if (this._position + length > this._length) {
  4052. throw new Error('Expected ' + (this._position + length - this._length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  4053. }
  4054. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  4055. this._offset = this._position;
  4056. this._stream.seek(this._offset);
  4057. this._buffer = this._stream.read(Math.min(0x10000000, this._length - this._offset));
  4058. this._view = new DataView(this._buffer.buffer, this._buffer.byteOffset, this._buffer.byteLength);
  4059. }
  4060. const position = this._position;
  4061. this._position += length;
  4062. return position - this._offset;
  4063. }
  4064. };
  4065. python.Error = class extends Error {
  4066. constructor(message) {
  4067. super(message);
  4068. this.name = 'Error loading Python module.';
  4069. }
  4070. };
  4071. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  4072. module.exports.Execution = python.Execution;
  4073. module.exports.Unpickler = python.Unpickler;
  4074. }