UNPKG

smartdown

Version:

A library for translating, rendering and interacting with Smartdown documents. Smartdown is an extension of Markdown that provides richer media support and reactive programming capability.

1,292 lines (1,289 loc) 766 kB
// brython.js brython.info // version [3, 9, 0, 'final', 0] // implementation [3, 9, 2, 'final', 0] // version compiled from commented, indented source files at // github.com/brython-dev/brython var __BRYTHON__=__BRYTHON__ ||{} try{ eval("async function* f(){}")}catch(err){console.warn("Your browser is not fully supported. If you are using "+ "Microsoft Edge, please upgrade to the latest version")} ;(function($B){ $B.isWebWorker=('undefined' !==typeof WorkerGlobalScope)&& ("function"===typeof importScripts)&& (navigator instanceof WorkerNavigator) $B.isNode=(typeof process !=='undefined')&&(process.release.name==='node') var _window if($B.isNode){_window={location:{href:'',origin:'',pathname:''},navigator:{userLanguage:''}}}else{ _window=self} var href=_window.location.href $B.protocol=href.split(':')[0] $B.BigInt=_window.BigInt $B.indexedDB=_window.indexedDB var $path if($B.brython_path===undefined){ var this_url; if($B.isWebWorker){this_url=_window.location.href; if(this_url.startsWith("blob:")){this_url=this_url.substr(5)}}else{var scripts=document.getElementsByTagName('script') this_url=scripts[scripts.length-1].src} var elts=this_url.split('/') elts.pop() $path=$B.brython_path=elts.join('/')+'/'}else{if(! $B.brython_path.endsWith("/")){$B.brython_path+="/"} $path=$B.brython_path} var path=_window.location.origin+_window.location.pathname,path_elts=path.split("/") path_elts.pop() var $script_dir=$B.script_dir=path_elts.join("/") $B.__ARGV=[] $B.webworkers={} $B.$py_module_path={} $B.file_cache={} $B.$py_src={} $B.path=[$path+'Lib',$path+'libs',$script_dir,$path+'Lib/site-packages'] $B.async_enabled=false if($B.async_enabled){$B.block={}} $B.imported={} $B.precompiled={} $B.frames_stack=[] $B.builtins={} $B.builtins_scope={id:'__builtins__',module:'__builtins__',binding:{}} $B.builtin_funcs={} $B.builtin_classes=[] $B.__getattr__=function(attr){return this[attr]} $B.__setattr__=function(attr,value){ if(['debug','stdout','stderr'].indexOf(attr)>-1){$B[attr]=value} else{throw $B.builtins.AttributeError.$factory( '__BRYTHON__ object has no attribute '+attr)}} $B.language=_window.navigator.userLanguage ||_window.navigator.language $B.locale="C" if($B.isWebWorker){$B.charset="utf-8"}else{ $B.charset=document.characterSet ||document.inputEncoding ||"utf-8"} $B.max_int=Math.pow(2,53)-1 $B.min_int=-$B.max_int $B.max_float=new Number(Number.MAX_VALUE) $B.min_float=new Number(Number.MIN_VALUE) // var nb=Math.pow(2,29) // while(true){try{'a'.repeat(nb) // nb*=2}catch(err){ // var lo=nb/2,hi=nb,mid // while(hi-lo > 1){try{mid=lo+(hi-lo)/2 // 'a'.repeat(mid) // lo=mid}catch(err){hi=mid}} // try{'a'.repeat(hi) // $B.max_string_length=hi // break}catch(err){$B.max_string_length=lo // break}}} $B.max_string_length=536870888 console.log('$B.max_string_length', $B.max_string_length) $B.$py_next_hash=Math.pow(2,53)-1 $B.$py_UUID=0 $B.lambda_magic=Math.random().toString(36).substr(2,8) $B.set_func_names=function(klass,module){if(klass.$infos){var name=klass.$infos.__name__ klass.$infos.__module__=module klass.$infos.__qualname__=name}else{var name=klass.__name__ klass.$infos={__name__:name,__module__:module,__qualname__:name}} klass.__module__=module for(var attr in klass){if(typeof klass[attr]=='function'){klass[attr].$infos={__doc__:klass[attr].__doc__ ||"",__module__:module,__qualname__ :name+'.'+attr,__name__:attr} if(klass[attr].$type=="classmethod"){klass[attr].__class__=$B.method}}}} var has_storage=typeof(Storage)!=="undefined" if(has_storage){$B.has_local_storage=false try{if(localStorage){$B.local_storage=localStorage $B.has_local_storage=true}}catch(err){} $B.has_session_storage=false try{if(sessionStorage){$B.session_storage=sessionStorage $B.has_session_storage=true}}catch(err){}}else{$B.has_local_storage=false $B.has_session_storage=false} $B.globals=function(){ return $B.frames_stack[$B.frames_stack.length-1][3]} $B.scripts={} $B.$options={} $B.update_VFS=function(scripts){$B.VFS=$B.VFS ||{} var vfs_timestamp=scripts.$timestamp if(vfs_timestamp !==undefined){delete scripts.$timestamp} for(var script in scripts){if($B.VFS.hasOwnProperty(script)){console.warn("Virtual File System: duplicate entry "+script)} $B.VFS[script]=scripts[script] $B.VFS[script].timestamp=vfs_timestamp}} $B.add_files=function(files){ $B.files=$B.files ||{} for(var file in files){$B.files[file]=files[file]}} $B.python_to_js=function(src,script_id){$B.meta_path=$B.$meta_path.slice() if(!$B.use_VFS){$B.meta_path.shift()} if(script_id===undefined){script_id="__main__"} var root=__BRYTHON__.py2js(src,script_id,script_id),js=root.to_js() js="(function() {\n var $locals_"+script_id+" = {}\n"+js+"\n}())" return js} _window.py=function(src){ var root=$B.py2js(src[0],"script","script"),js=root.to_js() $B.set_import_paths() new Function("$locals_script",js)({})}})(__BRYTHON__) ; __BRYTHON__.implementation=[3,9,2,'final',0] __BRYTHON__.__MAGIC__="3.9.2" __BRYTHON__.version_info=[3,9,0,'final',0] __BRYTHON__.compiled_date="2021-04-22 21:39:42.669205" __BRYTHON__.timestamp=1619120382669 __BRYTHON__.builtin_module_names=["_aio","_ajax","_base64","_binascii","_cmath","_io_classes","_json","_jsre","_locale","_multiprocessing","_posixsubprocess","_profile","_sre1","_sre_utils","_string","_strptime","_svg","_webcomponent","_webworker","_zlib_utils","array","bry_re","builtins","dis","encoding_cp932","hashlib","html_parser","long_int","marshal","math","module1","modulefinder","posix","python_re","python_re1","python_re2","random","unicodedata"] ; ;(function($B){Number.isInteger=Number.isInteger ||function(value){return typeof value==='number' && isFinite(value)&& Math.floor(value)===value}; Number.isSafeInteger=Number.isSafeInteger ||function(value){return Number.isInteger(value)&& Math.abs(value)<=Number.MAX_SAFE_INTEGER;}; var js,$pos,res,$op var _b_=$B.builtins var _window if($B.isNode){_window={location:{href:'',origin:'',pathname:''}}}else{ _window=self} $B.parser={} var clone=$B.clone=function(obj){var res={} for(var attr in obj){res[attr]=obj[attr]} return res} $B.last=function(table){if(table===undefined){console.log($B.frames_stack.slice())} return table[table.length-1]} $B.list2obj=function(list,value){var res={},i=list.length if(value===undefined){value=true} while(i--> 0){res[list[i]]=value} return res} $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=[] if(arguments[0]=="all"){keys=Object.keys($B.op2method) keys.splice(keys.indexOf("subset"),1)}else{for(var i=0,len=arguments.length;i < len;i++){keys.push(arguments[i])}} for(var i=0,len=keys.length;i < len;i++){var key=keys[i],ops=$B.op2method[key] if(ops===undefined){throw Error(key)} for(var attr in ops){res[attr]=ops[attr]}} return res}} var $operators=$B.op2method.subset("all") var $augmented_assigns=$B.augmented_assigns=$B.op2method.augmented_assigns var noassign=$B.list2obj(['True','False','None','__debug__']) var $op_order=[['or'],['and'],['not'],['in','not_in'],['<','<=','>','>=','!=','==','is','is_not'],['|'],['^'],['&'],['>>','<<'],['+'],['-'],['*','@','/','//','%'],['unary_neg','unary_inv','unary_pos'],['**'] ] var $op_weight={},$weight=1 $op_order.forEach(function(_tmp){_tmp.forEach(function(item){$op_weight[item]=$weight}) $weight++}) var $loop_num=0 var create_temp_name=$B.parser.create_temp_name=function(prefix){var _prefix=prefix ||'$temp' return _prefix+$loop_num++;} var replace_node=$B.parser.replace_node=function(replace_what,replace_with){var parent=replace_what.parent var pos=get_rank_in_parent(replace_what) parent.children[pos]=replace_with replace_with.parent=parent replace_with.bindings=replace_what.bindings} var get_rank_in_parent=$B.parser.get_rank_in_parent=function(node){return node.parent.children.indexOf(node)} var add_identnode=$B.parser.add_identnode=function(parent,insert_at,name,val){var new_node=new $Node() new_node.parent=parent new_node.locals=parent.locals new_node.module=parent.module var new_ctx=new $NodeCtx(new_node) var expr_ctx=new $ExprCtx(new_ctx,'id',true) var idctx=new $IdCtx(expr_ctx,name) var assign=new $AssignCtx(expr_ctx) if(insert_at===-1) parent.add(new_node) else parent.insert(insert_at,new_node) assign.tree[1]=val return new_node} var chained_comp_num=0 var $_SyntaxError=$B.parser.$_SyntaxError=function(C,msg,indent){ var ctx_node=C while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node,root=tree_node while(root.parent !==undefined){root=root.parent} var module=tree_node.module,src=root.src,line_num=tree_node.line_num if(src){line_num=src.substr(0,$pos).split("\n").length} if(root.line_info){line_num=root.line_info} if(indent===undefined ||typeof indent !="number"){if(Array.isArray(msg)){$B.$SyntaxError(module,msg[0],src,$pos,line_num,root)} if(msg==="Triple string end not found"){ $B.$SyntaxError(module,'invalid syntax : triple string end not found',src,$pos,line_num,root)} var message='invalid syntax' if(!(msg.startsWith("token "))){message+=' ('+msg+')'} $B.$SyntaxError(module,message,src,$pos,line_num,root)}else{throw $B.$IndentationError(module,msg,src,$pos,line_num,root)}} 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`+ ' '+lines[node.line_num-1] $B.$getattr($B.stderr,"write")(message)} function check_assignment(C){var ctx=C,forbidden=['assert','del','import','raise','return'] while(ctx){if(forbidden.indexOf(ctx.type)>-1){$_SyntaxError(C,'invalid syntax - assign')}else if(ctx.type=="expr" && 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"])}} ctx=ctx.parent}} var $Node=$B.parser.$Node=function(type){this.type=type this.children=[]} $Node.prototype.add=function(child){ this.children[this.children.length]=child child.parent=this child.module=this.module} $Node.prototype.insert=function(pos,child){ this.children.splice(pos,0,child) child.parent=this child.module=this.module} $Node.prototype.toString=function(){return "<object 'Node'>"} $Node.prototype.show=function(indent){ var res='' if(this.type==='module'){this.children.forEach(function(child){res+=child.show(indent)}) return res} indent=indent ||0 res+=' '.repeat(indent) res+=this.C if(this.children.length > 0){res+='{'} res+='\n' this.children.forEach(function(child){res+='['+i+'] '+child.show(indent+4)}) if(this.children.length > 0){res+=' '.repeat(indent) res+='}\n'} return res} $Node.prototype.to_js=function(indent){ if(this.js !==undefined){return this.js} this.res=[] this.unbound=[] if(this.type==='module'){this.children.forEach(function(child){this.res.push(child.to_js())},this) this.js=this.res.join('') return this.js} indent=indent ||0 var ctx_js=this.C.to_js() if(ctx_js){ this.res.push(' '.repeat(indent)) this.res.push(ctx_js) if(this.children.length > 0){this.res.push('{')} this.res.push('\n') this.children.forEach(function(child){this.res.push(child.to_js(indent+4))},this) if(this.children.length > 0){this.res.push(' '.repeat(indent)) this.res.push('}\n')}} this.js=this.res.join('') return this.js} $Node.prototype.transform=function(rank){ if(this.has_await){this.parent.insert(rank,$NodeJS("var save_stack = $B.save_stack()")) this.parent.insert(rank+2,$NodeJS("$B.restore_stack(save_stack, $locals)")) this.has_await=false return 1} if(this.has_yield && ! this.has_yield.transformed){ var parent=this.parent if(this.has_yield.from){var new_node=new $Node() var new_ctx=new $NodeCtx(new_node) var new_expr=new $ExprCtx(new_ctx,'js',false) var _id=new $RawJSCtx(new_expr,`var _i${this.has_yield.from_num}`) var assign=new $AssignCtx(new_expr) var right=new $ExprCtx(assign) right.tree=this.has_yield.tree parent.insert(rank,new_node) var pnode=$get_node(this.has_yield) var n=this.has_yield.from_num var replace_with=`$B.$import("sys",[],{}) _i${n}=_b_.iter(_i${n}) var $failed${n}=false try{var _y${n}=_b_.next(_i${n})}catch(_e){$B.set_exc(_e) $failed${n}=true $B.pmframe=$B.last($B.frames_stack) _e=$B.exception(_e) if(_e.__class__===_b_.StopIteration){var _r${n}=$B.$getattr(_e,"value")}else{throw _e}} if(! $failed${n}){while(true){var $failed1${n}=false try{$B.leave_frame({$locals}) var _s${n}=yield _y${n} $B.frames_stack.push($top_frame)}catch(_e){if(_e.__class__===_b_.GeneratorExit){var $failed2${n}=false try{var _m${n}=$B.$geatttr(_i${n},"close")}catch(_e1){$failed2${n}=true if(_e1.__class__ !==_b_.AttributeError){throw _e1}} if(! $failed2${n}){$B.$call(_m${n})()} throw _e}else if($B.is_exc(_e,[_b_.BaseException])){var _x=$B.$call($B.$getattr($locals.sys,"exc_info"))() var $failed3${n}=false try{var _m${n}=$B.$getattr(_i${n},"throw")}catch(err){$failed3${n}=true if($B.is_exc(err,[_b_.AttributeError])){throw err}} 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") break} throw err}}}} 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") break} throw err}}}}` parent.insert(rank+1,$NodeJS(replace_with)) return 3} parent.children.splice(rank,1) if(this.has_yield.tree[0].type==='abstract_expr'){new_node=$NodeJS("var result = _b_.None")}else{var new_node=new $Node() var new_ctx=new $NodeCtx(new_node) var new_expr=new $ExprCtx(new_ctx,'js',false) var _id=new $RawJSCtx(new_expr,'var result') var assign=new $AssignCtx(new_expr) assign.tree[1]=this.has_yield.tree[0] _id.parent=assign} new_node.line_num=this.line_num parent.insert(rank,new_node) var try_node=new $NodeJS("try") try_node.add($NodeJS("$B.leave_frame({$locals})")) try_node.add(this) parent.insert(rank+1,try_node) this.has_yield.to_js=function(){return 'yield result'} this.has_yield.transformed=true var i=0 while(i < try_node.children.length){var offset=try_node.children[i].transform(i) if(offset===undefined){offset=1} i+=offset} var catch_node=$NodeJS(`catch(err${this.line_num})`) catch_node.add($NodeJS("$B.frames_stack.push($top_frame)")) catch_node.add($NodeJS(`throw err${this.line_num}`)) parent.insert(rank+2,catch_node) parent.insert(rank+3,$NodeJS("$B.frames_stack.push($top_frame)")) return 2} if(this.type==='module'){ this.__doc__=$get_docstring(this) var i=0 while(i < this.children.length){var offset=this.children[i].transform(i) if(offset===undefined){offset=1} i+=offset}}else{var elt=this.C.tree[0],ctx_offset if(elt===undefined){console.log(this)} if(elt.transform !==undefined){ctx_offset=elt.transform(this,rank)} var i=0 while(i < this.children.length){var offset=this.children[i].transform(i) if(offset===undefined){offset=1} i+=offset} if(ctx_offset===undefined){ctx_offset=1} return ctx_offset}} $Node.prototype.clone=function(){var res=new $Node(this.type) for(var attr in this){res[attr]=this[attr]} return res} $Node.prototype.clone_tree=function(){var res=new $Node(this.type) for(var attr in this){res[attr]=this[attr]} res.children=[] for(var i=0,len=this.children.length;i < len;i++){res.add(this.children[i].clone_tree())} return res} var $AbstractExprCtx=$B.parser.$AbstractExprCtx=function(C,with_commas){this.type='abstract_expr' this.with_commas=with_commas this.parent=C this.tree=[] C.tree[C.tree.length]=this} $AbstractExprCtx.prototype.toString=function(){return '(abstract_expr '+this.with_commas+') '+this.tree} $AbstractExprCtx.prototype.transition=function(token,value){var C=this var packed=C.packed,is_await=C.is_await,assign=C.assign if(! assign){switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': case 'yield': C.parent.tree.pop() var commas=C.with_commas C=C.parent C.packed=packed C.is_await=is_await if(assign){console.log("set assign to parent",C) C.assign=assign}}} switch(token){case 'await': return new $AwaitCtx(C) case 'id': return new $IdCtx(new $ExprCtx(C,'id',commas),value) case 'str': return new $StringCtx(new $ExprCtx(C,'str',commas),value) case 'bytes': return new $StringCtx(new $ExprCtx(C,'bytes',commas),value) case 'int': return new $NumberCtx('int',new $ExprCtx(C,'int',commas),value) case 'float': return new $NumberCtx('float',new $ExprCtx(C,'float',commas),value) case 'imaginary': return new $NumberCtx('imaginary',new $ExprCtx(C,'imaginary',commas),value) case '(': return new $ListOrTupleCtx( new $ExprCtx(C,'tuple',commas),'tuple') case '[': return new $ListOrTupleCtx( new $ExprCtx(C,'list',commas),'list') case '{': return new $DictOrSetCtx( new $ExprCtx(C,'dict_or_set',commas)) case '.': return new $EllipsisCtx( new $ExprCtx(C,'ellipsis',commas)) case 'not': if(C.type=='op' && C.op=='is'){ C.op='is_not' return C} return new $NotCtx(new $ExprCtx(C,'not',commas)) case 'lambda': return new $LambdaCtx(new $ExprCtx(C,'lambda',commas)) case 'op': var tg=value switch(tg){case '*': C.parent.tree.pop() var commas=C.with_commas C=C.parent return new $PackedCtx( new $ExprCtx(C,'expr',commas)) case '-': case '~': case '+': C.parent.tree.pop() var left=new $UnaryCtx(C.parent,tg) 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')} return new $AbstractExprCtx(op_expr,false) case 'not': C.parent.tree.pop() var commas=C.with_commas C=C.parent return new $NotCtx( new $ExprCtx(C,'not',commas))} $_SyntaxError(C,'token '+token+' after '+ C) case '=','in': $_SyntaxError(C,'token '+token+' after '+ C) case 'yield': return new $AbstractExprCtx(new $YieldCtx(C),true) case ':': if(C.parent.type=="sub" || (C.parent.type=="list_or_tuple" && C.parent.parent.type=="sub")){return new $AbstractExprCtx(new $SliceCtx(C.parent),false)} return $transition(C.parent,token,value) case ')': case ',': switch(C.parent.type){case 'list_or_tuple': case 'slice': case 'call_arg': case 'op': case 'yield': break case 'annotation': $_SyntaxError(C,"empty annotation") default: $_SyntaxError(C,token)}} return $transition(C.parent,token,value)} $AbstractExprCtx.prototype.to_js=function(){this.js_processed=true if(this.type==='list')return '['+$to_js(this.tree)+']' return $to_js(this.tree)} var $AliasCtx=$B.parser.$AliasCtx=function(C){ this.type='ctx_manager_alias' this.parent=C this.tree=[] C.tree[C.tree.length-1].alias=this} $AliasCtx.prototype.transition=function(token,value){var C=this switch(token){case ',': case ':': C.parent.set_alias(C.tree[0].tree[0]) return $transition(C.parent,token,value)} $_SyntaxError(C,'token '+token+' after '+C)} var $AnnotationCtx=$B.parser.$AnnotationCtx=function(C){ this.type='annotation' this.parent=C this.tree=[] C.annotation=this var scope=$get_scope(C) if(scope.binding.__annotations__===undefined){ scope.binding.__annotations__=true C.create_annotations=true} if(scope.ntype=="def" && C.tree && C.tree.length > 0 && C.tree[0].type=="id"){var name=C.tree[0].value if(scope.globals && scope.globals.has(name)>-1){$_SyntaxError(C,["annotated name '"+name+ "' can't be global"])} scope.annotations=scope.annotations ||new Set() scope.annotations.add(name) if(! C.$in_parens){scope.binding=scope.binding ||{} scope.binding[name]=true}}} $AnnotationCtx.prototype.toString=function(){return '(annotation) '+this.tree} $AnnotationCtx.prototype.transition=function(token,value){var C=this if(token=="eol" && C.tree.length==1 && 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")} return $transition(C.parent,token)} $AnnotationCtx.prototype.to_js=function(){return $to_js(this.tree)} var $AssertCtx=$B.parser.$AssertCtx=function(C){ this.type='assert' this.parent=C this.tree=[] C.tree[C.tree.length]=this} $AssertCtx.prototype.toString=function(){return '(assert) '+this.tree} $AssertCtx.prototype.transition=function(token,value){var C=this if(token==","){if(this.tree.length > 1){$_SyntaxError(C,"too many commas after assert")} return new $AbstractExprCtx(this,false)} if(token=='eol'){return $transition(C.parent,token)} $_SyntaxError(C,token)} $AssertCtx.prototype.transform=function(node,rank){if(this.tree.length > 1){ var condition=this.tree[0] var message=this.tree[1]}else{var condition=this.tree[0] var message=null} if(this.tree[0].type=="expr" && this.tree[0].name=="tuple" && this.tree[0].tree[0].tree.length > 1){var warning=_b_.SyntaxWarning.$factory( "assertion is always true, perhaps remove parentheses?") var module=$get_module(this) $B.$syntax_err_line(warning,module.filename,module.src,$pos,$get_node(this).line_num) $B.imported._warnings.warn(warning)} var new_ctx=new $ConditionCtx(node.C,'if') var not_ctx=new $NotCtx(new_ctx) not_ctx.tree=[condition] node.C=new_ctx var new_node=new $Node() var js='throw _b_.AssertionError.$factory()' if(message !==null){js='throw _b_.AssertionError.$factory(_b_.str.$factory('+ message.to_js()+'))'} new $NodeJSCtx(new_node,js) node.add(new_node)} function make_assign(left,right,module){var node=new $Node() node.id=module var C=new $NodeCtx(node) var expr=new $ExprCtx(C,'left',true) expr.tree=left.tree var assign=new $AssignCtx(expr) assign.tree[1]=new $JSCode(right) return node} var $AssignCtx=$B.parser.$AssignCtx=function(C,expression){ check_assignment(C) if(C.type=="expr" && C.tree[0].type=="lambda"){$_SyntaxError(C,["cannot assign to lambda"])} this.type='assign' if(expression=='expression'){this.expression=true console.log("parent of assign expr",C.parent)} C.parent.tree.pop() C.parent.tree[C.parent.tree.length]=this this.parent=C.parent this.tree=[C] var scope=$get_scope(this) if(C.type=='expr' && C.tree[0].type=='call'){$_SyntaxError(C,["cannot assign to function call "])}else if(C.type=='list_or_tuple' || (C.type=='expr' && C.tree[0].type=='list_or_tuple')){if(C.type=='expr'){C=C.tree[0]} C.bind_ids(scope)}else if(C.type=='assign'){C.tree.forEach(function(elt){var assigned=elt.tree[0] if(assigned.type=='id'){$bind(assigned.value,scope,this)}},this)}else{var assigned=C.tree[0] if(assigned && assigned.type=='id'){if(noassign[assigned.value]===true){$_SyntaxError(C,["cannot assign to keyword"])} assigned.bound=true if(!scope.globals ||!scope.globals.has(assigned.value)){ var node=$get_node(this) node.bound_before=Object.keys(scope.binding) $bind(assigned.value,scope,this)}else{ var module=$get_module(C) assigned.global_module=module.module $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"])}}} $AssignCtx.prototype.guess_type=function(){return} $AssignCtx.prototype.toString=function(){return '(assign) '+this.tree[0]+'='+this.tree[1]} $AssignCtx.prototype.transition=function(token,value){var C=this if(token=='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+ C)} C.guess_type() return $transition(C.parent,'eol')} $_SyntaxError(C,'token '+token+' after '+C)} $AssignCtx.prototype.transform=function(node,rank){ var scope=$get_scope(this) var left=this.tree[0],right=this.tree[1],assigned=[] while(left.type=='assign'){assigned.push(left.tree[1]) left=left.tree[0]} if(assigned.length > 0){assigned.push(left) var ctx=node.C ctx.tree=[] var nleft=new $RawJSCtx(ctx,'var $temp'+$loop_num) nleft.tree=ctx.tree var nassign=new $AssignCtx(nleft) nassign.tree[1]=right assigned.forEach(function(elt){if(elt.type=="expr" && elt.tree[0].type=="list_or_tuple" && elt.tree[0].real=="tuple" && elt.tree[0].tree.length==1){ elt=elt.tree[0].tree[0]} var new_node=new $Node(),node_ctx=new $NodeCtx(new_node) new_node.locals=node.locals new_node.line_num=node.line_num node.parent.insert(rank+1,new_node) elt.parent=node_ctx var assign=new $AssignCtx(elt) new $RawJSCtx(assign,'$temp'+$loop_num)}) $loop_num++ this.tree[0]=left return} var left_items=null switch(left.type){case 'expr': if(left.tree.length > 1){left_items=left.tree}else if(left.tree[0].type=='list_or_tuple' || left.tree[0].type=='target_list'){left_items=left.tree[0].tree}else if(left.tree[0].type=='id'){ var name=left.tree[0].value if(scope.globals && scope.globals.has(name)){}else{left.tree[0].bound=true}} break case 'target_list': case 'list_or_tuple': left_items=left.tree} var right=this.tree[1] if(left_items===null){if(left.tree[0].bound){if(right.type=="expr" && right.name=="int"){node.bindings=node.bindings ||{} node.bindings[left.tree[0].value]="int"}} return} var right_items=null if(right.type=='list' ||right.type=='tuple'|| (right.type=='expr' && right.tree.length > 1)){right_items=right.tree} if(right_items !==null){ if(right_items.length > left_items.length){throw Error('ValueError : too many values to unpack (expected '+ left_items.length+')')}else if(right_items.length < left_items.length){throw Error('ValueError : need more than '+ right_items.length+' to unpack')} var new_nodes=[],pos=0 var new_node=new $Node() new_node.line_num=node.line_num new $NodeJSCtx(new_node,'void(0)') new_nodes[pos++]=new_node var $var='$temp'+$loop_num var new_node=new $Node() new_node.line_num=node.line_num new $NodeJSCtx(new_node,'var '+$var+' = [], $pos = 0') new_nodes[pos++]=new_node right_items.forEach(function(right_item){var js=$var+'[$pos++] = '+right_item.to_js() var new_node=new $Node() new_node.line_num=node.line_num new $NodeJSCtx(new_node,js) new_nodes[pos++]=new_node}) var this_node=$get_node(this) left_items.forEach(function(left_item){var new_node=new $Node() new_node.id=this_node.module new_node.locals=this_node.locals new_node.line_num=node.line_num var C=new $NodeCtx(new_node) left_item.parent=C var assign=new $AssignCtx(left_item,false) assign.tree[1]=new $JSCode($var+'['+i+']') new_nodes[pos++]=new_node},this) node.parent.children.splice(rank,1) for(var i=new_nodes.length-1;i >=0;i--){node.parent.insert(rank,new_nodes[i])} $loop_num++}else{ node.parent.children.splice(rank,1) var rname=create_temp_name('$right') var rlname=create_temp_name('$rlist'); var new_node=$NodeJS('var '+rname+' = '+ '$B.$getattr($B.$iter('+right.to_js()+ '), "__next__");') new_node.line_num=node.line_num node.parent.insert(rank++,new_node) node.parent.insert(rank++,$NodeJS('var '+rlname+'=[], $pos=0;'+ 'while(1){'+ 'try{'+ rlname+'[$pos++] = '+rname+'()'+ '}catch(err){'+ 'break'+ '}'+ '}') ) var packed=null var min_length=left_items.length for(var i=0;i < left_items.length;i++){var expr=left_items[i] if(expr.type=='packed' || (expr.type=='expr' && expr.tree[0].type=='packed')){packed=i min_length-- break}} node.parent.insert(rank++,$NodeJS('if('+rlname+'.length<'+min_length+'){'+ 'throw _b_.ValueError.$factory('+ '"need more than " +'+rlname+ '.length + " value" + ('+rlname+ '.length > 1 ?'+' "s" : "") + " to unpack")}' ) ) if(packed==null){node.parent.insert(rank++,$NodeJS('if('+rlname+'.length>'+min_length+'){'+ 'throw _b_.ValueError.$factory('+ '"too many values to unpack '+ '(expected '+left_items.length+')"'+ ')'+ '}') )} left_items.forEach(function(left_item,i){var new_node=new $Node() new_node.id=scope.id new_node.line_num=node.line_num node.parent.insert(rank++,new_node) var C=new $NodeCtx(new_node) left_item.parent=C var assign=new $AssignCtx(left_item,false) var js=rlname if(packed==null ||i < packed){js+='['+i+']'}else if(i==packed){js+='.slice('+i+','+rlname+'.length-'+ (left_items.length-i-1)+')'}else{js+='['+rlname+'.length-'+(left_items.length-i)+']'} assign.tree[1]=new $JSCode(js)}) $loop_num++}} $AssignCtx.prototype.to_js=function(){this.js_processed=true if(this.parent.type=='call'){ return '{$nat:"kw",name:'+this.tree[0].to_js()+ ',value:'+this.tree[1].to_js()+'}'} var left=this.tree[0] while(left.type=='expr' && ! left.assign){left=left.tree[0]} var right=this.tree[1] if(left.type=='attribute' ||left.type=='sub'){ var right_js=right.to_js() var res='',rvar='',$var='$temp'+$loop_num if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='call' && ('eval'==right.tree[0].func.value || 'exec'==right.tree[0].func.value)){res+='var '+$var+' = '+right_js+';\n' rvar=$var}else if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='sub'){res+='var '+$var+' = '+right_js+';\n' rvar=$var}else{rvar=right_js} if(left.type=='attribute'){ $loop_num++ left.func='setattr' var left_to_js=left.to_js() left.func='getattr' if(left.assign_self){return res+left_to_js[0]+rvar+left_to_js[1]+rvar+')'} res+=left_to_js res=res.substr(0,res.length-1) return res+','+rvar+');_b_.None;'} if(left.type=='sub'){ var seq=left.value.to_js(),temp='$temp'+$loop_num,type if(left.value.type=='id'){type=$get_node(this).locals[left.value.value]} $loop_num++ var res='var '+temp+' = '+seq+'\n' if(type !=='list'){res+='if(Array.isArray('+temp+') && !'+ temp+'.__class__){'} if(left.tree.length==1){res+='$B.set_list_key('+temp+','+ (left.tree[0].to_js()+'' ||'null')+','+ right.to_js()+')'}else if(left.tree.length==2){res+='$B.set_list_slice('+temp+','+ (left.tree[0].to_js()+'' ||'null')+','+ (left.tree[1].to_js()+'' ||'null')+','+ right.to_js()+')'}else if(left.tree.length==3){res+='$B.set_list_slice_step('+temp+','+ (left.tree[0].to_js()+'' ||'null')+','+ (left.tree[1].to_js()+'' ||'null')+','+ (left.tree[2].to_js()+'' ||'null')+','+ right.to_js()+')'} if(type=='list'){return res} res+='\n}else{' if(left.tree.length==1){res+='$B.$setitem('+left.value.to_js()+ ','+left.tree[0].to_js()+','+right_js+')};_b_.None;'}else{left.func='setitem' res+=left.to_js() res=res.substr(0,res.length-1) left.func='getitem' res+=','+right_js+')};_b_.None;'} return res}} return left.to_js()+' = '+right.to_js()} var $AsyncCtx=$B.parser.$AsyncCtx=function(C){ this.type='async' this.parent=C C.async=true} $AsyncCtx.prototype.toString=function(){return '(async)'} $AsyncCtx.prototype.transition=function(token,value){var C=this if(token=="def"){return $transition(C.parent,token,value)}else if(token=="for" ||token=="with"){var ntype=$get_scope(C).ntype if(ntype !=="def" && ntype !="generator"){$_SyntaxError(C,["'async "+token+ "' outside async function"])} var ctx=$transition(C.parent,token,value) ctx.parent.async=true return ctx} $_SyntaxError(C,'token '+token+' after '+C)} var $AttrCtx=$B.parser.$AttrCtx=function(C){ this.type='attribute' this.value=C.tree[0] this.parent=C C.tree.pop() C.tree[C.tree.length]=this this.tree=[] this.func='getattr' } $AttrCtx.prototype.toString=function(){return '(attr) '+this.value+'.'+this.name} $AttrCtx.prototype.transition=function(token,value){var C=this if(token==='id'){var name=value if(noassign[name]===true){$_SyntaxError(C,["cannot assign to "+name])} name=$mangle(name,C) C.name=name return C.parent} $_SyntaxError(C,token)} $AttrCtx.prototype.to_js=function(){this.js_processed=true var js=this.value.to_js() if(this.func=="setattr" && this.value.type=="id"){var scope=$get_scope(this),parent=scope.parent if(scope.ntype=="def"){if(parent.ntype=="class"){var params=scope.C.tree[0].positional_list if(this.value.value==params[0]&& parent.C && parent.C.tree[0].args===undefined){ this.assign_self=true return[js+".__class__ && "+js+".__dict__ && !"+ js+".__class__.$has_setattr && ! "+js+ ".$is_class ? _b_.dict.$setitem("+js+ ".__dict__, '"+$B.from_alias(this.name)+ "', ",") : $B.$setattr("+js+ ', "'+this.name+'", ']}}}} if(this.func=='setattr'){ return '$B.$setattr('+js+',"'+this.name+'")'}else{return '$B.$getattr('+js+',"'+this.name+'")'}} var $AugmentedAssignCtx=$B.parser.$AugmentedAssignCtx=function(C,op){ check_assignment(C) this.type='augm_assign' this.C=C this.parent=C.parent C.parent.tree.pop() C.parent.tree[C.parent.tree.length]=this this.op=op this.tree=[C] var scope=this.scope=$get_scope(this) if(C.type=='expr'){var assigned=C.tree[0] if(assigned.type=='id'){var name=assigned.value if(noassign[name]===true){$_SyntaxError(C,["cannot assign to keyword"])}else if((scope.ntype=='def' ||scope.ntype=='generator')&& (scope.binding[name]===undefined)){if(scope.globals===undefined || ! scope.globals.has(name)){ assigned.unbound=true}}}else if(['str','int','float','complex'].indexOf(assigned.type)>-1){$_SyntaxError(C,["cannot assign to literal"])}} $get_node(this).bound_before=Object.keys(scope.binding) this.module=scope.module} $AugmentedAssignCtx.prototype.toString=function(){return '(augm assign) '+this.tree} $AugmentedAssignCtx.prototype.transition=function(token,value){var C=this if(token=='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+ C)} return $transition(C.parent,'eol')} $_SyntaxError(C,'token '+token+' after '+C)} $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 parent.children.splice(rank,1) var left_is_id=(this.tree[0].type=='expr' && this.tree[0].tree[0].type=='id') if(left_is_id){var left_bound_to_int= this.tree[0].tree[0].bindingType(this.scope)=="int" this.tree[0].tree[0].augm_assign=true if($B.debug > 0){var check_node=$NodeJS('if('+this.tree[0].to_js()+ ' === undefined){throw _b_.NameError.$factory("name \''+ this.tree[0].tree[0].value+'\' is not defined")}') node.parent.insert(rank,check_node) offset++} 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} var right_is_int=(this.tree[1].type=='expr' && this.tree[1].tree[0].type=='int') if(right_is_int){var value=this.tree[1].tree[0].value,to_int=parseInt(value[1],value[0]) right_is_int=(to_int > $B.min_int)&&(to_int < $B.max_int)} var right=right_is_int ? this.tree[1].tree[0].to_js():'$temp' if(!right_is_int){ var new_node=new $Node() new_node.line_num=line_num lnum_set=true new $NodeJSCtx(new_node,'var $temp,$left;') parent.insert(rank,new_node) offset++ var new_node=new $Node() new_node.id=this.scope.id var new_ctx=new $NodeCtx(new_node) var new_expr=new $ExprCtx(new_ctx,'js',false) var _id=new $RawJSCtx(new_expr,'$temp') var assign=new $AssignCtx(new_expr) assign.tree[1]=this.tree[1] _id.parent=assign parent.insert(rank+offset,new_node) offset++} var prefix='',in_class=false switch(op){case '+=': case '-=': case '*=': case '/=': if(left_is_id){var scope=this.scope,global_ns='$local_'+scope.module.replace(/\./g,'_') switch(scope.ntype){case 'module': prefix=global_ns break case 'def': case 'generator': if(scope.globals && scope.globals.has(C.tree[0].value)){prefix=global_ns}else{prefix='$locals'} break case 'class': var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num lnum_set=true} new $NodeJSCtx(new_node,'var $left = '+ C.to_js()) parent.insert(rank+offset,new_node) in_class=true offset++}}} var left=C.tree[0].to_js() if(C.tree[0].type=="id"){var binding_scope=C.tree[0].firstBindingScopeId(),left_value=C.tree[0].value if(binding_scope){left="$locals_"+binding_scope.replace(/\./g,'_')+ '["'+left_value+'"]'}else{left='$locals["'+left_value+'"]'}} if(left_bound_to_int && right_is_int && op !="//="){ parent.insert(rank+offset,$NodeJS(left+" "+op+" "+right)) return offset++} prefix=prefix && !C.tree[0].unknown_binding && !left_id_unbound var op1=op.charAt(0) if(prefix){var left1=in_class ? '$left' :left var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} js=right_is_int ? 'if(' :'if(typeof $temp.valueOf() == "number" && ' js+=left1+'.constructor === Number' js+=' && Number.isSafeInteger('+left+op1+right+')){'+ (right_is_int ? '(' :'(typeof $temp == "number" && ')+ 'typeof '+left1+' == "number") ? ' js+=left+op+right js+=' : '+left+' = new Number('+left+op1+ (right_is_int ? right :right+'.valueOf()')+')}' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset++} var aaops={'+=':'add','-=':'sub','*=':'mul'} if(C.tree[0].type=='sub' && ('+='==op ||'-='==op ||'*='==op)&& C.tree[0].tree.length==1){var js1='$B.augm_item_'+aaops[op]+'('+ C.tree[0].value.to_js()+','+ C.tree[0].tree[0].to_js()+','+right+');_b_.None;' var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} new $NodeJSCtx(new_node,js1) parent.insert(rank+offset,new_node) offset++ return} var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} var js='' if(prefix){js+='else '} js+='if(! _b_.hasattr('+C.to_js()+',"'+func+'"))' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset++ var aa1=new $Node() aa1.id=this.scope.id aa1.line_num=node.line_num new_node.add(aa1) var ctx1=new $NodeCtx(aa1) var expr1=new $ExprCtx(ctx1,'clone',false) if(left_id_unbound){new $RawJSCtx(expr1,left)}else{expr1.tree=C.tree expr1.tree.forEach(function(elt){elt.parent=expr1})} var assign1=new $AssignCtx(expr1) var new_op=new $OpCtx(expr1,op.substr(0,op.length-1)) new_op.parent=assign1 new $RawJSCtx(new_op,right) assign1.tree.push(new_op) expr1.parent.tree.pop() expr1.parent.tree.push(assign1) var else_node=$NodeJS("else") parent.insert(rank+offset,else_node) var aa2=new $Node() aa2.line_num=node.line_num else_node.add(aa2) var ctx2=new $NodeCtx(aa2) var expr2=new $ExprCtx(ctx2,'clone',false) if(left_id_unbound){var js=left if(! binding_scope){js='$B.$local_search("'+left_value+'");'+left} new $RawJSCtx(expr2,js)}else{expr2.tree=C.tree expr2.tree.forEach(function(elt){elt.parent=expr2})} var assign2=new $AssignCtx(expr2) assign2.tree.push($NodeJS('$B.$getattr('+C.to_js()+',"'+ func+'")('+right+')')) expr2.parent.tree.pop() expr2.parent.tree.push(assign2) if(left_is_id && !was_bound && !this.scope.blurred){this.scope.binding[left_id]=undefined} return offset} $AugmentedAssignCtx.prototype.to_js=function(){return ''} var $AwaitCtx=$B.parser.$AwaitCtx=function(C){ this.type='await' this.parent=C this.tree=[] C.tree.push(this) var p=C while(p){if(p.type=="list_or_tuple"){p.is_await=true} p=p.parent}} $AwaitCtx.prototype.transition=function(token,value){var C=this C.parent.is_await=true return $transition(C.parent,token,value)} $AwaitCtx.prototype.to_js=function(){return 'var save_stack = $B.save_stack();'+ 'await ($B.promise('+$to_js(this.tree)+'));'+ '$B.restore_stack(save_stack, $locals); '} var $BodyCtx=$B.parser.$BodyCtx=function(C){ var ctx_node=C.parent while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var body_node=new $Node() body_node.is_body_node=true body_node.line_num=tree_node.line_num tree_node.insert(0,body_node) return new $NodeCtx(body_node)} var set_loop_context=$B.parser.set_loop_context=function(C,kw){ var ctx_node=C while(ctx_node.type !=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var loop_node=tree_node.parent var break_flag=false while(1){if(loop_node.type=='module'){ $_SyntaxError(C,kw+' outside of a loop')}else{var ctx=loop_node.C.tree[0] if(ctx.type=='condition' && ctx.token=='while'){this.loop_ctx=ctx ctx['has_'+kw]=true break} switch(ctx.type){case 'for': this.loop_ctx=ctx ctx['has_'+kw]=true break_flag=true break case 'def': case 'generator': case 'class': $_SyntaxError(C,kw+' outside of a loop') default: loop_node=loop_node.parent} if(break_flag){break}}}} var $BreakCtx=$B.parser.$BreakCtx=function(C){ this.type='break' this.parent=C C.tree[C.tree.length]=this set_loop_context.apply(this,[C,'break'])} $BreakCtx.prototype.toString=function(){return 'break '} $BreakCtx.prototype.transition=function(token,value){var C=this if(token=='eol'){return $transition(C.parent,'eol')} $_SyntaxError(C,token)} $BreakCtx.prototype.to_js=function(){this.js_processed=true var scope=$get_scope(this) var res=';$locals_'+scope.id.replace(/\./g,'_')+ '["$no_break'+this.loop_ctx.loop_num+'"] = false' if(this.loop_ctx.type !='asyncfor'){res+=';break'}else{res+=';throw _b_.StopIteration.$factory('+ this.loop_ctx.loop_num+')'} return res} var $CallArgCtx=$B.parser.$CallArgCtx=function(C){ this.type='call_arg' this.parent=C this.start=$pos this.tree=[] C.tree.push(this) this.expect='id'} $CallArgCtx.prototype.toString=function(){return 'call_arg '+this.tree} $CallArgCtx.prototype.transition=function(token,value){var C=this switch(token){case 'await': case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': if(C.expect=='id'){C.expect=',' var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,value)} break case '=': if(C.expect==','){return new $ExprCtx(new $KwArgCtx(C),'kw_value',false)} break case 'for': if(this.parent.tree.length > 1){$_SyntaxError(C,"non-parenthesized generator expression")} var lst=new $ListOrTupleCtx(C,'gen_expr') lst.vars=C.vars lst.locals=C.locals lst.intervals=[C.start] C.tree.pop() lst.expression=C.tree C.tree=[lst] lst.tree=[] var comp=new $ComprehensionCtx(lst) return new $TargetListCtx(new $CompForCtx(comp)) case 'op': if(C.expect=='id'){var op=value C.expect=',' switch(op){case '+': case '-': case '~': return $transition(new $AbstractExprCtx(C,false),token,op) case '*': return new $StarArgCtx(C) case '**': return new $DoubleStarArgCtx(C)}} $_SyntaxError(C,'token '+token+' after '+C) case ')': if(C.parent.kwargs && $B.last(C.parent.tree).tree[0]&& ['kwarg','star_arg','double_star_arg']. indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword argument after keyword argument'])} if(C.tree.length > 0){var son=C.tree[C.tree.length-1] if(son.type=='list_or_tuple' && son.real=='gen_expr'){son.intervals.push($pos)}} return $transition(C.parent,token) case ':': if(C.expect==',' && C.parent.parent.type=='lambda'){return $transition(C.parent.parent,token)} break case ',': if(C.expect==','){if(C.parent.kwargs && ['kwarg','star_arg','double_star_arg']. indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword argument after keyword argument'])} return $transition(C.parent,token,value)}} $_SyntaxError(C,'token '+token+' after '+C)} $CallArgCtx.prototype.to_js=function(){this.js_processed=true return $to_js(this.tree)} var $CallCtx=$B.parser.$CallCtx=function(C){ this.type='call' this.func=C.tree[0] if(this.func !==undefined){ this.func.parent=this} this.parent=C if(C.type !='class'){C.tree.pop() C.tree[C.tree.length]=this}else{ C.args=this} this.expect='id' this.tree=[] this.start=$pos if(this.func && this.func.type=="attribute" && this.func.name=="wait" && this.func.value.type=="id" && this.func.value.value=="time"){console.log('call',this.func) $get_node(this).blocking={'type':'wait','call':this}} if(this.func && this.func.value=='input'){$get_node(this).blocking={'type':'input'}}} $CallCtx.prototype.toString=function(){return '(call) '+this.func+'('+this.tree+')'} $CallCtx.prototype.transition=function(token,value){var C=this switch(token){case ',': if(C.expect=='id'){$_SyntaxError(C,token)} C.expect='id' return C case 'await': case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': C.expect=',' return $transition(new $CallArgCtx(C),token,value) case ')': C.end=$pos return C.parent case 'op': C.expect=',' switch(value){case '-': case '~': case '+': C.expect=',' return $transition(new $CallArgCtx(C),token,value) case '*': C.has_star=true return new $StarArgCtx(C) case '**': C.has_dstar=true return new $DoubleStarArgCtx(C)} $_SyntaxError(C,token) case 'yield': $_SyntaxError(C,token)} return $transition(C.parent,token,value)} $CallCtx.prototype.to_js=function(){this.js_processed=true if(this.tree.length > 0){if(this.tree[this.tree.length-1].tree.length==0){ this.tree.pop()}} var func_js=this.func.to_js() if(this.func !==undefined){switch(this.func.value){case 'classmethod': return '_b_.classmethod.$factory('+$to_js(this.tree)+')' default: if(this.func.type=='unary'){ var res='$B.$getattr('+$to_js(this.tree) switch(this.func.op){case '+': return res+',"__pos__")()' case '-': return res+',"__neg__")()' case '~': return res+',"__invert__")()'}}} var _block=false var positional=[],kw_args=[],star_args=false,dstar_args=[] this.tree.forEach(function(arg){var type switch(arg.type){case 'star_arg': star_args=true positional.push([arg.tree[0].tree[0].to_js(),'*']) break case 'double_star_arg': dstar_args.push(arg.tree[0].tree[0].to_js()) break case 'id': positional.push([arg.to_js(),'s']) break default: type=arg.tree[0].type switch(type){case 'expr': positional.push([arg.to_js(),'s']) break case 'kwarg': kw_args.push(arg.tree[0].tree[0].value+ ':'+arg.tree[0].tree[1].to_js()) break case 'list_or_tuple': case 'op': positional.push([arg.to_js(),'s']) break case 'star_arg': star_args=true positional.push([arg.tree[0].tree[0].to_js(),'*']) break case 'double_star_arg': dstar_args.push(arg.tree[0].tree[0].to_js()) break default: positional.push([arg.to_js(),'s']) break} break}}) var args_str if(star_args){ var p=[] for(var i=0,len=positional.length;i < len;i++){arg=positional[i] if(arg[1]=='*'){ p.push('_b_.list.$factory('+arg[0]+')')}else{var elt=[positional[i][0]] i++ while(i < len && positional[i][1]=='s'){elt.push(positional[i][0]) i++} i-- p.push('['+elt.join(',')+']')}} args_str=p[0] 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]} args_str=positional.join(', ')} var kw_args_str='{'+kw_args.join(', ')+'}' if(dstar_args.length){kw_args_str='{$nat:"kw",kw:['+kw_args_str+','+ dstar_args.join(', ')+']}'}else if(kw_args_str !='{}'){kw_args_str='{$nat:"kw",kw:'+kw_args_str+'}'}else{kw_args_str=''} if(star_args && kw_args_str){args_str+='.concat(['+kw_args_str+'])'}else{if(args_str && kw_args_str){args_str+=','+kw_args_str} else if(!args_str){args_str=kw_args_str}} if(star_args){ args_str='.apply(null,'+args_str+')'}else{args_str='('+args_str+')'} var default_res="$B.$call("+func_js+")"+args_str if(this.tree.length >-1 && this.func.type=='id' && this.func.is_builtin){ 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"] if($B.builtin_funcs[this.func.value]!==undefined){if(classes.indexOf(this.func.value)==-1){ return func_js+args_str}else{ return func_js+".$factory"+args_str}}} return default_res}} var $CaseCtx=$B.parser.$CaseCtx=function(node_ctx){ this.type="case" node_ctx.tree=[this] this.parent=node_ctx this.tree=[] this.expect='as'} $CaseCtx.prototype.set_alias=function(name){this.alias=name} $CaseCtx.prototype.transition=function(token,value){var C=this console.log('transition on case',token,value) switch(token){case 'as': return new $AbstractExprCtx(new $AliasCtx(C)) case ':': switch(C.expect){case 'id': case 'as': case ':': return $BodyCtx(C)} break}} $CaseCtx.prototype.to_js=function(){console.log('to js',this) return 'if(subject == '+$to_js(this.tree)+')'} var $ClassCtx=$B.parser.$ClassCtx=function(C){ this.type='class' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.expect='id' var scope=this.scope=$get_scope(this) this.parent.node.parent_block=scope this.parent.node.bound={} this.parent.node.binding={__annotations__:true}} $ClassCtx.prototype.toString=function(){return '(class) '+this.name+' '+this.tree+' args '+this.args} $ClassCtx.prototype.transition=function(token,value){var C=this switch(token){case 'id': if(C.expect=='id'){C.set_name(value) C.expect='(:' return C} break case '(': return new $CallCtx(C) case ':': return $BodyCtx(C)} $_SyntaxError(C,'token '+token+' after '+C)} $ClassCtx.prototype.set_name=function(name){var C=this.parent this.random=$B.UUID() this.name=name this.id=C.node.module+'_'+name+'_'+this.random this.binding={} this.parent.node.id=this.id var scope=this.scope,parent_block=scope var block=scope,parent_classes=[] while(block.ntype=="class"){parent_classes.splice(0,0,block.C.tree[0].name) block=block.parent} this.qualname=parent_classes.concat([name]).join(".") while(parent_block.C && parent_block.C.tree[0].type=='class'){parent_block=parent_block.parent} while(parent_block.C && 'def' !=parent_block.C.tree[0].type && 'generator' !=parent_block.C.tree[0].type){parent_block=parent_block.parent} this.parent.node.parent_block=parent_block $bind(name,scope,this) if(scope.is_function){if(scope.C.tree[0].locals.indexOf(name)==-1){scope.C.tree[0].locals.push(name)}}} $ClassCtx.prototype.transform=function(node,rank){ this.doc_string=$get_docstring(node) this.module=$get_module(this).module.replace(/\./g,'_') var indent='\n'+' '.repeat(node.indent+12),instance_decl=new $Node(),local_ns='$locals_'+this.id.replace(/\./g,'_'),js='var '+local_ns+' = {'+ '__annotations__: $B.empty_dict()}, '+ indent+'$locals = '+local_ns new $NodeJSCtx(instance_decl,js) node.insert(0,instance_decl) var global_scope=this.scope while(global_scope.parent_block.id !=='__builtins__'){global_scope=global_scope.parent_block} var global_ns='$locals_'+global_scope.id.replace(/\./g,'_') var js=' '.repeat(node.indent+4)+ '$locals.$name = "'+this.name+'"'+indent+ '$locals.$qualname = "'+this.qualname+'"'+indent+ '$locals.$is_class = true; '+indent+ '$locals.$line_info = "'+node.line_num+','+ this.module+'";'+indent+ 'var $top_frame = ["'+local_ns+'", $locals,'+'"'+ global_scope.id+'", '+global_ns+']'+ indent+'$locals.$f_trace = $B.enter_frame($top_frame);'+