brython.js (732739B)
1 // brython.js brython.info 2 // version [3, 8, 0, 'final', 0] 3 // implementation [3, 8, 10, 'final', 0] 4 // version compiled from commented, indented source files at 5 // github.com/brython-dev/brython 6 var __BRYTHON__=__BRYTHON__ ||{} 7 try{ 8 eval("async function* f(){}")}catch(err){console.warn("Your browser is not fully supported. If you are using "+ 9 "Microsoft Edge, please upgrade to the latest version")} 10 ;(function($B){ 11 $B.isWebWorker=('undefined' !==typeof WorkerGlobalScope)&& 12 ("function"===typeof importScripts)&& 13 (navigator instanceof WorkerNavigator) 14 $B.isNode=(typeof process !=='undefined')&&(process.release.name==='node') 15 var _window 16 if($B.isNode){_window={location:{href:'',origin:'',pathname:''},navigator:{userLanguage:''}}}else{ 17 _window=self} 18 var href=_window.location.href 19 $B.protocol=href.split(':')[0] 20 $B.BigInt=_window.BigInt 21 var $path 22 if($B.brython_path===undefined){ 23 var this_url; 24 if($B.isWebWorker){this_url=_window.location.href; 25 if(this_url.startsWith("blob:")){this_url=this_url.substr(5)}}else{var scripts=document.getElementsByTagName('script') 26 this_url=scripts[scripts.length-1].src} 27 var elts=this_url.split('/') 28 elts.pop() 29 $path=$B.brython_path=elts.join('/')+'/'}else{if(! $B.brython_path.endsWith("/")){$B.brython_path+="/"} 30 $path=$B.brython_path} 31 var path=_window.location.origin+_window.location.pathname,path_elts=path.split("/") 32 path_elts.pop() 33 var $script_dir=$B.script_dir=path_elts.join("/") 34 $B.__ARGV=[] 35 $B.webworkers={} 36 $B.$py_module_path={} 37 $B.file_cache={} 38 $B.$py_src={} 39 $B.path=[$path+'Lib',$path+'libs',$script_dir,$path+'Lib/site-packages'] 40 $B.async_enabled=false 41 if($B.async_enabled){$B.block={}} 42 $B.imported={} 43 $B.precompiled={} 44 $B.frames_stack=[] 45 $B.builtins={} 46 $B.builtins_scope={id:'__builtins__',module:'__builtins__',binding:{}} 47 $B.builtin_funcs={} 48 $B.builtin_classes=[] 49 $B.__getattr__=function(attr){return this[attr]} 50 $B.__setattr__=function(attr,value){ 51 if(['debug','stdout','stderr'].indexOf(attr)>-1){$B[attr]=value} 52 else{throw $B.builtins.AttributeError.$factory( 53 '__BRYTHON__ object has no attribute '+attr)}} 54 $B.language=_window.navigator.userLanguage ||_window.navigator.language 55 $B.locale="C" 56 if($B.isWebWorker){$B.charset="utf-8"}else{ 57 $B.charset=document.characterSet ||document.inputEncoding ||"utf-8"} 58 $B.max_int=Math.pow(2,53)-1 59 $B.min_int=-$B.max_int 60 $B.$py_next_hash=Math.pow(2,53)-1 61 $B.$py_UUID=0 62 $B.lambda_magic=Math.random().toString(36).substr(2,8) 63 $B.set_func_names=function(klass,module){if(klass.$infos){var name=klass.$infos.__name__ 64 klass.$infos.__module__=module 65 klass.$infos.__qualname__=name}else{var name=klass.__name__ 66 klass.$infos={__name__:name,__module__:module,__qualname__:name}} 67 klass.__module__=module 68 for(var attr in klass){if(typeof klass[attr]=='function'){klass[attr].$infos={__doc__:klass[attr].__doc__ ||"",__module__:module,__qualname__ :name+'.'+attr,__name__:attr} 69 if(klass[attr].$type=="classmethod"){klass[attr].__class__=$B.method}}}} 70 var has_storage=typeof(Storage)!=="undefined" 71 if(has_storage){$B.has_local_storage=false 72 try{if(localStorage){$B.local_storage=localStorage 73 $B.has_local_storage=true}}catch(err){} 74 $B.has_session_storage=false 75 try{if(sessionStorage){$B.session_storage=sessionStorage 76 $B.has_session_storage=true}}catch(err){}}else{$B.has_local_storage=false 77 $B.has_session_storage=false} 78 $B.globals=function(){ 79 return $B.frames_stack[$B.frames_stack.length-1][3]} 80 $B.scripts={} 81 $B.$options={} 82 $B.update_VFS=function(scripts){$B.VFS=$B.VFS ||{} 83 var vfs_timestamp=scripts.$timestamp 84 if(vfs_timestamp !==undefined){delete scripts.$timestamp} 85 for(var script in scripts){if($B.VFS.hasOwnProperty(script)){console.warn("Virtual File System: duplicate entry "+script)} 86 $B.VFS[script]=scripts[script] 87 $B.VFS[script].timestamp=vfs_timestamp}} 88 $B.add_files=function(files){ 89 $B.files=$B.files ||{} 90 for(var file in files){$B.files[file]=files[file]}} 91 $B.python_to_js=function(src,script_id){$B.meta_path=$B.$meta_path.slice() 92 if(!$B.use_VFS){$B.meta_path.shift()} 93 if(script_id===undefined){script_id="__main__"} 94 var root=__BRYTHON__.py2js(src,script_id,script_id),js=root.to_js() 95 js="(function() {\n var $locals_"+script_id+" = {}\n"+js+"\n}())" 96 return js} 97 _window.py=function(src){ 98 var root=$B.py2js(src[0],"script","script"),js=root.to_js() 99 $B.set_import_paths() 100 new Function("$locals_script",js)({})}})(__BRYTHON__) 101 ; 102 __BRYTHON__.implementation=[3,8,10,'final',0] 103 __BRYTHON__.__MAGIC__="3.8.10" 104 __BRYTHON__.version_info=[3,8,0,'final',0] 105 __BRYTHON__.compiled_date="2020-12-22 19:11:55.764534" 106 __BRYTHON__.timestamp=1608660715764 107 __BRYTHON__.builtin_module_names=["_aio","_ajax","_base64","_binascii","_io_classes","_json","_jsre","_locale","_multiprocessing","_posixsubprocess","_profile","_sre_utils","_string","_strptime","_svg","_warnings","_webcomponent","_webworker","_zlib_utils","array","builtins","dis","hashlib","long_int","marshal","math","modulefinder","posix","random","unicodedata"] 108 ; 109 110 ;(function($B){Number.isInteger=Number.isInteger ||function(value){return typeof value==='number' && 111 isFinite(value)&& 112 Math.floor(value)===value}; 113 Number.isSafeInteger=Number.isSafeInteger ||function(value){return Number.isInteger(value)&& Math.abs(value)<=Number.MAX_SAFE_INTEGER;}; 114 var js,$pos,res,$op 115 var _b_=$B.builtins 116 var _window 117 if($B.isNode){_window={location:{href:'',origin:'',pathname:''}}}else{ 118 _window=self} 119 $B.parser={} 120 var clone=$B.clone=function(obj){var res={} 121 for(var attr in obj){res[attr]=obj[attr]} 122 return res} 123 $B.last=function(table){if(table===undefined){console.log($B.frames_stack.slice())} 124 return table[table.length-1]} 125 $B.list2obj=function(list,value){var res={},i=list.length 126 if(value===undefined){value=true} 127 while(i--> 0){res[list[i]]=value} 128 return res} 129 $B.op2method={operations:{"**":"pow","//":"floordiv","<<":"lshift",">>":"rshift","+":"add","-":"sub","*":"mul","/":"truediv","%":"mod","@":"matmul" },augmented_assigns:{"//=":"ifloordiv",">>=":"irshift","<<=":"ilshift","**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv","%=":"imod","&=":"iand","|=":"ior","^=":"ixor","@=":"imatmul"},binary:{"&":"and","|":"or","~":"invert","^":"xor"},comparisons:{"<":"lt",">":"gt","<=":"le",">=":"ge","==":"eq","!=":"ne"},boolean:{"or":"or","and":"and","in":"in","not":"not","is":"is","not_in":"not_in","is_not":"is_not" },subset:function(){var res={},keys=[] 130 if(arguments[0]=="all"){keys=Object.keys($B.op2method) 131 keys.splice(keys.indexOf("subset"),1)}else{for(var i=0,len=arguments.length;i < len;i++){keys.push(arguments[i])}} 132 for(var i=0,len=keys.length;i < len;i++){var key=keys[i],ops=$B.op2method[key] 133 if(ops===undefined){throw Error(key)} 134 for(var attr in ops){res[attr]=ops[attr]}} 135 return res}} 136 var $operators=$B.op2method.subset("all") 137 var $augmented_assigns=$B.augmented_assigns=$B.op2method.augmented_assigns 138 var noassign=$B.list2obj(['True','False','None','__debug__']) 139 var $op_order=[['or'],['and'],['not'],['in','not_in'],['<','<=','>','>=','!=','==','is','is_not'],['|'],['^'],['&'],['>>','<<'],['+'],['-'],['*','@','/','//','%'],['unary_neg','unary_inv','unary_pos'],['**'] 140 ] 141 var $op_weight={},$weight=1 142 $op_order.forEach(function(_tmp){_tmp.forEach(function(item){$op_weight[item]=$weight}) 143 $weight++}) 144 var $loop_num=0 145 var create_temp_name=$B.parser.create_temp_name=function(prefix){var _prefix=prefix ||'$temp' 146 return _prefix+$loop_num++;} 147 var replace_node=$B.parser.replace_node=function(replace_what,replace_with){var parent=replace_what.parent 148 var pos=get_rank_in_parent(replace_what) 149 parent.children[pos]=replace_with 150 replace_with.parent=parent 151 replace_with.bindings=replace_what.bindings} 152 var get_rank_in_parent=$B.parser.get_rank_in_parent=function(node){return node.parent.children.indexOf(node)} 153 var add_identnode=$B.parser.add_identnode=function(parent,insert_at,name,val){var new_node=new $Node() 154 new_node.parent=parent 155 new_node.locals=parent.locals 156 new_node.module=parent.module 157 var new_ctx=new $NodeCtx(new_node) 158 var expr_ctx=new $ExprCtx(new_ctx,'id',true) 159 var idctx=new $IdCtx(expr_ctx,name) 160 var assign=new $AssignCtx(expr_ctx) 161 if(insert_at===-1) 162 parent.add(new_node) 163 else 164 parent.insert(insert_at,new_node) 165 assign.tree[1]=val 166 return new_node} 167 var chained_comp_num=0 168 var $_SyntaxError=$B.parser.$_SyntaxError=function(C,msg,indent){ 169 var ctx_node=C 170 while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} 171 var tree_node=ctx_node.node,root=tree_node 172 while(root.parent !==undefined){root=root.parent} 173 var module=tree_node.module,src=root.src,line_num=tree_node.line_num 174 if(src){line_num=src.substr(0,$pos).split("\n").length} 175 if(root.line_info){line_num=root.line_info} 176 if(indent===undefined ||typeof indent !="number"){if(Array.isArray(msg)){$B.$SyntaxError(module,msg[0],src,$pos,line_num,root)} 177 if(msg==="Triple string end not found"){ 178 $B.$SyntaxError(module,'invalid syntax : triple string end not found',src,$pos,line_num,root)} 179 var message='invalid syntax' 180 if(!(msg.startsWith("token "))){message+=' ('+msg+')'} 181 $B.$SyntaxError(module,message,src,$pos,line_num,root)}else{throw $B.$IndentationError(module,msg,src,$pos,line_num,root)}} 182 function SyntaxWarning(C,msg){var node=$get_node(C),module=$get_module(C),src=module.src,lines=src.split("\n"),message=`Module ${module.module}line ${node.line_num}:${msg}\n`+ 183 ' '+lines[node.line_num-1] 184 $B.$getattr($B.stderr,"write")(message)} 185 function check_assignment(C){var ctx=C,forbidden=['assert','del','import','raise','return'] 186 while(ctx){if(forbidden.indexOf(ctx.type)>-1){$_SyntaxError(C,'invalid syntax - assign')}else if(ctx.type=="expr" && 187 ctx.tree[0].type=="op"){if($B.op2method.comparisons[ctx.tree[0].op]!==undefined){$_SyntaxError(C,["cannot assign to comparison"])}else{$_SyntaxError(C,["cannot assign to operator"])}} 188 ctx=ctx.parent}} 189 var $Node=$B.parser.$Node=function(type){this.type=type 190 this.children=[]} 191 $Node.prototype.add=function(child){ 192 this.children[this.children.length]=child 193 child.parent=this 194 child.module=this.module} 195 $Node.prototype.insert=function(pos,child){ 196 this.children.splice(pos,0,child) 197 child.parent=this 198 child.module=this.module} 199 $Node.prototype.toString=function(){return "<object 'Node'>"} 200 $Node.prototype.show=function(indent){ 201 var res='' 202 if(this.type==='module'){this.children.forEach(function(child){res+=child.show(indent)}) 203 return res} 204 indent=indent ||0 205 res+=' '.repeat(indent) 206 res+=this.C 207 if(this.children.length > 0){res+='{'} 208 res+='\n' 209 this.children.forEach(function(child){res+='['+i+'] '+child.show(indent+4)}) 210 if(this.children.length > 0){res+=' '.repeat(indent) 211 res+='}\n'} 212 return res} 213 $Node.prototype.to_js=function(indent){ 214 if(this.js !==undefined){return this.js} 215 this.res=[] 216 this.unbound=[] 217 if(this.type==='module'){this.children.forEach(function(child){this.res.push(child.to_js())},this) 218 this.js=this.res.join('') 219 return this.js} 220 indent=indent ||0 221 var ctx_js=this.C.to_js() 222 if(ctx_js){ 223 this.res.push(' '.repeat(indent)) 224 this.res.push(ctx_js) 225 if(this.children.length > 0){this.res.push('{')} 226 this.res.push('\n') 227 this.children.forEach(function(child){this.res.push(child.to_js(indent+4))},this) 228 if(this.children.length > 0){this.res.push(' '.repeat(indent)) 229 this.res.push('}\n')}} 230 this.js=this.res.join('') 231 return this.js} 232 $Node.prototype.transform=function(rank){ 233 if(this.has_await){this.parent.insert(rank,$NodeJS("var save_stack = $B.save_stack()")) 234 this.parent.insert(rank+2,$NodeJS("$B.restore_stack(save_stack, $locals)")) 235 this.has_await=false 236 return 1} 237 if(this.has_yield && ! this.has_yield.transformed){ 238 var parent=this.parent 239 if(this.has_yield.from){var new_node=new $Node() 240 var new_ctx=new $NodeCtx(new_node) 241 var new_expr=new $ExprCtx(new_ctx,'js',false) 242 var _id=new $RawJSCtx(new_expr,`var _i${this.has_yield.from_num}`) 243 var assign=new $AssignCtx(new_expr) 244 var right=new $ExprCtx(assign) 245 right.tree=this.has_yield.tree 246 parent.insert(rank,new_node) 247 var pnode=$get_node(this.has_yield) 248 var n=this.has_yield.from_num 249 var replace_with=`$B.$import("sys",[],{}) 250 _i${n}=_b_.iter(_i${n}) 251 var $failed${n}=false 252 try{var _y${n}=_b_.next(_i${n})}catch(_e){$B.set_exc(_e) 253 $failed${n}=true 254 $B.pmframe=$B.last($B.frames_stack) 255 _e=$B.exception(_e) 256 if(_e.__class__===_b_.StopIteration){var _r${n}=$B.$getattr(_e,"value")}else{throw _e}} 257 if(! $failed${n}){while(true){var $failed1${n}=false 258 try{$B.leave_frame({$locals}) 259 var _s${n}=yield _y${n} 260 $B.frames_stack.push($top_frame)}catch(_e){if(_e.__class__===_b_.GeneratorExit){var $failed2${n}=false 261 try{var _m${n}=$B.$geatttr(_i${n},"close")}catch(_e1){$failed2${n}=true 262 if(_e1.__class__ !==_b_.AttributeError){throw _e1}} 263 if(! $failed2${n}){$B.$call(_m${n})()} 264 throw _e}else if($B.is_exc(_e,[_b_.BaseException])){var _x=$B.$call($B.$getattr($locals.sys,"exc_info"))() 265 var $failed3${n}=false 266 try{var _m${n}=$B.$getattr(_i${n},"throw")}catch(err){$failed3${n}=true 267 if($B.is_exc(err,[_b_.AttributeError])){throw err}} 268 if(! $failed3${n}){try{_y${n}=$B.$call(_m${n}).apply(null,_b_.list.$factory(_x${n}))}catch(err){if($B.$is_exc(err,[_b_.StopIteration])){_r${n}=$B.$getattr(err,"value") 269 break} 270 throw err}}}} 271 if(! $failed1${n}){try{if(_s${n}===_b_.None){_y${n}=_b_.next(_i${n})}else{_y${n}=$B.$call($B.$getattr(_i${n},"send"))(_s${n})}}catch(err){if($B.is_exc(err,[_b_.StopIteration])){_r${n}=$B.$getattr(err,"value") 272 break} 273 throw err}}}}` 274 parent.insert(rank+1,$NodeJS(replace_with)) 275 return 3} 276 parent.children.splice(rank,1) 277 if(this.has_yield.tree[0].type==='abstract_expr'){new_node=$NodeJS("var result = _b_.None")}else{var new_node=new $Node() 278 var new_ctx=new $NodeCtx(new_node) 279 var new_expr=new $ExprCtx(new_ctx,'js',false) 280 var _id=new $RawJSCtx(new_expr,'var result') 281 var assign=new $AssignCtx(new_expr) 282 assign.tree[1]=this.has_yield.tree[0] 283 _id.parent=assign} 284 new_node.line_num=this.line_num 285 parent.insert(rank,new_node) 286 var try_node=new $NodeJS("try") 287 try_node.add($NodeJS("$B.leave_frame({$locals})")) 288 try_node.add(this) 289 parent.insert(rank+1,try_node) 290 this.has_yield.to_js=function(){return 'yield result'} 291 this.has_yield.transformed=true 292 var i=0 293 while(i < try_node.children.length){var offset=try_node.children[i].transform(i) 294 if(offset===undefined){offset=1} 295 i+=offset} 296 var catch_node=$NodeJS(`catch(err${this.line_num})`) 297 catch_node.add($NodeJS("$B.frames_stack.push($top_frame)")) 298 catch_node.add($NodeJS(`throw err${this.line_num}`)) 299 parent.insert(rank+2,catch_node) 300 parent.insert(rank+3,$NodeJS("$B.frames_stack.push($top_frame)")) 301 return 2} 302 if(this.type==='module'){ 303 this.__doc__=$get_docstring(this) 304 var i=0 305 while(i < this.children.length){var offset=this.children[i].transform(i) 306 if(offset===undefined){offset=1} 307 i+=offset}}else{var elt=this.C.tree[0],ctx_offset 308 if(elt===undefined){console.log(this)} 309 if(elt.transform !==undefined){ctx_offset=elt.transform(this,rank)} 310 var i=0 311 while(i < this.children.length){var offset=this.children[i].transform(i) 312 if(offset===undefined){offset=1} 313 i+=offset} 314 if(ctx_offset===undefined){ctx_offset=1} 315 return ctx_offset}} 316 $Node.prototype.clone=function(){var res=new $Node(this.type) 317 for(var attr in this){res[attr]=this[attr]} 318 return res} 319 $Node.prototype.clone_tree=function(){var res=new $Node(this.type) 320 for(var attr in this){res[attr]=this[attr]} 321 res.children=[] 322 for(var i=0,len=this.children.length;i < len;i++){res.add(this.children[i].clone_tree())} 323 return res} 324 var $AbstractExprCtx=$B.parser.$AbstractExprCtx=function(C,with_commas){this.type='abstract_expr' 325 this.with_commas=with_commas 326 this.parent=C 327 this.tree=[] 328 C.tree[C.tree.length]=this} 329 $AbstractExprCtx.prototype.toString=function(){return '(abstract_expr '+this.with_commas+') '+this.tree} 330 $AbstractExprCtx.prototype.transition=function(token,value){var C=this 331 var packed=C.packed,is_await=C.is_await,assign=C.assign 332 if(! assign){switch(token){case 'id': 333 case 'imaginary': 334 case 'int': 335 case 'float': 336 case 'str': 337 case 'bytes': 338 case '[': 339 case '(': 340 case '{': 341 case '.': 342 case 'not': 343 case 'lambda': 344 case 'yield': 345 C.parent.tree.pop() 346 var commas=C.with_commas 347 C=C.parent 348 C.packed=packed 349 C.is_await=is_await 350 if(assign){console.log("set assign to parent",C) 351 C.assign=assign}}} 352 switch(token){case 'await': 353 return new $AwaitCtx(C) 354 case 'id': 355 return new $IdCtx(new $ExprCtx(C,'id',commas),value) 356 case 'str': 357 return new $StringCtx(new $ExprCtx(C,'str',commas),value) 358 case 'bytes': 359 return new $StringCtx(new $ExprCtx(C,'bytes',commas),value) 360 case 'int': 361 return new $NumberCtx('int',new $ExprCtx(C,'int',commas),value) 362 case 'float': 363 return new $NumberCtx('float',new $ExprCtx(C,'float',commas),value) 364 case 'imaginary': 365 return new $NumberCtx('imaginary',new $ExprCtx(C,'imaginary',commas),value) 366 case '(': 367 return new $ListOrTupleCtx( 368 new $ExprCtx(C,'tuple',commas),'tuple') 369 case '[': 370 return new $ListOrTupleCtx( 371 new $ExprCtx(C,'list',commas),'list') 372 case '{': 373 return new $DictOrSetCtx( 374 new $ExprCtx(C,'dict_or_set',commas)) 375 case '.': 376 return new $EllipsisCtx( 377 new $ExprCtx(C,'ellipsis',commas)) 378 case 'not': 379 if(C.type=='op' && C.op=='is'){ 380 C.op='is_not' 381 return C} 382 return new $NotCtx(new $ExprCtx(C,'not',commas)) 383 case 'lambda': 384 return new $LambdaCtx(new $ExprCtx(C,'lambda',commas)) 385 case 'op': 386 var tg=value 387 switch(tg){case '*': 388 C.parent.tree.pop() 389 var commas=C.with_commas 390 C=C.parent 391 return new $PackedCtx( 392 new $ExprCtx(C,'expr',commas)) 393 case '-': 394 case '~': 395 case '+': 396 C.parent.tree.pop() 397 var left=new $UnaryCtx(C.parent,tg) 398 if(tg=='-'){var op_expr=new $OpCtx(left,'unary_neg')}else if(tg=='+'){var op_expr=new $OpCtx(left,'unary_pos')}else{var op_expr=new $OpCtx(left,'unary_inv')} 399 return new $AbstractExprCtx(op_expr,false) 400 case 'not': 401 C.parent.tree.pop() 402 var commas=C.with_commas 403 C=C.parent 404 return new $NotCtx( 405 new $ExprCtx(C,'not',commas))} 406 $_SyntaxError(C,'token '+token+' after '+ 407 C) 408 case '=': 409 $_SyntaxError(C,'token '+token+' after '+ 410 C) 411 case 'yield': 412 return new $AbstractExprCtx(new $YieldCtx(C),true) 413 case ':': 414 if(C.parent.type=="sub" || 415 (C.parent.type=="list_or_tuple" && 416 C.parent.parent.type=="sub")){return new $AbstractExprCtx(new $SliceCtx(C.parent),false)} 417 return $transition(C.parent,token,value) 418 case ')': 419 case ',': 420 switch(C.parent.type){case 'list_or_tuple': 421 case 'slice': 422 case 'call_arg': 423 case 'op': 424 case 'yield': 425 break 426 case 'annotation': 427 $_SyntaxError(C,"empty annotation") 428 default: 429 $_SyntaxError(C,token)}} 430 return $transition(C.parent,token,value)} 431 $AbstractExprCtx.prototype.to_js=function(){this.js_processed=true 432 if(this.type==='list')return '['+$to_js(this.tree)+']' 433 return $to_js(this.tree)} 434 var $AliasCtx=$B.parser.$AliasCtx=function(C){ 435 this.type='ctx_manager_alias' 436 this.parent=C 437 this.tree=[] 438 C.tree[C.tree.length-1].alias=this} 439 $AliasCtx.prototype.transition=function(token,value){var C=this 440 switch(token){case ',': 441 case ':': 442 C.parent.set_alias(C.tree[0].tree[0]) 443 return $transition(C.parent,token,value)} 444 $_SyntaxError(C,'token '+token+' after '+C)} 445 var $AnnotationCtx=$B.parser.$AnnotationCtx=function(C){ 446 this.type='annotation' 447 this.parent=C 448 this.tree=[] 449 C.annotation=this 450 var scope=$get_scope(C) 451 if(scope.binding.__annotations__===undefined){ 452 scope.binding.__annotations__=true 453 C.create_annotations=true} 454 if(scope.ntype=="def" && C.tree && C.tree.length > 0 && 455 C.tree[0].type=="id"){var name=C.tree[0].value 456 if(scope.globals && scope.globals.has(name)>-1){$_SyntaxError(C,["annotated name '"+name+ 457 "' can't be global"])} 458 scope.annotations=scope.annotations ||new Set() 459 scope.annotations.add(name) 460 if(! C.$in_parens){scope.binding=scope.binding ||{} 461 scope.binding[name]=true}}} 462 $AnnotationCtx.prototype.toString=function(){return '(annotation) '+this.tree} 463 $AnnotationCtx.prototype.transition=function(token,value){var C=this 464 if(token=="eol" && C.tree.length==1 && 465 C.tree[0].tree.length==0){$_SyntaxError(C,"empty annotation")}else if(token==':' && C.parent.type !="def"){$_SyntaxError(C,"more than one annotation")}else if(token=="augm_assign"){$_SyntaxError(C,"augmented assign as annotation")}else if(token=="op"){$_SyntaxError(C,"operator as annotation")} 466 return $transition(C.parent,token)} 467 $AnnotationCtx.prototype.to_js=function(){return $to_js(this.tree)} 468 var $AssertCtx=$B.parser.$AssertCtx=function(C){ 469 this.type='assert' 470 this.parent=C 471 this.tree=[] 472 C.tree[C.tree.length]=this} 473 $AssertCtx.prototype.toString=function(){return '(assert) '+this.tree} 474 $AssertCtx.prototype.transition=function(token,value){var C=this 475 if(token==","){if(this.tree.length > 1){$_SyntaxError(C,"too many commas after assert")} 476 return new $AbstractExprCtx(this,false)} 477 if(token=='eol'){return $transition(C.parent,token)} 478 $_SyntaxError(C,token)} 479 $AssertCtx.prototype.transform=function(node,rank){if(this.tree.length > 1){ 480 var condition=this.tree[0] 481 var message=this.tree[1]}else{var condition=this.tree[0] 482 var message=null} 483 if(this.tree[0].type=="expr" && this.tree[0].name=="tuple" && 484 this.tree[0].tree[0].tree.length > 1){SyntaxWarning(this,"assertion is always true, perhaps "+ 485 "remove parentheses?")} 486 var new_ctx=new $ConditionCtx(node.C,'if') 487 var not_ctx=new $NotCtx(new_ctx) 488 not_ctx.tree=[condition] 489 node.C=new_ctx 490 var new_node=new $Node() 491 var js='throw _b_.AssertionError.$factory()' 492 if(message !==null){js='throw _b_.AssertionError.$factory(_b_.str.$factory('+ 493 message.to_js()+'))'} 494 new $NodeJSCtx(new_node,js) 495 node.add(new_node)} 496 var $AssignCtx=$B.parser.$AssignCtx=function(C,expression){ 497 check_assignment(C) 498 if(C.type=="expr" && C.tree[0].type=="lambda"){$_SyntaxError(C,["cannot assign to lambda"])} 499 this.type='assign' 500 if(expression=='expression'){this.expression=true 501 console.log("parent of assign expr",C.parent)} 502 C.parent.tree.pop() 503 C.parent.tree[C.parent.tree.length]=this 504 this.parent=C.parent 505 this.tree=[C] 506 var scope=$get_scope(this) 507 if(C.type=='expr' && C.tree[0].type=='call'){$_SyntaxError(C,["cannot assign to function call "])}else if(C.type=='list_or_tuple' || 508 (C.type=='expr' && C.tree[0].type=='list_or_tuple')){if(C.type=='expr'){C=C.tree[0]} 509 C.bind_ids(scope)}else if(C.type=='assign'){C.tree.forEach(function(elt){var assigned=elt.tree[0] 510 if(assigned.type=='id'){$bind(assigned.value,scope,this)}},this)}else{var assigned=C.tree[0] 511 if(assigned && assigned.type=='id'){if(noassign[assigned.value]===true){$_SyntaxError(C,["cannot assign to keyword"])} 512 assigned.bound=true 513 if(!scope.globals ||!scope.globals.has(assigned.value)){ 514 var node=$get_node(this) 515 node.bound_before=Object.keys(scope.binding) 516 $bind(assigned.value,scope,this)}else{ 517 var module=$get_module(C) 518 assigned.global_module=module.module 519 $bind(assigned.value,module,this)}}else if(["str","int","float","complex"].indexOf(assigned.type)>-1){$_SyntaxError(C,["cannot assign to literal"])}else if(assigned.type=="unary"){$_SyntaxError(C,["cannot assign to operator"])}}} 520 $AssignCtx.prototype.guess_type=function(){return} 521 $AssignCtx.prototype.toString=function(){return '(assign) '+this.tree[0]+'='+this.tree[1]} 522 $AssignCtx.prototype.transition=function(token,value){var C=this 523 if(token=='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+ 524 C)} 525 C.guess_type() 526 return $transition(C.parent,'eol')} 527 $_SyntaxError(C,'token '+token+' after '+C)} 528 $AssignCtx.prototype.transform=function(node,rank){ 529 var scope=$get_scope(this) 530 var left=this.tree[0],right=this.tree[1],assigned=[] 531 while(left.type=='assign'){assigned.push(left.tree[1]) 532 left=left.tree[0]} 533 if(assigned.length > 0){assigned.push(left) 534 var ctx=node.C 535 ctx.tree=[] 536 var nleft=new $RawJSCtx(ctx,'var $temp'+$loop_num) 537 nleft.tree=ctx.tree 538 var nassign=new $AssignCtx(nleft) 539 nassign.tree[1]=right 540 assigned.forEach(function(elt){if(elt.type=="expr" && elt.tree[0].type=="list_or_tuple" && 541 elt.tree[0].real=="tuple" && 542 elt.tree[0].tree.length==1){ 543 elt=elt.tree[0].tree[0]} 544 var new_node=new $Node(),node_ctx=new $NodeCtx(new_node) 545 new_node.locals=node.locals 546 new_node.line_num=node.line_num 547 node.parent.insert(rank+1,new_node) 548 elt.parent=node_ctx 549 var assign=new $AssignCtx(elt) 550 new $RawJSCtx(assign,'$temp'+$loop_num)}) 551 $loop_num++ 552 this.tree[0]=left 553 return} 554 var left_items=null 555 switch(left.type){case 'expr': 556 if(left.tree.length > 1){left_items=left.tree}else if(left.tree[0].type=='list_or_tuple' || 557 left.tree[0].type=='target_list'){left_items=left.tree[0].tree}else if(left.tree[0].type=='id'){ 558 var name=left.tree[0].value 559 if(scope.globals && scope.globals.has(name)){}else{left.tree[0].bound=true}} 560 break 561 case 'target_list': 562 case 'list_or_tuple': 563 left_items=left.tree} 564 var right=this.tree[1] 565 if(left_items===null){if(left.tree[0].bound){if(right.type=="expr" && right.name=="int"){node.bindings=node.bindings ||{} 566 node.bindings[left.tree[0].value]="int"}} 567 return} 568 var right_items=null 569 if(right.type=='list' ||right.type=='tuple'|| 570 (right.type=='expr' && right.tree.length > 1)){right_items=right.tree} 571 if(right_items !==null){ 572 if(right_items.length > left_items.length){throw Error('ValueError : too many values to unpack (expected '+ 573 left_items.length+')')}else if(right_items.length < left_items.length){throw Error('ValueError : need more than '+ 574 right_items.length+' to unpack')} 575 var new_nodes=[],pos=0 576 var new_node=new $Node() 577 new_node.line_num=node.line_num 578 new $NodeJSCtx(new_node,'void(0)') 579 new_nodes[pos++]=new_node 580 var $var='$temp'+$loop_num 581 var new_node=new $Node() 582 new_node.line_num=node.line_num 583 new $NodeJSCtx(new_node,'var '+$var+' = [], $pos = 0') 584 new_nodes[pos++]=new_node 585 right_items.forEach(function(right_item){var js=$var+'[$pos++] = '+right_item.to_js() 586 var new_node=new $Node() 587 new_node.line_num=node.line_num 588 new $NodeJSCtx(new_node,js) 589 new_nodes[pos++]=new_node}) 590 var this_node=$get_node(this) 591 left_items.forEach(function(left_item){var new_node=new $Node() 592 new_node.id=this_node.module 593 new_node.locals=this_node.locals 594 new_node.line_num=node.line_num 595 var C=new $NodeCtx(new_node) 596 left_item.parent=C 597 var assign=new $AssignCtx(left_item,false) 598 assign.tree[1]=new $JSCode($var+'['+i+']') 599 new_nodes[pos++]=new_node},this) 600 node.parent.children.splice(rank,1) 601 for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank,new_nodes[i])} 602 $loop_num++}else{ 603 node.parent.children.splice(rank,1) 604 var rname=create_temp_name('$right') 605 var rlname=create_temp_name('$rlist'); 606 var new_node=$NodeJS('var '+rname+' = '+ 607 '$B.$getattr($B.$iter('+right.to_js()+ 608 '), "__next__");') 609 new_node.line_num=node.line_num 610 node.parent.insert(rank++,new_node) 611 node.parent.insert(rank++,$NodeJS('var '+rlname+'=[], $pos=0;'+ 612 'while(1){'+ 613 'try{'+ 614 rlname+'[$pos++] = '+rname+'()'+ 615 '}catch(err){'+ 616 'break'+ 617 '}'+ 618 '}') 619 ) 620 var packed=null 621 var min_length=left_items.length 622 for(var i=0;i < left_items.length;i++){var expr=left_items[i] 623 if(expr.type=='packed' || 624 (expr.type=='expr' && expr.tree[0].type=='packed')){packed=i 625 min_length-- 626 break}} 627 node.parent.insert(rank++,$NodeJS('if('+rlname+'.length<'+min_length+'){'+ 628 'throw _b_.ValueError.$factory('+ 629 '"need more than " +'+rlname+ 630 '.length + " value" + ('+rlname+ 631 '.length > 1 ?'+' "s" : "") + " to unpack")}' 632 ) 633 ) 634 if(packed==null){node.parent.insert(rank++,$NodeJS('if('+rlname+'.length>'+min_length+'){'+ 635 'throw _b_.ValueError.$factory('+ 636 '"too many values to unpack '+ 637 '(expected '+left_items.length+')"'+ 638 ')'+ 639 '}') 640 )} 641 left_items.forEach(function(left_item,i){var new_node=new $Node() 642 new_node.id=scope.id 643 new_node.line_num=node.line_num 644 node.parent.insert(rank++,new_node) 645 var C=new $NodeCtx(new_node) 646 left_item.parent=C 647 var assign=new $AssignCtx(left_item,false) 648 var js=rlname 649 if(packed==null ||i < packed){js+='['+i+']'}else if(i==packed){js+='.slice('+i+','+rlname+'.length-'+ 650 (left_items.length-i-1)+')'}else{js+='['+rlname+'.length-'+(left_items.length-i)+']'} 651 assign.tree[1]=new $JSCode(js)}) 652 $loop_num++}} 653 $AssignCtx.prototype.to_js=function(){this.js_processed=true 654 if(this.parent.type=='call'){ 655 return '{$nat:"kw",name:'+this.tree[0].to_js()+ 656 ',value:'+this.tree[1].to_js()+'}'} 657 var left=this.tree[0] 658 while(left.type=='expr' && ! left.assign){left=left.tree[0]} 659 var right=this.tree[1] 660 if(left.type=='attribute' ||left.type=='sub'){ 661 var right_js=right.to_js() 662 var res='',rvar='',$var='$temp'+$loop_num 663 if(right.type=='expr' && right.tree[0]!==undefined && 664 right.tree[0].type=='call' && 665 ('eval'==right.tree[0].func.value || 666 'exec'==right.tree[0].func.value)){res+='var '+$var+' = '+right_js+';\n' 667 rvar=$var}else if(right.type=='expr' && right.tree[0]!==undefined && 668 right.tree[0].type=='sub'){res+='var '+$var+' = '+right_js+';\n' 669 rvar=$var}else{rvar=right_js} 670 if(left.type=='attribute'){ 671 $loop_num++ 672 left.func='setattr' 673 var left_to_js=left.to_js() 674 left.func='getattr' 675 if(left.assign_self){return res+left_to_js[0]+rvar+left_to_js[1]+rvar+')'} 676 res+=left_to_js 677 res=res.substr(0,res.length-1) 678 return res+','+rvar+');_b_.None;'} 679 if(left.type=='sub'){ 680 var seq=left.value.to_js(),temp='$temp'+$loop_num,type 681 if(left.value.type=='id'){type=$get_node(this).locals[left.value.value]} 682 $loop_num++ 683 var res='var '+temp+' = '+seq+'\n' 684 if(type !=='list'){res+='if(Array.isArray('+temp+') && !'+ 685 temp+'.__class__){'} 686 if(left.tree.length==1){res+='$B.set_list_key('+temp+','+ 687 (left.tree[0].to_js()+'' ||'null')+','+ 688 right.to_js()+')'}else if(left.tree.length==2){res+='$B.set_list_slice('+temp+','+ 689 (left.tree[0].to_js()+'' ||'null')+','+ 690 (left.tree[1].to_js()+'' ||'null')+','+ 691 right.to_js()+')'}else if(left.tree.length==3){res+='$B.set_list_slice_step('+temp+','+ 692 (left.tree[0].to_js()+'' ||'null')+','+ 693 (left.tree[1].to_js()+'' ||'null')+','+ 694 (left.tree[2].to_js()+'' ||'null')+','+ 695 right.to_js()+')'} 696 if(type=='list'){return res} 697 res+='\n}else{' 698 if(left.tree.length==1){res+='$B.$setitem('+left.value.to_js()+ 699 ','+left.tree[0].to_js()+','+right_js+')};_b_.None;'}else{left.func='setitem' 700 res+=left.to_js() 701 res=res.substr(0,res.length-1) 702 left.func='getitem' 703 res+=','+right_js+')};_b_.None;'} 704 return res}} 705 return left.to_js()+' = '+right.to_js()} 706 var $AsyncCtx=$B.parser.$AsyncCtx=function(C){ 707 this.type='async' 708 this.parent=C 709 C.async=true} 710 $AsyncCtx.prototype.toString=function(){return '(async)'} 711 $AsyncCtx.prototype.transition=function(token,value){var C=this 712 if(token=="def"){return $transition(C.parent,token,value)}else if(token=="for" ||token=="with"){var ntype=$get_scope(C).ntype 713 if(ntype !=="def" && ntype !="generator"){$_SyntaxError(C,["'async "+token+ 714 "' outside async function"])} 715 var ctx=$transition(C.parent,token,value) 716 ctx.parent.async=true 717 return ctx} 718 $_SyntaxError(C,'token '+token+' after '+C)} 719 var $AttrCtx=$B.parser.$AttrCtx=function(C){ 720 this.type='attribute' 721 this.value=C.tree[0] 722 this.parent=C 723 C.tree.pop() 724 C.tree[C.tree.length]=this 725 this.tree=[] 726 this.func='getattr' } 727 $AttrCtx.prototype.toString=function(){return '(attr) '+this.value+'.'+this.name} 728 $AttrCtx.prototype.transition=function(token,value){var C=this 729 if(token==='id'){var name=value 730 if(noassign[name]===true){$_SyntaxError(C,["cannot assign to "+name])} 731 name=$mangle(name,C) 732 C.name=name 733 return C.parent} 734 $_SyntaxError(C,token)} 735 $AttrCtx.prototype.to_js=function(){this.js_processed=true 736 var js=this.value.to_js() 737 if(this.func=="setattr" && this.value.type=="id"){var scope=$get_scope(this),parent=scope.parent 738 if(scope.ntype=="def"){if(parent.ntype=="class"){var params=scope.C.tree[0].positional_list 739 if(this.value.value==params[0]&& parent.C && 740 parent.C.tree[0].args===undefined){ 741 this.assign_self=true 742 return[js+".__class__ && "+js+".__dict__ && !"+ 743 js+".__class__.$has_setattr && ! "+js+ 744 ".$is_class ? _b_.dict.$setitem("+js+ 745 ".__dict__, '"+this.name+ 746 "', ",") : $B.$setattr("+js+ 747 ', "'+this.name+'", ']}}}} 748 if(this.func=='setattr'){ 749 return '$B.$setattr('+js+',"'+this.name+'")'}else{return '$B.$getattr('+js+',"'+this.name+'")'}} 750 var $AugmentedAssignCtx=$B.parser.$AugmentedAssignCtx=function(C,op){ 751 check_assignment(C) 752 this.type='augm_assign' 753 this.C=C 754 this.parent=C.parent 755 C.parent.tree.pop() 756 C.parent.tree[C.parent.tree.length]=this 757 this.op=op 758 this.tree=[C] 759 var scope=this.scope=$get_scope(this) 760 if(C.type=='expr'){var assigned=C.tree[0] 761 if(assigned.type=='id'){var name=assigned.value 762 if(noassign[name]===true){$_SyntaxError(C,["cannot assign to keyword"])}else if((scope.ntype=='def' ||scope.ntype=='generator')&& 763 (scope.binding[name]===undefined)){if(scope.globals===undefined || 764 ! scope.globals.has(name)){ 765 assigned.unbound=true}}}else if(['str','int','float','complex'].indexOf(assigned.type)>-1){$_SyntaxError(C,["cannot assign to literal"])}} 766 $get_node(this).bound_before=Object.keys(scope.binding) 767 this.module=scope.module} 768 $AugmentedAssignCtx.prototype.toString=function(){return '(augm assign) '+this.tree} 769 $AugmentedAssignCtx.prototype.transition=function(token,value){var C=this 770 if(token=='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+ 771 C)} 772 return $transition(C.parent,'eol')} 773 $_SyntaxError(C,'token '+token+' after '+C)} 774 $AugmentedAssignCtx.prototype.transform=function(node,rank){var C=this.C,op=this.op,func='__'+$operators[op]+'__',offset=0,parent=node.parent,line_num=node.line_num,lnum_set=false 775 parent.children.splice(rank,1) 776 var left_is_id=(this.tree[0].type=='expr' && 777 this.tree[0].tree[0].type=='id') 778 if(left_is_id){var left_bound_to_int= 779 this.tree[0].tree[0].bindingType(this.scope)=="int" 780 this.tree[0].tree[0].augm_assign=true 781 if($B.debug > 0){var check_node=$NodeJS('if('+this.tree[0].to_js()+ 782 ' === undefined){throw _b_.NameError.$factory("name \'' + 783 this.tree[0].tree[0].value + '\' is not defined")}') 784 node.parent.insert(rank,check_node) 785 offset++} 786 var left_id=this.tree[0].tree[0].value,was_bound=this.scope.binding[left_id]!==undefined,left_id_unbound=this.tree[0].tree[0].unbound} 787 var right_is_int=(this.tree[1].type=='expr' && 788 this.tree[1].tree[0].type=='int') 789 if(right_is_int){var value=this.tree[1].tree[0].value,to_int=parseInt(value[1],value[0]) 790 right_is_int=(to_int > $B.min_int)&&(to_int < $B.max_int)} 791 var right=right_is_int ? this.tree[1].tree[0].to_js():'$temp' 792 if(!right_is_int){ 793 var new_node=new $Node() 794 new_node.line_num=line_num 795 lnum_set=true 796 new $NodeJSCtx(new_node,'var $temp,$left;') 797 parent.insert(rank,new_node) 798 offset++ 799 var new_node=new $Node() 800 new_node.id=this.scope.id 801 var new_ctx=new $NodeCtx(new_node) 802 var new_expr=new $ExprCtx(new_ctx,'js',false) 803 var _id=new $RawJSCtx(new_expr,'$temp') 804 var assign=new $AssignCtx(new_expr) 805 assign.tree[1]=this.tree[1] 806 _id.parent=assign 807 parent.insert(rank+offset,new_node) 808 offset++} 809 var prefix='',in_class=false 810 switch(op){case '+=': 811 case '-=': 812 case '*=': 813 case '/=': 814 if(left_is_id){var scope=this.scope,global_ns='$local_'+scope.module.replace(/\./g,'_') 815 switch(scope.ntype){case 'module': 816 prefix=global_ns 817 break 818 case 'def': 819 case 'generator': 820 if(scope.globals && 821 scope.globals.has(C.tree[0].value)){prefix=global_ns}else{prefix='$locals'} 822 break 823 case 'class': 824 var new_node=new $Node() 825 if(!lnum_set){new_node.line_num=line_num 826 lnum_set=true} 827 new $NodeJSCtx(new_node,'var $left = '+ 828 C.to_js()) 829 parent.insert(rank+offset,new_node) 830 in_class=true 831 offset++}}} 832 var left=C.tree[0].to_js() 833 if(C.tree[0].type=="id"){var binding_scope=C.tree[0].firstBindingScopeId(),left_value=C.tree[0].value 834 if(binding_scope){left="$locals_"+binding_scope.replace(/\./g,'_')+ 835 '["'+left_value+'"]'}else{left='$locals["'+left_value+'"]'}} 836 if(left_bound_to_int && right_is_int && 837 op !="//="){ 838 parent.insert(rank+offset,$NodeJS(left+" "+op+" "+right)) 839 return offset++} 840 prefix=prefix && !C.tree[0].unknown_binding && !left_id_unbound 841 var op1=op.charAt(0) 842 if(prefix){var left1=in_class ? '$left' :left 843 var new_node=new $Node() 844 if(!lnum_set){new_node.line_num=line_num;lnum_set=true} 845 js=right_is_int ? 'if(' :'if(typeof $temp.valueOf() == "number" && ' 846 js+=left1+'.constructor === Number' 847 js+=' && Number.isSafeInteger('+left+op1+right+')){'+ 848 (right_is_int ? '(' :'(typeof $temp == "number" && ')+ 849 'typeof '+left1+' == "number") ? ' 850 js+=left+op+right 851 js+=' : '+left+' = new Number('+left+op1+ 852 (right_is_int ? right :right+'.valueOf()')+')}' 853 new $NodeJSCtx(new_node,js) 854 parent.insert(rank+offset,new_node) 855 offset++} 856 var aaops={'+=':'add','-=':'sub','*=':'mul'} 857 if(C.tree[0].type=='sub' && 858 ('+='==op ||'-='==op ||'*='==op)&& 859 C.tree[0].tree.length==1){var js1='$B.augm_item_'+aaops[op]+'('+ 860 C.tree[0].value.to_js()+','+ 861 C.tree[0].tree[0].to_js()+','+right+');_b_.None;' 862 var new_node=new $Node() 863 if(!lnum_set){new_node.line_num=line_num;lnum_set=true} 864 new $NodeJSCtx(new_node,js1) 865 parent.insert(rank+offset,new_node) 866 offset++ 867 return} 868 var new_node=new $Node() 869 if(!lnum_set){new_node.line_num=line_num;lnum_set=true} 870 var js='' 871 if(prefix){js+='else '} 872 js+='if(! _b_.hasattr('+C.to_js()+',"'+func+'"))' 873 new $NodeJSCtx(new_node,js) 874 parent.insert(rank+offset,new_node) 875 offset++ 876 var aa1=new $Node() 877 aa1.id=this.scope.id 878 aa1.line_num=node.line_num 879 new_node.add(aa1) 880 var ctx1=new $NodeCtx(aa1) 881 var expr1=new $ExprCtx(ctx1,'clone',false) 882 if(left_id_unbound){new $RawJSCtx(expr1,left)}else{expr1.tree=C.tree 883 expr1.tree.forEach(function(elt){elt.parent=expr1})} 884 var assign1=new $AssignCtx(expr1) 885 var new_op=new $OpCtx(expr1,op.substr(0,op.length-1)) 886 new_op.parent=assign1 887 new $RawJSCtx(new_op,right) 888 assign1.tree.push(new_op) 889 expr1.parent.tree.pop() 890 expr1.parent.tree.push(assign1) 891 var else_node=$NodeJS("else") 892 parent.insert(rank+offset,else_node) 893 var aa2=new $Node() 894 aa2.line_num=node.line_num 895 else_node.add(aa2) 896 var ctx2=new $NodeCtx(aa2) 897 var expr2=new $ExprCtx(ctx2,'clone',false) 898 if(left_id_unbound){var js=left 899 if(! binding_scope){js='$B.$local_search("'+left_value+'");'+left} 900 new $RawJSCtx(expr2,js)}else{expr2.tree=C.tree 901 expr2.tree.forEach(function(elt){elt.parent=expr2})} 902 var assign2=new $AssignCtx(expr2) 903 assign2.tree.push($NodeJS('$B.$getattr('+C.to_js()+',"'+ 904 func+'")('+right+')')) 905 expr2.parent.tree.pop() 906 expr2.parent.tree.push(assign2) 907 if(left_is_id && !was_bound && !this.scope.blurred){this.scope.binding[left_id]=undefined} 908 return offset} 909 $AugmentedAssignCtx.prototype.to_js=function(){return ''} 910 var $AwaitCtx=$B.parser.$AwaitCtx=function(C){ 911 this.type='await' 912 this.parent=C 913 this.tree=[] 914 C.tree.push(this) 915 var p=C 916 while(p){if(p.type=="list_or_tuple"){p.is_await=true} 917 p=p.parent}} 918 $AwaitCtx.prototype.transition=function(token,value){var C=this 919 C.parent.is_await=true 920 return $transition(C.parent,token,value)} 921 $AwaitCtx.prototype.to_js=function(){return 'var save_stack = $B.save_stack();'+ 922 'await ($B.promise('+$to_js(this.tree)+'));'+ 923 '$B.restore_stack(save_stack, $locals); '} 924 var $BodyCtx=$B.parser.$BodyCtx=function(C){ 925 var ctx_node=C.parent 926 while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} 927 var tree_node=ctx_node.node 928 var body_node=new $Node() 929 body_node.is_body_node=true 930 body_node.line_num=tree_node.line_num 931 tree_node.insert(0,body_node) 932 return new $NodeCtx(body_node)} 933 var set_loop_context=$B.parser.set_loop_context=function(C,kw){ 934 var ctx_node=C 935 while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} 936 var tree_node=ctx_node.node 937 var loop_node=tree_node.parent 938 var break_flag=false 939 while(1){if(loop_node.type=='module'){ 940 $_SyntaxError(C,kw+' outside of a loop')}else{var ctx=loop_node.C.tree[0] 941 if(ctx.type=='condition' && ctx.token=='while'){this.loop_ctx=ctx 942 ctx['has_'+kw]=true 943 break} 944 switch(ctx.type){case 'for': 945 this.loop_ctx=ctx 946 ctx['has_'+kw]=true 947 break_flag=true 948 break 949 case 'def': 950 case 'generator': 951 case 'class': 952 $_SyntaxError(C,kw+' outside of a loop') 953 default: 954 loop_node=loop_node.parent} 955 if(break_flag){break}}}} 956 var $BreakCtx=$B.parser.$BreakCtx=function(C){ 957 this.type='break' 958 this.parent=C 959 C.tree[C.tree.length]=this 960 set_loop_context.apply(this,[C,'break'])} 961 $BreakCtx.prototype.toString=function(){return 'break '} 962 $BreakCtx.prototype.transition=function(token,value){var C=this 963 if(token=='eol'){return $transition(C.parent,'eol')} 964 $_SyntaxError(C,token)} 965 $BreakCtx.prototype.to_js=function(){this.js_processed=true 966 var scope=$get_scope(this) 967 var res=';$locals_'+scope.id.replace(/\./g,'_')+ 968 '["$no_break'+this.loop_ctx.loop_num+'"] = false' 969 if(this.loop_ctx.type !='asyncfor'){res+=';break'}else{res+=';throw _b_.StopIteration.$factory('+ 970 this.loop_ctx.loop_num+')'} 971 return res} 972 var $CallArgCtx=$B.parser.$CallArgCtx=function(C){ 973 this.type='call_arg' 974 this.parent=C 975 this.start=$pos 976 this.tree=[] 977 C.tree.push(this) 978 this.expect='id'} 979 $CallArgCtx.prototype.toString=function(){return 'call_arg '+this.tree} 980 $CallArgCtx.prototype.transition=function(token,value){var C=this 981 switch(token){case 'await': 982 case 'id': 983 case 'imaginary': 984 case 'int': 985 case 'float': 986 case 'str': 987 case 'bytes': 988 case '[': 989 case '(': 990 case '{': 991 case '.': 992 case 'not': 993 case 'lambda': 994 if(C.expect=='id'){C.expect=',' 995 var expr=new $AbstractExprCtx(C,false) 996 return $transition(expr,token,value)} 997 break 998 case '=': 999 if(C.expect==','){return new $ExprCtx(new $KwArgCtx(C),'kw_value',false)} 1000 break 1001 case 'for': 1002 if(this.parent.tree.length > 1){$_SyntaxError(C,"non-parenthesized generator expression")} 1003 var lst=new $ListOrTupleCtx(C,'gen_expr') 1004 lst.vars=C.vars 1005 lst.locals=C.locals 1006 lst.intervals=[C.start] 1007 C.tree.pop() 1008 lst.expression=C.tree 1009 C.tree=[lst] 1010 lst.tree=[] 1011 var comp=new $ComprehensionCtx(lst) 1012 return new $TargetListCtx(new $CompForCtx(comp)) 1013 case 'op': 1014 if(C.expect=='id'){var op=value 1015 C.expect=',' 1016 switch(op){case '+': 1017 case '-': 1018 case '~': 1019 return $transition(new $AbstractExprCtx(C,false),token,op) 1020 case '*': 1021 return new $StarArgCtx(C) 1022 case '**': 1023 return new $DoubleStarArgCtx(C)}} 1024 $_SyntaxError(C,'token '+token+' after '+C) 1025 case ')': 1026 if(C.parent.kwargs && 1027 $B.last(C.parent.tree).tree[0]&& 1028 ['kwarg','star_arg','double_star_arg']. 1029 indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword argument after keyword argument'])} 1030 if(C.tree.length > 0){var son=C.tree[C.tree.length-1] 1031 if(son.type=='list_or_tuple' && 1032 son.real=='gen_expr'){son.intervals.push($pos)}} 1033 return $transition(C.parent,token) 1034 case ':': 1035 if(C.expect==',' && 1036 C.parent.parent.type=='lambda'){return $transition(C.parent.parent,token)} 1037 break 1038 case ',': 1039 if(C.expect==','){if(C.parent.kwargs && 1040 ['kwarg','star_arg','double_star_arg']. 1041 indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword argument after keyword argument'])} 1042 return $transition(C.parent,token,value)}} 1043 console.log('token ',token,' after ' ,C) 1044 $_SyntaxError(C,'token '+token+' after '+C)} 1045 $CallArgCtx.prototype.to_js=function(){this.js_processed=true 1046 return $to_js(this.tree)} 1047 var $CallCtx=$B.parser.$CallCtx=function(C){ 1048 this.type='call' 1049 this.func=C.tree[0] 1050 if(this.func !==undefined){ 1051 this.func.parent=this} 1052 this.parent=C 1053 if(C.type !='class'){C.tree.pop() 1054 C.tree[C.tree.length]=this}else{ 1055 C.args=this} 1056 this.expect='id' 1057 this.tree=[] 1058 this.start=$pos 1059 if(this.func && this.func.type=="attribute" && this.func.name=="wait" 1060 && this.func.value.type=="id" && this.func.value.value=="time"){console.log('call',this.func) 1061 $get_node(this).blocking={'type':'wait','call':this}} 1062 if(this.func && this.func.value=='input'){$get_node(this).blocking={'type':'input'}}} 1063 $CallCtx.prototype.toString=function(){return '(call) '+this.func+'('+this.tree+')'} 1064 $CallCtx.prototype.transition=function(token,value){var C=this 1065 switch(token){case ',': 1066 if(C.expect=='id'){$_SyntaxError(C,token)} 1067 C.expect='id' 1068 return C 1069 case 'await': 1070 case 'id': 1071 case 'imaginary': 1072 case 'int': 1073 case 'float': 1074 case 'str': 1075 case 'bytes': 1076 case '[': 1077 case '(': 1078 case '{': 1079 case '.': 1080 case 'not': 1081 case 'lambda': 1082 C.expect=',' 1083 return $transition(new $CallArgCtx(C),token,value) 1084 case ')': 1085 C.end=$pos 1086 return C.parent 1087 case 'op': 1088 C.expect=',' 1089 switch(value){case '-': 1090 case '~': 1091 case '+': 1092 C.expect=',' 1093 return $transition(new $CallArgCtx(C),token,value) 1094 case '*': 1095 C.has_star=true 1096 return new $StarArgCtx(C) 1097 case '**': 1098 C.has_dstar=true 1099 return new $DoubleStarArgCtx(C)} 1100 $_SyntaxError(C,token) 1101 case 'yield': 1102 $_SyntaxError(C,token)} 1103 return $transition(C.parent,token,value)} 1104 $CallCtx.prototype.to_js=function(){this.js_processed=true 1105 if(this.tree.length > 0){if(this.tree[this.tree.length-1].tree.length==0){ 1106 this.tree.pop()}} 1107 var func_js=this.func.to_js() 1108 if(this.func !==undefined){switch(this.func.value){case 'classmethod': 1109 return '_b_.classmethod.$factory('+$to_js(this.tree)+')' 1110 default: 1111 if(this.func.type=='unary'){ 1112 var res='$B.$getattr('+$to_js(this.tree) 1113 switch(this.func.op){case '+': 1114 return res+',"__pos__")()' 1115 case '-': 1116 return res+',"__neg__")()' 1117 case '~': 1118 return res+',"__invert__")()'}}} 1119 var _block=false 1120 var positional=[],kw_args=[],star_args=false,dstar_args=[] 1121 this.tree.forEach(function(arg){var type 1122 switch(arg.type){case 'star_arg': 1123 star_args=true 1124 positional.push([arg.tree[0].tree[0].to_js(),'*']) 1125 break 1126 case 'double_star_arg': 1127 dstar_args.push(arg.tree[0].tree[0].to_js()) 1128 break 1129 case 'id': 1130 positional.push([arg.to_js(),'s']) 1131 break 1132 default: 1133 type=arg.tree[0].type 1134 switch(type){case 'expr': 1135 positional.push([arg.to_js(),'s']) 1136 break 1137 case 'kwarg': 1138 kw_args.push(arg.tree[0].tree[0].value+ 1139 ':'+arg.tree[0].tree[1].to_js()) 1140 break 1141 case 'list_or_tuple': 1142 case 'op': 1143 positional.push([arg.to_js(),'s']) 1144 break 1145 case 'star_arg': 1146 star_args=true 1147 positional.push([arg.tree[0].tree[0].to_js(),'*']) 1148 break 1149 case 'double_star_arg': 1150 dstar_args.push(arg.tree[0].tree[0].to_js()) 1151 break 1152 default: 1153 positional.push([arg.to_js(),'s']) 1154 break} 1155 break}}) 1156 var args_str 1157 if(star_args){ 1158 var p=[] 1159 for(var i=0,len=positional.length;i < len;i++){arg=positional[i] 1160 if(arg[1]=='*'){ 1161 p.push('_b_.list.$factory('+arg[0]+')')}else{var elt=[positional[i][0]] 1162 i++ 1163 while(i < len && positional[i][1]=='s'){elt.push(positional[i][0]) 1164 i++} 1165 i-- 1166 p.push('['+elt.join(',')+']')}} 1167 args_str=p[0] 1168 for(var i=1;i < p.length;i++){args_str+='.concat('+p[i]+')'}}else{for(var i=0,len=positional.length;i < len;i++){positional[i]=positional[i][0]} 1169 args_str=positional.join(', ')} 1170 var kw_args_str='{'+kw_args.join(', ')+'}' 1171 if(dstar_args.length){kw_args_str='{$nat:"kw",kw:['+kw_args_str+','+ 1172 dstar_args.join(', ')+']}'}else if(kw_args_str !='{}'){kw_args_str='{$nat:"kw",kw:'+kw_args_str+'}'}else{kw_args_str=''} 1173 if(star_args && kw_args_str){args_str+='.concat(['+kw_args_str+'])'}else{if(args_str && kw_args_str){args_str+=','+kw_args_str} 1174 else if(!args_str){args_str=kw_args_str}} 1175 if(star_args){ 1176 args_str='.apply(null,'+args_str+')'}else{args_str='('+args_str+')'} 1177 var default_res="$B.$call("+func_js+")"+args_str 1178 if(this.tree.length >-1 && this.func.type=='id' && 1179 this.func.is_builtin){ 1180 var classes=["complex","bytes","bytearray","object","memoryview","int","float","str","list","tuple","dict","set","frozenset","range","slice","zip","bool","type","classmethod","staticmethod","enumerate","reversed","property","$$super","zip","map","filter"] 1181 if($B.builtin_funcs[this.func.value]!==undefined){if(classes.indexOf(this.func.value)==-1){ 1182 return func_js+args_str}else{ 1183 return func_js+".$factory"+args_str}}} 1184 return default_res}} 1185 var $ClassCtx=$B.parser.$ClassCtx=function(C){ 1186 this.type='class' 1187 this.parent=C 1188 this.tree=[] 1189 C.tree[C.tree.length]=this 1190 this.expect='id' 1191 var scope=this.scope=$get_scope(this) 1192 this.parent.node.parent_block=scope 1193 this.parent.node.bound={} 1194 this.parent.node.binding={__annotations__:true}} 1195 $ClassCtx.prototype.toString=function(){return '(class) '+this.name+' '+this.tree+' args '+this.args} 1196 $ClassCtx.prototype.transition=function(token,value){var C=this 1197 switch(token){case 'id': 1198 if(C.expect=='id'){C.set_name(value) 1199 C.expect='(:' 1200 return C} 1201 break 1202 case '(': 1203 return new $CallCtx(C) 1204 case ':': 1205 return $BodyCtx(C)} 1206 $_SyntaxError(C,'token '+token+' after '+C)} 1207 $ClassCtx.prototype.set_name=function(name){var C=this.parent 1208 this.random=$B.UUID() 1209 this.name=name 1210 this.id=C.node.module+'_'+name+'_'+this.random 1211 this.binding={} 1212 this.parent.node.id=this.id 1213 var scope=this.scope,parent_block=scope 1214 var block=scope,parent_classes=[] 1215 while(block.ntype=="class"){parent_classes.splice(0,0,block.C.tree[0].name) 1216 block=block.parent} 1217 this.qualname=parent_classes.concat([name]).join(".") 1218 while(parent_block.C && 1219 parent_block.C.tree[0].type=='class'){parent_block=parent_block.parent} 1220 while(parent_block.C && 1221 'def' !=parent_block.C.tree[0].type && 1222 'generator' !=parent_block.C.tree[0].type){parent_block=parent_block.parent} 1223 this.parent.node.parent_block=parent_block 1224 $bind(name,scope,this) 1225 if(scope.is_function){if(scope.C.tree[0].locals.indexOf(name)==-1){scope.C.tree[0].locals.push(name)}}} 1226 $ClassCtx.prototype.transform=function(node,rank){ 1227 this.doc_string=$get_docstring(node) 1228 this.module=$get_module(this).module.replace(/\./g,'_') 1229 var indent='\n'+' '.repeat(node.indent+12),instance_decl=new $Node(),local_ns='$locals_'+this.id.replace(/\./g,'_'),js='var '+local_ns+' = {'+ 1230 '__annotations__: $B.empty_dict()}, '+ 1231 indent+'$locals = '+local_ns 1232 new $NodeJSCtx(instance_decl,js) 1233 node.insert(0,instance_decl) 1234 var global_scope=this.scope 1235 while(global_scope.parent_block.id !=='__builtins__'){global_scope=global_scope.parent_block} 1236 var global_ns='$locals_'+global_scope.id.replace(/\./g,'_') 1237 var js=' '.repeat(node.indent+4)+ 1238 '$locals.$name = "'+this.name+'"'+indent+ 1239 '$locals.$qualname = "'+this.qualname+'"'+indent+ 1240 '$locals.$is_class = true; '+indent+ 1241 '$locals.$line_info = "'+node.line_num+','+ 1242 this.module+'";'+indent+ 1243 'var $top_frame = ["'+local_ns+'", $locals,'+'"'+ 1244 global_scope.id+'", '+global_ns+']'+ 1245 indent+'$locals.$f_trace = $B.enter_frame($top_frame);'+ 1246 indent+'if($locals.$f_trace !== _b_.None){'+ 1247 '$locals.$f_trace = $B.trace_line()}' 1248 node.insert(1,$NodeJS(js)) 1249 node.add($NodeJS('if($locals.$f_trace !== _b_.None){'+ 1250 '$B.trace_return(_b_.None)}')) 1251 node.add($NodeJS('$B.leave_frame({$locals})')) 1252 var ret_obj=new $Node() 1253 new $NodeJSCtx(ret_obj,'return '+local_ns+';') 1254 node.insert(node.children.length,ret_obj) 1255 var run_func=new $Node() 1256 new $NodeJSCtx(run_func,')();') 1257 node.parent.insert(rank+1,run_func) 1258 var module_name='$locals_'+this.module+'.__name__' 1259 rank++ 1260 node.parent.insert(rank+1,$NodeJS('$'+this.name+'_'+this.random+".__module__ = "+ 1261 module_name)) 1262 var scope=$get_scope(this) 1263 var name_ref=';$locals_'+scope.id.replace(/\./g,'_') 1264 name_ref+='["'+this.name+'"]' 1265 var js=[name_ref+' = $B.$class_constructor("'+this.name],pos=1 1266 js[pos++]='", $'+this.name+'_'+this.random 1267 if(this.args !==undefined){ 1268 var arg_tree=this.args.tree,args=[],kw=[] 1269 arg_tree.forEach(function(_tmp){if(_tmp.tree[0].type=='kwarg'){kw.push(_tmp.tree[0])} 1270 else{args.push(_tmp.to_js())}}) 1271 js[pos++]=', _b_.tuple.$factory(['+args.join(',')+']),[' 1272 var _re=new RegExp('"','g'),_r=[],rpos=0 1273 args.forEach(function(arg){_r[rpos++]='"'+arg.replace(_re,'\\"')+'"'}) 1274 js[pos++]=_r.join(',')+']' 1275 _r=[] 1276 rpos=0 1277 kw.forEach(function(_tmp){_r[rpos++]='["'+_tmp.tree[0].value+'",'+ 1278 _tmp.tree[1].to_js()+']'}) 1279 js[pos++]=',['+_r.join(',')+']'}else{ 1280 js[pos++]=', _b_.tuple.$factory([]),[],[]'} 1281 js[pos++]=')' 1282 var cl_cons=new $Node() 1283 new $NodeJSCtx(cl_cons,js.join('')) 1284 rank++ 1285 node.parent.insert(rank+1,cl_cons) 1286 rank++ 1287 var ds_node=new $Node() 1288 js=name_ref+'.__doc__ = '+(this.doc_string ||'_b_.None')+';' 1289 new $NodeJSCtx(ds_node,js) 1290 node.parent.insert(rank+1,ds_node) 1291 if(scope.ntype=='module'){var w_decl=new $Node() 1292 new $NodeJSCtx(w_decl,'$locals["'+this.name+'"] = '+ 1293 this.name)} 1294 node.parent.insert(rank+2,$NodeJS("_b_.None;")) 1295 this.transformed=true} 1296 $ClassCtx.prototype.to_js=function(){this.js_processed=true 1297 return 'var $'+this.name+'_'+this.random+' = (function()'} 1298 var $CompIfCtx=$B.parser.$CompIfCtx=function(C){ 1299 this.type='comp_if' 1300 C.parent.intervals.push($pos) 1301 this.parent=C 1302 this.tree=[] 1303 C.tree[C.tree.length]=this} 1304 $CompIfCtx.prototype.toString=function(){return '(comp if) '+this.tree} 1305 $CompIfCtx.prototype.transition=function(token,value){var C=this 1306 return $transition(C.parent,token,value)} 1307 $CompIfCtx.prototype.to_js=function(){this.js_processed=true 1308 return $to_js(this.tree)} 1309 var $ComprehensionCtx=$B.parser.$ComprehensionCtx=function(C){ 1310 this.type='comprehension' 1311 this.parent=C 1312 this.tree=[] 1313 C.tree[C.tree.length]=this} 1314 $ComprehensionCtx.prototype.toString=function(){return '(comprehension) '+this.tree} 1315 $ComprehensionCtx.prototype.transition=function(token,value){var C=this 1316 switch(token){case 'if': 1317 return new $AbstractExprCtx(new $CompIfCtx(C),false) 1318 case 'for': 1319 return new $TargetListCtx(new $CompForCtx(C))} 1320 return $transition(C.parent,token,value)} 1321 $ComprehensionCtx.prototype.to_js=function(){this.js_processed=true 1322 var intervals=[] 1323 this.tree.forEach(function(elt){intervals.push(elt.start)}) 1324 return intervals} 1325 var $CompForCtx=$B.parser.$CompForCtx=function(C){ 1326 this.type='comp_for' 1327 C.parent.intervals.push($pos) 1328 this.parent=C 1329 this.tree=[] 1330 this.expect='in' 1331 C.tree[C.tree.length]=this} 1332 $CompForCtx.prototype.toString=function(){return '(comp for) '+this.tree} 1333 $CompForCtx.prototype.transition=function(token,value){var C=this 1334 if(token=='in' && C.expect=='in'){C.expect=null 1335 return new $AbstractExprCtx(new $CompIterableCtx(C),true)} 1336 if(C.expect===null){ 1337 return $transition(C.parent,token,value)} 1338 $_SyntaxError(C,'token '+token+' after '+C)} 1339 $CompForCtx.prototype.to_js=function(){this.js_processed=true 1340 return $to_js(this.tree)} 1341 var $CompIterableCtx=$B.parser.$CompIterableCtx=function(C){ 1342 this.type='comp_iterable' 1343 this.parent=C 1344 this.tree=[] 1345 C.tree[C.tree.length]=this} 1346 $CompIterableCtx.prototype.toString=function(){return '(comp iter) '+this.tree} 1347 $CompIterableCtx.prototype.transition=function(token,value){var C=this 1348 return $transition(C.parent,token,value)} 1349 $CompIterableCtx.prototype.to_js=function(){this.js_processed=true 1350 return $to_js(this.tree)} 1351 var $ConditionCtx=$B.parser.$ConditionCtx=function(C,token){ 1352 this.type='condition' 1353 this.token=token 1354 this.parent=C 1355 this.tree=[] 1356 this.scope=$get_scope(this) 1357 if(token=='while'){this.loop_num=$loop_num++} 1358 C.tree[C.tree.length]=this} 1359 $ConditionCtx.prototype.toString=function(){return this.token+' '+this.tree} 1360 $ConditionCtx.prototype.transition=function(token,value){var C=this 1361 if(token==':'){if(C.tree[0].type=="abstract_expr" && 1362 C.tree[0].tree.length==0){ 1363 $_SyntaxError(C,'token '+token+' after '+C)} 1364 return $BodyCtx(C)} 1365 $_SyntaxError(C,'token '+token+' after '+C)} 1366 $ConditionCtx.prototype.transform=function(node,rank){var scope=$get_scope(this) 1367 if(this.token=="while"){node.parent.insert(rank,$NodeJS('$locals["$no_break'+this.loop_num+'"] = true')) 1368 var module=$get_module(this).module 1369 if($B.last(node.children).C.tree[0].type !="return"){var js='$locals.$line_info = "'+node.line_num+ 1370 ','+module+'";if($locals.$f_trace !== _b_.None){'+ 1371 '$B.trace_line()};_b_.None;' 1372 node.add($NodeJS(js))} 1373 return 2}} 1374 $ConditionCtx.prototype.to_js=function(){this.js_processed=true 1375 var tok=this.token 1376 if(tok=='elif'){tok='else if'} 1377 var res=[tok+'($B.$bool('] 1378 if(tok=='while'){res.push('$locals["$no_break'+this.loop_num+'"] && ')}else if(tok=='else if'){var line_info=$get_node(this).line_num+','+ 1379 $get_scope(this).id 1380 res.push('($B.set_line("'+line_info+'")) && ')} 1381 if(this.tree.length==1){res.push($to_js(this.tree)+'))')}else{ 1382 res.push(this.tree[0].to_js()+'))') 1383 if(this.tree[1].tree.length > 0){res.push('{'+this.tree[1].to_js()+'}')}} 1384 return res.join('')} 1385 var $ContinueCtx=$B.parser.$ContinueCtx=function(C){ 1386 this.type='continue' 1387 this.parent=C 1388 $get_node(this).is_continue=true 1389 C.tree[C.tree.length]=this 1390 set_loop_context.apply(this,[C,'continue'])} 1391 $ContinueCtx.prototype.toString=function(){return '(continue)'} 1392 $ContinueCtx.prototype.transition=function(token,value){var C=this 1393 if(token=='eol'){return C.parent} 1394 $_SyntaxError(C,'token '+token+' after '+C)} 1395 $ContinueCtx.prototype.to_js=function(){this.js_processed=true 1396 var js='continue' 1397 if(this.loop_ctx.has_break){ 1398 js=`$locals["$no_break${this.loop_ctx.loop_num}"]=true;${js}`} 1399 return js} 1400 var $DebuggerCtx=$B.parser.$DebuggerCtx=function(C){ 1401 this.type='continue' 1402 this.parent=C 1403 C.tree[C.tree.length]=this} 1404 $DebuggerCtx.prototype.toString=function(){return '(debugger)'} 1405 $DebuggerCtx.prototype.transition=function(token,value){var C=this} 1406 $DebuggerCtx.prototype.to_js=function(){this.js_processed=true 1407 return 'debugger'} 1408 var $DecoratorCtx=$B.parser.$DecoratorCtx=function(C){ 1409 this.type='decorator' 1410 this.parent=C 1411 C.tree[C.tree.length]=this 1412 this.tree=[]} 1413 $DecoratorCtx.prototype.toString=function(){return '(decorator) '+this.tree} 1414 $DecoratorCtx.prototype.transition=function(token,value){var C=this 1415 if(token=='id' && C.tree.length==0){return $transition(new $AbstractExprCtx(C,false),token,value)} 1416 if(token=='eol'){return $transition(C.parent,token)} 1417 $_SyntaxError(C,'token '+token+' after '+C)} 1418 $DecoratorCtx.prototype.transform=function(node,rank){var func_rank=rank+1,children=node.parent.children,decorators=[this.tree] 1419 while(1){if(func_rank >=children.length){$_SyntaxError(C,['decorator expects function'])} 1420 else if(children[func_rank].C.type=='node_js'){func_rank++}else if(children[func_rank].C.tree[0].type== 1421 'decorator'){decorators.push(children[func_rank].C.tree[0].tree) 1422 children.splice(func_rank,1)}else{break}} 1423 this.dec_ids=[] 1424 var pos=0 1425 decorators.forEach(function(){this.dec_ids.push('$id'+$B.UUID())},this) 1426 var obj=children[func_rank].C.tree[0] 1427 if(obj.type=='def'){obj.decorated=true 1428 obj.alias='$dec'+$B.UUID()} 1429 var tail='',scope=$get_scope(this),ref='$locals["' 1430 if(scope.globals && scope.globals.has(obj.name)){var module=$get_module(this) 1431 ref='$locals_'+module.id+'["'} 1432 ref+=obj.name+'"]' 1433 var res=ref+' = ' 1434 decorators.forEach(function(elt,i){res+='$B.$call('+this.dec_ids[i]+')(' 1435 tail+=')'},this) 1436 res+=(obj.decorated ? obj.alias :ref)+tail+';' 1437 $bind(obj.name,scope,this) 1438 node.parent.insert(func_rank+1,$NodeJS(res)) 1439 this.decorators=decorators} 1440 $DecoratorCtx.prototype.to_js=function(){this.js_processed=true 1441 var res=[] 1442 this.decorators.forEach(function(decorator,i){res.push('var '+this.dec_ids[i]+' = '+ 1443 $to_js(decorator)+';')},this) 1444 return res.join('')} 1445 var $DefCtx=$B.parser.$DefCtx=function(C){this.type='def' 1446 this.name=null 1447 this.parent=C 1448 this.tree=[] 1449 this.async=C.async 1450 this.locals=[] 1451 C.tree[C.tree.length]=this 1452 this.enclosing=[] 1453 var scope=this.scope=$get_scope(this) 1454 if(scope.C && scope.C.tree[0].type=="class"){this.class_name=scope.C.tree[0].name} 1455 C.node.binding={} 1456 var parent_block=scope 1457 while(parent_block.C && 1458 parent_block.C.tree[0].type=='class'){parent_block=parent_block.parent} 1459 while(parent_block.C && 1460 'def' !=parent_block.C.tree[0].type){parent_block=parent_block.parent} 1461 this.parent.node.parent_block=parent_block 1462 var pb=parent_block 1463 this.is_comp=pb.is_comp 1464 while(pb && pb.C){if(pb.C.tree[0].type=='def'){this.inside_function=true 1465 break} 1466 pb=pb.parent_block} 1467 this.module=scope.module 1468 this.root=$get_module(this) 1469 this.num=$loop_num 1470 $loop_num++ 1471 this.positional_list=[] 1472 this.default_list=[] 1473 this.other_args=null 1474 this.other_kw=null 1475 this.after_star=[]} 1476 $DefCtx.prototype.set_name=function(name){try{name=$mangle(name,this.parent.tree[0])}catch(err){console.log(err) 1477 console.log('parent',this.parent) 1478 throw err} 1479 var id_ctx=new $IdCtx(this,name) 1480 this.name=name 1481 this.id=this.scope.id+'_'+name 1482 this.id=this.id.replace(/\./g,'_') 1483 this.id+='_'+$B.UUID() 1484 this.parent.node.id=this.id 1485 this.parent.node.module=this.module 1486 this.binding={} 1487 var scope=this.scope 1488 if(scope.globals !==undefined && 1489 scope.globals.has(name)){ 1490 $bind(name,this.root,this)}else{$bind(name,scope,this)} 1491 id_ctx.bound=true 1492 if(scope.is_function){if(scope.C.tree[0].locals.indexOf(name)==-1){scope.C.tree[0].locals.push(name)}}} 1493 $DefCtx.prototype.toString=function(){return 'def '+this.name+'('+this.tree+')'} 1494 $DefCtx.prototype.transition=function(token,value){var C=this 1495 switch(token){case 'id': 1496 if(C.name){$_SyntaxError(C,'token '+token+' after '+C)} 1497 C.set_name(value) 1498 return C 1499 case '(': 1500 if(C.name==null){$_SyntaxError(C,"missing name in function definition")} 1501 C.has_args=true; 1502 return new $FuncArgs(C) 1503 case 'annotation': 1504 return new $AbstractExprCtx(new $AnnotationCtx(C),true) 1505 case ':': 1506 if(C.has_args){return $BodyCtx(C)}else{$_SyntaxError(C,"missing function parameters")} 1507 case 'eol': 1508 if(C.has_args){$_SyntaxError(C,"missing colon")}} 1509 $_SyntaxError(C,'token '+token+' after '+C)} 1510 $DefCtx.prototype.transform=function(node,rank){if(this.is_comp){$get_node(this).is_comp=true} 1511 if(this.transformed !==undefined){return} 1512 var scope=this.scope 1513 this.doc_string=$get_docstring(node) 1514 this.rank=rank 1515 var indent=node.indent+12 1516 if(this.name.substr(0,15)=='lambda_'+$B.lambda_magic){var pblock=scope.parent_block 1517 if(pblock.C && pblock.C.tree[0].type=="def"){this.enclosing.push(pblock)}} 1518 var pnode=this.parent.node 1519 while(pnode.parent && pnode.parent.is_def_func){this.enclosing.push(pnode.parent.parent) 1520 pnode=pnode.parent.parent} 1521 var defaults=[],defs1=[],has_end_pos=false 1522 this.argcount=0 1523 this.kwonlyargcount=0 1524 this.kwonlyargsdefaults=[] 1525 this.otherdefaults=[] 1526 this.varnames={} 1527 this.args=[] 1528 this.__defaults__=[] 1529 this.slots=[] 1530 var slot_list=[],slot_init=[],annotations=[] 1531 if(this.annotation){annotations.push('"return":'+this.annotation.to_js())} 1532 this.func_name=this.tree[0].to_js() 1533 var func_name1=this.func_name 1534 if(this.decorated){this.func_name='var '+this.alias 1535 func_name1=this.alias} 1536 var func_args=this.tree[1].tree 1537 func_args.forEach(function(arg){if(arg.type=='end_positional'){this.args.push("/") 1538 slot_list.push('"/"') 1539 has_end_pos=true}else{this.args.push(arg.name) 1540 this.varnames[arg.name]=true} 1541 if(arg.type=='func_arg_id'){if(this.star_arg){this.kwonlyargcount++ 1542 if(arg.has_default){this.kwonlyargsdefaults.push(arg.name)}} 1543 else{this.argcount++ 1544 if(arg.has_default){this.otherdefaults.push(arg.name)}} 1545 this.slots.push(arg.name+':null') 1546 slot_list.push('"'+arg.name+'"') 1547 slot_init.push(arg.name+':'+arg.name) 1548 if(arg.tree.length > 0){defaults.push('"'+arg.name+'"') 1549 defs1.push(arg.name+':'+$to_js(arg.tree)) 1550 this.__defaults__.push($to_js(arg.tree))}}else if(arg.type=='func_star_arg'){if(arg.op=='*'){this.star_arg=arg.name} 1551 else if(arg.op=='**'){this.kw_arg=arg.name}} 1552 if(arg.annotation){var name=$mangle(arg.name,this) 1553 annotations.push(name+': '+arg.annotation.to_js())}},this) 1554 slot_init='{'+slot_init.join(", ")+'}' 1555 var flags=67 1556 if(this.star_arg){flags |=4} 1557 if(this.kw_arg){flags |=8} 1558 if(this.type=='generator'){flags |=32} 1559 if(this.async){flags |=128} 1560 var nodes=[],js 1561 var global_scope=scope 1562 while(global_scope.parent_block && 1563 global_scope.parent_block.id !=='__builtins__'){global_scope=global_scope.parent_block} 1564 var global_ns='$locals_'+global_scope.id.replace(/\./g,'_') 1565 var name=this.name+this.num 1566 var local_ns='$locals_'+this.id,h='\n'+' '.repeat(indent) 1567 js='var '+local_ns+' = {},'+ 1568 h+'$locals = '+local_ns+';' 1569 var new_node=new $Node() 1570 new_node.locals_def=true 1571 new_node.func_node=node 1572 new $NodeJSCtx(new_node,js) 1573 nodes.push(new_node) 1574 var enter_frame_nodes=[$NodeJS('$locals.$line_info = "'+node.line_num+','+ 1575 this.module+'"'),$NodeJS(`var $top_frame=["${this.id}",$locals,`+ 1576 '"'+global_scope.id+'", '+global_ns+', '+ 1577 (this.is_comp ? this.name :name)+']'),$NodeJS('$locals.$f_trace = $B.enter_frame($top_frame)'),$NodeJS('var $stack_length = $B.frames_stack.length;') 1578 ] 1579 if(this.type=="generator"){enter_frame_nodes.push($NodeJS("$locals.$is_generator = true"))} 1580 if(this.async){enter_frame_nodes.splice(1,0,$NodeJS(`$locals.$async="${this.id}"`))} 1581 enter_frame_nodes.forEach(function(node){node.enter_frame=true}) 1582 if(this.is_comp){nodes.push($NodeJS("var $defaults = {}"))} 1583 this.env=[] 1584 var make_args_nodes=[] 1585 var js=local_ns+' = $locals = $B.args("'+this.name+'", '+ 1586 this.argcount+', {'+this.slots.join(', ')+'}, '+ 1587 '['+slot_list.join(', ')+'], arguments, $defaults, '+ 1588 this.other_args+', '+this.other_kw+');' 1589 var new_node=new $Node() 1590 new $NodeJSCtx(new_node,js) 1591 make_args_nodes.push(new_node) 1592 var only_positional=false 1593 if(this.other_args===null && this.other_kw===null && 1594 this.after_star.length==0 && !has_end_pos){ 1595 only_positional=true 1596 nodes.push($NodeJS('var $len = arguments.length;')) 1597 var new_node=new $Node() 1598 var js='if($len > 0 && arguments[$len - 1].$nat !== undefined)' 1599 new $NodeJSCtx(new_node,js) 1600 nodes.push(new_node) 1601 make_args_nodes.forEach(function(item){new_node.add(item)}) 1602 var else_node=new $Node() 1603 new $NodeJSCtx(else_node,'else') 1604 nodes.push(else_node) 1605 var pos_len=this.slots.length 1606 var test_node=$NodeJS('if($len == '+pos_len+')') 1607 else_node.add(test_node) 1608 test_node.add($NodeJS(local_ns+' = $locals = '+slot_init)) 1609 else_node.add($NodeJS('else if($len > '+pos_len+ 1610 '){$B.wrong_nb_args("'+this.name+'", $len, '+ 1611 pos_len+', ['+slot_list+'])}')) 1612 if(pos_len > 0){ 1613 else_node.add($NodeJS('else if($len + Object.keys($defaults).length < '+ 1614 pos_len+'){$B.wrong_nb_args("'+this.name+ 1615 '", $len, '+pos_len+', ['+slot_list+'])}')) 1616 subelse_node=$NodeJS("else") 1617 else_node.add(subelse_node) 1618 subelse_node.add($NodeJS(local_ns+' = $locals = '+slot_init)) 1619 subelse_node.add($NodeJS("var defparams = ["+slot_list+"]")) 1620 subelse_node.add($NodeJS("for(var i = $len; i < defparams.length"+ 1621 "; i++){$locals[defparams[i]] = $defaults[defparams[i]]}"))}}else{nodes.push(make_args_nodes[0]) 1622 if(make_args_nodes.length > 1){nodes.push(make_args_nodes[1])}} 1623 nodes=nodes.concat(enter_frame_nodes) 1624 var is_method=scope.ntype=="class" 1625 if(is_method){class_ref="$locals_"+scope.parent_block.id.replace(/\./g,'_')+ 1626 '.'+scope.C.tree[0].qualname 1627 this.parent.node.binding["__class__"]=true 1628 nodes.push($NodeJS("$locals.__class__ = "+class_ref))} 1629 nodes.push($NodeJS('$B.js_this = this;')) 1630 for(var i=nodes.length-1;i >=0;i--){node.children.splice(0,0,nodes[i])} 1631 var def_func_node=new $Node() 1632 this.params='' 1633 if(only_positional){this.params=Object.keys(this.varnames).join(', ')} 1634 new $NodeJSCtx(def_func_node,'') 1635 def_func_node.is_def_func=true 1636 def_func_node.module=this.module 1637 var last_node=node.children[node.children.length-1],indent=last_node.indent,last_instr=last_node.C.tree[0] 1638 if(last_instr.type !='return'){ 1639 js='if($locals.$f_trace !== _b_.None){\n'+ 1640 ' '.repeat(indent)+'$B.trace_return(_b_.None)\n'+ 1641 ' '.repeat(indent)+'}\n'+' '.repeat(indent) 1642 js+='$B.leave_frame' 1643 if(this.id.substr(0,5)=='$exec'){js+='_exec'} 1644 js+='({$locals});return _b_.None' 1645 node.add($NodeJS(js))} 1646 var free_vars=[] 1647 if(this.parent.node.referenced){for(var attr in this.parent.node.referenced){if(! this.parent.node.binding[attr]){free_vars.push('"'+attr+'"')}}} 1648 node.add(def_func_node) 1649 var offset=1,indent=node.indent 1650 if(! this.is_comp){ 1651 node.parent.insert(rank+offset++,$NodeJS(name+'.$is_func = true')) 1652 if(this.$has_yield_in_cm){node.parent.insert(rank+offset++,$NodeJS(name+'.$has_yield_in_cm = true'))} 1653 node.parent.insert(rank+offset++,$NodeJS(name+'.$infos = {')) 1654 var __name__=this.name 1655 if(this.name.substr(0,2)=="$$"){__name__=__name__.substr(2)} 1656 if(__name__.substr(0,15)=='lambda_'+$B.lambda_magic){__name__="<lambda>"} 1657 js=' __name__:"'+__name__+'",' 1658 node.parent.insert(rank+offset++,$NodeJS(js)) 1659 var __qualname__=__name__ 1660 if(this.class_name){__qualname__=this.class_name+'.'+__name__} 1661 js=' __qualname__:"'+__qualname__+'",' 1662 node.parent.insert(rank+offset++,$NodeJS(js)) 1663 if(this.otherdefaults.length > 0){var def_names=[] 1664 this.otherdefaults.forEach(function(_default){def_names.push('$defaults.'+_default)}) 1665 node.parent.insert(rank+offset++,$NodeJS(' __defaults__ : '+ 1666 '$B.fast_tuple(['+def_names.join(', ')+']),'))}else{node.parent.insert(rank+offset++,$NodeJS(' __defaults__ : '+ 1667 '_b_.None,'))} 1668 if(this.kwonlyargsdefaults.lengh > 0){var def_names=[] 1669 this.kwonlyargsdefaults.forEach(function(_default){def_names.push('$defaults.'+_default)}) 1670 node.parent.insert(rank+offset++,$NodeJS(' __kwdefaults__ : '+ 1671 '$B.fast_tuple(['+def_names.join(', ')+']),'))}else{node.parent.insert(rank+offset++,$NodeJS(' __kwdefaults__ : '+ 1672 '_b_.None,'))} 1673 node.parent.insert(rank+offset++,$NodeJS(' __annotations__: {'+annotations.join(',')+'},')) 1674 node.parent.insert(rank+offset++,$NodeJS(' __dict__: $B.empty_dict(),')) 1675 node.parent.insert(rank+offset++,$NodeJS(' __doc__: '+(this.doc_string ||'_b_.None')+',')) 1676 var root=$get_module(this) 1677 node.parent.insert(rank+offset++,$NodeJS(' __module__ : "'+root.module+'",')) 1678 for(var attr in this.binding){this.varnames[attr]=true} 1679 var co_varnames=[] 1680 for(var attr in this.varnames){co_varnames.push('"'+$B.from_alias(attr)+'"')} 1681 var CODE_MARKER='___%%%-CODE-%%%___'+this.name+this.num; 1682 var h='\n'+' '.repeat(indent+8) 1683 js=' __code__:{'+h+' co_argcount:'+this.argcount 1684 var h1=','+h+' '.repeat(4) 1685 var module=$get_module(this).module 1686 js+=h1+'co_filename:$locals_'+module.replace(/\./g,'_')+ 1687 '["__file__"] || "<string>"'+ 1688 h1+'co_firstlineno:'+node.line_num+ 1689 h1+'co_flags:'+flags+ 1690 h1+'co_freevars: ['+free_vars+']'+ 1691 h1+'co_kwonlyargcount:'+this.kwonlyargcount+ 1692 h1+'co_name: "'+this.name+'"'+ 1693 h1+'co_nlocals: '+co_varnames.length+ 1694 h1+'co_posonlyargcount: '+(this.pos_only ||0)+ 1695 h1+'co_varnames: $B.fast_tuple(['+co_varnames.join(', ')+'])'+ 1696 h+'}\n'+' '.repeat(indent+4)+'};' 1697 js+='_b_.None;' 1698 node.parent.insert(rank+offset++,$NodeJS(js))} 1699 this.default_str='{'+defs1.join(', ')+'}' 1700 if(! this.is_comp){var name1=name 1701 if(this.type=="generator"){name1=`$B.generator.$factory(${name})`} 1702 var res='return '+name1 1703 if(this.async){if(this.type=="generator"){res=`return $B.async_generator.$factory(${name})`}else{res='return $B.make_async('+name1+')'}} 1704 node.parent.insert(rank+offset++,$NodeJS(res+'}')) 1705 node.parent.insert(rank+offset++,$NodeJS( 1706 this.func_name+" = "+this.name+'$'+this.num+ 1707 '('+this.default_str+')')) 1708 node.parent.insert(rank+offset++,$NodeJS( 1709 func_name1+".$set_defaults = function(value){return "+ 1710 func_name1+" = "+this.name+"$"+this.num+ 1711 "(value)}")) 1712 if(this.$has_yield_in_cm){node.parent.insert(rank+offset++,$NodeJS(`${func_name1}.$has_yield_in_cm=true`))}} 1713 var parent=node 1714 for(var pos=0;pos < parent.children.length && 1715 parent.children[pos]!==$B.last(enter_frame_nodes);pos++){} 1716 var try_node=$NodeJS('try'),children=parent.children.slice(pos+1) 1717 parent.insert(pos+1,try_node) 1718 children.forEach(function(child){if(child.is_def_func){child.children.forEach(function(grand_child){try_node.add(grand_child)})}else{try_node.add(child)}}) 1719 parent.children.splice(pos+2,parent.children.length) 1720 var except_node=$NodeJS('catch(err)') 1721 except_node.add($NodeJS('$B.set_exc(err)')) 1722 except_node.add($NodeJS('if($locals.$f_trace !== _b_.None){'+ 1723 '$locals.$f_trace = $B.trace_exception()}')) 1724 except_node.add($NodeJS('$B.leave_frame({$locals});throw err')) 1725 parent.add(except_node) 1726 this.transformed=true 1727 return offset} 1728 $DefCtx.prototype.to_js=function(func_name){this.js_processed=true 1729 if(this.is_comp){return "var "+this.name+" = "+ 1730 (this.async ? ' async ' :'')+ 1731 "function* (expr)"} 1732 func_name=func_name ||this.tree[0].to_js() 1733 if(this.decorated){func_name='var '+this.alias} 1734 return "var "+this.name+'$'+this.num+ 1735 ' = function($defaults){'+ 1736 (this.async ? 'async ' :'')+'function'+ 1737 (this.type=='generator' ? "* " :" ")+ 1738 this.name+this.num+'('+this.params+')'} 1739 var $DelCtx=$B.parser.$DelCtx=function(C){ 1740 this.type='del' 1741 this.parent=C 1742 C.tree[C.tree.length]=this 1743 this.tree=[]} 1744 $DelCtx.prototype.toString=function(){return 'del '+this.tree} 1745 $DelCtx.prototype.transition=function(token,value){var C=this 1746 if(token=='eol'){return $transition(C.parent,token)} 1747 $_SyntaxError(C,'token '+token+' after '+C)} 1748 $DelCtx.prototype.to_js=function(){this.js_processed=true 1749 var C=this.parent 1750 if(this.tree[0].type=='list_or_tuple'){ 1751 var res=[] 1752 this.tree[0].tree.forEach(function(elt){var subdel=new $DelCtx(C) 1753 subdel.tree=[elt] 1754 res.push(subdel.to_js()) 1755 C.tree.pop()}) 1756 this.tree=[] 1757 return res.join(';')}else if(this.tree[0].type=='expr' && 1758 this.tree[0].tree[0].type=='list_or_tuple'){ 1759 this.tree[0]=this.tree[0].tree[0] 1760 return this.to_js()}else{var expr=this.tree[0].tree[0] 1761 switch(expr.type){case 'id': 1762 var scope=$get_scope(this),is_global=false 1763 if((scope.ntype=="def" ||scope.ntype=="generator")&& 1764 scope.globals && scope.globals.has(expr.value)){ 1765 scope=scope.parent 1766 while(scope.parent && 1767 scope.parent.id !=="__builtins__"){scope=scope.parent} 1768 is_global=true} 1769 var res='$B.$delete("'+expr.value+'"'+ 1770 (is_global ? ', "global"' :'')+');' 1771 delete scope.binding[expr.value] 1772 return res 1773 case 'list_or_tuple': 1774 var res=[] 1775 expr.tree.forEach(function(elt){res.push('delete '+elt.to_js())}) 1776 return res.join(';') 1777 case 'sub': 1778 expr.func='delitem' 1779 js=expr.to_js() 1780 expr.func='getitem' 1781 return js 1782 case 'op': 1783 $_SyntaxError(this,["cannot delete operator"]) 1784 case 'call': 1785 $_SyntaxError(this,["cannot delete function call"]) 1786 case 'attribute': 1787 return '_b_.delattr('+expr.value.to_js()+',"'+ 1788 expr.name+'")' 1789 default: 1790 $_SyntaxError(this,["cannot delete "+expr.type])}}} 1791 var $DictOrSetCtx=$B.parser.$DictOrSetCtx=function(C){ 1792 this.type='dict_or_set' 1793 this.real='dict_or_set' 1794 this.expect='id' 1795 this.closed=false 1796 this.start=$pos 1797 this.parent=C 1798 this.tree=[] 1799 C.tree[C.tree.length]=this} 1800 $DictOrSetCtx.prototype.toString=function(){switch(this.real){case 'dict': 1801 return '(dict) {'+this.items+'}' 1802 case 'set': 1803 return '(set) {'+this.tree+'}'} 1804 return '(dict_or_set) {'+this.tree+'}'} 1805 $DictOrSetCtx.prototype.transition=function(token,value){var C=this 1806 if(C.closed){switch(token){case '[': 1807 return new $AbstractExprCtx(new $SubCtx(C.parent),false) 1808 case '(': 1809 return new $CallArgCtx(new $CallCtx(C.parent))} 1810 return $transition(C.parent,token,value)}else{if(C.expect==','){switch(token){case '}': 1811 switch(C.real){case 'dict_or_set': 1812 if(C.tree.length !=1){break} 1813 C.real='set' 1814 case 'set': 1815 case 'set_comp': 1816 case 'dict_comp': 1817 C.items=C.tree 1818 C.tree=[] 1819 C.closed=true 1820 return C 1821 case 'dict': 1822 if(C.nb_dict_items()% 2==0){C.items=C.tree 1823 C.tree=[] 1824 C.closed=true 1825 return C}} 1826 $_SyntaxError(C,'token '+token+ 1827 ' after '+C) 1828 case ',': 1829 if(C.real=='dict_or_set'){C.real='set'} 1830 if(C.real=='dict' && 1831 C.nb_dict_items()% 2){$_SyntaxError(C,'token '+token+ 1832 ' after '+C)} 1833 C.expect='id' 1834 return C 1835 case ':': 1836 if(C.real=='dict_or_set'){C.real='dict'} 1837 if(C.real=='dict'){C.expect=',' 1838 return new $AbstractExprCtx(C,false)}else{$_SyntaxError(C,'token '+token+ 1839 ' after '+C)} 1840 case 'for': 1841 if(C.real=='dict_or_set'){C.real='set_comp'}else{C.real='dict_comp'} 1842 var lst=new $ListOrTupleCtx(C,'dict_or_set_comp') 1843 lst.intervals=[C.start+1] 1844 lst.vars=C.vars 1845 C.tree.pop() 1846 lst.expression=C.tree 1847 if(C.yields){lst.expression.yields=C.yields 1848 delete C.yields} 1849 C.tree=[lst] 1850 lst.tree=[] 1851 var comp=new $ComprehensionCtx(lst) 1852 return new $TargetListCtx(new $CompForCtx(comp))} 1853 $_SyntaxError(C,'token '+token+' after '+C)}else if(C.expect=='id'){switch(token){case '}': 1854 if(C.tree.length==0){ 1855 C.items=[] 1856 C.real='dict'}else{ 1857 C.items=C.tree} 1858 C.tree=[] 1859 C.closed=true 1860 return C 1861 case 'id': 1862 case 'imaginary': 1863 case 'int': 1864 case 'float': 1865 case 'str': 1866 case 'bytes': 1867 case '[': 1868 case '(': 1869 case '{': 1870 case '.': 1871 case 'not': 1872 case 'lambda': 1873 C.expect=',' 1874 var expr=new $AbstractExprCtx(C,false) 1875 return $transition(expr,token,value) 1876 case 'op': 1877 switch(value){case '*': 1878 case '**': 1879 C.expect="," 1880 var expr=new $AbstractExprCtx(C,false) 1881 expr.packed=value.length 1882 if(C.real=="dict_or_set"){C.real=value=="*" ? "set" : 1883 "dict"}else if( 1884 (C.real=="set" && value=="**")|| 1885 (C.real=="dict" && value=="*")){$_SyntaxError(C,'token '+token+ 1886 ' after '+C)} 1887 return expr 1888 case '+': 1889 return C 1890 case '-': 1891 case '~': 1892 C.expect=',' 1893 var left=new $UnaryCtx(C,value) 1894 if(value=='-'){var op_expr=new $OpCtx(left,'unary_neg')}else if(value=='+'){var op_expr=new $OpCtx(left,'unary_pos')}else{var op_expr=new $OpCtx(left,'unary_inv')} 1895 return new $AbstractExprCtx(op_expr,false)} 1896 $_SyntaxError(C,'token '+token+ 1897 ' after '+C)} 1898 $_SyntaxError(C,'token '+token+' after '+C)} 1899 return $transition(C.parent,token,value)}} 1900 $DictOrSetCtx.prototype.nb_dict_items=function(){var nb=0 1901 this.tree.forEach(function(item){if(item.packed){nb+=2} 1902 else{nb++}}) 1903 return nb} 1904 $DictOrSetCtx.prototype.packed_indices=function(){var ixs=[] 1905 this.items.forEach(function(t,i){if(t.type=="expr" && t.packed){ixs.push(i)}}) 1906 return ixs} 1907 $DictOrSetCtx.prototype.unpack_dict=function(packed){var js="",res,first,i=0,item,elts=[] 1908 while(i < this.items.length){item=this.items[i] 1909 first=i==0 1910 if(item.type=="expr" && item.packed){res="_b_.list.$factory(_b_.dict.items("+item.to_js()+"))" 1911 i++}else{res="[["+item.to_js()+","+ 1912 this.items[i+1].to_js()+"]]" 1913 i+=2} 1914 if(! first){res=".concat("+res+")"} 1915 js+=res} 1916 return js} 1917 $DictOrSetCtx.prototype.unpack_set=function(packed){var js="",res 1918 this.items.forEach(function(t,i){if(packed.indexOf(i)>-1){res="_b_.list.$factory("+t.to_js()+")"}else{res="["+t.to_js()+"]"} 1919 if(i > 0){res=".concat("+res+")"} 1920 js+=res}) 1921 return js} 1922 $DictOrSetCtx.prototype.to_js=function(){this.js_processed=true 1923 switch(this.real){case 'dict': 1924 var packed=this.packed_indices() 1925 if(packed.length > 0){return '_b_.dict.$factory('+this.unpack_dict(packed)+ 1926 ')'+$to_js(this.tree)} 1927 var res=[] 1928 for(var i=0;i < this.items.length;i+=2){res.push('['+this.items[i].to_js()+','+ 1929 this.items[i+1].to_js()+']')} 1930 return '_b_.dict.$factory(['+res.join(',')+'])'+ 1931 $to_js(this.tree) 1932 case 'set_comp': 1933 return '_b_.set.$factory('+$to_js(this.items)+')'+ 1934 $to_js(this.tree) 1935 case 'dict_comp': 1936 return '_b_.dict.$factory('+$to_js(this.items)+')'+ 1937 $to_js(this.tree)} 1938 var packed=this.packed_indices() 1939 if(packed.length > 0){return '_b_.set.$factory('+this.unpack_set(packed)+')'} 1940 return '_b_.set.$factory(['+$to_js(this.items)+'])'+$to_js(this.tree)} 1941 var $DoubleStarArgCtx=$B.parser.$DoubleStarArgCtx=function(C){ 1942 this.type='double_star_arg' 1943 this.parent=C 1944 this.tree=[] 1945 C.tree[C.tree.length]=this} 1946 $DoubleStarArgCtx.prototype.toString=function(){return '**'+this.tree} 1947 $DoubleStarArgCtx.prototype.transition=function(token,value){var C=this 1948 switch(token){case 'id': 1949 case 'imaginary': 1950 case 'int': 1951 case 'float': 1952 case 'str': 1953 case 'bytes': 1954 case '[': 1955 case '(': 1956 case '{': 1957 case '.': 1958 case 'not': 1959 case 'lambda': 1960 return $transition(new $AbstractExprCtx(C,false),token,value) 1961 case ',': 1962 case ')': 1963 return $transition(C.parent,token) 1964 case ':': 1965 if(C.parent.parent.type=='lambda'){return $transition(C.parent.parent,token)}} 1966 $_SyntaxError(C,'token '+token+' after '+C)} 1967 $DoubleStarArgCtx.prototype.to_js=function(){this.js_processed=true 1968 return '{$nat:"pdict",arg:'+$to_js(this.tree)+'}'} 1969 var $EllipsisCtx=$B.parser.$EllipsisCtx=function(C){ 1970 this.type='ellipsis' 1971 this.parent=C 1972 this.nbdots=1 1973 this.start=$pos 1974 C.tree[C.tree.length]=this} 1975 $EllipsisCtx.prototype.toString=function(){return 'ellipsis'} 1976 $EllipsisCtx.prototype.transition=function(token,value){var C=this 1977 if(token=='.'){C.nbdots++ 1978 if(C.nbdots==3 && $pos-C.start==2){C.$complete=true} 1979 return C}else{if(! C.$complete){$pos-- 1980 $_SyntaxError(C,'token '+token+' after '+ 1981 C)}else{return $transition(C.parent,token,value)}}} 1982 $EllipsisCtx.prototype.to_js=function(){this.js_processed=true 1983 return '$B.builtins["Ellipsis"]'} 1984 var $EndOfPositionalCtx=$B.parser.$EndOfConditionalCtx=function(C){ 1985 this.type="end_positional" 1986 this.parent=C 1987 C.has_end_positional=true 1988 C.parent.pos_only=C.tree.length 1989 C.tree.push(this)} 1990 $EndOfPositionalCtx.prototype.transition=function(token,value){var C=this 1991 if(token=="," ||token==")"){return $transition(C.parent,token,value)} 1992 $_SyntaxError(C,'token '+token+' after '+C)} 1993 $EndOfPositionalCtx.prototype.to_js=function(){return "/"} 1994 var $ExceptCtx=$B.parser.$ExceptCtx=function(C){ 1995 this.type='except' 1996 this.parent=C 1997 C.tree[C.tree.length]=this 1998 this.tree=[] 1999 this.expect='id' 2000 this.scope=$get_scope(this)} 2001 $ExceptCtx.prototype.toString=function(){return '(except) '} 2002 $ExceptCtx.prototype.transition=function(token,value){var C=this 2003 switch(token){case 'id': 2004 case 'imaginary': 2005 case 'int': 2006 case 'float': 2007 case 'str': 2008 case 'bytes': 2009 case '[': 2010 case '(': 2011 case '{': 2012 case 'not': 2013 case 'lambda': 2014 if(C.expect=='id'){C.expect='as' 2015 return $transition(new $AbstractExprCtx(C,false),token,value)} 2016 case 'as': 2017 if(C.expect=='as' && 2018 C.has_alias===undefined){C.expect='alias' 2019 C.has_alias=true 2020 return C} 2021 case 'id': 2022 if(C.expect=='alias'){C.expect=':' 2023 C.set_alias(value) 2024 return C} 2025 break 2026 case ':': 2027 var _ce=C.expect 2028 if(_ce=='id' ||_ce=='as' ||_ce==':'){return $BodyCtx(C)} 2029 break 2030 case '(': 2031 if(C.expect=='id' && C.tree.length==0){C.parenth=true 2032 return C} 2033 break 2034 case ')': 2035 if(C.expect==',' ||C.expect=='as'){C.expect='as' 2036 return C} 2037 case ',': 2038 if(C.parenth !==undefined && 2039 C.has_alias===undefined && 2040 (C.expect=='as' ||C.expect==',')){C.expect='id' 2041 return C}} 2042 $_SyntaxError(C,'token '+token+' after '+C.expect)} 2043 $ExceptCtx.prototype.set_alias=function(alias){this.tree[0].alias=$mangle(alias,this) 2044 $bind(alias,this.scope,this)} 2045 $ExceptCtx.prototype.transform=function(node,rank){ 2046 var linenum_node=$NodeJS("void(0)") 2047 linenum_node.line_num=node.line_num 2048 node.insert(0,linenum_node) 2049 var last_child=$B.last(node.children) 2050 if(last_child.C.tree && last_child.C.tree[0]&& 2051 last_child.C.tree[0].type=="return"){} 2052 else{node.add($NodeJS("$B.del_exc()"))}} 2053 $ExceptCtx.prototype.to_js=function(){ 2054 this.js_processed=true 2055 switch(this.tree.length){case 0: 2056 return 'else' 2057 case 1: 2058 if(this.tree[0].name=='Exception'){return 'else if(1)'}} 2059 var res=[] 2060 this.tree.forEach(function(elt){res.push(elt.to_js())}) 2061 var lnum='' 2062 if($B.debug > 0){var module=$get_module(this) 2063 lnum='($locals.$line_info = "'+$get_node(this).line_num+ 2064 ','+module.id+'") && '} 2065 return 'else if('+lnum+'$B.is_exc('+this.error_name+ 2066 ',['+res.join(',')+']))'} 2067 var $ExprCtx=$B.parser.$ExprCtx=function(C,name,with_commas){ 2068 this.type='expr' 2069 this.name=name 2070 this.with_commas=with_commas 2071 this.expect=',' 2072 this.parent=C 2073 if(C.packed){this.packed=C.packed} 2074 if(C.is_await){var node=$get_node(this) 2075 node.has_await=node.has_await ||[] 2076 this.is_await=C.is_await 2077 node.has_await.push(this)} 2078 if(C.assign){ 2079 this.assign=C.assign} 2080 this.tree=[] 2081 C.tree[C.tree.length]=this} 2082 $ExprCtx.prototype.toString=function(){return '(expr '+this.with_commas+') '+this.tree} 2083 $ExprCtx.prototype.transition=function(token,value){var C=this 2084 switch(token){case 'bytes': 2085 case 'float': 2086 case 'id': 2087 case 'imaginary': 2088 case 'int': 2089 case 'lambda': 2090 case 'pass': 2091 case 'str': 2092 $_SyntaxError(C,'token '+token+' after '+ 2093 C) 2094 break 2095 case '{': 2096 if(C.tree[0].type !="id" || 2097 ["print","exec"].indexOf(C.tree[0].value)==-1){$_SyntaxError(C,'token '+token+' after '+ 2098 C)} 2099 return new $DictOrSetCtx(C) 2100 case '[': 2101 case '(': 2102 case '.': 2103 case 'not': 2104 if(C.expect=='expr'){C.expect=',' 2105 return $transition(new $AbstractExprCtx(C,false),token,value)}} 2106 switch(token){case 'not': 2107 if(C.expect==','){return new $ExprNot(C)} 2108 break 2109 case 'in': 2110 if(C.parent.type=='target_list'){ 2111 return $transition(C.parent,token)} 2112 if(C.expect==','){return $transition(C,'op','in')} 2113 break 2114 case ',': 2115 if(C.expect==','){if(C.with_commas || 2116 ["assign","return"].indexOf(C.parent.type)>-1){if($parent_match(C,{type:"yield","from":true})){$_SyntaxError(C,"no implicit tuple for yield from")} 2117 C.parent.tree.pop() 2118 var tuple=new $ListOrTupleCtx(C.parent,'tuple') 2119 tuple.implicit=true 2120 tuple.has_comma=true 2121 tuple.tree=[C] 2122 C.parent=tuple 2123 return tuple}} 2124 return $transition(C.parent,token) 2125 case '.': 2126 return new $AttrCtx(C) 2127 case '[': 2128 return new $AbstractExprCtx(new $SubCtx(C),true) 2129 case '(': 2130 return new $CallCtx(C) 2131 case 'op': 2132 var op_parent=C.parent,op=value 2133 if(op_parent.type=='ternary' && op_parent.in_else){var new_op=new $OpCtx(C,op) 2134 return new $AbstractExprCtx(new_op,false)} 2135 var op1=C.parent,repl=null 2136 while(1){if(op1.type=='expr'){op1=op1.parent} 2137 else if(op1.type=='op' && 2138 $op_weight[op1.op]>=$op_weight[op]&& 2139 !(op1.op=='**' && op=='**')){ 2140 repl=op1 2141 op1=op1.parent}else if(op1.type=="not" && 2142 $op_weight['not']> $op_weight[op]){repl=op1 2143 op1=op1.parent}else{break}} 2144 if(repl===null){while(1){if(C.parent !==op1){C=C.parent 2145 op_parent=C.parent}else{break}} 2146 C.parent.tree.pop() 2147 var expr=new $ExprCtx(op_parent,'operand',C.with_commas) 2148 expr.expect=',' 2149 C.parent=expr 2150 var new_op=new $OpCtx(C,op) 2151 return new $AbstractExprCtx(new_op,false)}else{ 2152 if(op==='and' ||op==='or'){while(repl.parent.type=='not'|| 2153 (repl.parent.type=='expr' && 2154 repl.parent.parent.type=='not')){ 2155 repl=repl.parent 2156 op_parent=repl.parent}}} 2157 if(repl.type=='op'){var _flag=false 2158 switch(repl.op){case '<': 2159 case '<=': 2160 case '==': 2161 case '!=': 2162 case 'is': 2163 case '>=': 2164 case '>': 2165 _flag=true} 2166 if(_flag){switch(op){case '<': 2167 case '<=': 2168 case '==': 2169 case '!=': 2170 case 'is': 2171 case '>=': 2172 case '>': 2173 var c2=repl.tree[1], 2174 c2js=c2.to_js() 2175 var c2_clone=new Object() 2176 for(var attr in c2){c2_clone[attr]=c2[attr]} 2177 var vname="$c"+chained_comp_num 2178 c2.to_js=function(){return vname} 2179 c2_clone.to_js=function(){return vname} 2180 chained_comp_num++ 2181 while(repl.parent && repl.parent.type=='op'){if($op_weight[repl.parent.op]< 2182 $op_weight[repl.op]){repl=repl.parent}else{break}} 2183 repl.parent.tree.pop() 2184 var and_expr=new $OpCtx(repl,'and') 2185 and_expr.wrap={'name':vname,'js':c2js} 2186 c2_clone.parent=and_expr 2187 and_expr.tree.push('xxx') 2188 var new_op=new $OpCtx(c2_clone,op) 2189 return new $AbstractExprCtx(new_op,false)}}} 2190 repl.parent.tree.pop() 2191 var expr=new $ExprCtx(repl.parent,'operand',false) 2192 expr.tree=[op1] 2193 repl.parent=expr 2194 var new_op=new $OpCtx(repl,op) 2195 return new $AbstractExprCtx(new_op,false) 2196 case 'augm_assign': 2197 var parent=C.parent 2198 while(parent){if(parent.type=="assign" ||parent.type=="augm_assign"){$_SyntaxError(C,"augmented assignment inside assignment")}else if(parent.type=="op"){$_SyntaxError(C,["cannot assign to operator"])} 2199 parent=parent.parent} 2200 if(C.expect==','){return new $AbstractExprCtx( 2201 new $AugmentedAssignCtx(C,value),true)} 2202 return $transition(C.parent,token,value) 2203 case ":": 2204 if(C.parent.type=="sub" || 2205 (C.parent.type=="list_or_tuple" && 2206 C.parent.parent.type=="sub")){return new $AbstractExprCtx(new $SliceCtx(C.parent),false)}else if(C.parent.type=="slice"){return $transition(C.parent,token,value)}else if(C.parent.type=="node"){ 2207 if(C.tree.length==1){var child=C.tree[0] 2208 if(["id","sub","attribute"].indexOf(child.type)>-1){return new $AbstractExprCtx(new $AnnotationCtx(C),false)}else if(child.real=="tuple" && child.expect=="," && 2209 child.tree.length==1){return new $AbstractExprCtx(new $AnnotationCtx(child.tree[0]),false)}} 2210 $_SyntaxError(C,"invalid target for annotation")} 2211 break 2212 case '=': 2213 function has_parent(ctx,type){ 2214 while(ctx.parent){if(ctx.parent.type==type){return ctx.parent} 2215 ctx=ctx.parent} 2216 return false} 2217 var annotation 2218 if(C.expect==','){if(C.parent.type=="call_arg"){ 2219 if(C.tree[0].type !="id"){$_SyntaxError(C,['expression cannot contain'+ 2220 ' assignment, perhaps you meant "=="?'])} 2221 return new $AbstractExprCtx(new $KwArgCtx(C),true)}else if(annotation=has_parent(C,"annotation")){return $transition(annotation,token,value)}else if(C.parent.type=="op"){ 2222 $_SyntaxError(C,["cannot assign to operator"])}else if(C.parent.type=="not"){ 2223 $_SyntaxError(C,["cannot assign to operator"])}else if(C.parent.type=="list_or_tuple"){ 2224 for(var i=0;i < C.parent.tree.length;i++){var item=C.parent.tree[i] 2225 if(item.type=="expr" && item.name=="operand"){$_SyntaxError(C,["cannot assign to operator"])}}}else if(C.tree.length > 0 && C.tree[0].assign){ 2226 $_SyntaxError(C,["cannot assign to named expression"])}else if(C.parent.type=="expr" && 2227 C.parent.name=="target list"){$_SyntaxError(C,'token '+token+' after ' 2228 +C)}else if(C.parent.type=="lambda"){if(C.parent.parent.parent.type !="node"){$_SyntaxError(C,['expression cannot contain'+ 2229 ' assignment, perhaps you meant "=="?'])}} 2230 while(C.parent !==undefined){C=C.parent 2231 if(C.type=="condition"){$_SyntaxError(C,'token '+token+' after ' 2232 +C)}else if(C.type=="augm_assign"){$_SyntaxError(C,"assignment inside augmented assignment")}} 2233 C=C.tree[0] 2234 return new $AbstractExprCtx(new $AssignCtx(C),true)} 2235 break 2236 case ':=': 2237 var ptype=C.parent.type 2238 if(["node","assign","kwarg","annotation"]. 2239 indexOf(ptype)>-1){$_SyntaxError(C,':= invalid, parent '+ptype)}else if(ptype=="func_arg_id" && 2240 C.parent.tree.length > 0){ 2241 $_SyntaxError(C,':= invalid, parent '+ptype)}else if(ptype=="call_arg" && 2242 C.parent.parent.type=="call" && 2243 C.parent.parent.parent.type=="lambda"){ 2244 $_SyntaxError(C,':= invalid inside function arguments' )} 2245 if(C.tree.length==1 && 2246 C.tree[0].type=="id"){var scope=$get_scope(C),name=C.tree[0].value 2247 while(scope.is_comp){scope=scope.parent_block} 2248 $bind(name,scope,C) 2249 var parent=C.parent 2250 parent.tree.pop() 2251 var assign_expr=new $AbstractExprCtx(parent,false) 2252 assign_expr.assign=C.tree[0] 2253 return assign_expr} 2254 $_SyntaxError(C,'token '+token+' after '+C) 2255 case 'if': 2256 var in_comp=false,ctx=C.parent 2257 while(true){if(ctx.type=="list_or_tuple"){ 2258 break}else if(ctx.type=='comp_for' ||ctx.type=="comp_if"){in_comp=true 2259 break}else if(ctx.type=='call_arg'){break} 2260 if(ctx.parent !==undefined){ctx=ctx.parent} 2261 else{break}} 2262 if(in_comp){break} 2263 var ctx=C 2264 while(ctx.parent && 2265 (ctx.parent.type=='op' || 2266 (ctx.parent.type=="expr" && ctx.parent.name=="operand"))){ctx=ctx.parent} 2267 return new $AbstractExprCtx(new $TernaryCtx(ctx),true) 2268 case 'eol': 2269 if(C.tree.length==2 && 2270 C.tree[0].type=="id" && 2271 ["print","exec"].indexOf(C.tree[0].value)>-1){$_SyntaxError(C,["Missing parentheses in call "+ 2272 "to '"+C.tree[0].value+"'."])} 2273 if(["dict_or_set","list_or_tuple"].indexOf(C.parent.type)==-1){var t=C.tree[0] 2274 if(t.type=="packed" || 2275 (t.type=="call" && t.func.type=="packed")){$_SyntaxError(C,["can't use starred expression here"])}}} 2276 return $transition(C.parent,token)} 2277 $ExprCtx.prototype.to_js=function(arg){var res 2278 this.js_processed=true 2279 if(this.type=='list'){res='['+$to_js(this.tree)+']'}else if(this.tree.length==1){res=this.tree[0].to_js(arg)}else{res='_b_.tuple.$factory(['+$to_js(this.tree)+'])'} 2280 if(this.is_await){res="await ($B.promise("+res+"))"} 2281 if(this.assign){ 2282 var scope=$get_scope(this) 2283 while(scope.is_comp){scope=scope.parent_block} 2284 if(scope.globals && scope.globals.has(this.assign.value)){ 2285 while(scope.parent_block && 2286 scope.parent_block.id !=="__builtins__"){scope=scope.parent_block}}else if(scope.nonlocals && 2287 scope.nonlocals[this.assign.value]){ 2288 scope=scope.parent_block} 2289 res="($locals_"+scope.id.replace(/\./g,'_')+'["'+ 2290 this.assign.value+'"] = '+res+')'} 2291 return res} 2292 var $ExprNot=$B.parser.$ExprNot=function(C){ 2293 this.type='expr_not' 2294 this.parent=C 2295 this.tree=[] 2296 C.tree[C.tree.length]=this} 2297 $ExprNot.prototype.transition=function(token,value){var C=this 2298 if(token=='in'){ 2299 C.parent.tree.pop() 2300 return new $AbstractExprCtx( 2301 new $OpCtx(C.parent,'not_in'),false)} 2302 $_SyntaxError(C,'token '+token+' after '+C)} 2303 $ExprNot.prototype.toString=function(){return '(expr_not)'} 2304 var $ForExpr=$B.parser.$ForExpr=function(C){ 2305 if(C.node.parent.is_comp){ 2306 C.node.parent.first_for=this} 2307 this.type='for' 2308 this.parent=C 2309 this.tree=[] 2310 C.tree[C.tree.length]=this 2311 this.loop_num=$loop_num 2312 this.scope=$get_scope(this) 2313 if(this.scope.is_comp){} 2314 this.module=this.scope.module 2315 $loop_num++} 2316 $ForExpr.prototype.toString=function(){return '(for) '+this.tree} 2317 $ForExpr.prototype.transition=function(token,value){var C=this 2318 switch(token){case 'in': 2319 if(C.tree[0].tree.length==0){ 2320 $_SyntaxError(C,"missing target between 'for' and 'in'")} 2321 return new $AbstractExprCtx( 2322 new $ExprCtx(C,'target list',true),false) 2323 case ':': 2324 if(C.tree.length < 2 2325 ||C.tree[1].tree[0].type=="abstract_expr"){$_SyntaxError(C,'token '+token+' after '+ 2326 C)} 2327 return $BodyCtx(C)} 2328 $_SyntaxError(C,'token '+token+' after '+C)} 2329 $ForExpr.prototype.transform=function(node,rank){ 2330 var pnode=this.parent.node.parent 2331 while(pnode){if(pnode.is_comp){var module=$get_module(this) 2332 if(module.outermost_expr===undefined){pnode.outermost_expr=this.tree[1] 2333 module.outermost_expr=this.tree[1] 2334 this.tree.pop() 2335 new $RawJSCtx(this,"expr")} 2336 break} 2337 pnode=pnode.parent} 2338 if(this.async){return this.transform_async(node,rank)} 2339 var scope=$get_scope(this),target=this.tree[0],target_is_1_tuple=target.tree.length==1 && target.expect=='id',iterable=this.tree[1],num=this.loop_num,local_ns='$locals_'+scope.id.replace(/\./g,'_'),h='\n'+' '.repeat(node.indent+4) 2340 var $range=false 2341 if(target.tree.length==1 && 2342 ! scope.blurred && 2343 target.expct !='id' && 2344 iterable.type=='expr' && 2345 iterable.tree[0].type=='expr' && 2346 iterable.tree[0].tree[0].type=='call'){var call=iterable.tree[0].tree[0] 2347 if(call.func.type=='id'){var func_name=call.func.value 2348 if(func_name=='range' && call.tree.length < 3 && 2349 call.tree.length > 0){ 2350 $range=call}}} 2351 var new_nodes=[],pos=0 2352 var children=node.children 2353 var offset=1 2354 if($range){if(this.has_break){ 2355 new_node=new $Node() 2356 new $NodeJSCtx(new_node,local_ns+'["$no_break'+num+'"] = true') 2357 new_nodes[pos++]=new_node} 2358 var range_is_builtin=false,_scope=$get_scope(this),found=[] 2359 while(1){if(_scope.binding["range"]){found.push(_scope.id)} 2360 if(_scope.parent_block){_scope=_scope.parent_block} 2361 else{break}} 2362 range_is_builtin=found.length==1 && 2363 found[0]=="__builtins__" 2364 var test_range_node=new $Node() 2365 test_range_node.module=node.parent.module 2366 if(range_is_builtin){new $NodeJSCtx(test_range_node,'if(1)')}else{new $NodeJSCtx(test_range_node,'if('+call.func.to_js()+' === _b_.range)')} 2367 new_nodes[pos++]=test_range_node 2368 var idt=target.to_js(),shortcut=false 2369 if($range.tree.length==1){var stop=$range.tree[0].tree[0] 2370 if(stop.tree[0].type=="int"){stop=parseInt(stop.to_js()) 2371 if(0 < stop < $B.max_int){shortcut=true 2372 var varname="$i"+$B.UUID() 2373 var for_node=$NodeJS("for (var "+varname+" = 0; "+ 2374 varname+" < "+stop+"; "+varname+"++)") 2375 for_node.add($NodeJS(idt+" = "+varname))}} 2376 var start=0,stop=$range.tree[0].to_js()}else{var start=$range.tree[0].to_js(),stop=$range.tree[1].to_js()} 2377 if(!shortcut){var js='var $stop_'+num+' = $B.int_or_bool('+stop+'),'+ 2378 h+' $next'+num+" = "+start+','+ 2379 h+' $safe'+num+' = typeof $next'+num+ 2380 ' == "number" && typeof '+'$stop_'+num+' == "number";'+ 2381 h+' while(true)' 2382 var for_node=new $Node() 2383 new $NodeJSCtx(for_node,js) 2384 for_node.add($NodeJS('if($safe'+num+' && $next'+num+ 2385 '>= $stop_'+num+'){break}')) 2386 for_node.add($NodeJS('else if(!$safe'+num+' && $B.ge($next'+ 2387 num+', $stop_'+num+')){break}')) 2388 for_node.add($NodeJS(idt+' = $next'+num)) 2389 for_node.add($NodeJS('if($safe'+num+'){$next'+num+ 2390 ' += 1}')) 2391 for_node.add($NodeJS('else{$next'+num+' = $B.add($next'+ 2392 num+',1)}'))} 2393 children.forEach(function(child){for_node.add(child.clone_tree())}) 2394 if($B.last(node.children).C.tree[0].type !="return"){var js='$locals.$line_info = "'+node.line_num+ 2395 ','+this.module+'";if($locals.$f_trace !== _b_.None){'+ 2396 '$B.trace_line()};_b_.None;' 2397 for_node.add($NodeJS(js))} 2398 var in_loop=false 2399 if(scope.ntype=='module'){var pnode=node.parent 2400 while(pnode){if(pnode.for_wrapper){in_loop=true;break} 2401 pnode=pnode.parent}} 2402 if(scope.ntype=='module' && !in_loop){var func_node=new $Node() 2403 func_node.for_wrapper=true 2404 js='function $f'+num+'(' 2405 if(this.has_break){js+='$no_break'+num} 2406 js+=')' 2407 new $NodeJSCtx(func_node,js) 2408 test_range_node.add(func_node) 2409 func_node.add(for_node) 2410 if(this.has_break){func_node.add($NodeJS('return $no_break'+num))} 2411 test_range_node.add($NodeJS('var $res'+num+' = $f'+num+ 2412 '();')) 2413 if(this.has_break){test_range_node.add($NodeJS('var $no_break'+num+ 2414 ' = $res'+num))}}else{ 2415 test_range_node.add(for_node)} 2416 if(range_is_builtin){node.parent.children.splice(rank,1) 2417 var k=0 2418 if(this.has_break){node.parent.insert(rank,new_nodes[0]) 2419 k++} 2420 new_nodes[k].children.forEach(function(child){node.parent.insert(rank+k,child)}) 2421 node.parent.children[rank].line_num=node.line_num 2422 node.parent.children[rank].bindings=node.bindings 2423 node.children=[] 2424 return 0} 2425 var else_node=$NodeJS("else") 2426 new_nodes[pos++]=else_node 2427 for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank+1,new_nodes[i])} 2428 this.test_range=true 2429 new_nodes=[],pos=0} 2430 var new_node=new $Node() 2431 new_node.line_num=$get_node(this).line_num 2432 var it_js=iterable.to_js(),iterable_name='$iter'+num,js='var '+iterable_name+' = '+it_js+';'+ 2433 '$locals["$next'+num+'"]'+' = $B.$getattr($B.$iter('+ 2434 iterable_name+'),"__next__")' 2435 new $NodeJSCtx(new_node,js) 2436 new_nodes[pos++]=new_node 2437 if(this.has_break){ 2438 new_nodes[pos++]=$NodeJS(local_ns+'["$no_break'+num+ 2439 '"] = true;')} 2440 var while_node=new $Node() 2441 if(this.has_break){js='while('+local_ns+'["$no_break'+num+'"])'}else{js='while(true)'} 2442 new $NodeJSCtx(while_node,js) 2443 while_node.C.loop_num=num 2444 while_node.C.type='for' 2445 new_nodes[pos++]=while_node 2446 node.parent.children.splice(rank,1) 2447 if(this.test_range){for(var i=new_nodes.length-1;i >=0;i--){else_node.insert(0,new_nodes[i])}}else{for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank,new_nodes[i]) 2448 offset+=new_nodes.length}} 2449 var try_node=$NodeJS("try") 2450 try_node.bindings=node.bindings 2451 while_node.add(try_node) 2452 var iter_node=new $Node() 2453 iter_node.id=this.module 2454 var C=new $NodeCtx(iter_node) 2455 var target_expr=new $ExprCtx(C,'left',true) 2456 if(target_is_1_tuple){ 2457 var t=new $ListOrTupleCtx(target_expr) 2458 t.real='tuple' 2459 t.tree=target.tree}else{target_expr.tree=target.tree} 2460 var assign=new $AssignCtx(target_expr) 2461 assign.tree[1]=new $JSCode('$locals["$next'+num+'"]()') 2462 try_node.add(iter_node) 2463 while_node.add( 2464 $NodeJS('catch($err){if($B.is_exc($err, [_b_.StopIteration]))'+ 2465 '{break;}else{throw($err)}}')) 2466 children.forEach(function(child){ 2467 while_node.add(child.clone())}) 2468 if(node.children.length==0){console.log("bizarre",this)} 2469 if($B.last(node.children).C.tree[0].type !="return"){var js='$locals.$line_info = "'+node.line_num+ 2470 ','+this.module+'";if($locals.$f_trace !== _b_.None){'+ 2471 '$B.trace_line()};_b_.None;' 2472 while_node.add($NodeJS(js))} 2473 node.children=[] 2474 return 0} 2475 $ForExpr.prototype.transform_async=function(node,rank){ 2476 var scope=$get_scope(this),target=this.tree[0],target_is_1_tuple=target.tree.length==1 && target.expect=='id',iterable=this.tree[1],num=this.loop_num,local_ns='$locals_'+scope.id.replace(/\./g,'_'),h='\n'+' '.repeat(node.indent+4) 2477 var new_nodes=[] 2478 var it_js=iterable.to_js(),iterable_name='$iter'+num,type_name='$type'+num,running_name='$running'+num,anext_name='$anext'+num,target_name='$target'+num,js='var '+iterable_name+' = '+it_js 2479 new_nodes.push($NodeJS(js)) 2480 new_nodes.push($NodeJS('var '+type_name+' = _b_.type.$factory( '+ 2481 iterable_name+')')) 2482 js=iterable_name+' = $B.$call($B.$getattr('+type_name+ 2483 ', "__aiter__"))('+iterable_name+')' 2484 new_nodes.push($NodeJS(js)) 2485 new_nodes.push($NodeJS('var '+running_name+' = true')) 2486 new_nodes.push($NodeJS('var '+anext_name+ 2487 ' = $B.$call($B.$getattr('+type_name+', "__anext__"))')) 2488 var while_node=$NodeJS('while('+running_name+')') 2489 new_nodes.push(while_node) 2490 var try_node=$NodeJS('try') 2491 while_node.add(try_node) 2492 if(target.tree.length==1){var js=target.to_js()+' = await ($B.promise('+ 2493 anext_name+'('+iterable_name+')))' 2494 try_node.add($NodeJS(js))}else{var new_node=new $Node(),ctx=new $NodeCtx(new_node),expr=new $ExprCtx(ctx,"left",false) 2495 expr.tree.push(target) 2496 target.parent=expr 2497 var assign=new $AssignCtx(expr) 2498 new $RawJSCtx(assign,'await ($B.promise('+ 2499 anext_name+'('+iterable_name+')))') 2500 try_node.add(new_node)} 2501 var catch_node=$NodeJS('catch(err)') 2502 while_node.add(catch_node) 2503 var js='if(err.__class__ === _b_.StopAsyncIteration)'+ 2504 '{'+running_name+' = false; continue}else{throw err}' 2505 catch_node.add($NodeJS(js)) 2506 node.children.forEach(function(child){while_node.add(child)}) 2507 node.parent.children.splice(rank,1) 2508 for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank,new_nodes[i])} 2509 node.children=[] 2510 return 0} 2511 $ForExpr.prototype.to_js=function(){this.js_processed=true 2512 var iterable=this.tree.pop() 2513 return 'for ('+$to_js(this.tree)+' in '+iterable.to_js()+')'} 2514 var $FromCtx=$B.parser.$FromCtx=function(C){ 2515 this.type='from' 2516 this.parent=C 2517 this.module='' 2518 this.names=[] 2519 C.tree[C.tree.length]=this 2520 this.expect='module' 2521 this.scope=$get_scope(this)} 2522 $FromCtx.prototype.add_name=function(name){this.names[this.names.length]=name 2523 if(name=='*'){this.scope.blurred=true}} 2524 $FromCtx.prototype.bind_names=function(){ 2525 var scope=$get_scope(this) 2526 this.names.forEach(function(name){if(Array.isArray(name)){name=name[1]} 2527 $bind(name,scope,this)},this)} 2528 $FromCtx.prototype.transition=function(token,value){var C=this 2529 switch(token){case 'id': 2530 if(C.expect=='id'){C.add_name(value) 2531 C.expect=',' 2532 return C} 2533 if(C.expect=='alias'){C.names[C.names.length-1]= 2534 [$B.last(C.names),value] 2535 C.expect=',' 2536 return C} 2537 case '.': 2538 if(C.expect=='module'){if(token=='id'){C.module+=value} 2539 else{C.module+='.'} 2540 return C} 2541 case 'import': 2542 if(C.expect=='module'){C.expect='id' 2543 return C} 2544 case 'op': 2545 if(value=='*' && C.expect=='id' 2546 && C.names.length==0){if($get_scope(C).ntype !=='module'){$_SyntaxError(C,["import * only allowed at module level"])} 2547 C.add_name('*') 2548 C.expect='eol' 2549 return C} 2550 case ',': 2551 if(C.expect==','){C.expect='id' 2552 return C} 2553 case 'eol': 2554 switch(C.expect){case ',': 2555 case 'eol': 2556 C.bind_names() 2557 return $transition(C.parent,token) 2558 case 'id': 2559 $_SyntaxError(C,['trailing comma not allowed without '+ 2560 'surrounding parentheses']) 2561 default: 2562 $_SyntaxError(C,['invalid syntax'])} 2563 case 'as': 2564 if(C.expect==',' ||C.expect=='eol'){C.expect='alias' 2565 return C} 2566 case '(': 2567 if(C.expect=='id'){C.expect='id' 2568 return C} 2569 case ')': 2570 if(C.expect==',' ||C.expect=='id'){C.expect='eol' 2571 return C}} 2572 $_SyntaxError(C,'token '+token+' after '+C)} 2573 $FromCtx.prototype.toString=function(){return '(from) '+this.module+' (import) '+this.names} 2574 $FromCtx.prototype.to_js=function(){this.js_processed=true 2575 var scope=$get_scope(this),module=$get_module(this),mod=module.module,res=[],pos=0,indent=$get_node(this).indent,head=' '.repeat(indent) 2576 if(mod.startsWith("$exec")){var frame=$B.last($B.frames_stack)[1] 2577 if(frame.module && frame.module.__name__){mod=frame.module.__name__}} 2578 var mod_elts=this.module.split(".") 2579 for(var i=0;i < mod_elts.length;i++){module.imports[mod_elts.slice(0,i+1).join(".")]=true} 2580 var _mod=this.module.replace(/\$/g,''),$package,packages=[] 2581 while(_mod.length > 0){if(_mod.charAt(0)=='.'){if($package===undefined){if($B.imported[mod]!==undefined){$package=$B.imported[mod].__package__ 2582 packages=$package.split('.')}}else{$package=$B.imported[$package] 2583 packages.pop()} 2584 if($package===undefined){return 'throw _b_.SystemError.$factory("Parent module \'\' '+ 2585 'not loaded, cannot perform relative import")'}else if($package=='None'){console.log('package is None !')} 2586 _mod=_mod.substr(1)}else{break}} 2587 if(_mod){packages.push(_mod)} 2588 this.module=packages.join('.') 2589 var mod_name=this.module.replace(/\$/g,'') 2590 res[pos++]='var module = $B.$import("' 2591 res[pos++]=mod_name+'",["' 2592 var names=[] 2593 for(var i=0,len=this.names.length;i < len;i++){if(Array.isArray(this.names[i])){names.push(this.names[i][0])}else{names.push(this.names[i])}} 2594 res[pos++]=names.join('","')+'"], {' 2595 var sep='' 2596 for(var attr in this.aliases){res[pos++]=sep+'"'+attr+'": "'+this.aliases[attr]+'"' 2597 sep=','} 2598 res[pos++]='}, {}, true);' 2599 if(this.names[0]=='*'){ 2600 scope.blurred=true 2601 res[pos++]='\n'+head+'$B.import_all($locals, module);'}else{this.names.forEach(function(name){var alias=name 2602 if(Array.isArray(name)){alias=name[1] 2603 name=name[0]} 2604 module.imports[this.module+'.'+name]=true 2605 res[pos++]='\n'+head+'$locals["'+ 2606 alias+'"] = $B.$getattr($B.imported["'+ 2607 mod_name+'"], "'+name+'");'},this)} 2608 res[pos++]='\n'+head+'_b_.None;' 2609 return res.join('');} 2610 var $FuncArgs=$B.parser.$FuncArgs=function(C){ 2611 this.type='func_args' 2612 this.parent=C 2613 this.tree=[] 2614 this.names=[] 2615 C.tree[C.tree.length]=this 2616 this.expect='id' 2617 this.has_default=false 2618 this.has_star_arg=false 2619 this.has_kw_arg=false} 2620 $FuncArgs.prototype.toString=function(){return 'func args '+this.tree} 2621 $FuncArgs.prototype.transition=function(token,value){var C=this 2622 switch(token){case 'id': 2623 if(C.has_kw_arg){$_SyntaxError(C,'duplicate keyword argument')} 2624 if(C.expect=='id'){C.expect=',' 2625 if(C.names.indexOf(value)>-1){$_SyntaxError(C,['duplicate argument '+value+ 2626 ' in function definition'])}} 2627 return new $FuncArgIdCtx(C,value) 2628 case ',': 2629 if(C.expect==','){C.expect='id' 2630 return C} 2631 $_SyntaxError(C,'token '+token+' after '+ 2632 C) 2633 case ')': 2634 var last=$B.last(C.tree) 2635 if(last && last.type=="func_star_arg"){if(last.name=="*"){if(C.op=='*'){ 2636 $_SyntaxError(C,['named arguments must follow bare *'])}else{$_SyntaxError(C,'invalid syntax')}}} 2637 return C.parent 2638 case 'op': 2639 if(C.has_kw_arg){$_SyntaxError(C,'duplicate keyword argument')} 2640 var op=value 2641 C.expect=',' 2642 if(op=='*'){if(C.has_star_arg){$_SyntaxError(C,'duplicate star argument')} 2643 return new $FuncStarArgCtx(C,'*')}else if(op=='**'){return new $FuncStarArgCtx(C,'**')}else if(op=='/'){ 2644 if(C.has_end_positional){$_SyntaxError(C,['duplicate / in function parameters'])}else if(C.has_star_arg){$_SyntaxError(C,['/ after * in function parameters'])} 2645 return new $EndOfPositionalCtx(C)} 2646 $_SyntaxError(C,'token '+op+' after '+C) 2647 case ':': 2648 if(C.parent.type=="lambda"){return $transition(C.parent,token)}} 2649 $_SyntaxError(C,'token '+token+' after '+C)} 2650 $FuncArgs.prototype.to_js=function(){this.js_processed=true 2651 return $to_js(this.tree)} 2652 var $FuncArgIdCtx=$B.parser.$FuncArgIdCtx=function(C,name){ 2653 this.type='func_arg_id' 2654 this.name=name 2655 this.parent=C 2656 if(C.has_star_arg){C.parent.after_star.push(name)}else{C.parent.positional_list.push(name)} 2657 var node=$get_node(this) 2658 if(node.binding[name]){$_SyntaxError(C,["duplicate argument '"+name+"' in function definition"])} 2659 $bind(name,node,this) 2660 this.tree=[] 2661 C.tree[C.tree.length]=this 2662 var ctx=C 2663 while(ctx.parent !==undefined){if(ctx.type=='def'){ctx.locals.push(name) 2664 break} 2665 ctx=ctx.parent} 2666 this.expect='='} 2667 $FuncArgIdCtx.prototype.toString=function(){return 'func arg id '+this.name+'='+this.tree} 2668 $FuncArgIdCtx.prototype.transition=function(token,value){var C=this 2669 switch(token){case '=': 2670 if(C.expect=='='){C.has_default=true 2671 var def_ctx=C.parent.parent 2672 if(C.parent.has_star_arg){def_ctx.default_list.push(def_ctx.after_star.pop())}else{def_ctx.default_list.push(def_ctx.positional_list.pop())} 2673 return new $AbstractExprCtx(C,false)} 2674 break 2675 case ',': 2676 case ')': 2677 if(C.parent.has_default && C.tree.length==0 && 2678 C.parent.has_star_arg===undefined){$pos-=C.name.length 2679 $_SyntaxError(C,['non-default argument follows default argument'])}else{return $transition(C.parent,token)} 2680 case ':': 2681 if(C.parent.parent.type=="lambda"){ 2682 return $transition(C.parent.parent,":")} 2683 if(C.has_default){ 2684 $_SyntaxError(C,'token '+token+' after '+ 2685 C)} 2686 return new $AbstractExprCtx(new $AnnotationCtx(C),false)} 2687 $_SyntaxError(C,'token '+token+' after '+C)} 2688 $FuncArgIdCtx.prototype.to_js=function(){this.js_processed=true 2689 return this.name+$to_js(this.tree)} 2690 var $FuncStarArgCtx=$B.parser.$FuncStarArgCtx=function(C,op){ 2691 this.type='func_star_arg' 2692 this.op=op 2693 this.parent=C 2694 this.node=$get_node(this) 2695 C.has_star_arg=op=='*' 2696 C.has_kw_arg=op=='**' 2697 C.tree[C.tree.length]=this} 2698 $FuncStarArgCtx.prototype.toString=function(){return '(func star arg '+this.op+') '+this.name} 2699 $FuncStarArgCtx.prototype.transition=function(token,value){var C=this 2700 switch(token){case 'id': 2701 if(C.name===undefined){if(C.parent.names.indexOf(value)>-1){$_SyntaxError(C,['duplicate argument '+value+ 2702 ' in function definition'])}} 2703 C.set_name(value) 2704 C.parent.names.push(value) 2705 return C 2706 case ',': 2707 case ')': 2708 if(C.name===undefined){ 2709 C.set_name('*') 2710 C.parent.names.push('*')} 2711 return $transition(C.parent,token) 2712 case ':': 2713 if(C.parent.parent.type=="lambda"){ 2714 return $transition(C.parent.parent,":")} 2715 if(C.name===undefined){$_SyntaxError(C,'annotation on an unnamed parameter')} 2716 return new $AbstractExprCtx( 2717 new $AnnotationCtx(C),false)} 2718 $_SyntaxError(C,'token '+token+' after '+C)} 2719 $FuncStarArgCtx.prototype.set_name=function(name){this.name=name 2720 if(this.node.binding[name]){$_SyntaxError(C,["duplicate argument '"+name+"' in function definition"])} 2721 $bind(name,this.node,this) 2722 var ctx=this.parent 2723 while(ctx.parent !==undefined){if(ctx.type=='def'){ctx.locals.push(name) 2724 break} 2725 ctx=ctx.parent} 2726 if(this.op=='*'){ctx.other_args='"'+name+'"'} 2727 else{ctx.other_kw='"'+name+'"'}} 2728 var $GlobalCtx=$B.parser.$GlobalCtx=function(C){ 2729 this.type='global' 2730 this.parent=C 2731 this.tree=[] 2732 C.tree[C.tree.length]=this 2733 this.expect='id' 2734 this.scope=$get_scope(this) 2735 this.scope.globals=this.scope.globals ||new Set() 2736 this.module=$get_module(this) 2737 while(this.module.module !=this.module.id){this.module=this.module.parent_block} 2738 this.module.binding=this.module.binding ||{}} 2739 $GlobalCtx.prototype.toString=function(){return 'global '+this.tree} 2740 $GlobalCtx.prototype.transition=function(token,value){var C=this 2741 switch(token){case 'id': 2742 if(C.expect=='id'){new $IdCtx(C,value) 2743 C.add(value) 2744 C.expect=',' 2745 return C} 2746 break 2747 case ',': 2748 if(C.expect==','){C.expect='id' 2749 return C} 2750 break 2751 case 'eol': 2752 if(C.expect==','){return $transition(C.parent,token)} 2753 break} 2754 $_SyntaxError(C,'token '+token+' after '+C)} 2755 $GlobalCtx.prototype.add=function(name){if(this.scope.annotations && this.scope.annotations.has(name)){$_SyntaxError(C,["annotated name '"+name+ 2756 "' can't be global"])} 2757 this.scope.globals.add(name) 2758 var mod=this.scope.parent_block 2759 if(this.module.module.startsWith("$exec")){while(mod && mod.parent_block !==this.module){ 2760 mod._globals=mod._globals ||{} 2761 mod._globals[name]=this.module.id 2762 delete mod.binding[name] 2763 mod=mod.parent_block}} 2764 this.module.binding[name]=true} 2765 $GlobalCtx.prototype.to_js=function(){this.js_processed=true 2766 return ''} 2767 var $IdCtx=$B.parser.$IdCtx=function(C,value){ 2768 this.type='id' 2769 this.value=$mangle(value,C) 2770 this.parent=C 2771 this.tree=[] 2772 C.tree[C.tree.length]=this 2773 var scope=this.scope=$get_scope(this) 2774 this.blurred_scope=this.scope.blurred 2775 this.env=clone(this.scope.binding) 2776 if(["def","generator"].indexOf(scope.ntype)>-1){scope.referenced=scope.referenced ||{} 2777 if(! $B.builtins[this.value]){scope.referenced[this.value]=true}} 2778 if(C.parent.type=='call_arg'){this.call_arg=true} 2779 var ctx=C 2780 while(ctx.parent !==undefined){switch(ctx.type){case 'ctx_manager_alias': 2781 $bind(value,scope,this) 2782 break 2783 case 'list_or_tuple': 2784 case 'dict_or_set': 2785 case 'call_arg': 2786 case 'def': 2787 case 'lambda': 2788 if(ctx.vars===undefined){ctx.vars=[value]} 2789 else if(ctx.vars.indexOf(value)==-1){ctx.vars.push(value)} 2790 if(this.call_arg&&ctx.type=='lambda'){if(ctx.locals===undefined){ctx.locals=[value]} 2791 else{ctx.locals.push(value)}}} 2792 ctx=ctx.parent} 2793 if($parent_match(C,{type:'target_list'})){ 2794 this.no_bindings=true 2795 $bind(value,scope,this) 2796 this.bound=true} 2797 if(["def","generator"].indexOf(scope.ntype)>-1){ 2798 var _ctx=this.parent 2799 while(_ctx){if(_ctx.type=='list_or_tuple' && _ctx.is_comp()){this.in_comp=true 2800 break} 2801 _ctx=_ctx.parent} 2802 if(C.type=='expr' && C.parent.type=='comp_if'){}else if(C.type=='global'){if(scope.globals===undefined){scope.globals=new Set([value])}else{scope.globals.add(value)}}}} 2803 $IdCtx.prototype.toString=function(){return '(id) '+this.value+':'+(this.tree ||'')} 2804 $IdCtx.prototype.transition=function(token,value){var C=this 2805 switch(token){case '=': 2806 if(C.parent.type=='expr' && 2807 C.parent.parent !==undefined && 2808 C.parent.parent.type=='call_arg'){return new $AbstractExprCtx( 2809 new $KwArgCtx(C.parent),false)} 2810 return $transition(C.parent,token,value) 2811 case 'op': 2812 return $transition(C.parent,token,value) 2813 case 'id': 2814 case 'str': 2815 case 'int': 2816 case 'float': 2817 case 'imaginary': 2818 if(["print","exec"].indexOf(C.value)>-1 ){$_SyntaxError(C,["missing parenthesis in call to '"+ 2819 C.value+"'"])} 2820 $_SyntaxError(C,'token '+token+' after '+ 2821 C)} 2822 if(this.parent.parent.type=="packed"){if(['.','[','('].indexOf(token)==-1){return this.parent.parent.transition(token,value)}} 2823 return $transition(C.parent,token,value)} 2824 $IdCtx.prototype.firstBindingScopeId=function(){ 2825 var scope=this.scope,found=[],nb=0 2826 while(scope){if(scope.globals && scope.globals.has(this.value)){return $get_module(this).id} 2827 if(scope.binding && scope.binding[this.value]){return scope.id} 2828 scope=scope.parent}} 2829 $IdCtx.prototype.boundBefore=function(scope){ 2830 var node=$get_node(this),found=false 2831 var $test=false 2832 if($test){console.log(this.value,"bound before") 2833 console.log("node",node)} 2834 while(!found && node.parent){var pnode=node.parent 2835 if(pnode.bindings && pnode.bindings[this.value]){if($test){console.log("bound in",pnode)} 2836 return pnode.bindings[this.value]} 2837 for(var i=0;i < pnode.children.length;i++){var child=pnode.children[i] 2838 if(child===node){break} 2839 if(child.bindings && child.bindings[this.value]){if($test){console.log("bound in child",child)} 2840 return child.bindings[this.value]}} 2841 if(pnode===scope){break} 2842 node=pnode} 2843 return found} 2844 $IdCtx.prototype.bindingType=function(scope){ 2845 var nb=0,node=$get_node(this),found=false,unknown,ix 2846 while(!found && node.parent && nb++< 100){var pnode=node.parent 2847 if(pnode.bindings && pnode.bindings[this.value]){return pnode.bindings[this.value]} 2848 for(var i=0;i < pnode.children.length;i++){var child=pnode.children[i] 2849 if(child===node){break} 2850 if(child.bindings && child.bindings[this.value]){found=child.bindings[this.value] 2851 ix=i}} 2852 if(found){for(var j=ix+1;j < pnode.children.length;j++){child=pnode.children[j] 2853 if(child.children.length > 0){unknown=true 2854 break}else if(child===node){break}} 2855 return unknown ||found} 2856 if(pnode===scope){break} 2857 node=pnode} 2858 return found} 2859 $IdCtx.prototype.to_js=function(arg){ 2860 if(this.result !==undefined && this.scope.ntype=='generator'){return this.result} 2861 var val=this.value 2862 var $test=false 2863 if($test){console.log("this",this)} 2864 if(val=='__BRYTHON__' ||val=='$B'){return val} 2865 if(val.startsWith("comp_result_"+$B.lambda_magic)){if(this.bound){return "var "+val} 2866 return val} 2867 this.js_processed=true 2868 if(this.scope._globals && this.scope._globals[val]){this.global_module=this.scope._globals[val]} 2869 if(this.global_module){return '$locals_'+this.global_module.replace(/\./g,"_")+ 2870 '["'+val+'"]'} 2871 var is_local=this.scope.binding[val]!==undefined,this_node=$get_node(this),bound_before=this_node.bound_before 2872 this.nonlocal=this.scope.nonlocals && 2873 this.scope.nonlocals[val]!==undefined 2874 this.unbound=this.unbound ||(is_local && !this.bound && 2875 bound_before && bound_before.indexOf(val)==-1) 2876 if((!this.bound)&& this.scope.C 2877 && this.scope.ntype=='class' && 2878 this.scope.C.tree[0].name==val){ 2879 return '$B.$search("'+val+'")'} 2880 if(this.unbound && !this.nonlocal){if(this.scope.ntype=='def' ||this.scope.ntype=='generator'){return '$B.$local_search("'+val+'")'}else{return '$B.$search("'+val+'")'}} 2881 var innermost=$get_scope(this),scope=innermost,found=[] 2882 var search_ids=['"'+innermost.id+'"'] 2883 var gs=innermost 2884 while(true){if($test){console.log(gs.id,gs)} 2885 if(gs.parent_block){if(gs.parent_block==$B.builtins_scope){break} 2886 else if(gs.parent_block.id===undefined){break} 2887 gs=gs.parent_block} 2888 search_ids.push('"'+gs.id+'"')} 2889 search_ids="["+search_ids.join(", ")+"]" 2890 if(innermost.globals && innermost.globals.has(val)){search_ids=['"'+gs.id+'"'] 2891 innermost=gs} 2892 if($test){console.log("search ids",search_ids)} 2893 if(this.nonlocal ||this.bound){var bscope=this.firstBindingScopeId() 2894 if($test){console.log("binding",bscope)} 2895 if(bscope !==undefined){return "$locals_"+bscope.replace(/\./g,"_")+'["'+ 2896 val+'"]'}else if(this.bound){return "$locals_"+innermost.id.replace(/\./g,"_")+ 2897 '["'+val+'"]'}} 2898 var global_ns='$locals_'+gs.id.replace(/\./g,'_') 2899 while(1){if(scope.globals !==undefined && 2900 scope.globals.has(val)){if($test){console.log("in globals of",scope.id)} 2901 if(this.boundBefore(gs)){if($test){console.log("bound before in gs",gs)} 2902 return global_ns+'["'+val+'"]'}else{if($test){console.log("use global search",this)} 2903 if(this.augm_assign){return global_ns+'["'+val+'"]'}else{return '$B.$global_search("'+val+'", '+ 2904 search_ids+')'}}} 2905 if($test){console.log("scope",scope,"innermost",innermost,scope===innermost,"bound_before",bound_before,"found",found.slice())} 2906 if(scope===innermost){ 2907 if(bound_before){if(bound_before.indexOf(val)>-1){found.push(scope)} 2908 else if(scope.C && 2909 scope.C.tree[0].type=='def' && 2910 scope.C.tree[0].env.indexOf(val)>-1){found.push(scope)}}else{if(scope.binding[val]){ 2911 if(this_node.locals[val]===undefined){ 2912 if(!scope.is_comp && 2913 (!scope.parent_block || 2914 !scope.parent_block.is_comp)){ 2915 found.push(scope)}}else{found.push(scope) 2916 break} 2917 if($test){console.log(val,"found in",scope.id)}}}}else{if(scope.binding===undefined){console.log("scope",scope,val,"no binding",innermost)} 2918 if(scope.binding[val]){found.push(scope)}} 2919 if(scope.parent_block){scope=scope.parent_block} 2920 else{break}} 2921 this.found=found 2922 if($test){console.log("found",found) 2923 found.forEach(function(item){console.log(item.id)})} 2924 if(this.nonlocal && found[0]===innermost){found.shift()} 2925 if(found.length > 0){ 2926 if(found[0].C && found[0]===innermost 2927 && val.charAt(0)!='$'){var locs=this_node.locals ||{},nonlocs=innermost.nonlocals 2928 try{if(locs[val]===undefined && 2929 ! this.augm_assign && 2930 ((innermost.type !='def' || 2931 innermost.type !='generator')&& 2932 innermost.ntype !='class' && 2933 innermost.C.tree[0].args && 2934 innermost.C.tree[0].args.indexOf(val)==-1)&& 2935 (nonlocs===undefined ||nonlocs[val]===undefined)){if($test){console.log("$local search",val,"found",found,"innermost",innermost,"this",this)} 2936 this.result='$B.$local_search("'+val+'")' 2937 return this.result}}catch(err){console.log("error",val,innermost) 2938 throw err}} 2939 if(found.length > 1 && found[0].C){if(found[0].C.tree[0].type=='class'){var ns0='$locals_'+found[0].id.replace(/\./g,'_'),ns1='$locals_'+found[1].id.replace(/\./g,'_'),res 2940 if(bound_before){if(bound_before.indexOf(val)>-1){this.found=found[0].binding[val] 2941 res=ns0}else{this.found=found[1].binding[val] 2942 res=ns1} 2943 this.result=res+'["'+val+'"]' 2944 return this.result}else{this.found=false 2945 var res=ns0+'["'+val+'"] !== undefined ? ' 2946 res+=ns0+'["'+val+'"] : ' 2947 this.result="("+res+ns1+'["'+val+'"])' 2948 return this.result}}} 2949 var scope=found[0] 2950 this.found=scope.binding[val] 2951 var scope_ns='$locals_'+scope.id.replace(/\./g,'_') 2952 if(scope.C===undefined){if($test){console.log("module level",scope.id,scope.module)} 2953 if(scope.id=='__builtins__'){if(gs.blurred){ 2954 val='('+global_ns+'["'+val+'"] || _b_.'+val+')'}else{ 2955 val='_b_.'+val 2956 this.is_builtin=true}}else{ 2957 if($test){console.log("name found at module level")} 2958 if(this.bound ||this.augm_assign){ 2959 val=scope_ns+'["'+val+'"]'}else{if(scope===innermost && this.env[val]===undefined){ 2960 this.result='$B.$search("'+val+'")' 2961 return this.result}else{if($test){console.log("boudn before ?",scope,this.boundBefore(scope))} 2962 if(this.boundBefore(scope)){ 2963 val=scope_ns+'["'+val+'"]'}else{ 2964 if($test){console.log("use check def",scope)} 2965 val='$B.$check_def("'+val+'",'+ 2966 scope_ns+'["'+val+'"])'}}}}}else if(scope===innermost){if($test){console.log("scope is innermost",scope.id)} 2967 if(scope.globals && scope.globals.has(val)){val=global_ns+'["'+val+'"]'}else if(!this.bound && !this.augm_assign){ 2968 if(this.boundBefore(scope)){val='$locals["'+val+'"]'}else{val='$B.$check_def_local("'+val+'",$locals["'+ 2969 val+'"])'}}else{val='$locals["'+val+'"]'}}else if(!this.augm_assign){ 2970 val='$B.$check_def_free("'+val+'",'+scope_ns+ 2971 '["'+val+'"])'}else{val=scope_ns+'["'+val+'"]'} 2972 this.result=val+$to_js(this.tree,'') 2973 return this.result}else{ 2974 this.unknown_binding=true 2975 this.result='$B.$global_search("'+val+'", '+search_ids+')' 2976 return this.result}} 2977 var $ImportCtx=$B.parser.$ImportCtx=function(C){ 2978 this.type='import' 2979 this.parent=C 2980 this.tree=[] 2981 C.tree[C.tree.length]=this 2982 this.expect='id'} 2983 $ImportCtx.prototype.toString=function(){return 'import '+this.tree} 2984 $ImportCtx.prototype.transition=function(token,value){var C=this 2985 switch(token){case 'id': 2986 if(C.expect=='id'){new $ImportedModuleCtx(C,value) 2987 C.expect=',' 2988 return C} 2989 if(C.expect=='qual'){C.expect=',' 2990 C.tree[C.tree.length-1].name+= 2991 '.'+value 2992 C.tree[C.tree.length-1].alias+= 2993 '.'+value 2994 return C} 2995 if(C.expect=='alias'){C.expect=',' 2996 C.tree[C.tree.length-1].alias= 2997 value 2998 return C} 2999 break 3000 case '.': 3001 if(C.expect==','){C.expect='qual' 3002 return C} 3003 break 3004 case ',': 3005 if(C.expect==','){C.expect='id' 3006 return C} 3007 break 3008 case 'as': 3009 if(C.expect==','){C.expect='alias' 3010 return C} 3011 break 3012 case 'eol': 3013 if(C.expect==','){C.bind_names() 3014 return $transition(C.parent,token)} 3015 break} 3016 $_SyntaxError(C,'token '+token+' after '+C)} 3017 $ImportCtx.prototype.bind_names=function(){ 3018 var scope=$get_scope(this) 3019 this.tree.forEach(function(item){if(item.name==item.alias){var name=item.name,parts=name.split('.'),bound=name 3020 if(parts.length>1){bound=parts[0]}}else{bound=item.alias} 3021 $bind(bound,scope,this)},this)} 3022 $ImportCtx.prototype.to_js=function(){this.js_processed=true 3023 var scope=$get_scope(this),res=[],module=$get_module(this) 3024 this.tree.forEach(function(item){var mod_name=item.name,aliases=(item.name==item.alias)? 3025 '{}' :('{"'+mod_name+'" : "'+ 3026 item.alias+'"}'),localns='$locals_'+scope.id.replace(/\./g,'_'),mod_elts=item.name.split(".") 3027 for(var i=0;i < mod_elts.length;i++){module.imports[mod_elts.slice(0,i+1).join(".")]=true} 3028 var js='$B.$import("'+mod_name+'", [],'+aliases+ 3029 ','+localns+', true);' 3030 res.push(js)}) 3031 return res.join('')+'_b_.None;'} 3032 var $ImportedModuleCtx=$B.parser.$ImportedModuleCtx=function(C,name){this.type='imported module' 3033 this.parent=C 3034 this.name=name 3035 this.alias=name 3036 C.tree[C.tree.length]=this} 3037 $ImportedModuleCtx.prototype.toString=function(){return ' (imported module) '+this.name} 3038 $ImportedModuleCtx.prototype.transition=function(token,value){var C=this} 3039 $ImportedModuleCtx.prototype.to_js=function(){this.js_processed=true 3040 return '"'+this.name+'"'} 3041 var $JSCode=$B.parser.$JSCode=function(js){this.js=js} 3042 $JSCode.prototype.toString=function(){return this.js} 3043 $JSCode.prototype.transition=function(token,value){var C=this} 3044 $JSCode.prototype.to_js=function(){this.js_processed=true 3045 return this.js} 3046 var $KwArgCtx=$B.parser.$KwArgCtx=function(C){ 3047 this.type='kwarg' 3048 this.parent=C.parent 3049 this.tree=[C.tree[0]] 3050 C.parent.tree.pop() 3051 C.parent.tree.push(this) 3052 C.parent.parent.has_kw=true 3053 var value=this.tree[0].value 3054 var ctx=C.parent.parent 3055 if(ctx.kwargs===undefined){ctx.kwargs=[value]} 3056 else if(ctx.kwargs.indexOf(value)==-1){ctx.kwargs.push(value)} 3057 else{$_SyntaxError(C,['keyword argument repeated'])}} 3058 $KwArgCtx.prototype.toString=function(){return 'kwarg '+this.tree[0]+'='+this.tree[1]} 3059 $KwArgCtx.prototype.transition=function(token,value){var C=this 3060 if(token==','){return new $CallArgCtx(C.parent.parent)} 3061 return $transition(C.parent,token)} 3062 $KwArgCtx.prototype.to_js=function(){this.js_processed=true 3063 var key=this.tree[0].value 3064 if(key.substr(0,2)=='$$'){key=key.substr(2)} 3065 var res='{$nat:"kw",name:"'+key+'",' 3066 return res+'value:'+ 3067 $to_js(this.tree.slice(1,this.tree.length))+'}'} 3068 var $LambdaCtx=$B.parser.$LambdaCtx=function(C){ 3069 this.type='lambda' 3070 this.parent=C 3071 C.tree[C.tree.length]=this 3072 this.tree=[] 3073 this.args_start=$pos+6 3074 this.vars=[] 3075 this.locals=[] 3076 this.node=$get_node(this) 3077 this.node.binding={} 3078 this.positional_list=[] 3079 this.default_list=[] 3080 this.other_args=null 3081 this.other_kw=null 3082 this.after_star=[]} 3083 $LambdaCtx.prototype.toString=function(){return '(lambda) '+this.args_start+' '+this.body_start} 3084 $LambdaCtx.prototype.transition=function(token,value){var C=this 3085 if(token==':' && C.args===undefined){C.args=C.tree 3086 C.tree=[] 3087 C.body_start=$pos 3088 return new $AbstractExprCtx(C,false)}if(C.args !==undefined){ 3089 C.body_end=$pos 3090 return $transition(C.parent,token)} 3091 if(C.args===undefined && token !="("){return $transition(new $FuncArgs(C),token,value)} 3092 $_SyntaxError(C,'token '+token+' after '+C)} 3093 $LambdaCtx.prototype.to_js=function(){this.js_processed=true 3094 var C=this.parent,node=this.node,module=$get_module(this),src=$get_src(C),args=src.substring(this.args_start,this.body_start),body=src.substring(this.body_start+1,this.body_end) 3095 body=body.replace(/\\\n/g,' ') 3096 body=body.replace(/\n/g,' ') 3097 var scope=$get_scope(this) 3098 var rand=$B.UUID(),func_name='lambda_'+$B.lambda_magic+'_'+rand,py='def '+func_name+'('+args+'):' 3099 py+=' return '+body 3100 var lambda_name='lambda'+rand,module_name=module.id.replace(/\./g,'_') 3101 var root=$B.py2js(py,module_name,lambda_name,scope,node.line_num) 3102 var js=root.to_js() 3103 var params=`$locals_${lambda_name}`,args="{}" 3104 if(module.is_comp){ 3105 params+=`,$locals_${module.id.replace(/\./g,'_')}` 3106 args+=`,typeof $locals_${module.id.replace(/\./g,'_')}`+ 3107 `==="undefined" ?{}:$locals_${module.id.replace(/\./g,'_')}`} 3108 js=`(function(${params}){\n`+js+ 3109 `\nreturn $locals.${func_name}})(${args})` 3110 $B.clear_ns(lambda_name) 3111 $B.$py_src[lambda_name]=null 3112 delete $B.$py_src[lambda_name] 3113 return js} 3114 var $ListOrTupleCtx=$B.parser.$ListOrTupleCtx=function(C,real){ 3115 this.type='list_or_tuple' 3116 this.start=$pos 3117 this.real=real 3118 this.expect='id' 3119 this.closed=false 3120 this.parent=C 3121 this.tree=[] 3122 C.tree[C.tree.length]=this} 3123 $ListOrTupleCtx.prototype.toString=function(){switch(this.real){case 'list': 3124 return '(list) ['+this.tree+']' 3125 case 'list_comp': 3126 case 'gen_expr': 3127 return '('+this.real+') ['+this.intervals+'-'+ 3128 this.tree+']' 3129 default: 3130 return '(tuple) ('+this.tree+')'}} 3131 $ListOrTupleCtx.prototype.transition=function(token,value){var C=this 3132 if(C.closed){if(token=='['){return new $AbstractExprCtx( 3133 new $SubCtx(C.parent),false)} 3134 if(token=='('){return new $CallCtx(C.parent)} 3135 return $transition(C.parent,token,value)}else{if(C.expect==','){switch(C.real){case 'tuple': 3136 case 'gen_expr': 3137 if(token==')'){var close=true 3138 while(C.type=="list_or_tuple" && 3139 C.real=="tuple" && 3140 C.parent.type=="expr" && 3141 C.parent.parent.type=="node" && 3142 C.tree.length==1){ 3143 close=false 3144 var node=C.parent.parent,ix=node.tree.indexOf(C.parent),expr=C.tree[0] 3145 expr.parent=node 3146 expr.$in_parens=true 3147 node.tree.splice(ix,1,expr) 3148 C=expr.tree[0]} 3149 if(close){C.close()} 3150 if(C.real=='gen_expr'){ 3151 if(C.expression.yields){for(const _yield of C.expression.yields){$pos=_yield[1] 3152 $_SyntaxError(C,["'yield' inside generator expression"])}} 3153 C.intervals.push($pos)} 3154 if(C.parent.type=="packed"){return C.parent.parent} 3155 if(C.parent.type=="abstract_expr" && 3156 C.parent.assign){ 3157 C.parent.parent.tree.pop() 3158 var expr=new $ExprCtx(C.parent.parent,"assign",false) 3159 expr.tree=C.parent.tree 3160 expr.tree[0].parent=expr 3161 expr.assign=C.parent.assign 3162 return expr} 3163 return C.parent} 3164 break 3165 case 'list': 3166 case 'list_comp': 3167 if(token==']'){C.close() 3168 if(C.real=='list_comp'){ 3169 if(C.expression.yields){for(const _yield of C.expression.yields){$pos=_yield[1] 3170 $_SyntaxError(C,["'yield' inside list comprehension"])}} 3171 C.intervals.push($pos)} 3172 if(C.parent.type=="packed"){if(C.parent.tree.length > 0){return C.parent.tree[0]}else{return C.parent.parent}} 3173 return C.parent} 3174 break 3175 case 'dict_or_set_comp': 3176 if(token=='}'){ 3177 if(C.expression.yields){for(const _yield of C.expression.yields){$pos=_yield[1] 3178 var comp_type=C.parent.real=="set_comp" ? 3179 "set" :"dict" 3180 $_SyntaxError(C,[`'yield' inside ${comp_type}comprehension`])}} 3181 C.intervals.push($pos) 3182 return $transition(C.parent,token)} 3183 break} 3184 switch(token){case ',': 3185 if(C.real=='tuple'){C.has_comma=true} 3186 C.expect='id' 3187 return C 3188 case 'for': 3189 if(C.real=='list'){if(this.tree.length > 1){ 3190 $_SyntaxError(C,"unparenthesized "+ 3191 "expression before 'for'")} 3192 C.real='list_comp'} 3193 else{C.real='gen_expr'} 3194 C.intervals=[C.start+1] 3195 C.expression=C.tree 3196 if(C.yields){C.expression.yields=C.yields 3197 delete C.yields} 3198 C.tree=[] 3199 var comp=new $ComprehensionCtx(C) 3200 return new $TargetListCtx(new $CompForCtx(comp))} 3201 return $transition(C.parent,token,value)}else if(C.expect=='id'){switch(C.real){case 'tuple': 3202 if(token==')'){C.close() 3203 return C.parent} 3204 if(token=='eol' && C.implicit===true){C.close() 3205 return $transition(C.parent,token)} 3206 break 3207 case 'gen_expr': 3208 if(token==')'){C.close() 3209 return $transition(C.parent,token)} 3210 break 3211 case 'list': 3212 if(token==']'){C.close() 3213 return C} 3214 break} 3215 switch(token){case '=': 3216 if(C.real=='tuple' && 3217 C.implicit===true){C.close() 3218 C.parent.tree.pop() 3219 var expr=new $ExprCtx(C.parent,'tuple',false) 3220 expr.tree=[C] 3221 C.parent=expr 3222 return $transition(C.parent,token)} 3223 break 3224 case ')': 3225 break 3226 case ']': 3227 if(C.real=='tuple' && 3228 C.implicit===true){ 3229 return $transition(C.parent,token,value)}else{break} 3230 case ',': 3231 $_SyntaxError(C,'unexpected comma inside list') 3232 default: 3233 C.expect=',' 3234 var expr=new $AbstractExprCtx(C,false) 3235 return $transition(expr,token,value)}}else{return $transition(C.parent,token,value)}}} 3236 $ListOrTupleCtx.prototype.close=function(){this.closed=true 3237 for(var i=0,len=this.tree.length;i < len;i++){ 3238 var elt=this.tree[i] 3239 if(elt.type=="expr" && 3240 elt.tree[0].type=="list_or_tuple" && 3241 elt.tree[0].real=="tuple" && 3242 elt.tree[0].tree.length==1 && 3243 elt.tree[0].expect==","){this.tree[i]=elt.tree[0].tree[0] 3244 this.tree[i].parent=this}}} 3245 $ListOrTupleCtx.prototype.is_comp=function(){switch(this.real){case 'list_comp': 3246 case 'gen_expr': 3247 case 'dict_or_set_comp': 3248 return true} 3249 return false} 3250 $ListOrTupleCtx.prototype.get_src=function(){ 3251 var src=$get_module(this).src 3252 var scope=$get_scope(this) 3253 if(scope.comments===undefined){return src} 3254 scope.comments.forEach(function(comment){var start=comment[0],len=comment[1] 3255 src=src.substr(0,start)+' '.repeat(len+1)+ 3256 src.substr(start+len+1)}) 3257 return src} 3258 $ListOrTupleCtx.prototype.bind_ids=function(scope){ 3259 this.tree.forEach(function(item){if(item.type=='id'){$bind(item.value,scope,this) 3260 item.bound=true}else if(item.type=='expr' && item.tree[0].type=="id"){$bind(item.tree[0].value,scope,this) 3261 item.tree[0].bound=true}else if(item.type=='expr' && item.tree[0].type=="packed"){var ctx=item.tree[0].tree[0] 3262 if(ctx.type=='expr' && ctx.tree[0].type=='id'){$bind(ctx.tree[0].value,scope,this) 3263 ctx.tree[0].bound=true}}else if(item.type=='list_or_tuple' || 3264 (item.type=="expr" && 3265 item.tree[0].type=='list_or_tuple')){if(item.type=="expr"){item=item.tree[0]} 3266 item.bind_ids(scope)}},this)} 3267 $ListOrTupleCtx.prototype.packed_indices=function(){var ixs=[] 3268 for(var i=0;i < this.tree.length;i++){var t=this.tree[i] 3269 if(t.type=="expr"){t=t.tree[0] 3270 if(t.type=="packed" || 3271 (t.type=="call" && t.func.type=="packed")){ixs.push(i)}}} 3272 return ixs} 3273 $ListOrTupleCtx.prototype.unpack=function(packed){var js="",res 3274 for(var i=0;i < this.tree.length;i++){if(packed.indexOf(i)>-1){res="_b_.list.$factory("+this.tree[i].to_js()+")"}else{res="["+this.tree[i].to_js()+"]"} 3275 if(i > 0){res=".concat("+res+")"} 3276 js+=res} 3277 return js} 3278 $ListOrTupleCtx.prototype.to_js=function(){this.js_processed=true 3279 var scope=$get_scope(this),sc=scope,scope_id=scope.id.replace(/\//g, '_'), 3280 pos = 0 3281 var root = $get_module(this), 3282 module_name = root.module 3283 switch(this.real) { 3284 case 'list': 3285 var packed = this.packed_indices() 3286 if(packed.length > 0){ 3287 return '$B.$list(' + this.unpack(packed) + ')' 3288 } 3289 return '$B.$list([' + $to_js(this.tree) + '])' 3290 case 'list_comp': 3291 case 'gen_expr': 3292 case 'dict_or_set_comp': 3293 var src = this.get_src() 3294 var res1 = [], items = [] 3295 var qesc = new RegExp('"', "g") //to escape double quotes in arguments 3296 var comments=root.comments 3297 for(var i=1;i < this.intervals.length;i++){var start=this.intervals[i-1],end=this.intervals[i],txt=src.substring(start,end) 3298 for(var j=comments.length-1;j >=0;j--){var comment=comments[j] 3299 if(comment[0]> start && comment[0]< end){ 3300 var pos=comment[0]-start 3301 txt=txt.substr(0,pos)+ 3302 ' '.repeat(comment[1])+ 3303 txt.substr(pos+comment[1]+1)}} 3304 txt=txt.replace(/\\\n/g," ") 3305 items.push(txt) 3306 var lines=txt.split('\n') 3307 var res2=[] 3308 lines.forEach(function(txt){ 3309 if(txt.replace(/ /g,'').length !=0){txt=txt.replace(/\n/g,' ') 3310 txt=txt.replace(/\\/g,'\\\\') 3311 txt=txt.replace(qesc,'\\"') 3312 res2.push('"'+txt+'"')}}) 3313 res1.push('['+res2.join(',')+']')} 3314 var line_num=$get_node(this).line_num 3315 switch(this.real){case 'list_comp': 3316 var lc=$B.$list_comp(items), 3317 py=lc[0],ix=lc[1],listcomp_name='lc'+$B.lambda_magic+ix,save_pos=$pos,line_info=line_num+','+module_name 3318 var root=$B.py2js( 3319 {src:py,is_comp:true,line_info:line_info},module_name,listcomp_name,scope,1) 3320 var outermost_expr=root.outermost_expr 3321 if($get_node(this).has_yield){outermost_expr=this.tree[0].tree[0].tree[1]} 3322 if(outermost_expr===undefined){outermost_expr=root.first_for.tree[1]} 3323 var outer_most=outermost_expr.to_js() 3324 $pos=save_pos 3325 var js=root.to_js() 3326 root=null 3327 $B.clear_ns(listcomp_name) 3328 delete $B.$py_src[listcomp_name] 3329 js+='return $locals_'+listcomp_name+'["x'+ix+'"]' 3330 js=`function(expr){${js}})(${outer_most})` 3331 if(this.is_await){js='async '+js} 3332 return '('+js 3333 case 'dict_or_set_comp': 3334 if(this.expression.length==1){return $B.$gen_expr(module_name,scope,items,line_num,true)} 3335 return $B.$dict_comp(module_name,scope,items,line_num)} 3336 return $B.$gen_expr(module_name,scope,items,line_num) 3337 case 'tuple': 3338 var packed=this.packed_indices() 3339 if(packed.length > 0){return '$B.fast_tuple('+this.unpack(packed)+')'} 3340 if(this.tree.length==1 && this.has_comma===undefined){return this.tree[0].to_js()} 3341 return '$B.fast_tuple(['+$to_js(this.tree)+'])'}} 3342 var $NodeCtx=$B.parser.$NodeCtx=function(node){ 3343 this.node=node 3344 node.C=this 3345 this.tree=[] 3346 this.type='node' 3347 var scope=null 3348 var tree_node=node 3349 while(tree_node.parent && tree_node.parent.type !='module'){var ntype=tree_node.parent.C.tree[0].type,_break_flag=false 3350 switch(ntype){case 'def': 3351 case 'class': 3352 case 'generator': 3353 scope=tree_node.parent 3354 _break_flag=true} 3355 if(_break_flag){break} 3356 tree_node=tree_node.parent} 3357 if(scope===null){scope=tree_node.parent ||tree_node } 3358 this.node.locals=clone(scope.binding) 3359 this.scope=scope} 3360 $NodeCtx.prototype.toString=function(){return 'node '+this.tree} 3361 $NodeCtx.prototype.transition=function(token,value){var C=this 3362 switch(token){case 'id': 3363 case 'imaginary': 3364 case 'int': 3365 case 'float': 3366 case 'str': 3367 case 'bytes': 3368 case '[': 3369 case '(': 3370 case '{': 3371 case 'not': 3372 case 'lambda': 3373 case '.': 3374 var expr=new $AbstractExprCtx(C,true) 3375 return $transition(expr,token,value) 3376 case 'op': 3377 switch(value){case '*': 3378 case '+': 3379 case '-': 3380 case '~': 3381 var expr=new $AbstractExprCtx(C,true) 3382 return $transition(expr,token,value)} 3383 break 3384 case 'async': 3385 return new $AsyncCtx(C) 3386 case 'await': 3387 return new $AbstractExprCtx(new $AwaitCtx(C),true) 3388 case 'class': 3389 return new $ClassCtx(C) 3390 case 'continue': 3391 return new $ContinueCtx(C) 3392 case '__debugger__': 3393 return new $DebuggerCtx(C) 3394 case 'break': 3395 return new $BreakCtx(C) 3396 case 'def': 3397 return new $DefCtx(C) 3398 case 'for': 3399 return new $TargetListCtx(new $ForExpr(C)) 3400 case 'if': 3401 case 'while': 3402 return new $AbstractExprCtx( 3403 new $ConditionCtx(C,token),false) 3404 case 'elif': 3405 var previous=$previous(C) 3406 if(['condition'].indexOf(previous.type)==-1 || 3407 previous.token=='while'){$_SyntaxError(C,'elif after '+previous.type)} 3408 return new $AbstractExprCtx( 3409 new $ConditionCtx(C,token),false) 3410 case 'else': 3411 var previous=$previous(C) 3412 if(['condition','except','for']. 3413 indexOf(previous.type)==-1){$_SyntaxError(C,'else after '+previous.type)} 3414 return new $SingleKwCtx(C,token) 3415 case 'finally': 3416 var previous=$previous(C) 3417 if(['try','except'].indexOf(previous.type)==-1 && 3418 (previous.type !='single_kw' || 3419 previous.token !='else')){$_SyntaxError(C,'finally after '+previous.type)} 3420 return new $SingleKwCtx(C,token) 3421 case 'try': 3422 return new $TryCtx(C) 3423 case 'except': 3424 var previous=$previous(C) 3425 if(['try','except'].indexOf(previous.type)==-1){$_SyntaxError(C,'except after '+previous.type)} 3426 return new $ExceptCtx(C) 3427 case 'assert': 3428 return new $AbstractExprCtx( 3429 new $AssertCtx(C),false,true) 3430 case 'from': 3431 return new $FromCtx(C) 3432 case 'import': 3433 return new $ImportCtx(C) 3434 case 'global': 3435 return new $GlobalCtx(C) 3436 case 'nonlocal': 3437 return new $NonlocalCtx(C) 3438 case 'lambda': 3439 return new $LambdaCtx(C) 3440 case 'pass': 3441 return new $PassCtx(C) 3442 case 'raise': 3443 return new $AbstractExprCtx(new $RaiseCtx(C),true) 3444 case 'return': 3445 return new $AbstractExprCtx(new $ReturnCtx(C),true) 3446 case 'with': 3447 return new $AbstractExprCtx(new $WithCtx(C),false) 3448 case 'yield': 3449 return new $AbstractExprCtx(new $YieldCtx(C),true) 3450 case 'del': 3451 return new $AbstractExprCtx(new $DelCtx(C),true) 3452 case '@': 3453 return new $DecoratorCtx(C) 3454 case ',': 3455 if(C.tree && C.tree.length==0){$_SyntaxError(C,'token '+token+' after '+C)} 3456 var first=C.tree[0] 3457 C.tree=[] 3458 var implicit_tuple=new $ListOrTupleCtx(C) 3459 implicit_tuple.real="tuple" 3460 implicit_tuple.implicit=0 3461 implicit_tuple.tree.push(first) 3462 first.parent=implicit_tuple 3463 return implicit_tuple 3464 case 'eol': 3465 if(C.tree.length==0){ 3466 C.node.parent.children.pop() 3467 return C.node.parent.C} 3468 return C} 3469 $_SyntaxError(C,'token '+token+' after '+C)} 3470 $NodeCtx.prototype.to_js=function(){if(this.js !==undefined){return this.js} 3471 this.js_processed=true 3472 if(this.tree.length > 1){var new_node=new $Node() 3473 var ctx=new $NodeCtx(new_node) 3474 ctx.tree=[this.tree[1]] 3475 new_node.indent=node.indent+4 3476 this.tree.pop() 3477 node.add(new_node)} 3478 this.js="" 3479 if(this.tree[0]){var is_not_def=this.scope.ntype !="def" 3480 if(this.tree[0].annotation){ 3481 if(is_not_def){if(this.tree[0].type=="expr" && 3482 ! this.tree[0].$in_parens && 3483 this.tree[0].tree[0].type=="id"){var js="" 3484 if(this.create_annotations){js+="$locals.__annotations__ = $B.empty_dict();"} 3485 return js+"_b_.dict.$setitem($locals.__annotations__, '"+ 3486 this.tree[0].tree[0].value+"', "+ 3487 this.tree[0].annotation.to_js()+");"}else if(this.tree[0].type=="def"){ 3488 this.js=this.tree[0].annotation.to_js()+";"}else{ 3489 this.js="" 3490 this.tree=[]}}else if(this.tree[0].type !="def"){ 3491 this.tree=[]}}else if(this.tree[0].type=="assign" && 3492 ! this.tree[0].tree[0].$in_parens && 3493 this.tree[0].tree[0].annotation){ 3494 var left=this.tree[0].tree[0],right=this.tree[0].tree[1] 3495 if(this.create_annotations){this.js+="$locals.__annotations__ = $B.empty_dict();"} 3496 this.js+="var $value = "+right.to_js()+";" 3497 this.tree[0].tree.splice(1,1) 3498 new $RawJSCtx(this.tree[0],"$value") 3499 if(left.tree[0]&& left.tree[0].type=="id" && is_not_def){this.js+="_b_.dict.$setitem($locals.__annotations__, '"+ 3500 left.tree[0].value+"', "+ 3501 left.annotation.to_js()+");"}else{ 3502 this.js+=$to_js(this.tree)+";" 3503 if(is_not_def){this.js+=left.annotation.to_js()} 3504 return this.js}}} 3505 if(this.node.children.length==0){this.js+=$to_js(this.tree)+';'}else{this.js+=$to_js(this.tree)} 3506 return this.js} 3507 var $NodeJS=$B.parser.$NodeJS=function(js){var node=new $Node() 3508 new $NodeJSCtx(node,js) 3509 return node} 3510 var $NodeJSCtx=$B.parser.$NodeJSCtx=function(node,js){ 3511 this.node=node 3512 node.C=this 3513 this.type='node_js' 3514 this.tree=[js]} 3515 $NodeJSCtx.prototype.toString=function(){return 'js '+js} 3516 $NodeJSCtx.prototype.to_js=function(){this.js_processed=true 3517 return this.tree[0]} 3518 var $NonlocalCtx=$B.parser.$NonlocalCtx=function(C){ 3519 this.type='nonlocal' 3520 this.parent=C 3521 this.tree=[] 3522 this.names={} 3523 C.tree[C.tree.length]=this 3524 this.expect='id' 3525 this.scope=$get_scope(this) 3526 this.scope.nonlocals=this.scope.nonlocals ||{} 3527 if(this.scope.C===undefined){$_SyntaxError(C,["nonlocal declaration not allowed at module level"])}} 3528 $NonlocalCtx.prototype.toString=function(){return 'nonlocal '+this.tree} 3529 $NonlocalCtx.prototype.add=function(name){if(this.scope.binding[name]=="arg"){$_SyntaxError(C,["name '"+name+"' is parameter and nonlocal"])} 3530 this.names[name]=[false,$pos] 3531 this.scope.nonlocals[name]=true} 3532 $NonlocalCtx.prototype.transition=function(token,value){var C=this 3533 switch(token){case 'id': 3534 if(C.expect=='id'){new $IdCtx(C,value) 3535 C.add(value) 3536 C.expect=',' 3537 return C} 3538 break 3539 case ',': 3540 if(C.expect==','){C.expect='id' 3541 return C} 3542 break 3543 case 'eol': 3544 if(C.expect==','){return $transition(C.parent,token)} 3545 break} 3546 $_SyntaxError(C,'token '+token+' after '+C)} 3547 $NonlocalCtx.prototype.transform=function(node,rank){var C=this.parent,pscope=this.scope.parent_block 3548 if(pscope.C===undefined){$_SyntaxError(C,["no binding for nonlocal '"+ 3549 $B.last(Object.keys(this.names))+"' found"])}else{while(pscope !==undefined && pscope.C !==undefined){for(var name in this.names){if(pscope.binding[name]!==undefined){this.names[name]=[true]}} 3550 pscope=pscope.parent_block} 3551 for(var name in this.names){if(!this.names[name][0]){console.log('nonlocal error, C '+C) 3552 $pos=this.names[name][1] 3553 $_SyntaxError(C,["no binding for nonlocal '"+ 3554 name+"' found"])}}}} 3555 $NonlocalCtx.prototype.to_js=function(){this.js_processed=true 3556 return ''} 3557 var $NotCtx=$B.parser.$NotCtx=function(C){ 3558 this.type='not' 3559 this.parent=C 3560 this.tree=[] 3561 C.tree[C.tree.length]=this} 3562 $NotCtx.prototype.toString=function(){return 'not ('+this.tree+')'} 3563 $NotCtx.prototype.transition=function(token,value){var C=this 3564 switch(token){case 'in': 3565 C.parent.parent.tree.pop() 3566 return new $ExprCtx(new $OpCtx(C.parent,'not_in'),'op',false) 3567 case 'id': 3568 case 'imaginary': 3569 case 'int': 3570 case 'float': 3571 case 'str': 3572 case 'bytes': 3573 case '[': 3574 case '(': 3575 case '{': 3576 case '.': 3577 case 'not': 3578 case 'lambda': 3579 var expr=new $AbstractExprCtx(C,false) 3580 return $transition(expr,token,value) 3581 case 'op': 3582 var a=value 3583 if('+'==a ||'-'==a ||'~'==a){var expr=new $AbstractExprCtx(C,false) 3584 return $transition(expr,token,value)}} 3585 return $transition(C.parent,token)} 3586 $NotCtx.prototype.to_js=function(){this.js_processed=true 3587 return '!$B.$bool('+$to_js(this.tree)+')'} 3588 var $NumberCtx=$B.parser.$NumberCtx=function(type,C,value){ 3589 this.type=type 3590 this.value=value 3591 this.parent=C 3592 this.tree=[] 3593 C.tree[C.tree.length]=this} 3594 $NumberCtx.prototype.toString=function(){return this.type+' '+this.value} 3595 $NumberCtx.prototype.transition=function(token,value){var C=this 3596 switch(token){case 'id': 3597 case 'imaginary': 3598 case 'int': 3599 case 'float': 3600 case 'str': 3601 case 'bytes': 3602 case '[': 3603 case '(': 3604 case '{': 3605 case 'not': 3606 case 'lambda': 3607 $_SyntaxError(C,'token '+token+' after '+ 3608 C)} 3609 return $transition(C.parent,token,value)} 3610 $NumberCtx.prototype.to_js=function(){this.js_processed=true 3611 var type=this.type,value=this.value 3612 if(type=='int'){var v=parseInt(value[1],value[0]) 3613 if(v > $B.min_int && v < $B.max_int){if(this.unary_op){v=eval(this.unary_op+v)} 3614 return v}else{var v=$B.long_int.$factory(value[1],value[0]) 3615 switch(this.unary_op){case "-": 3616 v=$B.long_int.__neg__(v) 3617 break 3618 case "~": 3619 v=$B.long_int.__invert__(v) 3620 break} 3621 return '{__class__: $B.long_int, value: "'+v.value+ 3622 '", pos: '+v.pos+'}'}}else if(type=="float"){ 3623 if(/^\d+$/.exec(value)||/^\d+\.\d*$/.exec(value)){return '(new Number('+this.value+'))'} 3624 return '_b_.float.$factory('+value+')'}else if(type=="imaginary"){return '$B.make_complex(0,'+value+')'}} 3625 var $OpCtx=$B.parser.$OpCtx=function(C,op){ 3626 this.type='op' 3627 this.op=op 3628 this.parent=C.parent 3629 this.tree=[C] 3630 this.scope=$get_scope(this) 3631 if(C.type=="expr"){if(['int','float','str'].indexOf(C.tree[0].type)>-1){this.left_type=C.tree[0].type}else if(C.tree[0].type=="id"){var binding=this.scope.binding[C.tree[0].value] 3632 if(binding){this.left_type=binding.type}}} 3633 C.parent.tree.pop() 3634 C.parent.tree.push(this)} 3635 $OpCtx.prototype.toString=function(){return '(op '+this.op+') ['+this.tree+']'} 3636 $OpCtx.prototype.transition=function(token,value){var C=this 3637 if(C.op===undefined){$_SyntaxError(C,['C op undefined '+C])} 3638 if(C.op.substr(0,5)=='unary'){if(token !='eol'){if(C.parent.type=='assign' || 3639 C.parent.type=='return'){ 3640 C.parent.tree.pop() 3641 var t=new $ListOrTupleCtx(C.parent,'tuple') 3642 t.tree.push(C) 3643 C.parent=t 3644 return t}} 3645 if(C.tree.length==2 && C.tree[1].type=="expr" && 3646 C.tree[1].tree[0].type=="int"){ 3647 C.parent.tree.pop() 3648 C.parent.tree.push(C.tree[1]) 3649 C.tree[1].parent=C.parent 3650 C.tree[1].tree[0].unary_op=C.tree[0].op}} 3651 switch(token){case 'id': 3652 case 'imaginary': 3653 case 'int': 3654 case 'float': 3655 case 'str': 3656 case 'bytes': 3657 case '[': 3658 case '(': 3659 case '{': 3660 case '.': 3661 case 'not': 3662 case 'lambda': 3663 return $transition(new $AbstractExprCtx(C,false),token,value) 3664 case 'op': 3665 switch(value){case '+': 3666 case '-': 3667 case '~': 3668 return new $UnaryCtx(C,value)} 3669 default: 3670 if(C.tree[C.tree.length-1].type== 3671 'abstract_expr'){$_SyntaxError(C,'token '+token+' after '+ 3672 C)}} 3673 return $transition(C.parent,token)} 3674 $OpCtx.prototype.to_js=function(){this.js_processed=true 3675 var comps={'==':'eq','!=':'ne','>=':'ge','<=':'le','<':'lt','>':'gt'} 3676 if(comps[this.op]!==undefined){var method=comps[this.op] 3677 if(this.tree[0].type=='expr' && this.tree[1].type=='expr'){var t0=this.tree[0].tree[0],t1=this.tree[1].tree[0],js0=t0.to_js(),js1=t1.to_js() 3678 switch(t1.type){case 'int': 3679 switch(t0.type){case 'int': 3680 if(Number.isSafeInteger(t0.value)&& 3681 Number.isSafeInteger(t1.value)){return js0+this.op+js1}else{return '$B.$getattr('+ 3682 this.tree[0].to_js()+',"__'+ 3683 method+'__")('+ 3684 this.tree[1].to_js()+')'} 3685 case 'str': 3686 switch(this.op){case "==": 3687 return "false" 3688 case "!=": 3689 return "true" 3690 default: 3691 return '$B.$TypeError("unorderable types: '+ 3692 " int() "+this.op+' str()")'} 3693 case 'id': 3694 return '(typeof '+js0+' == "number" ? '+ 3695 js0+this.op+js1+' : $B.rich_comp("__'+ 3696 method+'__",'+this.tree[0].to_js()+ 3697 ','+this.tree[1].to_js()+'))'} 3698 break; 3699 case 'str': 3700 switch(t0.type){case 'str': 3701 return js0+this.op+js1 3702 case 'int': 3703 switch(this.op){case "==": 3704 return "false" 3705 case "!=": 3706 return "true" 3707 default: 3708 return '$B.$TypeError("unorderable types: '+ 3709 ' str() '+this.op+' int()")'} 3710 case 'id': 3711 return '(typeof '+js0+' == "string" ? '+ 3712 js0+this.op+js1+' : $B.rich_comp("__'+ 3713 method+'__",'+this.tree[0].to_js()+ 3714 ','+this.tree[1].to_js()+'))'} 3715 break; 3716 case 'id': 3717 if(t0.type=='id'){return 'typeof '+js0+'!="object" && typeof '+ 3718 js0+'!="function" && typeof '+js0+ 3719 ' == typeof '+js1+' ? '+js0+this.op+js1+ 3720 ' : $B.rich_comp("__'+method+'__",'+ 3721 this.tree[0].to_js()+','+this.tree[1].to_js()+ 3722 ')'} 3723 break}}} 3724 switch(this.op){case 'and': 3725 var op0=this.tree[0].to_js(),op1=this.tree[1].to_js() 3726 if(this.wrap !==undefined){ 3727 return '(function(){var '+this.wrap.name+' = '+ 3728 this.wrap.js+';return $B.$test_expr($B.$test_item('+ 3729 op0+') && $B.$test_item('+op1+'))})()'}else{return '$B.$test_expr($B.$test_item('+op0+')&&'+ 3730 '$B.$test_item('+op1+'))'} 3731 case 'or': 3732 var res='$B.$test_expr($B.$test_item('+ 3733 this.tree[0].to_js()+')||' 3734 return res+'$B.$test_item('+this.tree[1].to_js()+'))' 3735 case 'in': 3736 return '$B.$is_member('+$to_js(this.tree)+')' 3737 case 'not_in': 3738 return '!$B.$is_member('+$to_js(this.tree)+')' 3739 case 'unary_neg': 3740 case 'unary_pos': 3741 case 'unary_inv': 3742 var op,method 3743 if(this.op=='unary_neg'){op='-';method='__neg__'} 3744 else if(this.op=='unary_pos'){op='+';method='__pos__'} 3745 else{op='~';method='__invert__'} 3746 if(this.tree[1].type=="expr"){var x=this.tree[1].tree[0] 3747 switch(x.type){case 'int': 3748 var v=parseInt(x.value[1],x.value[0]) 3749 if(Number.isSafeInteger(v)){return op+v} 3750 return '$B.$getattr('+x.to_js()+', "'+ 3751 method+'")()' 3752 case 'float': 3753 return '_b_.float.$factory('+op+x.value+')' 3754 case 'imaginary': 3755 return '$B.make_complex(0,'+op+x.value+')'}} 3756 return '$B.$getattr('+this.tree[1].to_js()+',"'+ 3757 method+'")()' 3758 case 'is': 3759 return '$B.$is('+this.tree[0].to_js()+', '+ 3760 this.tree[1].to_js()+')' 3761 case 'is_not': 3762 return this.tree[0].to_js()+'!=='+this.tree[1].to_js() 3763 case '+': 3764 return '$B.add('+this.tree[0].to_js()+', '+ 3765 this.tree[1].to_js()+')' 3766 case '*': 3767 case '-': 3768 var op=this.op,vars=[],has_float_lit=false,scope=$get_scope(this) 3769 function is_simple(elt){if(elt.type=='expr' && elt.tree[0].type=='int'){return true}else if(elt.type=='expr' && 3770 elt.tree[0].type=='float'){has_float_lit=true 3771 return true}else if(elt.type=='expr' && 3772 elt.tree[0].type=='list_or_tuple' && 3773 elt.tree[0].real=='tuple' && 3774 elt.tree[0].tree.length==1 && 3775 elt.tree[0].tree[0].type=='expr'){return is_simple(elt.tree[0].tree[0].tree[0])}else if(elt.type=='expr' && elt.tree[0].type=='id'){var _var=elt.tree[0].to_js() 3776 if(vars.indexOf(_var)==-1){vars.push(_var)} 3777 return true}else if(elt.type=='op' && 3778 ['*','+','-'].indexOf(elt.op)>-1){for(var i=0;i < elt.tree.length;i++){if(!is_simple(elt.tree[i])){return false}} 3779 return true} 3780 return false} 3781 function get_type(ns,v){var t 3782 if(['int','float','str'].indexOf(v.type)>-1){t=v.type}else if(v.type=='id' && ns[v.value]){t=ns[v.value].type} 3783 return t} 3784 var e0=this.tree[0],e1=this.tree[1] 3785 if(is_simple(this)){var v0=this.tree[0].tree[0],v1=this.tree[1].tree[0] 3786 if(vars.length==0 && !has_float_lit){ 3787 return this.simple_js()}else if(vars.length==0){ 3788 return 'new Number('+this.simple_js()+')'}else{ 3789 var ns=scope.binding,t0=get_type(ns,v0),t1=get_type(ns,v1) 3790 if((t0=='float' && t1=='float')|| 3791 (this.op=='+' && t0=='str' && t1=='str')){this.result_type=t0 3792 return v0.to_js()+this.op+v1.to_js()}else if(['int','float'].indexOf(t0)>-1 && 3793 ['int','float'].indexOf(t1)>-1){if(t0=='int' && t1=='int'){this.result_type='int'}else{this.result_type='float'} 3794 switch(this.op){case '-': 3795 return '$B.sub('+v0.to_js()+','+ 3796 v1.to_js()+')' 3797 case '*': 3798 return '$B.mul('+v0.to_js()+','+ 3799 v1.to_js()+')'}} 3800 var tests=[],tests1=[],pos=0 3801 vars.forEach(function(_var){ 3802 tests.push('typeof '+_var+ 3803 '.valueOf() == "number"') 3804 tests1.push('typeof '+_var+' == "number"')}) 3805 var res=[tests.join(' && ')+' ? '] 3806 res.push('('+tests1.join(' && ')+' ? ') 3807 res.push(this.simple_js()) 3808 res.push(' : new Number('+this.simple_js()+')') 3809 res.push(')') 3810 var t0=this.tree[0].to_js(),t1=this.tree[1].to_js() 3811 if(this.op=='+'){res.push(' : (typeof '+t0+ 3812 ' == "string" && typeof '+t1+ 3813 ' == "string") ? '+t0+'+'+t1)} 3814 res.push(': $B.rich_op("'+$operators[this.op]+'",'+ 3815 t0+','+t1+')') 3816 return '('+res.join('')+')'}} 3817 if(comps[this.op]!==undefined){return '$B.rich_comp("__'+$operators[this.op]+'__",'+ 3818 e0.to_js()+','+e1.to_js()+')'}else{return '$B.rich_op("'+$operators[this.op]+'", '+ 3819 e0.to_js()+', '+e1.to_js()+')'} 3820 default: 3821 if(comps[this.op]!==undefined){return '$B.rich_comp("__'+$operators[this.op]+'__",'+ 3822 this.tree[0].to_js()+','+this.tree[1].to_js()+')'}else{return '$B.rich_op("'+$operators[this.op]+'", '+ 3823 this.tree[0].to_js()+', '+this.tree[1].to_js()+ 3824 ')'}}} 3825 $OpCtx.prototype.simple_js=function(){var op=this.op 3826 function sjs(elt){if(elt.type=='op'){return elt.simple_js()}else if(elt.type=='expr' && elt.tree[0].type=='list_or_tuple' 3827 && elt.tree[0].real=='tuple' 3828 && elt.tree[0].tree.length==1 3829 && elt.tree[0].tree[0].type=='expr'){return '('+elt.tree[0].tree[0].tree[0].simple_js()+')'}else{return elt.tree[0].to_js()}} 3830 if(op=='+'){return '$B.add('+sjs(this.tree[0])+','+ 3831 sjs(this.tree[1])+')'}else if(op=='-'){return '$B.sub('+sjs(this.tree[0])+','+ 3832 sjs(this.tree[1])+')'}else if(op=='*'){return '$B.mul('+sjs(this.tree[0])+','+ 3833 sjs(this.tree[1])+')'}else if(op=='/'){return '$B.div('+sjs(this.tree[0])+','+ 3834 sjs(this.tree[1])+')'}else{return sjs(this.tree[0])+op+sjs(this.tree[1])}} 3835 var $PackedCtx=$B.parser.$PackedCtx=function(C){ 3836 this.type='packed' 3837 if(C.parent.type=='list_or_tuple' && 3838 C.parent.parent.type=="node"){ 3839 for(var i=0;i < C.parent.tree.length;i++){var child=C.parent.tree[i] 3840 if(child.type=='expr' && child.tree.length > 0 3841 && child.tree[0].type=='packed'){$_SyntaxError(C,["two starred expressions in assignment"])}}} 3842 this.parent=C 3843 this.tree=[] 3844 C.tree[C.tree.length]=this} 3845 $PackedCtx.prototype.toString=function(){return '(packed) '+this.tree} 3846 $PackedCtx.prototype.transition=function(token,value){var C=this 3847 if(C.tree.length > 0 && token=="["){ 3848 return $transition(C.tree[0],token,value)} 3849 if(token=='id'){var expr=new $AbstractExprCtx(C,false) 3850 expr.packed=true 3851 C.parent.expect=',' 3852 var id=$transition(expr,token,value) 3853 return id}else if(token=="["){C.parent.expect=',' 3854 return new $ListOrTupleCtx(C,"list")}else if(token=="("){C.parent.expect=',' 3855 return new $ListOrTupleCtx(C,"tuple")}else if(token=="]"){return $transition(C.parent,token,value)}else if(token=="{"){C.parent.expect=',' 3856 return new $DictOrSetCtx(C)} 3857 return C.parent.transition(token,C)} 3858 $PackedCtx.prototype.to_js=function(){this.js_processed=true 3859 return $to_js(this.tree)} 3860 var $PassCtx=$B.parser.$PassCtx=function(C){ 3861 this.type='pass' 3862 this.parent=C 3863 this.tree=[] 3864 C.tree[C.tree.length]=this} 3865 $PassCtx.prototype.toString=function(){return '(pass)'} 3866 $PassCtx.prototype.transition=function(token,value){var C=this 3867 if(token=='eol'){return C.parent} 3868 $_SyntaxError(C,'token '+token+' after '+C)} 3869 $PassCtx.prototype.to_js=function(){this.js_processed=true 3870 return 'void(0)'} 3871 var $RaiseCtx=$B.parser.$RaiseCtx=function(C){ 3872 this.type='raise' 3873 this.parent=C 3874 this.tree=[] 3875 C.tree[C.tree.length]=this 3876 this.scope_type=$get_scope(this).ntype} 3877 $RaiseCtx.prototype.toString=function(){return ' (raise) '+this.tree} 3878 $RaiseCtx.prototype.transition=function(token,value){var C=this 3879 switch(token){case 'id': 3880 if(C.tree.length==0){return new $IdCtx(new $ExprCtx(C,'exc',false),value)} 3881 break 3882 case 'from': 3883 if(C.tree.length > 0){return new $AbstractExprCtx(C,false)} 3884 break 3885 case 'eol': 3886 return $transition(C.parent,token)} 3887 $_SyntaxError(C,'token '+token+' after '+C)} 3888 $RaiseCtx.prototype.to_js=function(){this.js_processed=true 3889 var exc=this.tree.length==0 ? '' :this.tree[0].to_js() 3890 return '$B.$raise('+exc+')'} 3891 var $RawJSCtx=$B.parser.$RawJSCtx=function(C,js){this.type="raw_js" 3892 C.tree[C.tree.length]=this 3893 this.parent=C 3894 this.js=js} 3895 $RawJSCtx.prototype.toString=function(){return '(js) '+this.js} 3896 $RawJSCtx.prototype.transition=function(token,value){var C=this} 3897 $RawJSCtx.prototype.to_js=function(){this.js_processed=true 3898 return this.js} 3899 var $ReturnCtx=$B.parser.$ReturnCtx=function(C){ 3900 this.type='return' 3901 this.parent=C 3902 this.tree=[] 3903 C.tree[C.tree.length]=this 3904 this.scope=$get_scope(this) 3905 if(["def","generator"].indexOf(this.scope.ntype)==-1){$_SyntaxError(C,["'return' outside function"])} 3906 var node=this.node=$get_node(this) 3907 while(node.parent){if(node.parent.C){var elt=node.parent.C.tree[0] 3908 if(elt.type=='for'){elt.has_return=true 3909 break}else if(elt.type=='try'){elt.has_return=true}else if(elt.type=='single_kw' && elt.token=='finally'){elt.has_return=true}} 3910 node=node.parent}} 3911 $ReturnCtx.prototype.toString=function(){return 'return '+this.tree} 3912 $ReturnCtx.prototype.transition=function(token,value){var C=this 3913 return $transition(C.parent,token)} 3914 $ReturnCtx.prototype.to_js=function(){this.js_processed=true 3915 if(this.tree.length==1 && this.tree[0].type=='abstract_expr'){ 3916 this.tree.pop() 3917 new $IdCtx(new $ExprCtx(this,'rvalue',false),'None')} 3918 var scope=this.scope 3919 if(scope.ntype=='generator'){return 'var $res = '+$to_js(this.tree)+'; $B.leave_frame({$locals});'+ 3920 'return $B.generator_return($res)'} 3921 var indent=' '.repeat(this.node.indent-1) 3922 var js='var $res = '+$to_js(this.tree)+';\n'+indent+ 3923 'if($locals.$f_trace !== _b_.None){$B.trace_return($res)}\n'+indent+ 3924 '$B.leave_frame' 3925 if(scope.id.substr(0,6)=='$exec_'){js+='_exec'} 3926 js+='({$locals});\n'+indent+'return $res' 3927 return js} 3928 var $SingleKwCtx=$B.parser.$SingleKwCtx=function(C,token){ 3929 this.type='single_kw' 3930 this.token=token 3931 this.parent=C 3932 this.tree=[] 3933 C.tree[C.tree.length]=this 3934 if(token=="else"){var node=C.node 3935 var pnode=node.parent 3936 for(var rank=0;rank < pnode.children.length;rank++){if(pnode.children[rank]===node){break}} 3937 var pctx=pnode.children[rank-1].C 3938 if(pctx.tree.length > 0){var elt=pctx.tree[0] 3939 if(elt.type=='for' || 3940 elt.type=='asyncfor' || 3941 (elt.type=='condition' && elt.token=='while')){elt.has_break=true 3942 elt.else_node=$get_node(this) 3943 this.loop_num=elt.loop_num}}}} 3944 $SingleKwCtx.prototype.toString=function(){return this.token} 3945 $SingleKwCtx.prototype.transition=function(token,value){var C=this 3946 if(token==':'){return $BodyCtx(C)} 3947 $_SyntaxError(C,'token '+token+' after '+C)} 3948 $SingleKwCtx.prototype.transform=function(node,rank){ 3949 if(this.token=='finally'){var scope=$get_scope(this) 3950 node.insert(0,$NodeJS('var $exit;'+ 3951 'if($B.frames_stack.length < $stack_length){'+ 3952 '$exit = true;'+ 3953 '$B.frames_stack.push($top_frame)'+ 3954 '}') 3955 ) 3956 var scope_id=scope.id.replace(/\./g,'_') 3957 var last_child=node.children[node.children.length-1] 3958 if(last_child.C.tree[0].type !="return"){node.add($NodeJS('if($exit){$B.leave_frame({$locals})}'))}}} 3959 $SingleKwCtx.prototype.to_js=function(){this.js_processed=true 3960 if(this.token=='finally'){return this.token} 3961 if(this.loop_num !==undefined){var scope=$get_scope(this) 3962 var res='if($locals_'+scope.id.replace(/\./g,'_') 3963 return res+'["$no_break'+this.loop_num+'"])'} 3964 return this.token} 3965 var $SliceCtx=$B.parser.$SliceCtx=function(C){ 3966 this.type='slice' 3967 this.parent=C 3968 this.tree=C.tree.length > 0 ?[C.tree.pop()]:[] 3969 C.tree.push(this)} 3970 $SliceCtx.prototype.transition=function(token,value){var C=this 3971 if(token==":"){return new $AbstractExprCtx(C,false)} 3972 return $transition(C.parent,token,value)} 3973 $SliceCtx.prototype.to_js=function(){for(var i=0;i < this.tree.length;i++){if(this.tree[i].type=="abstract_expr"){this.tree[i].to_js=function(){return "_b_.None"}}} 3974 return "_b_.slice.$factory("+$to_js(this.tree)+")"} 3975 var $StarArgCtx=$B.parser.$StarArgCtx=function(C){ 3976 this.type='star_arg' 3977 this.parent=C 3978 this.tree=[] 3979 C.tree[C.tree.length]=this} 3980 $StarArgCtx.prototype.toString=function(){return '(star arg) '+this.tree} 3981 $StarArgCtx.prototype.transition=function(token,value){var C=this 3982 switch(token){case 'id': 3983 if(C.parent.type=="target_list"){C.tree.push(value) 3984 C.parent.expect=',' 3985 return C.parent} 3986 return $transition(new $AbstractExprCtx(C,false),token,value) 3987 case 'imaginary': 3988 case 'int': 3989 case 'float': 3990 case 'str': 3991 case 'bytes': 3992 case '[': 3993 case '(': 3994 case '{': 3995 case 'not': 3996 case 'lambda': 3997 return $transition(new $AbstractExprCtx(C,false),token,value) 3998 case ',': 3999 case ')': 4000 if(C.tree.length==0){$_SyntaxError(C,"unnamed star argument")} 4001 return $transition(C.parent,token) 4002 case ':': 4003 if(C.parent.parent.type=='lambda'){return $transition(C.parent.parent,token)}} 4004 $_SyntaxError(C,'token '+token+' after '+C)} 4005 $StarArgCtx.prototype.to_js=function(){this.js_processed=true 4006 return '{$nat:"ptuple",arg:'+$to_js(this.tree)+'}'} 4007 var $StringCtx=$B.parser.$StringCtx=function(C,value){ 4008 this.type='str' 4009 this.parent=C 4010 this.tree=[value] 4011 C.tree[C.tree.length]=this 4012 this.raw=false} 4013 $StringCtx.prototype.toString=function(){return 'string '+(this.tree ||'')} 4014 $StringCtx.prototype.transition=function(token,value){var C=this 4015 switch(token){case '[': 4016 return new $AbstractExprCtx(new $SubCtx(C.parent),false) 4017 case '(': 4018 C.parent.tree[0]=C 4019 return new $CallCtx(C.parent) 4020 case 'str': 4021 C.tree.push(value) 4022 return C} 4023 return $transition(C.parent,token,value)} 4024 $StringCtx.prototype.to_js=function(){this.js_processed=true 4025 var res='',type=null,scope=$get_scope(this),has_surrogate=false 4026 function _has_surrogate(s){for(var i=0;i < s.length;i++){try{code=s.charCodeAt(i)}catch(err){console.log("err for s",s) 4027 throw err} 4028 if(code >=0xD800 && code <=0xDBFF){return true}} 4029 return false} 4030 function fstring(parsed_fstring){ 4031 var elts=[] 4032 for(var i=0;i < parsed_fstring.length;i++){if(parsed_fstring[i].type=='expression'){var expr=parsed_fstring[i].expression 4033 var pos=0,br_stack=[],parts=[expr] 4034 while(pos < expr.length){var car=expr.charAt(pos) 4035 if(car==":" && br_stack.length==0){parts=[expr.substr(0,pos),expr.substr(pos+1)] 4036 break}else if("{[(".indexOf(car)>-1){br_stack.push(car)}else if(")]}".indexOf(car)>-1){br_stack.pop()} 4037 pos++} 4038 expr=parts[0] 4039 var save_pos=$pos 4040 var expr_node=$B.py2js(expr,scope.module,scope.id,scope) 4041 expr_node.to_js() 4042 $pos=save_pos 4043 for(var j=0;j < expr_node.children.length;j++){var node=expr_node.children[j] 4044 if(node.C.tree && node.C.tree.length==1 && 4045 node.C.tree[0]=="try"){ 4046 for(var k=0;k < node.children.length;k++){ 4047 if(node.children[k].is_line_num){continue} 4048 var expr1=node.children[k].js 4049 while("\n;".indexOf(expr1.charAt(expr1.length-1))>-1){expr1=expr1.substr(0,expr1.length-1)} 4050 break} 4051 break}} 4052 switch(parsed_fstring[i].conversion){case "a": 4053 expr1='_b_.ascii('+expr1+')' 4054 break 4055 case "r": 4056 expr1='_b_.repr('+expr1+')' 4057 break 4058 case "s": 4059 expr1='_b_.str.$factory('+expr1+')' 4060 break} 4061 var fmt=parts[1] 4062 if(fmt !==undefined){ 4063 var parsed_fmt=$B.parse_fstring(fmt) 4064 if(parsed_fmt.length > 1){fmt=fstring(parsed_fmt)}else{fmt="'"+fmt+"'"} 4065 var res1="_b_.str.format('{0:' + "+ 4066 fmt+" + '}', "+expr1+")" 4067 elts.push(res1)}else{if(parsed_fstring[i].conversion===null){expr1='_b_.str.$factory('+expr1+')'} 4068 elts.push(expr1)}}else{var re=new RegExp("'","g") 4069 var elt=parsed_fstring[i].replace(re,"\\'") 4070 .replace(/\n/g,"\\n") 4071 has_surrogate=has_surrogate ||_has_surrogate(elt) 4072 elts.push("'"+elt+"'")}} 4073 return elts.join(' + ')} 4074 function prepare(value){value=value.replace(/\n/g,'\\n\\\n') 4075 value=value.replace(/\\U([A-Fa-f0-9]{8})/gm,function(mo){return String.fromCharCode("0x"+mo.slice(2))}) 4076 return value} 4077 for(var i=0;i < this.tree.length;i++){if(this.tree[i].type=="call"){ 4078 var js='(function(){throw _b_.TypeError.$factory("'+"'str'"+ 4079 ' object is not callable")}())' 4080 return js}else{var value=this.tree[i],is_fstring=Array.isArray(value),is_bytes=false 4081 if(!is_fstring){is_bytes=value.charAt(0)=='b'} 4082 if(type==null){type=is_bytes 4083 if(is_bytes){res+='_b_.bytes.$new(_b_.bytes, '}}else if(type !=is_bytes){return '$B.$TypeError("can\'t concat bytes to str")'} 4084 if(!is_bytes){if(is_fstring){res+=fstring(value)}else{has_surrogate=has_surrogate ||_has_surrogate(value) 4085 res+=prepare(value)}}else{res+=prepare(value.substr(1))} 4086 if(i < this.tree.length-1){res+='+'}}} 4087 if(is_bytes){res+=',"ISO-8859-1")'} 4088 if(res.length==0){res='""'} 4089 if(has_surrogate){res="_b_.str.$surrogate.$factory("+res+")"} 4090 return res} 4091 var $SubCtx=$B.parser.$SubCtx=function(C){ 4092 this.type='sub' 4093 this.func='getitem' 4094 this.value=C.tree[0] 4095 C.tree.pop() 4096 C.tree[C.tree.length]=this 4097 this.parent=C 4098 this.tree=[]} 4099 $SubCtx.prototype.toString=function(){return '(sub) (value) '+this.value+' (tree) '+this.tree} 4100 $SubCtx.prototype.transition=function(token,value){var C=this 4101 switch(token){case 'id': 4102 case 'imaginary': 4103 case 'int': 4104 case 'float': 4105 case 'str': 4106 case 'bytes': 4107 case '[': 4108 case '(': 4109 case '{': 4110 case '.': 4111 case 'not': 4112 case 'lambda': 4113 var expr=new $AbstractExprCtx(C,false) 4114 return $transition(expr,token,value) 4115 case ']': 4116 if(C.parent.packed){return C.parent.tree[0]} 4117 if(C.tree[0].tree.length > 0){return C.parent} 4118 break 4119 case ':': 4120 return new $AbstractExprCtx(new $SliceCtx(C),false) 4121 case ',': 4122 return new $AbstractExprCtx(C,false)} 4123 $_SyntaxError(C,'token '+token+' after '+C)} 4124 $SubCtx.prototype.to_js=function(){this.js_processed=true 4125 if(this.func=='getitem' && this.value.type=='id'){var type=$get_node(this).locals[this.value.value],val=this.value.to_js() 4126 if(type=='list' ||type=='tuple'){if(this.tree.length==1){return '$B.list_key('+val+ 4127 ', '+this.tree[0].to_js()+')'}else if(this.tree.length==2){return '$B.list_slice('+val+ 4128 ', '+(this.tree[0].to_js()||"null")+','+ 4129 (this.tree[1].to_js()||"null")+')'}else if(this.tree.length==3){return '$B.list_slice_step('+val+ 4130 ', '+(this.tree[0].to_js()||"null")+','+ 4131 (this.tree[1].to_js()||"null")+','+ 4132 (this.tree[2].to_js()||"null")+')'}}} 4133 if(this.func=='getitem' && this.tree.length==1){if(this.tree[0].type=="slice"){return `$B.getitem_slice(${this.value.to_js()},`+ 4134 `${this.tree[0].to_js()})`} 4135 return '$B.$getitem('+this.value.to_js()+','+ 4136 this.tree[0].to_js()+')'} 4137 var res='',shortcut=false 4138 if(this.func !=='delitem' && 4139 this.tree.length==1 && !this.in_sub){var expr='',x=this 4140 shortcut=true 4141 while(x.value.type=='sub'){expr+='['+x.tree[0].to_js()+']' 4142 x.value.in_sub=true 4143 x=x.value} 4144 var subs=x.value.to_js()+'['+x.tree[0].to_js()+']'+ 4145 '((Array.isArray('+x.value.to_js()+') || typeof '+ 4146 x.value.to_js()+' == "string") && '+subs+ 4147 ' !== undefined ?'+subs+expr+' : '} 4148 var val=this.value.to_js() 4149 res+='$B.$getattr('+val+',"__'+this.func+'__")(' 4150 if(this.tree.length==1){res+=this.tree[0].to_js()+')'}else{var res1=[] 4151 this.tree.forEach(function(elt){if(elt.type=='abstract_expr'){res1.push('_b_.None')} 4152 else{res1.push(elt.to_js())}}) 4153 res+='_b_.tuple.$factory(['+res1.join(',')+']))'} 4154 return shortcut ? res+')' :res} 4155 var $TargetListCtx=$B.parser.$TargetListCtx=function(C){ 4156 this.type='target_list' 4157 this.parent=C 4158 this.tree=[] 4159 this.expect='id' 4160 C.tree[C.tree.length]=this} 4161 $TargetListCtx.prototype.toString=function(){return '(target list) '+this.tree} 4162 $TargetListCtx.prototype.transition=function(token,value){var C=this 4163 switch(token){case 'id': 4164 if(C.expect=='id'){C.expect=',' 4165 return new $IdCtx( 4166 new $ExprCtx(C,'target',false),value)} 4167 case 'op': 4168 if(C.expect=='id' && value=='*'){ 4169 return new $PackedCtx(C)} 4170 case '(': 4171 case '[': 4172 if(C.expect=='id'){C.expect=',' 4173 return new $ListOrTupleCtx(C,token=='(' ? 'tuple' :'list')} 4174 case ')': 4175 case ']': 4176 if(C.expect==','){return C.parent} 4177 case ',': 4178 if(C.expect==','){C.expect='id' 4179 return C}} 4180 if(C.expect==','){return $transition(C.parent,token,value)}else if(token=='in'){ 4181 return $transition(C.parent,token,value)} 4182 $_SyntaxError(C,'token '+token+' after '+C)} 4183 $TargetListCtx.prototype.to_js=function(){this.js_processed=true 4184 return $to_js(this.tree)} 4185 var $TernaryCtx=$B.parser.$TernaryCtx=function(C){ 4186 this.type='ternary' 4187 this.parent=C.parent 4188 C.parent.tree.pop() 4189 C.parent.tree.push(this) 4190 C.parent=this 4191 this.tree=[C]} 4192 $TernaryCtx.prototype.toString=function(){return '(ternary) '+this.tree} 4193 $TernaryCtx.prototype.transition=function(token,value){var C=this 4194 if(token=='else'){C.in_else=true 4195 return new $AbstractExprCtx(C,false)}else if(! C.in_else){$_SyntaxError(C,'token '+token+' after '+C)}else if(token==","){ 4196 if(["assign","augm_assign","node","return"]. 4197 indexOf(C.parent.type)>-1){C.parent.tree.pop() 4198 var t=new $ListOrTupleCtx(C.parent,'tuple') 4199 t.implicit=true 4200 t.tree[0]=C 4201 C.parent=t 4202 t.expect="id" 4203 return t}} 4204 return $transition(C.parent,token,value)} 4205 $TernaryCtx.prototype.to_js=function(){this.js_processed=true 4206 var res='$B.$bool('+this.tree[1].to_js()+') ? ' 4207 res+=this.tree[0].to_js()+' : ' 4208 return res+this.tree[2].to_js()} 4209 var $TryCtx=$B.parser.$TryCtx=function(C){ 4210 this.type='try' 4211 this.parent=C 4212 C.tree[C.tree.length]=this} 4213 $TryCtx.prototype.toString=function(){return '(try) '} 4214 $TryCtx.prototype.transition=function(token,value){var C=this 4215 if(token==':'){return $BodyCtx(C)} 4216 $_SyntaxError(C,'token '+token+' after '+C)} 4217 $TryCtx.prototype.transform=function(node,rank){if(node.parent.children.length==rank+1){$_SyntaxError(C,["unexpected EOF while parsing"])}else{var next_ctx=node.parent.children[rank+1].C.tree[0] 4218 switch(next_ctx.type){case 'except': 4219 case 'finally': 4220 case 'single_kw': 4221 break 4222 default: 4223 $_SyntaxError(C,"no clause after try")}} 4224 var scope=$get_scope(this) 4225 var error_name=create_temp_name('$err') 4226 var failed_name="$locals."+create_temp_name('$failed') 4227 var js=failed_name+' = false;\n'+ 4228 ' '.repeat(node.indent+4)+'try' 4229 new $NodeJSCtx(node,js) 4230 node.has_return=this.has_return 4231 var catch_node=$NodeJS('catch('+error_name+')') 4232 node.parent.insert(rank+1,catch_node) 4233 catch_node.add($NodeJS("$B.set_exc("+error_name+")")) 4234 catch_node.add($NodeJS("if($locals.$f_trace !== _b_.None)"+ 4235 "{$locals.$f_trace = $B.trace_exception()}")) 4236 catch_node.add( 4237 $NodeJS(failed_name+' = true;'+ 4238 '$B.pmframe = $B.last($B.frames_stack);'+ 4239 'if(false){}') 4240 ) 4241 var pos=rank+2,has_default=false, 4242 has_else=false, 4243 has_finally=false 4244 while(1){if(pos==node.parent.children.length){break} 4245 var ctx=node.parent.children[pos].C.tree[0] 4246 if(ctx===undefined){ 4247 break} 4248 if(ctx.type=='except'){ 4249 if(has_else){$_SyntaxError(C,"'except' or 'finally' after 'else'")} 4250 if(has_finally){$_SyntaxError(C,"'except' after 'finally'")} 4251 ctx.error_name=error_name 4252 if(ctx.tree.length > 0 && ctx.tree[0].alias !==null 4253 && ctx.tree[0].alias !==undefined){ 4254 var alias=ctx.tree[0].alias 4255 node.parent.children[pos].insert(0,$NodeJS('$locals["'+alias+'"] = $B.exception('+ 4256 error_name+')') 4257 )} 4258 catch_node.insert(catch_node.children.length,node.parent.children[pos]) 4259 if(ctx.tree.length==0){if(has_default){$_SyntaxError(C,'more than one except: line')} 4260 has_default=true} 4261 node.parent.children.splice(pos,1)}else if(ctx.type=='single_kw' && ctx.token=='finally'){has_finally=true 4262 var finally_node=node.parent.children[pos] 4263 pos++}else if(ctx.type=='single_kw' && ctx.token=='else'){if(has_else){$_SyntaxError(C,"more than one 'else'")} 4264 if(has_finally){$_SyntaxError(C,"'else' after 'finally'")} 4265 has_else=true 4266 var else_body=node.parent.children[pos] 4267 node.parent.children.splice(pos,1)}else{break}} 4268 if(!has_default){ 4269 var new_node=new $Node(),ctx=new $NodeCtx(new_node) 4270 catch_node.insert(catch_node.children.length,new_node) 4271 new $SingleKwCtx(ctx,'else') 4272 new_node.add($NodeJS('throw '+error_name))} 4273 if(has_else){var else_node=new $Node() 4274 else_node.module=scope.module 4275 new $NodeJSCtx(else_node,'if(!'+failed_name+')') 4276 else_body.children.forEach(function(elt){else_node.add(elt)}) 4277 if(has_finally){finally_node.insert(0,else_node)}else{node.parent.insert(pos,else_node)} 4278 pos++} 4279 $loop_num++} 4280 $TryCtx.prototype.to_js=function(){this.js_processed=true 4281 return 'try'} 4282 var $UnaryCtx=$B.parser.$UnaryCtx=function(C,op){ 4283 this.type='unary' 4284 this.op=op 4285 this.parent=C 4286 C.tree[C.tree.length]=this} 4287 $UnaryCtx.prototype.toString=function(){return '(unary) '+this.op} 4288 $UnaryCtx.prototype.transition=function(token,value){var C=this 4289 switch(token){case 'int': 4290 case 'float': 4291 case 'imaginary': 4292 var expr=C.parent 4293 C.parent.parent.tree.pop() 4294 if(C.op=='-'){value="-"+value} 4295 else if(C.op=='~'){value=~value} 4296 return $transition(C.parent.parent,token,value) 4297 case 'id': 4298 C.parent.parent.tree.pop() 4299 var expr=new $ExprCtx(C.parent.parent,'call',false) 4300 var expr1=new $ExprCtx(expr,'id',false) 4301 new $IdCtx(expr1,value) 4302 var repl=new $AttrCtx(expr) 4303 if(C.op=='+'){repl.name='__pos__'} 4304 else if(C.op=='-'){repl.name='__neg__'} 4305 else{repl.name='__invert__'} 4306 return expr1 4307 case 'op': 4308 if('+'==value ||'-'==value){if(C.op===value){C.op='+'} 4309 else{C.op='-'} 4310 return C}} 4311 return $transition(C.parent,token,value)} 4312 this.to_js=function(){this.js_processed=true 4313 return this.op} 4314 var $WithCtx=$B.parser.$WithCtx=function(C){ 4315 this.type='with' 4316 this.parent=C 4317 C.tree[C.tree.length]=this 4318 this.tree=[] 4319 this.expect='as' 4320 this.scope=$get_scope(this)} 4321 $WithCtx.prototype.toString=function(){return '(with) '+this.tree} 4322 $WithCtx.prototype.transition=function(token,value){var C=this 4323 switch(token){case 'id': 4324 if(C.expect=='id'){C.expect='as' 4325 return $transition( 4326 new $AbstractExprCtx(C,false),token,value)} 4327 $_SyntaxError(C,'token '+token+' after '+C) 4328 case 'as': 4329 return new $AbstractExprCtx(new $AliasCtx(C)) 4330 case ':': 4331 switch(C.expect){case 'id': 4332 case 'as': 4333 case ':': 4334 return $BodyCtx(C)} 4335 break 4336 case '(': 4337 if(C.expect=='id' && C.tree.length==0){C.parenth=true 4338 return C}else if(C.expect=='alias'){C.expect=':' 4339 return new $TargetListCtx(C,false)} 4340 break 4341 case ')': 4342 if(C.expect==',' ||C.expect=='as'){C.expect=':' 4343 return C} 4344 break 4345 case ',': 4346 if(C.parenth !==undefined && 4347 C.has_alias===undefined && 4348 (C.expect==',' ||C.expect=='as')){C.expect='id' 4349 return C}else if(C.expect=='as'){C.expect='id' 4350 return C}else if(C.expect==':'){C.expect='id' 4351 return C} 4352 break} 4353 $_SyntaxError(C,'token '+token+' after '+ 4354 C.expect)} 4355 $WithCtx.prototype.set_alias=function(ctx){var ids=[] 4356 if(ctx.type=="id"){ids=[ctx]}else if(ctx.type=="list_or_tuple"){ 4357 ctx.tree.forEach(function(expr){if(expr.type=="expr" && expr.tree[0].type=="id"){ids.push(expr.tree[0])}})} 4358 for(var i=0,len=ids.length;i < len;i++){var id_ctx=ids[i] 4359 $bind(id_ctx.value,this.scope,this) 4360 id_ctx.bound=true 4361 if(this.scope.ntype !=='module'){ 4362 this.scope.C.tree[0].locals.push(id_ctx.value)}}} 4363 $WithCtx.prototype.transform=function(node,rank){while(this.tree.length > 1){ 4364 var suite=node.children,item=this.tree.pop(),new_node=new $Node(),ctx=new $NodeCtx(new_node),with_ctx=new $WithCtx(ctx) 4365 item.parent=with_ctx 4366 with_ctx.tree=[item] 4367 with_ctx.async=this.async 4368 suite.forEach(function(elt){new_node.add(elt)}) 4369 node.children=[new_node]} 4370 if(this.transformed){return} 4371 this.prefix="" 4372 if(this.tree.length > 1){var nw=new $Node(),ctx=new $NodeCtx(nw) 4373 nw.parent=node 4374 nw.module=node.module 4375 nw.indent=node.indent+4 4376 var wc=new $WithCtx(ctx) 4377 wc.async=this.async 4378 wc.tree=this.tree.slice(1) 4379 node.children.forEach(function(elt){nw.add(elt)}) 4380 node.children=[nw] 4381 this.transformed=true 4382 return} 4383 if(this.async){return this.transform_async(node,rank)} 4384 var top_try_node=$NodeJS("try") 4385 node.parent.insert(rank+1,top_try_node) 4386 var num=this.num=$loop_num++ 4387 top_try_node.ctx_manager_num=num 4388 this.cm_name=this.prefix+'$ctx_manager'+num 4389 this.cmexit_name=this.prefix+'$ctx_manager_exit'+num 4390 this.exc_name=this.prefix+'$exc'+num 4391 this.err_name='$err'+num 4392 this.val_name='$value'+num 4393 this.yield_name=this.prefix+'$yield'+num 4394 if(this.tree[0].alias===null){this.tree[0].alias='$temp'} 4395 if(this.tree[0].type=='expr' && 4396 this.tree[0].tree[0].type=='list_or_tuple'){if(this.tree[1].type !='expr' || 4397 this.tree[1].tree[0].type !='list_or_tuple'){$_SyntaxError(C)} 4398 if(this.tree[0].tree[0].tree.length != 4399 this.tree[1].tree[0].tree.length){$_SyntaxError(C,['wrong number of alias'])} 4400 var ids=this.tree[0].tree[0].tree,alias=this.tree[1].tree[0].tree 4401 this.tree.shift() 4402 this.tree.shift() 4403 for(var i=ids.length-1;i >=0;i--){ids[i].alias=alias[i].value 4404 this.tree.splice(0,0,ids[i])}} 4405 var block=node.children 4406 node.children=[] 4407 var try_node=new $Node() 4408 new $NodeJSCtx(try_node,'try') 4409 top_try_node.add(try_node) 4410 if(this.tree[0].alias){var alias=this.tree[0].alias.tree[0].tree[0].value 4411 try_node.add($NodeJS('$locals'+'["'+alias+'"] = '+ 4412 this.val_name))} 4413 block.forEach(function(elt){try_node.add(elt)}) 4414 var catch_node=new $Node() 4415 new $NodeJSCtx(catch_node,'catch('+this.err_name+')') 4416 var js=this.exc_name+' = false;'+this.err_name+ 4417 ' = $B.exception('+this.err_name+', true)\n'+ 4418 ' '.repeat(node.indent+4)+ 4419 'var $b = '+this.cmexit_name+'('+ 4420 this.err_name+'.__class__,'+ 4421 this.err_name+','+ 4422 '$B.$getattr('+this.err_name+', "__traceback__"));' 4423 if(this.scope.ntype=="generator"){js+='$B.set_cm_in_generator('+this.cmexit_name+');'} 4424 js+='if(!$B.$bool($b)){throw '+this.err_name+'}' 4425 catch_node.add($NodeJS(js)) 4426 top_try_node.add(catch_node) 4427 var finally_node=new $Node() 4428 new $NodeJSCtx(finally_node,'finally') 4429 finally_node.C.type='single_kw' 4430 finally_node.C.token='finally' 4431 finally_node.C.in_ctx_manager=true 4432 finally_node.is_except=true 4433 finally_node.in_ctx_manager=true 4434 var js='if('+this.exc_name 4435 js+='){'+this.cmexit_name+'(_b_.None, _b_.None, _b_.None);' 4436 if(this.scope.ntype=="generator"){js+='delete '+this.cmexit_name} 4437 js+='};' 4438 finally_node.add($NodeJS(js)) 4439 node.parent.insert(rank+2,finally_node) 4440 this.transformed=true} 4441 $WithCtx.prototype.transform_async=function(node,rank){ 4442 var scope=$get_scope(this),expr=this.tree[0],alias=this.tree[0].alias 4443 var new_nodes=[] 4444 var num=this.num=$loop_num++ 4445 this.cm_name='$ctx_manager'+num,this.cmexit_name='$ctx_manager_exit'+num 4446 this.exc_name='$exc'+num 4447 var cmtype_name='$ctx_mgr_type'+num,cmenter_name='$ctx_manager_enter'+num,err_name='$err'+num 4448 var js='var '+this.cm_name+' = '+expr.to_js()+',' 4449 new_nodes.push($NodeJS(js)) 4450 new_nodes.push($NodeJS(' '+cmtype_name+ 4451 ' = _b_.type.$factory('+this.cm_name+'),')) 4452 new_nodes.push($NodeJS(' '+this.cmexit_name+ 4453 ' = $B.$call($B.$getattr('+cmtype_name+', "__aexit__")),')) 4454 new_nodes.push($NodeJS(' '+cmenter_name+ 4455 ' = $B.$call($B.$getattr('+cmtype_name+', "__aenter__"))'+ 4456 '('+this.cm_name+'),')) 4457 new_nodes.push($NodeJS(" "+this.exc_name+" = false")) 4458 js="" 4459 if(alias){if(alias.tree[0].tree[0].type !="list_or_tuple"){var js=alias.tree[0].to_js()+' = '+ 4460 'await ($B.promise('+cmenter_name+'))' 4461 new_nodes.push($NodeJS(js))}else{ 4462 var new_node=new $Node(),ctx=new $NodeCtx(new_node),expr=new $ExprCtx(ctx,"left",false) 4463 expr.tree.push(alias.tree[0].tree[0]) 4464 alias.tree[0].tree[0].parent=expr 4465 var assign=new $AssignCtx(expr) 4466 new $RawJSCtx(assign,'await ($B.promise('+ 4467 cmenter_name+'))') 4468 new_nodes.push(new_node)}}else{new_nodes.push($NodeJS('await ($B.promise('+cmenter_name+'))'))} 4469 var try_node=new $NodeJS('try') 4470 node.children.forEach(function(child){try_node.add(child)}) 4471 new_nodes.push(try_node) 4472 var catch_node=new $NodeJS('catch(err)') 4473 new_nodes.push(catch_node) 4474 catch_node.add($NodeJS(this.exc_name+' = true')) 4475 catch_node.add($NodeJS('var '+err_name+ 4476 ' = $B.imported["_sys"].exc_info()')) 4477 var if_node=$NodeJS('if(! await ($B.promise('+ 4478 this.cmexit_name+'('+this.cm_name+', '+err_name+'[0], '+ 4479 err_name+'[1], '+err_name+'[2]))))') 4480 catch_node.add(if_node) 4481 if_node.add($NodeJS('$B.$raise()')) 4482 var else_node=$NodeJS('if(! '+this.exc_name+')') 4483 new_nodes.push(else_node) 4484 else_node.add($NodeJS('await ($B.promise('+this.cmexit_name+'('+ 4485 this.cm_name+', _b_.None, _b_.None, _b_.None)))')) 4486 node.parent.children.splice(rank,1) 4487 for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank,new_nodes[i])} 4488 node.children=[] 4489 return 0} 4490 $WithCtx.prototype.to_js=function(){this.js_processed=true 4491 var indent=$get_node(this).indent,h=' '.repeat(indent),num=this.num 4492 var head=this.prefix=="" ? "var " :this.prefix,cm_name='$ctx_manager'+num,cme_name=head+'$ctx_manager_exit'+num,exc_name=head+'$exc'+num,val_name='$value'+num 4493 return 'var '+cm_name+' = '+this.tree[0].to_js()+'\n'+ 4494 h+cme_name+' = $B.$getattr('+cm_name+',"__exit__")\n'+ 4495 h+'var '+val_name+' = $B.$getattr('+cm_name+',"__enter__")()\n'+ 4496 h+exc_name+' = true\n'} 4497 var $YieldCtx=$B.parser.$YieldCtx=function(C,is_await){ 4498 this.type='yield' 4499 this.parent=C 4500 this.tree=[] 4501 this.is_await=is_await 4502 C.tree[C.tree.length]=this 4503 if(C.type=="list_or_tuple" && C.tree.length > 1){$_SyntaxError(C,"non-parenthesized yield")} 4504 if($parent_match(C,{type:"annotation"})){$_SyntaxError(C,["'yield' outside function"])} 4505 var parent=this 4506 while(true){var list_or_tuple=$parent_match(parent,{type:"list_or_tuple"}) 4507 if(list_or_tuple){list_or_tuple.yields=list_or_tuple.yields ||[] 4508 list_or_tuple.yields.push([this,$pos]) 4509 parent=list_or_tuple}else{break}} 4510 var parent=this 4511 while(true){var set_or_dict=$parent_match(parent,{type:"dict_or_set"}) 4512 if(set_or_dict){set_or_dict.yields=set_or_dict.yields ||[] 4513 set_or_dict.yields.push([this,$pos]) 4514 parent=set_or_dict}else{break}} 4515 var root=$get_module(this) 4516 root.yields_func_check=root.yields_func_check ||[] 4517 root.yields_func_check.push([this,$pos]) 4518 var scope=this.scope=$get_scope(this,true),node=$get_node(this) 4519 node.has_yield=this 4520 var in_comp=$parent_match(this,{type:"comprehension"}) 4521 if($get_scope(this).id.startsWith("lc"+$B.lambda_magic)){delete node.has_yield} 4522 if(in_comp){var outermost_expr=in_comp.tree[0].tree[1] 4523 var parent=C 4524 while(parent){if(parent===outermost_expr){break} 4525 parent=parent.parent} 4526 if(! parent){$_SyntaxError(C,["'yield' inside list comprehension"])}} 4527 var in_lambda=false,parent=C 4528 while(parent){if(parent.type=="lambda"){in_lambda=true 4529 this.in_lambda=true 4530 break} 4531 parent=parent.parent} 4532 var parent=node.parent 4533 while(parent){if(parent.C && parent.C.tree.length > 0 && 4534 parent.C.tree[0].type=="with"){scope.C.tree[0].$has_yield_in_cm=true 4535 break} 4536 parent=parent.parent} 4537 if(! in_lambda){switch(C.type){case 'node': 4538 break; 4539 case 'assign': 4540 case 'list_or_tuple': 4541 break 4542 default: 4543 $_SyntaxError(C,'yield atom must be inside ()')}}} 4544 $YieldCtx.prototype.toString=function(){return '(yield) '+(this.from ? '(from) ' :'')+this.tree} 4545 $YieldCtx.prototype.transition=function(token,value){var C=this 4546 if(token=='from'){ 4547 if(C.tree[0].type !='abstract_expr'){ 4548 $_SyntaxError(C,"'from' must follow 'yield'")} 4549 C.from=true 4550 C.from_num=$B.UUID() 4551 return C.tree[0]} 4552 return $transition(C.parent,token)} 4553 $YieldCtx.prototype.transform=function(node,rank){ 4554 var parent=node.parent 4555 while(parent){if(parent.ctx_manager_num !==undefined){node.parent.insert(rank+1,$NodeJS("$top_frame[1].$has_yield_in_cm = true")) 4556 break} 4557 parent=parent.parent}} 4558 $YieldCtx.prototype.to_js=function(){if(this.from){return `_r${this.from_num}`}else{return "yield "+$to_js(this.tree)}} 4559 $YieldCtx.prototype.check_in_function=function(){if(this.in_lambda){return} 4560 var scope=$get_scope(this),in_func=scope.is_function,func_scope=scope 4561 if(! in_func && scope.is_comp){var parent=scope.parent_block 4562 while(parent.is_comp){parent=parent_block} 4563 in_func=parent.is_function 4564 func_scope=parent} 4565 if(! in_func){$_SyntaxError(this.parent,["'yield' outside function"])}else{var def=func_scope.C.tree[0] 4566 if(! this.is_await){def.type='generator'}}} 4567 var $add_line_num=$B.parser.$add_line_num=function(node,rank,line_info){if(node.type=='module'){var i=0 4568 while(i < node.children.length){i+=$add_line_num(node.children[i],i,line_info)}}else if(node.type !=='marker'){var elt=node.C.tree[0],offset=1,flag=true,pnode=node,_line_info 4569 while(pnode.parent !==undefined){pnode=pnode.parent} 4570 var mod_id=pnode.id 4571 var line_num=node.line_num 4572 if(line_num===undefined){flag=false} 4573 if(elt.type=='condition' && elt.token=='elif'){flag=false} 4574 else if(elt.type=='except'){flag=false} 4575 else if(elt.type=='single_kw'){flag=false} 4576 if(flag){_line_info=line_info===undefined ? line_num+','+mod_id : 4577 line_info 4578 var js=';$locals.$line_info = "'+_line_info+ 4579 '";if($locals.$f_trace !== _b_.None){$B.trace_line()};'+ 4580 '_b_.None;' 4581 var new_node=new $Node() 4582 new_node.is_line_num=true 4583 new $NodeJSCtx(new_node,js) 4584 node.parent.insert(rank,new_node) 4585 offset=2} 4586 var i=0 4587 while(i < node.children.length){i+=$add_line_num(node.children[i],i,line_info)} 4588 return offset}else{return 1}} 4589 var $bind=$B.parser.$bind=function(name,scope,C){ 4590 if(scope.nonlocals && scope.nonlocals[name]){ 4591 return} 4592 if(scope.globals && scope.globals.has(name)){var module=$get_module(C) 4593 module.binding[name]=true 4594 return} 4595 if(! C.no_bindings){var node=$get_node(C) 4596 node.bindings=node.bindings ||{} 4597 node.bindings[name]=true} 4598 scope.binding=scope.binding ||{} 4599 if(scope.binding[name]===undefined){scope.binding[name]=true}} 4600 function $parent_match(ctx,obj){ 4601 var flag 4602 while(ctx.parent){flag=true 4603 for(var attr in obj){if(ctx.parent[attr]!=obj[attr]){flag=false 4604 break}} 4605 if(flag){return ctx.parent} 4606 ctx=ctx.parent} 4607 return false} 4608 var $previous=$B.parser.$previous=function(C){var previous=C.node.parent.children[C.node.parent.children.length-2] 4609 if(!previous ||!previous.C){$_SyntaxError(C,'keyword not following correct keyword')} 4610 return previous.C.tree[0]} 4611 var $get_docstring=$B.parser.$get_docstring=function(node){var doc_string='' 4612 if(node.children.length > 0){var firstchild=node.children[0] 4613 if(firstchild.C.tree && firstchild.C.tree.length > 0 && 4614 firstchild.C.tree[0].type=='expr'){var expr=firstchild.C.tree[0].tree[0] 4615 if(expr.type=='str' && !Array.isArray(expr.tree[0])){doc_string=firstchild.C.tree[0].tree[0].to_js()}}} 4616 return doc_string} 4617 var $get_scope=$B.parser.$get_scope=function(C,flag){ 4618 var ctx_node=C.parent 4619 while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} 4620 var tree_node=ctx_node.node,scope=null 4621 while(tree_node.parent && tree_node.parent.type !=='module'){var ntype=tree_node.parent.C.tree[0].type 4622 switch(ntype){case 'def': 4623 case 'class': 4624 case 'generator': 4625 var scope=tree_node.parent 4626 scope.ntype=ntype 4627 scope.is_function=ntype !='class' 4628 return scope} 4629 tree_node=tree_node.parent} 4630 var scope=tree_node.parent ||tree_node 4631 scope.ntype="module" 4632 return scope} 4633 var $get_line_num=$B.parser.$get_line_num=function(C){var ctx_node=$get_node(C),line_num=ctx_node.line_num 4634 if(ctx_node.line_num===undefined){ctx_node=ctx_node.parent 4635 while(ctx_node && ctx_node.line_num===undefined){ctx_node=ctx_node.parent} 4636 if(ctx_node && ctx_node.line_num){line_num=ctx_node.line_num}} 4637 return line_num} 4638 var $get_module=$B.parser.$get_module=function(C){ 4639 var ctx_node=C.parent 4640 while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} 4641 var tree_node=ctx_node.node 4642 if(tree_node.ntype=="module"){return tree_node} 4643 var scope=null 4644 while(tree_node.parent.type !='module'){tree_node=tree_node.parent} 4645 scope=tree_node.parent 4646 scope.ntype="module" 4647 return scope} 4648 var $get_src=$B.parser.$get_src=function(C){ 4649 var node=$get_node(C) 4650 while(node.parent !==undefined){node=node.parent} 4651 return node.src} 4652 var $get_node=$B.parser.$get_node=function(C){var ctx=C 4653 while(ctx.parent){ctx=ctx.parent} 4654 return ctx.node} 4655 var $to_js_map=$B.parser.$to_js_map=function(tree_element){if(tree_element.to_js !==undefined){return tree_element.to_js()} 4656 throw Error('no to_js() for '+tree_element)} 4657 var $to_js=$B.parser.$to_js=function(tree,sep){if(sep===undefined){sep=','} 4658 return tree.map($to_js_map).join(sep)} 4659 var $mangle=$B.parser.$mangle=function(name,C){ 4660 if(name.substr(0,2)=="__" && name.substr(name.length-2)!=="__"){var klass=null,scope=$get_scope(C) 4661 while(true){if(scope.ntype=="module"){return name} 4662 else if(scope.ntype=="class"){var class_name=scope.C.tree[0].name 4663 while(class_name.charAt(0)=='_'){class_name=class_name.substr(1)} 4664 return '_'+class_name+name}else{if(scope.parent && scope.parent.C){scope=$get_scope(scope.C.tree[0])}else{return name}}}}else{return name}} 4665 var $transition=$B.parser.$transition=function(C,token,value){ 4666 return C.transition(token,value)} 4667 $B.forbidden=["alert","arguments","case","catch","const","constructor","Date","debugger","delete","default","do","document","enum","export","eval","extends","Error","history","function","instanceof","keys","length","location","Math","message","new","null","Number","RegExp","String","super","switch","this","throw","typeof","var","window","toLocaleString","toString","void"] 4668 $B.aliased_names=$B.list2obj($B.forbidden) 4669 var s_escaped='abfnrtvxuU"0123456789'+"'"+'\\',is_escaped={} 4670 for(var i=0;i < s_escaped.length;i++){is_escaped[s_escaped.charAt(i)]=true} 4671 var $tokenize=$B.parser.$tokenize=function(root,src){var br_close={")":"(","]":"[","}":"{"},br_stack="",br_pos=[] 4672 var kwdict=["class","return","break","for","lambda","try","finally","raise","def","from","nonlocal","while","del","global","with","as","elif","else","if","yield","assert","import","except","raise","in","pass","with","continue","__debugger__","async","await" 4673 ] 4674 var unsupported=[] 4675 var $indented=["class","def","for","condition","single_kw","try","except","with" 4676 ] 4677 var int_pattern=/^(\d[0-9_]*)(j|J)?/,float_pattern1=/^(\d[\d_]*)\.(\d+(_\d+)*)?([eE][+-]?\d+(_\d+)*)?(j|J)?/,float_pattern2=/^(\d[\d_]*)([eE][+-]?\d+(_\d+)*)(j|J)?/,hex_pattern=/^0[xX]([\da-fA-F_]+)/,octal_pattern=/^0[oO]([0-7_]+)/,binary_pattern=/^0[bB]([01_]+)/ 4678 var C=null 4679 var new_node=new $Node(),current=root,name="",_type=null,pos=0,indent=null,string_modifier=false 4680 var module=root.module 4681 var lnum=root.line_num ||1 4682 while(pos < src.length){var car=src.charAt(pos) 4683 if(indent===null){var indent=0 4684 while(pos < src.length){var _s=src.charAt(pos) 4685 if(_s==" "){indent++;pos++} 4686 else if(_s=="\t"){ 4687 indent++;pos++ 4688 if(indent % 8 > 0){indent+=8-indent % 8}}else{break}} 4689 var _s=src.charAt(pos) 4690 if(_s=='\n'){pos++;lnum++;indent=null; 4691 continue} 4692 else if(_s=='#'){ 4693 var offset=src.substr(pos).search(/\n/) 4694 if(offset==-1){break} 4695 pos+=offset+1 4696 lnum++ 4697 indent=null 4698 continue} 4699 new_node.indent=indent 4700 new_node.line_num=lnum 4701 new_node.module=module 4702 if(current.is_body_node){ 4703 current.indent=indent} 4704 if(indent > current.indent){ 4705 if(C !==null){if($indented.indexOf(C.tree[0].type)==-1){$pos=pos 4706 $_SyntaxError(C,'unexpected indent',pos)}} 4707 current.add(new_node)}else if(indent <=current.indent && C && C.tree[0]&& 4708 $indented.indexOf(C.tree[0].type)>-1 && 4709 C.tree.length < 2){$pos=pos 4710 $_SyntaxError(C,'expected an indented block',pos)}else{ 4711 while(indent !==current.indent){current=current.parent 4712 if(current===undefined ||indent > current.indent){$pos=pos 4713 $_SyntaxError(C,'unexpected indent',pos)}} 4714 current.parent.add(new_node)} 4715 current=new_node 4716 C=new $NodeCtx(new_node) 4717 continue} 4718 if(car=="#"){var end=src.substr(pos+1).search('\n') 4719 if(end==-1){end=src.length-1} 4720 root.comments.push([pos,end]) 4721 pos+=end+1 4722 continue} 4723 if(car=='"' ||car=="'"){var raw=C.type=='str' && C.raw,bytes=false,fstring=false,sm_length, 4724 end=null; 4725 if(string_modifier){switch(string_modifier){case 'r': 4726 raw=true 4727 break 4728 case 'u': 4729 break 4730 case 'b': 4731 bytes=true 4732 break 4733 case 'rb': 4734 case 'br': 4735 bytes=true;raw=true 4736 break 4737 case 'f': 4738 fstring=true 4739 sm_length=1 4740 break 4741 case 'fr','rf': 4742 fstring=true 4743 sm_length=2 4744 raw=true 4745 break} 4746 string_modifier=false} 4747 if(src.substr(pos,3)==car+car+car){_type="triple_string" 4748 end=pos+3}else{_type="string" 4749 end=pos+1} 4750 var escaped=false,zone=car,found=false 4751 while(end < src.length){if(escaped){if(src.charAt(end)=="a"){zone=zone.substr(0,zone.length-1)+"\u0007"}else{zone+=src.charAt(end) 4752 if(raw && src.charAt(end)=='\\'){zone+='\\'}} 4753 escaped=false 4754 end++}else if(src.charAt(end)=="\\"){if(raw){if(end < src.length-1 && 4755 src.charAt(end+1)==car){zone+='\\\\'+car 4756 end+=2}else{zone+='\\\\' 4757 end++} 4758 escaped=true}else{if(src.charAt(end+1)=='\n'){ 4759 end+=2 4760 lnum++}else if(src.substr(end+1,2)=='N{'){ 4761 var end_lit=end+3,re=new RegExp("[-a-zA-Z0-9 ]+"),search=re.exec(src.substr(end_lit)) 4762 if(search===null){$_SyntaxError(C,"(unicode error) "+ 4763 "malformed \\N character escape",pos)} 4764 var end_lit=end_lit+search[0].length 4765 if(src.charAt(end_lit)!="}"){$_SyntaxError(C,"(unicode error) "+ 4766 "malformed \\N character escape")} 4767 var description=search[0].toUpperCase() 4768 if($B.unicodedb===undefined){var xhr=new XMLHttpRequest 4769 xhr.open("GET",$B.brython_path+"unicode.txt",false) 4770 xhr.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){$B.unicodedb=this.responseText}else{console.log("Warning - could not "+ 4771 "load unicode.txt")}}} 4772 xhr.send()} 4773 if($B.unicodedb !==undefined){var re=new RegExp("^([0-9A-F]+);"+ 4774 description+";.*$","m") 4775 search=re.exec($B.unicodedb) 4776 if(search===null){$_SyntaxError(C,"(unicode error) "+ 4777 "unknown Unicode character name")} 4778 var cp="0x"+search[1] 4779 zone+=String.fromCodePoint(eval(cp)) 4780 end=end_lit+1}else{end++}}else{if(end < src.length-1 && 4781 is_escaped[src.charAt(end+1)]===undefined){zone+='\\'} 4782 zone+='\\' 4783 escaped=true 4784 end++}}}else if(src.charAt(end)=='\n' && _type !='triple_string'){ 4785 console.log(pos,end,src.substring(pos,end)) 4786 $pos=end 4787 $_SyntaxError(C,["EOL while scanning string literal"])}else if(src.charAt(end)==car){if(_type=="triple_string" && 4788 src.substr(end,3)!=car+car+car){zone+=src.charAt(end) 4789 end++}else{found=true 4790 $pos=pos 4791 var $string=zone.substr(1),string='' 4792 for(var i=0;i < $string.length;i++){var $car=$string.charAt(i) 4793 if($car==car && 4794 (raw ||(i==0 || 4795 $string.charAt(i-1)!='\\'))){string+='\\'} 4796 string+=$car} 4797 if(fstring){try{var re=new RegExp("\\\\"+car,"g"),string_no_bs=string.replace(re,car) 4798 var elts=$B.parse_fstring(string_no_bs)}catch(err){$_SyntaxError(C,[err.toString()])}} 4799 if(bytes){C=$transition(C,'str','b'+car+string+car)}else if(fstring){$pos-=sm_length 4800 C=$transition(C,'str',elts) 4801 $pos+=sm_length}else{C=$transition(C,'str',car+string+car)} 4802 C.raw=raw; 4803 pos=end+1 4804 if(_type=="triple_string"){pos=end+3} 4805 break}}else{zone+=src.charAt(end) 4806 if(src.charAt(end)=='\n'){lnum++} 4807 end++}} 4808 if(!found){if(_type==="triple_string"){$_SyntaxError(C,"Triple string end not found")}else{$_SyntaxError(C,"String end not found")}} 4809 continue} 4810 if(name=="" && car !='$'){ 4811 if($B.unicode_tables.XID_Start[car.charCodeAt(0)]){name=car 4812 var p0=pos 4813 pos++ 4814 while(pos < src.length && 4815 $B.unicode_tables.XID_Continue[src.charCodeAt(pos)]){name+=src.charAt(pos) 4816 pos++}} 4817 if(name){if(kwdict.indexOf(name)>-1){$pos=pos-name.length 4818 if(unsupported.indexOf(name)>-1){$_SyntaxError(C,"Unsupported Python keyword '"+name+"'")} 4819 C=$transition(C,name)}else if(typeof $operators[name]=='string' && 4820 ['is_not','not_in'].indexOf(name)==-1){ 4821 if(name=='is'){ 4822 var re=/^\s+not\s+/ 4823 var res=re.exec(src.substr(pos)) 4824 if(res !==null){pos+=res[0].length 4825 $pos=pos-name.length 4826 C=$transition(C,'op','is_not')}else{$pos=pos-name.length 4827 C=$transition(C,'op',name)}}else if(name=='not'){ 4828 var re=/^\s+in\s+/ 4829 var res=re.exec(src.substr(pos)) 4830 if(res !==null){pos+=res[0].length 4831 $pos=pos-name.length 4832 C=$transition(C,'op','not_in')}else{$pos=pos-name.length 4833 C=$transition(C,name)}}else{$pos=pos-name.length 4834 C=$transition(C,'op',name)}}else if((src.charAt(pos)=='"' ||src.charAt(pos)=="'") 4835 &&['r','b','u','rb','br','f','fr','rf']. 4836 indexOf(name.toLowerCase())!==-1){string_modifier=name.toLowerCase() 4837 name="" 4838 continue}else{if($B.forbidden.indexOf(name)>-1){name='$$'+name} 4839 $pos=pos-name.length 4840 C=$transition(C,'id',name)} 4841 name="" 4842 continue}} 4843 function rmuf(numeric_literal){ 4844 if(numeric_literal.search("__")>-1){ 4845 $_SyntaxError(C,"invalid literal")}else if(numeric_literal.endsWith("_")){ 4846 $_SyntaxError(C,"invalid literal")} 4847 return numeric_literal.replace(/_/g,"")} 4848 function check_int(numeric_literal){ 4849 rmuf(numeric_literal) 4850 if(numeric_literal.startsWith("0")){if(numeric_literal.substr(1).search(/[^0_]/)>-1){ 4851 $_SyntaxError(C,"invalid literal")}else{return "0"}}} 4852 function rmu(numeric_literal){return numeric_literal.replace(/_/g,"")} 4853 switch(car){case ' ': 4854 case '\t': 4855 pos++ 4856 break 4857 case '.': 4858 if(pos < src.length-1 &&/^\d$/.test(src.charAt(pos+1))){ 4859 var j=pos+1 4860 while(j < src.length && 4861 src.charAt(j).search(/\d|e|E|_/)>-1){j++} 4862 if(src.charAt(j)=="j"){C=$transition(C,'imaginary','0'+rmu(src.substr(pos,j-pos))) 4863 j++}else{C=$transition(C,'float','0'+rmu(src.substr(pos,j-pos)))} 4864 pos=j 4865 break} 4866 $pos=pos 4867 C=$transition(C,'.') 4868 pos++ 4869 break 4870 case '0': 4871 var res=hex_pattern.exec(src.substr(pos)) 4872 if(res){rmuf(res[1]) 4873 C=$transition(C,'int',[16,rmu(res[1])]) 4874 pos+=res[0].length 4875 break} 4876 var res=octal_pattern.exec(src.substr(pos)) 4877 if(res){C=$transition(C,'int',[8,rmuf(res[1])]) 4878 pos+=res[0].length 4879 break} 4880 var res=binary_pattern.exec(src.substr(pos)) 4881 if(res){C=$transition(C,'int',[2,rmuf(res[1])]) 4882 pos+=res[0].length 4883 break} 4884 if(src.charAt(pos+1).search(/\d/)>-1){ 4885 if(parseInt(src.substr(pos))===0){res=int_pattern.exec(src.substr(pos)) 4886 $pos=pos 4887 check_int(res[0]) 4888 C=$transition(C,'int',[10,rmu(res[0])]) 4889 pos+=res[0].length 4890 break}else{$_SyntaxError(C,'invalid literal starting with 0')}} 4891 case '0': 4892 case '1': 4893 case '2': 4894 case '3': 4895 case '4': 4896 case '5': 4897 case '6': 4898 case '7': 4899 case '8': 4900 case '9': 4901 var res=float_pattern1.exec(src.substr(pos)) 4902 if(res){check_int(res[1]) 4903 if(res[2]){rmuf(res[2])} 4904 $pos=pos 4905 if($B.last(res)!==undefined){C=$transition(C,'imaginary',rmuf(res[0].substr(0,res[0].length-1)))}else{C=$transition(C,'float',rmuf(res[0]))}}else{res=float_pattern2.exec(src.substr(pos)) 4906 if(res){check_int(res[1]) 4907 $pos=pos 4908 if($B.last(res)!==undefined){C=$transition(C,'imaginary',rmuf(res[0].substr(0,res[0].length-1)))}else{C=$transition(C,'float',rmuf(res[0]))}}else{res=int_pattern.exec(src.substr(pos)) 4909 check_int(res[1]) 4910 $pos=pos 4911 if(res[2]!==undefined){C=$transition(C,'imaginary',rmu(res[1]))}else{C=$transition(C,'int',[10,rmu(res[0])])}}} 4912 pos+=res[0].length 4913 break 4914 case '\n': 4915 lnum++ 4916 if(br_stack.length > 0){ 4917 pos++}else{if(current.C.tree.length > 0 ||current.C.async){$pos=pos 4918 C=$transition(C,'eol') 4919 indent=null 4920 new_node=new $Node()}else{new_node.line_num=lnum} 4921 pos++} 4922 break 4923 case '(': 4924 case '[': 4925 case '{': 4926 br_stack+=car 4927 br_pos[br_stack.length-1]=[C,pos] 4928 $pos=pos 4929 C=$transition(C,car) 4930 pos++ 4931 break 4932 case ')': 4933 case ']': 4934 case '}': 4935 if(br_stack==""){$pos=pos 4936 $_SyntaxError(C,"Unexpected closing bracket")}else if(br_close[car]!= 4937 br_stack.charAt(br_stack.length-1)){$pos=pos 4938 $_SyntaxError(C,"Unbalanced bracket")}else{br_stack=br_stack.substr(0,br_stack.length-1) 4939 $pos=pos 4940 C=$transition(C,car) 4941 pos++} 4942 break 4943 case '=': 4944 if(src.charAt(pos+1)!="="){$pos=pos 4945 C=$transition(C,'=') 4946 pos++}else{$pos=pos 4947 C=$transition(C,'op','==') 4948 pos+=2} 4949 break 4950 case ',': 4951 case ':': 4952 $pos=pos 4953 if(src.substr(pos,2)==":="){ 4954 C=$transition(C,":=") 4955 pos++}else{C=$transition(C,car)} 4956 pos++ 4957 break 4958 case ';': 4959 $transition(C,'eol') 4960 if(current.C.tree.length==0){ 4961 $pos=pos 4962 $_SyntaxError(C,'invalid syntax')} 4963 var pos1=pos+1 4964 var ends_line=false 4965 while(pos1 < src.length){var _s=src.charAt(pos1) 4966 if(_s=='\n' ||_s=='#'){ends_line=true;break} 4967 else if(_s==' '){pos1++} 4968 else{break}} 4969 if(ends_line){pos++;break} 4970 new_node=new $Node() 4971 new_node.indent=$get_node(C).indent 4972 new_node.line_num=lnum 4973 new_node.module=module 4974 $get_node(C).parent.add(new_node) 4975 current=new_node 4976 C=new $NodeCtx(new_node) 4977 pos++ 4978 break 4979 case '/': 4980 case '%': 4981 case '&': 4982 case '>': 4983 case '<': 4984 case '-': 4985 case '+': 4986 case '*': 4987 case '@': 4988 case '/': 4989 case '^': 4990 case '=': 4991 case '|': 4992 case '~': 4993 case '!': 4994 if(car=='-' && src.charAt(pos+1)=='>'){C=$transition(C,'annotation') 4995 pos+=2 4996 continue} 4997 if(car=='@' && C.type=="node"){$pos=pos 4998 C=$transition(C,car) 4999 pos++ 5000 break} 5001 var op_match="" 5002 for(var op_sign in $operators){if(op_sign==src.substr(pos,op_sign.length) 5003 && op_sign.length > op_match.length){op_match=op_sign}} 5004 $pos=pos 5005 if(op_match.length > 0){if(op_match in $augmented_assigns){C=$transition(C,'augm_assign',op_match)}else{C=$transition(C,'op',op_match)} 5006 pos+=op_match.length}else{$_SyntaxError(C,'invalid character: '+car)} 5007 break 5008 case '\\': 5009 if(src.charAt(pos+1)=='\n'){lnum++ 5010 pos+=2 5011 if(pos==src.length){$_SyntaxError(C,["unexpected EOF while parsing"])}else if(C.type=="node"){$_SyntaxError(C,'nothing before \\')} 5012 break}else{$pos=pos 5013 $_SyntaxError(C,['unexpected character after line continuation character'])} 5014 case String.fromCharCode(12): 5015 pos+=1 5016 break 5017 default: 5018 $pos=pos 5019 $_SyntaxError(C,'unknown token ['+car+']')}} 5020 if(br_stack.length !=0){var br_err=br_pos[0] 5021 $pos=br_err[1] 5022 var lines=src.split("\n"),id=root.id,fname=id.startsWith("$")? '<string>' :id 5023 $_SyntaxError(br_err[0],["unexpected EOF while parsing ("+fname+", line "+ 5024 (lines.length-1)+")"])} 5025 if(C !==null){if(C.type=="async"){ 5026 console.log("error with async",pos,src,src.substr(pos)) 5027 $pos=pos-7 5028 throw $_SyntaxError(C,"car "+car+"after async",pos)}else if(C.tree[0]&& 5029 $indented.indexOf(C.tree[0].type)>-1){$pos=pos-1 5030 $_SyntaxError(C,'expected an indented block',pos)}else{var parent=current.parent 5031 if(parent.C && parent.C.tree && 5032 parent.C.tree[0]&& 5033 parent.C.tree[0].type=="try"){$pos=pos-1 5034 $_SyntaxError(C,["unexpected EOF while parsing"])} 5035 if(root.yields_func_check){var save_pos=$pos 5036 for(const _yield of root.yields_func_check){$pos=_yield[1] 5037 _yield[0].check_in_function()} 5038 $pos=save_pos}}}} 5039 var $create_root_node=$B.parser.$create_root_node=function(src,module,locals_id,parent_block,line_num){var root=new $Node('module') 5040 root.module=module 5041 root.id=locals_id 5042 root.binding={__doc__:true,__name__:true,__file__:true,__package__:true} 5043 root.parent_block=parent_block 5044 root.line_num=line_num 5045 root.indent=-1 5046 root.comments=[] 5047 root.imports={} 5048 if(typeof src=="object"){root.is_comp=src.is_comp 5049 if(src.has_annotations){root.binding.__annotations__=true} 5050 src=src.src} 5051 root.src=src 5052 return root} 5053 $B.py2js=function(src,module,locals_id,parent_scope,line_num){ 5054 $pos=0 5055 if(typeof module=="object"){var __package__=module.__package__ 5056 module=module.__name__}else{var __package__=""} 5057 parent_scope=parent_scope ||$B.builtins_scope 5058 var t0=new Date().getTime(),is_comp=false,has_annotations=true, 5059 line_info, 5060 ix 5061 if(typeof src=='object'){var is_comp=src.is_comp,has_annotations=src.has_annotations,line_info=src.line_info,ix=src.ix 5062 if(line_info !==undefined){line_num=parseInt(line_info.split(",")[0])} 5063 src=src.src} 5064 src=src.replace(/\r\n/gm,"\n") 5065 if(src.endsWith("\\")&& !src.endsWith("\\\\")){src=src.substr(0,src.length-1)} 5066 if(src.charAt(src.length-1)!="\n"){src+="\n"} 5067 var locals_is_module=Array.isArray(locals_id) 5068 if(locals_is_module){locals_id=locals_id[0]} 5069 var internal=locals_id.charAt(0)=='$' 5070 var local_ns='$locals_'+locals_id.replace(/\./g,'_') 5071 var global_ns='$locals_'+module.replace(/\./g,'_') 5072 var root=$create_root_node( 5073 {src:src,is_comp:is_comp,has_annotations:has_annotations},module,locals_id,parent_scope,line_num) 5074 $tokenize(root,src) 5075 root.is_comp=is_comp 5076 if(ix !=undefined){root.ix=ix} 5077 root.transform() 5078 var js=['var $B = __BRYTHON__;\n'],pos=1 5079 js[pos++]='var _b_ = __BRYTHON__.builtins;\n' 5080 js[pos]='var $locals = '+local_ns 5081 if(is_comp){js[pos]+=' = {}'} 5082 var offset=0 5083 root.insert(0,$NodeJS(js.join(''))) 5084 offset++ 5085 root.insert(offset++,$NodeJS(local_ns+'.__package__ = "'+__package__+'"')) 5086 if(root.binding.__annotations__){root.insert(offset++,$NodeJS('$locals.__annotations__ = $B.empty_dict()'))} 5087 var enter_frame_pos=offset,js='var $top_frame = ["'+locals_id.replace(/\./g,'_')+'", '+ 5088 local_ns+', "'+module.replace(/\./g,'_')+'", '+ 5089 global_ns+']\n$locals.$f_trace = $B.enter_frame($top_frame)\n'+ 5090 'var $stack_length = $B.frames_stack.length;' 5091 root.insert(offset++,$NodeJS(js)) 5092 var try_node=new $NodeJS('try'),children=root.children.slice(enter_frame_pos+1,root.children.length) 5093 root.insert(enter_frame_pos+1,try_node) 5094 if(children.length==0){children=[$NodeJS('')]} 5095 children.forEach(function(child){try_node.add(child)}) 5096 try_node.add($NodeJS('$B.leave_frame({$locals, value: _b_.None})')) 5097 root.children.splice(enter_frame_pos+2,root.children.length) 5098 var catch_node=$NodeJS('catch(err)') 5099 catch_node.add($NodeJS('$B.leave_frame({$locals, value: _b_.None})')) 5100 catch_node.add($NodeJS('throw err')) 5101 root.add(catch_node) 5102 $add_line_num(root,null,line_info) 5103 var t1=new Date().getTime() 5104 if($B.debug > 2){if(module==locals_id){console.log('module '+module+' translated in '+ 5105 (t1-t0)+' ms')}} 5106 $B.compile_time+=t1-t0 5107 return root} 5108 $B.set_import_paths=function(){ 5109 var meta_path=[],path_hooks=[] 5110 if($B.use_VFS){meta_path.push($B.finders.VFS)} 5111 if($B.$options.static_stdlib_import !==false && $B.protocol !="file"){ 5112 meta_path.push($B.finders.stdlib_static) 5113 if($B.path.length > 3){$B.path.shift() 5114 $B.path.shift()}} 5115 if($B.protocol !=="file"){meta_path.push($B.finders.path) 5116 path_hooks.push($B.$path_hooks[0])} 5117 if($B.$options.cpython_import){if($B.$options.cpython_import=="replace"){$B.path.pop()} 5118 meta_path.push($B.finders.CPython)} 5119 $B.meta_path=meta_path 5120 $B.path_hooks=path_hooks} 5121 var brython=$B.parser.brython=function(options){ 5122 if(options===undefined){options={'debug':1}} 5123 if(typeof options=='number'){options={'debug':options}} 5124 if(options.debug===undefined){options.debug=1} 5125 $B.debug=options.debug 5126 _b_.__debug__=$B.debug > 0 5127 $B.compile_time=0 5128 if(options.profile===undefined){options.profile=0} 5129 $B.profile=options.profile 5130 if(options.indexedDB===undefined){options.indexedDB=true} 5131 if(options.static_stdlib_import===undefined){options.static_stdlib_import=true} 5132 $B.static_stdlib_import=options.static_stdlib_import 5133 $B.$options=options 5134 $B.set_import_paths() 5135 var $href=$B.script_path=_window.location.href,$href_elts=$href.split('/') 5136 $href_elts.pop() 5137 if($B.isWebWorker ||$B.isNode){$href_elts.pop()} 5138 $B.curdir=$href_elts.join('/') 5139 if(options.pythonpath !==undefined){$B.path=options.pythonpath 5140 $B.$options.static_stdlib_import=false} 5141 if(options.python_paths){options.python_paths.forEach(function(path){var lang,prefetch 5142 if(typeof path !=="string"){lang=path.lang 5143 prefetch=path.prefetch 5144 path=path.path} 5145 $B.path.push(path) 5146 if(path.slice(-7).toLowerCase()=='.vfs.js' && 5147 (prefetch===undefined ||prefetch===true)){$B.path_importer_cache[path+'/']= 5148 $B.imported['_importlib'].VFSPathFinder(path)} 5149 if(lang){_importlib.optimize_import_for_path(path,lang)}})} 5150 if(!($B.isWebWorker ||$B.isNode)){ 5151 var path_links=document.querySelectorAll('head link[rel~=pythonpath]'),_importlib=$B.imported['_importlib'] 5152 for(var i=0,e;e=path_links[i];++i){var href=e.href; 5153 if((' '+e.rel+' ').indexOf(' prepend ')!=-1){$B.path.unshift(href);}else{$B.path.push(href);} 5154 var filetype=e.hreflang 5155 if(filetype){if(filetype.slice(0,2)=='x-'){filetype=filetype.slice(2)} 5156 _importlib.optimize_import_for_path(e.href,filetype)}}} 5157 if($B.$options.args){$B.__ARGV=$B.$options.args}else{$B.__ARGV=_b_.list.$factory([])} 5158 if(!($B.isWebWorker ||$B.isNode)){_run_scripts(options)}} 5159 $B.run_script=function(src,name,run_loop){ 5160 $B.$py_module_path[name]=$B.script_path 5161 try{var root=$B.py2js(src,name,name),js=root.to_js(),script={__doc__:root.__doc__,js:js,__name__:name,$src:src,__file__:$B.script_path+ 5162 ($B.script_path.endsWith("/")? "" :"/")+name} 5163 $B.file_cache[script.__file__]=src 5164 if($B.debug > 1){console.log(js)}}catch(err){$B.handle_error(err)} 5165 if($B.hasOwnProperty("VFS")&& $B.has_indexedDB){ 5166 var imports1=Object.keys(root.imports).slice(),imports=imports1.filter(function(item){return $B.VFS.hasOwnProperty(item)}) 5167 Object.keys(imports).forEach(function(name){if($B.VFS.hasOwnProperty(name)){var submodule=$B.VFS[name],type=submodule[0] 5168 if(type==".py"){var src=submodule[1],subimports=submodule[2],is_package=submodule.length==4 5169 if(type==".py"){ 5170 required_stdlib_imports(subimports)} 5171 subimports.forEach(function(mod){if(imports.indexOf(mod)==-1){imports.push(mod)}})}}}) 5172 for(var j=0;j < imports.length;j++){$B.tasks.push([$B.inImported,imports[j]])} 5173 root=null} 5174 $B.tasks.push(["execute",script]) 5175 if(run_loop){$B.loop()}} 5176 var $log=$B.$log=function(js){js.split("\n").forEach(function(line,i){console.log(i+1,":",line)})} 5177 var _run_scripts=$B.parser._run_scripts=function(options){ 5178 var kk=Object.keys(_window) 5179 var defined_ids={} 5180 if(options.ipy_id !==undefined){var $elts=[] 5181 options.ipy_id.forEach(function(elt){$elts.push(document.getElementById(elt))})}else{var scripts=document.getElementsByTagName('script'),$elts=[],webworkers=[] 5182 for(var i=0;i < scripts.length;i++){var script=scripts[i] 5183 if(script.type=="text/python" ||script.type=="text/python3"){if(script.className=="webworker"){if(script.id===undefined){throw _b_.AttributeError.$factory( 5184 "webworker script has no attribute 'id'")} 5185 webworkers.push(script)}else{$elts.push(script)}}}} 5186 var first_script=true,module_name 5187 if(options.ipy_id !==undefined){module_name='__main__' 5188 var $src="",js,root 5189 $B.$py_module_path[module_name]=$B.script_path 5190 $elts.forEach(function(elt){$src+=(elt.innerHTML ||elt.textContent)}) 5191 try{ 5192 root=$B.py2js($src,module_name,module_name) 5193 js=root.to_js() 5194 if($B.debug > 1){$log(js)} 5195 eval(js) 5196 $B.clear_ns(module_name) 5197 root=null 5198 js=null}catch($err){root=null 5199 js=null 5200 console.log($err) 5201 if($B.debug > 1){console.log($err) 5202 for(var attr in $err){console.log(attr+' : ',$err[attr])}} 5203 if($err.$py_error===undefined){console.log('Javascript error',$err) 5204 $err=_b_.RuntimeError.$factory($err+'')} 5205 var $trace=$B.$getattr($err,'info')+'\n'+$err.__name__+ 5206 ': '+$err.args 5207 try{$B.$getattr($B.stderr,'write')($trace)}catch(print_exc_err){console.log($trace)} 5208 throw $err}}else{if($elts.length > 0){if(options.indexedDB && $B.has_indexedDB && 5209 $B.hasOwnProperty("VFS")){$B.tasks.push([$B.idb_open])}} 5210 for(var i=0;i < $elts.length;i++){var elt=$elts[i] 5211 if(elt.id){if(defined_ids[elt.id]){throw Error("Brython error : Found 2 scripts with the "+ 5212 "same id '"+elt.id+"'")}else{defined_ids[elt.id]=true}}} 5213 var src 5214 for(var i=0,len=webworkers.length;i < len;i++){var worker=webworkers[i] 5215 if(worker.src){ 5216 $B.tasks.push([$B.ajax_load_script,{name:worker.id,url:worker.src,is_ww:true}])}else{ 5217 src=(worker.innerHTML ||worker.textContent) 5218 src=src.replace(/^\n/,'') 5219 $B.webworkers[worker.id]=src}} 5220 for(var i=0;i < $elts.length;i++){var elt=$elts[i] 5221 if(elt.type=="text/python" ||elt.type=="text/python3"){ 5222 if(elt.id){module_name=elt.id}else{ 5223 if(first_script){module_name='__main__' 5224 first_script=false}else{module_name='__main__'+$B.UUID()} 5225 while(defined_ids[module_name]!==undefined){module_name='__main__'+$B.UUID()}} 5226 if(elt.src){ 5227 $B.tasks.push([$B.ajax_load_script,{name:module_name,url:elt.src}])}else{ 5228 src=(elt.innerHTML ||elt.textContent) 5229 src=src.replace(/^\n/,'') 5230 $B.run_script(src,module_name)}}}} 5231 if(options.ipy_id===undefined){$B.loop()}} 5232 $B.$operators=$operators 5233 $B.$Node=$Node 5234 $B.$NodeJSCtx=$NodeJSCtx 5235 $B.brython=brython})(__BRYTHON__) 5236 var brython=__BRYTHON__.brython 5237 if(__BRYTHON__.isNode){global.__BRYTHON__=__BRYTHON__ 5238 module.exports={__BRYTHON__ }} 5239 ; 5240 5241 (function($B){var _b_=$B.builtins 5242 if($B.VFS_timestamp && $B.VFS_timestamp > $B.timestamp){ 5243 $B.timestamp=$B.VFS_timestamp} 5244 function idb_load(evt,module){ 5245 var res=evt.target.result 5246 var timestamp=$B.timestamp 5247 if(res===undefined ||res.timestamp !=$B.timestamp || 5248 ($B.VFS[module]&& res.source_ts !==$B.VFS[module].timestamp)){ 5249 if($B.VFS[module]!==undefined){var elts=$B.VFS[module],ext=elts[0],source=elts[1] 5250 if(ext==".py"){var imports=elts[2],is_package=elts.length==4,source_ts=elts.timestamp,__package__ 5251 if(is_package){__package__=module} 5252 else{var parts=module.split(".") 5253 parts.pop() 5254 __package__=parts.join(".")} 5255 $B.imported[module]=$B.module.$factory(module,"",__package__) 5256 try{var root=$B.py2js(source,module,module),js=root.to_js()}catch(err){$B.handle_error(err)} 5257 delete $B.imported[module] 5258 if($B.debug > 1){console.log("precompile",module)} 5259 var parts=module.split(".") 5260 if(parts.length > 1){parts.pop()} 5261 if($B.stdlib.hasOwnProperty(parts.join("."))){var imports=elts[2] 5262 imports=imports.join(",") 5263 $B.tasks.splice(0,0,[store_precompiled,module,js,source_ts,imports,is_package])}}else{console.log('bizarre',module,ext)}}else{}}else{ 5264 if(res.is_package){$B.precompiled[module]=[res.content]}else{$B.precompiled[module]=res.content} 5265 if(res.imports.length > 0){ 5266 if($B.debug > 1){console.log(module,"imports",res.imports)} 5267 var subimports=res.imports.split(",") 5268 for(var i=0;i < subimports.length;i++){var subimport=subimports[i] 5269 if(subimport.startsWith(".")){ 5270 var url_elts=module.split("."),nb_dots=0 5271 while(subimport.startsWith(".")){nb_dots++ 5272 subimport=subimport.substr(1)} 5273 var elts=url_elts.slice(0,nb_dots) 5274 if(subimport){elts=elts.concat([subimport])} 5275 subimport=elts.join(".")} 5276 if(!$B.imported.hasOwnProperty(subimport)&& 5277 !$B.precompiled.hasOwnProperty(subimport)){ 5278 if($B.VFS.hasOwnProperty(subimport)){var submodule=$B.VFS[subimport],ext=submodule[0],source=submodule[1] 5279 if(submodule[0]==".py"){$B.tasks.splice(0,0,[idb_get,subimport])}else{add_jsmodule(subimport,source)}}}}}} 5280 loop()} 5281 function store_precompiled(module,js,source_ts,imports,is_package){ 5282 var db=$B.idb_cx.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),cursor=store.openCursor(),data={"name":module,"content":js,"imports":imports,"origin":origin,"timestamp":__BRYTHON__.timestamp,"source_ts":source_ts,"is_package":is_package},request=store.put(data) 5283 if($B.debug > 1){console.log("store precompiled",module,"package",is_package)} 5284 document.dispatchEvent(new CustomEvent('precompile',{detail:'cache module '+module})) 5285 var ix=$B.outdated.indexOf(module) 5286 if(ix >-1){$B.outdated.splice(ix,1)} 5287 request.onsuccess=function(evt){ 5288 $B.tasks.splice(0,0,[idb_get,module]) 5289 loop()}} 5290 function idb_get(module){ 5291 var db=$B.idb_cx.result,tx=db.transaction("modules","readonly") 5292 try{var store=tx.objectStore("modules") 5293 req=store.get(module) 5294 req.onsuccess=function(evt){idb_load(evt,module)}}catch(err){console.info('error',err)}} 5295 $B.idb_open=function(obj){$B.idb_name="brython-cache" 5296 var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name) 5297 idb_cx.onsuccess=function(){var db=idb_cx.result 5298 if(!db.objectStoreNames.contains("modules")){var version=db.version 5299 db.close() 5300 console.info('create object store',version) 5301 idb_cx=indexedDB.open($B.idb_name,version+1) 5302 idb_cx.onupgradeneeded=function(){console.info("upgrade needed") 5303 var db=$B.idb_cx.result,store=db.createObjectStore("modules",{"keyPath":"name"}) 5304 store.onsuccess=loop} 5305 idb_cx.onversionchanged=function(){console.log("version changed")} 5306 idb_cx.onsuccess=function(){console.info("db opened",idb_cx) 5307 var db=idb_cx.result,store=db.createObjectStore("modules",{"keyPath":"name"}) 5308 store.onsuccess=loop}}else{if($B.debug > 1){console.info("using indexedDB for stdlib modules cache")} 5309 var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[] 5310 var openCursor=store.openCursor() 5311 openCursor.onerror=function(evt){console.log("open cursor error",evt)} 5312 openCursor.onsuccess=function(evt){cursor=evt.target.result 5313 if(cursor){record=cursor.value 5314 if(record.timestamp==$B.timestamp){if(!$B.VFS ||!$B.VFS[record.name]|| 5315 $B.VFS[record.name].timestamp==record.source_ts){ 5316 if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content} 5317 if($B.debug > 1){console.info("load from cache",record.name)}}else{ 5318 outdated.push(record.name)}}else{outdated.push(record.name)} 5319 cursor.continue()}else{if($B.debug > 1){console.log("done")} 5320 $B.outdated=outdated 5321 loop()}}}} 5322 idb_cx.onupgradeneeded=function(){console.info("upgrade needed") 5323 var db=idb_cx.result,store=db.createObjectStore("modules",{"keyPath":"name"}) 5324 store.onsuccess=loop} 5325 idb_cx.onerror=function(){console.info('could not open indexedDB database') 5326 $B.idb_cx=null 5327 $B.idb_name=null 5328 $B.$options.indexedDB=false 5329 loop()}} 5330 $B.ajax_load_script=function(script){var url=script.url,name=script.name 5331 if($B.files && $B.files.hasOwnProperty(name)){$B.tasks.splice(0,0,[$B.run_script,$B.files[name],name,true])}else if($B.protocol !="file"){var req=new XMLHttpRequest(),qs=$B.$options.cache ? '' : 5332 (url.search(/\?/)>-1 ? '&' :'?')+Date.now() 5333 req.open("GET",url+qs,true) 5334 req.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var src=this.responseText 5335 if(script.is_ww){$B.webworkers[name]=src}else{$B.tasks.splice(0,0,[$B.run_script,src,name,true])} 5336 loop()}else if(this.status==404){throw Error(url+" not found")}}} 5337 req.send()}else{throw _b_.IOError.$factory("can't load external script at "+ 5338 script.url+" (Ajax calls not supported with protocol file:///)")}} 5339 function add_jsmodule(module,source){ 5340 source+="\nvar $locals_"+ 5341 module.replace(/\./g,"_")+" = $module" 5342 $B.precompiled[module]=source} 5343 var inImported=$B.inImported=function(module){if($B.imported.hasOwnProperty(module)){}else if(__BRYTHON__.VFS && __BRYTHON__.VFS.hasOwnProperty(module)){var elts=__BRYTHON__.VFS[module] 5344 if(elts===undefined){console.log('bizarre',module)} 5345 var ext=elts[0],source=elts[1],is_package=elts.length==4 5346 if(ext==".py"){if($B.idb_cx && !$B.idb_cx.$closed){$B.tasks.splice(0,0,[idb_get,module])}}else{add_jsmodule(module,source)}}else{console.log("bizarre",module)} 5347 loop()} 5348 var loop=$B.loop=function(){if($B.tasks.length==0){ 5349 if($B.idb_cx && ! $B.idb_cx.$closed){var db=$B.idb_cx.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules") 5350 while($B.outdated.length > 0){var module=$B.outdated.pop(),req=store.delete(module) 5351 req.onsuccess=function(event){if($B.debug > 1){console.info("delete outdated",module)} 5352 document.dispatchEvent(new CustomEvent('precompile',{detail:'remove outdated '+module+ 5353 ' from cache'}))}} 5354 document.dispatchEvent(new CustomEvent('precompile',{detail:"close"})) 5355 $B.idb_cx.result.close() 5356 $B.idb_cx.$closed=true} 5357 return} 5358 var task=$B.tasks.shift(),func=task[0],args=task.slice(1) 5359 if(func=="execute"){try{var script=task[1],script_id=script.__name__.replace(/\./g,"_"),module=$B.module.$factory(script.__name__) 5360 module.$src=script.$src 5361 module.__file__=script.__file__ 5362 $B.imported[script_id]=module 5363 new Function("$locals_"+script_id,script.js)(module)}catch(err){ 5364 if(err.__class__===undefined){console.log('Javascript error',err) 5365 if($B.is_recursion_error(err)){err=_b_.RecursionError.$factory("too much recursion")}else{$B.print_stack() 5366 err=_b_.RuntimeError.$factory(err+'')}} 5367 if($B.debug > 1){console.log("handle error",err.__class__,err.args,err.$stack) 5368 console.log($B.frames_stack.slice())} 5369 $B.handle_error(err)} 5370 loop()}else{ 5371 try{func.apply(null,args)}catch(err){$B.handle_error(err)}}} 5372 $B.tasks=[] 5373 $B.has_indexedDB=self.indexedDB !==undefined 5374 $B.handle_error=function(err){ 5375 if($B.debug > 1){console.log("handle error",err.__class__,err.args)} 5376 if(err.__class__ !==undefined){var name=$B.class_name(err),trace=$B.$getattr(err,'info') 5377 if(name=='SyntaxError' ||name=='IndentationError'){var offset=err.args[3] 5378 trace+='\n '+' '.repeat(offset)+'^'+ 5379 '\n'+name+': '+err.args[0]}else{trace+='\n'+name 5380 if(err.args[0]&& err.args[0]!==_b_.None){trace+=': '+_b_.str.$factory(err.args[0])}}}else{console.log(err) 5381 trace=err+""} 5382 try{$B.$getattr($B.stderr,'write')(trace) 5383 try{$B.$getattr($B.stderr,'flush')()}catch(err){console.log(err)}}catch(print_exc_err){console.log(trace)} 5384 throw err} 5385 function required_stdlib_imports(imports,start){ 5386 var nb_added=0 5387 start=start ||0 5388 for(var i=start;i < imports.length;i++){var module=imports[i] 5389 if($B.imported.hasOwnProperty(module)){continue} 5390 var mod_obj=$B.VFS[module] 5391 if(mod_obj===undefined){console.log("undef",module)} 5392 if(mod_obj[0]==".py"){var subimports=mod_obj[2] 5393 subimports.forEach(function(subimport){if(!$B.imported.hasOwnProperty(subimport)&& 5394 imports.indexOf(subimport)==-1){if($B.VFS.hasOwnProperty(subimport)){imports.push(subimport) 5395 nb_added++}}})}} 5396 if(nb_added){required_stdlib_imports(imports,imports.length-nb_added)} 5397 return imports}})(__BRYTHON__) 5398 ; 5399 __BRYTHON__.builtins.object=(function($B){var _b_=$B.builtins 5400 var object={ 5401 $infos:{__name__:"object"},$is_class:true,$native:true} 5402 var opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"] 5403 var opsigns=["+","-","*","/","//","%","**","<<",">>","&","^","|"] 5404 object.__delattr__=function(self,attr){attr=$B.from_alias(attr) 5405 if(self.__dict__ && self.__dict__.$string_dict && 5406 self.__dict__.$string_dict[attr]!==undefined){delete self.__dict__.$string_dict[attr] 5407 return _b_.None}else if(self.__dict__===undefined && self[attr]!==undefined){delete self[attr] 5408 return _b_.None}else{ 5409 var klass=self.__class__ 5410 if(klass){var prop=$B.$getattr(klass,attr) 5411 if(prop.__class__===_b_.property){if(prop.__delete__ !==undefined){prop.__delete__(self) 5412 return _b_.None}}}} 5413 throw _b_.AttributeError.$factory(attr)} 5414 object.__dir__=function(self){var objects 5415 if(self.$is_class){objects=[self].concat(self.__mro__)}else{var klass=self.__class__ ||$B.get_class(self) 5416 objects=[self,klass].concat(klass.__mro__)} 5417 var res=[] 5418 for(var i=0,len=objects.length;i < len;i++){for(var attr in objects[i]){if(attr.charAt(0)=="$"){if(attr.charAt(1)=="$"){ 5419 res.push(attr.substr(2))} 5420 continue} 5421 if(! isNaN(parseInt(attr.charAt(0)))){ 5422 continue} 5423 if(attr=="__mro__"){continue} 5424 res.push(attr)}} 5425 if(self.__dict__){for(var attr in self.__dict__.$string_dict){if(attr.substr(0,2)=="$$"){res.push(attr.substr(2))} 5426 else if(attr.charAt(0)!="$"){res.push(attr)}}} 5427 res=_b_.list.$factory(_b_.set.$factory(res)) 5428 _b_.list.sort(res) 5429 return res} 5430 object.__eq__=function(self,other){ 5431 if(self===other){return true} 5432 return _b_.NotImplemented} 5433 object.__format__=function(){var $=$B.args("__format__",2,{self:null,spec:null},["self","spec"],arguments,{},null,null) 5434 if($.spec !==""){throw _b_.TypeError.$factory( 5435 "non-empty format string passed to object.__format__")} 5436 return _b_.getattr($.self,"__str__")()} 5437 object.__ge__=function(){return _b_.NotImplemented} 5438 object.__getattribute__=function(obj,attr){var klass=obj.__class__ ||$B.get_class(obj),is_own_class_instance_method=false 5439 var $test=false 5440 if($test){console.log("attr",attr,"de",obj,"klass",klass)} 5441 if(attr==="__class__"){return klass} 5442 var res=obj[attr] 5443 if(Array.isArray(obj)&& Array.prototype[attr]!==undefined){ 5444 res=undefined} 5445 if(res===undefined && obj.__dict__){var dict=obj.__dict__ 5446 if(dict.$string_dict.hasOwnProperty(attr)){if($test){console.log("__dict__ hasOwnProperty",attr,dict.$string_dict[attr])} 5447 return dict.$string_dict[attr][0]}} 5448 if(res===undefined){ 5449 function check(obj,kl,attr){var v=kl[attr] 5450 if(v !==undefined){return v}} 5451 res=check(obj,klass,attr) 5452 if(res===undefined){var mro=klass.__mro__ 5453 for(var i=0,len=mro.length;i < len;i++){res=check(obj,mro[i],attr) 5454 if(res !==undefined){if($test){console.log("found in",mro[i])} 5455 break}}}else{if(res.__class__ !==$B.method && res.__get__===undefined){ 5456 is_own_class_instance_method=true}}}else{if(res.__set__===undefined){ 5457 return res}} 5458 if(res !==undefined){if($test){console.log(res)} 5459 if(res.__class__===_b_.property){return res.__get__(res,obj,klass)} 5460 if(res.__class__===$B.method){if($test){console.log("res is method")} 5461 if(res.__get__===undefined){console.log("bizarre",obj,attr,res)} 5462 return res.__get__(obj,klass)} 5463 var get=res.__get__ 5464 if(get===undefined && res.__class__){var get=res.__class__.__get__ 5465 for(var i=0;i < res.__class__.__mro__.length && 5466 get===undefined;i++){get=res.__class__.__mro__[i].__get__}} 5467 if($test){console.log("get",get)} 5468 var __get__=get===undefined ? null : 5469 $B.$getattr(res,"__get__",null) 5470 if($test){console.log("__get__",__get__)} 5471 if(__get__ !==null){try{return __get__.apply(null,[obj,klass])} 5472 catch(err){console.log('error in get.apply',err) 5473 console.log("get attr",attr,"of",obj) 5474 console.log(__get__+'') 5475 throw err}} 5476 if(typeof res=="object"){if(__get__ &&(typeof __get__=="function")){get_func=function(x,y){return __get__.apply(x,[y,klass.$factory])}}} 5477 if(__get__===null &&(typeof res=="function")){__get__=function(x){return x}} 5478 if(__get__ !==null){ 5479 res.__name__=attr 5480 if(attr=="__new__"){res.$type="staticmethod"} 5481 var res1=__get__.apply(null,[res,obj,klass]) 5482 if($test){console.log("res",res,"res1",res1)} 5483 if(typeof res1=="function"){ 5484 if(res1.__class__===$B.method){return res} 5485 if(res.$type=="staticmethod"){return res} 5486 else{var self=res.__class__===$B.method ? klass :obj,method=function(){var args=[self] 5487 for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} 5488 return res.apply(this,args)} 5489 method.__class__=$B.method 5490 method.__get__=function(obj,cls){var clmethod=res.bind(null,cls) 5491 clmethod.__class__=$B.method 5492 clmethod.$infos={__self__:cls,__func__:res,__name__:res.$infos.__name__,__qualname__:cls.$infos.__name__+"."+ 5493 res.$infos.__name__} 5494 return clmethod} 5495 method.__get__.__class__=$B.method_wrapper 5496 method.__get__.$infos=res.$infos 5497 if(klass.$infos===undefined){console.log("no $infos",klass) 5498 console.log($B.last($B.frames_stack))} 5499 method.$infos={__self__:self,__func__:res,__name__:attr,__qualname__:klass.$infos.__name__+"."+attr} 5500 if($test){console.log("return method",method)} 5501 if(is_own_class_instance_method){obj.$method_cache=obj.$method_cache ||{} 5502 obj.$method_cache[attr]=[method,res]} 5503 return method}}else{ 5504 return res1}} 5505 return res}else{ 5506 var _ga=obj["__getattr__"] 5507 if(_ga===undefined){_ga=klass["__getattr__"] 5508 if(_ga===undefined){var mro=klass.__mro__ 5509 for(var i=0,len=mro.length;i < len;i++){_ga=mro[i]["__getattr__"] 5510 if(_ga !==undefined){break}}}} 5511 if(_ga !==undefined){if(klass===$B.module){return _ga(attr)} 5512 return _ga(obj,attr)}else{throw _b_.AttributeError.$factory(attr)}}} 5513 object.__gt__=function(){return _b_.NotImplemented} 5514 object.__hash__=function(self){var hash=self.__hashvalue__ 5515 if(hash !==undefined){return hash} 5516 return self.__hashvalue__=$B.$py_next_hash--} 5517 object.__init__=function(){if(arguments.length==0){throw _b_.TypeError.$factory("descriptor '__init__' of 'object' "+ 5518 "object needs an argument")} 5519 return _b_.None} 5520 object.__init_subclass__=function(){ 5521 var $=$B.args("__init_subclass__",0,{},[],arguments,{},null,null) 5522 return _b_.None} 5523 object.__init_subclass__.$type="staticmethod" 5524 object.__le__=function(){return _b_.NotImplemented} 5525 object.__lt__=function(){return _b_.NotImplemented} 5526 object.__mro__=[] 5527 object.__new__=function(cls,...args){if(cls===undefined){throw _b_.TypeError.$factory("object.__new__(): not enough arguments")} 5528 var init_func=$B.$getattr(cls,"__init__") 5529 if(init_func===object.__init__){if(args.length > 0){throw _b_.TypeError.$factory("object() takes no parameters")}} 5530 return{ 5531 __class__ :cls,__dict__:$B.empty_dict()}} 5532 object.__ne__=function(self,other){ 5533 if(self===other){return false} 5534 var eq=$B.$getattr(self,"__eq__",null) 5535 if(eq !==null){var res=$B.$call(eq)(other) 5536 if(res===_b_.NotImplemented){return res} 5537 return ! $B.$bool(res)} 5538 return _b_.NotImplemented} 5539 object.__reduce__=function(self){function _reconstructor(cls){return $B.$call(cls)()} 5540 _reconstructor.$infos={__qualname__:"_reconstructor"} 5541 var res=[_reconstructor] 5542 res.push(_b_.tuple.$factory([self.__class__]. 5543 concat(self.__class__.__mro__))) 5544 var d=$B.empty_dict() 5545 for(var attr in self.__dict__.$string_dict){_b_.dict.$setitem(d.$string_dict,attr,self.__dict__.$string_dict[attr][0])} 5546 console.log("object.__reduce__, d",d) 5547 res.push(d) 5548 return _b_.tuple.$factory(res)} 5549 function __newobj__(cls){return $B.$getattr(cls,"__new__").apply(null,arguments)} 5550 __newobj__.$infos={__name__:"__newobj__",__qualname__:"__newobj__"} 5551 _b_.__newobj__=__newobj__ 5552 object.__reduce_ex__=function(self){var res=[__newobj__] 5553 var arg2=_b_.tuple.$factory([self.__class__]) 5554 if(Array.isArray(self)){self.forEach(function(item){arg2.push(item)})} 5555 res.push(arg2) 5556 var d=$B.empty_dict(),nb=0 5557 if(self.__dict__===undefined){throw _b_.TypeError.$factory("cannot pickle '"+ 5558 $B.class_name(self)+"' object")} 5559 for(var attr in self.__dict__.$string_dict){if(attr=="__class__" ||attr.startsWith("$")){continue} 5560 _b_.dict.$setitem(d,attr,self.__dict__.$string_dict[attr][0]) 5561 nb++} 5562 if(nb==0){d=_b_.None} 5563 res.push(d) 5564 res.push(_b_.None) 5565 return _b_.tuple.$factory(res)} 5566 object.__repr__=function(self){if(self===object){return "<class 'object'>"} 5567 if(self.__class__===_b_.type){return "<class '"+self.__name__+"'>"} 5568 var module=self.__class__.$infos.__module__ 5569 if(module !==undefined && !module.startsWith("$")&& 5570 module !=="builtins"){return "<"+self.__class__.$infos.__module__+"."+ 5571 $B.class_name(self)+" object>"}else{return "<"+$B.class_name(self)+" object>"}} 5572 object.__setattr__=function(self,attr,val){if(val===undefined){ 5573 throw _b_.TypeError.$factory( 5574 "can't set attributes of built-in/extension type 'object'")}else if(self.__class__===object){ 5575 if(object[attr]===undefined){throw _b_.AttributeError.$factory( 5576 "'object' object has no attribute '"+attr+"'")}else{throw _b_.AttributeError.$factory( 5577 "'object' object attribute '"+attr+"' is read-only")}} 5578 if($B.aliased_names[attr]){attr="$$"+attr} 5579 if(self.__dict__){_b_.dict.$setitem(self.__dict__,attr,val)}else{ 5580 self[attr]=val} 5581 return _b_.None} 5582 object.__setattr__.__get__=function(obj){return function(attr,val){object.__setattr__(obj,attr,val)}} 5583 object.__setattr__.__str__=function(){return "method object.setattr"} 5584 object.__str__=function(self){var repr_func=$B.$getattr(self,"__repr__") 5585 return $B.$call(repr_func)()} 5586 object.__subclasshook__=function(){return _b_.NotImplemented} 5587 object.$factory=function(){var res={__class__:object},args=[res].concat(Array.prototype.slice.call(arguments)) 5588 object.__init__.apply(null,args) 5589 return res} 5590 $B.set_func_names(object,"builtins") 5591 $B.make_class=function(name,factory){ 5592 var A={__class__:_b_.type,__mro__:[object],$infos:{__name__:name},$is_class:true} 5593 A.$factory=factory 5594 return A} 5595 return object})(__BRYTHON__) 5596 ; 5597 ;(function($B){var _b_=$B.builtins 5598 $B.$class_constructor=function(class_name,class_obj,bases,parents_names,kwargs){bases=bases ||[] 5599 var metaclass 5600 var module=class_obj.__module__ 5601 if(module===undefined){ 5602 module=class_obj.__module__=$B.last($B.frames_stack)[2]} 5603 for(var i=0;i < bases.length;i++){if(bases[i]===undefined){ 5604 $B.line_info=class_obj.$def_line 5605 throw _b_.NameError.$factory("name '"+parents_names[i]+ 5606 "' is not defined")}} 5607 var extra_kwargs={},prepare_kwargs={} 5608 if(kwargs){for(var i=0;i < kwargs.length;i++){var key=kwargs[i][0],val=kwargs[i][1] 5609 if(key=="metaclass"){ 5610 metaclass=val}else{ 5611 extra_kwargs[key]=val} 5612 prepare_kwargs[key]=val}} 5613 var mro0=class_obj 5614 if(class_obj.__eq__ !==undefined && class_obj.__hash__===undefined){class_obj.__hash__=_b_.None} 5615 var orig_bases=bases.slice(),use_mro_entries=false 5616 for(var i=0;i < bases.length;i++){if(bases[i]===undefined || 5617 (bases[i].__mro__===undefined)){var mro_entries=$B.$getattr(bases[i],"__mro_entries__",_b_.None) 5618 if(mro_entries !==_b_.None){var entries=_b_.list.$factory(mro_entries(bases)) 5619 bases.splice(i,1,...entries) 5620 use_mro_entries=true 5621 i-- 5622 continue}}} 5623 if(metaclass===undefined){if(bases && bases.length > 0){metaclass=bases[0].__class__ 5624 if(metaclass===undefined){ 5625 if(typeof bases[0]=="function"){if(bases.length !=1){throw _b_.TypeError.$factory("A Brython class "+ 5626 "can inherit at most 1 Javascript constructor")} 5627 metaclass=bases[0].__class__=$B.JSMeta 5628 $B.set_func_names(bases[0],module)}else{throw _b_.TypeError.$factory("Argument of "+class_name+ 5629 "is not a class (type '"+$B.class_name(bases[0])+ 5630 "')")}} 5631 for(var i=1;i < bases.length;i++){var mc=bases[i].__class__ 5632 if(mc===metaclass ||_b_.issubclass(metaclass,mc)){}else if(_b_.issubclass(mc,metaclass)){metaclass=mc}else if(metaclass.__bases__ && 5633 metaclass.__bases__.indexOf(mc)==-1){throw _b_.TypeError.$factory("metaclass conflict: the "+ 5634 "metaclass of a derived class must be a (non-"+ 5635 "strict) subclass of the metaclasses of all its bases")}}}else{metaclass=_b_.type}} 5636 var prepare=$B.$getattr(metaclass,"__prepare__",_b_.None),cl_dict=$B.$call(prepare)(class_name,bases) 5637 if(cl_dict.__class__ !==_b_.dict){set_class_item=$B.$getattr(cl_dict,"__setitem__")}else{set_class_item=function(attr,value){cl_dict.$string_dict[attr]=[value,cl_dict.$order++]}} 5638 for(var attr in class_obj){if(attr=="__annotations__"){if(cl_dict.$string_dict[attr]===undefined){cl_dict.$string_dict[attr]=[$B.empty_dict(),cl_dict.$order++]} 5639 for(var key in class_obj[attr].$string_dict){$B.$setitem(cl_dict.$string_dict[attr][0],key,class_obj[attr].$string_dict[key][0])}}else{if(attr.charAt(0)!="$" ||attr.substr(0,2)=="$$"){set_class_item(attr,class_obj[attr])}}} 5640 if(use_mro_entries){set_class_item("__orig_bases__",_b_.tuple.$factory(orig_bases))} 5641 var class_dict={__bases__:bases,__class__:metaclass,__dict__:cl_dict} 5642 if(cl_dict.__class__===_b_.dict){for(var key in cl_dict.$string_dict){class_dict[key]=cl_dict.$string_dict[key][0]}}else{var get_class_item=$B.$getattr(cl_dict,"__getitem__") 5643 var it=_b_.iter(cl_dict) 5644 while(true){try{var key=_b_.next(it) 5645 class_dict[key]=get_class_item(key)}catch(err){break}}} 5646 class_dict.__mro__=_b_.type.mro(class_dict).slice(1) 5647 var is_instanciable=true,non_abstract_methods={},abstract_methods={},mro=[class_dict].concat(class_dict.__mro__) 5648 for(var i=0;i < mro.length;i++){var kdict=i==0 ? mro0 :mro[i] 5649 for(var attr in kdict){if(non_abstract_methods[attr]){continue} 5650 var v=kdict[attr] 5651 if(typeof v=="function"){if(v.__isabstractmethod__===true || 5652 (v.$attrs && v.$attrs.__isabstractmethod__)){is_instanciable=false 5653 abstract_methods[attr]=true}else{non_abstract_methods[attr]=true}}}} 5654 var _slots=class_obj.__slots__ 5655 if(_slots !==undefined){if(typeof _slots=="string"){_slots=[_slots]}else{_slots=_b_.list.$factory(_slots)} 5656 cl_dict.__slots__=_slots} 5657 for(var i=0;i < mro.length-1;i++){for(var attr in mro[i]){if(attr=="__setattr__"){cl_dict.$has_setattr=true 5658 break}else if(mro[i][attr]){if(mro[i][attr].__get__ ||(mro[i][attr].__class__ && 5659 mro[i][attr].__class__.__get__)){ 5660 cl_dict.$has_setattr=true 5661 break}}}} 5662 var meta_new=_b_.type.__getattribute__(metaclass,"__new__") 5663 var kls=meta_new(metaclass,class_name,bases,cl_dict) 5664 kls.__module__=module 5665 kls.$infos={__module__:module,__name__:$B.from_alias(class_name),__qualname__:class_obj.$qualname} 5666 kls.$subclasses=[] 5667 for(var attr in class_obj){if(attr.charAt(0)!="$" ||attr.substr(0,2)=="$$"){if(typeof class_obj[attr]=="function"){class_obj[attr].$infos.$class=kls}}} 5668 if(kls.__class__===metaclass){ 5669 var meta_init=_b_.type.__getattribute__(metaclass,"__init__") 5670 meta_init(kls,class_name,bases,cl_dict)} 5671 for(var i=0;i < bases.length;i++){bases[i].$subclasses=bases[i].$subclasses ||[] 5672 bases[i].$subclasses.push(kls)} 5673 var sup=_b_.$$super.$factory(kls,kls) 5674 var init_subclass=_b_.$$super.__getattribute__(sup,"__init_subclass__") 5675 init_subclass({$nat:"kw",kw:extra_kwargs}) 5676 if(!is_instanciable){function nofactory(){throw _b_.TypeError.$factory("Can't instantiate abstract class "+ 5677 "interface with abstract methods "+ 5678 Object.keys(abstract_methods).join(", "))} 5679 kls.$factory=nofactory} 5680 kls.__qualname__=class_name.replace("$$","") 5681 return kls} 5682 var type=$B.make_class("type",function(obj,bases,cl_dict){if(arguments.length==1){if(obj===undefined){return $B.UndefinedClass} 5683 return obj.__class__ ||$B.get_class(obj)} 5684 return type.__new__(type,obj,bases,cl_dict)} 5685 ) 5686 type.__call__=function(){var extra_args=[],klass=arguments[0] 5687 for(var i=1,len=arguments.length;i < len;i++){extra_args.push(arguments[i])} 5688 var new_func=_b_.type.__getattribute__(klass,"__new__") 5689 var instance=new_func.apply(null,arguments) 5690 if(instance.__class__===klass){ 5691 var init_func=_b_.type.__getattribute__(klass,"__init__") 5692 if(init_func !==_b_.object.__init__){ 5693 var args=[instance].concat(extra_args) 5694 init_func.apply(null,args)}} 5695 return instance} 5696 type.__class__=type 5697 type.__format__=function(klass,fmt_spec){ 5698 return _b_.str.$factory(klass)} 5699 type.__getattribute__=function(klass,attr){switch(attr){case "__annotations__": 5700 var mro=[klass].concat(klass.__mro__),res 5701 for(var i=0,len=mro.length;i < len;i++){if(mro[i].__dict__){var ann=mro[i].__dict__.$string_dict.__annotations__[0] 5702 if(ann){if(res===undefined){res=ann}else if(res.__class__===_b_.dict && 5703 ann.__class__===_b_.dict){ 5704 for(var key in ann.$string_dict){res.$string_dict[key]=ann.$string_dict[key]}}}}} 5705 if(res===undefined){res=$B.empty_dict()} 5706 return res 5707 case "__bases__": 5708 var res=klass.__bases__ ||_b_.tuple.$factory() 5709 res.__class__=_b_.tuple 5710 if(res.length==0){res.push(_b_.object)} 5711 return res 5712 case "__class__": 5713 return klass.__class__ 5714 case "__doc__": 5715 return klass.__doc__ ||_b_.None 5716 case "__setattr__": 5717 if(klass["__setattr__"]!==undefined){var func=klass["__setattr__"]}else{var func=function(obj,key,value){obj[key]=value}} 5718 return method_wrapper.$factory(attr,klass,func) 5719 case "__delattr__": 5720 if(klass["__delattr__"]!==undefined){return klass["__delattr__"]} 5721 return method_wrapper.$factory(attr,klass,function(key){delete klass[key]})} 5722 var res=klass[attr] 5723 var $test=false 5724 if($test){console.log("attr",attr,"of",klass,res,res+"")} 5725 if(res===undefined && klass.__slots__ && 5726 klass.__slots__.indexOf(attr)>-1){return member_descriptor.$factory(attr,klass)} 5727 if(klass.__class__ && 5728 klass.__class__[attr]&& 5729 klass.__class__[attr].__get__ && 5730 klass.__class__[attr].__set__){ 5731 if($test){console.log("data descriptor")} 5732 return klass.__class__[attr].__get__(klass)} 5733 if(res===undefined){ 5734 var v=klass[attr] 5735 if(v===undefined){var mro=klass.__mro__ 5736 if(mro===undefined){console.log("pas de mro pour",klass)} 5737 for(var i=0;i < mro.length;i++){var v=mro[i][attr] 5738 if(v !==undefined){res=v 5739 break}}}else{res=v} 5740 if(res===undefined){ 5741 var meta=klass.__class__ ||$B.get_class(klass),res=meta[attr] 5742 if($test){console.log("search in meta",meta,res)} 5743 if(res===undefined){var meta_mro=meta.__mro__ 5744 for(var i=0;i < meta_mro.length;i++){var res=meta_mro[i][attr] 5745 if(res !==undefined){break}}} 5746 if(res !==undefined){if($test){console.log("found in meta",res,typeof res)} 5747 if(res.__class__===_b_.property){return res.fget(klass)} 5748 if(typeof res=="function"){ 5749 var meta_method=res.bind(null,klass) 5750 meta_method.__class__=$B.method 5751 meta_method.$infos={__self__:klass,__func__:res,__name__:attr,__qualname__:klass.$infos.__name__+"."+attr,__module__:res.$infos ? res.$infos.__module__ :""} 5752 return meta_method}} 5753 if(res===undefined){ 5754 var getattr=meta.__getattr__ 5755 if(getattr===undefined){for(var i=0;i < meta_mro.length;i++){if(meta_mro[i].__getattr__ !==undefined){getattr=meta_mro[i].__getattr__ 5756 break}}} 5757 if(getattr !==undefined){return getattr(klass,attr)}}}} 5758 if(res !==undefined){if($test){console.log("res",res)} 5759 if(res.__class__===_b_.property){return res} 5760 if(res.__get__){if(res.__class__===method){var result=res.__get__(res.__func__,klass) 5761 result.$infos={__func__:res,__name__:res.$infos.__name__,__qualname__:klass.$infos.__name__+"."+res.$infos.__name__,__self__:klass}}else{result=res.__get__(klass)} 5762 return result}else if(res.__class__ && res.__class__.__get__){ 5763 if(!(attr.startsWith("__")&& attr.endsWith("__"))){return res.__class__.__get__(res,_b_.None,klass)}} 5764 if(typeof res=="function"){ 5765 if(res.$infos===undefined && $B.debug > 1){console.log("warning: no attribute $infos for",res,"klass",klass,"attr",attr)} 5766 if($test){console.log("res is function",res)} 5767 if(attr=="__new__"){res.$type="staticmethod"} 5768 if(attr=="__class_getitem__" && res.__class__ !==$B.method){res=_b_.classmethod.$factory(res)} 5769 if(attr=="__init_subclass__"){res=_b_.classmethod.$factory(res)} 5770 if(res.__class__===$B.method){return res.__get__(null,klass)}else{if($test){console.log("return res",res)} 5771 return res}}else{return res}}} 5772 type.__hash__=function(cls){return _b_.hash(cls)} 5773 type.__init__=function(){} 5774 type.__init_subclass__=function(){ 5775 var $=$B.args("__init_subclass__",1,{},[],arguments,{},"args","kwargs") 5776 if($.kwargs !==undefined){if($.kwargs.__class__ !==_b_.dict || 5777 Object.keys($.kwargs.$string_dict).length > 0){throw _b_.TypeError.$factory( 5778 "__init_subclass__() takes no keyword arguments")}} 5779 return _b_.None} 5780 type.__instancecheck__=function(cls,instance){var kl=instance.__class__ ||$B.get_class(instance) 5781 if(kl===cls){return true} 5782 else{for(var i=0;i < kl.__mro__.length;i++){if(kl.__mro__[i]===cls){return true}}} 5783 return false} 5784 type.__instancecheck__.$type="staticmethod" 5785 type.__name__={__get__:function(self){return self.$infos.__name__},__set__:function(self,value){self.$infos.__name__=value},__str__:function(self){return "type"},__eq__:function(self,other){return self.$infos.__name__==other}} 5786 type.__new__=function(meta,name,bases,cl_dict){ 5787 var module=cl_dict.$string_dict.__module__ 5788 if(module){module=module[0]} 5789 var class_dict={__class__ :meta,__bases__ :bases,__dict__ :cl_dict,$infos:{__name__:name.replace("$$",""),__module__:module},$is_class:true,$has_setattr:cl_dict.$has_setattr} 5790 class_dict.__mro__=type.mro(class_dict).slice(1) 5791 var items=$B.dict_to_list(cl_dict) 5792 for(var i=0;i < items.length;i++){var key=$B.to_alias(items[i][0]),v=items[i][1] 5793 if(key==="__module__"){continue} 5794 if(v===undefined){continue} 5795 class_dict[key]=v 5796 if(v.__class__){ 5797 var set_name=$B.$getattr(v.__class__,"__set_name__",_b_.None) 5798 if(set_name !==_b_.None){set_name(v,class_dict,key)}} 5799 if(typeof v=="function"){if(v.$infos===undefined){console.log("type new",v,v+"") 5800 console.log($B.frames_stack.slice())} 5801 v.$infos.$class=class_dict 5802 v.$infos.__qualname__=name+'.'+v.$infos.__name__ 5803 if(v.$infos.$defaults){ 5804 var $defaults=v.$infos.$defaults 5805 $B.Function.__setattr__(v,"__defaults__",$defaults)}}} 5806 return class_dict} 5807 type.__repr__=type.__str__=function(kls){if(kls.$infos===undefined){console.log("no $infos",kls)} 5808 var qualname=kls.$infos.__qualname__ 5809 if(kls.$infos.__module__ && 5810 kls.$infos.__module__ !="builtins" && 5811 !kls.$infos.__module__.startsWith("$")){qualname=kls.$infos.__module__+"."+qualname} 5812 return "<class '"+qualname+"'>"} 5813 type.__prepare__=function(){return $B.empty_dict()} 5814 type.__qualname__={__get__:function(self){return self.$infos.__qualname__ ||self.$infos.__name__},__set__:function(self,value){self.$infos.__qualname__=value},__str__:function(self){console.log("type.__qualname__")},__eq__:function(self,other){return self.$infos.__qualname__==other}} 5815 type.mro=function(cls){ 5816 var bases=cls.__bases__,seqs=[],pos1=0 5817 for(var i=0;i < bases.length;i++){ 5818 if(bases[i]===_b_.str){bases[i]=$B.StringSubclass} 5819 var bmro=[],pos=0 5820 if(bases[i]===undefined || 5821 bases[i].__mro__===undefined){if(bases[i].__class__===undefined){ 5822 return[_b_.object]}else{throw _b_.TypeError.$factory( 5823 "Object passed as base class is not a class")}} 5824 bmro[pos++]=bases[i] 5825 var _tmp=bases[i].__mro__ 5826 if(_tmp[0]===bases[i]){_tmp.splice(0,1)} 5827 for(var k=0;k < _tmp.length;k++){bmro[pos++]=_tmp[k]} 5828 seqs[pos1++]=bmro} 5829 if(bases.indexOf(_b_.object)==-1){bases=bases.concat(_b_.tuple.$factory([_b_.object]))} 5830 seqs[pos1++]=bases.slice() 5831 var mro=[cls],mpos=1 5832 while(1){var non_empty=[],pos=0 5833 for(var i=0;i < seqs.length;i++){if(seqs[i].length > 0){non_empty[pos++]=seqs[i]}} 5834 if(non_empty.length==0){break} 5835 for(var i=0;i < non_empty.length;i++){var seq=non_empty[i],candidate=seq[0],not_head=[],pos=0 5836 for(var j=0;j < non_empty.length;j++){var s=non_empty[j] 5837 if(s.slice(1).indexOf(candidate)>-1){not_head[pos++]=s}} 5838 if(not_head.length > 0){candidate=null} 5839 else{break}} 5840 if(candidate===null){throw _b_.TypeError.$factory( 5841 "inconsistent hierarchy, no C3 MRO is possible")} 5842 mro[mpos++]=candidate 5843 for(var i=0;i < seqs.length;i++){var seq=seqs[i] 5844 if(seq[0]===candidate){ 5845 seqs[i].shift()}}} 5846 if(mro[mro.length-1]!==_b_.object){mro[mpos++]=_b_.object} 5847 return mro} 5848 type.__subclasscheck__=function(self,subclass){ 5849 var klass=self 5850 if(klass===_b_.str){klass=$B.StringSubclass}else if(klass===_b_.float){klass=$B.FloatSubclass} 5851 if(subclass.__bases__===undefined){return self===_b_.object} 5852 return subclass.__bases__.indexOf(klass)>-1} 5853 $B.set_func_names(type,"builtins") 5854 _b_.type=type 5855 var wrapper_descriptor=$B.make_class("wrapper_descriptor") 5856 $B.set_func_names(wrapper_descriptor,"builtins") 5857 type.__call__.__class__=wrapper_descriptor 5858 var $instance_creator=$B.$instance_creator=function(klass){ 5859 if(klass.$instanciable !==undefined){return function(){throw _b_.TypeError.$factory( 5860 "Can't instantiate abstract class interface "+ 5861 "with abstract methods")}} 5862 var metaclass=klass.__class__,call_func,factory 5863 if(metaclass===_b_.type &&(!klass.__bases__ ||klass.__bases__.length==0)){if(klass.hasOwnProperty("__new__")){if(klass.hasOwnProperty("__init__")){factory=function(){ 5864 var obj=klass.__new__.bind(null,klass). 5865 apply(null,arguments) 5866 klass.__init__.bind(null,obj).apply(null,arguments) 5867 return obj}}else{factory=function(){return klass.__new__.bind(null,klass). 5868 apply(null,arguments)}}}else if(klass.hasOwnProperty("__init__")){factory=function(){var obj={__class__:klass,__dict__:$B.empty_dict()} 5869 klass.__init__.bind(null,obj).apply(null,arguments) 5870 return obj}}else{factory=function(){if(arguments.length > 0){if(arguments.length==1 && arguments[0].$nat && 5871 Object.keys(arguments[0].kw).length==0){}else{throw _b_.TypeError.$factory("object() takes no parameters")}} 5872 return{__class__:klass,__dict__:$B.empty_dict()}}}}else{call_func=_b_.type.__getattribute__(metaclass,"__call__") 5873 var factory=function(){return call_func.bind(null,klass).apply(null,arguments)}} 5874 factory.__class__=$B.Function 5875 factory.$infos={__name__:klass.$infos.__name__,__module__:klass.$infos.__module__} 5876 return factory} 5877 var method_wrapper=$B.method_wrapper=$B.make_class("method_wrapper",function(attr,klass,method){var f=function(){return method.apply(null,arguments)} 5878 f.$infos={__name__:attr,__module__:klass.__module__} 5879 return f} 5880 ) 5881 method_wrapper.__str__=method_wrapper.__repr__=function(self){return "<method '"+self.$infos.__name__+"' of function object>"} 5882 var member_descriptor=$B.make_class("member_descriptor",function(attr,cls){return{__class__:member_descriptor,cls:cls,attr:attr}} 5883 ) 5884 member_descriptor.__str__=member_descriptor.__repr__=function(self){return "<member '"+self.attr+"' of '"+self.cls.$infos.__name__+ 5885 "' objects>"} 5886 $B.set_func_names(member_descriptor,"builtins") 5887 var method=$B.method=$B.make_class("method",function(func,cls){var f=function(){return $B.$call(func).bind(null,cls).apply(null,arguments)} 5888 f.__class__=method 5889 f.$infos=func.$infos 5890 return f} 5891 ) 5892 method.__eq__=function(self,other){return self.$infos !==undefined && 5893 other.$infos !==undefined && 5894 self.$infos.__func__===other.$infos.__func__ && 5895 self.$infos.__self__===other.$infos.__self__} 5896 method.__ne__=function(self,other){return ! $B.method.__eq__(self,other)} 5897 method.__get__=function(self){var f=function(){return self(arguments)} 5898 f.__class__=$B.method_wrapper 5899 f.$infos=method.$infos 5900 return f} 5901 method.__getattribute__=function(self,attr){ 5902 var infos=self.$infos 5903 if(infos && infos[attr]){if(attr=="__code__"){var res={__class__:$B.Code} 5904 for(var attr in infos.__code__){res[attr]=infos.__code__[attr]} 5905 return res}else{return infos[attr]}}else if(method.hasOwnProperty(attr)){return _b_.object.__getattribute__(self,attr)}else{ 5906 return $B.Function.__getattribute__(self.$infos.__func__,attr)}} 5907 method.__repr__=method.__str__=function(self){return "<bound method "+self.$infos.__qualname__+ 5908 " of "+_b_.str.$factory(self.$infos.__self__)+">"} 5909 method.__setattr__=function(self,key,value){ 5910 if(key=="__class__"){throw _b_.TypeError.$factory("__class__ assignment only supported "+ 5911 "for heap types or ModuleType subclasses")} 5912 throw _b_.AttributeError.$factory("'method' object has no attribute '"+ 5913 key+"'")} 5914 $B.set_func_names(method,"builtins") 5915 $B.method_descriptor=$B.make_class("method_descriptor") 5916 $B.classmethod_descriptor=$B.make_class("classmethod_descriptor") 5917 $B.GenericAlias=$B.make_class("GenericAlias",function(origin_class,items){return{ 5918 __class__:$B.GenericAlias,origin_class,items}} 5919 ) 5920 $B.GenericAlias.__args__={__get__:function(self){return $B.fast_tuple(self.items)}} 5921 $B.GenericAlias.__call__=function(self,...args){return self.origin_class.$factory.apply(null,args)} 5922 $B.GenericAlias.__eq__=function(self,other){return $B.rich_comp("__eq__",self.origin_class,other.origin_class)&& 5923 $B.rich_comp("__eq__",self.items,other.items)} 5924 $B.GenericAlias.__getitem__=function(self,item){throw _b_.TypeError.$factory("descriptor '__getitem__' for '"+ 5925 self.origin_class.$infos.__name__+"' objects doesn't apply to a '"+ 5926 $B.class_name(item)+"' object")} 5927 $B.GenericAlias.__origin__={__get__:function(self){return self.origin_class}} 5928 $B.GenericAlias.__parameters__={__get__:function(self){ 5929 return $B.fast_tuple([])}} 5930 $B.GenericAlias.__repr__=function(self){var items=self.items 5931 for(var i=0,len=items.length;i < len;i++){if(items[i]===_b_.Ellipsis){items[i]='...'}else{items[i]=items[i].$infos.__name__}} 5932 return self.origin_class.$infos.__qualname__+'['+ 5933 items.join(", ")+']'} 5934 _b_.object.__class__=type})(__BRYTHON__) 5935 ; 5936 ;(function($B){var _b_=$B.builtins,_window=self,isWebWorker=('undefined' !==typeof WorkerGlobalScope)&& 5937 ("function"===typeof importScripts)&& 5938 (navigator instanceof WorkerNavigator) 5939 $B.args=function($fname,argcount,slots,var_names,args,$dobj,extra_pos_args,extra_kw_args){ 5940 if($fname.startsWith("lambda_"+$B.lambda_magic)){$fname="<lambda>"} 5941 var has_kw_args=false,nb_pos=args.length,filled=0,extra_kw,only_positional 5942 var end_positional=var_names.indexOf("/") 5943 if(end_positional !=-1){var_names.splice(end_positional,1) 5944 only_positional=var_names.slice(0,end_positional)} 5945 if(nb_pos > 0 && args[nb_pos-1].$nat){nb_pos-- 5946 if(Object.keys(args[nb_pos].kw).length > 0){has_kw_args=true 5947 var kw_args=args[nb_pos].kw 5948 if(Array.isArray(kw_args)){var kwa=kw_args[0] 5949 for(var i=1,len=kw_args.length;i < len;i++){var kw_arg=kw_args[i] 5950 if(kw_arg.__class__===_b_.dict){for(var k in kw_arg.$numeric_dict){throw _b_.TypeError.$factory($fname+ 5951 "() keywords must be strings")} 5952 for(var k in kw_arg.$object_dict){throw _b_.TypeError.$factory($fname+ 5953 "() keywords must be strings")} 5954 for(var k in kw_arg.$string_dict){if(kwa[k]!==undefined){throw _b_.TypeError.$factory($fname+ 5955 "() got multiple values for argument '"+ 5956 k+"'")} 5957 kwa[k]=kw_arg.$string_dict[k][0]}}else{var it=_b_.iter(kw_arg),getitem=$B.$getattr(kw_arg,'__getitem__') 5958 while(true){try{var k=_b_.next(it) 5959 if(typeof k !=="string"){throw _b_.TypeError.$factory($fname+ 5960 "() keywords must be strings")} 5961 if(kwa[k]!==undefined){throw _b_.TypeError.$factory($fname+ 5962 "() got multiple values for argument '"+ 5963 k+"'")} 5964 kwa[k]=getitem(k)}catch(err){if($B.is_exc(err,[_b_.StopIteration])){break} 5965 throw err}}}} 5966 kw_args=kwa}}} 5967 if(extra_pos_args){slots[extra_pos_args]=[] 5968 slots[extra_pos_args].__class__=_b_.tuple} 5969 if(extra_kw_args){ 5970 extra_kw=$B.empty_dict()} 5971 if(nb_pos > argcount){ 5972 if(extra_pos_args===null ||extra_pos_args=="*"){ 5973 msg=$fname+"() takes "+argcount+" positional argument"+ 5974 (argcount > 1 ? "s" :"")+" but more were given" 5975 throw _b_.TypeError.$factory(msg)}else{ 5976 for(var i=argcount;i < nb_pos;i++){slots[extra_pos_args].push(args[i])} 5977 nb_pos=argcount}} 5978 for(var i=0;i < nb_pos;i++){slots[var_names[i]]=args[i] 5979 filled++} 5980 if(filled==argcount && argcount===var_names.length && 5981 ! has_kw_args){if(extra_kw_args){slots[extra_kw_args]=extra_kw} 5982 return slots} 5983 if(has_kw_args){for(var key in kw_args){var value=kw_args[key],key1=$B.to_alias(key) 5984 if(slots[key1]===undefined){ 5985 if(extra_kw_args){ 5986 if(key.substr(0,2)=="$$"){key=key.substr(2)} 5987 extra_kw.$string_dict[key]=[value,extra_kw.$order++]}else{throw _b_.TypeError.$factory($fname+ 5988 "() got an unexpected keyword argument '"+key+"'")}}else if(slots[key1]!==null){ 5989 throw _b_.TypeError.$factory($fname+ 5990 "() got multiple values for argument '"+key+"'")}else if(only_positional && only_positional.indexOf(key1)>-1){throw _b_.TypeError.$factory($fname+"() got an "+ 5991 "unexpected keyword argument '"+key+"'")}else{ 5992 slots[key1]=value}}} 5993 var missing=[] 5994 for(var attr in slots){if(slots[attr]===null){if($dobj[attr]!==undefined){slots[attr]=$dobj[attr]} 5995 else{missing.push("'"+attr+"'")}}} 5996 if(missing.length > 0){if(missing.length==1){throw _b_.TypeError.$factory($fname+ 5997 " missing 1 positional argument: "+missing[0])}else{var msg=$fname+" missing "+missing.length+ 5998 " positional arguments: " 5999 msg+=missing.join(" and ") 6000 throw _b_.TypeError.$factory(msg)}} 6001 if(extra_kw_args){slots[extra_kw_args]=extra_kw} 6002 return slots} 6003 $B.wrong_nb_args=function(name,received,expected,positional){if(received < expected){var missing=expected-received 6004 throw _b_.TypeError.$factory(name+"() missing "+missing+ 6005 " positional argument"+(missing > 1 ? "s" :"")+": "+ 6006 positional.slice(received))}else{throw _b_.TypeError.$factory(name+"() takes "+expected+ 6007 " positional argument"+(expected > 1 ? "s" :"")+ 6008 " but more were given")}} 6009 $B.get_class=function(obj){ 6010 if(obj===null){return $B.$NoneDict} 6011 if(obj===undefined){return $B.UndefinedClass} 6012 var klass=obj.__class__ 6013 if(klass===undefined){switch(typeof obj){case "number": 6014 if(obj % 1===0){ 6015 return _b_.int} 6016 return _b_.float 6017 case "string": 6018 return _b_.str 6019 case "boolean": 6020 return _b_.bool 6021 case "function": 6022 if(obj.$is_js_func){ 6023 return $B.JSObj} 6024 obj.__class__=$B.Function 6025 return $B.Function 6026 case "object": 6027 if(Array.isArray(obj)){if(Object.getPrototypeOf(obj)===Array.prototype){obj.__class__=_b_.list 6028 return _b_.list}}else if(obj.constructor===Number){return _b_.float}else if(typeof Node !=="undefined" 6029 && obj instanceof Node){return $B.DOMNode} 6030 break}} 6031 if(klass===undefined){return $B.JSObj} 6032 return klass} 6033 $B.class_name=function(obj){var klass=$B.get_class(obj) 6034 if(klass===$B.JSObj){return 'Javascript '+obj.constructor.name}else{return klass.$infos.__name__}} 6035 $B.$list_comp=function(items){ 6036 var ix=$B.UUID(),py="x"+ix+" = []\n",indent=0 6037 for(var i=1,len=items.length;i < len;i++){var item=items[i].replace(/\s+$/,"").replace(/\n/g,"") 6038 py+=" ".repeat(indent)+item+":\n" 6039 indent+=4} 6040 py+=" ".repeat(indent) 6041 py+="x"+ix+".append("+items[0]+")\n" 6042 return[py,ix]} 6043 $B.$dict_comp=function(module_name,parent_scope,items,line_num){ 6044 var ix=$B.UUID(),res="comp_result_"+$B.lambda_magic+ix,py=res+" = {}\n", 6045 indent=0 6046 for(var i=1,len=items.length;i < len;i++){var item=items[i].replace(/\s+$/,"").replace(/\n/g,"") 6047 py+=" ".repeat(indent)+item+":\n" 6048 indent++} 6049 py+=" ".repeat(indent)+res+".update({"+items[0]+"})" 6050 var line_info=line_num+','+module_name 6051 var dictcomp_name="dc"+ix,root=$B.py2js( 6052 {src:py,is_comp:true,line_info:line_info},module_name,dictcomp_name,parent_scope,line_num),outer_expr=root.outermost_expr.to_js(),js=root.to_js() 6053 js+='\nreturn '+res+'\n' 6054 js="(function(expr){"+js+"})("+outer_expr+")" 6055 $B.clear_ns(dictcomp_name) 6056 delete $B.$py_src[dictcomp_name] 6057 return js} 6058 $B.$gen_expr=function(module_name,parent_scope,items,line_num,set_comp){ 6059 var ix=$B.UUID(),genexpr_name=(set_comp ? "set_comp"+$B.lambda_magic :"__ge")+ix,py=`def ${genexpr_name}(expr):\n`, 6060 indent=1 6061 for(var i=1,len=items.length;i < len;i++){var item=items[i].replace(/\s+$/,"").replace(/\n/g,"") 6062 py+=" ".repeat(indent)+item+":\n" 6063 indent+=4} 6064 py+=" ".repeat(indent) 6065 py+="yield ("+items[0]+")" 6066 var line_info=line_num+','+module_name 6067 var root=$B.py2js({src:py,is_comp:true,line_info:line_info,ix:ix},genexpr_name,genexpr_name,parent_scope,line_num),js=root.to_js(),lines=js.split("\n") 6068 if(root.outermost_expr===undefined){console.log("no outermost",module_name,parent_scope)} 6069 var outer_expr=root.outermost_expr.to_js() 6070 js=lines.join("\n") 6071 js+="\nvar $res = $B.generator.$factory("+genexpr_name+ 6072 ')('+outer_expr+');\nreturn $res\n' 6073 js="(function($locals_"+genexpr_name+"){"+js+"})($locals)\n" 6074 return js} 6075 $B.copy_namespace=function(){var ns={} 6076 for(const frame of $B.frames_stack){for(const kv of[frame[1],frame[3]]){for(var key in kv){if(key.startsWith('$$')||!key.startsWith('$')){ns[key]=kv[key]}}}} 6077 return ns} 6078 $B.clear_ns=function(name){ 6079 if(name.startsWith("__ge")){console.log("clear ns",name)} 6080 var len=name.length 6081 for(var key in $B.$py_module_path){if(key.substr(0,len)==name){$B.$py_module_path[key]=null 6082 delete $B.$py_module_path[key]}} 6083 $B.$py_src[name]=null 6084 delete $B.$py_src[name] 6085 var alt_name=name.replace(/\./g,"_") 6086 if(alt_name !=name){$B.clear_ns(alt_name)}} 6087 $B.from_alias=function(attr){if(attr.substr(0,2)=="$$" && $B.aliased_names[attr.substr(2)]){return attr.substr(2)} 6088 return attr} 6089 $B.$search=function(name,global_ns){ 6090 var frame=$B.last($B.frames_stack) 6091 if(frame[1][name]!==undefined){return frame[1][name]} 6092 else if(frame[3][name]!==undefined){return frame[3][name]} 6093 else if(_b_[name]!==undefined){return _b_[name]} 6094 else{if(frame[0]==frame[2]||frame[1].$type=="class" || 6095 frame[1].$exec_locals){throw _b_.NameError.$factory( 6096 "name '"+name+"' is not defined")} 6097 else{throw _b_.UnboundLocalError.$factory("local variable '"+ 6098 name+"' referenced before assignment")}}} 6099 $B.$global_search=function(name,search_ids){ 6100 var ns={} 6101 for(var i=0;i< $B.frames_stack.length;i++){var frame=$B.frames_stack[i] 6102 if(search_ids.indexOf(frame[0])>-1 && 6103 frame[1][name]!==undefined){return frame[1][name]} 6104 if(search_ids.indexOf(frame[2])>-1 && 6105 frame[3][name]!==undefined){return frame[3][name]}} 6106 for(var i=0;i < search_ids.length;i++){var search_id=search_ids[i] 6107 if($B.imported[search_id]&& $B.imported[search_id][name]){return $B.imported[search_id][name]}} 6108 throw _b_.NameError.$factory("name '"+$B.from_alias(name)+ 6109 "' is not defined")} 6110 $B.$local_search=function(name){ 6111 var frame=$B.last($B.frames_stack) 6112 if(frame[1][name]!==undefined){return frame[1][name]} 6113 else{throw _b_.UnboundLocalError.$factory("local variable '"+ 6114 $B.from_alias(name)+"' referenced before assignment")}} 6115 $B.$check_def=function(name,value){ 6116 if(value !==undefined){return value}else if(_b_[name]!==undefined){ 6117 return _b_[name]}else{var frame=$B.last($B.frames_stack) 6118 if(frame[3][name]!==undefined){return frame[3][name]}} 6119 throw _b_.NameError.$factory("name '"+$B.from_alias(name)+ 6120 "' is not defined")} 6121 $B.$check_def_local=function(name,value){ 6122 if(value !==undefined){return value} 6123 throw _b_.UnboundLocalError.$factory("local variable '"+ 6124 $B.from_alias(name)+"' referenced before assignment")} 6125 $B.$check_def_free=function(name,value){ 6126 if(value !==undefined){return value} 6127 var res 6128 for(var i=$B.frames_stack.length-1;i >=0;i--){res=$B.frames_stack[i][1][name] 6129 if(res !==undefined){return res} 6130 res=$B.frames_stack[i][3][name] 6131 if(res !==undefined){return res}} 6132 throw _b_.NameError.$factory("free variable '"+$B.from_alias(name)+ 6133 "' referenced before assignment in enclosing scope")} 6134 $B.$check_def_free1=function(name,scope_id){ 6135 var res 6136 for(var i=$B.frames_stack.length-1;i >=0;i--){var frame=$B.frames_stack[i] 6137 res=frame[1][name] 6138 if(res !==undefined){return res} 6139 if(frame[1].$parent){res=frame[1].$parent[name] 6140 if(res !==undefined){return res}} 6141 if(frame[2]==scope_id){res=frame[3][name] 6142 if(res !==undefined){return res}}} 6143 throw _b_.NameError.$factory("free variable '"+$B.from_alias(name)+ 6144 "' referenced before assignment in enclosing scope")} 6145 $B.$JS2Py=function(src){if(typeof src==="number"){if(src % 1===0){return src} 6146 return _b_.float.$factory(src)} 6147 if(src===null ||src===undefined){return _b_.None} 6148 if(Array.isArray(src)&& 6149 Object.getPrototypeOf(src)===Array.prototype){src.$brython_class="js" } 6150 return src} 6151 $B.list_key=function(obj,key){key=$B.$GetInt(key) 6152 if(key < 0){key+=obj.length} 6153 var res=obj[key] 6154 if(res===undefined){throw _b_.IndexError.$factory("list index out of range")} 6155 return res} 6156 $B.list_slice=function(obj,start,stop){if(start===null){start=0} 6157 else{start=$B.$GetInt(start) 6158 if(start < 0){start=Math.max(0,start+obj.length)}} 6159 if(stop===null){return obj.slice(start)} 6160 stop=$B.$GetInt(stop) 6161 if(stop < 0){stop=Math.max(0,stop+obj.length)} 6162 return obj.slice(start,stop)} 6163 $B.list_slice_step=function(obj,start,stop,step){if(step===null ||step==1){return $B.list_slice(obj,start,stop)} 6164 if(step==0){throw _b_.ValueError.$factory("slice step cannot be zero")} 6165 step=$B.$GetInt(step) 6166 if(start===null){start=step >=0 ? 0 :obj.length-1} 6167 else{start=$B.$GetInt(start) 6168 if(start < 0){start=Math.min(0,start+obj.length)}} 6169 if(stop===null){stop=step >=0 ? obj.length :-1} 6170 else{stop=$B.$GetInt(stop) 6171 if(stop < 0){stop=Math.max(0,stop+obj.length)}} 6172 var res=[] 6173 if(step > 0){for(var i=start;i < stop;i+=step){res.push(obj[i])}}else{for(var i=start;i > stop;i+=step){res.push(obj[i])}} 6174 return res} 6175 function index_error(obj){var type=typeof obj=="string" ? "string" :"list" 6176 throw _b_.IndexError.$factory(type+" index out of range")} 6177 $B.$getitem=function(obj,item){var is_list=Array.isArray(obj)&& obj.__class__===_b_.list 6178 if(typeof item=="number"){if(is_list ||typeof obj=="string"){item=item >=0 ? item :obj.length+item 6179 if(obj[item]!==undefined){return obj[item]} 6180 else{index_error(obj)}}} 6181 try{item=$B.$GetInt(item)}catch(err){} 6182 if((is_list ||typeof obj=="string") 6183 && typeof item=="number"){item=item >=0 ? item :obj.length+item 6184 if(obj[item]!==undefined){return obj[item]} 6185 else{index_error(obj)}} 6186 if(obj.$is_class){var class_gi=$B.$getattr(obj,"__class_getitem__",_b_.None) 6187 if(class_gi !==_b_.None){return class_gi(item)}else if(obj.__class__){class_gi=$B.$getattr(obj.__class__,"__getitem__",_b_.None) 6188 if(class_gi !==_b_.None){return class_gi(obj,item)}}} 6189 if(is_list){return _b_.list.$getitem(obj,item)} 6190 var gi=$B.$getattr(obj,"__getitem__",_b_.None) 6191 if(gi !==_b_.None){return gi(item)} 6192 throw _b_.TypeError.$factory("'"+$B.class_name(obj)+ 6193 "' object is not subscriptable")} 6194 $B.getitem_slice=function(obj,slice){var res 6195 if(Array.isArray(obj)){if(slice.start===_b_.None && slice.stop===_b_.None){if(slice.step===_b_.None ||slice.step==1){res=obj.slice()}else if(slice.step==-1){res=obj.slice().reverse()}}else if(slice.step===_b_.None){if(slice.start===_b_.None){slice.start=0} 6196 if(slice.stop===_b_.None){slice.stop=obj.length} 6197 if(typeof slice.start=="number" && 6198 typeof slice.stop=="number"){if(slice.start < 0){slice.start+=obj.length} 6199 if(slice.stop < 0){slice.stop+=obj.length} 6200 res=obj.slice(slice.start,slice.stop)}} 6201 if(res){res.__class__=obj.__class__ 6202 return res}else{return _b_.list.$getitem(obj,slice)}} 6203 return $B.$getattr(obj,"__getitem__")(slice)} 6204 $B.set_list_key=function(obj,key,value){try{key=$B.$GetInt(key)} 6205 catch(err){if(_b_.isinstance(key,_b_.slice)){var s=_b_.slice.$conv_for_seq(key,obj.length) 6206 return $B.set_list_slice_step(obj,s.start,s.stop,s.step,value)}} 6207 if(key < 0){key+=obj.length} 6208 if(obj[key]===undefined){console.log(obj,key) 6209 throw _b_.IndexError.$factory("list assignment index out of range")} 6210 obj[key]=value} 6211 $B.set_list_slice=function(obj,start,stop,value){if(start===null){start=0} 6212 else{start=$B.$GetInt(start) 6213 if(start < 0){start=Math.max(0,start+obj.length)}} 6214 if(stop===null){stop=obj.length} 6215 stop=$B.$GetInt(stop) 6216 if(stop < 0){stop=Math.max(0,stop+obj.length)} 6217 var res=_b_.list.$factory(value) 6218 obj.splice.apply(obj,[start,stop-start].concat(res))} 6219 $B.set_list_slice_step=function(obj,start,stop,step,value){if(step===null ||step==1){return $B.set_list_slice(obj,start,stop,value)} 6220 if(step==0){throw _b_.ValueError.$factory("slice step cannot be zero")} 6221 step=$B.$GetInt(step) 6222 if(start===null){start=step > 0 ? 0 :obj.length-1}else{start=$B.$GetInt(start)} 6223 if(stop===null){stop=step > 0 ? obj.length :-1}else{stop=$B.$GetInt(stop)} 6224 var repl=_b_.list.$factory(value),j=0,test,nb=0 6225 if(step > 0){test=function(i){return i < stop}} 6226 else{test=function(i){return i > stop}} 6227 for(var i=start;test(i);i+=step){nb++} 6228 if(nb !=repl.length){throw _b_.ValueError.$factory( 6229 "attempt to assign sequence of size "+repl.length+ 6230 " to extended slice of size "+nb)} 6231 for(var i=start;test(i);i+=step){obj[i]=repl[j] 6232 j++}} 6233 $B.$setitem=function(obj,item,value){if(Array.isArray(obj)&& obj.__class__===undefined && 6234 typeof item=="number" && 6235 !_b_.isinstance(obj,_b_.tuple)){if(item < 0){item+=obj.length} 6236 if(obj[item]===undefined){throw _b_.IndexError.$factory("list assignment index out of range")} 6237 obj[item]=value 6238 return}else if(obj.__class__===_b_.dict){_b_.dict.$setitem(obj,item,value) 6239 return}else if(obj.__class__===_b_.list){return _b_.list.$setitem(obj,item,value)} 6240 $B.$getattr(obj,"__setitem__")(item,value)} 6241 $B.augm_item_add=function(obj,item,incr){if(Array.isArray(obj)&& typeof item=="number" && 6242 obj[item]!==undefined){if(Array.isArray(obj[item])&& Array.isArray(incr)){for(var i=0,len=incr.length;i < len;i++){obj[item].push(incr[i])} 6243 return}else if(typeof obj[item]=="string" && typeof incr=="string"){obj[item]+=incr 6244 return}} 6245 var ga=$B.$getattr 6246 try{var augm_func=ga(ga(obj,"__getitem__")(item),"__iadd__")}catch(err){ga(obj,"__setitem__")(item,ga(ga(obj,"__getitem__")(item),"__add__")(incr)) 6247 return} 6248 augm_func(incr)} 6249 var augm_item_src=""+$B.augm_item_add 6250 var augm_ops=[["-=","sub"],["*=","mul"]] 6251 for(var i=0,len=augm_ops.length;i < len;i++){var augm_code=augm_item_src.replace(/add/g,augm_ops[i][1]) 6252 augm_code=augm_code.replace(/\+=/g,augm_ops[i][0]) 6253 eval("$B.augm_item_"+augm_ops[i][1]+"="+augm_code)} 6254 $B.extend=function(fname,arg){ 6255 for(var i=2;i < arguments.length;i++){var mapping=arguments[i] 6256 var it=_b_.iter(mapping),getter=$B.$getattr(mapping,"__getitem__") 6257 while(true){try{var key=_b_.next(it) 6258 if(typeof key !=="string"){throw _b_.TypeError.$factory(fname+ 6259 "() keywords must be strings")} 6260 if(arg[key]!==undefined){throw _b_.TypeError.$factory(fname+ 6261 "() got multiple values for argument '"+key+"'")} 6262 arg[key]=getter(key)}catch(err){if(_b_.isinstance(err,[_b_.StopIteration])){break} 6263 throw err}}} 6264 return arg} 6265 $B.extend_list=function(){ 6266 var res=Array.prototype.slice.call(arguments,0,arguments.length-1),last=$B.last(arguments) 6267 var it=_b_.iter(last) 6268 while(true){try{res.push(_b_.next(it))}catch(err){if(_b_.isinstance(err,[_b_.StopIteration])){break} 6269 throw err}} 6270 return res} 6271 $B.$test_item=function(expr){ 6272 $B.$test_result=expr 6273 return _b_.bool.$factory(expr)} 6274 $B.$test_expr=function(){ 6275 return $B.$test_result} 6276 $B.$is=function(a,b){ 6277 if(a instanceof Number && b instanceof Number){return a.valueOf()==b.valueOf()} 6278 if((a===_b_.int && b==$B.long_int)|| 6279 (a===$B.long_int && b===_b_.int)){return true} 6280 return a===b} 6281 $B.$is_member=function(item,_set){ 6282 var f,_iter,method 6283 try{method=$B.$getattr(_set.__class__ ||$B.get_class(_set),"__contains__")} 6284 catch(err){} 6285 if(method){return $B.$call(method)(_set,item)} 6286 try{_iter=_b_.iter(_set)} 6287 catch(err){} 6288 if(_iter){while(1){try{var elt=_b_.next(_iter) 6289 if($B.rich_comp("__eq__",elt,item)){return true}}catch(err){return false}}} 6290 try{f=$B.$getattr(_set,"__getitem__")} 6291 catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(_set)+ 6292 "' object is not iterable")} 6293 if(f){var i=-1 6294 while(1){i++ 6295 try{var elt=f(i) 6296 if($B.rich_comp("__eq__",elt,item)){return true}}catch(err){if(err.__class__===_b_.IndexError){return false} 6297 throw err}}}} 6298 $B.$call=function(callable){if(callable.__class__===$B.method){return callable} 6299 else if(callable.$is_func ||typeof callable=="function"){return callable}else if(callable.$factory){return callable.$factory}else if(callable.$is_class){ 6300 return callable.$factory=$B.$instance_creator(callable)} 6301 try{return $B.$getattr(callable,"__call__")}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(callable)+ 6302 "' object is not callable")}} 6303 var $io=$B.make_class("io",function(out){return{ 6304 __class__:$io,out}} 6305 ) 6306 $io.flush=function(){} 6307 $io.write=function(self,msg){ 6308 console[self.out](msg) 6309 return _b_.None} 6310 if(console.error !==undefined){$B.stderr=$io.$factory("error")}else{$B.stderr=$io.$factory("log")} 6311 $B.stdout=$io.$factory("log") 6312 $B.stdin={__class__:$io,__original__:true,closed:false,len:1,pos:0,read:function(){return ""},readline:function(){return ""}} 6313 $B.make_iterator_class=function(name){ 6314 var klass={__class__:_b_.type,__mro__:[_b_.object],$factory:function(items){return{ 6315 __class__:klass,__dict__:$B.empty_dict(),counter:-1,items:items,len:items.length}},$infos:{__name__:name},$is_class:true,__iter__:function(self){self.counter=self.counter===undefined ?-1 :self.counter 6316 self.len=self.items.length 6317 return self},__len__:function(self){return self.items.length},__next__:function(self){if(typeof self.len_func=="function" && 6318 self.len_func()!=self.len){throw _b_.RuntimeError.$factory( 6319 "dictionary changed size during iteration")} 6320 self.counter++ 6321 if(self.counter < self.items.length){var item=self.items[self.counter] 6322 if(self.items.$brython_class=="js"){ 6323 item=$B.$JS2Py(item)} 6324 return item} 6325 throw _b_.StopIteration.$factory("StopIteration")},__reduce_ex__:function(self,protocol){return $B.fast_tuple([_b_.iter,_b_.tuple.$factory([self.items])])}} 6326 $B.set_func_names(klass,"builtins") 6327 return klass} 6328 function $err(op,klass,other){var msg="unsupported operand type(s) for "+op+" : '"+ 6329 klass.$infos.__name__+"' and '"+$B.class_name(other)+"'" 6330 throw _b_.TypeError.$factory(msg)} 6331 var ropnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"] 6332 var ropsigns=["+","-","*","/","//","%","**","<<",">>","&","^","|"] 6333 $B.make_rmethods=function(klass){for(var j=0,_len_j=ropnames.length;j < _len_j;j++){if(klass["__"+ropnames[j]+"__"]===undefined){klass["__"+ropnames[j]+"__"]=(function(name,sign){return function(self,other){try{return $B.$getattr(other,"__r"+name+"__")(self)} 6334 catch(err){$err(sign,klass,other)}}})(ropnames[j],ropsigns[j])}}} 6335 $B.UUID=function(){return $B.$py_UUID++} 6336 $B.InjectBuiltins=function(){var _str=["var _b_ = $B.builtins"],pos=1 6337 for(var $b in $B.builtins){_str[pos++]="var "+$b+'=_b_["'+$b+'"]'} 6338 return _str.join(";")} 6339 $B.$GetInt=function(value){ 6340 if(typeof value=="number" ||value.constructor===Number){return value} 6341 else if(typeof value==="boolean"){return value ? 1 :0} 6342 else if(_b_.isinstance(value,_b_.int)){return value} 6343 else if(_b_.isinstance(value,_b_.float)){return value.valueOf()} 6344 if(! value.$is_class){try{var v=$B.$getattr(value,"__int__")();return v}catch(e){} 6345 try{var v=$B.$getattr(value,"__index__")();return v}catch(e){}} 6346 throw _b_.TypeError.$factory("'"+$B.class_name(value)+ 6347 "' object cannot be interpreted as an integer")} 6348 $B.to_num=function(obj,methods){ 6349 var expected_class={"__complex__":_b_.complex,"__float__":_b_.float,"__index__":_b_.int,"__int__":_b_.int} 6350 var klass=obj.__class__ ||$B.get_class(obj) 6351 for(var i=0;i < methods.length;i++){var missing={},method=$B.$getattr(klass,methods[i],missing) 6352 if(method !==missing){var res=method(obj) 6353 if(!_b_.isinstance(res,expected_class[methods[i]])){console.log(res,methods[i],expected_class[methods[i]]) 6354 throw _b_.TypeError.$factory(methods[i]+"returned non-"+ 6355 expected_class[methods[i]].$infos.__name__+ 6356 "(type "+$B.get_class(res)+")")} 6357 return res}} 6358 return null} 6359 $B.PyNumber_Index=function(item){switch(typeof item){case "boolean": 6360 return item ? 1 :0 6361 case "number": 6362 return item 6363 case "object": 6364 if(item.__class__===$B.long_int){return item} 6365 if(_b_.isinstance(item,_b_.int)){ 6366 return item.$brython_value} 6367 var method=$B.$getattr(item,"__index__",_b_.None) 6368 if(method !==_b_.None){method=typeof method=="function" ? 6369 method :$B.$getattr(method,"__call__") 6370 return $B.int_or_bool(method())} 6371 default: 6372 throw _b_.TypeError.$factory("'"+$B.class_name(item)+ 6373 "' object cannot be interpreted as an integer")}} 6374 $B.int_or_bool=function(v){switch(typeof v){case "boolean": 6375 return v ? 1 :0 6376 case "number": 6377 return v 6378 case "object": 6379 if(v.__class__===$B.long_int){return v} 6380 else{throw _b_.TypeError.$factory("'"+$B.class_name(v)+ 6381 "' object cannot be interpreted as an integer")} 6382 default: 6383 throw _b_.TypeError.$factory("'"+$B.class_name(v)+ 6384 "' object cannot be interpreted as an integer")}} 6385 $B.enter_frame=function(frame){ 6386 $B.frames_stack.push(frame) 6387 if($B.tracefunc && $B.tracefunc !==_b_.None){if(frame[4]===$B.tracefunc || 6388 ($B.tracefunc.$infos && frame[4]&& 6389 frame[4]===$B.tracefunc.$infos.__func__)){ 6390 $B.tracefunc.$frame_id=frame[0] 6391 return _b_.None}else{ 6392 for(var i=$B.frames_stack.length-1;i >=0;i--){if($B.frames_stack[i][0]==$B.tracefunc.$frame_id){return _b_.None}} 6393 return $B.tracefunc($B._frame.$factory($B.frames_stack,$B.frames_stack.length-1),'call',_b_.None)}} 6394 return _b_.None} 6395 $B.trace_exception=function(){var top_frame=$B.last($B.frames_stack) 6396 if(top_frame[0]==$B.tracefunc.$current_frame_id){return _b_.None} 6397 var trace_func=top_frame[1].$f_trace,exc=top_frame[1].$current_exception,frame_obj=$B._frame.$factory($B.frames_stack,$B.frames_stack.length-1) 6398 return trace_func(frame_obj,'exception',$B.fast_tuple([exc.__class__,exc,$B.traceback.$factory(exc)]))} 6399 $B.trace_line=function(){var top_frame=$B.last($B.frames_stack) 6400 if(top_frame[0]==$B.tracefunc.$current_frame_id){return _b_.None} 6401 var trace_func=top_frame[1].$f_trace,frame_obj=$B._frame.$factory($B.frames_stack,$B.frames_stack.length-1) 6402 return trace_func(frame_obj,'line',_b_.None)} 6403 $B.set_line=function(line_info){ 6404 var top_frame=$B.last($B.frames_stack) 6405 if($B.tracefunc && top_frame[0]==$B.tracefunc.$current_frame_id){return _b_.None} 6406 top_frame[1].$line_info=line_info 6407 var trace_func=top_frame[1].$f_trace 6408 if(trace_func !==_b_.None){var frame_obj=$B._frame.$factory($B.frames_stack,$B.frames_stack.length-1) 6409 top_frame[1].$ftrace=trace_func(frame_obj,'line',_b_.None)} 6410 return true} 6411 $B.trace_return=function(value){var top_frame=$B.last($B.frames_stack),trace_func=top_frame[1].$f_trace,frame_obj=$B._frame.$factory($B.frames_stack,$B.frames_stack.length-1) 6412 if(top_frame[0]==$B.tracefunc.$current_frame_id){ 6413 return _b_.None} 6414 trace_func(frame_obj,'return',value)} 6415 function exit_ctx_managers_in_generators(frame){ 6416 for(key in frame[1]){if(frame[1][key]&& frame[1][key].__class__==$B.generator){ 6417 var gen_obj=frame[1][key] 6418 gen_obj.return()}}} 6419 $B.set_cm_in_generator=function(cm_exit){if(cm_exit !==undefined){$B.frames_stack.forEach(function(frame){frame[1].$cm_in_gen=frame[1].$cm_in_gen ||new Set() 6420 frame[1].$cm_in_gen.add(cm_exit)})}} 6421 $B.leave_frame=function(arg){ 6422 if($B.frames_stack.length==0){console.log("empty stack");return} 6423 if(arg && arg.value !==undefined && $B.tracefunc){if($B.last($B.frames_stack)[1].$f_trace===undefined){$B.last($B.frames_stack)[1].$f_trace=$B.tracefunc} 6424 if($B.last($B.frames_stack)[1].$f_trace !==_b_.None){$B.trace_return(arg.value)}} 6425 var frame=$B.frames_stack.pop() 6426 frame[1].$current_exception=undefined 6427 if(frame[1].$close_generators){ 6428 for(var i=0,len=frame[1].$close_generators.length;i < len;i++){var gen=frame[1].$close_generators[i] 6429 if(gen.$has_run){gen.return()}}} 6430 return _b_.None} 6431 $B.leave_frame_exec=function(arg){ 6432 if($B.profile > 0){$B.$profile.return()} 6433 if($B.frames_stack.length==0){console.log("empty stack");return} 6434 var frame=$B.frames_stack.pop() 6435 exit_ctx_managers_in_generators(frame) 6436 for(var i=$B.frames_stack.length-1;i >=0;i--){if($B.frames_stack[i][2]==frame[2]){$B.frames_stack[i][3]=frame[3]}}} 6437 var min_int=Math.pow(-2,53),max_int=Math.pow(2,53)-1 6438 $B.is_safe_int=function(){for(var i=0;i < arguments.length;i++){var arg=arguments[i] 6439 if(arg < min_int ||arg > max_int){return false}} 6440 return true} 6441 $B.add=function(x,y){if(typeof x.valueOf()=="number" && typeof y.valueOf()=="number"){if(typeof x=="number" && typeof y=="number"){ 6442 var z=x+y 6443 if(z < $B.max_int && z > $B.min_int){return z}else if(z===Infinity){return _b_.float.$factory("inf")}else if(z===-Infinity){return _b_.float.$factory("-inf")}else if(isNaN(z)){return _b_.float.$factory('nan')} 6444 return $B.long_int.__add__($B.long_int.$factory(x),$B.long_int.$factory(y))}else{ 6445 return new Number(x+y)}}else if(typeof x=="string" && typeof y=="string"){ 6446 return x+y} 6447 try{var method=$B.$getattr(x.__class__ ||$B.get_class(x),"__add__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("unsupported operand type(s) for "+ 6448 "+: '"+$B.class_name(x)+"' and '"+$B.class_name(y)+"'")} 6449 throw err} 6450 var res=$B.$call(method)(x,y) 6451 if(res===_b_.NotImplemented){ 6452 return $B.rich_op("add",x,y)} 6453 return res} 6454 $B.div=function(x,y){var z=x/y 6455 if(x > min_int && x < max_int && y > min_int && y < max_int 6456 && z > min_int && z < max_int){return z} 6457 else{return $B.long_int.__truediv__($B.long_int.$factory(x),$B.long_int.$factory(y))}} 6458 $B.eq=function(x,y){if(x > min_int && x < max_int && y > min_int && y < max_int){return x==y} 6459 return $B.long_int.__eq__($B.long_int.$factory(x),$B.long_int.$factory(y))} 6460 $B.floordiv=function(x,y){var z=x/y 6461 if(x > min_int && x < max_int && y > min_int && y < max_int 6462 && z > min_int && z < max_int){return Math.floor(z)} 6463 else{return $B.long_int.__floordiv__($B.long_int.$factory(x),$B.long_int.$factory(y))}} 6464 $B.mul=function(x,y){var z=(typeof x !="number" ||typeof y !="number")? 6465 new Number(x*y):x*y 6466 if(x > min_int && x < max_int && y > min_int && y < max_int 6467 && z > min_int && z < max_int){return z} 6468 else if((typeof x=="number" ||x.__class__===$B.long_int) 6469 &&(typeof y=="number" ||y.__class__===$B.long_int)){if((typeof x=="number" && isNaN(x))|| 6470 (typeof y=="number" && isNaN(y))){return _b_.float.$factory("nan")} 6471 switch(x){case Infinity: 6472 case-Infinity: 6473 if(y==0){return _b_.float.$factory("nan")}else{return y > 0 ? x :-x}} 6474 return $B.long_int.__mul__($B.long_int.$factory(x),$B.long_int.$factory(y))}else{return z}} 6475 $B.sub=function(x,y){var z=(typeof x !="number" ||typeof y !="number")? 6476 new Number(x-y):x-y 6477 if(x > min_int && x < max_int && y > min_int && y < max_int 6478 && z > min_int && z < max_int){return z}else if((typeof x=="number" ||x.__class__===$B.long_int) 6479 &&(typeof y=="number" ||y.__class__===$B.long_int)){if((typeof x=="number" && isNaN(x))|| 6480 (typeof y=="number" && isNaN(y))){return _b_.float.$factory("nan")} 6481 return $B.long_int.__sub__($B.long_int.$factory(x),$B.long_int.$factory(y))}else{return z}} 6482 $B.ge=function(x,y){if(typeof x=="number" && typeof y=="number"){return x >=y} 6483 else if(typeof x=="number" && typeof y !="number"){return ! y.pos} 6484 else if(typeof x !="number" && typeof y=="number"){return x.pos===true}else{return $B.long_int.__ge__(x,y)}} 6485 $B.gt=function(x,y){if(typeof x=="number" && typeof y=="number"){return x > y} 6486 else if(typeof x=="number" && typeof y !="number"){return ! y.pos} 6487 else if(typeof x !="number" && typeof y=="number"){return x.pos===true}else{return $B.long_int.__gt__(x,y)}} 6488 var reversed_op={"__lt__":"__gt__","__le__":"__ge__","__gt__":"__lt__","__ge__":"__le__"} 6489 var method2comp={"__lt__":"<","__le__":"<=","__gt__":">","__ge__":">="} 6490 $B.rich_comp=function(op,x,y){var x1=x.valueOf(),y1=y.valueOf() 6491 if(typeof x1=="number" && typeof y1=="number" && 6492 x.__class__===undefined && y.__class__===undefined){switch(op){case "__eq__": 6493 return x1==y1 6494 case "__ne__": 6495 return x1 !=y1 6496 case "__le__": 6497 return x1 <=y1 6498 case "__lt__": 6499 return x1 < y1 6500 case "__ge__": 6501 return x1 >=y1 6502 case "__gt__": 6503 return x1 > y1}} 6504 var res,rev_op 6505 if(x.$is_class ||x.$factory){if(op=="__eq__"){return(x===y)}else if(op=="__ne__"){return !(x===y)}else{throw _b_.TypeError.$factory("'"+method2comp[op]+ 6506 "' not supported between instances of '"+$B.class_name(x)+ 6507 "' and '"+$B.class_name(y)+"'")}} 6508 if(x.__class__ && y.__class__){ 6509 if(y.__class__.__mro__.indexOf(x.__class__)>-1){rev_op=reversed_op[op]||op 6510 var rev_func=$B.$getattr(y,rev_op) 6511 res=$B.$call($B.$getattr(y,rev_op))(x) 6512 if(res !==_b_.NotImplemented){return res}}} 6513 res=$B.$call($B.$getattr(x,op))(y) 6514 if(res !==_b_.NotImplemented){return res} 6515 rev_op=reversed_op[op]||op 6516 res=$B.$call($B.$getattr(y,rev_op))(x) 6517 if(res !==_b_.NotImplemented ){return res} 6518 if(op=="__eq__"){return _b_.False} 6519 else if(op=="__ne__"){return _b_.True} 6520 throw _b_.TypeError.$factory("'"+method2comp[op]+ 6521 "' not supported between instances of '"+$B.class_name(x)+ 6522 "' and '"+$B.class_name(y)+"'")} 6523 var opname2opsign={sub:"-",xor:"^",mul:"*"} 6524 $B.rich_op=function(op,x,y){var x_class=x.__class__ ||$B.get_class(x),y_class=y.__class__ ||$B.get_class(y),method 6525 if(x_class===y_class){ 6526 if(x_class===_b_.int){return _b_.int["__"+op+"__"](x,y)} 6527 try{method=$B.$call($B.$getattr(x,"__"+op+"__"))}catch(err){if(err.__class__===_b_.AttributeError){var kl_name=$B.class_name(x) 6528 throw _b_.TypeError.$factory("unsupported operand type(s) "+ 6529 "for "+opname2opsign[op]+" : '"+kl_name+"' and '"+ 6530 kl_name+"'")} 6531 throw err} 6532 return method(y)} 6533 var res 6534 try{method=$B.$call($B.$getattr(x,"__"+op+"__"))}catch(err){if(err.__class__ !==_b_.AttributeError){throw err} 6535 res=$B.$call($B.$getattr(y,"__r"+op+"__"))(x) 6536 if(res !==_b_.NotImplemented){return res} 6537 throw _b_.TypeError.$factory("'"+(opname2opsign[op]||op)+ 6538 "' not supported between instances of '"+$B.class_name(x)+ 6539 "' and '"+$B.class_name(y)+"'")} 6540 res=method(y) 6541 if(res===_b_.NotImplemented){res=$B.$call($B.$getattr(y,"__r"+op+"__"))(x) 6542 if(res !==_b_.NotImplemented){return res} 6543 throw _b_.TypeError.$factory("'"+(opname2opsign[op]||op)+ 6544 "' not supported between instances of '"+$B.class_name(x)+ 6545 "' and '"+$B.class_name(y)+"'")}else{return res}} 6546 $B.is_none=function(o){return o===undefined ||o===null ||o==_b_.None} 6547 var repr_stack=new Set() 6548 $B.repr={enter:function(obj){if(repr_stack.has(obj)){return true}else{repr_stack.add(obj)}},leave:function(obj){repr_stack.delete(obj)}}})(__BRYTHON__) 6549 ; 6550 6551 ;(function($B){var _b_=$B.builtins 6552 _b_.__debug__=false 6553 $B.$comps={'>':'gt','>=':'ge','<':'lt','<=':'le'} 6554 $B.$inv_comps={'>':'lt','>=':'le','<':'gt','<=':'ge'} 6555 var check_nb_args=$B.check_nb_args=function(name,expected,args){ 6556 var len=args.length,last=args[len-1] 6557 if(last && last.$nat=="kw"){var kw=last.kw 6558 if(Array.isArray(kw)&& kw[1]&& kw[1].__class__===_b_.dict){if(Object.keys(kw[1].$string_dict).length==0){len--}}} 6559 if(len !=expected){if(expected==0){throw _b_.TypeError.$factory(name+"() takes no argument"+ 6560 " ("+len+" given)")}else{throw _b_.TypeError.$factory(name+"() takes exactly "+ 6561 expected+" argument"+(expected < 2 ? '' :'s')+ 6562 " ("+len+" given)")}}} 6563 var check_no_kw=$B.check_no_kw=function(name,x,y){ 6564 if(x===undefined){console.log("x undef",name,x,y)} 6565 if((x.$nat && x.kw && x.kw[0]&& x.kw[0].length > 0)|| 6566 (y !==undefined && y.$nat)){throw _b_.TypeError.$factory(name+"() takes no keyword arguments")}} 6567 var NoneType={$factory:function(){return None},$infos:{__name__:"NoneType",__module__:"builtins"},__bool__:function(self){return False},__class__:_b_.type,__hash__:function(self){return 0},__mro__:[_b_.object],__repr__:function(self){return 'None'},__str__:function(self){return 'None'},$is_class:true} 6568 NoneType.__setattr__=function(self,attr){return no_set_attr(NoneType,attr)} 6569 var None={__class__:NoneType,} 6570 for(var $op in $B.$comps){ 6571 var key=$B.$comps[$op] 6572 switch(key){case 'ge': 6573 case 'gt': 6574 case 'le': 6575 case 'lt': 6576 NoneType['__'+key+'__']=(function(op){return function(other){return _b_.NotImplemented}})($op)}} 6577 for(var $func in None){if(typeof None[$func]=='function'){None[$func].__str__=(function(f){return function(){return "<method-wrapper "+f+ 6578 " of NoneType object>"}})($func)}} 6579 $B.set_func_names(NoneType,"builtins") 6580 function abs(obj){check_nb_args('abs',1,arguments) 6581 check_no_kw('abs',obj) 6582 if(isinstance(obj,_b_.int)){if(obj.__class__===$B.long_int){return{ 6583 __class__:$B.long_int,value:obj.value,pos:true}}else{return _b_.int.$factory(Math.abs(obj))}} 6584 if(isinstance(obj,_b_.float)){ 6585 return _b_.float.$factory(Math.abs(_b_.float.numerator(obj)))} 6586 var klass=obj.__class__ ||$B.get_class(obj) 6587 try{var method=$B.$getattr(klass,"__abs__")}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("Bad operand type for abs(): '"+ 6588 $B.class_name(obj)+"'")} 6589 throw err} 6590 return $B.$call(method)(obj)} 6591 function all(obj){check_nb_args('all',1,arguments) 6592 check_no_kw('all',obj) 6593 var iterable=iter(obj) 6594 while(1){try{var elt=next(iterable) 6595 if(!$B.$bool(elt)){return false}}catch(err){return true}}} 6596 function any(obj){check_nb_args('any',1,arguments) 6597 check_no_kw('any',obj) 6598 var iterable=iter(obj) 6599 while(1){try{var elt=next(iterable) 6600 if($B.$bool(elt)){return true}}catch(err){return false}}} 6601 function ascii(obj){check_nb_args('ascii',1,arguments) 6602 check_no_kw('ascii',obj) 6603 var res=repr(obj),res1='',cp 6604 for(var i=0;i < res.length;i++){cp=res.charCodeAt(i) 6605 if(cp < 128){res1+=res.charAt(i)} 6606 else if(cp < 256){res1+='\\x'+cp.toString(16)} 6607 else{var s=cp.toString(16) 6608 if(s.length % 2==1){s="0"+s} 6609 res1+='\\u'+s}} 6610 return res1} 6611 function $builtin_base_convert_helper(obj,base){var prefix=""; 6612 switch(base){case 2: 6613 prefix='0b';break 6614 case 8: 6615 prefix='0o';break 6616 case 16: 6617 prefix='0x';break 6618 default: 6619 console.log('invalid base:'+base)} 6620 if(obj.__class__===$B.long_int){var res=prefix+$B.long_int.to_base(obj,base) 6621 if(! obj.pos){res="-"+res} 6622 return res} 6623 var value=$B.$GetInt(obj) 6624 if(value===undefined){ 6625 throw _b_.TypeError.$factory('Error, argument must be an integer or'+ 6626 ' contains an __index__ function')} 6627 if(value >=0){return prefix+value.toString(base)} 6628 return '-'+prefix+(-value).toString(base)} 6629 function bin_hex_oct(base,obj){ 6630 if(isinstance(obj,_b_.int)){return $builtin_base_convert_helper(obj,base)}else{try{var klass=obj.__class__ ||$B.get_class(obj),method=$B.$getattr(klass,'__index__')}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+ 6631 "' object cannot be interpreted as an integer")} 6632 throw err} 6633 var res=$B.$call(method)(obj) 6634 return $builtin_base_convert_helper(res,base)}} 6635 function bin(obj){check_nb_args('bin',1,arguments) 6636 check_no_kw('bin',obj) 6637 return bin_hex_oct(2,obj)} 6638 function breakpoint(){ 6639 $B.$import('sys',[]) 6640 var missing={},hook=$B.$getattr($B.imported.sys,'breakpointhook',missing) 6641 if(hook===missing){throw _b_.RuntimeError.$factory('lost sys.breakpointhook')} 6642 return $B.$call(hook).apply(null,arguments)} 6643 function callable(obj){check_nb_args('callable',1,arguments) 6644 check_no_kw('callable',obj) 6645 return hasattr(obj,'__call__')} 6646 function chr(i){check_nb_args('chr',1,arguments) 6647 check_no_kw('chr',i) 6648 if(i < 0 ||i > 1114111){throw _b_.ValueError.$factory('Outside valid range')} 6649 return String.fromCodePoint(i)} 6650 var classmethod=$B.make_class("classmethod",function(func){check_nb_args('classmethod',1,arguments) 6651 check_no_kw('classmethod',func) 6652 var f=function(){return func.apply(null,arguments)} 6653 f.__class__=$B.method 6654 if(func.$attrs){for(var key in func.$attrs){f[key]=func.$attrs[key]}} 6655 f.$infos={__func__:func,__name__:func.$infos.__name__} 6656 f.__get__=function(obj,cls){var method=function(){return f(cls,...arguments)} 6657 method.__class__=$B.method 6658 method.$infos={__self__:cls,__func__:f,__name__:func.$infos.__name__,__qualname__:cls.$infos.__name__+"."+func.$infos.__name__} 6659 return method} 6660 f.__get__.__class__=$B.method_wrapper 6661 f.__get__.$infos=func.$infos 6662 return f} 6663 ) 6664 $B.set_func_names(classmethod,"builtins") 6665 var code=$B.code=$B.make_class("code") 6666 code.__repr__=code.__str__=function(self){return '<code object '+self.co_name+', file '+self.co_filename+'>'} 6667 code.__getattribute__=function(self,attr){return self[attr]} 6668 $B.set_func_names(code,"builtins") 6669 function compile(){var $=$B.args('compile',6,{source:null,filename:null,mode:null,flags:null,dont_inherit:null,optimize:null,_feature_version:null},['source','filename','mode','flags','dont_inherit','optimize','_feature_version'],arguments,{flags:0,dont_inherit:false,optimize:-1,_feature_version:0},null,null) 6670 var module_name='$exec_'+$B.UUID() 6671 $B.clear_ns(module_name) 6672 $.__class__=code 6673 $.co_flags=$.flags 6674 $.name="<module>" 6675 var interactive=$.mode=="single" &&($.flags & 0x200) 6676 if(interactive && ! $.source.endsWith("\n")){ 6677 var lines=$.source.split("\n") 6678 if($B.last(lines).startsWith(" ")){throw _b_.SyntaxError.$factory("unexpected EOF while parsing")}} 6679 $B.py2js($.source,module_name,module_name) 6680 return $} 6681 var __debug__=$B.debug > 0 6682 function delattr(obj,attr){ 6683 check_no_kw('delattr',obj,attr) 6684 check_nb_args('delattr',2,arguments) 6685 if(typeof attr !='string'){throw _b_.TypeError.$factory("attribute name must be string, not '"+ 6686 $B.class_name(attr)+"'")} 6687 return $B.$getattr(obj,'__delattr__')(attr)} 6688 $B.$delete=function(name,is_global){ 6689 function del(obj){if(obj.__class__===$B.generator){ 6690 obj.return()}} 6691 var found=false,frame=$B.last($B.frames_stack) 6692 if(! is_global){if(frame[1][name]!==undefined){found=true 6693 del(frame[1][name]) 6694 delete frame[1][name]}}else{if(frame[2]!=frame[0]&& frame[3][name]!==undefined){found=true 6695 del(frame[3][name]) 6696 delete frame[3][name]}} 6697 if(!found){throw _b_.NameError.$factory(name)}} 6698 function dir(obj){if(obj===undefined){ 6699 var frame=$B.last($B.frames_stack) 6700 locals_obj=frame[1],res=_b_.list.$factory(),pos=0 6701 for(var attr in locals_obj){if(attr.charAt(0)=='$' && attr.charAt(1)!='$'){ 6702 continue} 6703 res[pos++]=attr} 6704 _b_.list.sort(res) 6705 return res} 6706 check_nb_args('dir',1,arguments) 6707 check_no_kw('dir',obj) 6708 var klass=obj.__class__ ||$B.get_class(obj) 6709 if(obj.$is_class){ 6710 var dir_func=$B.$getattr(obj.__class__,"__dir__") 6711 return $B.$call(dir_func)(obj)} 6712 try{var res=$B.$call($B.$getattr(obj,'__dir__'))() 6713 res=_b_.list.$factory(res) 6714 return res}catch(err){} 6715 var res=[],pos=0 6716 for(var attr in obj){if(attr.charAt(0)!=='$' && attr !=='__class__' && 6717 obj[attr]!==undefined){res[pos++]=attr}} 6718 res.sort() 6719 return res} 6720 function divmod(x,y){check_no_kw('divmod',x,y) 6721 check_nb_args('divmod',2,arguments) 6722 var klass=x.__class__ ||$B.get_class(x) 6723 var dm=$B.$getattr(klass,"__divmod__",_b_.None) 6724 if(dm !==_b_.None){return dm(x,y)} 6725 return _b_.tuple.$factory([$B.$getattr(klass,'__floordiv__')(x,y),$B.$getattr(klass,'__mod__')(x,y)])} 6726 var enumerate=$B.make_class("enumerate",function(){var $ns=$B.args("enumerate",2,{iterable:null,start:null},['iterable','start'],arguments,{start:0},null,null),_iter=iter($ns["iterable"]),start=$ns["start"] 6727 return{ 6728 __class__:enumerate,__name__:'enumerate iterator',counter:start-1,iter:_iter,start:start}} 6729 ) 6730 enumerate.__iter__=function(self){self.counter=self.start-1 6731 return self} 6732 enumerate.__next__=function(self){self.counter++ 6733 return $B.fast_tuple([self.counter,next(self.iter)])} 6734 $B.set_func_names(enumerate,"builtins") 6735 $B.from_alias=function(attr){if(attr.substr(0,2)=='$$' && $B.aliased_names[attr.substr(2)]){return attr.substr(2)} 6736 return attr} 6737 $B.to_alias=function(attr){if($B.aliased_names[attr]){return '$$'+attr} 6738 return attr} 6739 function $$eval(src,_globals,_locals){var $=$B.args("eval",4,{src:null,globals:null,locals:null,mode:null},["src","globals","locals","mode"],arguments,{globals:_b_.None,locals:_b_.None,mode:"eval"},null,null),src=$.src,_globals=$.globals,_locals=$.locals,mode=$.mode 6740 if($.src.mode && $.src.mode=="single" && 6741 ["<console>","<stdin>"].indexOf($.src.filename)>-1){ 6742 _b_.print(">",$.src.source.trim())} 6743 var current_frame=$B.frames_stack[$B.frames_stack.length-1] 6744 if(current_frame !==undefined){var current_locals_id=current_frame[0].replace(/\./g,'_'),current_globals_id=current_frame[2].replace(/\./g,'_')} 6745 var stack_len=$B.frames_stack.length 6746 if(src.__class__===code){mode=src.mode 6747 src=src.source}else if(typeof src !=='string'){throw _b_.TypeError.$factory("eval() arg 1 must be a string, bytes "+ 6748 "or code object")} 6749 var globals_id='$exec_'+$B.UUID(),globals_name=globals_id,locals_id='$exec_'+$B.UUID(),parent_scope 6750 if(_globals===_b_.None){if(current_locals_id==current_globals_id){locals_id=globals_id} 6751 var local_scope={module:globals_id,id:locals_id,binding:{},bindings:{}} 6752 for(var attr in current_frame[1]){local_scope.binding[attr]=true 6753 local_scope.bindings[attr]=true} 6754 var global_scope={module:globals_id,id:globals_id,binding:{},bindings:{}} 6755 for(var attr in current_frame[3]){global_scope.binding[attr]=true 6756 global_scope.bindings[attr]=true} 6757 local_scope.parent_block=global_scope 6758 global_scope.parent_block=$B.builtins_scope 6759 parent_scope=local_scope 6760 eval("$locals_"+parent_scope.id+" = current_frame[1]")}else{ 6761 if(_globals.__class__ !=_b_.dict){throw _b_.TypeError.$factory("exec() globals must be a dict, not "+ 6762 $B.class_name(_globals))} 6763 if(_globals.globals_id){globals_id=globals_name=_globals.globals_id} 6764 _globals.globals_id=globals_id 6765 if(_locals===_globals ||_locals===_b_.None){locals_id=globals_id 6766 parent_scope=$B.builtins_scope}else{ 6767 var grandparent_scope={id:globals_id,parent_block:$B.builtins_scope,binding:{}} 6768 parent_scope={id:locals_id,parent_block:grandparent_scope,binding:{}} 6769 for(var attr in _globals.$string_dict){grandparent_scope.binding[attr]=true} 6770 for(var attr in _locals.$string_dict){parent_scope.binding[attr]=true}}} 6771 $B.$py_module_path[globals_id]=$B.$py_module_path[current_globals_id] 6772 eval('var $locals_'+globals_id+' = {}\nvar $locals_'+ 6773 locals_id+' = {}') 6774 if(_globals===_b_.None){var gobj=current_frame[3],ex='var $locals_'+globals_id+' = gobj;',obj={} 6775 eval(ex) 6776 for(var attr in gobj){if(attr.startsWith("$")&& !attr.startsWith("$$")){continue} 6777 obj[attr]=gobj[attr]} 6778 eval("$locals_"+globals_id+" = obj")}else{var globals_is_dict=false 6779 if(_globals.$jsobj){var items=_globals.$jsobj}else{var items=_b_.dict.$to_obj(_globals) 6780 _globals.$jsobj=items 6781 globals_is_dict=true} 6782 eval("$locals_"+globals_id+" = _globals.$jsobj") 6783 for(var item in items){var item1=$B.to_alias(item) 6784 try{eval('$locals_'+globals_id+'["'+item+'"] = items.'+item)}catch(err){console.log(err) 6785 console.log('error setting',item) 6786 break}}} 6787 _globals.$is_namespace=true 6788 if(_locals===_b_.None){if(_globals !==_b_.None){eval('var $locals_'+locals_id+' = $locals_'+globals_id)}else{var lobj=current_frame[1],ex='',obj={} 6789 for(var attr in current_frame[1]){if(attr.startsWith("$")&& !attr.startsWith("$$")){continue} 6790 obj[attr]=lobj[attr]} 6791 eval('$locals_'+locals_id+" = obj")}}else{var locals_is_dict=false 6792 if(_locals.$jsobj){var items=_locals.$jsobj}else{locals_id_dict=true 6793 var items=_b_.dict.$to_obj(_locals) 6794 _locals.$jsobj=items} 6795 for(var item in items){var item1=$B.to_alias(item) 6796 try{eval('$locals_'+locals_id+'["'+item+'"] = items.'+item)}catch(err){console.log(err) 6797 console.log('error setting',item) 6798 break}} 6799 eval("$locals_"+locals_id+".$exec_locals = true")} 6800 _locals.$is_namespace=true 6801 if(_globals===_b_.None && _locals===_b_.None && 6802 current_frame[0]==current_frame[2]){}else{eval("$locals_"+locals_id+".$src = src")} 6803 var root=$B.py2js(src,globals_id,locals_id,parent_scope),js,gns,lns 6804 if(_globals !==_b_.None && _locals==_b_.None){for(var attr in _globals.$string_dict){root.binding[attr]=true}} 6805 try{ 6806 var try_node=root.children[root.children.length-2],instr=try_node.children[try_node.children.length-2] 6807 var type=instr.C.tree[0].type 6808 switch(type){case 'expr': 6809 case 'list_or_tuple': 6810 case 'op': 6811 case 'ternary': 6812 var children=try_node.children 6813 root.children.splice(root.children.length-2,2) 6814 for(var i=0;i < children.length-1;i++){root.add(children[i])} 6815 break 6816 default: 6817 if(mode=="eval"){throw _b_.SyntaxError.$factory( 6818 "eval() argument must be an expression",'<string>',1,1,src)}} 6819 if(mode !="eval"){ 6820 var last=$B.last(root.children),js=last.to_js() 6821 if(["node_js"].indexOf(last.C.type)==-1){last.to_js=function(){while(js.endsWith("\n")){js=js.substr(0,js.length-1)} 6822 while(js.endsWith(";")){js=js.substr(0,js.length-1)} 6823 return "return ("+js+")"}} 6824 js=root.to_js() 6825 var locals_obj=eval("$locals_"+locals_id),globals_obj=eval("$locals_"+globals_id) 6826 if(_globals===_b_.None){var res=new Function("$locals_"+globals_id,"$locals_"+locals_id,js)( 6827 globals_obj,locals_obj)}else{current_globals_obj=current_frame[3] 6828 current_locals_obj=current_frame[1] 6829 var res=new Function("$locals_"+globals_id,"$locals_"+locals_id,"$locals_"+current_globals_id,"$locals_"+current_locals_id,js)(globals_obj,locals_obj,current_globals_obj,current_locals_obj)} 6830 if($.src.mode && $.src.mode=="single" && 6831 $.src.filename=="<stdin>"){if(res !==_b_.None && res !==undefined){_b_.print(_b_.repr(res))}}}else{js=root.to_js() 6832 var res=eval(js)} 6833 if($.src.filename=="<console>" && $.src.mode=="single" && 6834 res !==undefined && res !==_b_.None){_b_.print(res)} 6835 gns=eval("$locals_"+globals_id) 6836 if($B.frames_stack[$B.frames_stack.length-1][2]==globals_id){gns=$B.frames_stack[$B.frames_stack.length-1][3]} 6837 if(_locals !==_b_.None){lns=eval("$locals_"+locals_id) 6838 for(var attr in lns){var attr1=$B.from_alias(attr) 6839 if(attr1.charAt(0)!='$'){if(_locals.$jsobj){_locals.$jsobj[attr]=lns[attr]}else{_b_.dict.$setitem(_locals,attr1,lns[attr])}}}}else{for(var attr in lns){if(attr !=="$src"){current_frame[1][attr]=lns[attr]}}} 6840 if(_globals !==_b_.None){ 6841 if(globals_is_dict){var jsobj=_globals.$jsobj 6842 delete _globals.$jsobj} 6843 for(var attr in gns){attr1=$B.from_alias(attr) 6844 if(attr1.charAt(0)!='$'){if(globals_is_dict){_b_.dict.$setitem(_globals,attr,gns[attr])}else{_globals.$jsobj[attr1]=gns[attr]}}} 6845 for(var attr in _globals.$string_dict){if(attr.startsWith("$")&& !attr.startsWith("$$")){delete _globals.$string_dict[attr]}}}else{for(var attr in gns){if(attr !=="$src"){current_frame[3][attr]=gns[attr]}}} 6846 if(res===undefined){return _b_.None} 6847 return res}catch(err){err.src=src 6848 err.module=globals_id 6849 if(err.$py_error===undefined){throw $B.exception(err)} 6850 throw err}finally{ 6851 if($B.frames_stack.length==stack_len+1){$B.frames_stack.pop()} 6852 root=null 6853 js=null 6854 gns=null 6855 lns=null 6856 $B.clear_ns(globals_id) 6857 $B.clear_ns(locals_id)}} 6858 $$eval.$is_func=true 6859 function exec(src,globals,locals){var missing={} 6860 var $=$B.args("exec",3,{src:null,globals:null,locals:null},["src","globals","locals"],arguments,{globals:_b_.None,locals:_b_.None},null,null),src=$.src,globals=$.globals,locals=$.locals 6861 return $$eval(src,globals,locals,"exec")||_b_.None} 6862 exec.$is_func=true 6863 function exit(){throw _b_.SystemExit} 6864 exit.__repr__=exit.__str__=function(){return "Use exit() or Ctrl-Z plus Return to exit"} 6865 var filter=$B.make_class("filter",function(func,iterable){check_no_kw('filter',func,iterable) 6866 check_nb_args('filter',2,arguments) 6867 iterable=iter(iterable) 6868 if(func===_b_.None){func=$B.$bool} 6869 return{ 6870 __class__:filter,func:func,iterable:iterable}} 6871 ) 6872 filter.__iter__=function(self){return self} 6873 filter.__next__=function(self){while(true){var _item=next(self.iterable) 6874 if(self.func(_item)){return _item}}} 6875 $B.set_func_names(filter,"builtins") 6876 function format(value,format_spec){var $=$B.args("format",2,{value:null,format_spec:null},["value","format_spec"],arguments,{format_spec:''},null,null) 6877 var klass=value.__class__ ||$B.get_class(value) 6878 try{var method=$B.$getattr(klass,'__format__')}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.NotImplementedError("__format__ is not implemented "+ 6879 "for object '"+_b_.str.$factory(value)+"'")} 6880 throw err} 6881 return $B.$call(method)(value,$.format_spec)} 6882 function attr_error(attr,cname){var msg="bad operand type for unary #: '"+cname+"'" 6883 switch(attr){case '__neg__': 6884 throw _b_.TypeError.$factory(msg.replace('#','-')) 6885 case '__pos__': 6886 throw _b_.TypeError.$factory(msg.replace('#','+')) 6887 case '__invert__': 6888 throw _b_.TypeError.$factory(msg.replace('#','~')) 6889 case '__call__': 6890 throw _b_.TypeError.$factory("'"+cname+"'"+ 6891 ' object is not callable') 6892 default: 6893 while(attr.charAt(0)=='$'){attr=attr.substr(1)} 6894 throw _b_.AttributeError.$factory("'"+cname+ 6895 "' object has no attribute '"+attr+"'")}} 6896 function getattr(){var missing={} 6897 var $=$B.args("getattr",3,{obj:null,attr:null,_default:null},["obj","attr","_default"],arguments,{_default:missing},null,null) 6898 return $B.$getattr($.obj,$.attr,$._default===missing ? undefined :$._default)} 6899 function in_mro(klass,attr){if(klass===undefined){return false} 6900 if(klass.hasOwnProperty(attr)){return klass[attr]} 6901 var mro=klass.__mro__ 6902 for(var i=0,len=mro.length;i < len;i++){if(mro[i].hasOwnProperty(attr)){return mro[i][attr]}} 6903 return false} 6904 $B.$getattr=function(obj,attr,_default){ 6905 attr=$B.to_alias(attr) 6906 if(obj.$method_cache && 6907 obj.$method_cache[attr]&& 6908 obj.__class__ && 6909 obj.__class__[attr]==obj.$method_cache[attr][1]){ 6910 return obj.$method_cache[attr][0]} 6911 var rawname=attr 6912 if(obj===undefined){console.log("get attr",attr,"of undefined")} 6913 var is_class=obj.$is_class ||obj.$factory 6914 var klass=obj.__class__ 6915 var $test=false 6916 if($test){console.log("$getattr",attr,obj,klass)} 6917 if(klass !==undefined && klass.__bases__ && 6918 (klass.__bases__.length==0 || 6919 (klass.__bases__.length==1 && 6920 klass.__bases__[0]===_b_.object))){if(obj.hasOwnProperty(attr)){return obj[attr]}else if(obj.__dict__ && 6921 obj.__dict__.$string_dict.hasOwnProperty(attr)&& 6922 !(klass.hasOwnProperty(attr)&& 6923 klass[attr].__get__)){return obj.__dict__.$string_dict[attr][0]}else if(klass.hasOwnProperty(attr)){if(typeof klass[attr]!="function" && 6924 attr !="__dict__" && 6925 klass[attr].__get__===undefined){var kl=klass[attr].__class__ 6926 if(! in_mro(kl,"__get__")){return klass[attr]}}}} 6927 if($test){console.log("attr",attr,"of",obj,"class",klass,"isclass",is_class)} 6928 if(klass===undefined){ 6929 if(typeof obj=='string'){klass=_b_.str} 6930 else if(typeof obj=='number'){klass=obj % 1==0 ? _b_.int :_b_.float}else if(obj instanceof Number){klass=_b_.float}else{klass=$B.get_class(obj) 6931 if(klass===undefined){ 6932 if($test){console.log("no class",attr,obj.hasOwnProperty(attr),obj[attr])} 6933 var res=obj[attr] 6934 if(res !==undefined){if(typeof res=="function"){var f=function(){ 6935 return res.apply(obj,arguments)} 6936 f.$infos={__name__:attr,__qualname__:attr} 6937 return f}else{return $B.$JS2Py(res)}} 6938 if(_default !==undefined){return _default} 6939 throw _b_.AttributeError.$factory('object has no attribute '+rawname)}}} 6940 switch(attr){case '__call__': 6941 if(typeof obj=='function'){var res=function(){return obj.apply(null,arguments)} 6942 res.__class__=method_wrapper 6943 res.$infos={__name__:"__call__"} 6944 return res} 6945 break 6946 case '__class__': 6947 return klass 6948 case '__dict__': 6949 if(is_class){var proxy={} 6950 for(var key in obj){var key1=$B.from_alias(key) 6951 if(! key1.startsWith("$")){proxy[key1]=obj[key]}} 6952 proxy.__dict__=$B.getset_descriptor.$factory(obj,"__dict__") 6953 return $B.mappingproxy.$factory(proxy)}else{if(obj.hasOwnProperty(attr)){return obj[attr]}else if(obj.$infos){if(obj.$infos.hasOwnProperty("__dict__")){return obj.$infos.__dict__}else if(obj.$infos.hasOwnProperty("__func__")){return obj.$infos.__func__.$infos.__dict__}} 6954 return $B.obj_dict(obj)} 6955 case '__doc__': 6956 for(var i=0;i < builtin_names.length;i++){if(obj===_b_[builtin_names[i]]){_get_builtins_doc() 6957 return $B.builtins_doc[builtin_names[i]]}} 6958 break 6959 case '__mro__': 6960 if(obj.$is_class){ 6961 return _b_.tuple.$factory([obj].concat(obj.__mro__))}else if(obj.__dict__ && 6962 obj.__dict__.$string_dict.__mro__ !==undefined){return obj.__dict__.$string_dict.__mro__} 6963 throw _b_.AttributeError.$factory(attr) 6964 case '__subclasses__': 6965 if(klass.$factory ||klass.$is_class){var subclasses=obj.$subclasses ||[] 6966 return function(){return subclasses}} 6967 break} 6968 if(typeof obj=='function'){var value=obj[attr] 6969 if(value !==undefined){if(attr=='__module__'){return value}}} 6970 if((! is_class)&& klass.$native){if(obj.$method_cache && obj.$method_cache[attr]){return obj.$method_cache[attr]} 6971 if($test){console.log("native class",klass,klass[attr])} 6972 if(attr=="__doc__" && klass[attr]===undefined && klass.$infos){_get_builtins_doc() 6973 klass[attr]=$B.builtins_doc[klass.$infos.__name__]} 6974 if(klass[attr]===undefined){var object_attr=_b_.object[attr] 6975 if($test){console.log("object attr",object_attr)} 6976 if(object_attr !==undefined){klass[attr]=object_attr}else{if($test){console.log("obj[attr]",obj[attr])} 6977 var attrs=obj.__dict__ 6978 if(attrs && 6979 (object_attr=attrs.$string_dict[attr])!==undefined){return object_attr[0]} 6980 if(_default===undefined){attr_error(attr,klass.$infos.__name__)} 6981 return _default}} 6982 if(klass.$descriptors && klass.$descriptors[attr]!==undefined){return klass[attr](obj)} 6983 if(typeof klass[attr]=='function'){var func=klass[attr] 6984 if(attr=='__new__'){func.$type="staticmethod"} 6985 if(func.$type=="staticmethod"){return func} 6986 var self=klass[attr].__class__==$B.method ? klass :obj,method=klass[attr].bind(null,self) 6987 method.__class__=$B.method 6988 method.$infos={__func__:func,__name__:attr,__self__:self,__qualname__:klass.$infos.__name__+"."+attr} 6989 if(typeof obj=="object"){ 6990 obj.__class__=klass 6991 obj.$method_cache=obj.$method_cache ||{} 6992 obj.$method_cache[attr]=method} 6993 return method}else if(klass[attr]!==undefined){return klass[attr]} 6994 attr_error(rawname,klass.$infos.__name__)} 6995 var mro,attr_func 6996 if(is_class){attr_func=_b_.type.__getattribute__ }else{attr_func=klass.__getattribute__ 6997 if(attr_func===undefined){var mro=klass.__mro__ 6998 if(mro===undefined){console.log(obj,attr,"no mro, klass",klass)} 6999 for(var i=0,len=mro.length;i < len;i++){attr_func=mro[i]['__getattribute__'] 7000 if(attr_func !==undefined){break}}}} 7001 if(typeof attr_func !=='function'){console.log(attr+' is not a function '+attr_func,klass)} 7002 var odga=_b_.object.__getattribute__ 7003 if($test){console.log("attr_func is odga",attr_func,attr_func===odga,obj[attr])} 7004 if(attr_func===odga){var res=obj[attr] 7005 if(Array.isArray(obj)&& Array.prototype[attr]!==undefined){ 7006 res=undefined} 7007 if(res===null){return null} 7008 else if(res===undefined && obj.hasOwnProperty(attr)){return res}else if(res !==undefined){if($test){console.log(obj,attr,obj[attr],res.__set__ ||res.$is_class)} 7009 if(res.__set__===undefined ||res.$is_class){if($test){console.log("return",res,res+'',res.__set__,res.$is_class)} 7010 return res}}} 7011 try{var res=attr_func(obj,attr) 7012 if($test){console.log("result of attr_func",res)}}catch(err){if(_default !==undefined){return _default} 7013 throw err} 7014 if(res !==undefined){return res} 7015 if(_default !==undefined){return _default} 7016 var cname=klass.$infos.__name__ 7017 if(is_class){cname=obj.$infos.__name__} 7018 attr_error(rawname,cname)} 7019 function globals(){ 7020 check_nb_args('globals',0,arguments) 7021 var res=$B.obj_dict($B.last($B.frames_stack)[3]) 7022 res.$jsobj.__BRYTHON__=$B.JSObj.$factory($B) 7023 res.$is_namespace=true 7024 return res} 7025 function hasattr(obj,attr){check_no_kw('hasattr',obj,attr) 7026 check_nb_args('hasattr',2,arguments) 7027 try{$B.$getattr(obj,attr);return true} 7028 catch(err){return false}} 7029 var hash_cache={} 7030 function hash(obj){check_no_kw('hash',obj) 7031 check_nb_args('hash',1,arguments) 7032 if(obj.__hashvalue__ !==undefined){return obj.__hashvalue__} 7033 if(isinstance(obj,_b_.bool)){return _b_.int.$factory(obj)} 7034 if(isinstance(obj,_b_.int)){if(obj.$brython_value===undefined){return obj.valueOf()}else{ 7035 return obj.__hashvalue__=obj.$brython_value}} 7036 if(obj.$is_class || 7037 obj.__class__===_b_.type || 7038 obj.__class__===$B.Function){return obj.__hashvalue__=$B.$py_next_hash--} 7039 if(typeof obj=="string"){var cached=hash_cache[obj] 7040 if(cached !==undefined){return cached} 7041 else{return hash_cache[obj]=_b_.str.__hash__(obj)}} 7042 var klass=obj.__class__ ||$B.get_class(obj) 7043 if(klass===undefined){throw _b_.TypeError.$factory("unhashable type: '"+ 7044 _b_.str.$factory($B.JSObj.$factory(obj))+"'")} 7045 var hash_method=$B.$getattr(klass,'__hash__',_b_.None) 7046 if(hash_method===_b_.None){throw _b_.TypeError.$factory("unhashable type: '"+ 7047 $B.class_name(obj)+"'")} 7048 if(hash_method.$infos.__func__===_b_.object.__hash__){if($B.$getattr(obj,'__eq__').$infos.__func__ !==_b_.object.__eq__){throw _b_.TypeError.$factory("unhashable type: '"+ 7049 $B.class_name(obj)+"'",'hash')}else{return obj.__hashvalue__=_b_.object.__hash__(obj)}}else{return $B.$call(hash_method)(obj)}} 7050 function _get_builtins_doc(){if($B.builtins_doc===undefined){ 7051 var url=$B.brython_path 7052 if(url.charAt(url.length-1)=='/'){url=url.substr(0,url.length-1)} 7053 url+='/builtins_docstrings.js' 7054 var f=_b_.open(url) 7055 eval(f.$string) 7056 $B.builtins_doc=docs}} 7057 function help(obj){if(obj===undefined){obj='help'} 7058 if(typeof obj=='string' && _b_[obj]!==undefined){_get_builtins_doc() 7059 var _doc=$B.builtins_doc[obj] 7060 if(_doc !==undefined && _doc !=''){_b_.print(_doc) 7061 return}} 7062 for(var i=0;i < builtin_names.length;i++){if(obj===_b_[builtin_names[i]]){_get_builtins_doc() 7063 _b_.print(_doc=$B.builtins_doc[builtin_names[i]])}} 7064 if(typeof obj=='string'){$B.$import("pydoc"); 7065 var pydoc=$B.imported["pydoc"] 7066 $B.$getattr($B.$getattr(pydoc,"help"),"__call__")(obj) 7067 return} 7068 try{return $B.$getattr(obj,'__doc__')} 7069 catch(err){return ''}} 7070 help.__repr__=help.__str__=function(){return "Type help() for interactive help, or help(object) "+ 7071 "for help about object."} 7072 function hex(obj){check_no_kw('hex',obj) 7073 check_nb_args('hex',1,arguments) 7074 return bin_hex_oct(16,obj)} 7075 function id(obj){check_no_kw('id',obj) 7076 check_nb_args('id',1,arguments) 7077 if(isinstance(obj,[_b_.str,_b_.int,_b_.float])&& 7078 !isinstance(obj,$B.long_int)){return $B.$getattr(_b_.str.$factory(obj),'__hash__')()}else if(obj.$id !==undefined){return obj.$id} 7079 else{return obj.$id=$B.UUID()}} 7080 function __import__(mod_name,globals,locals,fromlist,level){ 7081 var $=$B.args('__import__',5,{name:null,globals:null,locals:null,fromlist:null,level:null},['name','globals','locals','fromlist','level'],arguments,{globals:None,locals:None,fromlist:_b_.tuple.$factory(),level:0},null,null) 7082 return $B.$__import__($.name,$.globals,$.locals,$.fromlist)} 7083 function input(msg){var res=prompt(msg ||'')||'' 7084 if($B.imported["sys"]&& $B.imported["sys"].ps1){ 7085 var ps1=$B.imported["sys"].ps1,ps2=$B.imported["sys"].ps2 7086 if(msg==ps1 ||msg==ps2){console.log(msg,res)}} 7087 return res} 7088 function isinstance(obj,cls){check_no_kw('isinstance',obj,cls) 7089 check_nb_args('isinstance',2,arguments) 7090 if(obj===null){return cls===None} 7091 if(obj===undefined){return false} 7092 if(cls.constructor===Array){for(var i=0;i < cls.length;i++){if(isinstance(obj,cls[i])){return true}} 7093 return false} 7094 if(cls.__class__===$B.GenericAlias){ 7095 throw _b_.TypeError.$factory( 7096 'isinstance() arg 2 cannot be a parameterized generic')} 7097 if(!cls.__class__ || 7098 !(cls.$factory !==undefined ||cls.$is_class !==undefined)){throw _b_.TypeError.$factory("isinstance() arg 2 must be a type "+ 7099 "or tuple of types")} 7100 if(cls===_b_.int &&(obj===True ||obj===False)){return True} 7101 if(cls===_b_.bool){switch(typeof obj){case "string": 7102 return false 7103 case "number": 7104 return false 7105 case "boolean": 7106 return true}} 7107 var klass=obj.__class__ 7108 if(klass==undefined){if(typeof obj=='string'){if(cls==_b_.str){return true} 7109 else if($B.builtin_classes.indexOf(cls)>-1){return false}}else if(obj.contructor===Number && Number.isFinite(obj)){if(cls==_b_.float){return true}}else if(typeof obj=='number' && Number.isFinite(obj)){if(Number.isFinite(obj)&& cls==_b_.int){return true}} 7110 klass=$B.get_class(obj)} 7111 if(klass===undefined){return false} 7112 function check(kl,cls){if(kl===cls){return true} 7113 else if(cls===_b_.str && kl===$B.StringSubclass){return true} 7114 else if(cls===_b_.int && kl===$B.IntSubclass){return true}} 7115 if(check(klass,cls)){return true} 7116 var mro=klass.__mro__ 7117 for(var i=0;i < mro.length;i++){if(check(mro[i],cls)){return true}} 7118 var instancecheck=$B.$getattr(cls.__class__ ||$B.get_class(cls),'__instancecheck__',_b_.None) 7119 if(instancecheck !==_b_.None){return instancecheck(cls,obj)} 7120 return false} 7121 function issubclass(klass,classinfo){check_no_kw('issubclass',klass,classinfo) 7122 check_nb_args('issubclass',2,arguments) 7123 if(!klass.__class__ || 7124 !(klass.$factory !==undefined ||klass.$is_class !==undefined)){throw _b_.TypeError.$factory("issubclass() arg 1 must be a class")} 7125 if(isinstance(classinfo,_b_.tuple)){for(var i=0;i < classinfo.length;i++){if(issubclass(klass,classinfo[i])){return true}} 7126 return false} 7127 if(classinfo.__class__===$B.GenericAlias){throw _b_.TypeError.$factory( 7128 'issubclass() arg 2 cannot be a parameterized generic')} 7129 if(classinfo.$factory ||classinfo.$is_class){if(klass===classinfo || 7130 klass.__mro__.indexOf(classinfo)>-1){return true}} 7131 var sch=$B.$getattr(classinfo.__class__ ||$B.get_class(classinfo),'__subclasscheck__',_b_.None) 7132 if(sch==_b_.None){return false} 7133 return sch(classinfo,klass)} 7134 var iterator_class=$B.make_class("iterator",function(getitem,len){return{ 7135 __class__:iterator_class,getitem:getitem,len:len,counter:-1}} 7136 ) 7137 iterator_class.__next__=function(self){self.counter++ 7138 if(self.len !==null && self.counter==self.len){throw _b_.StopIteration.$factory('')} 7139 try{return self.getitem(self.counter)} 7140 catch(err){throw _b_.StopIteration.$factory('')}} 7141 callable_iterator=$B.make_class("callable_iterator",function(func,sentinel){return{ 7142 __class__:callable_iterator,func:func,sentinel:sentinel}} 7143 ) 7144 callable_iterator.__iter__=function(self){return self} 7145 callable_iterator.__next__=function(self){var res=self.func() 7146 if($B.rich_comp("__eq__",res,self.sentinel)){throw _b_.StopIteration.$factory()} 7147 return res} 7148 $B.$iter=function(obj,sentinel){ 7149 if(sentinel===undefined){var klass=obj.__class__ ||$B.get_class(obj) 7150 try{var _iter=$B.$call($B.$getattr(klass,'__iter__'))}catch(err){if(err.__class__===_b_.AttributeError){try{var gi_method=$B.$call($B.$getattr(klass,'__getitem__')),gi=function(i){return gi_method(obj,i)},ln=len(obj) 7151 return iterator_class.$factory(gi,len)}catch(err){throw _b_.TypeError.$factory("'"+$B.class_name(obj)+ 7152 "' object is not iterable")}} 7153 throw err} 7154 var res=$B.$call(_iter)(obj) 7155 try{$B.$getattr(res,'__next__')} 7156 catch(err){if(isinstance(err,_b_.AttributeError)){throw _b_.TypeError.$factory( 7157 "iter() returned non-iterator of type '"+ 7158 $B.class_name(res)+"'")}} 7159 return res}else{return callable_iterator.$factory(obj,sentinel)}} 7160 function iter(){ 7161 var $=$B.args('iter',1,{obj:null},['obj'],arguments,{},'args','kw'),sentinel 7162 if($.args.length > 0){var sentinel=$.args[0]} 7163 return $B.$iter($.obj,sentinel)} 7164 function len(obj){check_no_kw('len',obj) 7165 check_nb_args('len',1,arguments) 7166 var klass=obj.__class__ ||$B.get_class(obj) 7167 try{var method=$B.$getattr(klass,'__len__')}catch(err){throw _b_.TypeError.$factory("object of type '"+ 7168 $B.class_name(obj)+"' has no len()")} 7169 return $B.$call(method)(obj)} 7170 function locals(){ 7171 check_nb_args('locals',0,arguments) 7172 var res=$B.obj_dict($B.last($B.frames_stack)[1]) 7173 res.$is_namespace=true 7174 delete res.$jsobj.__annotations__ 7175 return res} 7176 var map=$B.make_class("map",function(){var $=$B.args('map',2,{func:null,it1:null},['func','it1'],arguments,{},'args',null),func=$B.$call($.func) 7177 var iter_args=[$B.$iter($.it1)] 7178 $.args.forEach(function(item){iter_args.push($B.$iter(item))}) 7179 var obj={__class__:map,args:iter_args,func:func} 7180 return obj} 7181 ) 7182 map.__iter__=function(self){return self} 7183 map.__next__=function(self){var args=[] 7184 for(var i=0;i < self.args.length;i++){args.push(next(self.args[i]))} 7185 return self.func.apply(null,args)} 7186 $B.set_func_names(map,"builtins") 7187 function $extreme(args,op){ 7188 var $op_name='min' 7189 if(op==='__gt__'){$op_name="max"} 7190 if(args.length==0){throw _b_.TypeError.$factory($op_name+ 7191 " expected 1 arguments, got 0")} 7192 var last_arg=args[args.length-1],nb_args=args.length,has_default=false,func=false 7193 if(last_arg.$nat=='kw'){nb_args-- 7194 last_arg=last_arg.kw 7195 for(var attr in last_arg){switch(attr){case 'key': 7196 func=last_arg[attr] 7197 break 7198 case '$$default': 7199 var default_value=last_arg[attr] 7200 has_default=true 7201 break 7202 default: 7203 throw _b_.TypeError.$factory("'"+attr+ 7204 "' is an invalid keyword argument for this function")}}} 7205 if(!func){func=function(x){return x}} 7206 if(nb_args==0){throw _b_.TypeError.$factory($op_name+" expected 1 argument, got 0")}else if(nb_args==1){ 7207 var $iter=iter(args[0]),res=null 7208 while(true){try{var x=next($iter) 7209 if(res===null ||$B.$bool($B.$getattr(func(x),op)(func(res)))){res=x}}catch(err){if(err.__class__==_b_.StopIteration){if(res===null){if(has_default){return default_value} 7210 else{throw _b_.ValueError.$factory($op_name+ 7211 "() arg is an empty sequence")}}else{return res}} 7212 throw err}}}else{if(has_default){throw _b_.TypeError.$factory("Cannot specify a default for "+ 7213 $op_name+"() with multiple positional arguments")} 7214 var res=null 7215 for(var i=0;i < nb_args;i++){var x=args[i] 7216 if(res===null ||$B.$bool($B.$getattr(func(x),op)(func(res)))){res=x}} 7217 return res}} 7218 function max(){return $extreme(arguments,'__gt__')} 7219 var memoryview=$B.make_class('memoryview',function(obj){check_no_kw('memoryview',obj) 7220 check_nb_args('memoryview',1,arguments) 7221 if(obj.__class__===memoryview){return obj} 7222 if($B.get_class(obj).$buffer_protocol){return{ 7223 __class__:memoryview,obj:obj, 7224 format:'B',itemsize:1,ndim:1,shape:_b_.tuple.$factory([_b_.len(obj)]),strides:_b_.tuple.$factory([1]),suboffsets:_b_.tuple.$factory([]),c_contiguous:true,f_contiguous:true,contiguous:true}}else{throw _b_.TypeError.$factory("memoryview: a bytes-like object "+ 7225 "is required, not '"+$B.class_name(obj)+"'")}} 7226 ) 7227 memoryview.__eq__=function(self,other){if(other.__class__ !==memoryview){return false} 7228 return $B.$getattr(self.obj,'__eq__')(other.obj)} 7229 memoryview.__getitem__=function(self,key){if(isinstance(key,_b_.int)){var start=key*self.itemsize 7230 if(self.format=="I"){var res=self.obj.source[start],coef=256 7231 for(var i=1;i < 4;i++){res+=self.obj.source[start+i]*coef 7232 coef*=256} 7233 return res}else if("B".indexOf(self.format)>-1){if(key > self.obj.source.length-1){throw _b_.KeyError.$factory(key)} 7234 return self.obj.source[key]}else{ 7235 return self.obj.source[key]}} 7236 var res=self.obj.__class__.__getitem__(self.obj,key) 7237 if(key.__class__===_b_.slice){return memoryview.$factory(res)}} 7238 memoryview.__len__=function(self){return len(self.obj)/self.itemsize} 7239 memoryview.cast=function(self,format){switch(format){case "B": 7240 return memoryview.$factory(self.obj) 7241 case "I": 7242 var res=memoryview.$factory(self.obj),objlen=len(self.obj) 7243 res.itemsize=4 7244 res.format="I" 7245 if(objlen % 4 !=0){throw _b_.TypeError.$factory("memoryview: length is not "+ 7246 "a multiple of itemsize")} 7247 return res}} 7248 memoryview.hex=function(self){var res='',bytes=_b_.bytes.$factory(self) 7249 bytes.source.forEach(function(item){res+=item.toString(16)}) 7250 return res} 7251 memoryview.tobytes=function(self){return _b_.bytes.$factory(self.obj)} 7252 memoryview.tolist=function(self){if(self.itemsize==1){return _b_.list.$factory(_b_.bytes.$factory(self.obj))}else if(self.itemsize==4){if(self.format=="I"){var res=[] 7253 for(var i=0;i < self.obj.source.length;i+=4){var item=self.obj.source[i],coef=256 7254 for(var j=1;j < 4;j++){item+=coef*self.obj.source[i+j] 7255 coef*=256} 7256 res.push(item)} 7257 return res}}} 7258 $B.set_func_names(memoryview,"builtins") 7259 function min(){return $extreme(arguments,'__lt__')} 7260 function next(obj){check_no_kw('next',obj) 7261 var missing={},$=$B.args("next",2,{obj:null,def:null},['obj','def'],arguments,{def:missing},null,null) 7262 var klass=obj.__class__ ||$B.get_class(obj),ga=$B.$call($B.$getattr(klass,"__next__")) 7263 if(ga !==undefined){try{return $B.$call(ga)(obj)}catch(err){if(err.__class__===_b_.StopIteration && 7264 $.def !==missing){return $.def} 7265 throw err}} 7266 throw _b_.TypeError.$factory("'"+$B.class_name(obj)+ 7267 "' object is not an iterator")} 7268 var NotImplementedType=$B.make_class("NotImplementedType",function(){return NotImplemented} 7269 ) 7270 NotImplementedType.__repr__=NotImplementedType.__str__=function(self){return "NotImplemented"} 7271 var NotImplemented={__class__:NotImplementedType} 7272 function $not(obj){return !$B.$bool(obj)} 7273 function oct(obj){check_no_kw('oct',obj) 7274 check_nb_args('oct',1,arguments) 7275 return bin_hex_oct(8,obj)} 7276 function ord(c){check_no_kw('ord',c) 7277 check_nb_args('ord',1,arguments) 7278 if(typeof c=='string'){if(c.length==1){return c.charCodeAt(0)} 7279 throw _b_.TypeError.$factory('ord() expected a character, but '+ 7280 'string of length '+c.length+' found')} 7281 switch($B.get_class(c)){case _b_.str: 7282 if(c.length==1){return c.charCodeAt(0)} 7283 throw _b_.TypeError.$factory('ord() expected a character, but '+ 7284 'string of length '+c.length+' found') 7285 case _b_.str.$surrogate: 7286 if(c.items.length==1){return c.items[0].codePointAt(0)} 7287 throw _b_.TypeError.$factory('ord() expected a character, but '+ 7288 'string of length '+c.items.length+' found') 7289 case _b_.bytes: 7290 case _b_.bytearray: 7291 if(c.source.length==1){return c.source[0]} 7292 throw _b_.TypeError.$factory('ord() expected a character, but '+ 7293 'string of length '+c.source.length+' found') 7294 default: 7295 throw _b_.TypeError.$factory('ord() expected a character, but '+ 7296 $B.class_name(c)+' was found')}} 7297 function pow(){var $=$B.args('pow',3,{x:null,y:null,mod:null},['x','y','mod'],arguments,{mod:None},null,null),x=$.x,y=$.y,z=$.mod 7298 var klass=x.__class__ ||$B.get_class(x) 7299 if(z===_b_.None){return $B.$call($B.$getattr(klass,'__pow__'))(x,y)}else{if(x !=_b_.int.$factory(x)||y !=_b_.int.$factory(y)){throw _b_.TypeError.$factory("pow() 3rd argument not allowed "+ 7300 "unless all arguments are integers")} 7301 return $B.$call($B.$getattr(klass,'__pow__'))(x,y,z)}} 7302 function $print(){var $ns=$B.args('print',0,{},[],arguments,{},'args','kw') 7303 var ks=$ns['kw'].$string_dict 7304 var end=(ks['end']===undefined ||ks['end']===None)? '\n' :ks['end'][0],sep=(ks['sep']===undefined ||ks['sep']===None)? ' ' :ks['sep'][0],file=ks['file']===undefined ? $B.stdout :ks['file'][0],args=$ns['args'] 7305 var items=[] 7306 args.forEach(function(arg){items.push(_b_.str.$factory(arg))}) 7307 var res=items.join(sep)+end 7308 res=res.replace(new RegExp("\u0007","g"),""). 7309 replace(new RegExp("(.)\b","g"),"") 7310 $B.$getattr(file,'write')(res) 7311 var flush=$B.$getattr(file,'flush',None) 7312 if(flush !==None){flush()} 7313 return None} 7314 $print.__name__='print' 7315 $print.is_func=true 7316 var property=$B.make_class("property",function(fget,fset,fdel,doc){var res={__class__:property} 7317 property.__init__(res,fget,fset,fdel,doc) 7318 return res} 7319 ) 7320 property.__init__=function(self,fget,fset,fdel,doc){self.__doc__=doc ||"" 7321 self.$type=fget.$type 7322 self.fget=fget 7323 self.fset=fset 7324 self.fdel=fdel 7325 if(fget && fget.$attrs){for(var key in fget.$attrs){self[key]=fget.$attrs[key]}} 7326 self.__get__=function(self,obj,objtype){if(obj===undefined){return self} 7327 if(self.fget===undefined){throw _b_.AttributeError.$factory("unreadable attribute")} 7328 return $B.$call(self.fget)(obj)} 7329 if(fset !==undefined){self.__set__=function(self,obj,value){if(self.fset===undefined){throw _b_.AttributeError.$factory("can't set attribute")} 7330 $B.$getattr(self.fset,'__call__')(obj,value)}} 7331 self.__delete__=fdel; 7332 self.getter=function(fget){return property.$factory(fget,self.fset,self.fdel,self.__doc__)} 7333 self.setter=function(fset){return property.$factory(self.fget,fset,self.fdel,self.__doc__)} 7334 self.deleter=function(fdel){return property.$factory(self.fget,self.fset,fdel,self.__doc__)}} 7335 property.__repr__=function(self){return _b_.repr(self.fget(self))} 7336 property.__str__=function(self){return _b_.str.$factory(self.fget(self))} 7337 $B.set_func_names(property,"builtins") 7338 function quit(){throw _b_.SystemExit} 7339 quit.__repr__=quit.__str__=function(){return "Use quit() or Ctrl-Z plus Return to exit"} 7340 function repr(obj){check_no_kw('repr',obj) 7341 check_nb_args('repr',1,arguments) 7342 var klass=obj.__class__ ||$B.get_class(obj) 7343 return $B.$call($B.$getattr(klass,"__repr__"))(obj)} 7344 var reversed=$B.make_class("reversed",function(seq){ 7345 check_no_kw('reversed',seq) 7346 check_nb_args('reversed',1,arguments) 7347 var klass=seq.__class__ ||$B.get_class(seq),rev_method=$B.$getattr(klass,'__reversed__',null) 7348 if(rev_method !==null){return $B.$call(rev_method)(seq)} 7349 try{var method=$B.$getattr(klass,'__getitem__')}catch(err){throw _b_.TypeError.$factory("argument to reversed() must be a sequence")} 7350 var res={__class__:reversed,$counter :_b_.len(seq),getter:function(i){return $B.$call(method)(seq,i)}} 7351 return res} 7352 ) 7353 reversed.__iter__=function(self){return self} 7354 reversed.__next__=function(self){self.$counter-- 7355 if(self.$counter < 0){throw _b_.StopIteration.$factory('')} 7356 return self.getter(self.$counter)} 7357 $B.set_func_names(reversed,"builtins") 7358 function round(){var $=$B.args('round',2,{number:null,ndigits:null},['number','ndigits'],arguments,{ndigits:None},null,null),arg=$.number,n=$.ndigits===None ? 0 :$.ndigits 7359 if(!isinstance(arg,[_b_.int,_b_.float])){var klass=arg.__class__ ||$B.get_class(arg) 7360 try{return $B.$call($B.$getattr(klass,"__round__")).apply(null,arguments)}catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("type "+$B.class_name(arg)+ 7361 " doesn't define __round__ method")}else{throw err}}} 7362 if(isinstance(arg,_b_.float)&& 7363 (arg.value===Infinity ||arg.value===-Infinity)){throw _b_.OverflowError.$factory("cannot convert float infinity to integer")} 7364 if(!isinstance(n,_b_.int)){throw _b_.TypeError.$factory( 7365 "'"+$B.class_name(n)+"' object cannot be interpreted as an integer")} 7366 var mult=Math.pow(10,n),x=arg*mult,floor=Math.floor(x),diff=Math.abs(x-floor),res 7367 if(diff==0.5){if(floor % 2){floor+=1} 7368 res=_b_.int.__truediv__(floor,mult)}else{res=_b_.int.__truediv__(Math.round(x),mult)} 7369 if($.ndigits===None){ 7370 return res.valueOf()}else if(arg instanceof Number){return new Number(res)}else{return res.valueOf()}} 7371 function setattr(){var $=$B.args('setattr',3,{obj:null,attr:null,value:null},['obj','attr','value'],arguments,{},null,null),obj=$.obj,attr=$.attr,value=$.value 7372 if(!(typeof attr=='string')){throw _b_.TypeError.$factory("setattr(): attribute name must be string")} 7373 return $B.$setattr(obj,attr,value)} 7374 $B.$setattr=function(obj,attr,value){ 7375 var $test=false 7376 if($B.aliased_names[attr]){attr='$$'+attr}else if(attr=='__dict__'){ 7377 if(! isinstance(value,_b_.dict)){throw _b_.TypeError.$factory("__dict__ must be set to a dictionary, "+ 7378 "not a '"+$B.class_name(value)+"'")} 7379 if(obj.$infos){obj.$infos.__dict__=value 7380 return None} 7381 obj.__dict__=value 7382 return None}else if(attr=="__class__"){ 7383 function error(msg){throw _b_.TypeError.$factory(msg)} 7384 if(value.__class__){if(value.__module__=="builtins"){error("__class__ assignement only "+ 7385 "supported for heap types or ModuleType subclasses")}else if(Array.isArray(value.__bases__)){for(var i=0;i < value.__bases__.length;i++){if(value.__bases__[i].__module__=="builtins"){error("__class__ assignment: '"+$B.class_name(obj)+ 7386 "' object layout differs from '"+ 7387 $B.class_name(value)+"'")}}}} 7388 obj.__class__=value 7389 return None}else if(attr=="__doc__" && obj.__class__===_b_.property){obj[attr]=value} 7390 if($test){console.log("set attr",attr,"to",obj)} 7391 if(obj.$factory ||obj.$is_class){var metaclass=obj.__class__ 7392 if($test){console.log("obj is class",metaclass,metaclass[attr])} 7393 if(metaclass && metaclass[attr]&& metaclass[attr].__get__ && 7394 metaclass[attr].__set__){metaclass[attr].__set__(obj,value) 7395 return None} 7396 obj[attr]=value 7397 if(attr=="__init__" ||attr=="__new__"){ 7398 obj.$factory=$B.$instance_creator(obj)}else if(attr=="__bases__"){ 7399 obj.__mro__=_b_.type.mro(obj)} 7400 if($test){console.log("after setattr",obj)} 7401 return None} 7402 var res=obj[attr],klass=obj.__class__ ||$B.get_class(obj) 7403 if($test){console.log('set attr',attr,'of obj',obj,'class',klass,"obj[attr]",obj[attr])} 7404 if(res===undefined && klass){res=klass[attr] 7405 if(res===undefined){var mro=klass.__mro__,_len=mro.length 7406 for(var i=0;i < _len;i++){res=mro[i][attr] 7407 if(res !==undefined){break}}}} 7408 if($test){console.log('set attr',attr,'klass',klass,'found in class',res)} 7409 if(res !==undefined && res !==null){ 7410 if(res.__set__ !==undefined){res.__set__(res,obj,value);return None} 7411 var rcls=res.__class__,__set1__ 7412 if(rcls !==undefined){var __set1__=rcls.__set__ 7413 if(__set1__===undefined){var mro=rcls.__mro__ 7414 for(var i=0,_len=mro.length;i < _len;i++){__set1__=mro[i].__set__ 7415 if(__set1__){break}}}} 7416 if(__set1__ !==undefined){var __set__=$B.$getattr(res,'__set__',null) 7417 if(__set__ &&(typeof __set__=='function')){__set__.apply(res,[obj,value]) 7418 return None}}else if(klass && klass.$descriptors !==undefined && 7419 klass[attr]!==undefined){var setter=klass[attr].setter 7420 if(typeof setter=='function'){setter(obj,value) 7421 return None}else{throw _b_.AttributeError.$factory('readonly attribute')}}} 7422 var _setattr=false 7423 if(klass !==undefined){_setattr=klass.__setattr__ 7424 if(_setattr===undefined){var mro=klass.__mro__ 7425 for(var i=0,_len=mro.length-1;i < _len;i++){_setattr=mro[i].__setattr__ 7426 if(_setattr){break}}}} 7427 var special_attrs=["__module__"] 7428 if(klass && klass.__slots__ && special_attrs.indexOf(attr)==-1 && 7429 ! _setattr){function mangled_slots(klass){if(klass.__slots__){if(Array.isArray(klass.__slots__)){return klass.__slots__.map(function(item){if(item.startsWith("__")&& ! item.endsWith("_")){return "_"+klass.$infos.__name__+item}else{return item}})}else{return klass.__slots__}} 7430 return[]} 7431 var has_slot=false 7432 if(mangled_slots(klass).indexOf(attr)>-1){has_slot=true}else{for(var i=0;i < klass.__mro__.length;i++){var kl=klass.__mro__[i] 7433 if(mangled_slots(kl).indexOf(attr)>-1){has_slot=true 7434 break}}} 7435 if(! has_slot){throw _b_.AttributeError.$factory("'"+klass.$infos.__name__+ 7436 "' object has no attribute '"+attr+"'")}} 7437 if($test){console.log("attr",attr,"use _setattr",_setattr)} 7438 if(!_setattr){if(obj.__dict__===undefined){obj[attr]=value}else{_b_.dict.$setitem(obj.__dict__,attr,value)} 7439 if($test){console.log("no setattr, obj",obj)}}else{_setattr(obj,attr,value)} 7440 return None} 7441 function sorted(){var $=$B.args('sorted',1,{iterable:null},['iterable'],arguments,{},null,'kw') 7442 var _list=_b_.list.$factory(iter($.iterable)),args=[_list] 7443 for(var i=1;i < arguments.length;i++){args.push(arguments[i])} 7444 _b_.list.sort.apply(null,args) 7445 return _list} 7446 var staticmethod=$B.make_class("staticmethod",function(func){var f={$infos:func.$infos,__get__:function(){return func}} 7447 f.__get__.__class__=$B.method_wrapper 7448 f.__get__.$infos=func.$infos 7449 return f} 7450 ) 7451 $B.set_func_names(staticmethod,"builtins") 7452 function sum(iterable,start){var $=$B.args('sum',2,{iterable:null,start:null},['iterable','start'],arguments,{start:0},null,null),iterable=$.iterable,start=$.start 7453 if(_b_.isinstance(start,[_b_.str,_b_.bytes])){throw _b_.TypeError.$factory("TypeError: sum() can't sum bytes"+ 7454 " [use b''.join(seq) instead]")} 7455 var res=start,iterable=iter(iterable) 7456 while(1){try{var _item=next(iterable) 7457 res=$B.$getattr(res,'__add__')(_item)}catch(err){if(err.__class__===_b_.StopIteration){break}else{throw err}}} 7458 return res} 7459 $B.missing_super2=function(obj){obj.$missing=true 7460 return obj} 7461 var $$super=$B.make_class("super",function(_type,object_or_type){if(_type===undefined && object_or_type===undefined){var frame=$B.last($B.frames_stack),pyframe=$B.imported["_sys"].Getframe() 7462 if(pyframe.f_code && pyframe.f_code.co_varnames){_type=frame[1].__class__ 7463 if(_type===undefined){throw _b_.RuntimeError.$factory("super(): no arguments")} 7464 object_or_type=frame[1][pyframe.f_code.co_varnames[0]]}else{throw _b_.RuntimeError.$factory("super(): no arguments")}} 7465 if(Array.isArray(object_or_type)){object_or_type=object_or_type[0]} 7466 return{ 7467 __class__:$$super,__thisclass__:_type,__self_class__:object_or_type}} 7468 ) 7469 $$super.__get__=function(self,instance,klass){ 7470 return $$super.$factory(self.__thisclass__,instance)} 7471 $$super.__getattribute__=function(self,attr){var mro=self.__thisclass__.__mro__,res 7472 var sc=self.__self_class__ 7473 if(sc !==undefined){if(!sc.$is_class){sc=sc.__class__ ||$B.get_class(sc)} 7474 var sc_mro=[sc].concat(sc.__mro__) 7475 for(var i=0;i < sc_mro.length;i++){if(sc_mro[i]===self.__thisclass__){mro=sc_mro.slice(i+1) 7476 break}}} 7477 var $test=false 7478 var f 7479 for(var i=0,len=mro.length;i < len;i++){if(mro[i][attr]!==undefined){f=mro[i][attr] 7480 break}} 7481 if(f===undefined){if($$super[attr]!==undefined){return(function(x){return function(){var args=[x] 7482 for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} 7483 return $$super[attr].apply(null,args)}})(self)} 7484 if($test){console.log("no attr",attr,self,"mro",mro)} 7485 throw _b_.AttributeError.$factory(attr)} 7486 if($test){console.log("super",attr,self,"mro",mro,"found in mro[0]",mro[0],f,f+'')} 7487 if(f.$type=="staticmethod" ||attr=="__new__"){return f}else if(typeof f !="function"){return f}else{if(f.__class__===$B.method){ 7488 f=f.$infos.__func__} 7489 var callable=$B.$call(f) 7490 var method=function(){var res=callable(self.__self_class__,...arguments) 7491 if($test){console.log("calling super",self.__self_class__,attr,f,"res",res)} 7492 return res} 7493 method.__class__=$B.method 7494 var module 7495 if(f.$infos !==undefined){module=f.$infos.__module__}else if(f.__class__===property){module=f.fget.$infos.__module}else if(f.$is_class){module=f.__module__} 7496 method.$infos={__self__:self.__self_class__,__func__:f,__name__:attr,__module__:module,__qualname__:self.__thisclass__.$infos.__name__+"."+attr} 7497 return method} 7498 throw _b_.AttributeError.$factory("object 'super' has no attribute '"+ 7499 attr+"'")} 7500 $$super.__repr__=$$super.__str__=function(self){var res="<super: <class '"+self.__thisclass__.$infos.__name__+"'>" 7501 if(self.__self_class__ !==undefined){res+=', <'+self.__self_class__.__class__.$infos.__name__+' object>'}else{res+=', NULL'} 7502 return res+'>'} 7503 $B.set_func_names($$super,"builtins") 7504 function vars(){var def={},$=$B.args('vars',1,{obj:null},['obj'],arguments,{obj:def},null,null) 7505 if($.obj===def){return _b_.locals()}else{try{return $B.$getattr($.obj,'__dict__')} 7506 catch(err){if(err.__class__===_b_.AttributeError){throw _b_.TypeError.$factory("vars() argument must have __dict__ attribute")} 7507 throw err}}} 7508 var $Reader=$B.make_class("Reader") 7509 $Reader.__enter__=function(self){return self} 7510 $Reader.__exit__=function(self){return false} 7511 $Reader.__iter__=function(self){ 7512 return iter($Reader.readlines(self))} 7513 $Reader.__len__=function(self){return self.lines.length} 7514 $Reader.close=function(self){self.closed=true} 7515 $Reader.flush=function(self){return None} 7516 $Reader.read=function(){var $=$B.args("read",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),self=$.self,size=$B.$GetInt($.size) 7517 if(self.closed===true){throw _b_.ValueError.$factory('I/O operation on closed file')} 7518 make_content(self) 7519 var len=self.$binary ? self.$bytes.source.length :self.$string.length 7520 if(size < 0){size=len-self.$counter} 7521 if(self.$binary){res=_b_.bytes.$factory(self.$bytes.source.slice(self.$counter,self.$counter+size))}else{res=self.$string.substr(self.$counter,size)} 7522 self.$counter+=size 7523 return res} 7524 $Reader.readable=function(self){return true} 7525 function make_content(self){ 7526 if(self.$binary && self.$bytes===undefined){self.$bytes=_b_.str.encode(self.$string,self.encoding)}else if((! self.$binary)&& self.$string===undefined){self.$string=_b_.bytes.decode(self.$bytes,self.encoding)}} 7527 function make_lines(self){ 7528 if(self.$lines===undefined){make_content(self) 7529 if(! self.$binary){self.$lines=self.$string.split("\n")}else{console.log("make lines, binary") 7530 var lines=[],pos=0,source=self.$bytes.source 7531 while(true){var ix=source.indexOf(10) 7532 if(ix==-1){lines.push({__class__:_b_.bytes,source:source}) 7533 break}else{lines.push({__class__:_b_.bytes,source:source.slice(0,ix+1)}) 7534 source=source.slice(ix+1)}} 7535 self.$lines=lines}}} 7536 $Reader.readline=function(self,size){var $=$B.args("readline",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),self=$.self,size=$B.$GetInt($.size) 7537 self.$lc=self.$lc===undefined ?-1 :self.$lc 7538 if(self.closed===true){throw _b_.ValueError.$factory('I/O operation on closed file')} 7539 make_content(self) 7540 if(self.$binary){var ix=self.$bytes.source.indexOf(10,self.$counter) 7541 if(ix==-1){return _b_.bytes.$factory()}else{var res={__class__:_b_.bytes,source :self.$bytes.source.slice(self.$counter,ix+1)} 7542 self.$counter=ix+1 7543 return res}}else{var ix=self.$string.indexOf("\n",self.$counter) 7544 if(ix==-1){return ''}else{var res=self.$string.substring(self.$counter,ix+1) 7545 self.$counter=ix+1 7546 self.$lc+=1 7547 return res}}} 7548 $Reader.readlines=function(){var $=$B.args("readlines",2,{self:null,hint:null},["self","hint"],arguments,{hint:-1},null,null),self=$.self,hint=$B.$GetInt($.hint) 7549 var nb_read=0 7550 if(self.closed===true){throw _b_.ValueError.$factory('I/O operation on closed file')} 7551 self.$lc=self.$lc===undefined ?-1 :self.$lc 7552 make_lines(self) 7553 if(hint < 0){var lines=self.$lines.slice(self.$lc+1)}else{var lines=[] 7554 while(self.$lc < self.$lines.length && 7555 nb_read < hint){self.$lc++ 7556 lines.push(self.$lines[self.$lc])}} 7557 while(lines[lines.length-1]==''){lines.pop()} 7558 return lines} 7559 $Reader.seek=function(self,offset,whence){if(self.closed===True){throw _b_.ValueError.$factory('I/O operation on closed file')} 7560 if(whence===undefined){whence=0} 7561 if(whence===0){self.$counter=offset} 7562 else if(whence===1){self.$counter+=offset} 7563 else if(whence===2){self.$counter=self.$content.length+offset}} 7564 $Reader.seekable=function(self){return true} 7565 $Reader.tell=function(self){return self.$counter} 7566 $Reader.writable=function(self){return false} 7567 $B.set_func_names($Reader,"builtins") 7568 var $BufferedReader=$B.make_class('_io.BufferedReader') 7569 $BufferedReader.__mro__=[$Reader,_b_.object] 7570 var $TextIOWrapper=$B.make_class('_io.TextIOWrapper',function(){var $=$B.args("TextIOWrapper",6,{buffer:null,encoding:null,errors:null,newline:null,line_buffering:null,write_through:null},["buffer","encoding","errors","newline","line_buffering","write_through"],arguments,{encoding:"utf-8",errors:_b_.None,newline:_b_.None,line_buffering:_b_.False,write_through:_b_.False},null,null) 7571 return{ 7572 __class__:$TextIOWrapper,$bytes:$.buffer.$bytes,encoding:$.encoding,errors:$.errors,newline:$.newline}} 7573 ) 7574 $TextIOWrapper.__mro__=[$Reader,_b_.object] 7575 $B.set_func_names($TextIOWrapper,"builtins") 7576 $B.Reader=$Reader 7577 $B.TextIOWrapper=$TextIOWrapper 7578 $B.BufferedReader=$BufferedReader 7579 function $url_open(){ 7580 var $ns=$B.args('open',3,{file:null,mode:null,encoding:null},['file','mode','encoding'],arguments,{mode:'r',encoding:'utf-8'},'args','kw'),$bytes,$string,$res 7581 for(var attr in $ns){eval('var '+attr+'=$ns["'+attr+'"]')} 7582 if(args.length > 0){var mode=args[0]} 7583 if(args.length > 1){var encoding=args[1]} 7584 if(mode.search('w')>-1){throw _b_.IOError.$factory("Browsers cannot write on disk")}else if(['r','rb'].indexOf(mode)==-1){throw _b_.ValueError.$factory("Invalid mode '"+mode+"'")} 7585 if(isinstance(file,_b_.str)){ 7586 var is_binary=mode.search('b')>-1 7587 if($B.file_cache.hasOwnProperty($ns.file)){$string=$B.file_cache[$ns.file]}else if($B.files && $B.files.hasOwnProperty($ns.file)){ 7588 $res=atob($B.files[$ns.file].content) 7589 var source=[] 7590 for(const char of $res){source.push(char.charCodeAt(0))} 7591 $bytes=_b_.bytes.$factory() 7592 $bytes.source=source}else if($B.protocol !="file"){ 7593 if(is_binary){throw _b_.IOError.$factory( 7594 "open() in binary mode is not supported")} 7595 var req=new XMLHttpRequest(); 7596 req.onreadystatechange=function(){try{var status=this.status 7597 if(status==404){$res=_b_.FileNotFoundError.$factory(file)}else if(status !=200){$res=_b_.IOError.$factory('Could not open file '+ 7598 file+' : status '+status)}else{$res=this.responseText}}catch(err){$res=_b_.IOError.$factory('Could not open file '+ 7599 file+' : error '+err)}} 7600 var fake_qs=$B.$options.cache ? '' : 7601 '?foo='+(new Date().getTime()) 7602 req.open('GET',file+fake_qs,false) 7603 req.overrideMimeType('text/plain; charset=utf-8') 7604 req.send() 7605 if($res.constructor===Error){throw $res} 7606 $string=$res}else{throw _b_.FileNotFoundError.$factory( 7607 "cannot use 'open()' with protocol 'file'")} 7608 if($string===undefined && $bytes===undefined){throw _b_.FileNotFoundError.$factory($ns.file)} 7609 var res={$binary:is_binary,$string:$string,$bytes:$bytes,$counter:0,closed:False,encoding:encoding,mode:mode,name:file} 7610 res.__class__=is_binary ? $BufferedReader :$TextIOWrapper 7611 return res}else{throw _b_.TypeError.$factory("invalid argument for open(): "+ 7612 _b_.str.$factory(file))}} 7613 var zip=$B.make_class("zip",function(){var res={__class__:zip,items:[]} 7614 if(arguments.length==0)return res 7615 var $ns=$B.args('zip',0,{},[],arguments,{},'args','kw') 7616 var _args=$ns['args'] 7617 var args=[] 7618 for(var i=0;i < _args.length;i++){args.push(iter(_args[i]))} 7619 var rank=0,items=[] 7620 while(1){var line=[],flag=true 7621 for(var i=0;i < args.length;i++){try{line.push(next(args[i]))}catch(err){if(err.__class__==_b_.StopIteration){flag=false 7622 break}else{throw err}}} 7623 if(!flag){break} 7624 items[rank++]=_b_.tuple.$factory(line)} 7625 res.items=items 7626 return res} 7627 ) 7628 var zip_iterator=$B.make_iterator_class('zip_iterator') 7629 zip.__iter__=function(self){return zip_iterator.$factory(self.items)} 7630 $B.set_func_names(zip,"builtins") 7631 function no_set_attr(klass,attr){if(klass[attr]!==undefined){throw _b_.AttributeError.$factory("'"+klass.$infos.__name__+ 7632 "' object attribute '"+attr+"' is read-only")}else{throw _b_.AttributeError.$factory("'"+klass.$infos.__name__+ 7633 "' object has no attribute '"+attr+"'")}} 7634 var True=true 7635 var False=false 7636 var ellipsis=$B.make_class("ellipsis",function(){return Ellipsis} 7637 ) 7638 var Ellipsis={__class__:ellipsis,__bool__:function(){return True},} 7639 for(var $key in $B.$comps){ 7640 switch($B.$comps[$key]){case 'ge': 7641 case 'gt': 7642 case 'le': 7643 case 'lt': 7644 ellipsis['__'+$B.$comps[$key]+'__']=(function(k){return function(other){throw _b_.TypeError.$factory("unorderable types: ellipsis() "+ 7645 k+" "+$B.class_name(other))}})($key)}} 7646 for(var $func in Ellipsis){if(typeof Ellipsis[$func]=='function'){Ellipsis[$func].__str__=(function(f){return function(){return "<method-wrapper "+f+ 7647 " of Ellipsis object>"}})($func)}} 7648 $B.set_func_names(ellipsis) 7649 var FunctionCode=$B.make_class("function code") 7650 var FunctionGlobals=$B.make_class("function globals") 7651 $B.Function={__class__:_b_.type,__code__:{__class__:FunctionCode,__name__:'function code'},__globals__:{__class__:FunctionGlobals,__name__:'function globals'},__mro__:[_b_.object],$infos:{__name__:'function',__module__:"builtins"},$is_class:true} 7652 $B.Function.__delattr__=function(self,attr){if(attr=="__dict__"){throw _b_.TypeError.$factory("can't deleted function __dict__")}} 7653 $B.Function.__dir__=function(self){var infos=self.$infos ||{},attrs=self.$attrs ||{} 7654 return Object.keys(infos).concat(Object.keys(attrs))} 7655 $B.Function.__eq__=function(self,other){return self===other} 7656 $B.Function.__get__=function(self,obj){if(obj===_b_.None){return self} 7657 var method=function(){return self(obj,...arguments)} 7658 method.__class__=$B.method 7659 if(self.$infos===undefined){console.log("no $infos",self) 7660 console.log($B.last($B.frames_stack))} 7661 method.$infos={__name__:self.$infos.__name__,__qualname__:$B.class_name(obj)+"."+self.$infos.__name__,__self__:obj,__func__:self} 7662 return method} 7663 $B.Function.__getattribute__=function(self,attr){ 7664 if(self.$infos && self.$infos[attr]!==undefined){if(attr=='__code__'){var res={__class__:code} 7665 for(var attr in self.$infos.__code__){res[attr]=self.$infos.__code__[attr]} 7666 res.name=self.$infos.__name__ 7667 res.filename=self.$infos.__code__.co_filename 7668 res.co_code=self+"" 7669 return res}else if(attr=='__annotations__'){ 7670 return $B.obj_dict(self.$infos[attr])}else if(self.$infos.hasOwnProperty(attr)){return self.$infos[attr]}}else if(self.$infos && self.$infos.__dict__ && 7671 self.$infos.__dict__.$string_dict[attr]!==undefined){return self.$infos.__dict__.$string_dict[attr][0]}else if(attr=="__closure__"){var free_vars=self.$infos.__code__.co_freevars 7672 if(free_vars.length==0){return None} 7673 var cells=[] 7674 for(var i=0;i < free_vars.length;i++){try{cells.push($B.cell.$factory($B.$check_def_free(free_vars[i])))}catch(err){ 7675 cells.push($B.cell.$factory(None))}} 7676 return _b_.tuple.$factory(cells)}else if(attr=="__globals__"){return $B.obj_dict($B.imported[self.$infos.__module__])}else if(self.$attrs && self.$attrs[attr]!==undefined){return self.$attrs[attr]}else{return _b_.object.__getattribute__(self,attr)}} 7677 $B.Function.__repr__=$B.Function.__str__=function(self){if(self.$infos===undefined){return '<function '+self.name+'>'}else{return '<function '+self.$infos.__qualname__+'>'}} 7678 $B.Function.__mro__=[_b_.object] 7679 $B.Function.__setattr__=function(self,attr,value){if(attr=="__closure__"){throw _b_.AttributeError.$factory("readonly attribute")}else if(attr=="__defaults__"){ 7680 if(value===_b_.None){value=[]}else if(! isinstance(value,_b_.tuple)){throw _b_.TypeError.$factory( 7681 "__defaults__ must be set to a tuple object")} 7682 var set_func=self.$set_defaults 7683 if(set_func===undefined){throw _b_.AttributeError.$factory("cannot set attribute "+attr+ 7684 " of "+_b_.str.$factory(self))} 7685 if(self.$infos && self.$infos.__code__){ 7686 var argcount=self.$infos.__code__.co_argcount,varnames=self.$infos.__code__.co_varnames,params=varnames.slice(0,argcount),$defaults={} 7687 for(var i=value.length-1;i >=0;i--){var pos=params.length-value.length+i 7688 if(pos < 0){break} 7689 $defaults[params[pos]]=value[i]}}else{throw _b_.AttributeError.$factory("cannot set attribute "+attr+ 7690 " of "+_b_.str.$factory(self))} 7691 var klass=self.$infos.$class 7692 var new_func=set_func($defaults) 7693 new_func.$set_defaults=set_func 7694 if(klass){klass[self.$infos.__name__]=new_func 7695 new_func.$infos.$class=klass 7696 new_func.$infos.__defaults__=value}else{ 7697 self.$infos.$defaults=value 7698 self.$infos.__defaults__=value} 7699 return _b_.None} 7700 if(self.$infos[attr]!==undefined){self.$infos[attr]=value} 7701 else{self.$attrs=self.$attrs ||{};self.$attrs[attr]=value}} 7702 $B.Function.$factory=function(){} 7703 $B.set_func_names($B.Function,"builtins") 7704 _b_.__BRYTHON__=__BRYTHON__ 7705 $B.builtin_funcs=["abs","all","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dir","divmod","eval","exec","exit","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","locals","max","min","next","oct","open","ord","pow","print","quit","repr","round","setattr","sorted","sum","vars" 7706 ] 7707 var builtin_function=$B.builtin_function=$B.make_class("builtin_function_or_method") 7708 builtin_function.__getattribute__=$B.Function.__getattribute__ 7709 builtin_function.__reduce_ex__=builtin_function.__reduce__=function(self){return self.$infos.__name__} 7710 builtin_function.__repr__=builtin_function.__str__=function(self){return '<built-in function '+self.$infos.__name__+'>'} 7711 $B.set_func_names(builtin_function,"builtins") 7712 var method_wrapper=$B.make_class("method_wrapper") 7713 method_wrapper.__repr__=method_wrapper.__str__=function(self){return "<method wrapper '"+self.$infos.__name__+"' of function object>"} 7714 $B.set_func_names(method_wrapper,"builtins") 7715 var wrapper_descriptor=$B.wrapper_descriptor= 7716 $B.make_class("wrapper_descriptor") 7717 wrapper_descriptor.__getattribute__=$B.Function.__getattribute__ 7718 wrapper_descriptor.__repr__=wrapper_descriptor.__str__=function(self){return "<slot wrapper '"+self.$infos.__name__+"' of '"+ 7719 self.__objclass__.$infos.__name__+"' object>"} 7720 $B.set_func_names(wrapper_descriptor,"builtins") 7721 $B.builtin_classes=["bool","bytearray","bytes","classmethod","complex","dict","enumerate","filter","float","frozenset","int","list","map","memoryview","object","property","range","reversed","set","slice","staticmethod","str","super","tuple","type","zip" 7722 ] 7723 var other_builtins=['Ellipsis','False','None','True','__debug__','__import__','copyright','credits','license','NotImplemented' 7724 ] 7725 var builtin_names=$B.builtin_funcs. 7726 concat($B.builtin_classes). 7727 concat(other_builtins) 7728 for(var i=0;i < builtin_names.length;i++){var name=builtin_names[i],orig_name=name,name1=name 7729 if(name=='open'){name1='$url_open'} 7730 if(name=='super'){name=name1='$$super'} 7731 if(name=='eval'){name=name1='$$eval'} 7732 if(name=='print'){name1='$print'} 7733 try{_b_[name]=eval(name1) 7734 if($B.builtin_funcs.indexOf(orig_name)>-1){_b_[name].__class__=builtin_function 7735 _b_[name].$infos={__module__:'builtins',__name__:orig_name,__qualname__:orig_name}}} 7736 catch(err){}} 7737 _b_['open']=$url_open 7738 _b_['print']=$print 7739 _b_['$$super']=$$super 7740 _b_.object.__init__.__class__=wrapper_descriptor 7741 _b_.object.__new__.__class__=builtin_function})(__BRYTHON__) 7742 ; 7743 ;(function($B){var bltns=$B.InjectBuiltins() 7744 eval(bltns) 7745 $B.del_exc=function(){var frame=$B.last($B.frames_stack) 7746 frame[1].$current_exception=undefined} 7747 $B.set_exc=function(exc){var frame=$B.last($B.frames_stack) 7748 if(frame===undefined){console.log("no frame",exc)} 7749 frame[1].$current_exception=$B.exception(exc)} 7750 $B.get_exc=function(){var frame=$B.last($B.frames_stack) 7751 return frame[1].$current_exception} 7752 $B.$raise=function(arg){ 7753 if(arg===undefined){var es=$B.get_exc() 7754 if(es !==undefined){throw es} 7755 throw _b_.RuntimeError.$factory("No active exception to reraise")}else if(isinstance(arg,BaseException)){if(arg.__class__===_b_.StopIteration && 7756 $B.last($B.frames_stack)[1].$is_generator){ 7757 arg=_b_.RuntimeError.$factory("generator raised StopIteration")} 7758 throw arg}else if(arg.$is_class && issubclass(arg,BaseException)){if(arg===_b_.StopIteration){if($B.last($B.frames_stack)[1].$is_generator){ 7759 throw _b_.RuntimeError.$factory("generator raised StopIteration")}} 7760 throw $B.$call(arg)()}else{throw _b_.TypeError.$factory("exceptions must derive from BaseException")}} 7761 $B.$syntax_err_line=function(exc,module,src,pos,line_num){ 7762 var pos2line={},lnum=1,module=module.charAt(0)=="$" ? "<string>" :module 7763 if(src===undefined){exc.$line_info=line_num+','+module 7764 exc.args=_b_.tuple.$factory([$B.$getitem(exc.args,0),module,line_num,0,0])}else{var line_pos={1:0} 7765 for(var i=0,len=src.length;i < len;i++){pos2line[i]=lnum 7766 if(src.charAt(i)=="\n"){line_pos[++lnum]=i}} 7767 while(line_num===undefined){line_num=pos2line[pos] 7768 pos--} 7769 exc.$line_info=line_num+","+module 7770 var lines=src.split("\n"),line=lines[line_num-1],lpos=pos-line_pos[line_num],len=line.length 7771 exc.text=line 7772 lpos-=len-line.length 7773 if(lpos < 0){lpos=0} 7774 while(line.charAt(0)==' '){line=line.substr(1) 7775 if(lpos > 0){lpos--}} 7776 exc.offset=lpos 7777 exc.args=_b_.tuple.$factory([$B.$getitem(exc.args,0),module,line_num,lpos,line])} 7778 exc.lineno=line_num 7779 exc.msg=exc.args[0] 7780 exc.filename=module} 7781 $B.$SyntaxError=function(module,msg,src,pos,line_num,root){if(root !==undefined && root.line_info !==undefined){ 7782 line_num=root.line_info} 7783 var exc=_b_.SyntaxError.$factory(msg) 7784 $B.$syntax_err_line(exc,module,src,pos,line_num) 7785 throw exc} 7786 $B.$IndentationError=function(module,msg,src,pos,line_num,root){$B.frames_stack.push([module,{$line_info:line_num+","+module},module,{$src:src}]) 7787 if(root !==undefined && root.line_info !==undefined){ 7788 line_num=root.line_info} 7789 var exc=_b_.IndentationError.$factory(msg) 7790 $B.$syntax_err_line(exc,module,src,pos,line_num) 7791 throw exc} 7792 $B.print_stack=function(stack){stack=stack ||$B.frames_stack 7793 var trace=[] 7794 stack.forEach(function(frame){var line_info=frame[1].$line_info 7795 if(line_info !==undefined){var info=line_info.split(",") 7796 if(info[1].startsWith("$exec")){info[1]="<module>"} 7797 trace.push(info[1]+" line "+info[0]) 7798 var src=$B.file_cache[frame[3].__file__] 7799 if(src){var lines=src.split("\n"),line=lines[parseInt(info[0])-1] 7800 trace.push(" "+line.trim())}}}) 7801 console.log("print stack ok",trace) 7802 return trace.join("\n")} 7803 var traceback=$B.traceback=$B.make_class("traceback",function(exc,stack){var frame=$B.last($B.frames_stack) 7804 if(stack===undefined){stack=exc.$stack} 7805 return{ 7806 __class__ :traceback,$stack:stack,exc:exc}} 7807 ) 7808 traceback.__getattribute__=function(self,attr){var line_info 7809 if(attr==='tb_frame' || 7810 attr==='tb_lineno' || 7811 attr==='tb_lasti' || 7812 attr==='tb_next'){if(self.$stack.length==0){console.log("no stack",attr)} 7813 var first_frame=self.$stack[0] 7814 line_info=self.exc.$line_infos[self.exc.$line_infos.length- 7815 self.$stack.length]} 7816 switch(attr){case "tb_frame": 7817 return frame.$factory(self.$stack) 7818 case "tb_lineno": 7819 var lineno 7820 if(line_info===undefined || 7821 first_frame[0].startsWith($B.lambda_magic)){if(first_frame[4]&& first_frame[4].$infos && 7822 first_frame[4].$infos.__code__){lineno=first_frame[4].$infos.__code__.co_firstlineno}else{lineno=-1}}else{lineno=parseInt(line_info.split(",")[0])} 7823 return lineno 7824 case "tb_lasti": 7825 if(line_info===undefined){console.log("no line info",self.$stack) 7826 return ""}else{var info=line_info.split(","),src,file 7827 for(var i=self.$stack.length-1;i >=0;i--){var fr=self.$stack[i] 7828 if(fr[2]==info[1].replace(/\./g,'_')){file=fr[3].__file__ 7829 break}} 7830 if(src===undefined){if($B.file_cache.hasOwnProperty(file)){src=$B.file_cache[file]}else if($B.imported[info[1]]&& $B.imported[info[1]].__file__ ){src=$B.file_cache[$B.imported[info[1]].__file__] 7831 console.log("from filecache",line_info,$B.imported[info[1]].__file__)}} 7832 if(src !==undefined){try{return src.split("\n")[parseInt(info[0]-1)].trim()}catch(err){console.log("error in attr tb_lasti of",self) 7833 console.log(src,info) 7834 throw err}}else{console.log(file) 7835 console.log("no src for",info) 7836 return ""}} 7837 case "tb_next": 7838 if(self.$stack.length <=1){return None} 7839 else{return traceback.$factory(self.exc,self.$stack.slice(1))} 7840 default: 7841 return _b_.object.__getattribute__(self,attr)}} 7842 $B.set_func_names(traceback,"builtins") 7843 var frame=$B.make_class("frame",function(stack,pos){var fs=stack 7844 var res={__class__:frame,f_builtins :{}, 7845 $stack:stack.slice()} 7846 if(pos===undefined){pos=0} 7847 res.$pos=pos 7848 if(fs.length){var _frame=fs[pos],locals_id=_frame[0],filename 7849 try{res.f_locals=$B.obj_dict(_frame[1])}catch(err){console.log("err "+err) 7850 throw err} 7851 res.f_globals=$B.obj_dict(_frame[3]) 7852 if(_frame[3].__file__ !==undefined){filename=_frame[3].__file__} 7853 if(locals_id.startsWith("$exec")){filename="<string>"} 7854 if(_frame[1].$line_info===undefined){res.f_lineno=-1}else{var line_info=_frame[1].$line_info.split(",") 7855 res.f_lineno=parseInt(line_info[0]) 7856 var module_name=line_info[1] 7857 if($B.imported.hasOwnProperty(module_name)){filename=$B.imported[module_name].__file__} 7858 res.f_lineno=parseInt(_frame[1].$line_info.split(',')[0])} 7859 var co_name=locals_id.startsWith("$exec")? "<module>" : 7860 locals_id 7861 if(locals_id==_frame[2]){co_name="<module>"}else if(locals_id.startsWith("lc"+$B.lambda_magic)){co_name="<listcomp>"}else{if(_frame[1].$name){co_name=_frame[1].$name}else if(_frame[1].$dict_comp){co_name='<dictcomp>'}else if(_frame[1].$list_comp){co_name='<listcomp>'}else if(_frame.length > 4){if(_frame[4].$infos){co_name=_frame[4].$infos.__name__}else{co_name=_frame[4].name} 7862 if(_frame[4].$infos===undefined){ 7863 if(_frame[4].name.startsWith("__ge")){co_name="<genexpr>"}else if(_frame[4].name.startsWith("set_comp"+ 7864 $B.lambda_magic)){co_name="<setcomp>"}else if(_frame[4].name.startsWith("lambda"+ 7865 $B.lambda_magic)){co_name="<lambda>"}}else if(filename===undefined && _frame[4].$infos.__code__){filename=_frame[4].$infos.__code__.co_filename 7866 if(filename===undefined){filename=_frame[4].$infos.__module__} 7867 res.f_lineno=_frame[4].$infos.__code__.co_firstlineno}}} 7868 if(_frame.length > 4 && _frame[4].$infos !==undefined){res.f_code=_frame[4].$infos.__code__}else{res.f_code={co_name:co_name,co_filename:filename}} 7869 res.f_code.__class__=$B.code 7870 res.f_code.co_code=_b_.None 7871 if(filename===undefined){res.f_code.co_filename="<string>"}} 7872 return res} 7873 ) 7874 frame.__delattr__=function(self,attr){if(attr=="f_trace"){$B.last(self.$stack)[1].$f_trace=_b_.None}} 7875 frame.__getattr__=function(self,attr){ 7876 if(attr=="f_back"){if(self.$pos > 0){return frame.$factory(self.$stack.slice(0,self.$stack.length-1),self.$pos-1)}else{return _b_.None}}else if(attr=="clear"){return function(){}}else if(attr=="f_trace"){var locals=$B.last(self.$stack)[1] 7877 if(locals.$f_trace===undefined){return _b_.None} 7878 return locals.$f_trace}} 7879 frame.__setattr__=function(self,attr,value){if(attr=="f_trace"){ 7880 $B.last(self.$stack)[1].$f_trace=value}} 7881 frame.__str__=frame.__repr__=function(self){return '<frame object, file '+self.f_code.co_filename+ 7882 ', line '+self.f_lineno+', code '+self.f_code.co_name+'>'} 7883 $B.set_func_names(frame,"builtins") 7884 $B._frame=frame 7885 var BaseException=_b_.BaseException={__class__:_b_.type,__bases__ :[_b_.object],__mro__:[_b_.object],args:[],$infos:{__name__:"BaseException",__module__:"builtins"},$is_class:true} 7886 BaseException.__init__=function(self){var args=arguments[1]===undefined ?[]:[arguments[1]] 7887 self.args=_b_.tuple.$factory(args)} 7888 BaseException.__repr__=function(self){var res=self.__class__.$infos.__name__ 7889 if(self.args[0]){res+='('+repr(self.args[0])} 7890 if(self.args.length > 1){res+=', '+repr($B.fast_tuple(self.args.slice(1)))} 7891 return res+')'} 7892 BaseException.__str__=function(self){if(self.args.length > 0){return _b_.str.$factory(self.args[0])} 7893 return self.__class__.$infos.__name__} 7894 BaseException.__new__=function(cls){var err=_b_.BaseException.$factory() 7895 err.__class__=cls 7896 err.__dict__=$B.empty_dict() 7897 return err} 7898 var getExceptionTrace=function(exc,includeInternal){if(exc.__class__===undefined){if($B.debug > 1){console.log("no class",exc)} 7899 return exc+''} 7900 var info='' 7901 if(exc.$js_exc !==undefined && includeInternal){info+="\nJS stack:\n"+exc.$js_exc.stack+"\n"} 7902 info+="Traceback (most recent call last):" 7903 var line_info=exc.$line_info 7904 for(var i=0;i < exc.$stack.length;i++){var frame=exc.$stack[i] 7905 if(! frame[1]||! frame[1].$line_info){continue} 7906 var $line_info=frame[1].$line_info 7907 var line_info=$line_info.split(','),src 7908 if(exc.module==line_info[1]){src=exc.src} 7909 if(!includeInternal){var src=frame[3].$src 7910 if(src===undefined){if($B.VFS && $B.VFS.hasOwnProperty(frame[2])){src=$B.VFS[frame[2]][1]}else if(src=$B.file_cache[frame[3].__file__]){}else{continue}}} 7911 var file=frame[3].__file__ ||"<string>",module=line_info[1],is_exec=module.charAt(0)=="$" 7912 if(is_exec){module="<module>"} 7913 info+="\n File "+file+" line "+line_info[0] 7914 if(frame.length > 4){if(frame[4].$infos){var name=frame[4].$infos.__name__ 7915 if(name.startsWith("lc"+$B.lambda_magic)){info+=',in <listcomp>'}else{info+=', in '+name}}else if(frame[4].name.startsWith("__ge")){info+=', in <genexpr>'}else if(frame[4].name.startsWith("set_comp"+$B.lambda_magic)){info+=', in <setcomp>'}else if(frame[4].name.startsWith("lc"+$B.lambda_magic)){info+=', in <listcomp>'}else{console.log("frame[4]",frame[4])}}else if(frame[1].$list_comp){info+=', in <listcomp>'}else if(frame[1].$dict_comp){info+=', in <dictcomp>'}else{info+=', in <module>'} 7916 if(src !==undefined && ! is_exec){var lines=src.split("\n"),line=lines[parseInt(line_info[0])-1] 7917 if(line){line=line.replace(/^[ ]+/g,"")} 7918 info+="\n "+line}} 7919 if(exc.__class__===_b_.SyntaxError){info+="\n File "+exc.args[1]+", line "+exc.args[2]+ 7920 "\n "+exc.args[4]} 7921 return info} 7922 BaseException.__getattr__=function(self,attr){if(attr=="info"){return getExceptionTrace(self,false);}else if(attr=="infoWithInternal"){return getExceptionTrace(self,true);}else if(attr=="__traceback__"){ 7923 if(self.$traceback !==undefined){return self.$traceback} 7924 return traceback.$factory(self)}else{throw _b_.AttributeError.$factory(self.__class__.$infos.__name__+ 7925 " has no attribute '"+attr+"'")}} 7926 BaseException.with_traceback=function(self,tb){self.$traceback=tb 7927 return self} 7928 $B.deep_copy=function(stack){var res=[] 7929 for(const s of stack){var item=[s[0],{},s[2],{}] 7930 if(s[4]!==undefined){item.push(s[4])} 7931 for(const i of[1,3]){for(var key in s[i]){item[i][key]=s[i][key]}} 7932 res.push(item)} 7933 return res} 7934 $B.save_stack=function(){return $B.deep_copy($B.frames_stack)} 7935 $B.restore_stack=function(stack,locals){$B.frames_stack=stack 7936 $B.frames_stack[$B.frames_stack.length-1][1]=locals} 7937 $B.freeze=function(err){ 7938 if(err.$stack===undefined){err.$line_infos=[] 7939 for(var i=0,len=$B.frames_stack.length;i < len;i++){err.$line_infos.push($B.frames_stack[i][1].$line_info)} 7940 err.$stack=$B.frames_stack.slice() 7941 if($B.frames_stack.length){err.$line_info=$B.last($B.frames_stack)[1].$line_info}}} 7942 var show_stack=$B.show_stack=function(stack){stack=stack ||$B.frames_stack 7943 for(const frame of stack){console.log(frame[0],frame[1].$line_info)}} 7944 BaseException.$factory=function(){var err=Error() 7945 err.args=$B.fast_tuple(Array.prototype.slice.call(arguments)) 7946 err.__class__=_b_.BaseException 7947 err.$py_error=true 7948 $B.freeze(err) 7949 eval("//placeholder//") 7950 err.__cause__=_b_.None 7951 err.__context__=_b_.None 7952 err.__suppress_context__=false 7953 return err} 7954 BaseException.$factory.$infos={__name__:"BaseException",__qualname__:"BaseException"} 7955 $B.set_func_names(BaseException) 7956 _b_.BaseException=BaseException 7957 $B.exception=function(js_exc,in_ctx_manager){ 7958 if(! js_exc.__class__){console.log("Javascript exception:",js_exc) 7959 console.log($B.last($B.frames_stack)) 7960 console.log("recursion error ?",$B.is_recursion_error(js_exc)) 7961 var exc=Error() 7962 exc.__name__="Internal Javascript error: "+ 7963 (js_exc.__name__ ||js_exc.name) 7964 exc.__class__=_b_.Exception 7965 exc.$js_exc=js_exc 7966 if($B.is_recursion_error(js_exc)){return _b_.RecursionError.$factory("too much recursion")}else if(js_exc.name=="ReferenceError"){exc.__name__="NameError" 7967 exc.__class__=_b_.NameError 7968 js_exc.message=js_exc.message.replace("$$","")}else if(js_exc.name=="InternalError"){exc.__name__="RuntimeError" 7969 exc.__class__=_b_.RuntimeError} 7970 exc.__cause__=_b_.None 7971 exc.__context__=_b_.None 7972 exc.__suppress_context__=false 7973 var $message="<Javascript "+js_exc.name+">: "+ 7974 (js_exc.message ||"<"+js_exc+">") 7975 exc.args=_b_.tuple.$factory([$message]) 7976 exc.$py_error=true 7977 $B.freeze(exc)}else{var exc=js_exc 7978 $B.freeze(exc) 7979 if(in_ctx_manager){ 7980 var current_locals=$B.last($B.frames_stack)[0] 7981 for(var i=0,len=exc.$stack.length;i < len;i++){if(exc.$stack[i][0]==current_locals){exc.$stack=exc.$stack.slice(i) 7982 exc.$traceback=traceback.$factory(exc) 7983 break}}}} 7984 return exc} 7985 $B.is_exc=function(exc,exc_list){ 7986 if(exc.__class__===undefined){exc=$B.exception(exc)} 7987 var this_exc_class=exc.$is_class ? exc :exc.__class__ 7988 for(var i=0;i < exc_list.length;i++){var exc_class=exc_list[i] 7989 if(this_exc_class===undefined){console.log("exc class undefined",exc)} 7990 if(issubclass(this_exc_class,exc_class)){return true}} 7991 return false} 7992 $B.is_recursion_error=function(js_exc){ 7993 console.log("test is js exc is recursion error",js_exc,js_exc+"") 7994 var msg=js_exc+"",parts=msg.split(":"),err_type=parts[0].trim(),err_msg=parts[1].trim() 7995 return(err_type=='InternalError' && err_msg=='too much recursion')|| 7996 (err_type=='Error' && err_msg=='Out of stack space')|| 7997 (err_type=='RangeError' && err_msg=='Maximum call stack size exceeded')} 7998 function $make_exc(names,parent){ 7999 var _str=[],pos=0 8000 for(var i=0;i < names.length;i++){var name=names[i],code="" 8001 if(Array.isArray(name)){ 8002 var code=name[1],name=name[0]} 8003 $B.builtins_scope[name]=true 8004 var $exc=(BaseException.$factory+"").replace(/BaseException/g,name) 8005 $exc=$exc.replace("//placeholder//",code) 8006 _str[pos++]="_b_."+name+' = {__class__:_b_.type, '+ 8007 '__mro__: [_b_.'+parent.$infos.__name__+ 8008 "].concat(parent.__mro__), $is_class: true,"+ 8009 "$infos: {__name__:'"+name+"'}}" 8010 _str[pos++]="_b_."+name+".$factory = "+$exc 8011 _str[pos++]="_b_."+name+'.$factory.$infos = {__name__: "'+ 8012 name+'", __qualname__: "'+name+'"}' 8013 _str[pos++]="$B.set_func_names(_b_."+name+", 'builtins')"} 8014 try{eval(_str.join(";"))}catch(err){console.log("--err"+err) 8015 throw err}} 8016 $make_exc(["SystemExit","KeyboardInterrupt","GeneratorExit","Exception"],BaseException) 8017 $make_exc([["StopIteration","err.value = arguments[0]"],["StopAsyncIteration","err.value = arguments[0]"],"ArithmeticError","AssertionError","AttributeError","BufferError","EOFError",["ImportError","err.name = arguments[0]"],"LookupError","MemoryError","NameError","OSError","ReferenceError","RuntimeError",["SyntaxError","err.msg = arguments[0]"],"SystemError","TypeError","ValueError","Warning"],_b_.Exception) 8018 $make_exc(["FloatingPointError","OverflowError","ZeroDivisionError"],_b_.ArithmeticError) 8019 $make_exc([["ModuleNotFoundError","err.name = arguments[0]"]],_b_.ImportError) 8020 $make_exc(["IndexError","KeyError"],_b_.LookupError) 8021 $make_exc(["UnboundLocalError"],_b_.NameError) 8022 $make_exc(["BlockingIOError","ChildProcessError","ConnectionError","FileExistsError","FileNotFoundError","InterruptedError","IsADirectoryError","NotADirectoryError","PermissionError","ProcessLookupError","TimeoutError"],_b_.OSError) 8023 $make_exc(["BrokenPipeError","ConnectionAbortedError","ConnectionRefusedError","ConnectionResetError"],_b_.ConnectionError) 8024 $make_exc(["NotImplementedError","RecursionError"],_b_.RuntimeError) 8025 $make_exc(["IndentationError"],_b_.SyntaxError) 8026 $make_exc(["TabError"],_b_.IndentationError) 8027 $make_exc(["UnicodeError"],_b_.ValueError) 8028 $make_exc(["UnicodeDecodeError","UnicodeEncodeError","UnicodeTranslateError"],_b_.UnicodeError) 8029 $make_exc(["DeprecationWarning","PendingDeprecationWarning","RuntimeWarning","SyntaxWarning","UserWarning","FutureWarning","ImportWarning","UnicodeWarning","BytesWarning","ResourceWarning"],_b_.Warning) 8030 $make_exc(["EnvironmentError","IOError","VMSError","WindowsError"],_b_.OSError) 8031 $B.$TypeError=function(msg){throw _b_.TypeError.$factory(msg)} 8032 var se=_b_.SyntaxError.$factory 8033 _b_.SyntaxError.$factory=function(){var arg=arguments[0] 8034 if(arg.__class__===_b_.SyntaxError){return arg} 8035 var exc=se.apply(null,arguments),frame=$B.last($B.frames_stack) 8036 if(frame){line_info=frame[1].$line_info 8037 exc.filename=frame[3].__file__ 8038 exc.lineno=parseInt(line_info.split(",")[0]) 8039 var src=$B.file_cache[frame[3].__file__] 8040 if(src){lines=src.split("\n") 8041 exc.text=lines[exc.lineno-1]} 8042 exc.offset=arg.offset} 8043 return exc} 8044 _b_.SyntaxError})(__BRYTHON__) 8045 ; 8046 8047 ;(function($B){var _b_=$B.builtins,None=_b_.None,range={__class__:_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"range"},$is_class:true,$native:true,$descriptors:{start:true,step:true,stop:true}} 8048 range.__contains__=function(self,other){if(range.__len__(self)==0){return false} 8049 try{other=$B.int_or_bool(other)} 8050 catch(err){ 8051 try{range.index(self,other);return true} 8052 catch(err){return false}} 8053 var sub=$B.sub(other,self.start),fl=$B.floordiv(sub,self.step),res=$B.mul(self.step,fl) 8054 if($B.eq(res,sub)){if($B.gt(self.stop,self.start)){return $B.ge(other,self.start)&& $B.gt(self.stop,other)}else{return $B.ge(self.start,other)&& $B.gt(other,self.stop)}}else{return false}} 8055 range.__delattr__=function(self,attr,value){throw _b_.AttributeError.$factory("readonly attribute")} 8056 range.__eq__=function(self,other){if(_b_.isinstance(other,range)){var len=range.__len__(self) 8057 if(! $B.eq(len,range.__len__(other))){return false} 8058 if(len==0){return true} 8059 if(! $B.eq(self.start,other.start)){return false} 8060 if(len==1){return true} 8061 return $B.eq(self.step,other.step)} 8062 return false} 8063 function compute_item(r,i){var len=range.__len__(r) 8064 if(len==0){return r.start} 8065 else if(i > len){return r.stop} 8066 return $B.add(r.start,$B.mul(r.step,i))} 8067 range.__getitem__=function(self,rank){if(_b_.isinstance(rank,_b_.slice)){var norm=_b_.slice.$conv_for_seq(rank,range.__len__(self)),substep=$B.mul(self.step,norm.step),substart=compute_item(self,norm.start),substop=compute_item(self,norm.stop) 8068 return range.$factory(substart,substop,substep)} 8069 if(typeof rank !="number"){rank=$B.$GetInt(rank)} 8070 if($B.gt(0,rank)){rank=$B.add(rank,range.__len__(self))} 8071 var res=$B.add(self.start,$B.mul(rank,self.step)) 8072 if(($B.gt(self.step,0)&& 8073 ($B.ge(res,self.stop)||$B.gt(self.start,res)))|| 8074 ($B.gt(0,self.step)&& 8075 ($B.ge(self.stop,res)||$B.gt(res,self.start)))){throw _b_.IndexError.$factory("range object index out of range")} 8076 return res} 8077 range.__hash__=function(self){var len=range.__len__(self) 8078 if(len==0){return _b_.hash(_b_.tuple.$factory([0,None,None]))} 8079 if(len==1){return _b_.hash(_b_.tuple.$factory([1,self.start,None]))} 8080 return _b_.hash(_b_.tuple.$factory([len,self.start,self.step]))} 8081 var RangeIterator={__class__:_b_.type,__mro__:[_b_.object],__iter__:function(self){return self},__next__:function(self){return _b_.next(self.obj)},$infos:{__name__:"range_iterator",__module__:"builtins"},$is_class:true} 8082 RangeIterator.$factory=function(obj){return{__class__:RangeIterator,obj:obj}} 8083 $B.set_func_names(RangeIterator,"builtins") 8084 range.__iter__=function(self){var res={__class__ :range,start:self.start,stop:self.stop,step:self.step} 8085 if(self.$safe){res.$counter=self.start-self.step}else{res.$counter=$B.sub(self.start,self.step)} 8086 return RangeIterator.$factory(res)} 8087 range.__len__=function(self){var len 8088 if($B.gt(self.step,0)){if($B.ge(self.start,self.stop)){return 0} 8089 var n=$B.sub(self.stop,$B.add(1,self.start)),q=$B.floordiv(n,self.step) 8090 len=$B.add(1,q)}else{if($B.ge(self.stop,self.start)){return 0} 8091 var n=$B.sub(self.start,$B.add(1,self.stop)),q=$B.floordiv(n,$B.mul(-1,self.step)) 8092 len=$B.add(1,q)} 8093 if($B.maxsize===undefined){$B.maxsize=$B.long_int.__pow__($B.long_int.$factory(2),63) 8094 $B.maxsize=$B.long_int.__sub__($B.maxsize,1)} 8095 return len} 8096 range.__next__=function(self){if(self.$safe){self.$counter+=self.step 8097 if((self.step > 0 && self.$counter >=self.stop) 8098 ||(self.step < 0 && self.$counter <=self.stop)){throw _b_.StopIteration.$factory("")}}else{self.$counter=$B.add(self.$counter,self.step) 8099 if(($B.gt(self.step,0)&& $B.ge(self.$counter,self.stop)) 8100 ||($B.gt(0,self.step)&& $B.ge(self.stop,self.$counter))){throw _b_.StopIteration.$factory("")}} 8101 return self.$counter} 8102 range.__reversed__=function(self){var n=$B.sub(range.__len__(self),1) 8103 return range.$factory($B.add(self.start,$B.mul(n,self.step)),$B.sub(self.start,self.step),$B.mul(-1,self.step))} 8104 range.__repr__=range.__str__=function(self){var res="range("+_b_.str.$factory(self.start)+", "+ 8105 _b_.str.$factory(self.stop) 8106 if(self.step !=1){res+=", "+_b_.str.$factory(self.step)} 8107 return res+")"} 8108 range.__setattr__=function(self,attr,value){throw _b_.AttributeError.$factory("readonly attribute")} 8109 range.start=function(self){return self.start} 8110 range.step=function(self){return self.step},range.stop=function(self){return self.stop} 8111 range.count=function(self,ob){if(_b_.isinstance(ob,[_b_.int,_b_.float,_b_.bool])){return _b_.int.$factory(range.__contains__(self,ob))}else{var comp=function(other){return $B.rich_comp("__eq__",ob,other)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0 8112 while(true){try{if(comp(_next(it))){nb++}}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){return nb} 8113 throw err}}}} 8114 range.index=function(self,other){var $=$B.args("index",2,{self:null,other:null},["self","other"],arguments,{},null,null),self=$.self,other=$.other 8115 try{other=$B.int_or_bool(other)}catch(err){var comp=function(x){return $B.rich_comp("__eq__",other,x)},it=range.__iter__(self),_next=RangeIterator.__next__,nb=0 8116 while(true){try{if(comp(_next(it))){return nb} 8117 nb++}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){throw _b_.ValueError.$factory(_b_.str.$factory(other)+ 8118 " not in range")} 8119 throw err}}} 8120 var sub=$B.sub(other,self.start),fl=$B.floordiv(sub,self.step),res=$B.mul(self.step,fl) 8121 if($B.eq(res,sub)){if(($B.gt(self.stop,self.start)&& $B.ge(other,self.start) 8122 && $B.gt(self.stop,other))|| 8123 ($B.ge(self.start,self.stop)&& $B.ge(self.start,other) 8124 && $B.gt(other,self.stop))){return fl}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+ 8125 ' not in range')}}else{throw _b_.ValueError.$factory(_b_.str.$factory(other)+ 8126 " not in range")}} 8127 range.$factory=function(){var $=$B.args("range",3,{start:null,stop:null,step:null},["start","stop","step"],arguments,{start:null,stop:null,step:null},null,null),start=$.start,stop=$.stop,step=$.step,safe 8128 if(stop===null && step===null){if(start==null){throw _b_.TypeError.$factory("range expected 1 arguments, got 0")} 8129 stop=$B.PyNumber_Index(start) 8130 safe=typeof stop==="number" 8131 return{__class__:range,start:0,stop:stop,step:1,$is_range:true,$safe:safe}} 8132 if(step===null){step=1} 8133 start=$B.PyNumber_Index(start) 8134 stop=$B.PyNumber_Index(stop) 8135 step=$B.PyNumber_Index(step) 8136 if(step==0){throw _b_.ValueError.$factory("range arg 3 must not be zero")} 8137 safe=(typeof start=="number" && typeof stop=="number" && 8138 typeof step=="number") 8139 return{__class__:range,start:start,stop:stop,step:step,$is_range:true,$safe:safe}} 8140 $B.set_func_names(range,"builtins") 8141 var slice={__class__:_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"slice"},$is_class:true,$native:true,$descriptors:{start:true,step:true,stop:true}} 8142 slice.__eq__=function(self,other){var conv1=conv_slice(self),conv2=conv_slice(other) 8143 return conv1[0]==conv2[0]&& 8144 conv1[1]==conv2[1]&& 8145 conv1[2]==conv2[2]} 8146 slice.__repr__=slice.__str__=function(self){return "slice("+_b_.str.$factory(self.start)+", "+ 8147 _b_.str.$factory(self.stop)+", "+_b_.str.$factory(self.step)+")"} 8148 slice.__setattr__=function(self,attr,value){throw _b_.AttributeError.$factory("readonly attribute")} 8149 function conv_slice(self){ 8150 var attrs=["start","stop","step"],res=[] 8151 for(var i=0;i < attrs.length;i++){var val=self[attrs[i]] 8152 if(val===_b_.None){res.push(val)}else{try{res.push($B.PyNumber_Index(val))}catch(err){throw _b_.TypeError.$factory("slice indices must be "+ 8153 "integers or None or have an __index__ method")}}} 8154 return res} 8155 slice.$conv_for_seq=function(self,len){ 8156 var step=self.step===None ? 1 :$B.PyNumber_Index(self.step),step_is_neg=$B.gt(0,step),len_1=$B.sub(len,1) 8157 if(step==0){throw _b_.ValueError.$factory('slice step cannot be zero')} 8158 var start 8159 if(self.start===None){start=step_is_neg ? len_1 :0}else{start=$B.PyNumber_Index(self.start) 8160 if($B.gt(0,start)){start=$B.add(start,len) 8161 if($B.gt(0,start)){start=0}} 8162 if($B.ge(start,len)){start=step < 0 ? len_1 :len}} 8163 if(self.stop===None){stop=step_is_neg ?-1 :len}else{stop=$B.PyNumber_Index(self.stop) 8164 if($B.gt(0,stop)){stop=$B.add(stop,len)} 8165 if($B.ge(stop,len)){stop=step_is_neg ? len_1 :len}} 8166 return{start:start,stop:stop,step:step}} 8167 slice.start=function(self){return self.start} 8168 slice.step=function(self){return self.step} 8169 slice.stop=function(self){return self.stop} 8170 slice.indices=function(self,length){ 8171 var $=$B.args("indices",2,{self:null,length:null},["self","length"],arguments,{},null,null) 8172 var len=$B.$GetInt($.length) 8173 if(len < 0){_b_.ValueError.$factory("length should not be negative")} 8174 var _step=(self.step==_b_.None)? 1 :self.step 8175 if(_step < 0){var _start=self.start,_stop=self.stop 8176 _start=(_start==_b_.None)? len-1 : 8177 (_start < 0)? _b_.max(-1,_start+len):_b_.min(len-1,self.start) 8178 _stop=(self.stop==_b_.None)?-1 : 8179 (_stop < 0)? _b_.max(-1,_stop+len):_b_.min(len-1,self.stop)}else{var _start=(self.start==_b_.None)? 0 :_b_.min(len,self.start) 8180 var _stop=(self.stop==_b_.None)? len :_b_.min(len,self.stop) 8181 if(_start < 0){_start=_b_.max(0,_start+len)} 8182 if(_stop < 0){_stop=_b_.max(0,_stop+len)}} 8183 return _b_.tuple.$factory([_start,_stop,_step])} 8184 slice.$factory=function(){var $=$B.args("slice",3,{start:null,stop:null,step:null},["start","stop","step"],arguments,{stop:null,step:null},null,null),start,stop,step 8185 if($.stop===null && $.step===null){start=_b_.None 8186 stop=$.start 8187 step=_b_.None}else{start=$.start 8188 stop=$.stop 8189 step=$.step===null ? _b_.None :$.step} 8190 var res={__class__ :slice,start:start,stop:stop,step:step} 8191 conv_slice(res) 8192 return res} 8193 $B.set_func_names(slice,"builtins") 8194 _b_.range=range 8195 _b_.slice=slice})(__BRYTHON__) 8196 ; 8197 ;(function($B){var _b_=$B.builtins 8198 var from_unicode={},to_unicode={} 8199 $B.to_bytes=function(obj){var res 8200 if(_b_.isinstance(obj,[bytes,bytearray])){res=obj.source}else{var ga=$B.$getattr(obj,"tobytes",null) 8201 if(ga !==null){res=$B.$call(ga)().source} 8202 else{throw _b_.TypeError.$factory("object doesn't support the buffer protocol")}} 8203 return res} 8204 function _strip(self,cars,lr){if(cars===undefined){cars=[] 8205 var ws='\r\n \t' 8206 for(var i=0,len=ws.length;i < len;i++){cars.push(ws.charCodeAt(i))}}else if(_b_.isinstance(cars,bytes)){cars=cars.source}else{throw _b_.TypeError.$factory("Type str doesn't support the buffer API")} 8207 if(lr=='l'){for(var i=0,len=self.source.length;i < len;i++){if(cars.indexOf(self.source[i])==-1){break}} 8208 return bytes.$factory(self.source.slice(i))} 8209 for(var i=self.source.length-1;i >=0;i--){if(cars.indexOf(self.source[i])==-1){break}} 8210 return bytes.$factory(self.source.slice(0,i+1))} 8211 function invalid(other){return ! _b_.isinstance(other,[bytes,bytearray])} 8212 var bytearray={__class__:_b_.type,__mro__:[_b_.object],$buffer_protocol:true,$infos:{__module__:"builtins",__name__:"bytearray"},$is_class:true} 8213 var mutable_methods=["__delitem__","clear","copy","count","index","pop","remove","reverse","sort"] 8214 mutable_methods.forEach(function(method){bytearray[method]=(function(m){return function(self){var args=[self.source],pos=1 8215 for(var i=1,len=arguments.length;i < len;i++){args[pos++]=arguments[i]} 8216 return _b_.list[m].apply(null,args)}})(method)}) 8217 var bytearray_iterator=$B.make_iterator_class('bytearray_iterator') 8218 bytearray.__iter__=function(self){return bytearray_iterator.$factory(self.source)} 8219 bytearray.__mro__=[_b_.object] 8220 bytearray.__repr__=bytearray.__str__=function(self){return 'bytearray('+bytes.__repr__(self)+")"} 8221 bytearray.__setitem__=function(self,arg,value){if(_b_.isinstance(arg,_b_.int)){if(! _b_.isinstance(value,_b_.int)){throw _b_.TypeError.$factory('an integer is required')}else if(value > 255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")} 8222 var pos=arg 8223 if(arg < 0){pos=self.source.length+pos} 8224 if(pos >=0 && pos < self.source.length){self.source[pos]=value} 8225 else{throw _b_.IndexError.$factory('list index out of range')}}else if(_b_.isinstance(arg,_b_.slice)){var start=arg.start===_b_.None ? 0 :arg.start 8226 var stop=arg.stop===_b_.None ? self.source.length :arg.stop 8227 if(start < 0){start=self.source.length+start} 8228 if(stop < 0){stop=self.source.length+stop} 8229 self.source.splice(start,stop-start) 8230 try{var $temp=_b_.list.$factory(value) 8231 for(var i=$temp.length-1;i >=0;i--){if(! _b_.isinstance($temp[i],_b_.int)){throw _b_.TypeError.$factory('an integer is required')}else if($temp[i]> 255){throw ValueError.$factory("byte must be in range(0, 256)")} 8232 self.source.splice(start,0,$temp[i])}}catch(err){throw _b_.TypeError.$factory("can only assign an iterable")}}else{throw _b_.TypeError.$factory('list indices must be integer, not '+ 8233 $B.class_name(arg))}} 8234 bytearray.append=function(self,b){if(arguments.length !=2){throw _b_.TypeError.$factory( 8235 "append takes exactly one argument ("+(arguments.length-1)+ 8236 " given)")} 8237 if(! _b_.isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")} 8238 if(b > 255){throw ValueError.$factory("byte must be in range(0, 256)")} 8239 self.source[self.source.length]=b} 8240 bytearray.extend=function(self,b){if(b.__class__===bytearray ||b.__class__===bytes){b.source.forEach(function(item){self.source.push(item)}) 8241 return _b_.None} 8242 var it=_b_.iter(b) 8243 while(true){try{bytearray.__add__(self,_b_.next(it))}catch(err){if(err===_b_.StopIteration){break} 8244 throw err}} 8245 return _b_.None} 8246 bytearray.insert=function(self,pos,b){if(arguments.length !=3){throw _b_.TypeError.$factory( 8247 "insert takes exactly 2 arguments ("+(arguments.length-1)+ 8248 " given)")} 8249 if(! _b_.isinstance(b,_b_.int)){throw _b_.TypeError.$factory("an integer is required")} 8250 if(b > 255){throw ValueError.$factory("byte must be in range(0, 256)")} 8251 _b_.list.insert(self.source,pos,b)} 8252 bytearray.$factory=function(){var args=[bytearray] 8253 for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} 8254 return bytearray.__new__.apply(null,args)} 8255 var bytes={__class__ :_b_.type,__mro__:[_b_.object],$buffer_protocol:true,$infos:{__module__:"builtins",__name__:"bytes"},$is_class:true} 8256 bytes.__add__=function(self,other){if(_b_.isinstance(other,bytes)){return self.__class__.$factory(self.source.concat(other.source))}else if(_b_.isinstance(other,bytearray)){return self.__class__.$factory(bytes.__add__(self,bytes.$factory(other)))}else if(_b_.isinstance(other,_b_.memoryview)){return self.__class__.$factory(bytes.__add__(self,_b_.memoryview.tobytes(other)))} 8257 throw _b_.TypeError.$factory("can't concat bytes to "+ 8258 _b_.str.$factory(other))} 8259 bytes.__contains__=function(self,other){if(typeof other=="number"){return self.source.indexOf(other)>-1} 8260 if(self.source.length < other.source.length){return false} 8261 var len=other.source.length 8262 for(var i=0;i < self.source.length-other.source.length+1;i++){var flag=true 8263 for(var j=0;j < len;j++){if(other.source[i+j]!=self.source[j]){flag=false 8264 break}} 8265 if(flag){return true}} 8266 return false} 8267 var bytes_iterator=$B.make_iterator_class("bytes_iterator") 8268 bytes.__iter__=function(self){return bytes_iterator.$factory(self.source)} 8269 bytes.__eq__=function(self,other){if(invalid(other)){return false} 8270 return $B.$getattr(self.source,'__eq__')(other.source)} 8271 bytes.__ge__=function(self,other){if(invalid(other)){return _b_.NotImplemented} 8272 return _b_.list.__ge__(self.source,other.source)} 8273 bytes.__getitem__=function(self,arg){var i 8274 if(_b_.isinstance(arg,_b_.int)){var pos=arg 8275 if(arg < 0){pos=self.source.length+pos} 8276 if(pos >=0 && pos < self.source.length){return self.source[pos]} 8277 throw _b_.IndexError.$factory("index out of range")}else if(_b_.isinstance(arg,_b_.slice)){var s=_b_.slice.$conv_for_seq(arg,self.source.length),start=s.start,stop=s.stop,step=s.step 8278 var res=[],i=null,pos=0 8279 if(step > 0){stop=Math.min(stop,self.source.length) 8280 if(stop <=start){return bytes.$factory([])} 8281 for(var i=start;i < stop;i+=step){res[pos++]=self.source[i]}}else{if(stop >=start){return bytes.$factory([])} 8282 stop=Math.max(0,stop) 8283 for(var i=start;i >=stop;i+=step){res[pos++]=self.source[i]}} 8284 return bytes.$factory(res)}else if(_b_.isinstance(arg,_b_.bool)){return self.source.__getitem__(_b_.int.$factory(arg))}} 8285 bytes.__gt__=function(self,other){if(invalid(other)){return _b_.NotImplemented} 8286 return _b_.list.__gt__(self.source,other.source)} 8287 bytes.__hash__=function(self){if(self===undefined){return bytes.__hashvalue__ ||$B.$py_next_hash--} 8288 var hash=1 8289 for(var i=0,len=self.source.length;i < len;i++){hash=(101*hash+self.source[i])& 0xFFFFFFFF} 8290 return hash} 8291 bytes.__init__=function(){return _b_.None} 8292 bytes.__le__=function(self,other){if(invalid(other)){return _b_.NotImplemented} 8293 return _b_.list.__le__(self.source,other.source)} 8294 bytes.__len__=function(self){return self.source.length} 8295 bytes.__lt__=function(self,other){if(invalid(other)){return _b_.NotImplemented} 8296 return _b_.list.__lt__(self.source,other.source)} 8297 bytes.__mod__=function(self,args){ 8298 var s=decode(self,"ascii","strict"),res=_b_.str.__mod__(s,args) 8299 return _b_.str.encode(res,"ascii")} 8300 bytes.__mul__=function(){var $=$B.args('__mul__',2,{self:null,other:null},['self','other'],arguments,{},null,null),other=$B.PyNumber_Index($.other) 8301 var t=[],source=$.self.source,slen=source.length 8302 for(var i=0;i < other;i++){for(var j=0;j < slen;j++){t.push(source[j])}} 8303 var res=bytes.$factory() 8304 res.source=t 8305 return res} 8306 bytes.__ne__=function(self,other){return ! bytes.__eq__(self,other)} 8307 bytes.__new__=function(cls,source,encoding,errors){var $=$B.args("__new__",4,{cls:null,source:null,encoding:null,errors:null},["cls","source","encoding","errors"],arguments,{source:[],encoding:"utf-8",errors:"strict"},null,null) 8308 return bytes.$new($.cls,$.source,$.encoding,$.errors)} 8309 bytes.$new=function(cls,source,encoding,errors){ 8310 var self={__class__:cls},int_list=[],pos=0 8311 if(source===undefined){}else if(typeof source=="number" ||_b_.isinstance(source,_b_.int)){var i=source 8312 while(i--){int_list[pos++]=0}}else{if(typeof source=="string" ||_b_.isinstance(source,_b_.str)){if(encoding===undefined){throw _b_.TypeError.$factory("string argument without an encoding")} 8313 int_list=encode(source,encoding ||"utf-8",errors ||"strict")}else{ 8314 int_list=_b_.list.$factory(source) 8315 for(var i=0;i < int_list.length;i++){try{var item=_b_.int.$factory(int_list[i])}catch(err){throw _b_.TypeError.$factory("'"+ 8316 $B.class_name(int_list[i])+"' object "+ 8317 "cannot be interpreted as an integer")} 8318 if(item < 0 ||item > 255){throw _b_.ValueError.$factory("bytes must be in range"+ 8319 "(0, 256)")}}}} 8320 self.source=int_list 8321 self.encoding=encoding 8322 self.errors=errors 8323 return self} 8324 bytes.__repr__=bytes.__str__=function(self){var res="" 8325 for(var i=0,len=self.source.length;i < len;i++){var s=self.source[i] 8326 if(s==10){res+='\\n'}else if(s < 32 ||s >=128){var hx=s.toString(16) 8327 hx=(hx.length==1 ? '0' :'')+hx 8328 res+='\\x'+hx}else if(s=="\\".charCodeAt(0)){res+="\\\\"}else{res+=String.fromCharCode(s)}} 8329 if(res.indexOf("'")>-1 && res.indexOf('"')==-1){return 'b"'+res+'"'}else{return "b'"+res.replace(new RegExp("'","g"),"\\'")+"'"}} 8330 bytes.__reduce_ex__=function(self){return bytes.__repr__(self)} 8331 bytes.capitalize=function(self){var src=self.source,len=src.length,buffer=src.slice() 8332 if(buffer[0]> 96 && buffer[0]< 123){buffer[0]-=32} 8333 for(var i=1;i < len;++i){if(buffer[i]> 64 && buffer[i]< 91){buffer[i]+=32}} 8334 return bytes.$factory(buffer)} 8335 bytes.center=function(){var $=$B.args('center',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) 8336 var diff=$.width-$.self.source.length 8337 if(diff <=0){return bytes.$factory($.self.source)} 8338 var ljust=bytes.ljust($.self,$.self.source.length+Math.floor(diff/2),$.fillbyte) 8339 return bytes.rjust(ljust,$.width,$.fillbyte)} 8340 bytes.count=function(){var $=$B.args('count',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null) 8341 var n=0,index=-1,len=0 8342 if(typeof $.sub=="number"){if($.sub < 0 ||$.sub > 255) 8343 throw _b_.ValueError.$factory("byte must be in range(0, 256)") 8344 len=1}else if(!$.sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8345 "object, not '"+$B.class_name($.sub)+"'")}else if(!$.sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8346 "object, not '"+$B.class_name($.sub)+"'")}else{len=$.sub.source.length} 8347 do{index=bytes.find($.self,$.sub,Math.max(index+len,$.start),$.end) 8348 if(index !=-1){n++}}while(index !=-1) 8349 return n} 8350 bytes.decode=function(self,encoding,errors){var $=$B.args("decode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null) 8351 switch($.errors){case 'strict': 8352 case 'ignore': 8353 case 'replace': 8354 case 'surrogateescape': 8355 case 'surrogatepass': 8356 case 'xmlcharrefreplace': 8357 case 'backslashreplace': 8358 return decode($.self,$.encoding,$.errors) 8359 default:}} 8360 bytes.endswith=function(){var $=$B.args('endswith',4,{self:null,suffix:null,start:null,end:null},['self','suffix','start','end'],arguments,{start:-1,end:-1},null,null) 8361 if(_b_.isinstance($.suffix,bytes)){var start=$.start==-1 ? 8362 $.self.source.length-$.suffix.source.length : 8363 Math.min($.self.source.length-$.suffix.source.length,$.start) 8364 var end=$.end==-1 ? 8365 ($.start==-1 ? $.self.source.length :start+$.suffix.source.length): 8366 Math.min($.self.source.length-1,$.end) 8367 var res=true 8368 for(var i=$.suffix.source.length-1,len=$.suffix.source.length; 8369 i >=0 && res;--i){res=$.self.source[end-len+i]==$.suffix.source[i]} 8370 return res}else if(_b_.isinstance($.suffix,_b_.tuple)){for(var i=0;i < $.suffix.length;++i){if(_b_.isinstance($.suffix[i],bytes)){if(bytes.endswith($.self,$.suffix[i],$.start,$.end)){return true}}else{throw _b_.TypeError.$factory("endswith first arg must be "+ 8371 "bytes or a tuple of bytes, not "+ 8372 $B.class_name($.suffix))}} 8373 return false}else{throw _b_.TypeError.$factory("endswith first arg must be bytes "+ 8374 "or a tuple of bytes, not "+$B.class_name($.suffix))}} 8375 bytes.expandtabs=function(){var $=$B.args('expandtabs',2,{self:null,tabsize:null},['self','tabsize'],arguments,{tabsize:8},null,null) 8376 var tab_spaces=[] 8377 for(let i=0;i < $.tabsize;++i){tab_spaces.push(32)} 8378 var buffer=$.self.source.slice() 8379 for(let i=0;i < buffer.length;++i){if(buffer[i]===9){buffer.splice.apply(buffer,[i,1].concat(tab_spaces))}} 8380 return _b_.bytes.$factory(buffer)} 8381 bytes.find=function(self,sub){if(arguments.length !=2){var $=$B.args('find',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null),sub=$.sub,start=$.start,end=$.end}else{var start=0,end=-1} 8382 if(typeof sub=="number"){if(sub < 0 ||sub > 255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")} 8383 return self.source.slice(0,end==-1 ? undefined :end).indexOf(sub,start)}else if(! sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8384 "object, not '"+$B.class_name(sub)+"'")}else if(! sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8385 "object, not '"+$B.class_name(sub)+"'")} 8386 end=end==-1 ? self.source.length :Math.min(self.source.length,end) 8387 var len=sub.source.length 8388 for(var i=start;i <=end-len;i++){var chunk=self.source.slice(i,i+len),found=true 8389 for(var j=0;j < len;j++){if(chunk[j]!=sub.source[j]){found=false 8390 break}} 8391 if(found){return i}} 8392 return-1} 8393 bytes.fromhex=function(){var $=$B.args('fromhex',2,{cls:null,string:null},['cls','string'],arguments,{},null,null),string=$.string.replace(/\s/g,''),source=[] 8394 for(var i=0;i < string.length;i+=2){if(i+2 > string.length){throw _b_.ValueError.$factory("non-hexadecimal number found "+ 8395 "in fromhex() arg")} 8396 source.push(_b_.int.$factory(string.substr(i,2),16))} 8397 return $.cls.$factory(source)} 8398 bytes.hex=function(){ 8399 var $=$B.args('hex',1,{self:null},['self'],arguments,{},null,null),self=$.self,res="" 8400 for(var i=0,len=self.source.length;i < len;i++){var hexa=self.source[i].toString(16) 8401 if(hexa.length < 2){hexa="0"+hexa} 8402 res+=hexa} 8403 return res} 8404 bytes.index=function(){var $=$B.args('rfind',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null) 8405 var index=bytes.find($.self,$.sub,$.start,$.end) 8406 if(index==-1){throw _b_.ValueError.$factory("subsection not found")} 8407 return index} 8408 bytes.isalnum=function(self){var src=self.source,len=src.length,res=len > 0 8409 for(var i=0;i < len && res;++i){res=(src[i]> 96 && src[i]< 123)|| 8410 (src[i]> 64 && src[i]< 91)|| 8411 (src[i]> 47 && src[i]< 58)} 8412 return res} 8413 bytes.isalpha=function(self){var src=self.source,len=src.length,res=len > 0 8414 for(var i=0;i < len && res;++i){res=(src[i]> 96 && src[i]< 123)||(src[i]> 64 && src[i]< 91)} 8415 return res} 8416 bytes.isdigit=function(self){var src=self.source,len=src.length,res=len > 0 8417 for(let i=0;i < len && res;++i){res=src[i]> 47 && src[i]< 58} 8418 return res} 8419 bytes.islower=function(self){var src=self.source,len=src.length,res=false 8420 for(let i=0;i < len;++i){ 8421 res=res ||(src[i]> 96 && src[i]< 123) 8422 if(src[i]> 64 && src[i]< 91){return false}} 8423 return res} 8424 bytes.isspace=function(self){var src=self.source,len=src.length 8425 for(let i=0;i < len;++i){switch(src[i]){case 9: 8426 case 10: 8427 case 11: 8428 case 12: 8429 case 13: 8430 case 32: 8431 break 8432 default: 8433 return false}} 8434 return true} 8435 bytes.isupper=function(self){var src=self.source,len=src.length,res=false 8436 for(let i=0;i < len;++i){ 8437 res=res ||(src[i]> 64 && src[i]< 91) 8438 if(src[i]> 96 && src[i]< 123){return false}} 8439 return res} 8440 bytes.istitle=function(self){var src=self.source,len=src.length,current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false 8441 for(var i=0;i < len;++i){is_lowercase=src[i]> 96 && src[i]< 123 8442 is_uppercase=src[i]> 64 && src[i]< 91 8443 current_char_is_letter=is_lowercase ||is_uppercase 8444 if(current_char_is_letter && 8445 (prev_char_was_letter && is_uppercase)|| 8446 (! prev_char_was_letter && is_lowercase)){return false} 8447 prev_char_was_letter=current_char_is_letter} 8448 return true} 8449 bytes.join=function(){var $ns=$B.args('join',2,{self:null,iterable:null},['self','iterable'],arguments,{}),self=$ns['self'],iterable=$ns['iterable'] 8450 var next_func=$B.$getattr(_b_.iter(iterable),'__next__'),res=self.__class__.$factory(),empty=true 8451 while(true){try{var item=next_func() 8452 if(empty){empty=false} 8453 else{res=bytes.__add__(res,self)} 8454 res=bytes.__add__(res,item)}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){break} 8455 throw err}} 8456 return res} 8457 var _lower=function(char_code){if(char_code >=65 && char_code <=90){return char_code+32}else{return char_code}} 8458 bytes.lower=function(self){var _res=[],pos=0 8459 for(var i=0,len=self.source.length;i < len;i++){if(self.source[i]){_res[pos++]=_lower(self.source[i])}} 8460 return bytes.$factory(_res)} 8461 bytes.ljust=function(){var $=$B.args('ljust',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) 8462 if(!$.fillbyte.__class__){throw _b_.TypeError.$factory("argument 2 must be a byte string of length 1, "+ 8463 "not '"+$B.class_name($.fillbyte)+"'")}else if(!$.fillbyte.__class__.$buffer_protocol){throw _b_.TypeError.$factory("argument 2 must be a byte string of length 1, "+ 8464 "not '"+$B.class_name($.fillbyte)+"'")} 8465 var padding=[],count=$.width-$.self.source.length 8466 for(var i=0;i < count;++i){padding.push($.fillbyte.source[0])} 8467 return bytes.$factory($.self.source.concat(padding))} 8468 bytes.lstrip=function(self,cars){return _strip(self,cars,'l')} 8469 bytes.maketrans=function(from,to){var _t=[],to=$B.to_bytes(to) 8470 for(var i=0;i < 256;i++){_t[i]=i} 8471 for(var i=0,len=from.source.length;i < len;i++){var _ndx=from.source[i] 8472 _t[_ndx]=to[i]} 8473 return bytes.$factory(_t)} 8474 bytes.partition=function(){var $=$B.args('partition',2,{self:null,sep:null},['self','sep'],arguments,{},null,null) 8475 if(! $.sep.__class__){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8476 "not '"+$B.class_name($.sep)+"'")}else if(! $.sep.__class__.$buffer_protocol){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8477 "not '"+$B.class_name($.sep)+"'")} 8478 var len=$.sep.source.length,src=$.self.source,i=bytes.find($.self,$.sep) 8479 return _b_.tuple.$factory([bytes.$factory(src.slice(0,i)),bytes.$factory(src.slice(i,i+len)),bytes.$factory(src.slice(i+len)) 8480 ])} 8481 bytes.removeprefix=function(){var $=$B.args("removeprefix",2,{self:null,prefix:null},["self","prefix"],arguments,{},null,null) 8482 if(!_b_.isinstance($.prefix,[bytes,bytearray])){throw _b_.ValueError.$factory("prefix should be bytes, not "+ 8483 `'${$B.class_name($.prefix)}'`)} 8484 if(bytes.startswith($.self,$.prefix)){return bytes.__getitem__($.self,_b_.slice.$factory($.prefix.source.length,_b_.None))} 8485 return bytes.__getitem__($.self,_b_.slice.$factory(0,_b_.None))} 8486 bytes.removesuffix=function(){var $=$B.args("removesuffix",2,{self:null,prefix:null},["self","suffix"],arguments,{},null,null) 8487 if(!_b_.isinstance($.suffix,[bytes,bytearray])){throw _b_.ValueError.$factory("suffix should be bytes, not "+ 8488 `'${$B.class_name($.suffix)}'`)} 8489 if(bytes.endswith($.self,$.suffix)){return bytes.__getitem__($.self,_b_.slice.$factory(0,$.suffix.source.length+1))} 8490 return bytes.__getitem__($.self,_b_.slice.$factory(0,_b_.None))} 8491 bytes.replace=function(){var $=$B.args('replace',4,{self:null,old:null,new:null,count:null},['self','old','new','count'],arguments,{count:-1},null,null),res=[] 8492 var self=$.self,src=self.source,len=src.length,old=$.old,$new=$.new 8493 var count=$.count >=0 ? $.count :src.length 8494 if(! $.old.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8495 "object, not '"+$B.class_name($.old)+"'")}else if(! $.old.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8496 "object, not '"+$B.class_name($.sep)+"'")} 8497 if(! $.new.__class__){throw _b_.TypeError.$factory("second argument must be a bytes-like "+ 8498 "object, not '"+$B.class_name($.old)+"'")}else if(! $.new.__class__.$buffer_protocol){throw _b_.TypeError.$factory("second argument must be a bytes-like "+ 8499 "object, not '"+$B.class_name($.sep)+"'")} 8500 for(var i=0;i < len;i++){if(bytes.startswith(self,old,i)&& count){for(var j=0;j < $new.source.length;j++){res.push($new.source[j])} 8501 i+=(old.source.length-1) 8502 count--}else{res.push(src[i])}} 8503 return bytes.$factory(res)} 8504 bytes.rfind=function(self,subbytes){if(arguments.length==2 && subbytes.__class__===bytes){var sub=subbytes,start=0,end=-1}else{var $=$B.args('rfind',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null),self=$.self,sub=$.sub,start=$.start,end=$.end} 8505 if(typeof sub=="number"){if(sub < 0 ||sub > 255){throw _b_.ValueError.$factory("byte must be in range(0, 256)")} 8506 return $.self.source.slice(start,$.end==-1 ? undefined :$.end). 8507 lastIndexOf(sub)+start}else if(! sub.__class__){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8508 "object, not '"+$B.class_name($.sub)+"'")}else if(! sub.__class__.$buffer_protocol){throw _b_.TypeError.$factory("first argument must be a bytes-like "+ 8509 "object, not '"+$B.class_name(sub)+"'")} 8510 end=end==-1 ? self.source.length :Math.min(self.source.length,end) 8511 var len=sub.source.length 8512 for(var i=end-len;i >=start;--i){var chunk=self.source.slice(i,i+len),found=true 8513 for(var j=0;j < len;j++){if(chunk[j]!=sub.source[j]){found=false 8514 break}} 8515 if(found){return i}} 8516 return-1} 8517 bytes.rindex=function(){var $=$B.args('rfind',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null) 8518 var index=bytes.rfind($.self,$.sub,$.start,$.end) 8519 if(index==-1){throw _b_.ValueError.$factory("subsection not found")} 8520 return index} 8521 bytes.rjust=function(){var $=$B.args('rjust',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) 8522 if(!$.fillbyte.__class__){throw _b_.TypeError.$factory("argument 2 must be a byte string of length 1, "+ 8523 "not '"+$B.class_name($.fillbyte)+"'")}else if(!$.fillbyte.__class__.$buffer_protocol){throw _b_.TypeError.$factory("argument 2 must be a byte string of length 1, "+ 8524 "not '"+$B.class_name($.fillbyte)+"'")} 8525 var padding=[],count=$.width-$.self.source.length 8526 for(var i=0;i < count;++i){padding.push($.fillbyte.source[0])} 8527 return bytes.$factory(padding.concat($.self.source))} 8528 bytes.rpartition=function(){var $=$B.args('rpartition',2,{self:null,sep:null},['self','sep'],arguments,{},null,null) 8529 if(!$.sep.__class__){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8530 "not '"+$B.class_name($.sep)+"'")}else if(!$.sep.__class__.$buffer_protocol){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8531 "not '"+$B.class_name($.sep)+"'")} 8532 var len=$.sep.source.length,src=$.self.source,i=bytes.rfind($.self,$.sep) 8533 return _b_.tuple.$factory([bytes.$factory(src.slice(0,i)),bytes.$factory(src.slice(i,i+len)),bytes.$factory(src.slice(i+len)) 8534 ])} 8535 bytes.rstrip=function(self,cars){return _strip(self,cars,'r')} 8536 bytes.split=function(){var $=$B.args('split',2,{self:null,sep:null},['self','sep'],arguments,{},null,null),res=[],start=0,stop=0 8537 if(! $.sep.__class__ ){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8538 "not '"+$B.class_name($.sep)+"'")}else if(! $.sep.__class__.$buffer_protocol){throw _b_.TypeError.$factory("a bytes-like object is required, "+ 8539 "not '"+$B.class_name($.sep)+"'")} 8540 var seps=$.sep.source,len=seps.length,src=$.self.source,blen=src.length 8541 while(stop < blen){var match=true 8542 for(var i=0;i < len && match;i++){if(src[stop+i]!=seps[i]){match=false}} 8543 if(match){res.push(bytes.$factory(src.slice(start,stop))) 8544 start=stop+len 8545 stop=start}else{stop++}} 8546 if(match ||(stop > start)){res.push(bytes.$factory(src.slice(start,stop)))} 8547 return res} 8548 bytes.splitlines=function(self){var $=$B.args('splitlines',2,{self:null,keepends:null},['self','keepends'],arguments,{keepends:false},null,null) 8549 if(!_b_.isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError('integer argument expected, got '+ 8550 $B.get_class($.keepends).__name)} 8551 var keepends=_b_.int.$factory($.keepends),res=[],source=$.self.source,start=0,pos=0 8552 if(! source.length){return res} 8553 while(pos < source.length){if(pos < source.length-1 && source[pos]==0x0d && 8554 source[pos+1]==0x0a){res.push(bytes.$factory(source.slice(start,keepends ? pos+2 :pos))) 8555 start=pos=pos+2}else if(source[pos]==0x0d ||source[pos]==0x0a){res.push(bytes.$factory(source.slice(start,keepends ? pos+1 :pos))) 8556 start=pos=pos+1}else{pos++}} 8557 if(start < source.length){res.push(bytes.$factory(source.slice(start)))} 8558 return res} 8559 bytes.startswith=function(){var $=$B.args('startswith',3,{self:null,prefix:null,start:null},['self','prefix','start'],arguments,{start:0},null,null),start=$.start 8560 if(_b_.isinstance($.prefix,bytes)){var res=true 8561 for(var i=0;i < $.prefix.source.length && res;i++){res=$.self.source[start+i]==$.prefix.source[i]} 8562 return res}else if(_b_.isinstance($.prefix,_b_.tuple)){var items=[] 8563 for(var i=0;i < $.prefix.length;i++){if(_b_.isinstance($.prefix[i],bytes)){items=items.concat($.prefix[i].source)}else{throw _b_.TypeError.$factory("startswith first arg must be "+ 8564 "bytes or a tuple of bytes, not "+ 8565 $B.class_name($.prefix))}} 8566 var prefix=bytes.$factory(items) 8567 return bytes.startswith($.self,prefix,start)}else{throw _b_.TypeError.$factory("startswith first arg must be bytes "+ 8568 "or a tuple of bytes, not "+$B.class_name($.prefix))}} 8569 bytes.strip=function(self,cars){var res=bytes.lstrip(self,cars) 8570 return bytes.rstrip(res,cars)} 8571 bytes.swapcase=function(self){var src=self.source,len=src.length,buffer=src.slice() 8572 for(var i=0;i < len;++i){if(buffer[i]> 96 && buffer[i]< 123){buffer[i]-=32}else if(buffer[i]> 64 && buffer[i]< 91){buffer[i]+=32}} 8573 return bytes.$factory(buffer)} 8574 bytes.title=function(self){var src=self.source,len=src.length 8575 buffer=src.slice(),current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false 8576 for(var i=0;i < len;++i){is_lowercase=buffer[i]> 96 && buffer[i]< 123 8577 is_uppercase=buffer[i]> 64 && buffer[i]< 91 8578 current_char_is_letter=is_lowercase ||is_uppercase 8579 if(current_char_is_letter){if(prev_char_was_letter && is_uppercase){buffer[i]+=32}else if(! prev_char_was_letter && is_lowercase){buffer[i]-=32}} 8580 prev_char_was_letter=current_char_is_letter} 8581 return bytes.$factory(buffer)} 8582 bytes.translate=function(self,table,_delete){if(_delete===undefined){_delete=[]}else if(_b_.isinstance(_delete,bytes)){_delete=_delete.source}else{throw _b_.TypeError.$factory("Type "+ 8583 $B.get_class(_delete).__name+" doesn't support the buffer API")} 8584 var res=[],pos=0 8585 if(_b_.isinstance(table,bytes)&& table.source.length==256){for(var i=0,len=self.source.length;i < len;i++){if(_delete.indexOf(self.source[i])>-1){continue} 8586 res[pos++]=table.source[self.source[i]]}} 8587 return bytes.$factory(res)} 8588 var _upper=function(char_code){if(char_code >=97 && char_code <=122){return char_code-32}else{return char_code}} 8589 bytes.upper=function(self){var _res=[],pos=0 8590 for(var i=0,len=self.source.length;i < len;i++){if(self.source[i]){_res[pos++]=_upper(self.source[i])}} 8591 return bytes.$factory(_res)} 8592 bytes.zfill=function(self,width){var buffer=self.source.slice(),prefix_offset=(buffer[0]==43 ||buffer[0]==45)? 1 :0 8593 var count=width-self.source.length 8594 var padding=[] 8595 for(var i=0;i < count;++i){padding.push(48)} 8596 buffer.splice.apply(buffer,[prefix_offset,0].concat(padding)) 8597 return bytes.$factory(buffer)} 8598 function $UnicodeEncodeError(encoding,code_point,position){throw _b_.UnicodeEncodeError.$factory("'"+encoding+ 8599 "' codec can't encode character "+_b_.hex(code_point)+ 8600 " in position "+position)} 8601 function $UnicodeDecodeError(encoding,position){throw _b_.UnicodeDecodeError.$factory("'"+encoding+ 8602 "' codec can't decode bytes in position "+position)} 8603 function _hex(_int){return _int.toString(16)} 8604 function _int(hex){return parseInt(hex,16)} 8605 function normalise(encoding){var enc=encoding.toLowerCase() 8606 if(enc.substr(0,7)=="windows"){enc="cp"+enc.substr(7)} 8607 if(enc.startsWith("cp")||enc.startsWith("iso")){enc=enc.replace("-","")} 8608 enc=enc.replace(/-/g,"_") 8609 return enc} 8610 function load_decoder(enc){ 8611 if(to_unicode[enc]===undefined){var mod=_b_.__import__("encodings."+enc) 8612 if(mod[enc].getregentry){to_unicode[enc]=$B.$getattr(mod[enc].getregentry(),"decode")}}} 8613 function load_encoder(enc){ 8614 if(from_unicode[enc]===undefined){var mod=_b_.__import__("encodings."+enc) 8615 if(mod[enc].getregentry){from_unicode[enc]=$B.$getattr(mod[enc].getregentry(),"encode")}}} 8616 var decode=$B.decode=function(obj,encoding,errors){var s="",b=obj.source,enc=normalise(encoding),has_surrogate=false 8617 switch(enc){case "utf_8": 8618 case "utf-8": 8619 case "utf8": 8620 case "U8": 8621 case "UTF": 8622 var pos=0,s="",err_info 8623 while(pos < b.length){var byte=b[pos] 8624 err_info=null 8625 if(!(byte & 0x80)){ 8626 s+=String.fromCodePoint(byte) 8627 pos++}else if((byte >> 5)==6){ 8628 if(b[pos+1]===undefined){err_info=[byte,pos,"end"]}else if((b[pos+1]& 0xc0)!=0x80){err_info=[byte,pos,"continuation"]} 8629 if(err_info !==null){if(errors=="ignore"){pos++}else{throw _b_.UnicodeDecodeError.$factory( 8630 "'utf-8' codec can't decode byte 0x"+ 8631 err_info[0].toString(16)+" in position "+ 8632 err_info[1]+ 8633 (err_info[2]=="end" ? ": unexpected end of data" : 8634 ": invalid continuation byte"))}}else{var cp=byte & 0x1f 8635 cp <<=6 8636 cp+=b[pos+1]& 0x3f 8637 s+=String.fromCodePoint(cp) 8638 pos+=2}}else if((byte >> 4)==14){ 8639 if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]& 0xc0)!=0x80){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+'-'+(pos+1),"end",pos+2]}else if((b[pos+2]& 0xc0)!=0x80){err_info=[byte,pos,"continuation",pos+3]} 8640 if(err_info !==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(var i=pos;i < err_info[3];i++){s+=String.fromCodePoint(0xdc80+b[i]-0x80)} 8641 pos=err_info[3]}else{throw _b_.UnicodeDecodeError.$factory( 8642 "'utf-8' codec can't decode byte 0x"+ 8643 err_info[0].toString(16)+" in position "+ 8644 err_info[1]+ 8645 (err_info[2]=="end" ? ": unexpected end of data" : 8646 ": invalid continuation byte"))}}else{var cp=byte & 0xf 8647 cp=cp << 12 8648 cp+=(b[pos+1]& 0x3f)<< 6 8649 cp+=b[pos+2]& 0x3f 8650 s+=String.fromCodePoint(cp) 8651 pos+=3}}else if((byte >> 3)==30){ 8652 has_surrogate=true 8653 if(b[pos+1]===undefined){err_info=[byte,pos,"end",pos+1]}else if((b[pos+1]& 0xc0)!=0x80){err_info=[byte,pos,"continuation",pos+2]}else if(b[pos+2]===undefined){err_info=[byte,pos+'-'+(pos+1),"end",pos+2]}else if((b[pos+2]& 0xc0)!=0x80){err_info=[byte,pos,"continuation",pos+3]}else if(b[pos+3]===undefined){err_info=[byte,pos+'-'+(pos+1)+'-'+(pos+2),"end",pos+3]}else if((b[pos+2]& 0xc0)!=0x80){err_info=[byte,pos,"continuation",pos+3]} 8654 if(err_info !==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(var i=pos;i < err_info[3];i++){s+=String.fromCodePoint(0xdc80+b[i]-0x80)} 8655 pos=err_info[3]}else{throw _b_.UnicodeDecodeError.$factory( 8656 "'utf-8' codec can't decode byte 0x"+ 8657 err_info[0].toString(16)+" in position "+ 8658 err_info[1]+ 8659 (err_info[2]=="end" ? ": unexpected end of data" : 8660 ": invalid continuation byte"))}}else{var cp=byte & 0xf 8661 cp=cp << 18 8662 cp+=(b[pos+1]& 0x3f)<< 12 8663 cp+=(b[pos+2]& 0x3f)<< 6 8664 cp+=(b[pos+3]& 0x3f) 8665 s+=String.fromCodePoint(cp) 8666 pos+=4}}else{if(errors=="ignore"){pos++}else if(errors=="surrogateescape"){s+=String.fromCodePoint(0xdc80+b[pos]-0x80) 8667 pos++}else{throw _b_.UnicodeDecodeError.$factory( 8668 "'utf-8' codec can't decode byte 0x"+ 8669 byte.toString(16)+" in position "+pos+ 8670 ": invalid start byte")}}} 8671 if(has_surrogate){return _b_.str.$surrogate.$factory(s)} 8672 return s 8673 case "latin_1": 8674 case "windows1252": 8675 case "iso-8859-1": 8676 case "iso8859-1": 8677 case "8859": 8678 case "cp819": 8679 case "latin": 8680 case "latin1": 8681 case "L1": 8682 b.forEach(function(item){s+=String.fromCharCode(item)}) 8683 break 8684 case "unicode_escape": 8685 if(obj.__class__===bytes ||obj.__class__===bytearray){obj=decode(obj,"latin-1","strict")} 8686 return obj.replace(/\\n/g,"\n"). 8687 replace(/\\a/g,"\u0007"). 8688 replace(/\\b/g,"\b"). 8689 replace(/\\f/g,"\f"). 8690 replace(/\\t/g,"\t"). 8691 replace(/\\'/g,"'"). 8692 replace(/\\"/g,'"') 8693 case "raw_unicode_escape": 8694 if(obj.__class__===bytes ||obj.__class__===bytearray){obj=decode(obj,"latin-1","strict")} 8695 return obj.replace(/\\u([a-fA-F0-9]{4})/g,function(mo){var cp=parseInt(mo.substr(2),16) 8696 return String.fromCharCode(cp)}) 8697 case "ascii": 8698 for(var i=0,len=b.length;i < len;i++){var cp=b[i] 8699 if(cp <=127){s+=String.fromCharCode(cp)}else{if(errors=="ignore"){}else{var msg="'ascii' codec can't decode byte 0x"+ 8700 cp.toString(16)+" in position "+i+ 8701 ": ordinal not in range(128)" 8702 throw _b_.UnicodeDecodeError.$factory(msg)}}} 8703 break 8704 default: 8705 try{load_decoder(enc)}catch(err){console.log(b,encoding,"error load_decoder",err) 8706 throw _b_.LookupError.$factory("unknown encoding: "+enc)} 8707 return to_unicode[enc](obj)[0]} 8708 return s} 8709 var encode=$B.encode=function(){var $=$B.args("encode",3,{s:null,encoding:null,errors:null},["s","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),s=$.s,encoding=$.encoding,errors=$.errors 8710 var t=[],pos=0,enc=normalise(encoding) 8711 switch(enc){case "utf-8": 8712 case "utf_8": 8713 case "utf8": 8714 var res=[] 8715 for(var i=0,len=s.length;i < len;i++){var cp=s.charCodeAt(i) 8716 if(cp < 0x7f){res.push(cp)}else if(cp < 0x7ff){res.push(0xc0+(cp >> 6),0x80+(cp & 0x3f))}else if(cp < 0xffff){res.push(0xe0+(cp >> 12),0x80+((cp & 0xfff)>> 6),0x80+(cp & 0x3f))}else{console.log("4 bytes")}} 8717 return res 8718 case "latin": 8719 case "latin1": 8720 case "latin-1": 8721 case "latin_1": 8722 case "L1": 8723 case "iso8859_1": 8724 case "iso_8859_1": 8725 case "8859": 8726 case "cp819": 8727 case "windows1252": 8728 for(var i=0,len=s.length;i < len;i++){var cp=s.charCodeAt(i) 8729 if(cp <=255){t[pos++]=cp} 8730 else if(errors !="ignore"){$UnicodeEncodeError(encoding,i)}} 8731 break 8732 case "ascii": 8733 for(var i=0,len=s.length;i < len;i++){var cp=s.charCodeAt(i) 8734 if(cp <=127){t[pos++]=cp} 8735 else if(errors !="ignore"){$UnicodeEncodeError(encoding,i)}} 8736 break 8737 case "raw_unicode_escape": 8738 for(var i=0,len=s.length;i < len;i++){var cp=s.charCodeAt(i) 8739 if(cp < 256){t[pos++]=cp}else{var us=cp.toString(16) 8740 if(us.length % 2){us="0"+us} 8741 us="\\u"+us 8742 for(var j=0;j < us.length;j++){t[pos++]=us.charCodeAt(j)}}} 8743 break 8744 default: 8745 try{load_encoder(enc)}catch(err){throw _b_.LookupError.$factory("unknown encoding: "+encoding)} 8746 t=from_unicode[enc](s)[0].source} 8747 return t} 8748 bytes.$factory=function(source,encoding,errors){var $=$B.args("bytes",3,{source:null,encoding:null,errors:null},["source","encoding","errors"],arguments,{source:[],encoding:"utf-8",errors:"strict"},null,null) 8749 return bytes.$new(bytes,$.source,$.encoding,$.errors)} 8750 bytes.__class__=_b_.type 8751 bytes.$is_class=true 8752 for(var attr in bytes){if(bytearray[attr]===undefined && typeof bytes[attr]=="function"){bytearray[attr]=(function(_attr){return function(){return bytes[_attr].apply(null,arguments)}})(attr)}} 8753 $B.set_func_names(bytes,"builtins") 8754 bytes.fromhex=_b_.classmethod.$factory(bytes.fromhex) 8755 $B.set_func_names(bytearray,"builtins") 8756 bytearray.fromhex=_b_.classmethod.$factory(bytearray.fromhex) 8757 _b_.bytes=bytes 8758 _b_.bytearray=bytearray})(__BRYTHON__) 8759 ; 8760 ;(function($B){var _b_=$B.builtins,object=_b_.object,$N=_b_.None 8761 function create_type(obj){return $B.get_class(obj).$factory()} 8762 function clone(obj){var res=create_type(obj) 8763 res.$items=obj.$items.slice() 8764 for(key in obj.$hashes){res.$hashes[key]=obj.$hashes[key]} 8765 return res} 8766 var set={__class__:_b_.type,$infos:{__module__:"builtins",__name__:"set"},$is_class:true,$native:true} 8767 set.__add__=function(self,other){throw _b_.TypeError.$factory( 8768 "unsupported operand type(s) for +: 'set' and "+typeof other)} 8769 set.__and__=function(self,other,accept_iter){try{$test(accept_iter,other)} 8770 catch(err){return _b_.NotImplemented} 8771 var res=create_type(self) 8772 for(var i=0,len=self.$items.length;i < len;i++){if(_b_.getattr(other,"__contains__")(self.$items[i])){set.add(res,self.$items[i])}} 8773 return res} 8774 set.__class_getitem__=function(cls,item){ 8775 if(! Array.isArray(item)){item=[item]} 8776 return $B.GenericAlias.$factory(cls,item)} 8777 set.__contains__=function(self,item){if(self.$simple){if(typeof item=="number" ||item instanceof Number){if(isNaN(item)){ 8778 for(var i=self.$items.length-1;i >=0;i--){if(isNaN(self.$items[i])){return true}} 8779 return false}else if(item instanceof Number){return self.$numbers.indexOf(item.valueOf())>-1}else{return self.$items.indexOf(item)>-1}}else if(typeof item=="string"){return self.$items.indexOf(item)>-1}} 8780 if(! _b_.isinstance(item,set)){$B.$getattr(item,"__hash__")} 8781 var hash=_b_.hash(item) 8782 if(self.$hashes[hash]){for(var i=0,len=self.$hashes[hash].length;i < len;i++){if($B.rich_comp("__eq__",self.$hashes[hash][i],item)){return true}}} 8783 return false} 8784 set.__eq__=function(self,other){ 8785 if(other===undefined){return self===set} 8786 if(_b_.isinstance(other,[_b_.set,_b_.frozenset])){if(other.$items.length==self.$items.length){for(var i=0,len=self.$items.length;i < len;i++){if(set.__contains__(self,other.$items[i])===false){return false}} 8787 return true} 8788 return false} 8789 return _b_.NotImplemented} 8790 set.__format__=function(self,format_string){return set.__str__(self)} 8791 set.__ge__=function(self,other){if(_b_.isinstance(other,[set,frozenset])){return set.__le__(other,self)} 8792 return _b_.NotImplemented} 8793 set.__gt__=function(self,other){if(_b_.isinstance(other,[set,frozenset])){return set.__lt__(other,self)} 8794 return _b_.NotImplemented} 8795 set.__hash__=_b_.None 8796 set.__init__=function(self,iterable,second){if(second===undefined){if(Array.isArray(iterable)){for(var i=0,len=iterable.length;i < len;i++){$add(self,iterable[i])} 8797 return $N}} 8798 var $=$B.args("__init__",2,{self:null,iterable:null},["self","iterable"],arguments,{iterable:[]},null,null),self=$.self,iterable=$.iterable 8799 if(_b_.isinstance(iterable,[set,frozenset])){self.$items=iterable.$items.slice() 8800 self.$hashes={} 8801 for(var key in iterable.$hashes){self.$hashes[key]=iterable.$hashes[key]} 8802 return $N} 8803 var it=$B.$iter(iterable) 8804 while(1){try{var item=_b_.next(it) 8805 $add(self,item)}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){break} 8806 throw err}} 8807 return $N} 8808 var set_iterator=$B.make_iterator_class("set iterator") 8809 set.__iter__=function(self){self.$items.sort() 8810 return set_iterator.$factory(self.$items)} 8811 set.__le__=function(self,other){ 8812 if(_b_.isinstance(other,[set,frozenset])){var cfunc=_b_.getattr(other,"__contains__") 8813 for(var i=0,len=self.$items.length;i < len;i++){if(! cfunc(self.$items[i])){return false}} 8814 return true}else{return _b_.NotImplemented}} 8815 set.__len__=function(self){return self.$items.length} 8816 set.__lt__=function(self,other){if(_b_.isinstance(other,[set,frozenset])){return set.__le__(self,other)&& 8817 set.__len__(self)< _b_.getattr(other,"__len__")()}else{return _b_.NotImplemented}} 8818 set.__mro__=[_b_.object] 8819 set.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory("set.__new__(): not enough arguments")} 8820 return{ 8821 __class__:cls,$simple:true,$items:[],$numbers:[], 8822 $hashes:{}}} 8823 set.__or__=function(self,other,accept_iter){ 8824 var res=clone(self),func=_b_.getattr($B.$iter(other),"__next__") 8825 while(1){try{set.add(res,func())} 8826 catch(err){if(_b_.isinstance(err,_b_.StopIteration)){break} 8827 throw err}} 8828 res.__class__=self.__class__ 8829 return res} 8830 set.__rand__=function(self,other){ 8831 return set.__and__(self,other)} 8832 set.__reduce__=function(self){return _b_.tuple.$factory([self.__class__,_b_.tuple.$factory([self.$items]),$N])} 8833 set.__reduce_ex__=function(self,protocol){return set.__reduce__(self)} 8834 set.__rsub__=function(self,other){ 8835 return set.__sub__(self,other)} 8836 set.__rxor__=function(self,other){ 8837 return set.__xor__(self,other)} 8838 set.__str__=set.__repr__=function(self){var klass_name=$B.class_name(self) 8839 if(self.$items.length===0){return klass_name+"()"} 8840 var head=klass_name+"({",tail="})" 8841 if(head=="set({"){head="{";tail="}"} 8842 var res=[] 8843 if($B.repr.enter(self)){return klass_name+"(...)"} 8844 self.$items.sort() 8845 for(var i=0,len=self.$items.length;i < len;i++){var r=_b_.repr(self.$items[i]) 8846 if(r===self ||r===self.$items[i]){res.push("{...}")} 8847 else{res.push(r)}} 8848 res=res.join(", ") 8849 $B.repr.leave(self) 8850 return head+res+tail} 8851 set.__sub__=function(self,other,accept_iter){ 8852 try{$test(accept_iter,other,"-")} 8853 catch(err){return _b_.NotImplemented} 8854 var res=create_type(self),cfunc=_b_.getattr(other,"__contains__"),items=[] 8855 for(var i=0,len=self.$items.length;i < len;i++){if(! cfunc(self.$items[i])){items.push(self.$items[i])}} 8856 set.__init__.call(null,res,items) 8857 return res} 8858 set.__xor__=function(self,other,accept_iter){ 8859 try{$test(accept_iter,other,"^")} 8860 catch(err){return _b_.NotImplemented} 8861 var res=create_type(self),cfunc=_b_.getattr(other,"__contains__") 8862 for(var i=0,len=self.$items.length;i < len;i++){if(! cfunc(self.$items[i])){set.add(res,self.$items[i])}} 8863 for(var i=0,len=other.$items.length;i < len;i++){if(! set.__contains__(self,other.$items[i])){set.add(res,other.$items[i])}} 8864 return res} 8865 function $test(accept_iter,other,op){if(accept_iter===undefined && 8866 ! _b_.isinstance(other,[set,frozenset])){throw _b_.TypeError.$factory("unsupported operand type(s) for "+op+ 8867 ": 'set' and '"+$B.class_name(other)+"'")}} 8868 $B.make_rmethods(set) 8869 function $add(self,item){var $simple=false 8870 if(typeof item==="string" ||typeof item==="number" || 8871 item instanceof Number){$simple=true} 8872 if($simple){var ix=self.$items.indexOf(item) 8873 if(ix==-1){if(item instanceof Number && 8874 self.$numbers.indexOf(item.valueOf())>-1){}else if(typeof item=="number" && 8875 self.$numbers.indexOf(item)>-1){}else{self.$items.push(item) 8876 var value=item.valueOf() 8877 if(typeof value=="number"){self.$numbers.push(value)}}}else{ 8878 if(item !==self.$items[ix]){self.$items.push(item)}}}else{ 8879 var hashvalue=_b_.hash(item) 8880 var items=self.$hashes[hashvalue] 8881 if(items===undefined){self.$hashes[hashvalue]=[item] 8882 self.$items.push(item)}else{var items=self.$hashes[hashvalue],cfunc=function(other){return $B.rich_comp("__eq__",item,other)} 8883 for(var i=0,len=items.length;i < len;i++){if(cfunc(items[i])){ 8884 return $N}} 8885 self.$hashes[hashvalue].push(item) 8886 self.$items.push(item)}} 8887 return $N} 8888 set.add=function(){var $=$B.args("add",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item 8889 return $add(self,item)} 8890 set.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null) 8891 $.self.$items=[] 8892 $.self.$hashes={} 8893 return $N} 8894 set.copy=function(){var $=$B.args("copy",1,{self:null},["self"],arguments,{},null,null) 8895 if(_b_.isinstance($.self,frozenset)){return $.self} 8896 var res=set.$factory() 8897 $.self.$items.forEach(function(item){res.$items.push(item)}) 8898 $.self.$numbers.forEach(function(item){res.$numbers.push(item)}) 8899 for(key in self.$hashes){res.$hashes[key]=self.$hashes[key]} 8900 return res} 8901 set.difference_update=function(self){var $=$B.args("difference_update",1,{self:null},["self"],arguments,{},"args",null) 8902 for(var i=0;i < $.args.length;i++){var s=set.$factory($.args[i]),_next=_b_.getattr($B.$iter(s),"__next__"),item 8903 while(true){try{item=_next() 8904 var _type=typeof item 8905 if(_type=="string" ||_type=="number"){var _index=self.$items.indexOf(item) 8906 if(_index >-1){self.$items.splice(_index,1)}}else{for(var j=0;j < self.$items.length;j++){if($B.rich_comp("__eq__",self.$items[j],item)){self.$items.splice(j,1) 8907 var hash=_b_.hash(item) 8908 if(self.$hashes[hash]){for(var k=0;k < self.$hashes[hash].length;k++){if($B.rich_comp("__eq__",self.$hashes[hash][k],item)){self.$hashes[hash].splice(k,1) 8909 break}}}}}}}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){break} 8910 throw err}}} 8911 return $N} 8912 set.discard=function(){var $=$B.args("discard",2,{self:null,item:null},["self","item"],arguments,{},null,null) 8913 try{set.remove($.self,$.item)} 8914 catch(err){if(!_b_.isinstance(err,[_b_.KeyError,_b_.LookupError])){throw err}} 8915 return $N} 8916 set.intersection_update=function(){ 8917 var $=$B.args("intersection_update",1,{self:null},["self"],arguments,{},"args",null),self=$.self 8918 for(var i=0;i < $.args.length;i++){var remove=[],s=set.$factory($.args[i]) 8919 for(var j=0;j < self.$items.length;j++){var _item=self.$items[j],_type=typeof _item 8920 if(_type=="string" ||_type=="number"){if(s.$items.indexOf(_item)==-1){remove.push(j)}}else{var found=false,hash=_b_.hash(_item) 8921 if(s.$hashes[hash]){var hashes=s.$hashes[hash] 8922 for(var k=0;! found && k < hashes.length;k++){if($B.rich_comp("__eq__",hashes[k],_item)){found=true}} 8923 if(! found){remove.push(j) 8924 hashes=self.$hashes[hash] 8925 for(var k=0;! found && k < hashes.length;k++){if($B.rich_comp("__eq__",hashes[k],_item)){self.$hashes.splice(k,1)}}}}}} 8926 remove.sort(function(x,y){return x-y}).reverse() 8927 for(var j=0;j < remove.length;j++){self.$items.splice(remove[j],1)}} 8928 return $N} 8929 set.isdisjoint=function(){var $=$B.args("is_disjoint",2,{self:null,other:null},["self","other"],arguments,{},null,null) 8930 for(var i=0,len=$.self.$items.length;i < len;i++){if(_b_.getattr($.other,"__contains__")($.self.$items[i])){return false}} 8931 return true} 8932 set.pop=function(self){if(self.$items.length===0){throw _b_.KeyError.$factory('pop from an empty set')} 8933 var item=self.$items.pop() 8934 if(typeof item !="string" && typeof item !="number"){ 8935 var hash=_b_.hash(item),items=self.$hashes[hash] 8936 for(var k=0;k < items.length;k++){if($B.rich_comp("__eq__",items[k],item)){self.$hashes[hash].splice(k,1) 8937 break}}} 8938 return item} 8939 set.remove=function(self,item){ 8940 var $=$B.args("remove",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item 8941 if(! _b_.isinstance(item,set)){_b_.hash(item)} 8942 if(typeof item=="string" ||typeof item=="number"){var _i=self.$items.indexOf(item) 8943 if(_i==-1){throw _b_.KeyError.$factory(item)} 8944 self.$items.splice(_i,1) 8945 if(typeof item=="number"){self.$numbers.splice(self.$numbers.indexOf(item),1)} 8946 return $N} 8947 var hash=_b_.hash(item) 8948 if(self.$hashes[hash]){ 8949 for(var i=0,len=self.$items.length;i < len;i++){if($B.rich_comp("__eq__",self.$items[i],item)){self.$items.splice(i,1) 8950 if(item instanceof Number){self.$numbers.splice(self.$numbers.indexOf(item.valueOf()),1)} 8951 break}} 8952 for(var i=0,len=self.$hashes[hash].length;i < len;i++){if($B.rich_comp("__eq__",self.$hashes[hash][i],item)){self.$hashes[hash].splice(i,1) 8953 break}} 8954 return $N} 8955 throw _b_.KeyError.$factory(item)} 8956 set.symmetric_difference_update=function(self,s){ 8957 var $=$B.args("symmetric_difference_update",2,{self:null,s:null},["self","s"],arguments,{},null,null),self=$.self,s=$.s 8958 var _next=_b_.getattr($B.$iter(s),"__next__"),item,remove=[],add=[] 8959 while(true){try{item=_next() 8960 var _type=typeof item 8961 if(_type=="string" ||_type=="number"){var _index=self.$items.indexOf(item) 8962 if(_index >-1){remove.push(_index)}else{add.push(item)}}else{var found=false 8963 for(var j=0;! found && j < self.$items.length;j++){if($B.rich_comp("__eq__",self.$items[j],item)){remove.push(j) 8964 found=true}} 8965 if(! found){add.push(item)}}}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){break} 8966 throw err}} 8967 remove.sort(function(x,y){return x-y}).reverse() 8968 for(var i=0;i < remove.length;i++){if(remove[i]!=remove[i-1]){self.$items.splice(remove[i],1)}} 8969 for(var i=0;i < add.length;i++){set.add(self,add[i])} 8970 return $N} 8971 set.update=function(self){ 8972 var $=$B.args("update",1,{self:null},["self"],arguments,{},"args",null) 8973 for(var i=0;i < $.args.length;i++){var other=set.$factory($.args[i]) 8974 for(var j=0,_len=other.$items.length;j < _len;j++){$add(self,other.$items[j])}} 8975 return $N} 8976 set.difference=function(){var $=$B.args("difference",1,{self:null},["self"],arguments,{},"args",null) 8977 if($.args.length==0){return set.copy($.self)} 8978 var res=clone($.self) 8979 for(var i=0;i < $.args.length;i++){res=set.__sub__(res,set.$factory($.args[i]),true)} 8980 return res} 8981 var fc=set.difference+"" 8982 eval("set.intersection = "+ 8983 fc.replace(/difference/g,"intersection").replace("__sub__","__and__")) 8984 eval("set.symmetric_difference = "+ 8985 fc.replace(/difference/g,"symmetric_difference").replace("__sub__","__xor__")) 8986 eval("set.union = "+ 8987 fc.replace(/difference/g,"union").replace("__sub__","__or__")) 8988 set.issubset=function(){var $=$B.args("issubset",2,{self:null,other:null},["self","other"],arguments,{},"args",null),func=_b_.getattr($.other,"__contains__") 8989 for(var i=0,len=$.self.$items.length;i < len;i++){if(! func($.self.$items[i])){return false}} 8990 return true} 8991 set.issuperset=function(){var $=$B.args("issuperset",2,{self:null,other:null},["self","other"],arguments,{},"args",null) 8992 var func=_b_.getattr($.self,"__contains__"),it=$B.$iter($.other) 8993 while(true){try{var item=_b_.next(it) 8994 if(! func(item)){return false}}catch(err){if(_b_.isinstance(err,_b_.StopIteration)){return true} 8995 throw err}} 8996 return true} 8997 function $accept_only_set(f,op){return function(self,other,accept_iter){$test(accept_iter,other,op) 8998 f(self,other) 8999 return self}} 9000 set.__iand__=$accept_only_set(set.intersection_update,"&=") 9001 set.__isub__=$accept_only_set(set.difference_update,"-=") 9002 set.__ixor__=$accept_only_set(set.symmetric_difference_update,"^=") 9003 set.__ior__=$accept_only_set(set.update,"|=") 9004 set.$factory=function(){ 9005 var res={__class__:set,$simple:true,$items:[],$numbers:[],$hashes:{}} 9006 var args=[res].concat(Array.prototype.slice.call(arguments)) 9007 set.__init__.apply(null,args) 9008 return res} 9009 $B.set_func_names(set,"builtins") 9010 set.__class_getitem__=_b_.classmethod.$factory(set.__class_getitem__) 9011 var frozenset={__class__:_b_.type,__mro__:[object],$infos:{__module__:"builtins",__name__:"frozenset"},$is_class:true,$native:true} 9012 for(var attr in set){switch(attr){case "add": 9013 case "clear": 9014 case "discard": 9015 case "pop": 9016 case "remove": 9017 case "update": 9018 break 9019 default: 9020 if(frozenset[attr]==undefined){if(typeof set[attr]=="function"){frozenset[attr]=(function(x){return function(){return set[x].apply(null,arguments)}})(attr)}else{frozenset[attr]=set[attr]}}}} 9021 frozenset.__hash__=function(self){if(self===undefined){return frozenset.__hashvalue__ ||$B.$py_next_hash--} 9022 if(self.__hashvalue__ !==undefined){return self.__hashvalue__} 9023 var _hash=1927868237 9024 _hash*=self.$items.length 9025 for(var i=0,len=self.$items.length;i < len;i++){var _h=_b_.hash(self.$items[i]) 9026 _hash ^=((_h ^ 89869747)^(_h << 16))*3644798167} 9027 _hash=_hash*69069+907133923 9028 if(_hash==-1){_hash=590923713} 9029 return self.__hashvalue__=_hash} 9030 frozenset.__init__=function(){ 9031 return $N} 9032 frozenset.__new__=function(cls){if(cls===undefined){throw _b_.TypeError.$factory( 9033 "frozenset.__new__(): not enough arguments")} 9034 return{ 9035 __class__:cls,$simple:true,$items:[],$numbers:[],$hashes:{}}} 9036 var singleton_id=Math.floor(Math.random()*Math.pow(2,40)) 9037 function empty_frozenset(){var res=frozenset.__new__(frozenset) 9038 res.$id=singleton_id 9039 return res} 9040 frozenset.$factory=function(){var $=$B.args("frozenset",1,{iterable:null},["iterable"],arguments,{iterable:null},null,null) 9041 if($.iterable===null){return empty_frozenset()} 9042 else if($.iterable.__class__==frozenset){return $.iterable} 9043 var res=set.$factory($.iterable) 9044 if(res.$items.length==0){return empty_frozenset()} 9045 res.__class__=frozenset 9046 return res} 9047 $B.set_func_names(frozenset,"builtins") 9048 _b_.set=set 9049 _b_.frozenset=frozenset})(__BRYTHON__) 9050 ; 9051 ;(function($B){var _b_=$B.builtins 9052 var object=_b_.object 9053 var _window=self; 9054 function to_simple(value){switch(typeof value){case 'string': 9055 case 'number': 9056 return value 9057 case 'boolean': 9058 return value ? "true" :"false" 9059 case 'object': 9060 if(value===_b_.None){return 'null'}else if(value instanceof Number){return value.valueOf()} 9061 default: 9062 console.log("erreur",value) 9063 throw _b_.TypeError.$factory("keys must be str, int, "+ 9064 "float, bool or None, not "+$B.class_name(value))}} 9065 $B.pyobj2structuredclone=function(obj,strict){ 9066 strict=strict===undefined ? true :strict 9067 if(typeof obj=="boolean" ||typeof obj=="number" || 9068 typeof obj=="string"){return obj}else if(obj instanceof Number){return obj.valueOf()}else if(obj===_b_.None){return null }else if(Array.isArray(obj)||obj.__class__===_b_.list || 9069 obj.__class__===_b_.tuple){var res=[] 9070 for(var i=0,len=obj.length;i < len;i++){res.push($B.pyobj2structuredclone(obj[i]))} 9071 return res}else if(_b_.isinstance(obj,_b_.dict)){if(strict){if(Object.keys(obj.$numeric_dict).length > 0 || 9072 Object.keys(obj.$object_dict).length > 0){throw _b_.TypeError.$factory("a dictionary with non-string "+ 9073 "keys does not support structured clone")}} 9074 var items=$B.dict_to_list(obj),res={} 9075 for(var i=0,len=items.length;i < len;i++){res[to_simple(items[i][0])]=$B.pyobj2structuredclone(items[i][1])} 9076 return res}else{return obj}} 9077 $B.structuredclone2pyobj=function(obj){if(obj===null){return _b_.None}else if(obj===undefined){return $B.Undefined}else if(typeof obj=="boolean" ||typeof obj=="number" || 9078 typeof obj=="string"){return obj}else if(obj instanceof Number){return obj.valueOf()}else if(Array.isArray(obj)||obj.__class__===_b_.list || 9079 obj.__class__===_b_.tuple){var res=_b_.list.$factory() 9080 for(var i=0,len=obj.length;i < len;i++){res.push($B.structuredclone2pyobj(obj[i]))} 9081 return res}else if(typeof obj=="object"){var res=$B.empty_dict() 9082 for(var key in obj){_b_.dict.$setitem(res,key,$B.structuredclone2pyobj(obj[key]))} 9083 return res}else{console.log(obj,Array.isArray(obj),obj.__class__,_b_.list,obj.__class__===_b_.list) 9084 throw _b_.TypeError.$factory(_b_.str.$factory(obj)+ 9085 " does not support the structured clone algorithm")}} 9086 var JSConstructor={__class__:_b_.type,__mro__:[object],$infos:{__module__:"<javascript>",__name__:'JSConstructor'},$is_class:true} 9087 JSConstructor.__call__=function(self){ 9088 return function(){var args=[null] 9089 for(var i=0,len=arguments.length;i < len;i++){args.push(pyobj2jsobj(arguments[i]))} 9090 var factory=self.func.bind.apply(self.func,args) 9091 var res=new factory() 9092 return $B.$JS2Py(res)}} 9093 JSConstructor.__getattribute__=function(self,attr){ 9094 if(attr=="__call__"){return function(){var args=[null] 9095 for(var i=0,len=arguments.length;i < len;i++){args.push(pyobj2jsobj(arguments[i]))} 9096 var factory=self.func.bind.apply(self.func,args) 9097 var res=new factory() 9098 return $B.$JS2Py(res)}} 9099 return JSObject.__getattribute__(self,attr)} 9100 JSConstructor.$factory=function(obj){return{ 9101 __class__:JSConstructor,js:obj,func:obj.js_func}} 9102 var jsobj2pyobj=$B.jsobj2pyobj=function(jsobj){switch(jsobj){case true: 9103 case false: 9104 return jsobj} 9105 if(jsobj===undefined){return $B.Undefined} 9106 else if(jsobj===null){return _b_.None} 9107 if(Array.isArray(jsobj)){return _b_.list.$factory(jsobj.map(jsobj2pyobj))} 9108 if(typeof jsobj==='number'){if(jsobj.toString().indexOf('.')==-1){return _b_.int.$factory(jsobj)} 9109 return _b_.float.$factory(jsobj)} 9110 if(jsobj.$nat==='kw'){return jsobj} 9111 if($B.$isNode(jsobj)){return $B.DOMNode.$factory(jsobj)} 9112 return $B.JSObj.$factory(jsobj)} 9113 var pyobj2jsobj=$B.pyobj2jsobj=function(pyobj){ 9114 if(pyobj===true ||pyobj===false){return pyobj} 9115 if(pyobj===_b_.None){return null} 9116 if(pyobj===$B.Undefined){return undefined} 9117 var klass=$B.get_class(pyobj) 9118 if(klass===undefined){ 9119 return pyobj;} 9120 if(klass===JSConstructor){ 9121 if(pyobj.js_func !==undefined){return pyobj.js_func} 9122 return pyobj.js}else if(klass===$B.DOMNode || 9123 klass.__mro__.indexOf($B.DOMNode)>-1){ 9124 return pyobj}else if([_b_.list,_b_.tuple].indexOf(klass)>-1){ 9125 var res=[] 9126 pyobj.forEach(function(item){res.push(pyobj2jsobj(item))}) 9127 return res}else if(klass===_b_.dict ||_b_.issubclass(klass,_b_.dict)){ 9128 var jsobj={} 9129 var items=_b_.list.$factory(_b_.dict.items(pyobj)) 9130 items.forEach(function(item){if(typeof item[1]=='function'){ 9131 item[1].bind(jsobj)} 9132 jsobj[item[0]]=pyobj2jsobj(item[1])}) 9133 return jsobj}else if(klass===_b_.float){ 9134 return pyobj.valueOf()}else if(klass===$B.Function ||klass===$B.method){ 9135 return function(){try{var args=[] 9136 for(var i=0;i < arguments.length;i++){if(arguments[i]===undefined){args.push(_b_.None)} 9137 else{args.push(jsobj2pyobj(arguments[i]))}} 9138 return pyobj2jsobj(pyobj.apply(this,args))}catch(err){console.log(err) 9139 console.log($B.$getattr(err,'info')) 9140 console.log($B.class_name(err)+':',err.args.length > 0 ? err.args[0]:'' ) 9141 throw err}}}else{ 9142 return pyobj}} 9143 $B.JSConstructor=JSConstructor 9144 function pyargs2jsargs(pyargs){var args=[] 9145 for(var i=0,len=pyargs.length;i < len;i++){var arg=pyargs[i] 9146 if(arg !==undefined && arg !==null && 9147 arg.$nat !==undefined){var kw=arg.kw 9148 if(Array.isArray(kw)){kw=$B.extend(js_attr.name,...kw)} 9149 if(Object.keys(kw).length > 0){ 9150 throw _b_.TypeError.$factory( 9151 "A Javascript function can't take "+ 9152 "keyword arguments")}}else{args.push($B.pyobj2jsobj(arg))}} 9153 return args} 9154 $B.JSObj=$B.make_class("JSObj",function(jsobj){if(Array.isArray(jsobj)){}else if(typeof jsobj=="function"){jsobj.$is_js_func=true}else if(typeof jsobj=="number" && ! Number.isInteger(jsobj)){return new Number(jsobj)} 9155 return jsobj} 9156 ) 9157 $B.JSObj.__sub__=function(self,other){ 9158 if(typeof self=="bigint" && typeof other=="bigint"){return self-other} 9159 throw _b_.TypeError.$factory("unsupported operand type(s) for - : '"+ 9160 $B.class_name(self)+"' and '"+$B.class_name(other)+"'")} 9161 var ops={'+':'__add__','*':'__mul__','**':'__pow__','%' :'__mod__'} 9162 for(var op in ops){eval('$B.JSObj.'+ops[op]+' = '+ 9163 ($B.JSObj.__sub__+'').replace(/-/g,op))} 9164 $B.JSObj.__eq__=function(self,other){switch(typeof self){case "object": 9165 if(Object.keys(self).length !==Object.keys(other).length){return false} 9166 for(var key in self){if(! $B.JSObj.__eq__(self[key],other[key])){return false}} 9167 default: 9168 return self===other}} 9169 $B.JSObj.__ne__=function(self,other){return ! $B.JSObj.__eq__(self,other)} 9170 $B.JSObj.__getattribute__=function(self,attr){var test=false 9171 if(test){console.log("__ga__",self,attr)} 9172 if(attr=="$$new" && typeof self=="function"){ 9173 if(self.$js_func){return function(){var args=pyargs2jsargs(arguments) 9174 return $B.JSObj.$factory(new self.$js_func(...args))}}else{return function(){var args=pyargs2jsargs(arguments) 9175 return $B.JSObj.$factory(new self(...args))}}} 9176 if(typeof attr=="string"){attr=$B.from_alias(attr)} 9177 var js_attr=self[attr] 9178 if(js_attr==undefined && typeof self=="function" && self.$js_func){js_attr=self.$js_func[attr]} 9179 if(js_attr===undefined){if(typeof self.getNamedItem=='function'){var res=self.getNamedItem(attr) 9180 if(res !==undefined){return $B.JSObj.$factory(res)}} 9181 var klass=$B.get_class(self) 9182 if(klass && klass[attr]){var class_attr=klass[attr] 9183 if(typeof class_attr=="function"){return function(){var args=[self] 9184 for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} 9185 return $B.JSObj.$factory(class_attr.apply(null,args))}}else{return class_attr}} 9186 if(attr=="bind" && typeof self.addEventListener=="function"){return function(event,callback){return self.addEventListener(event,callback)}} 9187 throw _b_.AttributeError.$factory(attr)} 9188 if(typeof js_attr==='function'){var res=function(){var args=pyargs2jsargs(arguments),target=self.$js_func ||self 9189 try{var result=js_attr.apply(target,args)}catch(err){console.log("error",err) 9190 console.log("attribute",attr,"of self",self,js_attr,args,arguments) 9191 throw err} 9192 if(result===undefined){return $B.Undefined}else if(result===null){return _b_.None} 9193 return $B.JSObj.$factory(result)} 9194 res.prototype=js_attr.prototype 9195 res.$js_func=js_attr 9196 res.__mro__=[_b_.object] 9197 res.$infos={__name__:js_attr.name,__qualname__:js_attr.name} 9198 if($B.frames_stack.length > 0){res.$infos.__module__=$B.last($B.frames_stack)[3].__name__} 9199 return $B.JSObj.$factory(res)}else{return $B.JSObj.$factory(js_attr)}} 9200 $B.JSObj.__setattr__=function(self,attr,value){if(typeof attr=="string"){attr=$B.from_alias(attr)} 9201 self[attr]=$B.pyobj2structuredclone(value) 9202 return _b_.None} 9203 $B.JSObj.__getitem__=function(self,key){if(typeof key=="string"){return $B.JSObj.__getattribute__(self,key)}else if(typeof key=="number"){if(self[key]!==undefined){return $B.JSObj.$factory(self[key])} 9204 if(typeof self.length=='number'){if((typeof key=="number" ||typeof key=="boolean")&& 9205 typeof self.item=='function'){var rank=_b_.int.$factory(key) 9206 if(rank < 0){rank+=self.length} 9207 var res=self.item(rank) 9208 if(res===null){throw _b_.IndexError.$factory(rank)} 9209 return $B.JSObj.$factory(res)}}} 9210 throw _b_.KeyError.$factory(rank)} 9211 $B.JSObj.__setitem__=$B.JSObj.__setattr__ 9212 var JSObj_iterator=$B.make_iterator_class('JS object iterator') 9213 $B.JSObj.__iter__=function(self){var items=[] 9214 if(_window.Symbol && self[Symbol.iterator]!==undefined){ 9215 var items=[] 9216 if(self.next !==undefined){while(true){var nxt=self.next() 9217 if(nxt.done){break} 9218 items.push($B.JSObj.$factory(nxt.value))}}else if(self.length !==undefined && self.item !==undefined){for(var i=0;i < self.length;i++){items.push($B.JSObj.$factory(self.item(i)))}} 9219 return JSObj_iterator.$factory(items)}else if(self.length !==undefined && self.item !==undefined){ 9220 for(var i=0;i < self.length;i++){items.push($B.JSObj.$factory(self.js.item(i)))} 9221 return JSObj_iterator.$factory(items)} 9222 var _dict=$B.JSObj.to_dict(self) 9223 return _b_.dict.__iter__(_dict)} 9224 $B.JSObj.__len__=function(self){if(typeof self.length=='number'){return self.length} 9225 throw _b_.AttributeError.$factory(self+' has no attribute __len__')} 9226 $B.JSObj.__repr__=$B.JSObj.__str__=function(self){return '<Javascript '+self.constructor.name+' object: '+ 9227 self.toString()+'>'} 9228 $B.JSObj.bind=function(self,evt,func){ 9229 var js_func=function(ev){return func(jsobj2pyobj(ev))} 9230 self.addEventListener(evt,js_func) 9231 return _b_.None} 9232 $B.JSObj.to_dict=function(self){ 9233 return $B.structuredclone2pyobj(self)} 9234 $B.set_func_names($B.JSObj,"builtins") 9235 $B.JSMeta=$B.make_class("JSMeta") 9236 $B.JSMeta.__call__=function(cls){ 9237 var args=[] 9238 for(var i=1,len=arguments.length;i < len;i++){args.push(arguments[i])} 9239 return new cls.__mro__[0].$js_func(...args)} 9240 $B.JSMeta.__mro__=[_b_.type,_b_.object] 9241 $B.JSMeta.__getattribute__=function(cls,attr){if(cls[attr]!==undefined){return cls[attr]}else if($B.JSMeta[attr]!==undefined){return $B.JSMeta[attr]}else{ 9242 return _b_.type.__getattribute__(cls,attr)}} 9243 $B.JSMeta.__init_subclass__=function(){} 9244 $B.set_func_names($B.JSMeta,"builtins")})(__BRYTHON__) 9245 ; 9246 __BRYTHON__.stdlib = {} 9247 9248 ;(function($B){var _b_=$B.builtins,_window=self 9249 var module=$B.module={__class__ :_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"module"},$is_class:true} 9250 module.__init__=function(){} 9251 module.__new__=function(cls,name,doc,$package){return{ 9252 __class__:cls,__name__:name,__doc__:doc ||_b_.None,__package__:$package ||_b_.None}} 9253 module.__repr__=module.__str__=function(self){var res="<module "+self.__name__ 9254 if(self.__file__===undefined){res+=" (built-in)"} 9255 return res+">"} 9256 module.__setattr__=function(self,attr,value){if(self.__name__=="__builtins__"){ 9257 $B.builtins[attr]=value}else{self[attr]=value}} 9258 module.$factory=function(name,doc,$package){return{ 9259 __class__:module,__name__:name,__doc__:doc ||_b_.None,__package__:$package ||_b_.None}} 9260 $B.set_func_names(module,"builtins") 9261 function parent_package(mod_name){var parts=mod_name.split(".") 9262 parts.pop() 9263 return parts.join(".")} 9264 function $download_module(mod,url,$package){var xhr=new XMLHttpRequest(),fake_qs="?v="+(new Date().getTime()),res=null,mod_name=mod.__name__ 9265 var timer=_window.setTimeout(function(){xhr.abort()},5000) 9266 if($B.$options.cache){xhr.open("GET",url,false)}else{xhr.open("GET",url+fake_qs,false)} 9267 xhr.send() 9268 if($B.$CORS){if(xhr.status==200 ||xhr.status==0){res=xhr.responseText}else{res=_b_.ModuleNotFoundError.$factory("No module named '"+ 9269 mod_name+"'")}}else{if(xhr.readyState==4){if(xhr.status==200){res=xhr.responseText 9270 mod.$last_modified= 9271 xhr.getResponseHeader("Last-Modified")}else{ 9272 console.info("Error "+xhr.status+ 9273 " means that Python module "+mod_name+ 9274 " was not found at url "+url) 9275 res=_b_.ModuleNotFoundError.$factory("No module named '"+ 9276 mod_name+"'")}}} 9277 _window.clearTimeout(timer) 9278 if(res==null){throw _b_.ModuleNotFoundError.$factory("No module named '"+ 9279 mod_name+"' (res is null)")} 9280 if(res.constructor===Error){throw res} 9281 return res} 9282 $B.$download_module=$download_module 9283 function import_js(mod,path){try{var module_contents=$download_module(mod,path,undefined)}catch(err){return null} 9284 run_js(module_contents,path,mod) 9285 return true} 9286 function run_js(module_contents,path,_module){ 9287 try{var $module=new Function(module_contents+";\nreturn $module")() 9288 if($B.$options.store){_module.$js=module_contents}}catch(err){console.log(err) 9289 console.log(path,_module) 9290 throw err} 9291 try{$module} 9292 catch(err){console.log("no $module") 9293 throw _b_.ImportError.$factory("name '$module' not defined in module")} 9294 $module.__name__=_module.__name__ 9295 for(var attr in $module){if(typeof $module[attr]=="function"){$module[attr].$infos={__module__:_module.__name__,__name__:attr,__qualname__:attr}}} 9296 if(_module !==undefined){ 9297 for(var attr in $module){_module[attr]=$module[attr]} 9298 $module=_module 9299 $module.__class__=module }else{ 9300 $module.__class__=module 9301 $module.__name__=_module.__name__ 9302 $module.__repr__=$module.__str__=function(){if($B.builtin_module_names.indexOf(_module.name)>-1){return "<module '"+_module.__name__+"' (built-in)>"} 9303 return "<module '"+_module.__name__+"' from "+path+" >"} 9304 if(_module.name !="builtins"){ 9305 $module.__file__=path}} 9306 $B.imported[_module.__name__]=$module 9307 return true} 9308 function show_ns(){var kk=Object.keys(_window) 9309 for(var i=0,len=kk.length;i < len;i++){console.log(kk[i]) 9310 if(kk[i].charAt(0)=="$"){console.log(eval(kk[i]))}} 9311 console.log("---")} 9312 function import_py(mod,path,$package){ 9313 var mod_name=mod.__name__,module_contents=$download_module(mod,path,$package) 9314 mod.$src=module_contents 9315 $B.imported[mod_name].$is_package=mod.$is_package 9316 $B.imported[mod_name].$last_modified=mod.$last_modified 9317 if(path.substr(path.length-12)=="/__init__.py"){$B.imported[mod_name].__package__=mod_name 9318 $B.imported[mod_name].__path__=path 9319 $B.imported[mod_name].$is_package=mod.$is_package=true}else if($package){$B.imported[mod_name].__package__=$package}else{var mod_elts=mod_name.split(".") 9320 mod_elts.pop() 9321 $B.imported[mod_name].__package__=mod_elts.join(".")} 9322 $B.imported[mod_name].__file__=path 9323 return run_py(module_contents,path,mod)} 9324 function run_py(module_contents,path,module,compiled){ 9325 $B.file_cache[path]=module_contents 9326 var root,js,mod_name=module.__name__ 9327 if(! compiled){var $Node=$B.$Node,$NodeJSCtx=$B.$NodeJSCtx 9328 $B.$py_module_path[module.__name__]=path 9329 var src={src:module_contents,has_annotations:false} 9330 root=$B.py2js(src,module,module.__name__,$B.builtins_scope) 9331 if(module.__package__ !==undefined){root.binding["__package__"]=true}} 9332 try{js=compiled ? module_contents :root.to_js() 9333 if($B.$options.debug==10){console.log("code for module "+module.__name__) 9334 console.log(js)} 9335 var src=js 9336 js="var $module = (function(){\n"+js+"return $locals_"+ 9337 module.__name__.replace(/\./g,"_")+"})(__BRYTHON__)\n"+ 9338 "return $module" 9339 var module_id="$locals_"+module.__name__.replace(/\./g,'_') 9340 var $module=(new Function(module_id,js))(module)}catch(err){console.log(err+" for module "+module.__name__) 9341 console.log("module",module) 9342 console.log(root) 9343 if($B.debug > 1){console.log(js)} 9344 for(var attr in err){console.log(attr,err[attr])} 9345 console.log(_b_.getattr(err,"info","[no info]")) 9346 console.log("message: "+err.$message) 9347 console.log("filename: "+err.fileName) 9348 console.log("linenum: "+err.lineNumber) 9349 if($B.debug > 0){console.log("line info "+$B.line_info)} 9350 throw err}finally{$B.clear_ns(module.__name__)} 9351 try{ 9352 var mod=eval("$module") 9353 for(var attr in mod){module[attr]=mod[attr]} 9354 module.__initializing__=false 9355 $B.imported[module.__name__]=module 9356 return{ 9357 content:src,name:mod_name,imports:Object.keys(root.imports).join(",")}}catch(err){console.log(""+err+" "+" for module "+module.__name__) 9358 for(var attr in err){console.log(attr+" "+err[attr])} 9359 if($B.debug > 0){console.log("line info "+__BRYTHON__.line_info)} 9360 throw err}} 9361 $B.run_py=run_py 9362 function new_spec(fields){ 9363 fields.__class__=module 9364 return fields} 9365 var finder_VFS={__class__:_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"VFSFinder"},create_module :function(cls,spec){ 9366 return _b_.None},exec_module :function(cls,modobj){var stored=modobj.__spec__.loader_state.stored,timestamp=modobj.__spec__.loader_state.timestamp 9367 delete modobj.__spec__["loader_state"] 9368 var ext=stored[0],module_contents=stored[1],imports=stored[2] 9369 modobj.$is_package=stored[3]||false 9370 var path="VFS."+modobj.__name__ 9371 path+=modobj.$is_package ? "/__init__.py" :ext 9372 modobj.__file__=path 9373 $B.file_cache[modobj.__file__]=$B.VFS[modobj.__name__][1] 9374 if(ext=='.js'){run_js(module_contents,modobj.__path__,modobj)}else if($B.precompiled.hasOwnProperty(modobj.__name__)){if($B.debug > 1){console.info("load",modobj.__name__,"from precompiled")} 9375 var parts=modobj.__name__.split(".") 9376 for(var i=0;i < parts.length;i++){var parent=parts.slice(0,i+1).join(".") 9377 if($B.imported.hasOwnProperty(parent)&& 9378 $B.imported[parent].__initialized__){continue} 9379 var mod_js=$B.precompiled[parent],is_package=modobj.$is_package 9380 if(Array.isArray(mod_js)){mod_js=mod_js[0]} 9381 var mod=$B.imported[parent]=module.$factory(parent,undefined,is_package) 9382 mod.__initialized__=true 9383 if(is_package){mod.__path__="<stdlib>" 9384 mod.__package__=parent}else{var elts=parent.split(".") 9385 elts.pop() 9386 mod.__package__=elts.join(".")} 9387 mod.__file__=path 9388 try{var parent_id=parent.replace(/\./g,"_") 9389 mod_js+="return $locals_"+parent_id 9390 var $module=new Function("$locals_"+parent_id,mod_js)( 9391 mod)}catch(err){if($B.debug > 1){console.log(err) 9392 for(var k in err){console.log(k,err[k])} 9393 console.log(Object.keys($B.imported)) 9394 if($B.debug > 2){console.log(modobj,"mod_js",mod_js)}} 9395 throw err} 9396 for(var attr in $module){mod[attr]=$module[attr]} 9397 $module.__file__=path 9398 if(i > 0){ 9399 $B.builtins.setattr( 9400 $B.imported[parts.slice(0,i).join(".")],parts[i],$module)}} 9401 return $module}else{var mod_name=modobj.__name__ 9402 if($B.debug > 1){console.log("run Python code from VFS",mod_name)} 9403 var record=run_py(module_contents,modobj.__path__,modobj) 9404 record.is_package=modobj.$is_package 9405 record.timestamp=$B.timestamp 9406 record.source_ts=timestamp 9407 $B.precompiled[mod_name]=record.is_package ?[record.content]: 9408 record.content 9409 var elts=mod_name.split(".") 9410 if(elts.length > 1){elts.pop()} 9411 if($B.$options.indexedDB && self.indexedDB && 9412 $B.idb_name){ 9413 var idb_cx=indexedDB.open($B.idb_name) 9414 idb_cx.onsuccess=function(evt){var db=evt.target.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),cursor=store.openCursor(),request=store.put(record) 9415 request.onsuccess=function(){if($B.debug > 1){console.info(modobj.__name__,"stored in db")}} 9416 request.onerror=function(){console.info("could not store "+modobj.__name__)}}}}},find_module:function(cls,name,path){return{ 9417 __class__:Loader,load_module:function(name,path){var spec=cls.find_spec(cls,name,path) 9418 var mod=module.$factory(name) 9419 $B.imported[name]=mod 9420 mod.__spec__=spec 9421 cls.exec_module(cls,mod)}}},find_spec :function(cls,fullname,path,prev_module){var stored,is_package,timestamp 9422 if(!$B.use_VFS){return _b_.None} 9423 stored=$B.VFS[fullname] 9424 if(stored===undefined){return _b_.None} 9425 is_package=stored[3]||false 9426 timestamp=stored.timestamp 9427 if(stored){var is_builtin=$B.builtin_module_names.indexOf(fullname)>-1 9428 return new_spec({name :fullname,loader:cls, 9429 origin :is_builtin? "built-in" :"brython_stdlib", 9430 submodule_search_locations:is_package?[]:_b_.None,loader_state:{stored:stored,timestamp:timestamp}, 9431 cached:_b_.None,parent:is_package? fullname :parent_package(fullname),has_location:_b_.False})}}} 9432 $B.set_func_names(finder_VFS,"<import>") 9433 for(var method in finder_VFS){if(typeof finder_VFS[method]=="function"){finder_VFS[method]=_b_.classmethod.$factory( 9434 finder_VFS[method])}} 9435 finder_VFS.$factory=function(){return{__class__:finder_VFS}} 9436 var finder_cpython={__class__:_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"CPythonFinder"},create_module :function(cls,spec){ 9437 return _b_.None},exec_module :function(cls,modobj){console.log("exec PYthon module",modobj) 9438 var loader_state=modobj.__spec__.loader_state 9439 var content=loader_state.content 9440 delete modobj.__spec__["loader_state"] 9441 modobj.$is_package=loader_state.is_package 9442 modobj.__file__=loader_state.__file__ 9443 $B.file_cache[modobj.__file__]=content 9444 var mod_name=modobj.__name__ 9445 if($B.debug > 1){console.log("run Python code from CPython",mod_name)} 9446 run_py(content,modobj.__path__,modobj)},find_module:function(cls,name,path){return{ 9447 __class__:Loader,load_module:function(name,path){var spec=cls.find_spec(cls,name,path) 9448 var mod=module.$factory(name) 9449 $B.imported[name]=mod 9450 mod.__spec__=spec 9451 cls.exec_module(cls,mod)}}},find_spec :function(cls,fullname,path,prev_module){console.log("finder cpython",fullname) 9452 var xhr=new XMLHttpRequest(),url="/cpython_import?module="+fullname,result 9453 xhr.open("GET",url,false) 9454 xhr.onreadystatechange=function(){if(this.readyState==4 && this.status==200){var data=JSON.parse(this.responseText) 9455 result=new_spec({name :fullname,loader:cls, 9456 origin :"CPython", 9457 submodule_search_locations:data.is_package?[]:_b_.None,loader_state:{content:data.content}, 9458 cached:_b_.None,parent:data.is_package? fullname :parent_package(fullname),has_location:_b_.False})}} 9459 xhr.send() 9460 return result}} 9461 $B.set_func_names(finder_cpython,"<import>") 9462 for(var method in finder_cpython){if(typeof finder_cpython[method]=="function"){finder_cpython[method]=_b_.classmethod.$factory( 9463 finder_cpython[method])}} 9464 finder_cpython.$factory=function(){return{__class__:finder_cpython}} 9465 var finder_stdlib_static={$factory :finder_stdlib_static,__class__ :_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"StdlibStatic"},create_module :function(cls,spec){ 9466 return _b_.None},exec_module :function(cls,module){var metadata=module.__spec__.loader_state 9467 module.$is_package=metadata.is_package 9468 if(metadata.ext=="py"){import_py(module,metadata.path,module.__package__)}else{import_js(module,metadata.path)} 9469 delete module.__spec__["loader_state"]},find_module:function(cls,name,path){var spec=cls.find_spec(cls,name,path) 9470 if(spec===_b_.None){return _b_.None} 9471 return{ 9472 __class__:Loader,load_module:function(name,path){var mod=module.$factory(name) 9473 $B.imported[name]=mod 9474 mod.__spec__=spec 9475 mod.__package__=spec.parent 9476 cls.exec_module(cls,mod)}}},find_spec:function(cls,fullname,path,prev_module){if($B.stdlib && $B.$options.static_stdlib_import){var address=$B.stdlib[fullname] 9477 if(address===undefined){var elts=fullname.split(".") 9478 if(elts.length > 1){elts.pop() 9479 var $package=$B.stdlib[elts.join(".")] 9480 if($package && $package[1]){address=["py"]}}} 9481 if(address !==undefined){var ext=address[0],is_pkg=address[1]!==undefined,path=$B.brython_path+ 9482 ((ext=="py")? "Lib/" :"libs/")+ 9483 fullname.replace(/\./g,"/"),metadata={ext:ext,is_package:is_pkg,path:path+(is_pkg? "/__init__.py" : 9484 ((ext=="py")? ".py" :".js")),address:address} 9485 var res=new_spec({name :fullname,loader:cls, 9486 origin :metadata.path,submodule_search_locations:is_pkg?[path]:_b_.None,loader_state:metadata, 9487 cached:_b_.None,parent:is_pkg ? fullname :parent_package(fullname),has_location:_b_.True}) 9488 return res}} 9489 return _b_.None}} 9490 $B.set_func_names(finder_stdlib_static,"<import>") 9491 for(var method in finder_stdlib_static){if(typeof finder_stdlib_static[method]=="function"){finder_stdlib_static[method]=_b_.classmethod.$factory( 9492 finder_stdlib_static[method])}} 9493 finder_stdlib_static.$factory=function(){return{__class__:finder_stdlib_static}} 9494 var finder_path={__class__:_b_.type,__mro__:[_b_.object],$infos:{__module__:"builtins",__name__:"ImporterPath"},create_module :function(cls,spec){ 9495 return _b_.None},exec_module :function(cls,_module){var _spec=$B.$getattr(_module,"__spec__"),code=_spec.loader_state.code; 9496 _module.$is_package=_spec.loader_state.is_package,delete _spec.loader_state["code"] 9497 var src_type=_spec.loader_state.type 9498 if(src_type=="py" ||src_type=="pyc.js"){run_py(code,_spec.origin,_module,src_type=="pyc.js")} 9499 else if(_spec.loader_state.type=="js"){run_js(code,_spec.origin,_module)}},find_module:function(cls,name,path){return finder_path.find_spec(cls,name,path)},find_spec :function(cls,fullname,path,prev_module){var current_module=$B.last($B.frames_stack)[2] 9500 if($B.VFS && $B.VFS[current_module]){ 9501 return _b_.None} 9502 if($B.is_none(path)){ 9503 path=$B.path} 9504 for(var i=0,li=path.length;i < li;++i){var path_entry=path[i] 9505 if(path_entry[path_entry.length-1]!="/"){path_entry+="/"} 9506 var finder=$B.path_importer_cache[path_entry] 9507 if(finder===undefined){var finder_notfound=true 9508 for(var j=0,lj=$B.path_hooks.length; 9509 j < lj && finder_notfound;++j){var hook=$B.path_hooks[j].$factory 9510 try{finder=(typeof hook=="function" ? hook : 9511 $B.$getattr(hook,"__call__"))(path_entry) 9512 finder_notfound=false}catch(e){if(e.__class__ !==_b_.ImportError){throw e}}} 9513 if(finder_notfound){$B.path_importer_cache[path_entry]=_b_.None}} 9514 if($B.is_none(finder)){continue} 9515 var find_spec=$B.$getattr(finder,"find_spec"),fs_func=typeof find_spec=="function" ? 9516 find_spec : 9517 $B.$getattr(find_spec,"__call__") 9518 var spec=fs_func(fullname,prev_module) 9519 if(!$B.is_none(spec)){return spec}} 9520 return _b_.None}} 9521 $B.set_func_names(finder_path,"<import>") 9522 for(var method in finder_path){if(typeof finder_path[method]=="function"){finder_path[method]=_b_.classmethod.$factory( 9523 finder_path[method])}} 9524 finder_path.$factory=function(){return{__class__:finder_path}} 9525 var url_hook={__class__:_b_.type,__mro__:[_b_.object],__repr__:function(self){return "<UrlPathFinder"+(self.hint? " for '"+self.hint+"'": 9526 "(unbound)")+" at "+self.path_entry+'>'},$infos:{__module__:"builtins",__name__:"UrlPathFinder"},find_spec :function(self,fullname,module){var loader_data={},notfound=true,hint=self.hint,base_path=self.path_entry+fullname.match(/[^.]+$/g)[0],modpaths=[] 9527 var tryall=hint===undefined 9528 if(tryall ||hint=='py'){ 9529 modpaths=modpaths.concat([[base_path+".py","py",false],[base_path+"/__init__.py","py",true]])} 9530 for(var j=0;notfound && j < modpaths.length;++j){try{var file_info=modpaths[j],module={__name__:fullname,$is_package:false} 9531 loader_data.code=$download_module(module,file_info[0],undefined) 9532 notfound=false 9533 loader_data.type=file_info[1] 9534 loader_data.is_package=file_info[2] 9535 if(hint===undefined){self.hint=file_info[1] 9536 $B.path_importer_cache[self.path_entry]=self} 9537 if(loader_data.is_package){ 9538 $B.path_importer_cache[base_path+'/']= 9539 url_hook.$factory(base_path+'/',self.hint)} 9540 loader_data.path=file_info[0]}catch(err){}} 9541 if(!notfound){return new_spec({name :fullname,loader:finder_path,origin :loader_data.path, 9542 submodule_search_locations:loader_data.is_package? 9543 [base_path]:_b_.None,loader_state:loader_data, 9544 cached:_b_.None,parent:loader_data.is_package? fullname : 9545 parent_package(fullname),has_location:_b_.True})} 9546 return _b_.None},invalidate_caches :function(self){}} 9547 url_hook.$factory=function(path_entry,hint){return{ 9548 __class__:url_hook,path_entry:path_entry.endsWith("/")? path_entry :path_entry+"/",hint:hint}} 9549 $B.set_func_names(url_hook,"<import>") 9550 $B.path_importer_cache={}; 9551 var _sys_paths=[[$B.script_dir+"/","py"],[$B.brython_path+"Lib/","py"],[$B.brython_path+"Lib/site-packages/","py"],[$B.brython_path+"libs/","js"]] 9552 for(var i=0;i < _sys_paths.length;++i){var _path=_sys_paths[i],_type=_path[1] 9553 _path=_path[0] 9554 $B.path_importer_cache[_path]=url_hook.$factory(_path,_type)} 9555 function import_error(mod_name){var exc=_b_.ImportError.$factory(mod_name) 9556 exc.name=mod_name 9557 throw exc} 9558 $B.$__import__=function(mod_name,globals,locals,fromlist,level){var $test=false 9559 if($test){console.log("__import__",mod_name)} 9560 var from_stdlib=false 9561 if(globals.$jsobj && globals.$jsobj.__file__){var file=globals.$jsobj.__file__ 9562 if((file.startsWith($B.brython_path+"Lib/")&& 9563 ! file.startsWith($B.brython_path+"Lib/site-packages/"))|| 9564 file.startsWith($B.brython_path+"libs/")|| 9565 file.startsWith("VFS.")){from_stdlib=true}} 9566 var modobj=$B.imported[mod_name],parsed_name=mod_name.split('.'),has_from=fromlist.length > 0 9567 if(modobj==_b_.None){ 9568 import_error(mod_name)} 9569 if(modobj===undefined){ 9570 if($B.is_none(fromlist)){fromlist=[]} 9571 for(var i=0,modsep="",_mod_name="",len=parsed_name.length-1,__path__=_b_.None;i <=len;++i){var _parent_name=_mod_name; 9572 _mod_name+=modsep+parsed_name[i] 9573 modsep="." 9574 var modobj=$B.imported[_mod_name] 9575 if(modobj==_b_.None){ 9576 import_error(_mod_name)}else if(modobj===undefined){try{$B.import_hooks(_mod_name,__path__,from_stdlib)}catch(err){delete $B.imported[_mod_name] 9577 throw err} 9578 if($B.is_none($B.imported[_mod_name])){import_error(_mod_name)}else{ 9579 if(_parent_name){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}}}else if($B.imported[_parent_name]&& 9580 $B.imported[_parent_name][parsed_name[i]]===undefined){ 9581 _b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])} 9582 if(i < len){try{__path__=$B.$getattr($B.imported[_mod_name],"__path__")}catch(e){ 9583 if(i==len-1 && 9584 $B.imported[_mod_name][parsed_name[len]]&& 9585 $B.imported[_mod_name][parsed_name[len]].__class__=== 9586 module){return $B.imported[_mod_name][parsed_name[len]]} 9587 if(has_from){ 9588 import_error(mod_name)}else{ 9589 var exc=_b_.ModuleNotFoundError.$factory() 9590 exc.msg="No module named '"+mod_name+"'; '"+ 9591 _mod_name+"' is not a package" 9592 exc.args=$B.fast_tuple([exc.msg]) 9593 exc.name=mod_name 9594 exc.path=_b_.None 9595 throw exc}}}}}else{if($B.imported[parsed_name[0]]&& 9596 parsed_name.length==2){try{if($B.imported[parsed_name[0]][parsed_name[1]]===undefined){$B.$setattr($B.imported[parsed_name[0]],parsed_name[1],modobj)}}catch(err){console.log("error",parsed_name,modobj) 9597 throw err}}} 9598 if(fromlist.length > 0){ 9599 return $B.imported[mod_name]}else{ 9600 return $B.imported[parsed_name[0]]}} 9601 $B.$import=function(mod_name,fromlist,aliases,locals){fromlist=fromlist===undefined ?[]:fromlist 9602 aliases=aliases===undefined ?{}:aliases 9603 locals=locals===undefined ?{}:locals 9604 var parts=mod_name.split(".") 9605 if(mod_name[mod_name.length-1]=="."){parts.pop()} 9606 var norm_parts=[],prefix=true 9607 for(var i=0,len=parts.length;i < len;i++){var p=parts[i] 9608 if(prefix && p==""){ 9609 elt=norm_parts.pop() 9610 if(elt===undefined){throw _b_.ImportError.$factory("Parent module '' not loaded, "+ 9611 "cannot perform relative import")}}else{prefix=false; 9612 norm_parts.push(p.substr(0,2)=="$$" ? p.substr(2):p)}} 9613 var mod_name=norm_parts.join(".") 9614 if($B.$options.debug==10){console.log("$import "+mod_name) 9615 console.log("use VFS ? "+$B.use_VFS) 9616 console.log("use static stdlib paths ? "+$B.static_stdlib_import)} 9617 var current_frame=$B.frames_stack[$B.frames_stack.length-1],_globals=current_frame[3],__import__=_globals["__import__"],globals=$B.obj_dict(_globals) 9618 if(__import__===undefined){ 9619 __import__=$B.$__import__} 9620 var importer=typeof __import__=="function" ? 9621 __import__ : 9622 $B.$getattr(__import__,"__call__"),modobj=importer(mod_name,globals,undefined,fromlist,0) 9623 if(! fromlist ||fromlist.length==0){ 9624 var alias=aliases[mod_name] 9625 if(alias){locals[alias]=$B.imported[mod_name]}else{locals[$B.to_alias(norm_parts[0])]=modobj}}else{var __all__=fromlist,thunk={} 9626 if(fromlist && fromlist[0]=="*"){__all__=$B.$getattr(modobj,"__all__",thunk); 9627 if(__all__ !==thunk){ 9628 aliases={}}} 9629 if(__all__===thunk){ 9630 for(var attr in modobj){if(attr[0]!=="_"){locals[attr]=modobj[attr]}}}else{ 9631 for(var i=0,l=__all__.length;i < l;++i){var name=__all__[i] 9632 var alias=aliases[name]||name 9633 try{ 9634 locals[alias]=$B.$getattr(modobj,name)}catch($err1){ 9635 try{var name1=$B.from_alias(name) 9636 $B.$getattr(__import__,'__call__')(mod_name+'.'+name1,globals,undefined,[],0) 9637 locals[alias]=$B.$getattr(modobj,name1)}catch($err3){ 9638 if(mod_name==="__future__"){ 9639 var frame=$B.last($B.frames_stack),line_info=frame[3].$line_info,line_elts=line_info.split(','),line_num=parseInt(line_elts[0]) 9640 $B.$SyntaxError(frame[2],"future feature "+name+" is not defined",current_frame[3].src,undefined,line_num)} 9641 if($err3.$py_error){var errname=$err3.__class__.$infos.__name__ 9642 if($err3.__class__ !==_b_.ImportError && 9643 $err3.__class__ !==_b_.ModuleNotFoundError){$B.handle_error($err3)} 9644 throw _b_.ImportError.$factory( 9645 "cannot import name '"+name+"'")} 9646 if($B.debug > 1){console.log($err3) 9647 console.log($B.last($B.frames_stack))} 9648 throw _b_.ImportError.$factory( 9649 "cannot import name '"+name+"'")}}}} 9650 return locals}} 9651 $B.import_all=function(locals,module){ 9652 for(var attr in module){if(attr.startsWith("$$")){locals[attr]=module[attr]}else if('_$'.indexOf(attr.charAt(0))==-1){locals[attr]=module[attr]}}} 9653 $B.$path_hooks=[url_hook] 9654 $B.$meta_path=[finder_VFS,finder_stdlib_static,finder_path] 9655 $B.finders={VFS:finder_VFS,stdlib_static:finder_stdlib_static,path:finder_path,CPython:finder_cpython} 9656 function optimize_import_for_path(path,filetype){if(path.slice(-1)!="/"){path=path+"/" } 9657 var value=(filetype=='none')? _b_.None : 9658 url_hook.$factory(path,filetype) 9659 $B.path_importer_cache[path]=value} 9660 var Loader={__class__:$B.$type,__mro__:[_b_.object],__name__ :"Loader"} 9661 var _importlib_module={__class__ :module,__name__ :"_importlib",Loader:Loader,VFSFinder:finder_VFS,StdlibStatic:finder_stdlib_static,ImporterPath:finder_path,UrlPathFinder:url_hook,optimize_import_for_path :optimize_import_for_path} 9662 _importlib_module.__repr__=_importlib_module.__str__=function(){return "<module '_importlib' (built-in)>"} 9663 $B.imported["_importlib"]=_importlib_module})(__BRYTHON__) 9664 ; 9665 ;(function($B){var bltns=$B.InjectBuiltins() 9666 eval(bltns) 9667 var object=_b_.object 9668 function $err(op,other){var msg="unsupported operand type(s) for "+op+ 9669 ": 'float' and '"+$B.class_name(other)+"'" 9670 throw _b_.TypeError.$factory(msg)} 9671 function float_value(obj){ 9672 return obj.$brython_value !==undefined ? obj.$brython_value :obj} 9673 var float={__class__:_b_.type,__dir__:object.__dir__,$infos:{__module__:"builtins",__name__:"float"},$is_class:true,$native:true,$descriptors:{"numerator":true,"denominator":true,"imag":true,"real":true}} 9674 float.numerator=function(self){return float_value(self)} 9675 float.denominator=function(self){return _b_.int.$factory(1)} 9676 float.imag=function(self){return _b_.int.$factory(0)} 9677 float.real=function(self){return float_value(self)} 9678 float.__float__=function(self){return float_value(self)} 9679 float.as_integer_ratio=function(self){self=float_value(self) 9680 if(self.valueOf()==Number.POSITIVE_INFINITY || 9681 self.valueOf()==Number.NEGATIVE_INFINITY){throw _b_.OverflowError.$factory("Cannot pass infinity to "+ 9682 "float.as_integer_ratio.")} 9683 if(! Number.isFinite(self.valueOf())){throw _b_.ValueError.$factory("Cannot pass NaN to "+ 9684 "float.as_integer_ratio.")} 9685 var tmp=_b_.$frexp(self.valueOf()),fp=tmp[0],exponent=tmp[1] 9686 for(var i=0;i < 300;i++){if(fp==Math.floor(fp)){break}else{fp*=2 9687 exponent--}} 9688 numerator=float.$factory(fp) 9689 py_exponent=abs(exponent) 9690 denominator=1 9691 py_exponent=_b_.getattr(_b_.int.$factory(denominator),"__lshift__")(py_exponent) 9692 if(exponent > 0){numerator=numerator*py_exponent}else{denominator=py_exponent} 9693 return _b_.tuple.$factory([_b_.int.$factory(numerator),_b_.int.$factory(denominator)])} 9694 float.__bool__=function(self){self=float_value(self) 9695 return _b_.bool.$factory(self.valueOf())} 9696 float.__eq__=function(self,other){self=float_value(self) 9697 other=float_value(other) 9698 if(isNaN(self)&& isNaN(other)){return false} 9699 if(isinstance(other,_b_.int)){return self==other} 9700 if(isinstance(other,float)){ 9701 return self.valueOf()==other.valueOf()} 9702 if(isinstance(other,_b_.complex)){if(other.$imag !=0){return false} 9703 return self==other.$real} 9704 return _b_.NotImplemented} 9705 float.__floordiv__=function(self,other){self=float_value(self) 9706 other=float_value(other) 9707 if(isinstance(other,[_b_.int,float])){if(other.valueOf()==0){throw ZeroDivisionError.$factory('division by zero')} 9708 return float.$factory(Math.floor(self/other))} 9709 if(hasattr(other,"__rfloordiv__")){return getattr(other,"__rfloordiv__")(self)} 9710 $err("//",other)} 9711 float.fromhex=function(arg){ 9712 if(! isinstance(arg,_b_.str)){throw _b_.ValueError.$factory("argument must be a string")} 9713 var value=arg.trim() 9714 switch(value.toLowerCase()){case "+inf": 9715 case "inf": 9716 case "+infinity": 9717 case "infinity": 9718 return $FloatClass(Infinity) 9719 case "-inf": 9720 case "-infinity": 9721 return $FloatClass(-Infinity) 9722 case "+nan": 9723 case "nan": 9724 return $FloatClass(Number.NaN) 9725 case "-nan": 9726 return $FloatClass(-Number.NaN) 9727 case "": 9728 throw _b_.ValueError.$factory("could not convert string to float")} 9729 var _m=/^(\d*\.?\d*)$/.exec(value) 9730 if(_m !==null){return $FloatClass(parseFloat(_m[1]))} 9731 var _m=/^(\+|-)?(0x)?([0-9A-F]+\.?)?(\.[0-9A-F]+)?(p(\+|-)?\d+)?$/i.exec(value) 9732 if(_m==null){throw _b_.ValueError.$factory("invalid hexadecimal floating-point string")} 9733 var _sign=_m[1],_int=parseInt(_m[3]||'0',16),_fraction=_m[4]||'.0',_exponent=_m[5]||'p0' 9734 if(_sign=="-"){_sign=-1}else{_sign=1} 9735 var _sum=_int 9736 for(var i=1,len=_fraction.length;i < len;i++){_sum+=parseInt(_fraction.charAt(i),16)/Math.pow(16,i)} 9737 return new Number(_sign*_sum*Math.pow(2,parseInt(_exponent.substring(1))))} 9738 float.__getformat__=function(arg){if(arg=="double" ||arg=="float"){return "IEEE, little-endian"} 9739 throw _b_.ValueError.$factory("__getformat__() argument 1 must be "+ 9740 "'double' or 'float'")} 9741 function preformat(self,fmt){if(fmt.empty){return _b_.str.$factory(self)} 9742 if(fmt.type && 'eEfFgGn%'.indexOf(fmt.type)==-1){throw _b_.ValueError.$factory("Unknown format code '"+fmt.type+ 9743 "' for object of type 'float'")} 9744 if(isNaN(self)){if(fmt.type=="f" ||fmt.type=="g"){return "nan"} 9745 else{return "NAN"}} 9746 if(self==Number.POSITIVE_INFINITY){if(fmt.type=="f" ||fmt.type=="g"){return "inf"} 9747 else{return "INF"}} 9748 if(fmt.precision===undefined && fmt.type !==undefined){fmt.precision=6} 9749 if(fmt.type=="%"){self*=100} 9750 if(fmt.type=="e"){var res=self.toExponential(fmt.precision),exp=parseInt(res.substr(res.search("e")+1)) 9751 if(Math.abs(exp)< 10){res=res.substr(0,res.length-1)+"0"+ 9752 res.charAt(res.length-1)} 9753 return res} 9754 if(fmt.precision !==undefined){ 9755 var prec=fmt.precision 9756 if(prec==0){return Math.round(self)+""} 9757 var res=self.toFixed(prec),pt_pos=res.indexOf(".") 9758 if(fmt.type !==undefined && 9759 (fmt.type=="%" ||fmt.type.toLowerCase()=="f")){if(pt_pos==-1){res+="."+"0".repeat(fmt.precision)}else{var missing=fmt.precision-res.length+pt_pos+1 9760 if(missing > 0){res+="0".repeat(missing)}}}else if(fmt.type && fmt.type.toLowerCase()=="g"){var exp_fmt=preformat(self,{type:"e"}).split("e"),exp=parseInt(exp_fmt[1]) 9761 if(-4 <=exp && exp < fmt.precision){res=preformat(self,{type:"f",precision:fmt.precision-1-exp})}else{res=preformat(self,{type:"e",precision:fmt.precision-1})} 9762 var parts=res.split("e") 9763 if(fmt.alternate){if(parts[0].search(/\./)==-1){parts[0]+='.'}}else{if(parts[1]){var signif=parts[0] 9764 while(signif.endsWith("0")){signif=signif.substr(0,signif.length-1)} 9765 if(signif.endsWith(".")){signif=signif.substr(0,signif.length-1)} 9766 parts[0]=signif}} 9767 res=parts.join("e") 9768 if(fmt.type=="G"){res=res.toUpperCase()} 9769 return res}else if(fmt.type===undefined){fmt.type="g" 9770 res=preformat(self,fmt) 9771 fmt.type=undefined}else{var res1=self.toExponential(fmt.precision-1),exp=parseInt(res1.substr(res1.search("e")+1)) 9772 if(exp <-4 ||exp >=fmt.precision-1){var elts=res1.split("e") 9773 while(elts[0].endsWith("0")){elts[0]=elts[0].substr(0,elts[0].length-1)} 9774 res=elts.join("e")}}}else{var res=_b_.str.$factory(self)} 9775 if(fmt.type===undefined ||"gGn".indexOf(fmt.type)!=-1){ 9776 if(res.search("e")==-1){while(res.charAt(res.length-1)=="0"){res=res.substr(0,res.length-1)}} 9777 if(res.charAt(res.length-1)=="."){if(fmt.type===undefined){res+="0"} 9778 else{res=res.substr(0,res.length-1)}}} 9779 if(fmt.sign !==undefined){if((fmt.sign==" " ||fmt.sign=="+" )&& self > 0){res=fmt.sign+res}} 9780 if(fmt.type=="%"){res+="%"} 9781 return res} 9782 float.__format__=function(self,format_spec){self=float_value(self) 9783 var fmt=new $B.parse_format_spec(format_spec) 9784 fmt.align=fmt.align ||">" 9785 var raw=preformat(self,fmt).split('.'),_int=raw[0] 9786 if(fmt.comma){var len=_int.length,nb=Math.ceil(_int.length/3),chunks=[] 9787 for(var i=0;i < nb;i++){chunks.push(_int.substring(len-3*i-3,len-3*i))} 9788 chunks.reverse() 9789 raw[0]=chunks.join(",")} 9790 return $B.format_width(raw.join("."),fmt)} 9791 float.__hash__=function(self){if(self===undefined){return float.__hashvalue__ ||$B.$py_next_hash--} 9792 var _v=self.valueOf() 9793 if(_v===Infinity){return 314159} 9794 if(_v===-Infinity){return-271828} 9795 if(isNaN(_v)){return 0} 9796 if(_v==Math.round(_v)){return Math.round(_v)} 9797 var r=_b_.$frexp(_v) 9798 r[0]*=Math.pow(2,31) 9799 var hipart=_b_.int.$factory(r[0]) 9800 r[0]=(r[0]-hipart)*Math.pow(2,31) 9801 var x=hipart+_b_.int.$factory(r[0])+(r[1]<< 15) 9802 return x & 0xFFFFFFFF} 9803 _b_.$isninf=function(x){var x1=x 9804 if(isinstance(x,float)){x1=x.valueOf()} 9805 return x1==-Infinity ||x1==Number.NEGATIVE_INFINITY} 9806 _b_.$isinf=function(x){var x1=x 9807 if(isinstance(x,float)){x1=x.valueOf()} 9808 return x1==Infinity ||x1==-Infinity || 9809 x1==Number.POSITIVE_INFINITY ||x1==Number.NEGATIVE_INFINITY} 9810 _b_.$fabs=function(x){return x > 0 ? float.$factory(x):float.$factory(-x)} 9811 _b_.$frexp=function(x){var x1=x 9812 if(isinstance(x,float)){x1=x.valueOf()} 9813 if(isNaN(x1)||_b_.$isinf(x1)){return[x1,-1]} 9814 if(x1==0){return[0,0]} 9815 var sign=1,ex=0,man=x1 9816 if(man < 0.){sign=-sign 9817 man=-man} 9818 while(man < 0.5){man*=2.0 9819 ex--} 9820 while(man >=1.0){man*=0.5 9821 ex++} 9822 man*=sign 9823 return[man,ex]} 9824 _b_.$ldexp=function(x,i){if(_b_.$isninf(x)){return float.$factory('-inf')} 9825 if(_b_.$isinf(x)){return float.$factory('inf')} 9826 var y=x 9827 if(isinstance(x,float)){y=x.valueOf()} 9828 if(y==0){return y} 9829 var j=i 9830 if(isinstance(i,float)){j=i.valueOf()} 9831 return y*Math.pow(2,j)} 9832 float.hex=function(self){ 9833 self=float_value(self) 9834 var DBL_MANT_DIG=53, 9835 TOHEX_NBITS=DBL_MANT_DIG+3-(DBL_MANT_DIG+2)% 4 9836 switch(self.valueOf()){case Infinity: 9837 case-Infinity: 9838 case Number.NaN: 9839 case-Number.NaN: 9840 return self 9841 case-0: 9842 return "-0x0.0p0" 9843 case 0: 9844 return "0x0.0p0"} 9845 var _a=_b_.$frexp(_b_.$fabs(self.valueOf())),_m=_a[0],_e=_a[1],_shift=1-Math.max(-1021-_e,0) 9846 _m=_b_.$ldexp(_m,_shift) 9847 _e-=_shift 9848 var _int2hex="0123456789ABCDEF".split(""),_s=_int2hex[Math.floor(_m)] 9849 _s+='.' 9850 _m-=Math.floor(_m) 9851 for(var i=0;i <(TOHEX_NBITS-1)/4;i++){_m*=16.0 9852 _s+=_int2hex[Math.floor(_m)] 9853 _m-=Math.floor(_m)} 9854 var _esign="+" 9855 if(_e < 0){_esign="-" 9856 _e=-_e} 9857 if(self.value < 0){return "-0x"+_s+"p"+_esign+_e} 9858 return "0x"+_s+"p"+_esign+_e} 9859 float.__init__=function(self,value){return _b_.None} 9860 float.__int__=function(self){return parseInt(self)} 9861 float.is_integer=function(self){return _b_.int.$factory(self)==self} 9862 float.__mod__=function(self,other){ 9863 self=float_value(self) 9864 other=float_value(other) 9865 if(other==0){throw ZeroDivisionError.$factory("float modulo")} 9866 if(isinstance(other,_b_.int)){return new Number((self % other+other)% other)} 9867 if(isinstance(other,float)){ 9868 var q=Math.floor(self/other),r=self-other*q 9869 return new Number(r)} 9870 if(isinstance(other,_b_.bool)){var bool_value=0 9871 if(other.valueOf()){bool_value=1} 9872 return new Number((self % bool_value+bool_value)% bool_value)} 9873 if(hasattr(other,"__rmod__")){return getattr(other,"__rmod__")(self)} 9874 $err("%",other)} 9875 float.__mro__=[object] 9876 float.__mul__=function(self,other){self=float_value(self) 9877 other=float_value(other) 9878 if(isinstance(other,_b_.int)){if(other.__class__==$B.long_int){return new Number(self*parseFloat(other.value))} 9879 return new Number(self*other)} 9880 if(isinstance(other,float)){return new Number(self*float_value(other))} 9881 if(isinstance(other,_b_.bool)){var bool_value=0 9882 if(other.valueOf()){bool_value=1} 9883 return new Number(self*bool_value)} 9884 if(isinstance(other,_b_.complex)){return $B.make_complex(float.$factory(self*other.$real),float.$factory(self*other.$imag))} 9885 if(hasattr(other,"__rmul__")){return getattr(other,"__rmul__")(self)} 9886 $err("*",other)} 9887 float.__ne__=function(self,other){var res=float.__eq__(self,other) 9888 return res===_b_.NotImplemented ? res :! res} 9889 float.__neg__=function(self,other){return float.$factory(-float_value(self))} 9890 float.__new__=function(cls,value){if(cls===undefined){throw _b_.TypeError.$factory("float.__new__(): not enough arguments")}else if(! _b_.isinstance(cls,_b_.type)){throw _b_.TypeError.$factory("float.__new__(X): X is not a type object")} 9891 if(cls===float){return float.$factory(value)} 9892 return{ 9893 __class__:cls,__dict__:$B.empty_dict(),$brython_value:value ||0}} 9894 float.__pos__=function(self){return float_value(self)} 9895 float.__pow__=function(self,other){self=float_value(self) 9896 other=float_value(other) 9897 var other_int=isinstance(other,_b_.int)