python.js 143 KB

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