// brython.js brython.info // version [3, 14, 0, 'final', 0] // implementation [3, 14, 0, 'dev', 0] // version compiled from commented, indented source files at // github.com/brython-dev/brython var __BRYTHON__=globalThis.__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') &&(process.__nwjs !==1) var _window=globalThis; _window.location ||={href:'',origin:'',pathname:''}; _window.navigator ||={userLanguage:''} _window.document ||={getElementsByTagName:()=>[{src:"http://localhost/"}], currentScript:{src:"http://localhost/"}, querySelectorAll:()=>[]} _window.HTMLElement ||=class HTMLElement{}; _window.MutationObserver ||=function(){this.observe=()=>{};}; _window.customElements ||={define:()=>{}}; var href=_window.location.href $B.protocol=href.split(':')[0] $B.BigInt=_window.BigInt $B.indexedDB=_window.indexedDB 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{this_url=document.currentScript.src} var elts=this_url.split('/'); elts.pop() $B.brython_path=elts.join('/')+'/'}else{if(! $B.brython_path.endsWith("/")){$B.brython_path+="/"}} var parts_re=new RegExp('(.*?)://(.*?)/(.*)'),mo=parts_re.exec($B.brython_path) if(mo){$B.full_url={protocol:mo[1],host:mo[2],address:mo[3]} if(['http','https'].includes(mo[1])){$B.domain=mo[1]+'://'+mo[2]}} var path=_window.location.origin+_window.location.pathname,path_elts=path.split("/") path_elts.pop() $B.script_dir=path_elts.join("/") mo=parts_re.exec($B.script_dir) if(mo){if(['http','https'].includes(mo[1])){$B.script_domain=mo[1]+'://'+mo[2]}}else{var parts_re_root=new RegExp('(.*?)://(.*?)'),mo=parts_re_root.exec($B.script_dir) if(mo &&['http','https'].includes(mo[1])){ $B.script_domain=$B.script_dir}} $B.strip_host=function(url){try{var parsed_url=new URL(url) return parsed_url.pathname.substr(1)+parsed_url.search+ parsed_url.hash}catch{console.log(Error().stack) throw Error("not a url: "+url)}} var href=$B.script_path=_window.location.href.split('#')[0],href_elts=href.split('/') href_elts.pop() if($B.isWebWorker ||$B.isNode){href_elts.pop()} $B.curdir=href_elts.join('/') $B.webworkers={} $B.file_cache={} $B.url2name={} $B.scripts={} $B.import_info={} $B.imported={} $B.precompiled={} $B.frame_obj=null $B.builtins=Object.create(null) $B.builtins_scope={id:'__builtins__',module:'__builtins__',binding:{}} $B.language=_window.navigator.userLanguage ||_window.navigator.language $B.locale="C" var date=new Date() var formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:'short'}),short=formatter.format(date) formatter=new Intl.DateTimeFormat($B.language,{timeZoneName:'long'}) var long=formatter.format(date) var ix=0,minlen=Math.min(short.length,long.length) while(ix < minlen && short[ix]==long[ix]){ix++} $B.tz_name=long.substr(ix).trim() $B.PyCF_ONLY_AST=1024 $B.PyCF_TYPE_COMMENTS=0x1000 $B.CO_FUTURE_ANNOTATIONS=0x1000000 $B.PyCF_ALLOW_INCOMPLETE_INPUT=0x4000 $B.COMPILER_FLAGS={OPTIMIZED:1,NEWLOCALS:2,VARARGS:4,VARKEYWORDS:8,NESTED:16,GENERATOR:32,NOFREE:64,COROUTINE:128,ITERABLE_COROUTINE:256,ASYNC_GENERATOR:512} var DEF_GLOBAL=1, DEF_LOCAL=2 , DEF_PARAM=2 << 1, DEF_NONLOCAL=2 << 2, USE=2 << 3 , DEF_FREE=2 << 4 , DEF_FREE_CLASS=2 << 5, DEF_IMPORT=2 << 6, DEF_ANNOT=2 << 7, DEF_COMP_ITER=2 << 8, DEF_TYPE_PARAM=2 << 9, DEF_COMP_CELL=2 << 10 var DEF_BOUND=DEF_LOCAL |DEF_PARAM |DEF_IMPORT var SCOPE_OFFSET=12,SCOPE_OFF=SCOPE_OFFSET,SCOPE_MASK=(DEF_GLOBAL |DEF_LOCAL |DEF_PARAM |DEF_NONLOCAL) var LOCAL=1,GLOBAL_EXPLICIT=2,GLOBAL_IMPLICIT=3,FREE=4,CELL=5 var TYPE_CLASS=1,TYPE_FUNCTION=0,TYPE_MODULE=2 $B.SYMBOL_FLAGS={DEF_GLOBAL, DEF_LOCAL, DEF_PARAM, DEF_NONLOCAL, USE, DEF_FREE, DEF_FREE_CLASS, DEF_IMPORT, DEF_ANNOT, DEF_COMP_ITER, DEF_TYPE_PARAM, DEF_COMP_CELL, DEF_BOUND,SCOPE_OFFSET,SCOPE_OFF,SCOPE_MASK,LOCAL,GLOBAL_EXPLICIT,GLOBAL_IMPLICIT,FREE,CELL,TYPE_CLASS,TYPE_FUNCTION,TYPE_MODULE} $B.max_int=Math.pow(2,53)-1 $B.min_int=-$B.max_int $B.int_max_str_digits=4300 $B.str_digits_check_threshold=640 $B.max_array_size=2**32-1 $B.recursion_limit=900 $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"},subset:function(){var res={},keys=[] if(arguments[0]=="all"){keys=Object.keys($B.op2method) keys.splice(keys.indexOf("subset"),1)}else{for(var arg of arguments){keys.push(arg)}} for(var key of keys){var ops=$B.op2method[key] if(ops===undefined){throw Error(key)} for(var attr in ops){res[attr]=ops[attr]}} return res}} $B.method_to_op={} for(var category in $B.op2method){for(var op in $B.op2method[category]){var method=`__${$B.op2method[category][op]}__` $B.method_to_op[method]=op}} $B.special_string_repr={8:"\\x08",9:"\\t",10:"\\n",11:"\\x0b",12:"\\x0c",13:"\\r",92:"\\\\",160:"\\xa0"} $B.$py_next_hash=Math.pow(2,53)-1 $B.$py_UUID=Math.floor(Math.random()*2**50) $B.lambda_magic=Math.random().toString(36).substr(2,8) const func_attrs=['__module__','__name__','__qualname__','__file__','__defaults__','__kwdefaults__','__doc__','arg_names','args_vararg','args_kwarg','positional_length','lineno','flags','free_vars','kwonlyargs_length','posonlyargs_length','varnames','__annotations__','__type_params__','method_class' ] var i=0 $B.func_attrs={} for(var func_attr of func_attrs){$B.func_attrs[func_attr]=i++} $B.set_func_names=function(klass,module){klass.__module__=module for(var attr in klass){if(typeof klass[attr]=='function'){$B.add_function_infos(klass,attr)}}} $B.add_function_infos=function(klass,attr){var module=klass.__module__ $B.set_function_infos(klass[attr],{__doc__:klass[attr].__doc__ ||'',__module__:module,__name__:attr,__qualname__ :klass.__qualname__+'.'+attr,__defaults__:[],__kwdefaults__:{}} ) if(klass[attr].$type=="classmethod"){klass[attr].__class__=$B.method}} $B.set_function_infos=function(f,attrs){f.$function_infos=f.$function_infos ??[] for(var key in attrs){if($B.func_attrs[key]===undefined){throw Error('no function attribute '+key)} f.$function_infos[$B.func_attrs[key]]=attrs[key]}} $B.set_function_attr=function(func,attr,value){if($B.func_attrs[attr]===undefined){throw Error('no function attribute '+attr)} func.$function_infos[$B.func_attrs[attr]]=value} 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.frame_obj.frame[3]} $B.$options={} $B.builtins_repr_check=function(builtin,args){ var $=$B.args('__repr__',1,{self:null},['self'],args,{},null,null),self=$.self if(! $B.$isinstance(self,builtin)){var _b_=$B.builtins $B.RAISE(_b_.TypeError,"descriptor '__repr__' requires a "+ `'${builtin.__name__}' object but received a `+ `'${$B.class_name(self)}'`)}} $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.stdlib_module_names=Object.keys($B.VFS)} $B.loadBrythonPackage=function(brythonPackage){$B.use_VFS=true $B.update_VFS(brythonPackage)} $B.add_files=function(files){ $B.files=$B.files ||{} for(var file in files){$B.files[file]=files[file]}} $B.has_file=function(file){ return($B.files && $B.files.hasOwnProperty(file))} $B.show_tokens=function(src,mode){ for(var token of $B.tokenizer(src,'',mode ||'file')){console.log(token.type,$B.builtins.repr(token.string),`[${token.lineno}.${token.col_offset}-`+ `${token.end_lineno}.${token.end_col_offset}]`,token.line)}} function from_py(src,script_id){if(! $B.options_parsed){ $B.parse_options()} script_id=script_id ||'python_script_'+$B.UUID() var filename=$B.script_path+'#'+script_id $B.url2name[filename]=script_id $B.imported[script_id]={} var root=__BRYTHON__.py2js({src,filename},script_id,script_id,__BRYTHON__.builtins_scope) return root.to_js()} $B.pythonToAST=function(python_code,filename,mode){let parser=new $B.Parser(python_code,filename ?? 'test',mode ?? 'file') return $B._PyPegen.run_parser(parser)} $B.python_to_js=function(src,script_id){ return "(function() {\n"+from_py(src,script_id)+"\nreturn locals}())"} $B.pythonToJS=$B.python_to_js var fakeScript=$B.fakeScript=function(filename){this.options={}} fakeScript.prototype.getAttribute=function(key){return this.options[key]?? null} fakeScript.prototype.dispatchEvent=function(){} $B.runPythonSource=function(src,options){var script_id if(options){if(typeof options=='string'){script_id=options}else if(options.constructor===Object){if(options.hasOwnProperty('id')){script_id=options.id delete options.id}}else{console.debug('invalid options argument:',options)}} var script=new fakeScript(),url=$B.script_path=globalThis.location.href.split('#')[0] if(options){for(var[key,value]of Object.entries(options)){script.options[key]=value}} script_id=script_id ?? 'python_script_'+$B.UUID() $B.run_script(script,src,script_id,url,true) return $B.imported[script_id]} $B.getPythonModule=function(name){return $B.imported[name]} $B.importPythonModule=function(name,options){return $B.runPythonSource('import '+name,options)} $B.importModule=function(name,options){if(! $B.imported.hasOwnProperty(name)){$B.runPythonSource('import '+name,options)} return $B.imported[name]}})(__BRYTHON__); ; __BRYTHON__.ast_classes={Add:'',And:'',AnnAssign:'target,annotation,value?,simple',Assert:'test,msg?',Assign:'targets*,value,type_comment?',AsyncFor:'target,iter,body*,orelse*,type_comment?',AsyncFunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?,type_params*',AsyncWith:'items*,body*,type_comment?',Attribute:'value,attr,ctx',AugAssign:'target,op,value',Await:'value',BinOp:'left,op,right',BitAnd:'',BitOr:'',BitXor:'',BoolOp:'op,values*',Break:'',Call:'func,args*,keywords*',ClassDef:'name,bases*,keywords*,body*,decorator_list*,type_params*',Compare:'left,ops*,comparators*',Constant:'value,kind?',Continue:'',Del:'',Delete:'targets*',Dict:'keys*,values*',DictComp:'key,value,generators*',Div:'',Eq:'',ExceptHandler:'type?,name?,body*',Expr:'value',Expression:'body',FloorDiv:'',For:'target,iter,body*,orelse*,type_comment?',FormattedValue:'value,conversion,format_spec?',FunctionDef:'name,args,body*,decorator_list*,returns?,type_comment?,type_params*',FunctionType:'argtypes*,returns',GeneratorExp:'elt,generators*',Global:'names*',Gt:'',GtE:'',If:'test,body*,orelse*',IfExp:'test,body,orelse',Import:'names*',ImportFrom:'module?,names*,level?',In:'',Interactive:'body*',Interpolation:'value,str,conversion,format_spec?',Invert:'',Is:'',IsNot:'',JoinedStr:'values*',LShift:'',Lambda:'args,body',List:'elts*,ctx',ListComp:'elt,generators*',Load:'',Lt:'',LtE:'',MatMult:'',Match:'subject,cases*',MatchAs:'pattern?,name?',MatchClass:'cls,patterns*,kwd_attrs*,kwd_patterns*',MatchMapping:'keys*,patterns*,rest?',MatchOr:'patterns*',MatchSequence:'patterns*',MatchSingleton:'value',MatchStar:'name?',MatchValue:'value',Mod:'',Module:'body*,type_ignores*',Mult:'',Name:'id,ctx',NamedExpr:'target,value',Nonlocal:'names*',Not:'',NotEq:'',NotIn:'',Or:'',ParamSpec:'name,default_value?',Pass:'',Pow:'',RShift:'',Raise:'exc?,cause?',Return:'value?',Set:'elts*',SetComp:'elt,generators*',Slice:'lower?,upper?,step?',Starred:'value,ctx',Store:'',Sub:'',Subscript:'value,slice,ctx',TemplateStr:'values*',Try:'body*,handlers*,orelse*,finalbody*',TryStar:'body*,handlers*,orelse*,finalbody*',Tuple:'elts*,ctx',TypeAlias:'name,type_params*,value',TypeIgnore:'lineno,tag',TypeVar:'name,bound?,default_value?',TypeVarTuple:'name,default_value?',UAdd:'',USub:'',UnaryOp:'op,operand',While:'test,body*,orelse*',With:'items*,body*,type_comment?',Yield:'value?',YieldFrom:'value',alias:'name,asname?',arg:'arg,annotation?,type_comment?',arguments:'posonlyargs*,args*,vararg?,kwonlyargs*,kw_defaults*,kwarg?,defaults*',boolop:['And','Or'],cmpop:['Eq','NotEq','Lt','LtE','Gt','GtE','Is','IsNot','In','NotIn'],comprehension:'target,iter,ifs*,is_async',excepthandler:['ExceptHandler'],expr:['BoolOp','NamedExpr','BinOp','UnaryOp','Lambda','IfExp','Dict','Set','ListComp','SetComp','DictComp','GeneratorExp','Await','Yield','YieldFrom','Compare','Call','FormattedValue','Interpolation','JoinedStr','TemplateStr','Constant','Attribute','Subscript','Starred','Name','List','Tuple','Slice'],expr_context:['Load','Store','Del'],keyword:'arg?,value',match_case:'pattern,guard?,body*',mod:['Module','Interactive','Expression','FunctionType'],operator:['Add','Sub','Mult','MatMult','Div','Mod','Pow','LShift','RShift','BitOr','BitXor','BitAnd','FloorDiv'],pattern:['MatchValue','MatchSingleton','MatchSequence','MatchMapping','MatchClass','MatchStar','MatchAs','MatchOr'],stmt:['FunctionDef','AsyncFunctionDef','ClassDef','Return','Delete','Assign','TypeAlias','AugAssign','AnnAssign','For','AsyncFor','While','If','With','AsyncWith','Match','Raise','Try','TryStar','Assert','Import','ImportFrom','Global','Nonlocal','Expr','Pass','Break','Continue'],type_ignore:['TypeIgnore'],type_param:['TypeVar','ParamSpec','TypeVarTuple'],unaryop:['Invert','Not','UAdd','USub'],withitem:'context_expr,optional_vars?'} ; ;(function($B){$B.stdlib={} var pylist=['VFS_import','__future__','_aio','_ast_unparse','_codecs','_codecs_jp','_collections','_collections_abc','_colorize','_compat_pickle','_compression','_contextvars','_csv','_dummy_thread','_frozen_importlib','_functools','_imp','_io','_markupbase','_multibytecodec','_opcode','_operator','_py_abc','_py_warnings','_pydatetime','_pydecimal','_pyio','_queue','_signal','_socket','_sre','_strptime','_struct','_sysconfigdata','_sysconfigdata_0_brython_','_testcapi','_thread','_threading_local','_typing','_weakref','_weakrefset','abc','annotationlib','antigravity','argparse','ast','asyncio','atexit','base64','bdb','binascii','bisect','browser.ajax','browser.highlight','browser.idbcache','browser.indexed_db','browser.local_storage','browser.markdown','browser.object_storage','browser.session_storage','browser.svg','browser.template','browser.timer','browser.ui','browser.webcomponent','browser.websocket','browser.worker','calendar','cmath','cmd','code','codecs','codeop','colorsys','configparser','contextlib','contextvars','copy','copyreg','csv','dataclasses','datetime','decimal','difflib','doctest','enum','errno','external_import','faulthandler','fnmatch','formatter','fractions','functools','gc','genericpath','getopt','getpass','gettext','glob','gzip','heapq','hmac','imp','inspect','interpreter','io','ipaddress','itertools','keyword','linecache','locale','mimetypes','ntpath','numbers','opcode','operator','optparse','os','pathlib','pdb','pickle','pkgutil','platform','posixpath','pprint','profile','pwd','py_compile','pyclbr','pydoc','queue','quopri','random','re','re1','reprlib','rlcompleter','secrets','select','selectors','shlex','shutil','signal','site','site-packages.__future__','site-packages.docs','site-packages.header','site-packages.test_sp','socket','sre_compile','sre_constants','sre_parse','stat','statistics','string','stringprep','struct','subprocess','symtable','sys','sysconfig','tabnanny','tarfile','tb','tempfile','test.namespace_pkgs.module_and_namespace_package.a_test','textwrap','this','threading','time','timeit','token','tokenize','traceback','turtle','types','typing','uuid','warnings','weakref','webbrowser','zipfile','zipimport','zlib'] for(var i=0;i < pylist.length;i++){$B.stdlib[pylist[i]]=['py']} var js=['_ajax','_ast','_base64','_binascii','_io_classes','_json','_jsre','_locale','_multiprocessing','_posixsubprocess','_profile','_random','_sre','_sre_utils','_string','_svg','_symtable','_tokenize','_webcomponent','_webworker','_zlib_utils','aes','array','builtins','dis','encoding_cp932','hashlib','hmac-md5','hmac-ripemd160','hmac-sha1','hmac-sha224','hmac-sha256','hmac-sha3','hmac-sha384','hmac-sha512','html_parser','marshal','math','md5','modulefinder','pbkdf2','posix','pyexpat','python_re','rabbit','rabbit-legacy','rc4','ripemd160','sha1','sha224','sha256','sha3','sha384','sha512','tripledes','unicodedata','xml_helpers','xml_parser'] for(var i=0;i < js.length;i++){$B.stdlib[js[i]]=['js']} var pkglist=['_pyrepl','browser','browser.widgets','collections','compression','compression._common','compression.zstd','concurrent','concurrent.futures','email','email.mime','encodings','html','http','importlib','importlib.metadata','importlib.resources','json','logging','multiprocessing','multiprocessing.dummy','pyexpat_utils','site-packages.foobar','site-packages.simpleaio','site-packages.ui','test','test.encoded_modules','test.leakers','test.namespace_pkgs.not_a_namespace_pkg.foo','test.support','test.support._hypothesis_stubs','test.test_email','test.test_importlib','test.test_importlib.builtin','test.test_importlib.extension','test.test_importlib.frozen','test.test_importlib.import_','test.test_importlib.source','test.test_json','test.tracedmodules','unittest','unittest.test','unittest.test.testmock','urllib'] for(var i=0;i < pkglist.length;i++){$B.stdlib[pkglist[i]]=['py',true]} $B.stdlib_module_names=Object.keys($B.stdlib)})(__BRYTHON__); ; var $B=__BRYTHON__ $B.unicode={"No_digits":[178,179,185,[4969,9],6618,8304,[8308,6],[8320,10],[9312,9],[9332,9],[9352,9],9450,[9461,9],9471,[10102,9],[10112,9],[10122,9],[68160,4],[69216,9],[69714,9],[127232,11]],"Lo_numeric":[13317,13443,14378,15181,19968,19971,19975,19977,20004,20061,20108,20116,20118,20140,20159,20160,20191,20200,20237,20336,20457,20486,20740,20806,[20841,3,2],21313,[21315,3],21324,[21441,4],22235,22769,22777,24186,24318,24319,[24332,3],24336,25296,25342,25420,26578,27934,28422,29590,30334,30357,31213,32902,33836,36014,36019,36144,37390,38057,38433,38470,38476,38520,38646,63851,63859,63864,63922,63953,63955,63997,131073,131172,131298,131361,133418,133507,133516,133532,133866,133885,133913,140176,141720,146203,156269,194704]} $B.digits_starts=[48,1632,1776,1984,2406,2534,2662,2790,2918,3046,3174,3302,3430,3558,3664,3792,3872,4160,4240,6112,6160,6470,6608,6784,6800,6992,7088,7232,7248,42528,43216,43264,43472,43504,43600,44016,65296,66720,68912,68928,69734,69872,69942,70096,70384,70736,70864,71248,71360,71376,71386,71472,71904,72016,72688,72784,73040,73120,73184,73552,90416,92768,92864,93008,93552,118000,120782,120792,120802,120812,120822,123200,123632,124144,124401,125264,130032] $B.unicode_casefold={223:[115,115],304:[105,775],329:[700,110],496:[106,780],912:[953,776,769],944:[965,776,769],1415:[1381,1410],7830:[104,817],7831:[116,776],7832:[119,778],7833:[121,778],7834:[97,702],7838:[223],8016:[965,787],8018:[965,787,768],8020:[965,787,769],8022:[965,787,834],8064:[7936,953],8065:[7937,953],8066:[7938,953],8067:[7939,953],8068:[7940,953],8069:[7941,953],8070:[7942,953],8071:[7943,953],8072:[8064],8073:[8065],8074:[8066],8075:[8067],8076:[8068],8077:[8069],8078:[8070],8079:[8071],8080:[7968,953],8081:[7969,953],8082:[7970,953],8083:[7971,953],8084:[7972,953],8085:[7973,953],8086:[7974,953],8087:[7975,953],8088:[8080],8089:[8081],8090:[8082],8091:[8083],8092:[8084],8093:[8085],8094:[8086],8095:[8087],8096:[8032,953],8097:[8033,953],8098:[8034,953],8099:[8035,953],8100:[8036,953],8101:[8037,953],8102:[8038,953],8103:[8039,953],8104:[8096],8105:[8097],8106:[8098],8107:[8099],8108:[8100],8109:[8101],8110:[8102],8111:[8103],8114:[8048,953],8115:[945,953],8116:[940,953],8118:[945,834],8119:[945,834,953],8124:[8115],8130:[8052,953],8131:[951,953],8132:[942,953],8134:[951,834],8135:[951,834,953],8140:[8131],8146:[953,776,768],8147:[912],8150:[953,834],8151:[953,776,834],8162:[965,776,768],8163:[944],8164:[961,787],8166:[965,834],8167:[965,776,834],8178:[8060,953],8179:[969,953],8180:[974,953],8182:[969,834],8183:[969,834,953],8188:[8179],64256:[102,102],64257:[102,105],64258:[102,108],64259:[102,102,105],64260:[102,102,108],64261:[64262],64262:[115,116],64275:[1396,1398],64276:[1396,1381],64277:[1396,1387],64278:[1406,1398],64279:[1396,1389]} $B.unicode_bidi_whitespace=[9,10,11,12,13,28,29,30,31,32,133,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8287,12288] ; __BRYTHON__.implementation=[3,14,0,'dev',0] __BRYTHON__.version_info=[3,14,0,'final',0] __BRYTHON__.compiled_date="2026-01-25 08:24:08.349361" __BRYTHON__.timestamp=1769325848348 __BRYTHON__.builtin_module_names=["_ajax","_ast","_base64","_binascii","_io_classes","_json","_jsre","_locale","_multiprocessing","_posixsubprocess","_profile","_random","_sre","_sre_utils","_string","_svg","_symtable","_tokenize","_webcomponent","_webworker","_zlib_utils","_zlib_utils1","_zlib_utils_kozh","array","builtins","dis","encoding_cp932","encoding_cp932_v2","hashlib","html_parser","marshal","math","modulefinder","posix","pyexpat","python_re","python_re_new","unicodedata","xml_helpers","xml_parser","xml_parser_backup"]; ; (function($B){const tokens=['ENDMARKER','NAME','NUMBER','STRING','NEWLINE','INDENT','DEDENT','LPAR','RPAR','LSQB','RSQB','COLON','COMMA','SEMI','PLUS','MINUS','STAR','SLASH','VBAR','AMPER','LESS','GREATER','EQUAL','DOT','PERCENT','LBRACE','RBRACE','EQEQUAL','NOTEQUAL','LESSEQUAL','GREATEREQUAL','TILDE','CIRCUMFLEX','LEFTSHIFT','RIGHTSHIFT','DOUBLESTAR','PLUSEQUAL','MINEQUAL','STAREQUAL','SLASHEQUAL','PERCENTEQUAL','AMPEREQUAL','VBAREQUAL','CIRCUMFLEXEQUAL','LEFTSHIFTEQUAL','RIGHTSHIFTEQUAL','DOUBLESTAREQUAL','DOUBLESLASH','DOUBLESLASHEQUAL','AT','ATEQUAL','RARROW','ELLIPSIS','COLONEQUAL','EXCLAMATION','OP','TYPE_IGNORE','TYPE_COMMENT','SOFT_KEYWORD','FSTRING_START','FSTRING_MIDDLE','FSTRING_END','TSTRING_START','TSTRING_MIDDLE','TSTRING_END','COMMENT','NL', 'ERRORTOKEN','ENCODING','N_TOKENS' ] $B.py_tokens={} var pos=0 for(var tok of tokens){$B.py_tokens[tok]=pos++} $B.py_tokens['NT_OFFSET']=256 $B.EXACT_TOKEN_TYPES={'!':'EXCLAMATION','!=':'NOTEQUAL','%':'PERCENT','%=':'PERCENTEQUAL','&':'AMPER','&=':'AMPEREQUAL','(':'LPAR',')':'RPAR','*':'STAR','**':'DOUBLESTAR','**=':'DOUBLESTAREQUAL','*=':'STAREQUAL','+':'PLUS','+=':'PLUSEQUAL',',':'COMMA','-':'MINUS','-=':'MINEQUAL','->':'RARROW','.':'DOT','...':'ELLIPSIS','/':'SLASH','//':'DOUBLESLASH','//=':'DOUBLESLASHEQUAL','/=':'SLASHEQUAL',':':'COLON',':=':'COLONEQUAL',';':'SEMI','<':'LESS','<<':'LEFTSHIFT','<<=':'LEFTSHIFTEQUAL','<=':'LESSEQUAL','=':'EQUAL','==':'EQEQUAL','>':'GREATER','>=':'GREATEREQUAL','>>':'RIGHTSHIFT','>>=':'RIGHTSHIFTEQUAL','@':'AT','@=':'ATEQUAL','[':'LSQB',']':'RSQB','^':'CIRCUMFLEX','^=':'CIRCUMFLEXEQUAL','{':'LBRACE','|':'VBAR','|=':'VBAREQUAL','}':'RBRACE','~':'TILDE'} function ISTERMINAL(x){return x < NT_OFFSET} function ISNONTERMINAL(x){return x >=NT_OFFSET} function ISEOF(x){return x==ENDMARKER}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function is_whitespace(char){return ' \n\r\t\f'.includes(char)} var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u const Other_ID_Start=[0x1885,0x1886,0x2118,0x212E,0x309B,0x309C].map( x=> String.fromCodePoint(x)) function is_ID_Start(char){return/\p{Letter}/u.test(char)|| /\p{Nl}/u.test(char)|| char=='_' || Other_ID_Start.includes(char)} const Other_ID_Continue=[0x00B7,0x0387,0x1369,0x1370,0x1371,0x19DA,0x200C,0x200D,0x30FB,0xFF65]. map(x=> String.fromCodePoint(x)) function is_ID_Continue(char){return is_ID_Start(char)|| /\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}/u.test(char)|| Other_ID_Continue.includes(char)} $B.is_XID_Start=function(cp){let char=String.fromCodePoint(cp) if(! is_ID_Start(char)){return false} var norm=char.normalize('NFKC') if(! is_ID_Start(norm[0])){return false} for(let char of norm.substr(1)){if(! is_ID_Continue(char)){return false}} return true} $B.is_XID_Continue=function(cp){let char=String.fromCodePoint(cp) if(! is_ID_Continue(char)){return false} var norm=char.normalize('NFKC') for(let char of norm.substr(1)){if(! is_ID_Continue(char)){return false}} return true} $B.in_unicode_category=function(category,cp){if(isNaN(cp)){return false} try{var re=new RegExp('\\p{'+category+'}','u') return re.test(String.fromCodePoint(cp))}catch(err){ return in_unicode_category(category,cp)}} function in_unicode_category(category,cp){ var table=$B.unicode[category],start=0,end=table.length-1,len=table.length,ix=Math.floor(len/2),nb=0 var first=table[start],item=typeof first=='number' ? first :first[0] if(cp < item){return false} var last=table[end] if(typeof last=='number'){if(cp > last){return false}}else if(last[0]+last[1]< cp){return false} while(true){nb++ if(nb > 100){console.log('infinite loop for',cp) alert()} item=table[ix] if(typeof item !='number'){item=item[0]} if(item==cp){return true}else if(item > cp){end=ix}else{start=ix} len=Math.floor((end-start)/2) if(end-start==1){break} ix=start+len} var step=table[start][2] if(step===undefined){return table[start][0]+table[start][1]> cp} return(table[start][0]+step*table[start][1]> cp)&& ((cp-table[start][0])% step)==0} const FT_START={f:'FSTRING_START',t:'TSTRING_START'},FT_MIDDLE={f:'FSTRING_MIDDLE',t:'TSTRING_MIDDLE'},FT_END={f:'FSTRING_END',t:'TSTRING_END'} function ord(char){if(char.length==1){return char.charCodeAt(0)} var code=0x10000 code+=(char.charCodeAt(0)& 0x03FF)<< 10 code+=(char.charCodeAt(1)& 0x03FF) return code} function $last(array){return array[array.length-1]} function raise_error(err_type,filename,lineno,col_offset,end_lineno,end_col_offset,line,message){var exc=$B.EXC(err_type,message) exc.filename=filename exc.lineno=lineno exc.offset=col_offset exc.end_lineno=end_lineno exc.end_offset=end_col_offset exc.text=line var args1=[filename,lineno,col_offset,line.trimRight(),end_lineno,end_col_offset] exc.args=$B.fast_tuple([message,$B.fast_tuple(args1)]) throw exc} var ops='.,:;+-*/%~^|&=<>[](){}@', op2=['**','//','>>','<<'],augm_op='+-*/%^|&=<>@',closing={'}':'{',']':'[',')':'('} function ErrorToken(err_type,filename,lineno,col_offset,end_lineno,end_col_offset,line,message){var token=Token('ERRORTOKEN','',lineno,col_offset,end_lineno,end_col_offset,line) token.message=message return token} function ErrorTokenKnownToken(){var args=Array.from(arguments) args.$error_token_known_token=true return args} function Token(type,string,lineno,col_offset,end_lineno,end_col_offset,line){ var res={type,string,line,lineno,col_offset,end_lineno,end_col_offset} res.type=res.num_type=$B.py_tokens[type] if(type=='OP'){res.num_type=$B.py_tokens[$B.EXACT_TOKEN_TYPES[string]]}else if(type=='ENCODING'){res.parser_ignored=true}else if(type=='NL' ||type=='COMMENT'){res.parser_ignored=true} res.bytes=res.string return res} function get_comment(parser,src,pos,line_num,line_start,token_name,line){var start=pos,ix var t=[] while(true){if(pos >=src.length ||(ix='\r\n'.indexOf(src[pos]))>-1){if(parser && parser.flags & $B.PyCF_TYPE_COMMENTS){var comment=src.substring(start-1,pos),mo=/^#\s*type\s*:(.*)/.exec(comment) if(mo){var is_type_ignore=false if(mo[1].startsWith('ignore')){if(mo[1].length==6){is_type_ignore=true}else{var char=mo[1][6] if(char.charCodeAt(0)<=128 &&/[a-zA-Z0-9]/.exec(char)===null){is_type_ignore=true}}} if(is_type_ignore){t.push(Token('TYPE_IGNORE',comment,line_num,start-line_start,line_num,pos-line_start+1,line))}else{t.push(Token('TYPE_COMMENT',comment,line_num,start-line_start,line_num,pos-line_start+1,line))} return{t,pos}}} t.push(Token('COMMENT',src.substring(start-1,pos),line_num,start-line_start,line_num,pos-line_start+1,line)) if(ix !==undefined){var nb=1 if(src[pos]=='\r' && src[pos+1]=='\n'){nb++}else if(src[pos]===undefined){ nb=0} t.push(Token(token_name,src.substr(pos,nb),line_num,pos-line_start+1,line_num,pos-line_start+nb+1,line)) if(src[pos]===undefined){t.push(Token('NEWLINE','\n',line_num,pos-line_start+1,line_num,pos-line_start+2,''))} pos+=nb} return{t,pos}} pos++}} function test_num(num_type,char){switch(num_type){case '': return $B.in_unicode_category('Nd',ord(char)) case 'x': return '0123456789abcdef'.includes(char.toLowerCase()) case 'b': return '01'.includes(char) case 'o': return '01234567'.includes(char) default: throw Error('unknown num type '+num_type)}} function nesting_level(token_modes){var ix=token_modes.length-1 while(ix >=0){var mode=token_modes[ix] if(mode.nesting !==undefined){return mode.nesting} ix--}} $B.tokenizer=function(src,filename,mode,parser){var string_prefix=/^(r|u|R|U|f|F|t|T||fr|Fr|fR|FR|rf|rF|Rf|RF||tr|Tr|tR|TR|rt|rT|Rt|RT)$/,bytes_prefix=/^(b|B|br|Br|bR|BR|rb|rB|Rb|RB)$/,t=[] if(mode !='eval' && ! src.endsWith('\n')){src+='\n'} var lines=src.split('\n'),linenum=0,line_at={} for(let i=0,len=src.length;i < len;i++){line_at[i]=linenum if(src[i]=='\n'){linenum++}} function get_line_at(pos){return lines[line_at[pos]]+'\n'} var state="line_start",char,cp,mo,pos=0,quote,triple_quote,escaped=false,string_start,string,prefix,name,number,num_type,comment,indent,indent_before_continuation=0,indents=[],braces=[],line,line_num=0,line_start=1,token_modes=['regular'],token_mode='regular',save_mode=token_mode,format_specifier,ft_type,ft_buffer,ft_start,ft_expr_start,ft_escape,ft_format_spec if(parser){parser.braces=braces} t.push(Token('ENCODING','utf-8',0,0,0,0,'')) while(pos < src.length){char=src[pos] cp=src.charCodeAt(pos) if(cp >=0xD800 && cp <=0xDBFF){ cp=ord(src.substr(pos,2)) char=src.substr(pos,2) pos++} pos++ if(token_mode !=save_mode){if(token_mode=='ft'){ft_buffer='' ft_escape=false}else if(token_mode=='format_specifier'){format_specifier=''}} save_mode=token_mode if(token_mode=='ft'){ if(char==token_mode.quote){if(ft_escape){ft_buffer+='\\'+char ft_escape=false continue} if(token_mode.triple_quote){if(src.substr(pos,2)!=token_mode.quote.repeat(2)){ft_buffer+=char continue} char=token_mode.quote.repeat(3) pos+=2} if(ft_buffer.length > 0){ t.push(Token(FT_MIDDLE[ft_type],ft_buffer,line_num,ft_start,line_num,ft_start+ft_buffer.length,line))} t.push(Token(FT_END[ft_type],char,line_num,pos-line_start,line_num,pos-line_start+1,line)) token_modes.pop() token_mode=$B.last(token_modes) state=null continue}else if(char=='{'){if(src.charAt(pos)=='{'){ ft_buffer+=char pos++ continue}else{ if(ft_buffer.length > 0){t.push(Token(FT_MIDDLE[ft_type],ft_buffer,line_num,ft_start,line_num,ft_start+ft_buffer.length,line))} token_mode='regular_within_ft' ft_expr_start=pos-line_start state=null token_modes.push(token_mode)}}else if(char=='}'){if(src.charAt(pos)=='}'){ ft_buffer+=char pos++ continue}else{ t.push(Token('OP',char,line_num,pos-line_start,line_num,pos-line_start+1,line)) continue}}else if(char=='\\'){if(token_mode.raw){ft_buffer+=char+char}else{if(ft_escape){ft_buffer+='\\'+char} ft_escape=! ft_escape} continue}else{if(ft_escape){ft_buffer+='\\'} ft_buffer+=char ft_escape=false if(char=='\n'){line_num++} continue}}else if(token_mode=='format_specifier'){if(char==quote){if(format_specifier.length > 0){ t.push(Token(FT_MIDDLE[ft_type],format_specifier,line_num,ft_start,line_num,ft_start+format_specifier.length,line)) token_modes.pop() token_mode=$B.last(token_modes) continue}}else if(char=='{'){ t.push(Token(FT_MIDDLE[ft_type],format_specifier,line_num,ft_start,line_num,ft_start+format_specifier.length,line)) token_mode='regular_within_ft' ft_expr_start=pos-line_start state=null token_modes.push(token_mode)}else if(char=='}'){ t.push(Token(FT_MIDDLE[ft_type],format_specifier,line_num,ft_start,line_num,ft_start+format_specifier.length,line)) t.push(Token('OP',char,line_num,pos-line_start,line_num,pos-line_start+1,line)) if(braces.length==0 ||$B.last(braces).char !=='{'){throw Error('wrong braces')} braces.pop() token_modes.pop() token_mode=$B.last(token_modes) continue}else{format_specifier+=char continue}} switch(state){case "line_start": line=get_line_at(pos-1) line_start=pos line_num++ if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1))){ t.push(Token('NL',mo[0],line_num,0,line_num,mo[0].length,line)) pos+=mo[0].length-1 continue}else if(char=='#'){comment=get_comment(parser,src,pos,line_num,line_start,'NL',line) for(var item of comment.t){t.push(item)} pos=comment.pos state='line_start' continue} indent=0 if(char==' '){indent=1}else if(char=='\t'){indent=8} if(indent){var broken=false while(pos < src.length){if(broken && indent > 0 && ' \t'.includes(src[pos])){t.push(ErrorToken( _b_.IndentationError,filename,line_num,pos-line_start,line_num,pos-line_start+1,line,'unindent does not match any outer indentation level')) return t} if(src[pos]==' '){indent++}else if(src[pos]=='\t'){indent+=8}else if(src[pos]=='\\' && src[pos+1]=='\n'){ pos++ line_start=pos+2 line_num++ line=get_line_at(pos+2) broken=true}else{break} pos++} if(pos==src.length){ line_num-- break} if(src[pos]=='#'){ comment=get_comment(parser,src,pos+1,line_num,line_start,'NL',line) for(var item of comment.t){t.push(item)} pos=comment.pos continue}else if(src[pos]=='\\'){if(/^\f?(\r\n|\r|\n)/.exec(src[pos+1])){line_num++ pos++ continue}else{t.push(ErrorToken(_b_.SyntaxError,filename,line_num,pos+2-line_start,line_num,pos+3-line_start,line,'unexpected character after line continuation character')) return t}}else if(mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos))){ t.push(Token('NL','',line_num,pos-line_start+1,line_num,pos-line_start+1+mo[0].length,line)) pos+=mo[0].length continue} if(indents.length==0 ||indent > $last(indents)){indents.push(indent) t.push(Token('INDENT','',line_num,0,line_num,indent,line))}else if(indent < $last(indents)){var ix=indents.indexOf(indent) if(ix==-1){var message='unindent does not match '+ 'any outer indentation level' t.push(ErrorToken(_b_.IndentationError,filename,line_num,0,line_num,0,line,message)) return t} for(var i=indents.length-1;i > ix;i--){indents.pop() t.push(Token('DEDENT','',line_num,indent,line_num,indent,line))}} state=null}else{ while(indents.length > 0){indents.pop() t.push(Token('DEDENT','',line_num,indent,line_num,indent,line))} state=null pos--} break case null: switch(char){case '"': case "'": quote=char triple_quote=src[pos]==char && src[pos+1]==char string_start=[line_num,pos-line_start,line_start] if(triple_quote){pos+=2} escaped=false state='STRING' string="" prefix="" break case '#': var token_name=braces.length > 0 ? 'NL' :'NEWLINE' comment=get_comment(parser,src,pos,line_num,line_start,token_name,line) for(var item of comment.t){t.push(item)} pos=comment.pos if(braces.length==0){state='line_start'}else{state=null line_num++ line_start=pos+1 line=get_line_at(pos)} break case '0': state='NUMBER' number=char num_type='' if(src[pos]&& 'xbo'.includes(src[pos].toLowerCase())){number+=src[pos] num_type=src[pos].toLowerCase() pos++}else if(src[pos]){var pos1=pos while(pos1 < src.length){if(src[pos1].match(/\d/)){if(src[pos1]=='0'){pos1++ continue} let msg='leading zeros in decimal integer '+ 'literals are not permitted; use an 0o prefix '+ 'for octal integers' t.push(ErrorToken(_b_.SyntaxError,filename,line_num,pos-line_start-number.length,line_num,pos-line_start,line,msg)) return t}else{break}}} break case '.': if(src[pos]&& $B.in_unicode_category('Nd',ord(src[pos]))){state='NUMBER' num_type='' number=char}else{var op=char while(src[pos]==char){pos++ op+=char} var dot_pos=pos-line_start-op.length+1 while(op.length >=3){ t.push(Token('OP','...',line_num,dot_pos,line_num,dot_pos+3,line)) op=op.substr(3)} for(var i=0;i < op.length;i++){t.push(Token('OP','.',line_num,dot_pos,line_num,dot_pos+1,line)) dot_pos++}} break case '\\': var mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos)) if(mo){if(pos==src.length-1){var msg='unexpected EOF while parsing' raise_error(_b_.SyntaxError,filename,line_num,pos-line_start,line_num,pos-line_start+1,line,msg)} line_num++ pos+=mo[0].length line_start=pos+1 line=get_line_at(pos)}else{pos++; var msg='unexpected character after line '+ 'continuation character' raise_error(_b_.SyntaxError,filename,line_num,pos-line_start,line_num,pos-line_start+1,line,msg)} break case '\n': case '\r': var token_name=braces.length > 0 ? 'NL':'NEWLINE' mo=/^\f?(\r\n|\r|\n)/.exec(src.substr(pos-1)) t.push(Token(token_name,mo[0],line_num,pos-line_start,line_num,pos-line_start+mo[0].length,line)) pos+=mo[0].length-1 if(token_name=='NEWLINE'){state='line_start'}else{line_num++ line_start=pos+1 line=get_line_at(pos)} break default: if($B.is_XID_Start(ord(char))){ state='NAME' name=char}else if($B.in_unicode_category('Nd',ord(char))){state='NUMBER' num_type='' number=char}else if(ops.includes(char)){if(token_mode=='regular_within_ft' && (char==':' ||char=='}')){if(char==':'){ if(nesting_level(token_modes)==braces.length-1){let colon=Token('OP',char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line) colon.metadata=src.substr( line_start+ft_expr_start,pos-line_start-ft_expr_start-1) t.push(colon) token_modes.pop() token_mode='format_specifier' token_modes.push(token_mode) continue}}else{ let closing_brace=Token('OP',char,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line) closing_brace.metadata=src.substring( line_start+ft_expr_start,pos-1) t.push(closing_brace) token_modes.pop() token_mode=token_modes[token_modes.length-1] if(braces.length==0 ||$B.last(braces).char !=='{'){t.push(Error('wrong braces')) return t} braces.pop() continue}} var op=char if(op2.includes(char+src[pos])){op=char+src[pos] pos++} if(src[pos]=='=' &&(op.length==2 || augm_op.includes(op))){op+=src[pos] pos++}else if((char=='-' && src[pos]=='>')|| (char==':' && src[pos]=='=')){op+=src[pos] pos++} if('[({'.includes(char)){braces.push({char,pos,line_num,line_start,line})}else if('])}'.includes(char)){if(braces.length && $last(braces).char==closing[char]){braces.pop()}else{braces.push({char,pos,line_num,line_start,line})}} t.push(Token('OP',op,line_num,pos-line_start-op.length+1,line_num,pos-line_start+1,line))}else if(char=='!'){if(src[pos]=='='){t.push(Token('OP','!=',line_num,pos-line_start,line_num,pos-line_start+2,line)) pos++}else{ let token=Token('OP',char,line_num,pos-line_start,line_num,pos-line_start+1,line) token.metadata=src.substring( line_start+ft_start+2,pos-1) t.push(token)}}else if(char==' ' ||char=='\t'){}else{ var cp=char.codePointAt(0),err_msg='invalid' if(unprintable_re.exec(char)){err_msg+=' non-printable'} var unicode=cp.toString(16).toUpperCase() while(unicode.length < 4){unicode='0'+unicode} err_msg+=` character '${char}' (U+${unicode})` if(char=='$' ||char=='`'){err_msg='invalid syntax'} var err_token=Token('ERRORTOKEN',char,line_num,pos-line_start,line_num,pos-line_start+1,line) t.push(ErrorTokenKnownToken(_b_.SyntaxError,filename,err_token,err_msg)) return t}} break case 'NAME': if($B.is_XID_Continue(ord(char))){name+=char}else if(char=='"' ||char=="'"){if(string_prefix.exec(name)||bytes_prefix.exec(name)){ state='STRING' quote=char triple_quote=src[pos]==quote && src[pos+1]==quote prefix=name if(triple_quote){pos+=2} var is_ft=false if(prefix.toLowerCase().includes('f')){is_ft=true ft_type='f'}else if(prefix.toLowerCase().includes('t')){is_ft=true ft_type='t'} if(is_ft){token_mode=new String('ft') ft_start=pos-line_start-name.length token_mode.nesting=braces.length token_mode.quote=quote token_mode.triple_quote=triple_quote token_mode.raw=prefix.toLowerCase().includes('r') token_modes.push(token_mode) var s=triple_quote ? quote.repeat(3):quote var end_col=ft_start+name.length+s.length t.push(Token(FT_START[ft_type],prefix+s,line_num,ft_start,line_num,end_col,line)) continue} escaped=false string_start=[line_num,pos-line_start-name.length,line_start] string=''}else{t.push(Token('NAME',name,line_num,pos-line_start-name.length,line_num,pos-line_start,line)) state=null pos--}}else{t.push(Token('NAME',name,line_num,pos-line_start-name.length,line_num,pos-line_start,line)) state=null pos--} break case 'STRING': switch(char){case quote: if(! escaped){ var string_line=line if(line_num > string_start[0]){string_line=src.substring( string_start[2]-1,pos+2)} var full_string if(! triple_quote){full_string=prefix+quote+string+ quote t.push(Token('STRING',full_string,string_start[0],string_start[1],line_num,pos-line_start+1,string_line)) state=null}else if(char+src.substr(pos,2)== quote.repeat(3)){full_string=prefix+quote.repeat(3)+ string+quote.repeat(3) t.push(Token('STRING',full_string,string_start[0],string_start[1],line_num,pos-line_start+3,string_line)) pos+=2 state=null}else{string+=char}}else{string+=char} escaped=false break case '\r': case '\n': if(! escaped && ! triple_quote){ var msg if(token_mode=='regular_within_fstring'){msg="f-string: missing '}'"}else{var msg=`unterminated string literal `+ `(detected at line ${line_num})`,line_num=string_start[0],col_offset=string_start[1]} t.push(ErrorToken(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)) return t} string+=char line_num++ line_start=pos+1 if(char=='\r' && src[pos]=='\n'){string+=src[pos] line_start++ pos++} line=get_line_at(pos) escaped=false break case '\\': string+=char escaped=! escaped break default: escaped=false string+=char break} break case 'NUMBER': if(test_num(num_type,char)){number+=char}else if(char=='_' && ! number.endsWith('.')){if(number.endsWith('_')){throw SyntaxError('consecutive _ in number')}else if(src[pos]===undefined || ! test_num(num_type,src[pos])){ t.push(Token('NUMBER',number,line_num,pos-line_start-number.length,line_num,pos-line_start,line)) state=null pos--}else{number+=char}}else if(char=='.' && ! number.includes(char)){number+=char}else if(char.toLowerCase()=='e' && ! number.toLowerCase().includes('e')){if('+-'.includes(src[pos])|| $B.in_unicode_category('Nd',ord(src[pos]))){number+=char}else{t.push(Token('NUMBER',number,line_num,pos-line_start-number.length,line_num,pos-line_start,line)) state=null pos--}}else if((char=='+' ||char=='-')&& number.toLowerCase().endsWith('e')){number+=char}else if(char.toLowerCase()=='j'){ number+=char t.push(Token('NUMBER',number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line)) state=null}else if(char.match(/\p{Letter}/u)){raise_error(_b_.SyntaxError,filename,line_num,pos-line_start,line_num,pos-line_start,line,'invalid decimal literal') return t}else{t.push(Token('NUMBER',number,line_num,pos-line_start-number.length,line_num,pos-line_start,line)) state=null pos--} break}} switch(state){case 'line_start': line_num++ break case 'NAME': t.push(Token('NAME',name,line_num,pos-line_start-name.length+1,line_num,pos-line_start+1,line)) break case 'NUMBER': t.push(Token('NUMBER',number,line_num,pos-line_start-number.length+1,line_num,pos-line_start+1,line)) break case 'STRING': line_num=string_start[0] line=lines[line_num-1] var msg=`unterminated ${triple_quote ? 'triple-quoted ' : ''}`+ `string literal (detected at line ${line_num})`,col_offset=string_start[1] t.push(ErrorToken(_b_.SyntaxError,filename,line_num,col_offset,line_num,col_offset,line,msg)) return t} if(! src.endsWith('\n')&& state !=line_start){t.push(Token('NEWLINE','',line_num,pos-line_start+1,line_num,pos-line_start+1,line+'\n')) line_num++} while(indents.length > 0){indents.pop() t.push(Token('DEDENT','',line_num,0,line_num,0,''))} t.push(Token('ENDMARKER','',line_num,0,line_num,0,'')) return t}})(__BRYTHON__); ; (function($B){ var binary_ops={'+':'Add','-':'Sub','*':'Mult','/':'Div','//':'FloorDiv','%':'Mod','**':'Pow','<<':'LShift','>>':'RShift','|':'BitOr','^':'BitXor','&':'BitAnd','@':'MatMult'} var boolean_ops={'and':'And','or':'Or'} var comparison_ops={'==':'Eq','!=':'NotEq','<':'Lt','<=':'LtE','>':'Gt','>=':'GtE','is':'Is','is_not':'IsNot','in':'In','not_in':'NotIn'} var unary_ops={unary_inv:'Invert',unary_pos:'UAdd',unary_neg:'USub',unary_not:'Not'} var op_types=$B.op_types=[binary_ops,boolean_ops,comparison_ops,unary_ops] var _b_=$B.builtins var ast=$B.ast={} for(var kl in $B.ast_classes){var args=$B.ast_classes[kl],body='' if(typeof args=="string"){if(args.length > 0){for(var arg of args.split(',')){if(arg.endsWith('*')){arg=arg.substr(0,arg.length-1) body+=` this.${arg} = $B.$list(${arg} === undefined ? [] : ${arg})\n`}else if(arg.endsWith('?')){arg=arg.substr(0,arg.length-1) body+=` this.${arg} = ${arg}\n`}else{body+=` this.${arg} = ${arg}\n`}}} var arg_list=args.replace(/[*?]/g,'').split(',') ast[kl]=Function(...arg_list,body) ast[kl]._fields=args.split(',')}else{ast[kl]=args.map(x=> ast[x])} ast[kl].$name=kl} $B.ast_js_to_py=function(obj){$B.create_python_ast_classes() if(obj===undefined){return _b_.None}else if(Array.isArray(obj)){return $B.$list(obj.map($B.ast_js_to_py))}else{var class_name=obj.constructor.$name,py_class=$B.python_ast_classes[class_name],py_ast_obj={__class__:py_class} if(py_class===undefined){return obj} for(var field of py_class._fields){py_ast_obj[field]=$B.ast_js_to_py(obj[field])} py_ast_obj._attributes=$B.fast_tuple([]) for(var loc of['lineno','col_offset','end_lineno','end_col_offset']){if(obj[loc]!==undefined){py_ast_obj[loc]=obj[loc] py_ast_obj._attributes.push(loc)}} return py_ast_obj}} $B.ast_py_to_js=function(obj){if(obj===undefined ||obj===_b_.None){return undefined}else if(Array.isArray(obj)){return obj.map($B.ast_py_to_js)}else if(typeof obj=="string"){return obj}else{var class_name=$B.class_name(obj),js_class=$B.ast[class_name] if(js_class===undefined){return obj} var js_ast_obj=new js_class() for(var field of js_class._fields){if(field.endsWith('?')||field.endsWith('*')){field=field.substr(0,field.length-1)} js_ast_obj[field]=$B.ast_py_to_js(obj[field])} for(var loc of['lineno','col_offset','end_lineno','end_col_offset']){if(obj[loc]!==undefined){js_ast_obj[loc]=obj[loc]}} return js_ast_obj}} $B.create_python_ast_classes=function(){if($B.python_ast_classes){return} $B.python_ast_classes={} for(var klass in $B.ast_classes){$B.python_ast_classes[klass]=(function(kl){var _fields,raw_fields if(typeof $B.ast_classes[kl]=="string"){if($B.ast_classes[kl]==''){raw_fields=_fields=[]}else{raw_fields=$B.ast_classes[kl].split(',') _fields=raw_fields.map(x=> (x.endsWith('*')||x.endsWith('?'))? x.substr(0,x.length-1):x)}} var cls=$B.make_class(kl),$defaults={},slots={},nb_args=0 if(raw_fields){for(let i=0,len=_fields.length;i < len;i++){let f=_fields[i],rf=raw_fields[i] nb_args++ slots[f]=null if(rf.endsWith('*')){$defaults[f]=[]}else if(rf.endsWith('?')){$defaults[f]=_b_.None}}} cls.__match_args__=$B.fast_tuple(Object.keys(slots)) cls.$factory=function(){var $=$B.args(klass,nb_args,$B.clone(slots),Object.keys(slots),arguments,$B.clone($defaults),null,'kw') var res={__class__:cls,_attributes:$B.fast_tuple([])} for(let key in $){if(key=='kw'){for(let item of _b_.dict.$iter_items($.kw)){res[item.key]=item.value}}else{res[key]=$[key]}} if(klass=="Constant"){res.value=$B.AST.$convert($.value)} return res} if(_fields){cls._fields=_fields} cls.__mro__=[$B.AST,_b_.object] cls.__module__='ast' cls.__dict__=$B.empty_dict() if(raw_fields){for(let i=0,len=raw_fields.length;i < len;i++){var raw_field=raw_fields[i] if(raw_field.endsWith('?')){_b_.dict.$setitem(cls.__dict__,_fields[i],_b_.None)}}} return cls})(klass)}} var op2ast_class=$B.op2ast_class={},ast_types=[ast.BinOp,ast.BoolOp,ast.Compare,ast.UnaryOp] for(var i=0;i < 4;i++){for(var op in op_types[i]){op2ast_class[op]=[ast_types[i],ast[op_types[i][op]]]}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var _window if($B.isNode){_window={location:{href:'',origin:'',pathname:''}}}else{ _window=self} $B.parser={} $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.make_frames_stack())} return table[table.length-1]} var ast=$B.ast function get_line(filename,lineno){var src=$B.file_cache[filename],line=_b_.None if(src !==undefined){var lines=src.split('\n') line=lines[lineno-1]} return line} var VALID_FUTURES=["nested_scopes","generators","division","absolute_import","with_statement","print_function","unicode_literals","barry_as_FLUFL","generator_stop","annotations"] $B.future_features=function(mod,filename){var features=0 var i=0; if(mod.body[0]instanceof $B.ast.Expr){if(mod.body[0].value instanceof $B.ast.Constant && typeof mod.body[0].value.value=="string"){ i++}} while(i < mod.body.length){var child=mod.body[i] if(child instanceof $B.ast.ImportFrom && child.module=='__future__'){ for(var alias of child.names){var name=alias.name if(name=="braces"){raise_error_known_location(_b_.SyntaxError,filename,alias.lineno,alias.col_offset,alias.end_lineno,alias.end_col_offset,get_line(filename,child.lineno),"not a chance")}else if(name=="annotations"){features |=$B.CO_FUTURE_ANNOTATIONS}else if(VALID_FUTURES.indexOf(name)==-1){raise_error_known_location(_b_.SyntaxError,filename,alias.lineno,alias.col_offset,alias.end_lineno,alias.end_col_offset,get_line(filename,child.lineno),`future feature ${name} is not defined`)}} i++}else{break}} return{features}} $B.format_indent=function(js,indent){ var indentation=' ',lines=js.split('\n'),level=indent,res='',last_is_closing_brace=false,last_is_backslash=false,last_is_var_and_comma=false for(var i=0,len=lines.length;i < len;i++){var line=lines[i],add_closing_brace=false,add_spaces=true if(last_is_backslash){add_spaces=false}else if(last_is_var_and_comma){line=' '+line.trim()}else{line=line.trim()} if(add_spaces && last_is_closing_brace && (line.startsWith('else')|| line.startsWith('catch')|| line.startsWith('finally'))){res=res.substr(0,res.length-1) add_spaces=false} last_is_closing_brace=line.endsWith('}') if(line.startsWith('}')){level--}else if(line.endsWith('}')){line=line.substr(0,line.length-1) add_closing_brace=true} if(level < 0){if($B.get_option('debug')> 2){console.log('wrong js indent')} level=0} try{res+=(add_spaces ? indentation.repeat(level):'')+line+'\n'}catch(err){console.log(res) throw err} if(line.endsWith('{')){level++}else if(add_closing_brace){level-- if(level < 0){level=0} try{res+=indentation.repeat(level)+'}\n'}catch(err){console.log(res) throw err}} last_is_backslash=line.endsWith('\\') last_is_var_and_comma=line.endsWith(',')&& (line.startsWith('var ')||last_is_var_and_comma)} return res} function get_docstring(node){var doc_string=_b_.None if(node.body.length > 0){var firstchild=node.body[0] if(firstchild instanceof $B.ast.Constant && typeof firstchild.value=='string'){doc_string=firstchild.value}} return doc_string} var s_escaped='abfnrtvxuU"0123456789'+"'"+'\\',is_escaped={} for(var i=0;i < s_escaped.length;i++){is_escaped[s_escaped.charAt(i)]=true} function SurrogatePair(value){ value=value-0x10000 return String.fromCharCode(0xD800 |(value >> 10))+ String.fromCharCode(0xDC00 |(value & 0x3FF))} function test_escape(text,antislash_pos){ var seq_end,mo mo=/^[0-7]{1,3}/.exec(text.substr(antislash_pos+1)) if(mo){return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]} switch(text[antislash_pos+1]){case "x": mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=2){seq_end=antislash_pos+mo[0].length+1 $token.value.start[1]=seq_end throw Error( "(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\xXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]} break case "u": mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=4){seq_end=antislash_pos+mo[0].length+1 $token.value.start[1]=seq_end throw Error( "(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\uXXXX escape")}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]} break case "U": mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=8){seq_end=antislash_pos+mo[0].length+1 $token.value.start[1]=seq_end throw Error( "(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\uXXXX escape")}else{let value=parseInt(mo[0],16) if(value > 0x10FFFF){throw Error('invalid unicode escape '+mo[0])}else if(value >=0x10000){return[SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}} $B.test_escape=test_escape function unindent(src){ var lines=src.split('\n'),line,global_indent,indent,first,unindented_lines=[] var min_indent for(var line of lines){if(/^\s*$/.exec(line)){continue} indent=line.match(/^\s*/)[0].length if(indent==0){return src} if(min_indent===undefined){min_indent=indent} if(indent < min_indent){min_indent=indent}} for(var line of lines){if(/^\s*$/.exec(line)){unindented_lines.push(line)}else{unindented_lines.push(line.substr(min_indent))}} return unindented_lines.join('\n')} var $token={} $B.parse_time=0 $B.py2js=function(src,module,locals_id,parent_scope){ if(typeof module=="object"){module=module.__name__} parent_scope=parent_scope ||$B.builtins_scope var filename,imported if(typeof src=='object'){filename=src.filename imported=src.imported src=src.src} src=src.replace(/\r\n/g,'\n'). replace(/\r/g,'\n') var locals_is_module=Array.isArray(locals_id) if(locals_is_module){locals_id=locals_id[0]} var t0=globalThis.performance.now() var parser=new $B.Parser(src,filename,'file'),_ast=$B._PyPegen.run_parser(parser) $B.parse_time+=globalThis.performance.now()-t0 var future=$B.future_features(_ast,filename) var symtable=$B._PySymtable_Build(_ast,filename,future) var js_obj=$B.js_from_root({ast:_ast,symtable,filename,src,imported}) var js_from_ast=js_obj.js return{ _ast,imports:js_obj.imports,to_js:function(){return js_from_ast}}} $B.parse_options=function(options){ if(options===undefined){options={}}else if(typeof options=='number'){ options={debug:options}}else if(typeof options !=='object'){console.warn('ignoring invalid argument passed to brython():',options) options={}} let options_lowered={} for(const[key,value]of Object.entries(options)){options_lowered[key.toLowerCase()]=value} options=options_lowered $B.debug=options.debug===undefined ? 1 :options.debug _b_.__debug__=$B.debug > 0 options.python_extension=options.python_extension ||'.py' if($B.$options.args){$B.__ARGV=$B.$options.args}else{$B.__ARGV=_b_.list.$factory([])} $B.options_parsed=true return options} if(!($B.isWebWorker ||$B.isNode)){var startup_observer=new MutationObserver(function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){addPythonScript(addedNode);}}}); startup_observer.observe(document.documentElement,{childList:true,subtree:true});} var brython_options=$B.brython_options={} var python_scripts=[] if(!$B.isWebWorker){ python_scripts=python_scripts.concat(Array.from( document.querySelectorAll('script[type="text/python"]'))).concat( Array.from( document.querySelectorAll('script[type="text/python3"]'))) var onload addEventListener('DOMContentLoaded',function(ev){if(ev.target.body){onload=ev.target.body.onload} if(! onload){ ev.target.body.onload=function(){return brython()}}else{ ev.target.body.onload=function(){onload() if(! status.brython_called){brython()}}}} ) class BrythonOptions extends HTMLElement{ constructor(){super()} connectedCallback(){for(var attr of this.getAttributeNames()){brython_options[attr]=convert_option(attr,this.getAttribute(attr))}}} customElements.define('brython-options',BrythonOptions)} var defined_ids={},script_to_id=new Map(),id_to_script={} function addPythonScript(addedNode){ if(addedNode.tagName=='SCRIPT' && (addedNode.type=="text/python" || addedNode.type=="text/python3")){python_scripts.push(addedNode)}} var status={brython_called:false,first_unnamed_script:true} $B.dispatch_load_event=function(script){ script.dispatchEvent(new Event('load'))} function injectPythonScript(addedNode){ if(addedNode.tagName=='SCRIPT' && addedNode.type=="text/python"){set_script_id(addedNode) run_scripts([addedNode])}} function set_script_id(script){if(script_to_id.has(script)){}else if(script.id){if(defined_ids[script.id]){throw Error("Brython error : Found 2 scripts with the "+ "same id '"+script.id+"'")}else{defined_ids[script.id]=true} script_to_id.set(script,script.id)}else{if(script.className==='webworker'){$B.RAISE_ATTRIBUTE_ERROR( "webworker script has no attribute 'id'",script,'id')} if(status.first_unnamed_script){script_to_id.set(script,'__main__') status.first_unnamed_script=false}else{script_to_id.set(script,'__main__'+$B.UUID())}} var id=script_to_id.get(script) id_to_script[id]=script return id} var brython=$B.parser.brython=function(options){$B.$options=$B.parse_options(options) if(!($B.isWebWorker ||$B.isNode)){if(! status.brython_called){ status.brython_called=true startup_observer.disconnect() var inject_observer=new MutationObserver(function(mutations){for(var mutation of mutations){for(var addedNode of mutation.addedNodes){injectPythonScript(addedNode);}}}) inject_observer.observe(document.documentElement,{childList:true,subtree:true})}}else if($B.isNode){return} for(var python_script of python_scripts){set_script_id(python_script)} var scripts=[] var kk=Object.keys(_window) var ids=$B.get_page_option('ids') if(ids !==undefined){if(! Array.isArray(ids)){$B.RAISE(_b_.ValueError,"ids is not a list")} if(ids.length==0){} for(var id of ids){var script=document.querySelector(`script[id="${id}"]`) if(script){set_script_id(script) scripts.push(script)}else{console.log(`no script with id '${id}'`) $B.RAISE(_b_.KeyError,`no script with id '${id}'`)}}}else if($B.isWebWorker){}else{scripts=python_scripts.slice()} run_scripts(scripts)} function convert_option(option,value){ if(option=='debug'){if(typeof value=='string' && value.match(/^\d+$/)){return parseInt(value)}else if(typeof value=='number'){return value}else{if(value !==null && value !==undefined){console.debug(`Invalid value for debug: ${value}`)}}}else if(option=='cache' || option=='indexeddb' || option=='static_stdlib_import'){if(value=='1' ||value.toLowerCase()=='true'){return true}else if(value=='0' ||value.toLowerCase()=='false'){return false}else{console.debug(`Invalid value for ${option}: ${value}`)}}else if(option=='ids' ||option=='pythonpath' ||option=='args'){ if(typeof value=='string'){if(value.trim().length==0){return[]} return value.trim().split(/\s+/)}}else if(option=='js_tab'){if(/\d+/.test(value)){var res=parseInt(value) if(res < 1 ||res > 4){console.log('Warning: option "js_tab" must be between '+ `1 and 4, got ${res}`) res=2} return res} console.warn('illegal value for js_tab',value)} return value} const default_option={args:[],cache:false,debug:1,indexeddb:true,python_extension:'.py',static_stdlib_import:true,js_tab:2} $B.get_filename=function(){if($B.count_frames()> 0){return $B.get_frame_at(0).__file__}} $B.get_filename_for_import=function(){var filename=$B.get_filename() if($B.import_info[filename]===undefined){$B.make_import_paths(filename)} return filename} $B.get_page_option=function(option){ option=option.toLowerCase() if($B.$options.hasOwnProperty(option)){ return $B.$options[option]}else if(brython_options.hasOwnProperty(option)){ return brython_options[option]}else{return default_option[option]}} $B.get_option=function(option,err){var filename=$B.script_filename if(err && err.filename){filename=err.filename}else if(err && err.$frame_obj){filename=$B.get_frame_at(0,err.$frame_obj).__file__}else{filename=$B.get_filename()?? filename} return $B.get_option_from_filename(option,filename)} $B.get_option_from_filename=function(option,filename){if(filename===undefined ||! $B.scripts[filename]){return $B.get_page_option(option)} var value=$B.scripts[filename].getAttribute(option) if(value !==null){return convert_option(option,value)}else{return $B.get_page_option(option)}} function run_scripts(_scripts){ var webworkers=_scripts.filter(script=> script.className==='webworker'),scripts=_scripts.filter(script=> script.className !=='webworker') var module_name,filename if(scripts.length > 0 ||$B.isWebWorker){if($B.get_page_option('indexedDB')&& $B.has_indexedDB && $B.hasOwnProperty("VFS")){$B.tasks.push([$B.idb_open])}} var src for(var worker of webworkers){if(worker.src){ $B.tasks.push([$B.ajax_load_script,{script:worker,name:worker.id,url:worker.src,is_ww:true}])}else{ $B.webworkers[worker.id]=worker filename=$B.script_filename=$B.strip_host( $B.script_path+"#"+worker.id) var source=(worker.innerText ||worker.textContent) source=unindent(source) source=source.replace(/^\n/,'') $B.url2name[filename]=worker.id $B.file_cache[filename]=source $B.scripts[filename]=worker $B.dispatch_load_event(worker)}} for(var script of scripts){module_name=script_to_id.get(script) if(script.src){ $B.tasks.push([$B.ajax_load_script,{script,name:module_name,url:script.src,id:script.id}])}else{filename=$B.script_filename=$B.strip_host( $B.script_path+"#"+module_name) src=(script.innerHTML ||script.textContent) src=unindent(src) src=src.replace(/^\n/,'') if(src.endsWith('\n')){src=src.substr(0,src.length-1)} $B.tasks.push([$B.run_script,script,src,module_name,$B.script_path,true])}} $B.loop()} $B.run_script=function(script,src,name,url,run_loop){ var filename=$B.script_filename=$B.strip_host(url+'#'+name) var script_elts=url.split('/') script_elts.pop() $B.script_dir=script_elts.join('/') $B.file_cache[filename]=src $B.url2name[filename]=name $B.scripts[filename]=script $B.make_import_paths(filename) _b_.__debug__=$B.get_option('debug')> 0 var root,js try{root=$B.py2js({src:src,filename},name,name) js=root.to_js() if($B.get_option_from_filename('debug',filename)> 1){console.log(js)}}catch(err){return $B.handle_error($B.exception(err))} var _script={__doc__:get_docstring(root._ast),js:js,__name__:name,__file__:url,script_element:script} $B.tasks.push(["execute",_script]) if(run_loop){$B.loop()}} $B.brython=brython})(__BRYTHON__); globalThis.brython=__BRYTHON__.brython if(__BRYTHON__.isNode){global.__BRYTHON__=__BRYTHON__ module.exports={__BRYTHON__ }} ; (function($B){var _b_=$B.builtins if($B.VFS_timestamp && $B.VFS_timestamp > $B.timestamp){ $B.timestamp=$B.VFS_timestamp} function idb_load(evt,module){ var res=evt.target.result var debug=$B.get_page_option('debug') if(res===undefined ||res.timestamp !=$B.timestamp || ($B.VFS[module]&& res.source_ts !==$B.VFS[module].timestamp)){ if($B.VFS[module]!==undefined){var elts=$B.VFS[module],ext=elts[0],source=elts[1] if(ext==".py"){var is_package=elts.length==4,__package__ if(is_package){__package__=module} else{var parts=module.split(".") parts.pop() __package__=parts.join(".")} $B.imported[module]=$B.module.$factory(module,"",__package__) $B.url2name[module]=module try{$B.py2js({src:source,filename:module},module,module)}catch(err){$B.handle_error(err)} delete $B.imported[module] if(debug > 1){console.log("precompile",module)}}else{console.log('bizarre',module,ext)}}else{}}else{ if(res.is_package){$B.precompiled[module]=[res.content]}else{$B.precompiled[module]=res.content} if(res.imports.length > 0){ if(debug > 1){console.log(module,"imports",res.imports)} var subimports=res.imports.split(",") for(var i=0;i < subimports.length;i++){var subimport=subimports[i] if(subimport.startsWith(".")){ var url_elts=module.split("."),nb_dots=0 while(subimport.startsWith(".")){nb_dots++ subimport=subimport.substr(1)} let elts=url_elts.slice(0,nb_dots) if(subimport){elts=elts.concat([subimport])} subimport=elts.join(".")} if(!$B.imported.hasOwnProperty(subimport)&& !$B.precompiled.hasOwnProperty(subimport)){ if($B.VFS.hasOwnProperty(subimport)){let submodule=$B.VFS[subimport],source=submodule[1] if(submodule[0]==".py"){$B.tasks.splice(0,0,[idb_get,subimport])}else{add_jsmodule(subimport,source)}}}}}} loop()} function idb_get(module){ var db=$B.idb_cx.result,tx=db.transaction("modules","readonly") try{var store=tx.objectStore("modules"),req=store.get(module) req.onsuccess=function(evt){idb_load(evt,module)}}catch(err){console.info('error',err)}} function remove_outdated(db,outdated,callback){var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules") if(outdated.length > 0){let module=outdated.pop(),req=store.delete(module) req.onsuccess=(function(mod){return function(){if($B.get_page_option('debug')> 1){console.info("delete outdated",mod)} report_remove_outdated(mod) remove_outdated(db,outdated,callback)}})(module)}else{report_close() callback()}} $B.idb_open_promise=function(){return new Promise(function(resolve,reject){$B.idb_name="brython-cache" var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name) idb_cx.onsuccess=function(){var db=idb_cx.result var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[] var openCursor=store.openCursor() openCursor.onerror=function(){reject("open cursor error")} openCursor.onsuccess=function(evt){var cursor=evt.target.result if(cursor){record=cursor.value if(record.timestamp==$B.timestamp){if(!$B.VFS ||!$B.VFS[record.name]|| $B.VFS[record.name].timestamp==record.source_ts){ if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content}}else{ outdated.push(record.name)}}else{outdated.push(record.name)} cursor.continue()}else{remove_outdated(db,outdated,resolve)}}} idb_cx.onupgradeneeded=function(){var db=idb_cx.result,store=db.createObjectStore("modules",{"keyPath":"name"}) store.onsuccess=resolve} idb_cx.onerror=function(){ $B.idb_cx=null $B.idb_name=null $B.$options.indexeddb=false reject('could not open indexedDB database')}})} $B.idb_open=function(){$B.idb_name="brython-cache" var idb_cx=$B.idb_cx=indexedDB.open($B.idb_name) idb_cx.onsuccess=function(){var db=idb_cx.result if($B.get_page_option('debug')> 1){console.info("using indexedDB for stdlib modules cache")} var tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),record,outdated=[] var openCursor=store.openCursor() openCursor.onerror=function(evt){console.log("open cursor error",evt)} openCursor.onsuccess=function(evt){var cursor=evt.target.result if(cursor){record=cursor.value if(record.timestamp==$B.timestamp){if(!$B.VFS ||!$B.VFS[record.name]|| $B.VFS[record.name].timestamp==record.source_ts){ if(record.is_package){$B.precompiled[record.name]=[record.content]}else{$B.precompiled[record.name]=record.content} if($B.get_page_option('debug')> 1){console.info("load from cache",record.name)}}else{ outdated.push(record.name)}}else{outdated.push(record.name)} cursor.continue()}else{if($B.get_page_option('debug')> 1){console.log("done")} remove_outdated(db,outdated,loop)}}} idb_cx.onupgradeneeded=function(){console.info("upgrade needed") var db=idb_cx.result,store=db.createObjectStore("modules",{"keyPath":"name"}) store.onsuccess=loop} idb_cx.onerror=function(){console.info('could not open indexedDB database') $B.idb_cx=null $B.idb_name=null $B.$options.indexeddb=false loop()} idb_cx.onversionchange=function(){console.log('version change')}} $B.ajax_load_script=function(s){var script=s.script,url=s.url,name=s.name,rel_path=url.substr($B.script_dir.length+1) if($B.files && $B.files.hasOwnProperty(rel_path)){ var src=atob($B.files[rel_path].content) if(s.is_ww){$B.webworkers[name]=script var filename=$B.script_filename=$B.strip_host(url) $B.file_cache[filename]=src $B.dispatch_load_event(script)} $B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true]) loop()}else if($B.protocol !="file"){var filename=$B.script_filename=$B.strip_host(url) $B.scripts[filename]=script var req=new XMLHttpRequest(),cache=$B.get_option('cache'),qs=cache ? '' : (url.search(/\?/)>-1 ? '&' :'?')+Date.now() req.open("GET",url+qs,true) req.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var src=this.responseText if(s.is_ww){$B.webworkers[name]=script $B.file_cache[filename]=src $B.dispatch_load_event(script)}else{$B.tasks.splice(0,0,[$B.run_script,script,src,name,url,true])} loop()}else if(this.status==404){throw Error(url+" not found")}}} req.send()}else{$B.RAISE(_b_.IOError,"can't load external script at "+ script.url+" (Ajax calls not supported with protocol file:///)")}} function add_jsmodule(module,source){ source+="\nvar $locals_"+ module.replace(/\./g,"_")+" = $module" $B.precompiled[module]=source} $B.inImported=function(module){if($B.imported.hasOwnProperty(module)){}else if(__BRYTHON__.VFS && __BRYTHON__.VFS.hasOwnProperty(module)){var elts=__BRYTHON__.VFS[module] var ext=elts[0],source=elts[1] if(ext==".py"){if($B.idb_cx){$B.tasks.splice(0,0,[idb_get,module])}}else{add_jsmodule(module,source)}}else{console.log("bizarre",module)} loop()} function report_remove_outdated(mod){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent('precompile',{detail:`remove outdated ${mod} from cache`}))}} function report_close(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent('precompile',{detail:"close"}))}} function report_done(){if(!$B.isWebWorker){document.dispatchEvent(new CustomEvent("brython_done",{detail:_b_.dict.$from_js($B.$options)}))}} var loop=$B.loop=function(){if($B.tasks.length==0){ report_done() return} var task=$B.tasks.shift(),func=task[0],args=task.slice(1) if(func=="execute"){let script=task[1],script_id=script.__name__.replace(/\./g,"_"),module=$B.module.$factory(script.__name__) module.__file__=script.__file__ module.__doc__=script.__doc__ $B.imported[script_id]=module try{var modobj=new Function(script.js+`\nreturn locals`)() for(var key in modobj){if(! key.startsWith('$')){try{module[key]=modobj[key]}catch(err){}}} $B.dispatch_load_event(script.script_element)}catch(err){ if(err.__class__===undefined){if(err.$py_exc){err=err.$py_exc}else{if($B.get_option('debug')> 2){console.log('JS error stack',err.stack)} var stack=err.$stack,frame_obj=err.$frame_obj,linenums=err.$linenums var lineNumber=err.lineNumber if(lineNumber !==undefined){console.log('around line',lineNumber) console.log(script.js.split('\n'). slice(lineNumber-4,lineNumber).join('\n'))} $B.print_stack() err=$B.EXC(_b_.RuntimeError,err+'') err.$stack=stack err.$frame_obj=frame_obj err.$linenums=linenums}} $B.handle_error(err)} loop()}else{ try{func.apply(null,args)}catch(err){$B.handle_error(err)}}} $B.tasks=[] $B.has_indexedDB=self.indexedDB !==undefined})(__BRYTHON__); ; ;(function($B){var _b_=$B.builtins,_window=globalThis,isWebWorker=('undefined' !==typeof WorkerGlobalScope)&& ("function"===typeof importScripts)&& (navigator instanceof WorkerNavigator) function missing_required_kwonly(fname,args){var plural=args.length==1 ? '' :'s',arg_list args=args.map(x=> `'${x}'`) if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+' and '+args[1]}else{arg_list=args.slice(0,args.length-1).join(', ')+', and '+ args[args.length-1]} $B.RAISE(_b_.TypeError,fname+'() '+ `missing ${args.length} required keyword-only argument${plural}: `+ arg_list)} function missing_required_pos(fname,args){var plural=args.length==1 ? '' :'s',arg_list args=args.map(x=> `'${x}'`) if(args.length==1){arg_list=args[0]}else if(args.length==2){arg_list=args[0]+' and '+args[1]}else{arg_list=args.slice(0,args.length-1).join(', ')+', and '+ args[args.length-1]} $B.RAISE(_b_.TypeError,fname+'() '+ `missing ${args.length} required positional argument${plural}: `+ arg_list)} function multiple_values(fname,arg){$B.RAISE(_b_.TypeError,fname+'() '+ `got multiple values for argument '${arg}'`)} function pos_only_passed_as_keyword(fname,arg){return $B.EXC(_b_.TypeError,fname+ `() got some positional-only arguments passed as keyword arguments:`+ ` '${arg}'`)} function too_many_pos_args(fname,kwarg,arg_names,nb_kwonly,defaults,args,slots){var nb_pos=args.length,last=$B.last(args) if(last !==null && last !==undefined && last.$kw){ if(! kwarg){var kw=$B.parse_kwargs(last.$kw,fname) for(var k in kw){if(! slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error(arg_names,k) throw unexpected_keyword(fname,k,suggestion)}}} nb_pos--} var nb_def=defaults.length var expected=arg_names.length-nb_kwonly,plural=expected==1 ? '' :'s' if(nb_def){expected=`from ${expected - nb_def} to ${expected}` plural='s'} var verb=nb_pos==1 ? 'was' :'were' return $B.EXC(_b_.TypeError,fname+'() takes '+ `${expected} positional argument${plural} but ${nb_pos} ${verb} given`)} function unexpected_keyword(fname,k,suggestion){var msg=`${fname}() got an unexpected keyword argument '${k}'` if(suggestion !==_b_.None){msg+=`. Did you mean: '${suggestion}'?`} return $B.EXC(_b_.TypeError,msg)} var empty={} function args0(f,args){ var arg_names=f.$infos.arg_names,code=f.$infos.__code__,slots={} for(var arg_name of arg_names){slots[arg_name]=empty} return $B.parse_args( args,f.$infos.__name__,code.co_argcount,slots,arg_names,f.$infos.__defaults__,f.$infos.__kwdefaults__,f.$infos.vararg,f.$infos.kwarg,code.co_posonlyargcount,code.co_kwonlyargcount)} function args0_NEW(fct,args){ const LAST_ARGS=args[args.length-1]; const HAS_KW=LAST_ARGS !==undefined && LAST_ARGS !==null && LAST_ARGS.$kw !==undefined; let ARGS_POS_COUNT=args.length,ARGS_NAMED=null; if(HAS_KW){--ARGS_POS_COUNT ARGS_NAMED=LAST_ARGS.$kw} const result={} const $INFOS=fct.$infos,$CODE=$INFOS.__code__,PARAMS_NAMES=$INFOS.arg_names,PARAMS_POS_COUNT=$CODE.co_argcount,PARAMS_NAMED_COUNT=$CODE.co_kwonlyargcount,PARAMS_VARARGS_NAME=$INFOS.vararg,PARAMS_KWARGS_NAME=$INFOS.kwarg,PARAMS_POS_DEFAULTS=$INFOS.__defaults__,PARAMS_POS_DEFAULTS_COUNT=PARAMS_POS_DEFAULTS.length,PARAMS_POS_DEFAULTS_OFFSET=PARAMS_POS_COUNT-PARAMS_POS_DEFAULTS_COUNT const min=Math.min(ARGS_POS_COUNT,PARAMS_POS_COUNT) let offset=0 for(;offset < min;++offset){result[PARAMS_NAMES[offset]]=args[offset]} if(PARAMS_VARARGS_NAME !==null ){ result[PARAMS_VARARGS_NAME]=$B.fast_tuple( Array.prototype.slice.call(args,PARAMS_POS_COUNT,ARGS_POS_COUNT ));}else if(ARGS_POS_COUNT > PARAMS_POS_COUNT){args0(fct,args) throw new Error('Too much positional arguments given (args0 should have raised an error) !')} if(ARGS_NAMED===null){ if(offset < PARAMS_POS_DEFAULTS_OFFSET){args0(fct,args) throw new Error('Not enough positional arguments given (args0 should have raised an error) !')} for(let i=offset-PARAMS_POS_DEFAULTS_OFFSET; i < PARAMS_POS_DEFAULTS_COUNT; ++i){result[PARAMS_NAMES[offset++]]=PARAMS_POS_DEFAULTS[i]} if(PARAMS_KWARGS_NAME !==null){result[PARAMS_KWARGS_NAME]=$B.empty_dict()} if(PARAMS_NAMED_COUNT===0 ){return result} const kwargs_defaults_values=fct.$kwdefaults_values; const nb_named_defaults=kwargs_defaults_values.length; if(nb_named_defaults < PARAMS_NAMED_COUNT){args0(fct,args) throw new Error('Named argument expected (args0 should have raised an error) !')} for(let i=0;i < nb_named_defaults;++i){result[PARAMS_NAMES[offset++]]=kwargs_defaults_values[i]} return result} const kwargs_defaults=fct.$kwdefaults; const PARAMS_POSONLY_COUNT=$CODE.co_posonlyargcount; if(offset < PARAMS_POSONLY_COUNT){if(offset < PARAMS_POS_DEFAULTS_OFFSET){args0(fct,args) throw new Error('Not enough positional parameters given (args0 should have raised an error) !')} const max=PARAMS_POS_DEFAULTS_COUNT- (PARAMS_POS_COUNT-PARAMS_POSONLY_COUNT) for(let i=offset-PARAMS_POS_DEFAULTS_OFFSET; i < max; ++i){result[PARAMS_NAMES[offset++]]=PARAMS_POS_DEFAULTS[i]}} if(PARAMS_KWARGS_NAME===null){let nb_named_args=0; let kargs=ARGS_NAMED[0]; for(let argname in kargs){result[argname ]=kargs[argname] ++nb_named_args} for(let id=1,len=ARGS_NAMED.length;id < len;++id){kargs=ARGS_NAMED[id]; for(let argname of $B.make_js_iterator($B.$getattr(kargs.__class__,"keys")(kargs))){if(typeof argname !=="string"){$B.args0_old(fct,args); throw new Error('Non string key passed in **kargs');} result[argname ]=$B.$getitem(kargs,argname); ++nb_named_args}} let found=0 let ioffset=offset for(;ioffset < PARAMS_POS_DEFAULTS_OFFSET;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result ){ continue} args0(fct,args) throw new Error('Missing a named arguments (args0 should have raised an error) !')} for(;ioffset < PARAMS_POS_COUNT;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result){continue} result[key]=PARAMS_POS_DEFAULTS[ioffset-PARAMS_POS_DEFAULTS_OFFSET] ++found} for(;ioffset < PARAMS_NAMES.length;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result ){continue} if(! kwargs_defaults.has(key)){args0(fct,args) throw new Error('Missing a named arguments (args0 should have raised an error) !');} result[key]=kwargs_defaults.get(key) ++found} if(found+nb_named_args !==PARAMS_NAMES.length-offset){args0(fct,args) throw new Error('Inexistant or duplicate named arguments (args0 should have raised an error) !')} return result} const extra={}; const HAS_PARAMS=fct.$hasParams; let nb_named_args=0 let nb_extra_args=0 let kargs=ARGS_NAMED[0]; for(let argname in kargs){if(HAS_PARAMS.has(argname)){result[argname ]=kargs[argname] ++nb_named_args}else{extra[argname ]=kargs[argname] ++nb_extra_args}} for(let id=1,len=ARGS_NAMED.length;id < len;++id){kargs=ARGS_NAMED[id]; for(let argname of $B.make_js_iterator($B.$getattr(kargs.__class__,"keys")(kargs))){if(typeof argname !=="string"){$B.args0_old(fct,args); throw new Error('Non string key passed in **kargs');} if(HAS_PARAMS.has(argname)){result[argname ]=$B.$getitem(kargs,argname); ++nb_named_args}else{extra[argname ]=$B.$getitem(kargs,argname); ++nb_extra_args}}} let found=0 let ioffset=offset for(;ioffset < PARAMS_POS_DEFAULTS_OFFSET;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result){ continue} args0(fct,args) throw new Error('Missing a named arguments (args0 should have raised an error) !')} for(;ioffset < PARAMS_POS_COUNT;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result){continue} result[key]=PARAMS_POS_DEFAULTS[ioffset-PARAMS_POS_DEFAULTS_OFFSET] ++found} for(;ioffset < PARAMS_NAMES.length;++ioffset){const key=PARAMS_NAMES[ioffset] if(key in result ){continue} if(! kwargs_defaults.has(key)){args0(fct,args) throw new Error('Missing a named arguments (args0 should have raised an error) !')} result[key]=kwargs_defaults.get(key) ++found} if(found+nb_named_args !==PARAMS_NAMES.length-offset){args0(fct,args) throw new Error('Inexistant or duplicate named arguments (args0 should have raised an error) !')} if(Object.keys(extra).length !==nb_extra_args){args0(fct,args) throw new Error('Duplicate name given to **kargs parameter (args0 should have raised an error) !')} result[PARAMS_KWARGS_NAME]=_b_.dict.$from_js(extra) return result} $B.args0_old=args0; $B.args0=args0_NEW; $B.args=function(fname,argcount,slots,var_names,args,$dobj,vararg,kwarg,nb_posonly){ var nb_posonly=nb_posonly ||0,nb_kwonly=var_names.length-argcount,defaults=[],kwdefaults={$jsobj:{}} for(var i=0,len=var_names.length;i < len;i++){var var_name=var_names[i] if($dobj.hasOwnProperty(var_name)){if(i < argcount){defaults.push($dobj[var_name])}else{kwdefaults.$jsobj[var_name]=$dobj[var_name]}}} for(var k in slots){slots[k]=empty} return $B.parse_args(args,fname,argcount,slots,var_names,defaults,kwdefaults,vararg,kwarg,nb_posonly,nb_kwonly)} $B.single_arg=function(fname,arg,args){var slots={} slots[arg]=null var $=$B.args(fname,1,slots,[arg],args,{},null,null) return $[arg]} $B.parse_args=function(args,fname,argcount,slots,arg_names,defaults,kwdefaults,vararg,kwarg,nb_posonly,nb_kwonly){ var nb_passed=args.length,nb_passed_pos=nb_passed, nb_expected=arg_names.length,nb_pos_or_kw=nb_expected-nb_kwonly,posonly_set={},nb_def=defaults.length,varargs=[],extra_kw={},kw for(var i=0;i < nb_passed;i++){var arg=args[i] if(arg && arg.__class__===$B.generator){slots.$has_generators=true} if(arg && arg.$kw){ nb_passed_pos-- kw=$B.parse_kwargs(arg.$kw,fname)}else{var arg_name=arg_names[i] if(arg_name !==undefined){if(i >=nb_pos_or_kw){if(vararg){varargs.push(arg)}else{throw too_many_pos_args( fname,kwarg,arg_names,nb_kwonly,defaults,args,slots)}}else{if(i < nb_posonly){posonly_set[arg_name]=true} slots[arg_name]=arg}}else if(vararg){varargs.push(arg)}else{throw too_many_pos_args( fname,kwarg,arg_names,nb_kwonly,defaults,args,slots)}}} for(var j=nb_passed_pos;j < nb_pos_or_kw;j++){var arg_name=arg_names[j] if(kw && kw.hasOwnProperty(arg_name)){ if(j < nb_posonly){ if(! kwarg){throw pos_only_passed_as_keyword(fname,arg_name)}}else{slots[arg_name]=kw[arg_name] kw[arg_name]=empty}} if(slots[arg_name]===empty){ var def_value=defaults[j-(nb_pos_or_kw-nb_def)] if(def_value !==undefined){slots[arg_name]=def_value if(j < nb_posonly){ if(kw && kw.hasOwnProperty(arg_name)&& kwarg){extra_kw[arg_name]=kw[arg_name] kw[arg_name]=empty}}}else{var missing_pos=arg_names.slice(j,nb_pos_or_kw-nb_def) throw missing_required_pos(fname,missing_pos)}}} var missing_kwonly=[] for(var i=nb_pos_or_kw;i < nb_expected;i++){var arg_name=arg_names[i] if(kw && kw.hasOwnProperty(arg_name)){slots[arg_name]=kw[arg_name] kw[arg_name]=empty}else{var kw_def=_b_.dict.$get_string(kwdefaults,arg_name) if(kw_def !==_b_.dict.$missing){slots[arg_name]=kw_def}else{missing_kwonly.push(arg_name)}}} if(missing_kwonly.length > 0){throw missing_required_kwonly(fname,missing_kwonly)} if(! kwarg){for(var k in kw){if(! slots.hasOwnProperty(k)){var suggestion=$B.offer_suggestions_for_unexpected_keyword_error( arg_names,k) throw unexpected_keyword(fname,k,suggestion)}}} for(var k in kw){if(kw[k]===empty){continue} if(! slots.hasOwnProperty(k)){if(kwarg){extra_kw[k]=kw[k]}}else if(slots[k]!==empty){if(posonly_set[k]&& kwarg){ extra_kw[k]=kw[k]}else{throw multiple_values(fname,k)}}else{slots[k]=kw[k]}} if(kwarg){slots[kwarg]=_b_.dict.$from_js(extra_kw)} if(vararg){slots[vararg]=$B.fast_tuple(varargs)} return slots} $B.parse_kwargs=function(kw_args,fname){var kwa=kw_args[0] for(var i=1,len=kw_args.length;i < len;i++){var kw_arg=kw_args[i],key,value if(kw_arg.__class__===_b_.dict){for(var entry of _b_.dict.$iter_items(kw_arg)){key=entry.key if(typeof key !=='string'){$B.RAISE(_b_.TypeError,fname+ "() keywords must be strings")}else if(kwa[key]!==undefined){$B.RAISE(_b_.TypeError,fname+ "() got multiple values for argument '"+ key+"'")}else{kwa[key]=entry.value}}}else{ var cls=$B.get_class(kw_arg) try{var keys_method=$B.$call1($B.$getattr(cls,'keys'))}catch(err){$B.RAISE(_b_.TypeError,`${fname} argument `+ `after ** must be a mapping, not ${$B.class_name(kw_arg)}`)} var keys_iter=$B.make_js_iterator(keys_method(kw_arg)),getitem for(var k of keys_iter){if(typeof k !=="string"){$B.RAISE(_b_.TypeError,fname+ "() keywords must be strings")} if(kwa[k]!==undefined){$B.RAISE(_b_.TypeError,fname+ "() got multiple values for argument '"+ k+"'")} if(! getitem){try{getitem=$B.$getattr(cls,'__getitem__')}catch(err){$B.RAISE(_b_.TypeError,`'${$B.class_name(kw_arg)}' object is not subscriptable`)}} kwa[k]=getitem(kw_arg,k)}}} return kwa} $B.check_nb_args=function(name,expected,args){ var len=args.length,last=args[len-1] if(last && last.$kw){var kw=last.$kw if(kw[1]){if(_b_.len(kw[1])==0){len--}}} if(len !=expected){if(expected==0){$B.RAISE(_b_.TypeError,name+"() takes no argument"+ " ("+len+" given)")}else{$B.RAISE(_b_.TypeError,name+"() takes exactly "+ expected+" argument"+(expected < 2 ? '' :'s')+ " ("+len+" given)")}}} $B.check_no_kw=function(name,x,y){ if((x.$kw && x.$kw[0]&& Object.keys(x.$kw[0]).length > 0)|| (y !==undefined && y.$kw)){$B.RAISE(_b_.TypeError,name+"() takes no keyword arguments")}} $B.check_nb_args_no_kw=function(name,expected,args){ var len=args.length,last=args[len-1] if(last && last.$kw){if(last.$kw.length==2 && Object.keys(last.$kw[0]).length==0){len--}else{$B.RAISE(_b_.TypeError,name+"() takes no keyword arguments")}} if(len !=expected){if(expected==0){$B.RAISE(_b_.TypeError,name+"() takes no argument"+ " ("+len+" given)")}else{$B.RAISE(_b_.TypeError,name+"() takes exactly "+ expected+" argument"+(expected < 2 ? '' :'s')+ " ("+len+" given)")}}} $B.check_annotate_format=function(format){if(! $B.$isinstance(format,_b_.int)){$B.RAISE(_b_.TypeError,'__annotate__ argument should be '+ `int, not ${$B.class_name(format)}`)} if(format !=1 && format !=2){$B.RAISE(_b_.NotImplementedError,'')}} $B.get_class=function(obj){ if(obj===null){return $B.imported.javascript.NullType } if(obj===undefined){return $B.imported.javascript.UndefinedType } var klass=obj.__class__ ||obj.$tp_class if(klass===undefined){switch(typeof obj){case "number": if(Number.isInteger(obj)){return _b_.int} break case "string": return _b_.str case "boolean": return _b_.bool case "function": if(! obj.$js_func){ return $B.function} case "object": if(Array.isArray(obj)){return $B.js_array}else if(obj instanceof $B.str_dict){return _b_.dict}else if(typeof Node !=="undefined" && obj instanceof Node){if(obj.tagName){return $B.imported['browser.html'][obj.tagName]|| $B.DOMNode} return $B.DOMNode}else if(obj instanceof Event){return $B.DOMEvent} break}} if(klass===undefined){return $B.get_jsobj_class(obj)} return klass} $B.class_name=function(obj){var klass=$B.get_class(obj) if(klass===$B.JSObj){return 'Javascript '+obj.constructor.name}else{return klass.__name__}} $B.unpack_mapping=function(func,obj){var items=[] if($B.$isinstance(obj,_b_.dict)){for(var item of _b_.dict.$iter_items(obj)){if(! $B.$isinstance(item.key,_b_.str)){$B.RAISE(_b_.TypeError,'keywords must be strings')} items.push(item)} return items} var klass=$B.get_class(obj) var getitem=$B.$getattr(klass,'__getitem__',null) if(getitem===null){$B.RAISE(_b_.TypeError,`'${$B.class_name(obj)}' object `+ 'is not subscriptable')} getitem=$B.$call(getitem) var key_func=$B.$getattr(klass,'keys',null) if(key_func===null){var f=`${func.$infos.__module__}.${func.$infos.__name__}` $B.RAISE(_b_.TypeError,`${f}() argument after **`+ ` must be a mapping, not ${$B.class_name(obj)}`)} var keys=$B.$call($B.$getattr(klass,'keys'))(obj) for(var key of $B.make_js_iterator(keys)){if(! $B.$isinstance(key,_b_.str)){$B.RAISE(_b_.TypeError,'keywords must be strings')} items.push({key,value:getitem(obj,key)})} return items} $B.make_js_iterator=function(iterator,frame,lineno){ var set_lineno=$B.set_lineno if(frame===undefined){if(! $B.frame_obj){set_lineno=function(){}}else{frame=$B.frame_obj.frame lineno=frame.$lineno}} if(iterator.__class__===_b_.range){var obj={ix:iterator.start} if(iterator.step > 0){return{ [Symbol.iterator](){return this},next(){set_lineno(frame,lineno) if(obj.ix >=iterator.stop){return{done:true,value:null}} var value=obj.ix obj.ix+=iterator.step return{done:false,value}}}}else{return{ [Symbol.iterator](){return this},next(){set_lineno(frame,lineno) if(obj.ix <=iterator.stop){return{done:true,value:null}} var value=obj.ix obj.ix+=iterator.step return{done:false,value}}}}} if(iterator[Symbol.iterator]&& ! iterator.$is_js_array){var it=iterator[Symbol.iterator]() return{ [Symbol.iterator](){return this},next(){set_lineno(frame,lineno) return it.next()}}} var next_func=$B.$getattr(_b_.iter(iterator),'__next__',null) if(next_func !==null){next_func=$B.$call(next_func) return{ [Symbol.iterator](){return this},next(){set_lineno(frame,lineno) try{var value=next_func() return{done:false,value}}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return{done:true,value:null}} if(iterator.$inum){$B.set_inum(iterator.$inum)} throw err}}}}} $B.unpacker=function(obj,nb_targets,has_starred){ var inum_rank=3 if(has_starred){var nb_after_starred=arguments[3] inum_rank++} var inum=arguments[inum_rank] var t=_b_.list.$factory(obj),right_length=t.length,left_length=nb_targets+(has_starred ? nb_after_starred-1 :0) if((! has_starred &&(right_length < nb_targets))|| (has_starred &&(right_length < nb_targets-1))){$B.set_inum(inum) var exc=$B.EXC(_b_.ValueError,`not enough values to unpack `+ `(expected ${has_starred ? ' at least ' : ''} `+ `${left_length}, got ${right_length})`) throw exc} if((! has_starred)&& right_length > left_length){var exc=$B.EXC(_b_.ValueError,"too many values to unpack "+ `(expected ${left_length}, got ${right_length})`) throw exc} t.index=-1 t.read_one=function(){t.index++ return t[t.index]} t.read_rest=function(){ t.index++ var res=t.slice(t.index,t.length-nb_after_starred) t.index=t.length-nb_after_starred-1 return $B.$list(res)} return t} $B.set_lineno=function(frame,lineno,type){frame.$lineno=lineno if(frame.$f_trace !==_b_.None){$B.trace_line()} if(type){frame[type]=frame[type]||{} frame[type][lineno]=true} return true} $B.get_method_class=function(method,ns,qualname,refs){ var klass=ns if(method.$function_infos && method.$function_infos[$B.func_attrs.method_class]){return method.$function_infos[$B.func_attrs.method_class]} for(var ref of refs){if(klass[ref]===undefined){return $B.make_class(qualname)} klass=klass[ref]} return klass} $B.warn=function(klass,message,filename,token){var warning=$B.EXC(klass,message) warning.filename=filename if(klass===_b_.SyntaxWarning){warning.lineno=token.lineno warning.offset=token.col_offset warning.end_lineno=token.end_lineno warning.end_offset=token.end_coloffset warning.text=token.line warning.args[1]=$B.fast_tuple([filename,warning.lineno,warning.offset,warning.text,warning.end_lineno,warning.end_offset])} $B.imported._warnings.warn(warning)} $B.assert=function(test,msg,inum){if(! $B.$bool(test)){var exc=$B.EXC(_b_.AssertionError,msg) $B.set_inum(inum) throw exc}} function index_error(obj){var type=typeof obj=="string" ? "string" :"list" return $B.EXC(_b_.IndexError,type+" index out of range")} $B.$getitem=function(obj,item,inum){try{return $B.$getitem1(obj,item)}catch(err){$B.set_inum(inum) throw err}} $B.$getitem1=function(obj,item){var is_list=Array.isArray(obj)&& obj.__class__===_b_.list,is_dict=obj.__class__===_b_.dict && ! obj.$jsobj if(typeof item=="number"){if(is_list ||typeof obj=="string"){item=item >=0 ? item :obj.length+item if(obj[item]!==undefined){return obj[item]}else{throw index_error(obj)}}}else if(item.valueOf && typeof item.valueOf()=="string" && is_dict){return _b_.dict.$getitem(obj,item)} if(obj.$is_class){if(! Array.isArray(item)){item=$B.fast_tuple([item])} if(obj===_b_.type){return $B.$class_getitem(obj,item)} var class_gi=$B.$getattr(obj,"__class_getitem__",_b_.None) if(class_gi !==_b_.None){return $B.$call(class_gi)(item)}else if(obj.__class__){class_gi=$B.$getattr(obj.__class__,"__getitem__",_b_.None) if(class_gi !==_b_.None){return class_gi(obj,item)}else{$B.RAISE(_b_.TypeError,"type '"+ $B.$getattr(obj,'__qualname__')+ "' is not subscriptable")}}} if(is_list){return _b_.list.$getitem(obj,item)} if(is_dict){return _b_.dict.$getitem(obj,item)} var gi=$B.$getattr(obj.__class__ ||$B.get_class(obj),"__getitem__",_b_.None) if(gi !==_b_.None){return gi(obj,item)} var exc=$B.EXC(_b_.TypeError,"'"+$B.class_name(obj)+ "' object is not subscriptable") throw exc} $B.getitem_slice=function(obj,slice){var res if(Array.isArray(obj)&& obj.__class__===_b_.list){return _b_.list.$getitem(obj,slice)}else if(typeof obj=="string"){return _b_.str.__getitem__(obj,slice)} return $B.$getattr($B.get_class(obj),"__getitem__")(obj,slice)} $B.$getattr_pep657=function(obj,attr,inum){try{return $B.$getattr(obj,attr)}catch(err){$B.set_inum(inum) throw err}} $B.$setitem=function(obj,item,value,inum){if(Array.isArray(obj)&& obj.__class__===undefined && ! obj.$is_js_array && typeof item=="number" && ! $B.$isinstance(obj,_b_.tuple)){if(item < 0){item+=obj.length} if(obj[item]===undefined){$B.set_inum(inum) $B.RAISE(_b_.IndexError,"list assignment index out of range")} obj[item]=value return}else if(obj.__class__===_b_.dict){_b_.dict.$setitem(obj,item,value) return}else if(obj.__class__===_b_.list){try{return _b_.list.$setitem(obj,item,value)}catch(err){if($B.is_exc(err,[_b_.IndexError])){$B.set_inum(inum)} throw err}} var si=$B.$getattr(obj.__class__ ||$B.get_class(obj),"__setitem__",null) if(si===null ||typeof si !='function'){$B.set_inum(inum) $B.RAISE(_b_.TypeError,"'"+$B.class_name(obj)+ "' object does not support item assignment")} return si(obj,item,value)} $B.set_inum=function(inum){if(inum !==undefined && $B.frame_obj){$B.frame_obj.frame.inum=inum}} $B.$delitem=function(obj,item,inum){if(Array.isArray(obj)&& obj.__class__===_b_.list && typeof item=="number" && !$B.$isinstance(obj,_b_.tuple)){if(item < 0){item+=obj.length} if(obj[item]===undefined){$B.set_inum(inum) $B.RAISE(_b_.IndexError,"list deletion index out of range")} obj.splice(item,1) return}else if(obj.__class__===_b_.dict){if(obj.$is_namespace){ Object.defineProperty(obj.$jsobj,item,{get(){throw $B.name_error(item)},set(value){ Object.defineProperty(obj.$jsobj,item,{value}) return _b_.None}} )}else{try{_b_.dict.__delitem__(obj,item)}catch(err){if(err.__class__===_b_.KeyError){$B.set_inum(inum)} throw err}} return}else if(obj.__class__===_b_.list){try{return _b_.list.__delitem__(obj,item)}catch(err){if(err.__class__===_b_.IndexError){$B.set_inum(inum)} throw err}} var di=$B.search_in_mro($B.get_class(obj),"__delitem__") if(di===undefined){$B.RAISE(_b_.TypeError,"'"+$B.class_name(obj)+ "' object doesn't support item deletion")} return di(obj,item)} $B.delete_for_reassign=function(name,namespace){ if(namespace.$is_namespace){return $B.$delitem(namespace,name)} if(namespace.hasOwnProperty && namespace.hasOwnProperty(name)){try{var value=namespace[name]}catch(err){ return} var klass=$B.get_class(value) if($B.$isinstance(value,$B.DOMNode)){}else{var del_method=$B.search_in_mro(klass,'__del__') if(del_method){$B.$call(del_method)(value)}}} delete namespace[name]} function num_result_type(x,y){var is_int,is_float,x_num,y_num if(typeof x=="number"){x_num=x if(typeof y=="number"){is_int=true y_num=y}else if(y.__class__===_b_.float){is_float=true y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value if(typeof y=="number"){y_num=y is_float=true}else if(y.__class__===_b_.float){is_float=true y_num=y.value}} return{is_int,is_float,x:x_num,y:y_num}} $B.augm_assign=function(left,op,right){var res_type=num_result_type(left,right) if(res_type.is_int ||res_type.is_float){var z switch(op){case '+=': z=res_type.x+res_type.y break case '-=': z=res_type.x-res_type.y break case '*=': z=res_type.x*res_type.y break case '/=': return $B.fast_float(res_type.x/res_type.y)} if(z){if(res_type.is_int && Number.isSafeInteger(z)){return z}else if(res_type.res_is_float){return $B.fast_float(z)}}}else if(op=='*='){if(typeof left=="number" && typeof right=="string"){return left <=0 ? '' :right.repeat(left)}else if(typeof left=="string" && typeof right=="number"){return right <=0 ? '' :left.repeat(right)}}else if(op=='+='){if(typeof left=="string" && typeof right=="string"){return left+right}} var op1=op.substr(0,op.length-1),method=$B.op2method.augmented_assigns[op],augm_func=$B.$getattr(left,'__'+method+'__',null) if(augm_func !==null){var res=$B.$call(augm_func)(right) if(res===_b_.NotImplemented){$B.RAISE(_b_.TypeError,`unsupported operand type(s)`+ ` for ${op}: '${$B.class_name(left)}' `+ `and '${$B.class_name(right)}'`)} return res}else{var method1=$B.op2method.operations[op1] if(method1===undefined){method1=$B.op2method.binary[op1]} return $B.rich_op(`__${method1}__`,left,right)}} $B.$is=function(a,b){ if((a===undefined ||a===$B.Undefined)&& (b===undefined ||b===$B.Undefined)){return true} if(a===null){return b===null} if(b===null){return a===null} if(a.__class__===_b_.float && b.__class__===_b_.float){if(isNaN(a.value)&& isNaN(b.value)){return true} return a.value==b.value} if((a===_b_.int && b==$B.long_int)|| (a===$B.long_int && b===_b_.int)){return true} return a===b} $B.is_or_equals=function(x,y){ return $B.$is(x,y)||$B.rich_comp('__eq__',x,y)} $B.member_func=function(obj){var klass=$B.get_class(obj),contains=$B.$getattr(klass,"__contains__",null) if(contains !==null){contains=$B.$call(contains) return contains.bind(null,obj)} try{ var iterator=$B.make_js_iterator(obj) return function(key){try{for(var item of iterator){if($B.is_or_equals(key,item)){return true}} return false}catch(err){return false}}}catch(err){ var getitem=$B.$getattr(klass,'__getitem__',null) if(getitem !==null){return function(key){var i=-1 while(true){i++ try{var item=getitem(obj,i) if($B.is_or_equals(key,item)){return true}}catch(err){if($B.$is_exc(err,[_b_.StopIteration])){return false} throw err}}}}else{$B.RAISE(_b_.TypeError,'argument of type '+ `'${$B.class_name(obj)}' is not iterable`)}}} $B.$is_member=function(item,_set){return $B.member_func(_set)(item)} $B.$call=function(callable,inum){try{callable=$B.$call1(callable)}catch(err){$B.set_inum(inum) throw err} return function(){try{return callable.apply(null,arguments)}catch(exc){$B.set_inum(inum) throw exc}} return callable} $B.$call1=function(callable){if(callable.__class__===$B.method){return callable}else if(callable.__class__===_b_.staticmethod){return callable.__func__}else if(callable.$factory){return callable.$factory}else if(callable.$is_class){ return callable.$factory=$B.$instance_creator(callable)}else if(callable.$is_js_class){ return callable.$factory=function(){return new callable(...arguments)}}else if(callable.$in_js_module){ return function(){var res=callable(...arguments) return res===undefined ? _b_.None :res}}else if(callable.$is_func ||typeof callable=="function"){if(callable.$function_infos){var flags=callable.$function_infos[$B.func_attrs.flags] if(flags & $B.COMPILER_FLAGS.GENERATOR){ $B.frame_obj.frame.$has_generators=true} if(flags & $B.COMPILER_FLAGS.COROUTINE){if($B.frame_obj !==null){var frame=$B.frame_obj.frame frame.$async=callable}}} return callable} try{return $B.$getattr(callable,"__call__")}catch(err){$B.RAISE(_b_.TypeError,"'"+$B.class_name(callable)+ "' object is not callable")}} var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"] var ropsigns=["+","-","*","/","//","%","**","<<",">>","&","^","|"] $B.make_rmethods=function(klass){for(var r_opname of r_opnames){if(klass["__r"+r_opname+"__"]===undefined && klass['__'+r_opname+'__']){klass["__r"+r_opname+"__"]=(function(name){return function(self,other){return klass["__"+name+"__"](other,self)}})(r_opname)}}} $B.UUID=function(){return $B.$py_UUID++} $B.to_num=function(obj,methods){ var expected_class={"__complex__":_b_.complex,"__float__":_b_.float,"__index__":_b_.int,"__int__":_b_.int} var klass=obj.__class__ ||$B.get_class(obj) for(var i=0;i < methods.length;i++){var missing={},method=$B.$getattr(klass,methods[i],missing) if(method !==missing){var res=method(obj) if(!$B.$isinstance(res,expected_class[methods[i]])){$B.RAISE(_b_.TypeError,methods[i]+"returned non-"+ expected_class[methods[i]].__name__+ "(type "+$B.get_class(res)+")")} return{result:res,method:methods[i]}}} return null} $B.PyNumber_Index=function(item){switch(typeof item){case "boolean": return item ? 1 :0 case "number": return item case "object": if(item.__class__===$B.long_int){return item} if($B.$isinstance(item,_b_.int)){ return item.$brython_value} var method=$B.$getattr(item,"__index__",_b_.None) if(method !==_b_.None){method=typeof method=="function" ? method :$B.$getattr(method,"__call__") return $B.int_or_bool(method())}else{$B.RAISE(_b_.TypeError,"'"+$B.class_name(item)+ "' object cannot be interpreted as an integer")} default: $B.RAISE(_b_.TypeError,"'"+$B.class_name(item)+ "' object cannot be interpreted as an integer")}} $B.int_or_bool=function(v){switch(typeof v){case "boolean": return v ? 1 :0 case "number": return v case "object": if(v.__class__===$B.long_int){return v}else{$B.RAISE(_b_.TypeError,"'"+$B.class_name(v)+ "' object cannot be interpreted as an integer")} default: $B.RAISE(_b_.TypeError,"'"+$B.class_name(v)+ "' object cannot be interpreted as an integer")}} $B.enter_frame=function(frame,__file__,lineno){ var count=$B.frame_obj===null ? 0 :$B.frame_obj.count if(count > $B.recursion_limit){var exc=$B.EXC(_b_.RecursionError,"maximum recursion depth exceeded") $B.set_exc(exc,frame) throw exc} frame.__class__=$B.frame frame.__file__=__file__ frame.$lineno=lineno frame.$f_trace=_b_.None frame.$has_generators=!! frame[1].$has_generators $B.frame_obj={prev:$B.frame_obj,frame,count:count+1} if($B.tracefunc !==_b_.None){if(frame[4]===$B.tracefunc || ($B.tracefunc.$infos && frame[4]&& frame[4]===$B.tracefunc.$infos.__func__)){ $B.tracefunc.$frame_id=frame[0] frame.$f_trace=_b_.None return}else{ var frame_obj=$B.frame_obj while(frame_obj !==null){if(frame_obj.frame[0]==$B.tracefunc.$frame_id){frame.$f_trace=_b_.None return} frame_obj=frame_obj.prev} try{var res=$B.tracefunc(frame,'call',_b_.None) var frame_obj=$B.frame_obj while(frame_obj !==null){if(frame_obj.frame[4]==res){return _b_.None} frame_obj=frame_obj.prev} frame.$f_trace=res return}catch(err){$B.set_exc(err,frame) $B.frame_obj=$B.frame_obj.prev err.$in_trace_func=true throw err}}}} $B.trace_exception=function(){var frame=$B.frame_obj.frame if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None} var trace_func=frame.$f_trace,exc=frame[1].$current_exception return trace_func(frame,'exception',$B.fast_tuple([exc.__class__,exc,$B.traceback.$factory(exc)]))} $B.trace_line=function(){var frame=$B.frame_obj.frame if(frame[0]==$B.tracefunc.$current_frame_id){return _b_.None} var trace_func=frame.$f_trace if(trace_func===undefined){console.log('trace line, frame',frame)} return trace_func(frame,'line',_b_.None)} $B.trace_return=function(value){var frame=$B.frame_obj.frame,trace_func=frame.$f_trace if(frame[0]==$B.tracefunc.$current_frame_id){ return _b_.None} trace_func(frame,'return',value)} $B.leave_frame=function(arg){ if($B.frame_obj===null){return} if(arg && arg.value !==undefined && $B.tracefunc !==_b_.None){if($B.frame_obj.frame.$f_trace===undefined){$B.frame_obj.frame.$f_trace=$B.tracefunc} if($B.frame_obj.frame.$f_trace !==_b_.None){$B.trace_return(arg.value)}} if($B.frame_obj===undefined){throw Error('no frame_obj')} var frame=$B.frame_obj.frame if(frame.$coroutine){if(! frame.$coroutine.$sent){var cname=frame.$coroutine.$func.$function_infos[$B.func_attrs.name] var message=$B.EXC(_b_.RuntimeWarning,`coroutine '${cname}' was never awaited`) message.lineno=frame.$coroutine.$lineno $B.imported._warnings.warn(message)}} $B.frame_obj=$B.frame_obj.prev if(frame.$has_generators){for(var key in frame[1]){if(frame[1][key]&& frame[1][key].__class__===$B.generator){var gen=frame[1][key] if(gen.$frame===undefined){continue} var ctx_managers=gen.$frame[1].$context_managers if(ctx_managers){for(var cm of ctx_managers){$B.$call($B.$getattr(cm,'__exit__'))( _b_.None,_b_.None,_b_.None)}}}}} if(frame[1].$current_exception){delete frame[1].$current_exception} return _b_.None} $B.trace_return_and_leave=function(frame,return_value){if(frame.$f_trace !==_b_.None){$B.trace_return(return_value)} $B.leave_frame() return return_value} $B.push_frame=function(frame){var count=$B.frame_obj===null ? 0 :$B.frame_obj.count return{ prev:$B.frame_obj,frame,count:count+1}} var reversed_op={"__lt__":"__gt__","__le__":"__ge__","__gt__":"__lt__","__ge__":"__le__"} var method2comp={"__lt__":"<","__le__":"<=","__gt__":">","__ge__":">="} $B.rich_comp=function(op,x,y){if(x===undefined){console.log(Error().stack) $B.RAISE(_b_.RuntimeError,'error in rich comp')} var x1=x !==null && x.valueOf ? x.valueOf():x,y1=y !==null && y.valueOf ? y.valueOf():y if(typeof x1=="number" && typeof y1=="number" && x.__class__===undefined && y.__class__===undefined){switch(op){case "__eq__": return x1==y1 case "__ne__": return x1 !=y1 case "__le__": return x1 <=y1 case "__lt__": return x1 < y1 case "__ge__": return x1 >=y1 case "__gt__": return x1 > y1}} var res if(x !==null &&(x.$is_class ||x.$factory)){if(op=="__eq__"){return(x===y)}else if(op=="__ne__"){return !(x===y)}else{$B.RAISE(_b_.TypeError,"'"+method2comp[op]+ "' not supported between instances of '"+$B.class_name(x)+ "' and '"+$B.class_name(y)+"'")}} var rev_op=reversed_op[op]||op,y_rev_func if(x !==null && x.__class__ && y !==null && y.__class__){ if(y.__class__.__mro__.indexOf(x.__class__)>-1){y_rev_func=$B.$getattr(y,rev_op) res=$B.$call(y_rev_func)(x) if(res !==_b_.NotImplemented){return res}}} var in_mro=$B.search_in_mro($B.get_class(x),op) if(in_mro===undefined){$B.RAISE(_b_TypeError,`no attribute ${op}`)} var getter=$B.search_in_mro($B.get_class(in_mro),'__get__') if(getter){res=$B.$call(getter(in_mro,x,$B.get_class(x)))(y)}else{if(typeof in_mro !=='function'){var call_in_mro=$B.search_in_mro($B.get_class(in_mro),'__call__') if(call_in_mro){res=call_in_mro(in_mro,y)}else{$B.RAISE(_b_.TypeError,`not callable {op}`)}}else{res=in_mro(x,y)}} if(res !==_b_.NotImplemented){return res} if(y_rev_func===undefined){ y_rev_func=$B.$call($B.$getattr($B.get_class(y),rev_op)) res=y_rev_func(y,x) if(res !==_b_.NotImplemented ){return res}} if(op=="__eq__"){return _b_.False}else if(op=="__ne__"){return _b_.True} $B.RAISE(_b_.TypeError,"'"+method2comp[op]+ "' not supported between instances of '"+$B.class_name(x)+ "' and '"+$B.class_name(y)+"'")} var opname2opsign={__sub__:"-",__xor__:"^",__mul__:"*",__and__:'&',__or__:'|'} $B.get_position_from_inum=function(inum){ if($B.frame_obj !==null){var frame=$B.frame_obj.frame if(frame.positions){return frame.positions[Math.floor(inum/2)]}}} $B.rich_op=function(op,x,y,inum){try{return $B.rich_op1(op,x,y)}catch(exc){$B.set_inum(inum) throw exc}} $B.rich_op1=function(op,x,y){ var res_is_int,res_is_float,x_num,y_num if(typeof x=="number"){x_num=x if(typeof y=="number"){res_is_int=true y_num=y}else if(y.__class__===_b_.float){res_is_float=true y_num=y.value}}else if(x.__class__===_b_.float){x_num=x.value if(typeof y=="number"){y_num=y res_is_float=true}else if(y.__class__===_b_.float){res_is_float=true y_num=y.value}} if(res_is_int ||res_is_float){var z switch(op){case "__add__": z=x_num+y_num break case "__sub__": z=x_num-y_num break case "__mul__": z=x_num*y_num break case '__pow__': if(res_is_int && y_num >=0){return _b_.int.$int_or_long(BigInt(x_num)**BigInt(y_num))} break case "__truediv__": if(y_num==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} z=x_num/y_num return{__class__:_b_.float,value:z}} if(z){if(res_is_int && Number.isSafeInteger(z)){return z}else if(res_is_float){return{__class__:_b_.float,value:z}}}}else if(typeof x=="string" && typeof y=="string" && op=="__add__"){return x+y} var x_class=x.__class__ ||$B.get_class(x),y_class=y.__class__ ||$B.get_class(y),rop='__r'+op.substr(2),method if(x_class===y_class){ if(x_class===_b_.int){return _b_.int[op](x,y)}else if(x_class===_b_.bool){return(_b_.bool[op]||_b_.int[op]) (x,y)} try{method=$B.$call($B.$getattr(x_class,op))}catch(err){if(err.__class__===_b_.AttributeError){var kl_name=$B.class_name(x) $B.RAISE(_b_.TypeError,"unsupported operand type(s) "+ "for "+opname2opsign[op]+": '"+kl_name+"' and '"+ kl_name+"'")} throw err} return method(x,y)} if(_b_.issubclass(y_class,x_class)){ var reflected_left=$B.$getattr(x_class,rop,false),reflected_right=$B.$getattr(y_class,rop,false) if(reflected_right && reflected_left && reflected_right !==reflected_left){return reflected_right(y,x)}} if(op=='__mul__'){if(x_class.$is_sequence && $B.$isinstance(y,[_b_.float,_b_.complex])){$B.RAISE(_b_.TypeError,"can't multiply sequence by "+ `non-int of type '${$B.class_name(y)}'`)} if(y_class.$is_sequence && $B.$isinstance(x,[_b_.float,_b_.complex])){$B.RAISE(_b_.TypeError,"can't multiply sequence by "+ `non-int of type '${$B.class_name(x)}'`)}} var res var fail try{res=$B.call_with_mro(x,op,y) if(res===_b_.NotImplemented){fail=true}}catch(err){if(! $B.is_exc(err,[_b_.AttributeError])){throw err} fail=true} if(! fail){return res} fail=false try{res=$B.call_with_mro(y,rop,x) if(res===_b_.NotImplemented){fail=true}}catch(err){if(! $B.is_exc(err,[_b_.AttributeError])){throw err} fail=true} if(! fail){return res} $B.RAISE(_b_.TypeError,`unsupported operand type(s) for ${$B.method_to_op[op]}:`+ ` '${$B.class_name(x)}' and '${$B.class_name(y)}'`)} $B.is_none=function(o){return o===undefined ||o===null ||o==_b_.None} var repr_stack=new Set() $B.repr={enter:function(obj){var obj_id=_b_.id(obj) if(repr_stack.has(obj_id)){return true}else{repr_stack.add(obj_id) if(repr_stack.size > $B.recursion_limit){repr_stack.clear() $B.RAISE(_b_.RecursionError,"maximum recursion depth "+ "exceeded while getting the repr of an object")}}},leave:function(obj){repr_stack.delete(_b_.id(obj))}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var object={ __name__:'object',__qualname__:'object',$is_class:true,$native:true} object.__delattr__=function(self,attr){ var klass=$B.get_class(self) var kl_attr=$B.search_in_mro(klass,attr) if(kl_attr !==undefined && _b_.hasattr(kl_attr,'__delete__')){return $B.$getattr(kl_attr,'__delete__')(self)} if(self.__dict__ && $B.$isinstance(self.__dict__,_b_.dict)&& _b_.dict.$contains_string(self.__dict__,attr)){_b_.dict.$delete_string(self.__dict__,attr) delete self[attr] return _b_.None}else if(self.__dict__===undefined && self[attr]!==undefined){delete self[attr] return _b_.None} throw $B.attr_error(attr,self)} object.__dir__=function(self){var objects if(self.$is_class){objects=[self].concat(self.__mro__)}else{var klass=self.__class__ ||$B.get_class(self) objects=[self,klass].concat(klass.__mro__)} var res=[] for(var i=0,len=objects.length;i < len;i++){for(let attr in objects[i]){if(attr.charAt(0)=="$"){if(attr.charAt(1)=="$"){ res.push(attr.substr(2))} continue} if(! isNaN(parseInt(attr.charAt(0)))){ continue} if(attr=="__mro__"){continue} res.push(attr)}} if(self.__dict__){for(let attr of $B.make_js_iterator(self.__dict__)){if(attr.charAt(0)!="$"){res.push(attr)}}} res=_b_.list.$factory(_b_.set.$factory(res)) _b_.list.sort(res) return res} object.__eq__=function(self,other){ return self===other ? true :_b_.NotImplemented} object.__format__=function(){var $=$B.args("__format__",2,{self:null,spec:null},["self","spec"],arguments,{},null,null) if($.spec !==""){$B.RAISE(_b_.TypeError,"non-empty format string passed to object.__format__")} return _b_.getattr($.self,"__str__")()} object.__ge__=function(){return _b_.NotImplemented} $B.nb_from_dict=0 object.__getattribute__=function(obj,attr){var klass=obj.__class__ ||$B.get_class(obj),is_own_class_instance_method=false var $test=false if($test){console.log("object.__getattribute__, attr",attr,"de",obj,"klass",klass) console.log('obj.__dict__',obj.__dict__)} if(attr==="__class__"){return klass} if(obj.$is_class && attr=='__bases__'){throw $B.attr_error(attr,obj)} var res=obj[attr] if($test){console.log('obj[attr]',obj[attr])} if(Array.isArray(obj)&& Array.prototype[attr]!==undefined){ res=undefined} if(res===undefined && obj.__dict__){var dict=obj.__dict__ if($test){console.log('obj.__dict__',obj.__dict__)} if(dict.__class__===$B.getset_descriptor){return dict.cls[attr]} var in_dict=_b_.dict.$get_string(dict,attr) if(in_dict !==_b_.dict.$missing){return in_dict}} if(res===undefined){ function check(obj,kl,attr){var v if(kl.__dict__){v=_b_.dict.$get_string(kl.__dict__,attr) if(v !==_b_.dict.$missing){return v}} v=kl[attr] if(v !==undefined){if($test){console.log('check, kl',kl,'attr',attr,'v',v)} return v}} res=check(obj,klass,attr) if(res===undefined){var mro=klass.__mro__ for(let i=0,len=mro.length;i < len;i++){res=check(obj,mro[i],attr) if($test){console.log('in class',mro[i],'res',res)} if(res !==undefined){if($test){console.log("found in",mro[i])} break}}}else{if($test){console.log(attr,'found in own class')} if(res.__class__ !==$B.method && res.__get__===undefined){is_own_class_instance_method=true}}}else{if(res.__set__===undefined){ return res}} if($test){console.log('after search classes',res)} if(res !==undefined){if($test){console.log(res)} if(res.__class__ && _b_.issubclass(res.__class__,_b_.property)){return $B.$getattr(res,'__get__')(obj,klass)}else if(res.__class__===_b_.classmethod){return _b_.classmethod.__get__(res,obj,klass)} if(res.__class__===$B.method){if(res.$infos.__self__){ return res} return $B.method.__get__(res)} var get=res.__get__ if(get===undefined && res.__class__){get=res.__class__.__get__ for(let i=0;i < res.__class__.__mro__.length && get===undefined;i++){get=res.__class__.__mro__[i].__get__}} if($test){console.log("get",get)} var __get__=get===undefined ? null : $B.$getattr(res,"__get__",null) if($test){console.log("__get__",__get__)} if(__get__ !==null){if($test){console.log('apply __get__',[obj,klass])} try{return __get__.apply(null,[obj,klass])}catch(err){if($B.get_option('debug')> 2){console.log('error in get.apply',err) console.log("get attr",attr,"of",obj) console.log('res',res) console.log('__get__',__get__) console.log(__get__+'')} throw err}} if(__get__===null &&(typeof res=="function")){__get__=function(x){return x}} if(__get__ !==null){ res.__name__=attr if(attr=="__new__" || res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"} var res1=__get__.apply(null,[res,obj,klass]) if($test){console.log("res",res,"res1",res1)} if(typeof res1=="function"){ if(res1.__class__===$B.method){return res} if(res.$type=="staticmethod"){return res}else{var self=res.__class__===$B.method ? klass :obj,method=function(){var args=[self] for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} return res.apply(this,args)} method.__class__=$B.method method.__get__=function(obj,cls){var clmethod=res.bind(null,cls) clmethod.__class__=$B.method clmethod.$infos={__self__:cls,__func__:res,__name__:res.$infos.__name__,__qualname__:cls.__name__+"."+ res.$infos.__name__} return clmethod} method.__get__.__class__=$B.method_wrapper method.__get__.$infos=res.$infos method.$infos={__self__:self,__func__:res,__name__:attr,__qualname__:klass.__qualname__+"."+attr} if($test){console.log("return method",method)} if(is_own_class_instance_method){obj.$method_cache=obj.$method_cache ||{} obj.$method_cache[attr]=[method,res]} return method}}else{ return res1}} return res}else if(obj.hasOwnProperty && obj.hasOwnProperty(attr)&& ! Array.isArray(obj)){return $B.Undefined}else{throw $B.attr_error(attr,obj)}} object.__gt__=function(){return _b_.NotImplemented} object.__hash__=function(self){var hash=self.__hashvalue__ if(hash !==undefined){return hash} return self.__hashvalue__=$B.$py_next_hash--} object.__init__=function(){if(arguments.length==0){$B.RAISE(_b_.TypeError,"descriptor '__init__' of 'object' "+ "object needs an argument")} var $=$B.args('__init__',1,{self:null},['self'],arguments,{},'args','kw'),self=$.self if($.args.length > 0 ||_b_.dict.__len__($.kw)> 0){var type=$B.get_class(self) var tp_init=$B.search_in_mro(type,'__init__') if(tp_init !==object.__init__){$B.RAISE(_b_.TypeError,"object.__init__() takes exactly one argument (the instance to initialize)")} var tp_new=$B.search_in_mro(type,'__new__') if(tp_new==object.__new__){$B.RAISE(_b_.TypeError,`${$B.class_name(self)}.__init__() takes exactly`+ ` one argument (the instance to initialize)`)}} return _b_.None} object.__le__=function(){return _b_.NotImplemented} object.__lt__=function(){return _b_.NotImplemented} object.__mro__=[] object.$new=function(cls){return function(){var $=$B.args('__new__',0,[],[],arguments,{},'args','kwargs') if($.args.length > 0 ||_b_.dict.__len__($.kwargs)> 0){$B.RAISE(_b_.TypeError,"object() takes no parameters")} var res=Object.create(null) res.__class__=cls res.__dict__=$B.obj_dict({}) return res}} object.$no_new_init=function(cls){ var res=Object.create(null) res.__class__=cls res.__dict__=$B.obj_dict({}) return res} object.__new__=function(cls,...args){if(cls===undefined){$B.RAISE(_b_.TypeError,"object.__new__(): not enough arguments")} var init_func=$B.$getattr(cls,"__init__") if(init_func===object.__init__){if(args.length > 0){$B.RAISE(_b_.TypeError,"object() takes no parameters")}} var res=Object.create(null) $B.update_obj(res,{__class__ :cls,__dict__:$B.obj_dict({})}) return res} object.__ne__=function(self,other){if(self===other){return false} var eq=$B.$getattr(self.__class__ ||$B.get_class(self),"__eq__",null) if(eq !==null){var res=$B.$call(eq)(self,other) if(res===_b_.NotImplemented){return res} return ! $B.$bool(res)} return _b_.NotImplemented} object.__reduce__=function(self){if(! self.__dict__){$B.RAISE(_b_.TypeError,`cannot pickle '${$B.class_name(self)}' object`)} if($B.imported.copyreg===undefined){$B.$import('copyreg')} var res=[$B.imported.copyreg._reconstructor] var D=$B.get_class(self),B=object for(var klass of D.__mro__){if(klass.__module__=='builtins'){B=klass break}} var args=$B.$list([D,B]) if(B===object){args.push(_b_.None)}else{args.push($B.$call(B)(self))} res.push($B.fast_tuple(args)) var d=$B.empty_dict() for(var attr of _b_.dict.$keys_string(self.__dict__)){_b_.dict.$setitem(d,attr,_b_.dict.$getitem_string(self.__dict__,attr))} res.push(d) return _b_.tuple.$factory(res)} function getNewArguments(self,klass){var newargs_ex=$B.$getattr(self,'__getnewargs_ex__',null) if(newargs_ex !==null){let newargs=newargs_ex() if((! newargs)||newargs.__class__ !==_b_.tuple){$B.RAISE(_b_.TypeError,"__getnewargs_ex__ should "+ `return a tuple, not '${$B.class_name(newargs)}'`)} if(newargs.length !=2){$B.RAISE(_b_.ValueError,"__getnewargs_ex__ should "+ `return a tuple of length 2, not ${newargs.length}`)} let args=newargs[0],kwargs=newargs[1] if((! args)||args.__class__ !==_b_.tuple){$B.RAISE(_b_.TypeError,"first item of the tuple returned "+ `by __getnewargs_ex__ must be a tuple, not '${$B.class_name(args)}'`)} if((! kwargs)||kwargs.__class__ !==_b_.dict){$B.RAISE(_b_.TypeError,"second item of the tuple returned "+ `by __getnewargs_ex__ must be a dict, not '${$B.class_name(kwargs)}'`)} return{args,kwargs}} let newargs=klass.$getnewargs,args if(! newargs){newargs=$B.$getattr(klass,'__getnewargs__',null)} if(newargs){args=newargs(self) if((! args)||args.__class__ !==_b_.tuple){$B.RAISE(_b_.TypeError,"__getnewargs__ should "+ `return a tuple, not '${$B.class_name(args)}'`)} return{args}}} object.__reduce_ex__=function(self,protocol){var klass=$B.get_class(self) if($B.imported.copyreg===undefined){$B.$import('copyreg')} if(protocol < 2){return $B.$call($B.imported.copyreg._reduce_ex)(self,protocol)} var reduce=$B.$getattr(klass,'__reduce__') if(reduce !==object.__reduce__){return $B.$call(reduce)(self)} var res=[$B.imported.copyreg.__newobj__] var arg2=[klass] var newargs=getNewArguments(self,klass) if(newargs){arg2=arg2.concat(newargs.args)} res.push($B.fast_tuple(arg2)) var getstate=$B.search_in_mro(klass,'__getstate__') if(getstate){var d=$B.$call(getstate)(self)}else{var d=$B.empty_dict(),nb=0 if(self.__dict__){for(var item of _b_.dict.$iter_items(self.__dict__)){if(item.key=="__class__" ||item.key.startsWith("$")){continue} _b_.dict.$setitem(d,item.key,item.value) nb++}} if(nb==0){d=_b_.None}} res.push(d) var list_like_iterator=_b_.None if($B.$getattr(klass,'append',null)!==null && $B.$getattr(klass,'extend',null)!==null){list_like_iterator=_b_.iter(self)} res.push(list_like_iterator) var key_value_iterator=_b_.None if($B.$isinstance(self,_b_.dict)){key_value_iterator=_b_.dict.items(self)} res.push(key_value_iterator) return _b_.tuple.$factory(res)} object.__repr__=function(self){if(self===object){return ""} if(self.__class__===_b_.type){return ""} var klass=$B.get_class(self),module=klass.__module__ if(module !==undefined && !module.startsWith("$")&& module !=="builtins"){return `<${module}.${$B.class_name(self)} object>`}else{return "<"+$B.class_name(self)+" object>"}} object.__setattr__=function(self,attr,val){if(val===undefined){ $B.RAISE(_b_.TypeError,"can't set attributes of built-in/extension type 'object'")}else if(self.__class__===object){ if(object[attr]===undefined){throw $B.attr_error(attr,self)}else{$B.RAISE_ATTRIBUTE_ERROR( "'object' object attribute '"+attr+"' is read-only",self,attr)}} if(self.__dict__){_b_.dict.$setitem(self.__dict__,attr,val)}else{ self[attr]=val} return _b_.None} object.__setattr__.__get__=function(obj){return function(attr,val){object.__setattr__(obj,attr,val)}} object.__setattr__.__str__=function(){return "method object.setattr"} object.__str__=function(self){if(self===undefined ||self.$kw){$B.RAISE(_b_.TypeError,"descriptor '__str__' of 'object' "+ "object needs an argument")} var klass=self.__class__ ||$B.get_class(self) var repr_func=$B.$getattr(klass,"__repr__") return $B.$call(repr_func).apply(null,arguments)} object.__subclasshook__=function(){return _b_.NotImplemented} object.$factory=function(){if(arguments.length > 0 || (arguments.length==1 && arguments[0].$kw && Object.keys(arguments[0].$kw).length > 0) ){$B.RAISE(_b_.TypeError,'object() takes no arguments')} var res={__class__:object},args=[res] object.__init__.apply(null,args) return res} $B.set_func_names(object,"builtins") _b_.object=object})(__BRYTHON__); ; (function($B){var _b_=$B.builtins const TPFLAGS={STATIC_BUILTIN:1 << 1,MANAGED_WEAKREF:1 << 3,MANAGED_DICT:1 << 4,SEQUENCE:1 << 5,MAPPING:1 << 6,DISALLOW_INSTANTIATION:1 << 7,IMMUTABLETYPE:1 << 8,HEAPTYPE:1 << 9,BASETYPE:1 << 10,HAVE_VECTORCALL:1 << 11,READY:1 << 12,READYING:1 << 13,HAVE_GC:1 << 14,METHOD_DESCRIPTOR:1 << 17,VALID_VERSION_TAG:1 << 19,IS_ABSTRACT:1 << 20,MATCH_SELF:1 << 22,LONG_SUBCLASS:1 << 24,LIST_SUBCLASS:1 << 25,TUPLE_SUBCLASS:1 << 26,BYTES_SUBCLASS:1 << 27,UNICODE_SUBCLASS:1 << 28,DICT_SUBCLASS:1 << 29,BASE_EXC_SUBCLASS:1 << 30,TYPE_SUBCLASS:1 << 31,HAVE_FINALIZE:1 << 0,HAVE_VERSION_TAG:1 << 18} $B.$class_constructor=function(class_name,frame,metaclass,resolved_bases,bases,kwargs,static_attributes,annotate,firstlineno){var dict var class_obj_proxy=frame[1] if(class_obj_proxy instanceof $B.str_dict){dict=$B.empty_dict() dict.$strings=class_obj_proxy}else{dict=class_obj_proxy.$target} var module=class_obj_proxy.__module__ for(var base of bases){if(base.__flags__ !==undefined && !(base.__flags__ & TPFLAGS.BASETYPE)){$B.RAISE(_b_.TypeError,`type '${base.__qualname__}' is not an acceptable base type`)}} var extra_kwargs={} if(kwargs){for(let i=0;i < kwargs.length;i++){var key=kwargs[i][0],val=kwargs[i][1] if(key !="metaclass"){ extra_kwargs[key]=val}}} if(class_obj_proxy.__eq__ !==undefined && class_obj_proxy.__hash__===undefined){$B.$setitem(dict,'__hash__',_b_.None)} var slots=class_obj_proxy.__slots__ if(slots !==undefined){if(typeof slots=="string"){slots=[slots]}else{for(let item of $B.make_js_iterator(slots)){if(typeof item !='string'){$B.RAISE(_b_.TypeError,'__slots__ items must be '+ `strings, not '${$B.class_name(item)}'`)}}} $B.$setitem(dict,'__slots__',slots)} $B.make_annotate_func(dict,annotate,frame) var meta_new=_b_.type.__getattribute__(metaclass,"__new__") var kls=meta_new(metaclass,class_name,resolved_bases,dict,{$kw:[extra_kwargs]}) kls.__module__=module kls.$subclasses=[] kls.$is_class=true kls.__static_attributes__=$B.fast_tuple(static_attributes) kls.__firstlineno__=firstlineno if(kls.__class__===metaclass){ var meta_init=_b_.type.__getattribute__(metaclass,"__init__") try{meta_init(kls,class_name,resolved_bases,dict,{$kw:[extra_kwargs]})}catch(err){if(class_name=='SupportsInt'){console.log('err for',class_name) console.log(err) console.log(err.stack)} throw err}} for(let i=0;i < bases.length;i++){bases[i].$subclasses=bases[i].$subclasses ||[] bases[i].$subclasses.push(kls)} return kls} $B.get_metaclass=function(class_name,module,bases,kw_meta){ var metaclass if(kw_meta===undefined && bases.length==0){return _b_.type}else if(kw_meta){if(! $B.$isinstance(kw_meta,_b_.type)){return kw_meta} metaclass=kw_meta} if(bases && bases.length > 0){if(bases[0].__class__===undefined){ if(typeof bases[0]=="function"){if(bases.length !=1){$B.RAISE(_b_.TypeError,"A Brython class "+ "can inherit at most 1 Javascript constructor")} $B.set_func_names(bases[0],module) return $B.JSMeta}else{$B.RAISE(_b_.TypeError,"Argument of "+class_name+ " is not a class (type '"+$B.class_name(bases[0])+ "')")}} for(var base of bases){var mc=base.__class__ if(metaclass===undefined){metaclass=mc}else if(mc===metaclass ||_b_.issubclass(metaclass,mc)){}else if(_b_.issubclass(mc,metaclass)){metaclass=mc}else if(metaclass.__bases__ && metaclass.__bases__.indexOf(mc)==-1){$B.RAISE(_b_.TypeError,"metaclass conflict: the "+ "metaclass of a derived class must be a (non-"+ "strict) subclass of the metaclasses of all its bases")}}}else{metaclass=metaclass ||_b_.type} return metaclass} function set_attr_if_absent(dict,attr,value){try{$B.$getitem(dict,attr)}catch(err){$B.$setitem(dict,attr,value)}} $B.make_class_namespace=function(metaclass,class_name,module,qualname,orig_bases,bases){ var class_dict=_b_.dict.$literal([['__module__',module],['__qualname__',qualname] ]) if(metaclass !==_b_.type){var prepare=$B.$getattr(metaclass,"__prepare__",_b_.None) if(prepare !==_b_.None){class_dict=$B.$call(prepare)(class_name,bases) set_attr_if_absent(class_dict,'__module__',module) set_attr_if_absent(class_dict,'__qualname__',qualname)}} if(orig_bases !==bases){$B.$setitem(class_dict,'__orig_bases__',orig_bases)} if(class_dict.__class__===_b_.dict){if(class_dict.$all_str){return class_dict.$strings} return new Proxy(class_dict,{get:function(target,prop){if(prop=='__class__'){return _b_.dict}else if(prop=='$target'){return target} if(_b_.dict.$contains_string(target,prop)){return _b_.dict.$getitem_string(target,prop)} return undefined},set:function(target,prop,value){_b_.dict.$setitem(target,prop,value)}})}else{var setitem=$B.$call($B.$getattr(class_dict,"__setitem__")),getitem=$B.$getattr(class_dict,"__getitem__") return new Proxy(class_dict,{get:function(target,prop){if(prop=='__class__'){return $B.get_class(target)}else if(prop=='$target'){return target} try{return getitem(prop)}catch(err){return undefined}},set:function(target,prop,value){try{setitem(prop,value)}catch(err){console.log('error calling setitem',setitem) console.log('class dict',class_dict) console.log('prop',prop,'value',value) console.log('frame obj',$B.frame_obj) throw err} return _b_.None}})}} $B.resolve_mro_entries=function(bases){ var new_bases=[],has_mro_entries=false for(var base of bases){if(! $B.$isinstance(base,_b_.type)){var mro_entries=$B.$getattr(base,"__mro_entries__",_b_.None) if(mro_entries !==_b_.None){has_mro_entries=true var entries=_b_.list.$factory(mro_entries(bases)) new_bases=new_bases.concat(entries)}else{new_bases.push(base)}}else{new_bases.push(base)}} return has_mro_entries ? new_bases :bases} $B.make_class=function(qualname,factory){ var A={__class__:type,__bases__:[_b_.object],__mro__:[_b_.object],__name__:qualname,__qualname__:qualname,$is_class:true} A.$factory=factory return A} var type=$B.make_class("type",function(){var missing={},$=$B.args('type',3,{kls:null,bases:null,cl_dict:null},['kls','bases','cl_dict'],arguments,{bases:missing,cl_dict:missing},null,'kw'),kls=$.kls,bases=$.bases,cl_dict=$.cl_dict,kw=$.kw var kwarg={} for(var item of _b_.dict.$iter_items(kw)){kwarg[item.key]=item.value} var kwargs={$kw:[kwarg]} if(cl_dict===missing){if(bases !==missing){$B.RAISE(_b_.TypeError,'type() takes 1 or 3 arguments')} var res=$B.get_class(kls) if(res===$B.long_int){return _b_.int} return res}else{var module=$B.frame_obj.frame[2],resolved_bases=$B.resolve_mro_entries(bases),metaclass=$B.get_metaclass(kls,module,resolved_bases) return type.__call__(metaclass,kls,resolved_bases,cl_dict,kwargs)}} ) type.__class__=type var classmethod=_b_.classmethod=$B.make_class("classmethod",function(func){$B.check_nb_args_no_kw('classmethod',1,arguments) return{ __class__:classmethod,__func__:func}} ) classmethod.__dict__={} classmethod.__get__=function(){ var $=$B.args('classmethod',3,{self:null,obj:null,cls:null},['self','obj','cls'],arguments,{cls:_b_.None},null,null),self=$.self,obj=$.obj,cls=$.cls if(cls===_b_.None ||cls===undefined){cls=$B.get_class(obj)} var func_class=$B.get_class(self.__func__),candidates=[func_class].concat(func_class.__mro__) for(var candidate of candidates){if(candidate===$B.function){break} if(candidate.__get__){return candidate.__get__(self.__func__,cls,cls)}} return $B.method.$factory(self.__func__,cls)} $B.set_func_names(classmethod,"builtins") var staticmethod=_b_.staticmethod=$B.make_class("staticmethod",function(func){return{ __class__:staticmethod,__func__:func}} ) staticmethod.__call__=function(self){return $B.$call(self.__func__)} staticmethod.__get__=function(self){return self.__func__} $B.set_func_names(staticmethod,"builtins") $B.getset_descriptor=$B.make_class("getset_descriptor",function(klass,attr,getter,setter,deleter){var res={__class__:$B.getset_descriptor,__doc__:_b_.None,cls:klass,attr,getter,setter,deleter} return res} ) $B.getset_descriptor.__delete__=function(self,obj){return self.deleter(obj)} $B.getset_descriptor.__get__=function(self,obj){if(obj===_b_.None){return self} return self.getter(obj)} $B.getset_descriptor.__set__=function(self,klass,value){if(self.setter===undefined){$B.RAISE_ATTRIBUTE_ERROR( `attribute '${self.attr}' of '${self.cls.__qualname__}' objects is not writable`,self,self.attr)} return self.setter(klass,value)} $B.getset_descriptor.__repr__=function(self){return ``} $B.set_func_names($B.getset_descriptor,"builtins") type.__dict__={} type.__dict__.__annotations__=$B.getset_descriptor.$factory(type,'__annotations__',function(klass){if(klass.__annotations__ !==undefined){ return klass.__annotations__} if(klass.__annotations_cache__ !==undefined){return klass.__annotations_cache__} var annotate=$B.search_in_mro(klass,'__annotate__') var annotate_func=klass.__annotate_func__ if(annotate_func===undefined){console.log('no __annotate_func__ for klass',klass)} if(annotate_func===_b_.None){return $B.empty_dict()} return klass.__annotations_cache__=$B.$call(annotate_func)(1)},function(klass,value){klass.__annotations__=value},function(klass){if(klass.__annotations_cache__===undefined){$B.RAISE_ATTRIBUTE_ERROR('__annotations__',klass,'__annotations__')} klass.__annotations_cache__=$B.empty_dict() klass.__annotate__=_b_.None} ) type.__dict__.__annotate__=$B.getset_descriptor.$factory(type,'__annotate__',function(klass){if(klass.__annotate__ !==undefined){ return klass.__annotate__} return klass.__annotate_func__ ?? _b_.None},function(klass,value){try{$B.$call(value)}catch(err){if(value !==_b_.None){$B.RAISE(_b_.TypeError,'__annotate__ must be callable or None')} klass.__annotate__=value}} ) type.__dict__.__mro__={__get__:function(cls){return $B.fast_tuple([cls].concat(cls.__mro__))}} type.__dict__.__dict__={__get__:function(cls){ if(cls===undefined ||cls===null){return $B.empty_dict()} if(cls.__dict__ !==undefined){return cls.__dict__} if(cls.$tp_dict){return $B.obj_dict(cls.$tp_dict)} return $B.empty_dict()}} type.$call=function(klass,new_func,init_func){ return function(){ var instance=new_func.bind(null,klass).apply(null,arguments) if($B.$isinstance(instance,klass)){ init_func.bind(null,instance).apply(null,arguments)} return instance}} type.$call_no_new_init=function(klass,init_func){ return function(){var instance=_b_.object.$no_new_init(klass) init_func(instance,...arguments) return instance}} type.$call_no_init=function(klass,new_func){ return new_func.bind(null,klass)} type.__call__=function(){var extra_args=[],klass=arguments[0] for(var i=1,len=arguments.length;i < len;i++){extra_args.push(arguments[i])} var new_func=_b_.type.__getattribute__(klass,"__new__") var instance=new_func.apply(null,arguments),instance_class=instance.__class__ ||$B.get_class(instance) if(instance_class===klass){ var init_func=_b_.type.__getattribute__(klass,"__init__") if(init_func !==_b_.object.__init__){ var args=[instance].concat(extra_args) init_func.apply(null,args)}} return instance} $B.$class_getitem=function(kls,origin,args){return $B.GenericAlias.$factory(kls,origin,args)} function merge_class_dict(dict,klass){var classdict,bases classdict=$B.$getattr(klass,'__dict__',null) if(classdict !==null){_b_.dict.update(dict,classdict)}else{return} bases=klass.__bases__ if(bases===undefined){return} for(var base of bases){merge_class_dict(dict,base)}} type.__dir__=function(klass){var dict=$B.empty_dict() merge_class_dict(dict,klass) return _b_.sorted(dict)} type.__format__=function(klass){ return _b_.str.$factory(klass)} type.__getattribute__=function(klass,attr){switch(attr){case "__bases__": if(klass.__bases__ !==undefined){return $B.fast_tuple($B.resolve_mro_entries(klass.__bases__))} throw $B.attr_error(attr,klass) case "__class__": return klass.__class__ case "__doc__": return klass.__doc__ ||_b_.None case '__name__': return klass.__name__ ||klass.__qualname__ case "__setattr__": var func=klass["__setattr__"]?? function(kls,key,value){kls[key]=value} return method_wrapper.$factory(attr,klass,func) case "__delattr__": if(klass["__delattr__"]!==undefined){return klass["__delattr__"]} return method_wrapper.$factory(attr,klass,function(key){if(klass.__flags__ && TPFLAGS.IMMUTABLETYPE){$B.RAISE(_b_.TypeError,`cannot delete '${key}' attribute `+ `of immutable type '${klass.__name__}'`)} if(klass.__dict__){_b_.dict.__delitem__(klass.__dict__,key)} delete klass[key]})} var res=klass.hasOwnProperty(attr)? klass[attr]:undefined var $test=false if($test){console.log("attr",attr,"of",klass,'res',res)} if(klass.__class__ && klass.__class__[attr]&& klass.__class__[attr].__get__ && klass.__class__[attr].__set__){ if($test){console.log("data descriptor")} return klass.__class__[attr].__get__(klass)} if(res===undefined){ var v=klass.hasOwnProperty(attr)? klass[attr]:undefined if(v===undefined){if($test){console.log(attr,'not in klass[attr], search in __dict__',klass.__dict__)} if(klass.$tp_dict && ! klass.__dict__){klass.__dict__=$B.obj_dict(klass.$tp_dict)} if(klass.__dict__ && klass.__dict__.__class__===_b_.dict && _b_.dict.$contains_string(klass.__dict__,attr)){res=klass[attr]=_b_.dict.$getitem_string(klass.__dict__,attr) if($test){console.log('found in __dict__',res)}}else{var mro=klass.__mro__ if(mro===undefined){console.log("no mro for",klass,'attr',attr)} for(let i=0;i < mro.length;i++){if(mro[i].hasOwnProperty(attr)){res=mro[i][attr] if($test){console.log('found in class',mro[i])} break}}}}else{res=v}} if(res===undefined){ if(res===undefined){var meta=klass.__class__ ||$B.get_class(klass) res=meta.hasOwnProperty(attr) ? meta[attr] :meta.__dict__ && _b_.dict.$contains(meta.__dict__,attr) ? _b_.dict.$getitem(meta.__dict__,attr) :undefined if($test){console.log("search in meta",meta,res)} if(res===undefined){var meta_mro=meta.__mro__ for(let i=0;i < meta_mro.length;i++){if(meta_mro[i].hasOwnProperty(attr)){res=meta_mro[i][attr] break}}} if(res !==undefined){if($test){console.log("found in meta",res,typeof res)} if(res.__class__===_b_.property){return res.fget(klass)}else if(res.__class__===$B.getset_descriptor){return res.getter(klass)} if(typeof res=="function"){ if(attr=='__new__'){ return res} var meta_method=res.bind(null,klass) meta_method.__class__=$B.method meta_method.$infos={__self__:klass,__func__:res,__name__:attr,__qualname__:meta.__name__+"."+attr,__module__:res.$infos ? res.$infos.__module__ :""} if($test){console.log('return method from meta',meta_method,meta_method+'')} return meta_method}}} if(res===undefined){ var getattr=meta.__getattr__ if(getattr===undefined){for(let i=0;i < meta_mro.length;i++){if(meta_mro[i].__getattr__ !==undefined){getattr=meta_mro[i].__getattr__ break}}} if(getattr !==undefined){return getattr(klass,attr)}}} if(res !==undefined){if($test){console.log("res",res,'class',$B.get_class(res)) console.log('is $B.in_mro ?',res===$B.in_mro)} if(res.__class__===_b_.property){return res}else if(res.__class__===_b_.classmethod){return _b_.classmethod.__get__(res,_b_.None,klass)} if(res.__get__){if(res.__class__===method){if($test){console.log('__get__ of method',res.$infos.__self__,klass)} if(res.$infos.__self__){ return res} var result=res.__get__(res.__func__,klass) result.$infos={__func__:res,__name__:res.$infos.__name__,__qualname__:klass.__name__+"."+res.$infos.__name__,__self__:klass}}else{result=res.__get__(klass)} return result}else if(res.__class__){var getter=$B.search_in_mro(res.__class__,'__get__') if(getter){ var getter_res=$B.$call(getter)(res,_b_.None,klass) if(getter_res===undefined){console.log('no result for getter',getter) console.log(Error().stack)} res=getter_res}} if(typeof res=="function"){ if(res.$infos !==undefined && res.$function_infos===undefined){console.log('$infos not undef',res,res.$infos) throw Error()} if(res.$infos===undefined && res.$function_infos===undefined && $B.get_option('debug')> 1){console.log("warning: no attribute $infos for",res,"klass",klass,"attr",attr)} if($test){console.log("res is function",res)} if(attr=="__new__" || res.__class__===$B.builtin_function_or_method){res.$type="staticmethod"} if((attr=="__class_getitem__" ||attr=="__init_subclass__") && res.__class__ !==_b_.classmethod){res=_b_.classmethod.$factory(res) return _b_.classmethod.__get__(res,_b_.None,klass)} if(res.__class__===$B.method){return res.__get__(null,klass)}else{if($test){console.log("return res",res)} return res}}else{return res}}} type.__hash__=function(cls){return _b_.hash(cls)} type.__init__=function(){if(arguments.length==0){$B.RAISE(_b_.TypeError,"descriptor '__init__' of 'type' "+ "object needs an argument")}} type.__init_subclass__=function(){ var $=$B.args("__init_subclass__",1,{cls:null},['cls'],arguments,{},"args","kwargs") if($.args.length > 0){$B.RAISE(_b_.TypeError,`${$.cls.__qualname__}.__init_subclass__ takes no arguments `+ `(${$.args.length} given)`)} if(_b_.dict.__len__($.kwargs)> 0){$B.RAISE(_b_.TypeError,`${$.cls.__qualname__}.__init_subclass__() `+ `takes no keyword arguments`)} return _b_.None} _b_.object.__init_subclass__=type.__init_subclass__ type.__instancecheck__=function(cls,instance){var kl=instance.__class__ ||$B.get_class(instance) if(kl===cls){return true}else{for(var i=0;i < kl.__mro__.length;i++){if(kl.__mro__[i]===cls){return true}}} return false} type.__instancecheck__.$type="staticmethod" type.__name__='type' type.__new__=function(meta,name,bases,cl_dict,extra_kwargs){ extra_kwargs=extra_kwargs===undefined ?{$kw:[{}]}: extra_kwargs var module=_b_.dict.$get_string(cl_dict,'__module__',$B.frame_obj.frame[2]) var qualname=_b_.dict.$get_string(cl_dict,'__qualname__',name) var class_dict={__class__ :meta,__bases__ :bases.length==0 ?[_b_.object]:bases,__dict__ :cl_dict,__qualname__:qualname,__module__:module,__name__:name,$is_class:true} let slots=_b_.dict.$get_string(cl_dict,'__slots__',_b_.None) if(slots !==_b_.None){for(let key of $B.make_js_iterator(slots)){class_dict[key]=member_descriptor.$factory(key,class_dict)}} class_dict.__mro__=type.mro(class_dict).slice(1) for(var entry of _b_.dict.$iter_items(cl_dict)){var key=entry.key,v=entry.value if(['__module__','__class__','__name__','__qualname__'].includes(key)){continue} if(key.startsWith('$')){continue} if(v===undefined){continue} class_dict[key]=v if(v.__class__){ var set_name=$B.$getattr(v.__class__,"__set_name__",_b_.None) if(set_name !==_b_.None){set_name(v,class_dict,key)}} if(typeof v=="function"){if(v.$function_infos===undefined){ if(v.$infos){v.$infos.__qualname__=name+'.'+v.$infos.__name__}}else{v.$function_infos[$B.func_attrs.method_class]=class_dict v.$function_infos[$B.func_attrs.__qualname__]=name+'.'+ v.$function_infos[$B.func_attrs.__name__]}}} class_dict.$tp_setattr=$B.search_in_mro(class_dict,'__setattr__') var sup=_b_.super.$factory(class_dict,class_dict) var init_subclass=_b_.super.__getattribute__(sup,"__init_subclass__") init_subclass(extra_kwargs) return class_dict} type.__or__=function(){var $=$B.args('__or__',2,{cls:null,other:null},['cls','other'],arguments,{},null,null),cls=$.cls,other=$.other if(other !==_b_.None && ! $B.$isinstance(other,[type,$B.GenericAlias,$B.UnionType])){return _b_.NotImplemented} return $B.UnionType.$factory([cls,other])} type.__prepare__=function(){return $B.empty_dict()} type.__qualname__='type' type.__repr__=function(kls){$B.builtins_repr_check(type,arguments) var qualname=kls.__qualname__ if(kls.__module__ && kls.__module__ !="builtins" && !kls.__module__.startsWith("$")){qualname=kls.__module__+"."+qualname} return ""} type.__ror__=function(){var len=arguments.length if(len !=1){$B.RAISE(_b_.TypeError,`expected 1 argument, got ${len}`)} return _b_.NotImplemented} function update_subclasses(kls,name,alias,value){ for(var subclass of kls.$subclasses){if(! subclass.hasOwnProperty(name)){subclass[alias]=value update_subclasses(subclass,name,alias,value)}}} type.__setattr__=function(kls,attr,value){var $test=false if($test){console.log("kls is class",type)} if($B.mappingproxy.$contains(type.__dict__,attr)){var v=$B.mappingproxy.$getitem(type.__dict__,attr) var vtype=$B.get_class(v) if(vtype.__set__){return vtype.__set__(v,kls,value)}} if(kls.__flags__ && TPFLAGS.IMMUTABLETYPE){$B.RAISE(_b_.TypeError,`cannot set '${attr}' attribute of immutable type '`+ kls.__qualname__+"'")} kls[attr]=value var mp=kls.__dict__ ||$B.$getattr(kls,'__dict__') _b_.dict.$setitem(mp,attr,value) switch(attr){case '__init__': case '__new__': kls.$factory=$B.$instance_creator(kls) break case "__bases__": kls.__mro__=_b_.type.mro(kls) break case '__setattr__': var initial_value=kls.$tp_setattr kls.$tp_setattr=value update_subclasses(kls,'__setattr__','$tp_setattr',value) break} if($test){console.log("after setattr",kls)} return _b_.None} type.$mro=function(cls){ if(cls===undefined){$B.RAISE(_b_.TypeError,'unbound method type.mro() needs an argument')} var bases=cls.__bases__,seqs=[],pos1=0 for(var base of bases){ let bmro=[],pos=0 if(base===undefined || base.__mro__===undefined){if(base.__class__===undefined){ return[_b_.object]}else{console.log('error for base',base) console.log('cls',cls)}} bmro[pos++]=base var _tmp=base.__mro__ if(_tmp){if(_tmp[0]===base){_tmp.splice(0,1)} for(var k=0;k < _tmp.length;k++){bmro[pos++]=_tmp[k]}} seqs[pos1++]=bmro} seqs[pos1++]=bases.slice() var mro=[cls],mpos=1 while(1){let non_empty=[],pos=0 for(let i=0;i < seqs.length;i++){if(seqs[i].length > 0){non_empty[pos++]=seqs[i]}} if(non_empty.length==0){break} let candidate for(let i=0;i < non_empty.length;i++){let seq=non_empty[i] candidate=seq[0] let not_head=[],pos=0 for(let j=0;j < non_empty.length;j++){let s=non_empty[j] if(s.slice(1).indexOf(candidate)>-1){not_head[pos++]=s}} if(not_head.length > 0){candidate=null}else{break}} if(candidate===null){$B.RAISE(_b_.TypeError,"inconsistent hierarchy, no C3 MRO is possible")} mro[mpos++]=candidate for(let i=0;i < seqs.length;i++){let seq=seqs[i] if(seq[0]===candidate){ seqs[i].shift()}}} if(mro[mro.length-1]!==_b_.object){mro[mpos++]=_b_.object} return mro} type.mro=function(cls){return $B.$list(type.$mro(cls))} type.__subclasscheck__=function(self,subclass){ var klass=self if(subclass.__bases__===undefined){return self===_b_.object} return subclass.__bases__.indexOf(klass)>-1} $B.set_func_names(type,"builtins") type.__init_subclass__=_b_.classmethod.$factory(type.__init_subclass__) _b_.type=type var property=_b_.property=$B.make_class("property",function(fget,fset,fdel,doc){var res={__class__:property} property.__init__(res,fget,fset,fdel,doc) return res} ) property.__init__=function(){var $=$B.args('__init__',5,{self:null,fget:null,fset:null,fdel:null,doc:null},['self','fget','fset','fdel','doc'],arguments,{fget:_b_.None,fset:_b_.None,fdel:_b_.None,doc:_b_.None},null,null),self=$.self,fget=$.fget,fset=$.fset,fdel=$.fdel,doc=$.doc self.__doc__=doc if($B.$getattr && doc===_b_.None){self.__doc__=$B.$getattr(fget,'__doc__',doc)} self.$type=fget.$type self.fget=fget self.fset=fset self.fdel=fdel self.$is_property=true if(fget && fget.$attrs){for(var key in fget.$attrs){self[key]=fget.$attrs[key]}} self.__delete__=fdel; self.getter=function(fget){return property.$factory(fget,self.fset,self.fdel,self.__doc__)} self.setter=function(fset){return property.$factory(self.fget,fset,self.fdel,self.__doc__)} self.deleter=function(fdel){return property.$factory(self.fget,self.fset,fdel,self.__doc__)}} property.__get__=function(self,kls){if(self.fget===undefined){$B.RAISE_ATTRIBUTE_ERROR("unreadable attribute",self,'__get__')} return $B.$call(self.fget)(kls)} property.__new__=function(cls){return{ __class__:cls}} property.__set__=function(self,obj,value){if(self.fset===undefined){var name=self.fget.$function_infos[$B.func_attrs.__name__] var msg=`property '${name}' of '${$B.class_name(obj)}' object `+ 'has no setter' $B.RAISE_ATTRIBUTE_ERROR(msg,self,'__set__')} $B.$getattr(self.fset,'__call__')(obj,value)} $B.set_func_names(property,"builtins") var wrapper_descriptor=$B.wrapper_descriptor= $B.make_class("wrapper_descriptor") wrapper_descriptor.__text_signature__={__get__:function(){return '(self, /, *args, **kwargs)'}} $B.set_func_names(wrapper_descriptor,"builtins") type.__call__.__class__=wrapper_descriptor $B.$instance_creator=function(klass){var test=false if(test){console.log('instance creator of',klass)} if(klass.prototype && klass.prototype.constructor==klass){ return function(){return new klass(...arguments)}} if(klass.__abstractmethods__ && $B.$bool(klass.__abstractmethods__)){return function(){var ams=Array.from($B.make_js_iterator(klass.__abstractmethods__)) ams.sort() var quoted_methods=ams.map(m=> "'"+m+"'").join(', ') var method_word=ams.length > 1 ? 'methods' :'method' $B.RAISE(_b_.TypeError,"Can't instantiate abstract class "+klass.__name__+ " without an implementation for abstract "+method_word+" "+ quoted_methods)}} var metaclass=klass.__class__ ||$B.get_class(klass),call_func,factory if(metaclass===_b_.type){var new_func=type.__getattribute__(klass,'__new__'),init_func=type.__getattribute__(klass,'__init__') if(init_func===_b_.object.__init__){if(new_func===_b_.object.__new__){factory=_b_.object.$new(klass)}else{factory=new_func.bind(null,klass)}}else if(new_func===_b_.object.__new__){factory=type.$call_no_new_init(klass,init_func)}else{factory=type.$call(klass,new_func,init_func)}}else{call_func=_b_.type.__getattribute__(metaclass,"__call__") if(call_func.$is_class){factory=$B.$call(call_func)}else{factory=call_func.bind(null,klass)}} factory.__class__=$B.function factory.$infos={__name__:klass.__name__,__module__:klass.__module__} return factory} var method_wrapper=$B.method_wrapper=$B.make_class("method_wrapper",function(attr,klass,method){var f=function(){return method.apply(null,arguments)} f.$infos={__name__:attr,__module__:klass.__module__} return f} ) method_wrapper.__str__=method_wrapper.__repr__=function(self){return ""} var member_descriptor=$B.member_descriptor=$B.make_class("member_descriptor",function(attr,cls){return{__class__:member_descriptor,cls:cls,attr:attr}} ) member_descriptor.__delete__=function(self,kls){if(kls.$slot_values===undefined || ! kls.$slot_values.hasOwnProperty(self.attr)){$B.RAISE_ATTRIBUTE_ERROR('cannot delete',self,self.attr)} kls.$slot_values.delete(self.attr)} member_descriptor.__get__=function(self,kls){if(kls===_b_.None){return self} if(kls.$slot_values===undefined || ! kls.$slot_values.has(self.attr)){throw $B.attr_error(self.attr,kls)} return kls.$slot_values.get(self.attr)} member_descriptor.__set__=function(self,kls,value){if(kls.$slot_values===undefined){kls.$slot_values=new Map()} kls.$slot_values.set(self.attr,value)} member_descriptor.__str__=member_descriptor.__repr__=function(self){return ""} $B.set_func_names(member_descriptor,"builtins") var method=$B.method=$B.make_class("method",function(func,cls){var f=function(){return $B.$call(func).bind(null,cls).apply(null,arguments)} f.__class__=method if(typeof func !=='function'){console.log('method from func w-o $infos',func,'all',$B.$call(func))} if(! func.$infos && func.$function_infos){$B.make_function_infos(func,...func.$function_infos) f.$function_infos=func.$function_infos} f.$infos=func.$infos ||{} f.$infos.__func__=func f.$infos.__self__=cls f.$infos.__dict__=$B.empty_dict() return f} ) method.__call__=function(f){return f(...Array.from(arguments).slice(1))} method.__eq__=function(self,other){return self.$infos !==undefined && other.$infos !==undefined && self.$infos.__func__===other.$infos.__func__ && self.$infos.__self__===other.$infos.__self__} method.__ne__=function(self,other){return ! $B.method.__eq__(self,other)} method.__get__=function(self){var f=function(){return self(...arguments)} f.__class__=$B.method_wrapper f.$infos=method.$infos return f} method.__getattribute__=function(self,attr){ var infos=self.$infos if(infos && infos[attr]){if(attr=="__code__"){var res={__class__:$B.Code} for(var key in infos.__code__){res[key]=infos.__code__[key]} return res}else{return infos[attr]}}else if(method.hasOwnProperty(attr)){return _b_.object.__getattribute__(self,attr)}else{ return _b_.object.__getattribute__(self.$infos.__func__,attr)}} method.__repr__=method.__str__=function(self){return ""} method.__setattr__=function(self,key){ if(key=="__class__"){$B.RAISE(_b_.TypeError,"__class__ assignment only supported "+ "for heap types or ModuleType subclasses")} throw $B.attr_error(key,self)} $B.set_func_names(method,"builtins") $B.method_descriptor=$B.make_class("method_descriptor") $B.classmethod_descriptor=$B.make_class("classmethod_descriptor") _b_.object.__class__=type $B.make_iterator_class=function(name,reverse){ var klass={__class__:_b_.type,__mro__:[_b_.object],__name__:name,__qualname__:name,$factory:function(items){return{ __class__:klass,__dict__:$B.empty_dict(),counter:reverse ? items.length :-1,items:items,len:items.length,$builtin_iterator:true}},$is_class:true,$iterator_class:true,__iter__:function(self){self.counter= self.counter===undefined ? reverse ? self.items.length :-1 :self.counter self.len=self.items.length return self},__len__:function(self){return self.items.length},__next__:function(self){if(typeof self.test_change=="function"){var message=self.test_change() if(message){$B.RAISE(_b_.RuntimeError,message)}} if(reverse){self.counter-- if(self.counter >=0){var item=self.items[self.counter] if(self.items.$is_js_array){ item=$B.jsobj2pyobj(item)} return item}}else{self.counter++ if(self.counter < self.items.length){var item=self.items[self.counter] if(self.items.$is_js_array){ item=$B.jsobj2pyobj(item)} return item}} $B.RAISE(_b_.StopIteration,"StopIteration")},__reduce_ex__:function(self){return $B.fast_tuple([_b_.iter,_b_.tuple.$factory([self.items])])}} $B.set_func_names(klass,"builtins") return klass} $B.GenericAlias=$B.make_class("GenericAlias",function(origin_class,items){var res={__class__:$B.GenericAlias,__mro__:[origin_class],origin_class,items} return res} ) $B.GenericAlias.__args__=_b_.property.$factory( self=> $B.fast_tuple(self.items) ) $B.GenericAlias.__call__=function(self,...args){return self.origin_class.$factory.apply(null,args)} $B.GenericAlias.__eq__=function(self,other){if(! $B.$isinstance(other,$B.GenericAlias)){return false} return $B.rich_comp("__eq__",self.origin_class,other.origin_class)&& $B.rich_comp("__eq__",self.items,other.items)} $B.GenericAlias.__getitem__=function(self,item){$B.RAISE(_b_.TypeError,"descriptor '__getitem__' for '"+ self.origin_class.__name__+"' objects doesn't apply to a '"+ $B.class_name(item)+"' object")} $B.GenericAlias.__mro_entries__=function(self){return $B.fast_tuple([self.origin_class])} $B.GenericAlias.__new__=function(origin_class,items){var res={__class__:$B.GenericAlias,__mro__:[origin_class],origin_class,items,$is_class:true} return res} $B.GenericAlias.__or__=function(){var $=$B.args('__or__',2,{self:null,other:null},['self','other'],arguments,{},null,null) return $B.UnionType.$factory([$.self,$.other])} $B.GenericAlias.__origin__=_b_.property.$factory( self=> self.origin_class ) $B.GenericAlias.__parameters__=_b_.property.$factory( function(){return $B.fast_tuple([])} ) $B.GenericAlias.__repr__=function(self){var items=Array.isArray(self.items)? self.items :[self.items] var reprs=[] for(var item of items){if(item===_b_.Ellipsis){reprs.push('...')}else{if(item.$is_class){reprs.push(item.__name__)}else{reprs.push(_b_.repr(item))}}} var iv=$B.$getattr(self.origin_class,'__infer_variance__',true) var prefix=iv ? '' :'~' return prefix+$B.$getattr(self.origin_class,'__qualname__')+'['+ reprs.join(", ")+']'} $B.GenericAlias.__type_params__=_b_.property.$factory( function(self){return $B.$getattr(self.origin_class,'__type_params__')} ) $B.set_func_names($B.GenericAlias,"types") $B.UnionType=$B.make_class("UnionType",function(items){return{ __class__:$B.UnionType,items}} ) $B.UnionType.__args__=_b_.property.$factory( self=> $B.fast_tuple(self.items) ) $B.UnionType.__class_getitem__=function(cls,items){if($B.$isinstance(items,_b_.tuple)){return $B.UnionType.$factory(items)}else{return items}} $B.UnionType.__eq__=function(self,other){if(! $B.$isinstance(other,$B.UnionType)){return _b_.NotImplemented} return _b_.list.__eq__(self.items,other.items)} $B.UnionType.__or__=function(self,other){var items=self.items.slice() if(! items.includes(other)){items.push(other)} return $B.UnionType.$factory(items)} $B.UnionType.__parameters__=_b_.property.$factory( ()=> $B.fast_tuple([]) ) $B.UnionType.__repr__=function(self){var t=[] for(var item of self.items){if(item.$is_class){var s=item.__name__ if(item.__module__ !=="builtins"){s=item.__module__+'.'+s} t.push(s)}else{t.push(_b_.repr(item))}} return t.join(' | ')} $B.set_func_names($B.UnionType,"types") $B.make_annotate_func=function(dict,annotations,class_frame){if(annotations===undefined){$B.$setitem(dict,'__annotate_func__',_b_.None) return} var __annotate_func__=annotations $B.$setitem(dict,'__annotate_func__',__annotate_func__) $B.set_function_infos(__annotate_func__,{__defaults__:_b_.None,__kwdefaults__:_b_.None,__name__:'__annotate__',__module__:class_frame[2],__qualname__:class_frame[0]+'.__annotate__'} )} $B.postpone_annotations=function(obj,file){ var module_frame=$B.frame_obj.frame obj.$annotations={} Object.defineProperty(obj,'__annotations__',{configurable:true,get(){if(obj.$set_annotations){return obj.$set_annotations} var res=$B.empty_dict() for(var key in obj.$annotations){_b_.dict.$setitem(res,key,obj.$annotations[key][1]())} return res},set(value){obj.$set_annotations=value}} )} $B.make_module_annotate=function(locals){Object.defineProperty(locals,'__annotations__',{get(){if(locals.$set_annotations){return locals.$set_annotations} if(locals.__annotate__){return locals.__annotate__(1)} return locals.__annotate_func__(1)},set(value){locals.$set_annotations=value}} ) Object.defineProperty(locals,'__annotate__',{get(){if(locals.$annotate){return locals.$annotate} return locals.__annotate_func__},set(value){locals.$annotate=value}} ) locals.__annotate_func__=function(format){switch(format){case 1: var ann_dict=$B.empty_dict() for(var key in locals.$annotations){var item=locals.$annotations[key] $B.$setitem(ann_dict,key,item[1]())} return ann_dict default: $B.RAISE(_b_.NotImplementedError,)}} $B.add_function_infos(locals,'__annotate_func__') $B.set_function_attr(locals.__annotate_func__,'__name__','__annotate__') $B.set_function_attr(locals.__annotate_func__,'__qualname__','__annotate__')}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var FunctionCode=$B.make_class("function code") var FunctionGlobals=$B.make_class("function globals") $B.function={__class__:_b_.type,__mro__:[_b_.object],__name__:'function',__qualname__:'function',$is_class:true} $B.function.__dict__={} $B.function.__dict__.__annotations__=$B.getset_descriptor.$factory( $B.function,'__annotations__',function(f){$B.check_infos(f) if(f.__annotations__ !==undefined){return f.__annotations__}else{return f.__annotations__=f.__annotate__(1)}},function(f,value){$B.check_infos(f) if(! $B.$isinstance(value,_b_.dict)){$B.RAISE(_b_.TypeError,'__annotations__ must be set to a dict object')} f.__annotations__=value} ) $B.function.__dict__.__builtins__=$B.getset_descriptor.$factory( $B.function,'__builtins__',function(f){$B.check_infos(f) if(f.$infos && f.$infos.__globals__){return _b_.dict.$getitem(self.$infos.__globals__,'__builtins__')} return $B.obj_dict(_b_)} ,function(f){$B.RAISE_ATTRIBUTE_ERROR('readonly attribute',f,'__builtins__')} ) $B.function.__dict__.__closure__=$B.getset_descriptor.$factory( $B.function,'__closure__',function(f){var free_vars=f.$function_infos[$B.func_attrs.free_vars] if(free_vars===undefined ||free_vars.length==0){return _b_.None} var cells=[] for(var i=0;i < free_vars.length;i++){try{cells.push($B.cell.$factory($B.$check_def_free(free_vars[i])))}catch(err){ cells.push($B.cell.$factory(_b_.None))}} return $B.fast_tuple(cells)} ,function(f){$B.RAISE_ATTRIBUTE_ERROR('readonly attribute',f,'__closure__')} ) $B.function.__dict__.__code__=$B.getset_descriptor.$factory( $B.function,'__code__',function(f){$B.check_infos(f) var res={__class__:_b_.code} for(var _attr in f.$infos.__code__){res[_attr]=f.$infos.__code__[_attr]} res.name=f.$infos.__name__ res.filename=f.$infos.__code__.co_filename res.co_code=f+"" return res},function(f,value){$B.check_infos(f) if(! $B.$isinstance(value,_b_.code)){$B.RAISE(_b_.TypeError,'__code__ must be set to a code object')} f.$infos.__code__=value} ) $B.function.__dict__.__defaults__=$B.getset_descriptor.$factory( $B.function,'__defaults__',function(f){$B.check_infos(f) return f.$infos.__defaults__},function(f,value){$B.check_infos(f) if(value===_b_.None){value=[]}else if(! $B.$isinstance(value,_b_.tuple)){$B.RAISE(_b_.TypeError,"__defaults__ must be set to a tuple object")} f.$infos.__defaults__=value f.$function_infos[$B.func_attrs.__defaults__]=value $B.make_args_parser(f)} ) $B.function.__delattr__=function(self,attr){if(attr=="__dict__"){$B.RAISE(_b_.TypeError,"can't delete function __dict__")}} $B.function.__dict__.__doc__=$B.getset_descriptor.$factory( $B.function,'__doc__',function(f){$B.check_infos(f) return f.$infos.__doc__},function(f,value){$B.check_infos(f) f.$infos.__doc__=value} ) $B.function.__dict__.__module__=$B.getset_descriptor.$factory( $B.function,'__module__',function(f){$B.check_infos(f) return f.$infos.__module__},function(f,value){$B.check_infos(f) f.$infos.__module__=value} ) $B.function.__dict__.__name__=$B.getset_descriptor.$factory( $B.function,'__name__',function(f){$B.check_infos(f) return f.$infos.__name__},function(f,value){$B.check_infos(f) if(! $B.$isinstance(value,_b_.str)){$B.RAISE(_b_.TypeError,'__name__ must be set to a string object')} f.$infos.__name__=value} ) $B.function.__dict__.__qualname__=$B.getset_descriptor.$factory( $B.function,'__qualname__',function(f){$B.check_infos(f) return f.$infos.__qualname__},function(f,value){$B.check_infos(f) if(! $B.$isinstance(value,_b_.str)){$B.RAISE(_b_.TypeError,'__qualname__ must be set to a string object')} f.$infos.__qualname__=value} ) $B.function.__dict__.__type_params__=$B.getset_descriptor.$factory( $B.function,'__type_params__',function(f){$B.check_infos(f) return f.$infos.__type_params__},function(f,value){$B.check_infos(f) if(! $B.$isinstance(value,_b_.tuple)){$B.RAISE(_b_.TypeError,'TypeError: __type_params__ must be set to a tuple')} f.$infos.__type_params__=value} ) $B.function.__dir__=function(self){if(self.$function_infos && ! self.$infos){$B.make_function_infos(self,...self.$function_infos)} var infos=self.$infos.__dict__ ||{},attrs=self.$attrs ||{} return $B.$list(Object.keys(infos). concat(Object.keys(attrs)). concat(Object.keys($B.function)). filter(x=> !x.startsWith('$'))). sort()} $B.function.__get__=function(self,obj){ if(obj===_b_.None){return self} return $B.method.$factory(self,obj)} $B.function.__dict__.__globals__=$B.getset_descriptor.$factory( $B.function,'__globals__',function(f){$B.check_infos(f) return $B.obj_dict($B.imported[f.$infos.__module__])} ,function(f){$B.RAISE_ATTRIBUTE_ERROR('readonly attribute',f,'__globals__')} ) $B.function.__dict__.__kwdefaults__=$B.getset_descriptor.$factory( $B.function,'__kwdefaults__',function(f){$B.check_infos(f) return f.$infos.__kwdefaults__},function(f,value){$B.check_infos(f) if(value==_b_.None){value=$B.empty_dict()}else if(! $B.$isinstance(value,_b_.dict)){$B.RAISE(_b_.TypeError,'__kwdefaults__ must be set to a dict object')} f.$infos.__kwdefaults__=value var kwd={} for(var item of _b_.dict.$iter_items(value)){kwd[item.key]=item.value} f.$function_infos[$B.func_attrs.__kwdefaults__]=kwd $B.make_args_parser(f)} ) $B.function.__repr__=function(self){if(self.$function_infos){return ``}else if(self.$infos===undefined){return ''}else{return ''}} $B.function.__mro__=[_b_.object] $B.function.__setattr__=function(self,attr,value){if(self.$infos===undefined){$B.make_function_infos(self,...self.$function_infos)} var klass_attr=$B.function[attr] if(klass_attr !==undefined && klass_attr.__class__ && klass_attr.__class__.__get__ && klass_attr.__set__){return klass_attr.__class__.__set__(klass_attr,self,value)} try{klass_attr=_b_.dict.$getitem($B.function.__dict__,attr)}catch(err){klass_attr=null} if(klass_attr && klass_attr.__class__.__get__ && klass_attr.__class__.__set__){return klass_attr.__class__.__set__(klass_attr,self,value)} if(! self.__dict__){self.__dict__=$B.empty_dict()} _b_.dict.$setitem(self.__dict__,attr,value)} $B.check_infos=function(f){if(! f.$infos){if(f.$function_infos){$B.make_function_infos(f,...f.$function_infos)}else{console.log('no $infos, no $function_infos')}}} $B.make_function_infos=function(f,__module__,co_name,co_qualname,co_filename,__defaults__,__kwdefaults__,__doc__,arg_names,vararg,kwarg,co_argcount,co_firstlineno,co_flags,co_freevars,co_kwonlyargcount,co_posonlyargcount,co_varnames,annotations,type_params ){f.$is_func=true f.$args_parser=$B.make_args_parser_and_parse if(co_flags & $B.COMPILER_FLAGS.COROUTINE){f.$is_async=true} __defaults__=__defaults__===_b_.None ?[]:__defaults__ __defaults__.__class__=_b_.tuple __kwdefaults__=__kwdefaults__===_b_.None ? _b_.None : _b_.dict.$from_js(__kwdefaults__) f.$infos={__module__,__defaults__,__kwdefaults__,__doc__,arg_names,vararg,kwarg} f.$infos.__name__=co_name f.$infos.__qualname__=co_qualname type_params=type_params ??[] type_params.__class__=_b_.tuple f.$infos.__type_params__=type_params co_freevars=co_freevars ??[] co_freevars.__class__=_b_.tuple co_varnames=co_varnames ??[] co_varnames.__class__=_b_.tuple if(annotations){ f.__annotations__=_b_.dict.$literal(annotations)} f.$infos.__code__={co_argcount,co_filename,co_firstlineno,co_flags,co_freevars,co_kwonlyargcount,co_name,co_nlocals:co_varnames.length,co_posonlyargcount,co_qualname,co_varnames} f.$infos.__code__.co_positions=()=> $B.$list([]) f.$infos.__code__.co_positions.__class__=$B.function f.$infos.__dict__=$B.empty_dict()} $B.make_args_parser_and_parse=function make_args_parser_and_parse(fct,args){return $B.make_args_parser(fct)(fct,args);} $B.make_args_parser=function(f){if((! f.$infos)&& f.$function_infos){$B.make_function_infos(f,...f.$function_infos)} if(f.$infos===undefined ||f.$infos.__code__===undefined){console.log('f',f) $B.RAISE_ATTRIBUTE_ERROR(`cannot set defauts to ${_b_.str.$factory(f)}`,f,'defaults')} const varnames=f.$infos.__code__.co_varnames,value=f.$infos.__defaults__,offset=f.$infos.__code__.co_argcount-value.length,$kwdefaults=new Map() var nb_kw_defaults=f.$infos.__kwdefaults__===_b_.None ? 0 : _b_.dict.__len__(f.$infos.__kwdefaults__) if(f.$infos.__kwdefaults__ !==_b_.None){const kwdef=f.$infos.__kwdefaults__ for(let kw of $B.make_js_iterator(kwdef)){$kwdefaults.set(kw,$B.$getitem(kwdef,kw))}} f.$kwdefaults=$kwdefaults f.$kwdefaults_values=[...$kwdefaults.values()] f.$hasParams=new Set() var nb_args=f.$infos.__code__.co_argcount+ f.$infos.__code__.co_kwonlyargcount+ (f.$infos.kwargs ? 1 :0) for(let i=0 ;i < nb_args;++i){f.$hasParams.add(varnames[i])} const $INFOS=f.$infos,$CODE=$INFOS.__code__,DEFAULTS=$B.getArgs0.DEFAULTS const PARAMS_NAMED_COUNT=$CODE.co_kwonlyargcount,PARAMS_NAMED_DEFAULTS_COUNT=nb_kw_defaults let named_defaults=DEFAULTS.NONE; if(PARAMS_NAMED_DEFAULTS_COUNT > 0){named_defaults=PARAMS_NAMED_DEFAULTS_COUNT >=PARAMS_NAMED_COUNT ? DEFAULTS.ALL :DEFAULTS.SOME} const PARAMS_POSONLY_COUNT=$CODE.co_posonlyargcount const PARAMS_POS_COUNT=$CODE.co_argcount-PARAMS_POSONLY_COUNT let pos_defaults=DEFAULTS.NONE if(PARAMS_POS_COUNT !==0 && value.length > 0){pos_defaults=value.length >=PARAMS_POS_COUNT ? DEFAULTS.ALL : DEFAULTS.SOME;} let posonly_defaults=DEFAULTS.NONE if(value.length > PARAMS_POS_COUNT){posonly_defaults=value.length >=$CODE.co_argcount ? DEFAULTS.ALL : DEFAULTS.SOME;} f.$args_parser=f.$infos.args_parser=$B.getArgs0( PARAMS_POSONLY_COUNT !==0,posonly_defaults,PARAMS_POS_COUNT !==0,pos_defaults,$INFOS.vararg !==null,PARAMS_NAMED_COUNT !==0,named_defaults,$INFOS.kwarg !==null ) return f.$args_parser} $B.function.$factory=function(){var $=$B.args('FunctionType',2,{code:null,globals:null},['code','globals'],arguments,{},null,'kw') var code=$.code var __name__=$.name===_b_.None ? code.co_name :$.name var frame=$B.frame_obj.frame var globals_name='locals_'+frame[2] var __file__=frame.__file__ var func=new Function('_b_','__file__',globals_name,'return '+code.co_code) var f=func(_b_,__file__,$.globals) $B.set_function_infos(f,{__name__,__qualname__:frame[2]+'.'+__name__} ) var kwargs=$.kw if(kwargs.hasOwnProperty('argdefs')){$B.set_function_attr(f,'__defaults__',kwargs.argdefs)} if(kwargs.hasOwnProperty('kwdefaults')){$B.set_function_attr(f,'__kwdefaults__',kwargs.kwdefaults)} return f} $B.set_func_names($B.function,"builtins") const args0_fcts=$B.args_parsers=[]; function getArgs0(hasPosOnly,posOnlyDefaults,hasPos,posDefaults,hasVargars,hasNamedOnly,namedOnlyDefaults,hasKWargs){const IDX=hasPosOnly |posOnlyDefaults << 1 |hasPos << 3 |posDefaults << 4 |hasVargars << 6 |hasNamedOnly << 7 |namedOnlyDefaults << 8 |hasKWargs << 10; const args0=args0_fcts[IDX]; if(args0 !==undefined) return args0; const fct=args0_fcts[IDX]=generate_args0(hasPosOnly,posOnlyDefaults,hasPos,posDefaults,hasVargars,hasNamedOnly,namedOnlyDefaults,hasKWargs); fct.id=IDX; return fct;} $B.getArgs0=getArgs0; const DEFAULTS=getArgs0.DEFAULTS={NONE:0,SOME:1,ALL :3} function generate_args0(...args){return new Function('fct','args',generate_args0_str(...args));} function generate_args0_str(hasPosOnly,posOnlyDefaults,hasPos,posDefaults,hasVargars,hasNamedOnly,namedOnlyDefaults,hasKWargs){let fct= ` const LAST_ARGS = args[args.length-1]; const HAS_KW = LAST_ARGS !== undefined && LAST_ARGS !== null && LAST_ARGS.$kw !== undefined; let ARGS_POS_COUNT = args.length; let ARGS_NAMED = null; if( HAS_KW ) { --ARGS_POS_COUNT; ARGS_NAMED = LAST_ARGS.$kw; } const result = {}; // using const should enable the browser to perform some optimisation. const $INFOS = fct.$infos; const $CODE = $INFOS.__code__; `; if(hasPos ||hasPosOnly ||hasNamedOnly ) fct+=` const PARAMS_NAMES = $INFOS.arg_names; `; let PARAMS_POS_COUNT="0"; if(hasPos ||hasPosOnly ){PARAMS_POS_COUNT="PARAMS_POS_COUNT"; fct+=` const PARAMS_POS_COUNT = $CODE.co_argcount; `;} let PARAMS_POS_DEFAULTS_OFFSET=PARAMS_POS_COUNT; let PARAMS_POS_DEFAULTS_COUNT="0"; if(posOnlyDefaults !==DEFAULTS.NONE ||posDefaults !==DEFAULTS.NONE ){PARAMS_POS_DEFAULTS_OFFSET="PARAMS_POS_DEFAULTS_OFFSET"; PARAMS_POS_DEFAULTS_COUNT="PARAMS_POS_DEFAULTS_COUNT"; fct+=` const PARAMS_POS_DEFAULTS = $INFOS.__defaults__; const PARAMS_POS_DEFAULTS_COUNT = PARAMS_POS_DEFAULTS.length; const PARAMS_POS_DEFAULTS_OFFSET= ${PARAMS_POS_COUNT} - PARAMS_POS_DEFAULTS_COUNT; `;} fct+=` let offset = 0; `; if(hasVargars ){fct+= ` result[$INFOS.vararg] = $B.fast_tuple( Array.prototype.slice.call(args, ${PARAMS_POS_COUNT}, ARGS_POS_COUNT ) ); //TODO: opti, better way to construct tuple from subarray ? ` if(hasPosOnly ||hasPos ){fct+= ` const min = Math.min( ARGS_POS_COUNT, ${PARAMS_POS_COUNT} ); for( ; offset < min ; ++offset) result[ PARAMS_NAMES[offset] ] = args[offset]; `}}else{ fct+= ` if( ARGS_POS_COUNT > ${PARAMS_POS_COUNT} ) { $B.args0_old(fct, args); throw new Error('Too much positional arguments given (args0 should have raised an error) !'); } ` if(hasPosOnly ||hasPos ){fct+= ` for( ; offset < ARGS_POS_COUNT ; ++offset) result[ PARAMS_NAMES[offset] ] = args[offset]; `}} if(! hasPos && ! hasNamedOnly && ! hasKWargs ){fct+=` if( HAS_KW === true ) { for(let argname in ARGS_NAMED[0] ) { $B.args0_old(fct, args); throw new Error('No named arguments expected !!!'); } for(let id = 1; id < ARGS_NAMED.length; ++id ) { const kargs = ARGS_NAMED[id]; for(let argname of $B.unpack_mapping( fct, kargs) ) { //TODO: not optimal $B.args0_old(fct, args); throw new Error('No named arguments expected !!!'); } } } `;}else{ fct+=` if( HAS_KW === false ) { `;} if(hasPos ||hasPosOnly ){if(posOnlyDefaults !==DEFAULTS.ALL && posDefaults !==DEFAULTS.ALL ){fct+=` if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) { $B.args0_old(fct, args); throw new Error('Not enough positional arguments given (args0 should have raised an error) !'); } `} if(posOnlyDefaults !==DEFAULTS.NONE ||posDefaults !==DEFAULTS.NONE){fct+=` for(let i = offset - PARAMS_POS_DEFAULTS_OFFSET; i < PARAMS_POS_DEFAULTS_COUNT; ++i) result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i];`}} if(hasKWargs ){fct+=` result[$INFOS.kwarg] = __BRYTHON__.empty_dict();`} if(hasNamedOnly && namedOnlyDefaults !==DEFAULTS.ALL){fct+=` $B.args0_old(fct, args); throw new Error('Named argument expected (args0 should have raised an error) !'); `}else if(namedOnlyDefaults !==DEFAULTS.NONE ){fct+=` const kwargs_defaults_values = fct.$kwdefaults_values; for(let i = 0; i < kwargs_defaults_values.length; ++i ) result[ PARAMS_NAMES[offset++] ] = kwargs_defaults_values[i]; `} fct+=` return result; ` if(! hasPos && ! hasNamedOnly && ! hasKWargs ){return fct;}else{ fct+=` } `;} if(namedOnlyDefaults !==DEFAULTS.NONE){fct+=` const kwargs_defaults = fct.$kwdefaults; `} if(hasPosOnly ){fct+=` const PARAMS_POSONLY_COUNT = $CODE.co_posonlyargcount; if( offset < PARAMS_POSONLY_COUNT ) { `; if(posOnlyDefaults !==DEFAULTS.SOME){fct+=` if( offset < ${PARAMS_POS_DEFAULTS_OFFSET} ) { $B.args0_old(fct, args); throw new Error('Not enough positional parameters given (args0 should have raised an error) !'); } `} if(posOnlyDefaults===DEFAULTS.NONE){fct+=` $B.args0_old(fct, args); throw new Error('Not enough positional parameters given (args0 should have raised an error) !'); `;} fct+=` const max = ${PARAMS_POS_DEFAULTS_COUNT} - (${PARAMS_POS_COUNT} - PARAMS_POSONLY_COUNT); // default parameters for(let i = offset - ${PARAMS_POS_DEFAULTS_OFFSET}; i < max; ++i) result[ PARAMS_NAMES[offset++] ] = PARAMS_POS_DEFAULTS[i]; } `} if(hasKWargs){fct+=` const extra = {}; let nb_extra_args = 0; ` if(hasPos ||hasNamedOnly ){fct+=` const HAS_PARAMS = fct.$hasParams; `;}} fct+=` let nb_named_args = 0; const kargs = ARGS_NAMED[0]; for(let argname in kargs) { `; if(! hasKWargs ){fct+=` result[ argname ] = kargs[argname]; ++nb_named_args; `;} if(hasKWargs ){if(! hasNamedOnly && ! hasPos ){fct+=` extra[ argname ] = kargs[argname]; ++nb_extra_args; `}else{ fct+=` if( HAS_PARAMS.has(argname) ) { result[ argname ] = kargs[argname]; ++nb_named_args; } else { extra[ argname ] = kargs[argname]; ++nb_extra_args; } `}} fct+=` } for(let id = 1; id < ARGS_NAMED.length; ++id ) { const kargs = ARGS_NAMED[id]; for(let item of $B.unpack_mapping(fct, kargs) ) { let argname = item.key if( typeof argname !== "string") { $B.args0_old(fct, args); throw new Error('Non string key passed in **kargs'); } `; if(! hasKWargs ){fct+=` result[ argname ] = item.value; ++nb_named_args; `;} if(hasKWargs ){if(! hasNamedOnly && ! hasPos ){fct+=` extra[ argname ] = $B.$getitem(kargs, argname); ++nb_extra_args; `}else{ fct+=` if( HAS_PARAMS.has(argname) ) { result[ argname ] = $B.$getitem(kargs, argname); ++nb_named_args; } else { extra[ argname ] = $B.$getitem(kargs, argname); ++nb_extra_args; } `}} fct+=` } } ` fct+=` let found = 0; let ioffset = offset; `; if((hasPosOnly ||hasPos) &&(! hasPosOnly ||posOnlyDefaults !==DEFAULTS.ALL) &&(! hasPos ||posDefaults !==DEFAULTS.ALL)){fct+=` for( ; ioffset < ${PARAMS_POS_DEFAULTS_OFFSET}; ++ioffset) { const key = PARAMS_NAMES[ioffset]; if( key in result ) // maybe could be speed up using "!(key in result)" continue; $B.args0_old(fct, args); throw new Error('Missing a named arguments (args0 should have raised an error) !'); } `} if((hasPosOnly && posOnlyDefaults !==DEFAULTS.NONE)||(hasPos && posDefaults !==DEFAULTS.NONE)){fct+=` for( ; ioffset < PARAMS_POS_COUNT; ++ioffset) { const key = PARAMS_NAMES[ioffset]; if( key in result ) continue; result[key] = PARAMS_POS_DEFAULTS[ioffset - ${PARAMS_POS_DEFAULTS_OFFSET}]; ++found; } `} if(hasNamedOnly ){fct+=` for( ; ioffset < PARAMS_NAMES.length; ++ioffset) { const key = PARAMS_NAMES[ioffset]; if( key in result ) continue; ` if(namedOnlyDefaults===DEFAULTS.SOME){fct+=` if( ! kwargs_defaults.has(key) ) { $B.args0_old(fct, args); throw new Error('Missing a named arguments (args0 should have raised an error) !'); } `} if(namedOnlyDefaults===DEFAULTS.NONE ){fct+=` $B.args0_old(fct, args); throw new Error('Missing a named arguments (args0 should have raised an error) !'); `} if(namedOnlyDefaults !==DEFAULTS.NONE){fct+=` result[key] = kwargs_defaults.get(key); ++found; `;} fct+=` } `;} if(hasNamedOnly ||hasPos ) fct+=` if( found + nb_named_args !== PARAMS_NAMES.length - offset) { $B.args0_old(fct, args); throw new Error('Inexistant or duplicate named arguments (args0 should have raised an error) !'); } `; if(hasKWargs ){fct+=` if( Object.keys(extra).length !== nb_extra_args ) { $B.args0_old(fct, args); throw new Error('Duplicate name given to **kargs parameter (args0 should have raised an error) !'); } result[$INFOS.kwarg] = __BRYTHON__.builtins.dict.$from_js(extra); `} fct+=` return result `; return fct;} function missing_names(missing){var len=missing.length var plural=len==1 ? '' :'s' var report switch(len){case 1: report=`${missing[0]}` break case 2: report=`${missing[0]} and ${missing[1]}` break default: report=`${missing.slice(0, len - 1).join(', ')}, and `+ `${missing[len - 1]}` break} return report} function add_to_kwargs(kw_dict,key,value){kw_dict.$strings[key]=value} $B.args_parser=function(f,args){if(! f.$arguments_parser){f.$arguments_parser=make_arguments_parser(f)} return f.$arguments_parser(f,args)} $B.has_kw=function(args){var last_arg=args[args.length-1] return last_arg && last_arg.$kw} var empty={} function make_arguments_parser(f){ var infos=f.$function_infos var name=infos[$B.func_attrs.__name__] var arg_names=infos[$B.func_attrs.arg_names] var positional_length=infos[$B.func_attrs.positional_length] var kwonly_length=infos[$B.func_attrs.kwonlyargs_length] var vararg=infos[$B.func_attrs.args_vararg] var kwarg=infos[$B.func_attrs.args_kwarg] var defaults=infos[$B.func_attrs.__defaults__] var posonly_length=infos[$B.func_attrs.posonlyargs_length] var kwonly_defs=[$B.func_attrs.__kwdefaults__] var nb_formal=positional_length+kwonly_length var def_obj={} if(defaults !==_b_.None){var start_defs=positional_length-defaults.length for(var i=start_defs;i < positional_length;i++){def_obj[arg_names[i]]=defaults[i-start_defs]}} if(kwonly_defs !==_b_.None){for(var key in kwonly_defs){def_obj[key]=kwonly_defs[key]}} var parser=function(f,args){function add_key(key,value){var index=arg_names.indexOf(key) if(index==-1){if(kwarg){add_to_kwargs(locals[kwarg],key,value) return}else{$B.RAISE(_b_.TypeError,name+ `() got an unexpected keyword argument '${key}'`)}} if(locals.hasOwnProperty(key)){if(kwarg && index < posonly_length){_b_.dict.$setitem_string(locals[kwarg],key,value) return} $B.RAISE(_b_.TypeError,name+ `() got multiple values for argument '${key}'`)} if(index < posonly_length){if(defaults===_b_.None || index <=positional_length-defaults.length){ if(kwarg){_b_.dict.$setitem_string(locals[kwarg],key,value)}else{posonly_as_keywords.push(key)}}}else{locals[key]=value filled_pos++}} var too_many_pos=0 var posonly_as_keywords=[] const locals={} var filled_pos=0 var vargs if(kwarg !==null){locals[kwarg]=$B.empty_dict()} const args_length=args.length const last_arg=args[args_length-1] const has_kw=last_arg && last_arg.$kw const nb_pos=has_kw ? args_length-1 :args_length if(vararg !==null){locals[vararg]=vargs=[]} if(nb_pos <=positional_length){for(let iarg=0;iarg < nb_pos;iarg++){locals[arg_names[iarg]]=args[iarg]} filled_pos=nb_pos}else{for(let iarg=0;iarg < positional_length;iarg++){locals[arg_names[iarg]]=args[iarg]} filled_pos=positional_length if(vararg !==null){for(let j=positional_length;j < nb_pos;j++){vargs[vargs.length]=args[j]}}else{too_many_pos=nb_pos-positional_length}} if(has_kw){var elt=last_arg for(let key in elt.$kw[0]){add_key(key,elt.$kw[0][key])} for(let i=1;i< elt.$kw.length;i++){if(elt.$kw[i].__class__===_b_.dict){for(let item of _b_.dict.$iter_items(elt.$kw[i])){add_key(item.key,item.value)}}else{let klass=$B.get_class(elt.$kw[i]) let keys_method=$B.$getattr(klass,'keys',null) let getitem=$B.$getattr(klass,'__getitem__',null) if(keys_method===null ||getitem===null){$B.RAISE(_b_.TypeError,`${name} argument after ** must be a mapping, `+ `not ${$B.class_name(elt.$kw[i])}`)} for(let key of $B.make_js_iterator(keys_method(elt.$kw[i]))){add_key(key,getitem(elt.$kw[i],key))}}}} if(vararg !==null){locals[vararg]=$B.fast_tuple(locals[vararg])} if(nb_formal==0){ return locals} if(too_many_pos > 0){var plural=positional_length==1 ? '' :'s' var nb=positional_length+too_many_pos var report=positional_length if(defaults.length){var nb_min=positional_length-defaults.length report=`from ${nb_min} to ${positional_length}` plural='s'} $B.RAISE(_b_.TypeError,`${name}() takes ${report} positional argument`+ `${plural} but ${nb} were given`)} if(posonly_as_keywords.length > 0){$B.RAISE(_b_.TypeError,`${name}() got some positional-only arguments passed as keyword `+ `arguments: '${posonly_as_keywords.join(', ')}'`)} if(filled_pos < nb_formal){for(let key in def_obj){if(! locals.hasOwnProperty(key)){locals[key]=def_obj[key] filled_pos++}} if(filled_pos < nb_formal){ var missing_positional=[] var missing_kwonly=[] for(let i=0;i < nb_formal;i++){let arg_name=arg_names[i] if(! locals.hasOwnProperty(arg_name)){if(i < positional_length){missing_positional.push(`'${arg_name}'`)}else{missing_kwonly.push(`'${arg_name}'`)}}} var missing var missing_type var report if(missing_positional.length){missing=missing_positional missing_type='positional'}else{missing=missing_kwonly missing_type='keyword-only'} var report=missing_names(missing) var nb_missing=missing.length var plural=nb_missing==1 ? '' :'s' $B.RAISE(_b_.TypeError,name+ `() missing ${nb_missing} required ${missing_type} `+ `argument${plural}: ${report}`)}} return locals} return parser}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var IOUnsupported const DEFAULT_BUFFER_SIZE=(128*1024) $B.make_IOUnsupported=function(){if($B._IOUnsupported===undefined){$B._IOUnsupported=$B.make_class('UnsupportedOperation') $B._IOUnsupported.__bases__=[_b_.OSError,_b_.ValueError] $B._IOUnsupported.__mro__=_b_.type.$mro($B._IOUnsupported) $B._IOUnsupported.__module__='_io'}} function _io_unsupported(value){$B.make_IOUnsupported() throw $B.$call($B._IOUnsupported)(value)} var _IOBase=$B.make_class("_IOBase") _IOBase.__del__=function(_self){ console.log('del',_self) try{var closed=$B.$getattr(_self,'closed')}catch(err){if($B.is_exc(err,_b_.AttributeError)){ return}} if(closed){return} $B$call($B.$getattr(_self,'close'))()} _IOBase.__enter__=function(self){return self} _IOBase.__exit__=function(self){_IOBase.close(self)} _IOBase.__iter__=function(_self){if(_self.closed){$B.RAISE(_b_.ValueError,'closed')} return _self} _IOBase.__next__=function(_self){var readline=$B.search_in_mro($B.get_class(_self),'readline') var line=readline(_self) if(line==undefined ||_b_.len(line)===0){$B.RAISE(_b_.StopIteration,'')} return line;} _IOBase.__del__=function(_self){return _IOBase.close(_self)} _IOBase.close=function(_self){_self._closed=true} _IOBase.fileno=function(_self){_io_unsupported('fileno')} _IOBase.flush=function(_self){if(_self._closed){$B.RAISE(_b_.ValueError,"I/O operation on closed file.")} return _b_.None} _IOBase.isatty=function(){return false} _IOBase.readable=function(){return false} function make_lines(self){ if(self.$lines===undefined){if(! self.$binary){self.$lines=self.$content.split("\n") if($B.last(self.$lines)==''){self.$lines.pop()} self.$lines=self.$lines.map(x=> x+'\n')}else{var lines=[],pos=0,source=self.$content.source,len=source.length while(pos < len){var ix=source.indexOf(10,pos) if(ix==-1){lines.push({__class__:_b_.bytes,source:source.slice(pos)}) break}else{lines.push({__class__:_b_.bytes,source:source.slice(pos,ix+1)}) pos=ix+1}} self.$lines=lines}}} _IOBase.readline=function(_self,limit=-1){var $=$B.args('readline',2,{self:null,limit:null},['self','limit'],arguments,{limit:-1},null,null),_self=$.self,limit=$.limit var old_size=-1 var peek=$B.$getattr(_self,"peek",null) var buffer=_b_.bytearray.$factory() limit=$B.PyNumber_Index(limit) while(limit < 0 ||_b_.len(buffer)< limit){var nreadahead=1 var b if(peek !=null){var readahead=peek(1) if(! $B.$isinstance(readahead,_b_.bytes)){$B.RAISE(_b_.OSError,"peek() should have returned a bytes object, "+ `not '${$B.class_name(readahead)}'`)} if(readahead.length > 0){var n=0 var buf=_b_.bytes.$decode(readahead,'latin-1') if(limit >=0){while(true){if(n >=readahead.length ||n >=limit){break} if(buf[n++]=='\n'){break}}}else{while(true){if(n >=readahead.length){break} if($B.$getitem(buffer,n++)=='\n'){break}}} nreadahead=n}} var read=$B.search_in_mro($B.get_class(_self),"read") b=$B.$call(read)(_self,nreadahead) if(! $B.$isinstance(b,_b_.bytes)){$B.RAISE(_b_.OSError,"read() should have returned a bytes object, "+ `not '${$B.class_name(b)}'`)} if(_b_.len(b)==0){break;} _b_.bytearray.extend(buffer,b) if($B.last(_b_.list.$factory(buffer))==10){ break}} return $B.$call(_b_.bytes)(buffer)} _IOBase.readlines=function(_self,hint){var $=$B.args('readlines',2,{self:null,hint:null},['self','hint'],arguments,{hint:-1},null,null) var _self=$.self,hint=$.hint var length=0; var result,it if(hint===_b_.None){hint=-1}else{hint=$B.PyNumber_Index(hint)} result=$B.$list([]) if(hint <=0){return _b_.list.$factory(_self)} var readline=$B.search_in_mro($B.get_class(_self),'readline') var nb=0 while(true){nb++ if(nb > 5000){console.log('overflow',result) break} var line=readline(_self) var line_length=_b_.len(line) if(line_length==0){break}else{result[result.length]=line} if(line_length > hint-length){break} length+=line_length} return result} _IOBase.seek=function(_self){_io_unsupported('seek')} _IOBase.seekable=function(){return false} _IOBase.tell=function(self){return $B.$getattr(self,'seek')(0,1)} _IOBase.truncate=function(){_io_unsupported('truncate')} _IOBase.writable=function(){return false} _IOBase.writelines=function(_self,lines){if(_self.closed){return _b_.None} var iter=$B.make_js_iterator(lines) var writer=$B.search_in_mro($B.get_class(_self),'write') if(writer===undefined){$B.RAISE_ATTRIBUTE_ERROR( `'${$B.class_name(_self)}' object has no attribute 'write'`,_self,'write')} for(var line of iter){writer(_self,line)} return _b_.None} _IOBase.writelines=function(_self,lines){var iter,res; if(_self.closed){$B.RAISE(_b_.OSError,'closed')} var writer=$B.$call($B.$getattr(_self,'write')) for(var line of $B.make_js_iterator(lines)){writer(line)} return _b_.None} $B.set_func_names(_IOBase,"builtins") $B._RawIOBase=$B.make_class('_io._RawIOBase') $B._RawIOBase.__bases__=[_IOBase] $B._RawIOBase.__mro__=[_IOBase,_b_.object] $B._RawIOBase.read=function(_self,n){var b,res if(n < 0){return $B.$call($B.$getattr(_self,"readall"))} b=_b_.bytearray.$factory() $B.$call($B.$getattr(_self,"readinto"))(b) return b} $B._RawIOBase.readall=function(_self){var r var chunks=[] var result while(1){var data=$B.$call($B.$getattr(_self,"read"))(DEFAULT_BUFFER_SIZE) if(data===_b_.None){if(chunks.length==0){return data} break} if(! $B.$isinstance(data,_b_.bytes)){$B.RAISE(_b_.TypeError,"read() should return bytes")} if(_b_.len(data)==0){break} chunks.push(data)} result=_b_.bytes.join(_b_.bytes.$fast_bytes([]),chunks) return result} $B._RawIOBase.readinto=function(_self,b){throw _b_.NotImplementedError('readinto')} $B._RawIOBase.write=function(){throw _b_.NotImplementedError('readinto')} $B.set_func_names($B._RawIOBase,"_io") $B._BufferedIOBase=$B.make_class('_BufferedIOBase') $B._BufferedIOBase.__bases__=[_IOBase] $B._BufferedIOBase.__mro__=[_IOBase,_b_.object] $B.is_buffer=function(obj){if($B.get_class(obj).$buffer_protocol){return true} for(var klass of $B.get_class(obj).__mro__){if(klass.$buffer_protocol){return true}} return false} function _bufferediobase_readinto_generic(_self,buffer,readinto1){var len,data if(! $B.is_buffer(buffer)){$B.RAISE(_b_.TypeError," readinto() argument must be "+ `read-write bytes-like object, not ${$B.class_name(buffer)}`)} var attr=readinto1 ? "read1" :"read" data=$B.$call($B.$getattr(_self,attr))(_b_.len(buffer)) if(! $B.$isinstance(data,_b_.bytes)){$B.RAISE(_b_.TypeError,"read() should return bytes")} len=_b_.bytes.__len__(data) if(len > _b_.len(buffer)){$B.RAISE(_b_.ValueError,"read() returned too much data: " `${_b_.len(buffer)} bytes requested, ${len} returned`)} var setitem=$B.search_in_mro($B.get_class(buffer),'__setitem__') $B.$call(setitem)(buffer,_b_.slice.$factory(0,len),data) return len} $B._BufferedIOBase.readinto=function(_self,buffer){return _bufferediobase_readinto_generic(_self,buffer,0);} $B._BufferedIOBase.readinto1=function(_self,buffer){return _bufferediobase_readinto_generic(_self,buffer,1);} $B._BufferedIOBase.close=function(_self){_self.closed=true} $B._BufferedIOBase.detach=function(){_io_unsupported("detach")} $B._BufferedIOBase.read=function(){_io_unsupported("read")} $B._BufferedIOBase.read1=function(){_io_unsupported("read1")} $B._BufferedIOBase.write=function(){_io_unsupported("write")} $B.set_func_names($B._BufferedIOBase,'_io') function _bufferedreader_read_all(_self){return $B.$call($B.$getattr(_self.raw,'readall'))()} function _bufferedreader_read_fast(_self,n){var raw=_self.raw if(raw.$byte_pos >=raw.$bytes.length){return _b_.None} var b=raw.$bytes.slice(raw.$byte_pos,raw.$byte_pos+n) raw.$byte_pos+=n raw.$byte_pos=Math.min(raw.$byte_pos,raw.$bytes.length) return $B.fast_bytes(b)} function _bufferedreader_readline(_self){var raw=_self.raw if(raw.$byte_pos >=raw.$bytes.length){return $B.fast_bytes()} var eof=raw.$byte_pos while(eof < raw.$bytes.length){if(raw.$bytes[eof]==10){break} eof++} var b=raw.$bytes.slice(raw.$byte_pos,eof+1) raw.$byte_pos=eof+1 raw.$byte_pos=Math.min(raw.$byte_pos,raw.$bytes.length) return $B.fast_bytes(b)} $B._BufferedReader=$B.make_class('_BufferedReader') $B._BufferedReader.__bases__=[$B._BufferedIOBase] $B._BufferedReader.__mro__=_b_.type.$mro($B._BufferedReader) $B._BufferedReader.__init__=function(_self,raw,buffer_size=DEFAULT_BUFFER_SIZE){_self.raw=raw _self.buffer_size=buffer_size} $B._BufferedReader.peek=function(_self,size){var $=$B.args('peek',2,{self:null,size:null},['self','size'],arguments,{size:0},null,null),_self=$.self,size=$.size var raw=_self.raw return $B.fast_bytes(raw.$bytes.slice(raw.$byte_pos,raw.$byte_pos+size))} $B._BufferedReader.seek=function(_self,offset,whence){var $=$B.args('seek',2,{self:null,offset:null,whence:null},['self','offset','whence'],arguments,{whence:0},null,null),_self=$.self,offset=$.offset,whence=$.whence if(_self.closed){$B.RAISE(_b_.ValueError,'I/O operation on closed file')} if(whence===undefined){whence=0} if(whence===0){_self.$byte_pos=offset}else if(whence===1){_self.$byte_pos+=offset}else if(whence===2){_self.$byte_pos=self.$bytes.length+offset} return _b_.None} function CHECK_CLOSED(fileobj,msg){if(fileobj.closed){$B.RAISE(_b_.ValueError,msg)}} $B._BufferedReader.read=function(_self,n=-1){var res if(n <-1){$B.RAISE(_b_.ValueError,"read length must be non-negative or -1")} CHECK_CLOSED(self,"read of closed file") if(n==-1){ res=_bufferedreader_read_all(_self)}else{res=_bufferedreader_read_fast(_self,n) if(res !=_b_.None){return res} return $B.fast_bytes()} return res} $B._BufferedReader.readline=function(_self,size=-1){return _bufferedreader_readline(_self)} $B.set_func_names($B._BufferedReader,'_io') $B._FileIO=$B.make_class('_FileIO') $B._FileIO.__bases__=[$B._RawIOBase] $B._FileIO.__mro__=_b_.type.$mro($B._FileIO) function bad_mode(){$B.RAISE(_b_.ValueError,"Must have exactly one of create/read/write/append "+ "mode and at most one plus")} function err_closed(){$B.RAISE(_b_.ValueError,"I/O operation on closed file")} const O_RDONLY=0,O_WRONLY=1,O_RDWR=2,O_EXCL=1024,O_CREAT=256,O_TRUNC=512,O_APPEND=8 $B._FileIO.__new__=function(cls){return{ __class__:cls,fd:-1,created:0,readable:0,writable:0,appending:0,seekable:-1,closefd:1}} $B._FileIO.__init__=function(){var $=$B.args('__init__',5,{self:null,name:null,mode:null,closefd:null,opener:null},['self','name','mode','closefd','opener'],arguments,{mode:'r',closefd:true,opener:_b_.None},null,null),_self=$.self,name=$.name,mode=$.mode,closefd=$.closefd,opener=$.opener var flags=0 var ret=0 var rwa=0,plus=0 var s=mode var pos=0 while(pos < s.length){switch(s[pos]){case 'x': if(rwa){bad_mode()} rwa=1 _self.created=1 _self.writable=1 flags |=O_EXCL |O_CREAT break case 'r': if(rwa){bad_mode()} rwa=1 _self.readable=1 break case 'w': if(rwa){bad_mode()} rwa=1 _self.writable=1 flags |=O_CREAT |O_TRUNC break case 'a': if(rwa){bad_mode()} rwa=1; _self.writable=1 _self.appending=1 flags |=O_APPEND |O_CREAT break case 'b': break case '+': if(plus){bad_mode()} _self.readable=_self.writable=1 plus=1 break default: $B.RAISE(_b_.ValueError,`invalid mode: ${mode}`);} pos++} if(!rwa){bad_mode()} if(_self.readable && _self.writable){flags |=O_RDWR;}else if(_self.readable){flags |=O_RDONLY}else{flags |=O_WRONLY} if($B.file_cache.hasOwnProperty(name)){_self.$bytes=$B.to_bytes($B.encode($B.file_cache[name],'utf-8')) _self.$byte_pos=0 _self.$line_pos=0 _self.$text=$B.file_cache[name] _self.$text_iterator=_self.$text[Symbol.iterator]() _self.$text_length=_b_.len(_self.$text) return}else if($B.files && $B.files.hasOwnProperty(name)){ var $res=atob($B.files[name].content) var bytes=[] for(const char of $res){bytes.push(char.charCodeAt(0))} _self.$bytes=bytes _self.$byte_pos=_self.$line_pos=0 return} _self.fd=new XMLHttpRequest() _self.fd.overrideMimeType('text/plain;charset=x-user-defined') _self.fd.onreadystatechange=function(){if(this.readyState !=4){return} var status=this.status if(status==404){this.error=$B.EXC(_b_.FileNotFoundError,name)}else if(status !=200){this.error=$B.EXC(_b_.IOError,'Could not open file '+ name+' : status '+status)}else{var bytes=[] for(var codePoint of this.response){var cp=codePoint.codePointAt(0) if(cp > 0xf700){cp-=0xf700} bytes[bytes.length]=cp} _self.$bytes=bytes _self.$byte_pos=0 _self.$line_pos=0}} var cache=$B.get_option('cache'),fake_qs=cache ? '' :'?foo='+(new Date().getTime()) _self.fd.open('GET',encodeURI(name+fake_qs),false) _self.fd.send() if(_self.fd.error){throw _self.fd.error}} $B._FileIO.readable=function(_self){if(_self.fd < 0){err_closed()} return $B.$bool(_self.readable)} $B._FileIO.readall=function(_self){var buffer=_b_.bytearray.$factory() $B._FileIO.readinto(_self,buffer) buffer.__class__=_b_.bytes return buffer} $B._FileIO.readinto=function(_self,buffer){if(_self.fd < 0){err_closed()} if(! _self.readable){return err_mode(state,"reading")} _b_.bytearray.extend(buffer,$B.fast_bytes(_self.$bytes)) var n=_b_.len(buffer) return n} $B._FileIO.readinto1=$B._FileIO.readinto $B._FileIO.seekable=function(_self){if(_self.fd < 0){err_closed()} return $B.$bool(_self.seekable)} $B._FileIO.writable=function(_self){if(_self.fd < 0){err_closed()} return $B.$bool(_self.writable)} $B.set_func_names($B._FileIO,'_io') $B._TextIOBase=$B.make_class('_io._TextIOBase') $B._TextIOBase.__bases__=[_IOBase] $B._TextIOBase.__mro__=[_IOBase,_b_.object] $B._TextIOBase.encoding=$B.getset_descriptor.$factory( $B._TextIOBase,'encoding',function(_self){return _self._encoding ?? _b_.None},function(_self,value){_self._encoding=value} ) $B._TextIOBase.errors=$B.getset_descriptor.$factory( $B._TextIOBase,'errors',function(_self){return _self.errors ?? _b_.None},function(_self,value){_self._errors=value} ) $B._TextIOBase.read=function(){_io_unsupported('read')} var $BufferedReader=$B.make_class('_io.BufferedReader',function(content){return{ __class__:$BufferedReader,$binary:true,$content:content,$read_func:$B.$getattr(content,'read')}} ) $BufferedReader.__mro__=[_IOBase,_b_.object] $BufferedReader.read=function(self,size){if(self.$read_func===undefined){return _IOBase.read(self,size===undefined ?-1 :size)} return self.$read_func(size ||-1)} $B._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) if($.encoding===_b_.None){$.encoding='utf-8'} var bytes=$B.fast_bytes($.buffer.raw.$bytes) var res={__class__:$B._TextIOWrapper,$buffer:$.buffer,$bytes:bytes,$encoding:$.encoding,$errors:$.errors,$newline:$.newline,__dict__:$B.empty_dict()} return res} ) $B._TextIOWrapper.$tp_dict={} $B._TextIOWrapper.__bases__=[$B._TextIOBase] $B._TextIOWrapper.__mro__=[$B._TextIOBase,_IOBase,_b_.object] $B._TextIOWrapper.$tp_dict.buffer=$B.getset_descriptor.$factory( $B._TextIOWrapper,'buffer',function(_self){return _self.$buffer} ) $B._TextIOWrapper.fileno=function(_self){return-1} $B._TextIOWrapper.read=function(){var $=$B.args("read",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),_self=$.self,size=$B.PyNumber_Index($.size) if(_self.closed===true){$B.RAISE(_b_.ValueError,'I/O operation on closed file')} if(_self.$text===undefined){_self.$text=$B.decode(_self.$bytes,_self.$encoding,_self.$errors) _self.$text_pos=0} var len=_b_.len(_self.$text) if(size < 0){size=len-_self.$text_pos} var res=_b_.str.__getitem__(_self.$text,_b_.slice.$fast_slice(_self.$text_pos,_self.$text_pos+size,1)) _self.$text_pos+=size _self.$text_pos=Math.min(_self.$text_pos,_self.$text.length) return res} $B._TextIOWrapper.readline=function(){var $=$B.args("read",2,{self:null,size:null},["self","size"],arguments,{size:-1},null,null),_self=$.self,size=$B.PyNumber_Index($.size) if(_self.closed===true){$B.RAISE(_b_.ValueError,'I/O operation on closed file')} if(_self.$text===undefined){_self.$text=$B.decode(_self.$bytes,_self.$encoding,_self.$errors) _self.$text_iterator=_self.$text[Symbol.iterator]() _self.$text_pos=0 _self.$text_length=_b_.len(_self.$text)} var res='' var nb=0 if(size < 0){size=_self.$text_length} while(1){var char=_self.$text_iterator.next() if(char.done){break}else if(char.value=='\n'){res+=char.value break}else{res+=char.value nb++ if(nb > size){break}}} return $B.String(res)} $B._TextIOWrapper.seek=function(_self,offset,whence){if(_self.closed){$B.RAISE(_b_.ValueError,'I/O operation on closed file')} if(whence===undefined){whence=0} if(whence===0){self.$text_pos=offset}else if(whence===1){self.$text_pos+=offset}else if(whence===2){self.$text_pos=self.$text_length+offset} return _b_.None} $B.set_func_names($B._TextIOWrapper,"builtins") $B._IOBase=_IOBase function invalid_mode(mode){$B.RAISE(_b_.ValueError,`invalid mode: '${mode}'`)} function _io_open_impl(file,mode,buffering,encoding,errors,newline,closefd,opener){var i; var creating=0,reading=0,writing=0,appending=0,updating=0; var text=0,binary=0; var rawmode='',m; var line_buffering,is_number,isatty=0; var raw,modeobj,buffer,wrapper,result,path_or_fd=NULL; path_or_fd=file if(! $B.$isinstance(path_or_fd,_b_.str)){$B.RAISE(_b_.TypeError,`invalid file: ${file}`)} if(encoding=='locale'){ encoding='utf-8'} for(var i=0,len=mode.length;i < len;i++){var c=mode[i] switch(c){case 'x': creating=1 break case 'r': reading=1 break case 'w': writing=1 break case 'a': appending=1 break case '+': updating=1 break case 't': text=1 break case 'b': binary=1 break default: invalid_mode(mode)} if(mode[i+1]==c){invalid_mode(mode)}} m='' if(creating)m+='x'; if(reading)m+='r'; if(writing)m+='w'; if(appending)m+='a'; if(updating)m+='+'; rawmode=m if(text && binary){$B.RAISE(_b_.ValueError,"can't have text and binary mode at once")} if(creating+reading+writing+appending > 1){$B.RAISE(_b_.ValueError,"must have exactly one of create/read/write/append mode")} if(binary && encoding !==_b_.None){$B.RAISE(_b_.ValueError,"binary mode doesn't take an encoding argument")} if(binary && errors !=_b_.None){$B.RAISE(_b_.ValueError,"binary mode doesn't take an errors argument");} if(binary && newline !==_b_.None){$B.RAISE(_b_.ValueError,"binary mode doesn't take a newline argument");} if(binary && buffering==1){$B.RAISE(_b_.RuntimeWarning,"line buffering (buffering=1) isn't supported in "+ "binary mode, the default buffer size will be used")} var RawIO_class=$B._FileIO raw=$B.$call(RawIO_class)(path_or_fd,rawmode,closefd ? true :false,opener) result=raw modeobj=mode if(buffering < 0){isatty=false} if(buffering==1 ||isatty){buffering=-1 line_buffering=1}else{line_buffering=0} if(buffering < 0){buffering=DEFAULT_BUFFER_SIZE} if(buffering==0){if(! binary){$B.RAISE(_b_.ValueError,"can't have unbuffered text I/O")} return result} var Buffered_class if(updating){Buffered_class=$B._BufferedRandom}else if(creating ||writing ||appending){Buffered_class=$B._BufferedWriter}else if(reading){Buffered_class=$B._BufferedReader}else{$B.RAISE(_b_.ValueError,`unknown mode: '${mode}'`)} result=$B.$call(Buffered_class)(raw,buffering) if(binary){return result} var wrapper=$B.$call($B._TextIOWrapper)(result,encoding,errors,newline,line_buffering ? true :false) $B.$setattr(wrapper,'mode',modeobj) return wrapper} _b_.open=function(){ var $=$B.args('open',3,{file:null,mode:null,encoding:null},['file','mode','encoding'],arguments,{mode:'r',encoding:'utf-8'},'args','kw'),file=$.file,mode=$.mode,encoding=$.encoding,result={} if(encoding=='locale'){ encoding='utf-8'} var is_binary=mode.search('b')>-1 if(mode.search('w')>-1){ result={$binary:is_binary,$content:is_binary ? _b_.bytes.$factory():'',$encoding:encoding,closed:False,mode,name:file} result.__class__=is_binary ? $BufferedReader :$TextIOWrapper $B.file_cache[file]=result.$content return result}else if(['r','rb'].indexOf(mode)==-1){$B.RAISE(_b_.ValueError,"Invalid mode '"+mode+"'")} if($B.$isinstance(file,_b_.str)){ if($B.file_cache.hasOwnProperty($.file)){var f=$B.file_cache[$.file] result.content=f if(is_binary && typeof f=='string'){result.content=_b_.str.encode(f,'utf-8')}else if(f.__class__===_b_.bytes && ! is_binary){result.content=_b_.bytes.decode(f,encoding)}}else if($B.files && $B.files.hasOwnProperty($.file)){ var $res=atob($B.files[$.file].content) var source=[] for(const char of $res){source.push(char.charCodeAt(0))} result.content=_b_.bytes.$factory(source) if(!is_binary){ try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}else if($B.protocol !="file"){ var req=new XMLHttpRequest() req.overrideMimeType('text/plain;charset=x-user-defined') req.onreadystatechange=function(){if(this.readyState !=4){return} var status=this.status if(status==404){result.error=$B.EXC(_b_.FileNotFoundError,file)}else if(status !=200){result.error=$B.EXC(_b_.IOError,'Could not open file '+ file+' : status '+status)}else{var bytes=[] for(var codePoint of this.response){var cp=codePoint.codePointAt(0) if(cp > 0xf700){cp-=0xf700} bytes[bytes.length]=cp} result.content=_b_.bytes.$factory(bytes) if(! is_binary){ try{result.content=_b_.bytes.decode(result.content,encoding)}catch(error){result.error=error}}}} var cache=$B.get_option('cache'),fake_qs=cache ? '' :'?foo='+(new Date().getTime()) req.open('GET',encodeURI(file+fake_qs),false) req.send()}else{$B.RAISE(_b_.FileNotFoundError,"cannot use 'open()' with protocol 'file'")} if(result.error !==undefined){throw result.error} if(! is_binary){return $B.TextIOWrapper.$factory()} var res={$binary:is_binary,$content:result.content,$counter:0,$encoding:encoding,$length:is_binary ? result.content.source.length : result.content.length,closed:False,mode,name:file} res.__class__=is_binary ? $BufferedReader :$TextIOWrapper return res}else{$B.RAISE(_b_.TypeError,"invalid argument for open(): "+ _b_.str.$factory(file))}} _b_.open=function(){var $=$B.args('open',3,{file:null,mode:null,buffering:null,encoding:null,errors:null,newline:null,closefd:null,opener:null},['file','mode','buffering','encoding','errors','newline','closefd','opener'],arguments,{mode:'r',buffering:-1,encoding:_b_.None,errors:_b_.None,newline:_b_.None,closefd:true,opener:_b_.None}),file=$.file,mode=$.mode,encoding=$.encoding,result={} return _io_open_impl($.file,$.mode,$.buffering,$.encoding,$.errors,$.newline,$.closefd,$.opener)}})(__BRYTHON__) ; (function($B){var _b_=$B.builtins _b_.__debug__=false $B.$comps={'>':'gt','>=':'ge','<':'lt','<=':'le'} $B.$inv_comps={'>':'lt','>=':'le','<':'gt','<=':'ge'} var check_nb_args=$B.check_nb_args,check_no_kw=$B.check_no_kw,check_nb_args_no_kw=$B.check_nb_args_no_kw var NoneType=$B.NoneType={$factory:function(){return None},__bool__:function(){return False},__class__:_b_.type,__hash__:function(){return 0},__module__:'builtins',__mro__:[_b_.object],__name__:'NoneType',__qualname__:'NoneType',__repr__:function(){return 'None'},__str__:function(){return 'None'},$is_class:true} NoneType.__setattr__=function(self,attr){return no_set_attr(NoneType,attr)} var None=_b_.None={__class__:NoneType} None.__doc__=None NoneType.__doc__=None for(var $op in $B.$comps){ var key=$B.$comps[$op] switch(key){case 'ge': case 'gt': case 'le': case 'lt': NoneType['__'+key+'__']=(function(){return function(){return _b_.NotImplemented}})($op)}} for(var $func in None){if(typeof None[$func]=='function'){None[$func].__str__=(function(f){return function(){return ""}})($func)}} $B.set_func_names(NoneType,"builtins") _b_.__build_class__=function(){$B.RAISE(_b_.NotImplementedError,'__build_class__')} _b_.abs=function(obj){check_nb_args_no_kw('abs',1,arguments) var klass=obj.__class__ ||$B.get_class(obj) try{var method=$B.$getattr(klass,"__abs__")}catch(err){if(err.__class__===_b_.AttributeError){$B.RAISE(_b_.TypeError,"Bad operand type for abs(): '"+ $B.class_name(obj)+"'")} throw err} return $B.$call(method)(obj)} _b_.aiter=function(async_iterable){return $B.$call($B.$getattr(async_iterable,'__aiter__'))()} _b_.all=function(obj){check_nb_args_no_kw('all',1,arguments) var iterable=iter(obj) while(1){try{var elt=next(iterable) if(!$B.$bool(elt)){return false}}catch(err){return true}}} _b_.anext=function(){var missing={},$=$B.args('anext',2,{async_iterator:null,_default:null},['async_iterator','_default'],arguments,{_default:missing},null,null) var awaitable=$B.$call($B.$getattr($.async_iterator,'__anext__'))() return awaitable.catch( function(err){if($B.is_exc(err,[_b_.StopAsyncIteration])){if($._default !==missing){return $._default}} throw err} )} _b_.any=function(obj){check_nb_args_no_kw('any',1,arguments) for(var elt of $B.make_js_iterator(obj)){if($B.$bool(elt)){return true}} return false} _b_.ascii=function(obj){check_nb_args_no_kw('ascii',1,arguments) var res=repr(obj),res1='',cp for(var i=0;i < res.length;i++){cp=res.charCodeAt(i) if(cp < 128){res1+=res.charAt(i)} else if(cp < 256){res1+='\\x'+cp.toString(16)} else{var s=cp.toString(16) if(s.length % 2==1){s="0"+s} res1+='\\u'+s}} return res1} function $builtin_base_convert_helper(obj,base){var prefix=""; switch(base){case 2: prefix='0b';break case 8: prefix='0o';break case 16: prefix='0x';break default: console.log('invalid base:'+base)} if(obj.__class__===$B.long_int){var res=prefix+obj.value.toString(base) return res} var value=$B.PyNumber_Index(obj) if(value===undefined){ $B.RAISE(_b_.TypeError,'Error, argument must be an integer or'+ ' contains an __index__ function')} if(value >=0){return prefix+value.toString(base)} return '-'+prefix+(-value).toString(base)} function bin_hex_oct(base,obj){ if($B.$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){$B.RAISE(_b_.TypeError,"'"+$B.class_name(obj)+ "' object cannot be interpreted as an integer")} throw err} var res=$B.$call(method)(obj) return $builtin_base_convert_helper(res,base)}} _b_.bin=function(obj){check_nb_args_no_kw('bin',1,arguments) return bin_hex_oct(2,obj)} _b_.breakpoint=function(){ $B.$import('sys',[]) var missing={},hook=$B.$getattr($B.imported.sys,'breakpointhook',missing) if(hook===missing){$B.RAISE(_b_.RuntimeError,'lost sys.breakpointhook')} return $B.$call(hook).apply(null,arguments)} _b_.callable=function(obj){check_nb_args_no_kw('callable',1,arguments) return _b_.hasattr(obj,'__call__')} _b_.chr=function(i){check_nb_args_no_kw('chr',1,arguments) i=$B.PyNumber_Index(i) if(i < 0 ||i > 1114111){$B.RAISE(_b_.ValueError,'Outside valid range')}else if(i >=0x10000 && i <=0x10FFFF){var code=(i-0x10000),s=String.fromCodePoint(0xD800 |(code >> 10))+ String.fromCodePoint(0xDC00 |(code & 0x3FF)) return $B.make_String(s,[0])}else{return String.fromCodePoint(i)}} var code=_b_.code=$B.make_class("code") code.__repr__=code.__str__=function(_self){return ``} code.replace=function(){var $=$B.args('replace',1,{self:null},['self'],arguments,{},null,'kw') var _self=$.self var expected=['co_argcount','co_branches','co_cellvars','co_code','co_consts','co_exceptiontable','co_filename','co_firstlineno','co_flags','co_freevars','co_kwonlyargcount','co_lines','co_linetable','co_lnotab','co_name','co_names','co_nlocals','co_positions','co_posonlyargcount','co_qualname','co_stacksize','co_varnames'] $B.set_expected_kwargs(_self,expected,$.kw) return _self} $B.set_func_names(code,"builtins") _b_.compile=function(){var $=$B.args('compile',7,{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) var module_name='$exec_'+$B.UUID() $.__class__=code $.co_flags=$.flags $.co_name="" var filename=$.co_filename=$.filename var interactive=$.mode=="single" &&($.flags & 0x200) $B.file_cache[filename]=$.source $B.url2name[filename]=module_name if($.flags & $B.PyCF_TYPE_COMMENTS){} if($B.$isinstance($.source,_b_.bytes)){var encoding='utf-8',lfpos=$.source.source.indexOf(10),first_line,second_line if(lfpos==-1){first_line=$.source}else{first_line=_b_.bytes.$factory($.source.source.slice(0,lfpos))} first_line=_b_.bytes.decode(first_line,'latin-1') var encoding_re=/^[\t\f]*#.*?coding[:=][\t]*([-_.a-zA-Z0-9]+)/ var mo=first_line.match(encoding_re) if(mo){encoding=mo[1]}else if(lfpos >-1){ var rest=$.source.source.slice(lfpos+1) lfpos=rest.indexOf(10) if(lfpos >-1){second_line=_b_.bytes.$factory(rest.slice(0,lfpos))}else{second_line=_b_.bytes.$factory(rest)} second_line=_b_.bytes.decode(second_line,'latin-1') mo=second_line.match(encoding_re) if(mo){encoding=mo[1]}} $.source=_b_.bytes.decode($.source,encoding)} if(! $B.$isinstance(filename,[_b_.bytes,_b_.str])){ $B.warn(_b_.DeprecationWarning,`path should be string, bytes, or os.PathLike, `+ `not ${$B.class_name(filename)}`)} if(interactive && ! $.source.endsWith("\n")){ var lines=$.source.split("\n"),last_line=$B.last(lines) if(last_line.startsWith(" ")){var msg="unexpected EOF while parsing",exc=$B.EXC(_b_.SyntaxError) exc.filename=filename exc.lineno=exc.end_lineno=lines.length-1 exc.offset=0 exc.end_offset=last_line.length-1 exc.text=last_line exc.args=[msg,$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset])] throw exc}} if($.source.__class__ && $.source.__class__.__module__=='ast'){ $B.imported._ast._validate($.source) $._ast=$.source delete $.source return $} var _ast,parser try{var parser_mode=$.mode=='eval' ? 'eval' :'file' parser=new $B.Parser($.source,filename,parser_mode) parser.flags=$.flags _ast=$B._PyPegen.run_parser(parser)}catch(err){if($.mode=='single'){var tester=parser.tokens[parser.tokens.length-2] if(tester &&( (tester.type=="NEWLINE" &&($.flags & $B.PyCF_ALLOW_INCOMPLETE_INPUT))|| (tester.type=="DEDENT" &&($.flags & 0x200)))){err.__class__=_b_._IncompleteInputError err.args[0]='incomplete input'}} throw err} if($.mode=='single' && _ast.body.length==1 && _ast.body[0]instanceof $B.ast.Expr){ parser=new $B.Parser($.source,filename,'eval') _ast=$B._PyPegen.run_parser(parser) $.single_expression=true} if($.flags==$B.PyCF_ONLY_AST){delete $B.url2name[filename] let res=$B.ast_js_to_py(_ast) res.$js_ast=_ast return res} delete $B.url2name[filename] $._ast=$B.ast_js_to_py(_ast) $._ast.$js_ast=_ast var future=$B.future_features(_ast,filename) var symtable=$B._PySymtable_Build(_ast,filename,future) $B.js_from_root({ast:_ast,symtable,filename,src:$.source}) return $} _b_.debug=$B.debug > 0 _b_.delattr=function(obj,attr){ check_nb_args_no_kw('delattr',2,arguments) if(typeof attr !='string'){$B.RAISE(_b_.TypeError,"attribute name must be string, not '"+ $B.class_name(attr)+"'")} var deleter=$B.search_in_mro($B.get_class(obj),'__delattr__') if(deleter){return deleter(obj,attr)} return _b_.object.__delattr__(obj,attr)} $B.$delattr=function(obj,attr,inum){try{_b_.delattr(obj,attr)}catch(err){$B.set_inum(inum) throw err}} $B.$delete=function(name,locals_id,inum){ function del(obj){if(obj.__class__===$B.generator){ obj.js_gen.return()} var del_method=$B.search_in_mro($B.get_class(obj),'__del__') if(del_method){del_method(obj)}} var found=false if(locals_id=='local'){var frame=$B.frame_obj.frame if(frame[1].hasOwnProperty(name)){found=true del(frame[1][name]) delete frame[1][name]}}else if(locals_id=='global'){var frame=$B.frame_obj.frame if(frame[3].hasOwnProperty(name)){found=true del(frame[3][name]) delete frame[3][name]}}else if(locals_id !==null && locals_id[name]!==undefined){found=true del(locals_id[name]) delete locals_id[name]} if(! found){$B.set_inum(inum) if(locals_id=='local'){$B.RAISE(_b_.UnboundLocalError,`cannot access local variable '${name}' `+ 'where it is not associated with a value')}else{throw $B.name_error(name)}}} _b_.dir=function(obj){if(obj===undefined){ var locals=_b_.locals() return _b_.sorted(locals)} check_nb_args_no_kw('dir',1,arguments) var klass=obj.__class__ ||$B.get_class(obj) if(obj.$is_class){ var dir_func=$B.$getattr(obj.__class__,"__dir__") return $B.$call(dir_func)(obj)} try{let res=$B.$call($B.$getattr(klass,'__dir__'))(obj) res=_b_.list.$factory(res) return res}catch(err){ if($B.get_option('debug')> 2){console.log('error in dir, obj',obj,'klass',klass,$B.$getattr(klass,'__dir__'),err.message)} throw err}} _b_.divmod=function(x,y){check_nb_args_no_kw('divmod',2,arguments) try{return $B.rich_op('__divmod__',x,y)}catch(err){if($B.is_exc(err,[_b_.TypeError])){return _b_.tuple.$factory([$B.rich_op('__floordiv__',x,y),$B.rich_op('__mod__',x,y)])} throw err}} var enumerate=_b_.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"] return{ __class__:enumerate,__name__:'enumerate iterator',counter:start-1,iter:_iter,start:start}} ) enumerate.__class_getitem__=$B.$class_getitem enumerate.__iter__=function(self){self.counter=self.start-1 return self} enumerate.__next__=function(self){self.counter++ return $B.fast_tuple([self.counter,next(self.iter)])} $B.set_func_names(enumerate,"builtins") $B.LOCALS_PROXY=Symbol('locals_proxy') enumerate.__class_getitem__=_b_.classmethod.$factory(enumerate.__class_getitem__) var $$eval=_b_.eval=function(){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,4),src=$.src,_globals=$.globals,_locals=$.locals,mode=$.mode if($.src.mode && $.src.mode=="single" && ["",""].indexOf($.src.filename)>-1){ _b_.print(">",$.src.source.trim())} var filename='' if(src.__class__===code){filename=src.filename}else if((! src.valueOf)||typeof src.valueOf()!=='string'){$B.RAISE(_b_.TypeError,`${mode}() arg 1 must be a string,`+ " bytes or code object")}else{ src=src.valueOf() src=src.replace(/\r\n/g,'\n'). replace(/\r/g,'\n')} var __name__='exec' if(_globals===_b_.None){if($B.frame_obj !==null){__name__=$B.frame_obj.frame[2]}} if(_globals !==_b_.None && _globals.__class__==_b_.dict && _b_.dict.$contains_string(_globals,'__name__')){__name__=_b_.dict.$getitem_string(_globals,'__name__')} $B.url2name[filename]=__name__ var frame=$B.frame_obj.frame $B.exec_scope=$B.exec_scope ||{} if(typeof src=='string' && src.endsWith('\\\n')){var exc=$B.EXC(_b_.SyntaxError,'unexpected EOF while parsing') var lines=src.split('\n'),line=lines[lines.length-2] exc.args=['unexpected EOF while parsing',[filename,lines.length-1,1,line]] exc.filename=filename exc.text=line throw exc} var local_name=('locals_'+__name__).replace(/\./g,'_'),global_name=('globals_'+__name__).replace(/\./g,'_'),exec_locals={},exec_globals={} if(_globals===_b_.None){ if(frame[1]===frame[3]){ global_name+='_globals' exec_locals=exec_globals=frame[3]}else{if(mode=="exec"){ exec_locals=$B.clone(frame[1]) for(var attr in frame[3]){exec_locals[attr]=frame[3][attr]} exec_globals=exec_locals}else{ exec_locals=frame[1] exec_globals=frame[3]}}}else{if(_globals.__class__ !==_b_.dict){$B.RAISE(_b_.TypeError,`${mode}() globals must be `+ "a dict, not "+$B.class_name(_globals))} exec_globals={} if(_globals.$jsobj){ exec_globals=_globals.$jsobj}else{ exec_globals=_globals.$jsobj={} for(var key of _b_.dict.$keys_string(_globals)){_globals.$jsobj[key]=_b_.dict.$getitem_string(_globals,key) if(key=='__name__'){__name__=_globals.$jsobj[key]}} _globals.$all_str=false} if(exec_globals.__builtins__===undefined){exec_globals.__builtins__=_b_.__builtins__} if(_locals===_b_.None){exec_locals=exec_globals}else{if(_locals===_globals){ global_name+='_globals' exec_locals=exec_globals}else if(_locals.$jsobj){for(let key in _locals.$jsobj){exec_globals[key]=_locals.$jsobj[key]}}else{if(_locals.$jsobj){exec_locals=_locals.$jsobj}else{var klass=$B.get_class(_locals),getitem=$B.$call($B.$getattr(klass,'__getitem__')),setitem=$B.$call($B.$getattr(klass,'__setitem__')) exec_locals=new Proxy(_locals,{get(target,prop){if(prop=='$target'){return target}else if(prop==$B.LOCALS_PROXY){return true} try{return getitem(target,prop)}catch(err){return undefined}},set(target,prop,value){return setitem(target,prop,value)}})}}}} var save_frame_obj=$B.frame_obj var _ast frame=[__name__,exec_locals,__name__,exec_globals] frame.is_exec_top=true $B.enter_frame(frame,filename,1) var _frame_obj=$B.frame_obj if(src.__class__===code){if(src.mode=='exec' && mode=='eval'){return _b_.None} _ast=src._ast if(_ast.$js_ast){_ast=_ast.$js_ast}else{_ast=$B.ast_py_to_js(_ast)} if(_ast instanceof $B.ast.Expression){ var expr_name='_'+$B.UUID() var name=new $B.ast.Name(expr_name,new $B.ast.Store()) $B.copy_position(name,_ast.body) var assign=new $B.ast.Assign([name],_ast.body) $B.copy_position(assign,_ast.body) _ast=new $B.ast.Module([assign])}} try{if(! _ast){var _mode=mode=='eval' ? 'eval' :'file' var parser=new $B.Parser(src,filename,_mode) _ast=$B._PyPegen.run_parser(parser)} var future=$B.future_features(_ast,filename),symtable=$B._PySymtable_Build(_ast,filename,future),js_obj=$B.js_from_root({ast:_ast,symtable,filename,src,namespaces:{local_name,exec_locals,global_name,exec_globals}}),js=js_obj.js}catch(err){if(err.args){if(err.args[1]){exec_locals.$lineno=err.args[1][1]}}else{console.log('JS Error',err.message)} $B.frame_obj=save_frame_obj throw err} if(mode=='eval'){ if(src.__class__===_b_.code){js+=`\nreturn locals.${expr_name}`}else{js=`var __file__ = '${filename}'\n`+ `var locals = ${local_name};\n`+ 'return '+js}}else if(src.single_expression){if(src.__class__===_b_.code){js+=`var result = locals.${expr_name}\n`+ `if(result !== _b_.None){\n`+ `_b_.print(result)\n`+ `}`}else{js=`var __file__ = '${filename}'\n`+ `var result = ${js}\n`+ `if(result !== _b_.None){\n`+ `_b_.print(result)\n`+ `}`}} try{var exec_func=new Function('$B','_b_','locals',local_name,global_name,'frame','_frame_obj',js)}catch(err){if($B.get_option('debug')> 1){console.log('eval() error\n',$B.format_indent(js,0)) console.log('-- python source\n',src)} $B.frame_obj=save_frame_obj throw err} try{var res=exec_func($B,_b_,exec_locals,exec_locals,exec_globals,frame,_frame_obj)}catch(err){if($B.get_option('debug')> 2){console.log( 'Python code\n',src,'\nexec func',$B.format_indent(exec_func+'',0),'\n filename',filename,'\n name from filename',$B.url2name[filename],'\n local_name',local_name,'\n exec_locals',exec_locals,'\n global_name',global_name,'\n exec_globals',exec_globals,'\n frame',frame,'\n _ast',_ast,'\n js',js,'\n err',err.__class__,err.args,err.$frame_obj)} $B.set_exc(err,frame) $B.frame_obj=save_frame_obj throw err} if(_globals !==_b_.None && ! _globals.$jsobj){for(var _key in exec_globals){if(! _key.startsWith('$')){_b_.dict.$setitem(_globals,_key,exec_globals[_key])}}} $B.frame_obj=save_frame_obj return res} $$eval.$is_func=true var exec=_b_.exec=function(){var $=$B.args("exec",3,{src:null,globals:null,locals:null},["src","globals","locals"],arguments,{globals:_b_.None,locals:_b_.None},null,null,1),src=$.src,globals=$.globals,locals=$.locals $$eval(src,globals,locals,"exec") return _b_.None} exec.$is_func=true var exit=_b_.exit=function(){throw _b_.SystemExit} exit.__repr__=exit.__str__=function(){return "Use exit() or Ctrl-Z plus Return to exit"} var filter=_b_.filter=$B.make_class("filter",function(func,iterable){check_nb_args_no_kw('filter',2,arguments) iterable=iter(iterable) if(func===_b_.None){func=$B.$bool} return{ __class__:filter,func:func,iterable:iterable}} ) filter.__iter__=function(self){return self} filter.__next__=function(self){while(true){var _item=next(self.iterable) if(self.func(_item)){return _item}}} $B.set_func_names(filter,"builtins") _b_.format=function(){var $=$B.args("format",2,{value:null,format_spec:null},["value","format_spec"],arguments,{format_spec:''},null,null),value=$.value var klass=value.__class__ ||$B.get_class(value) try{var method=$B.$getattr(klass,'__format__')}catch(err){if(err.__class__===_b_.AttributeError){$B.RAISE(_b_.NotImplementedError,"__format__ is not implemented "+ "for object '"+_b_.str.$factory(value)+"'")} throw err} return $B.$call(method)(value,$.format_spec)} function attr_error(attr,obj){var cname=$B.get_class(obj) var msg="bad operand type for unary #: '"+cname+"'" switch(attr){case '__neg__': $B.RAISE(_b_.TypeError,msg.replace('#','-')) case '__pos__': $B.RAISE(_b_.TypeError,msg.replace('#','+')) case '__invert__': $B.RAISE(_b_.TypeError,msg.replace('#','~')) case '__call__': $B.RAISE(_b_.TypeError,"'"+cname+"'"+ ' object is not callable') default: throw $B.attr_error(attr,obj)}} _b_.getattr=function(){var missing={} var $=$B.args("getattr",3,{obj:null,attr:null,_default:null},["obj","attr","_default"],arguments,{_default:missing},null,null) if(! $B.$isinstance($.attr,_b_.str)){$B.RAISE(_b_.TypeError,"attribute name must be string, "+ `not '${$B.class_name($.attr)}'`)} return $B.$getattr($.obj,_b_.str.$to_string($.attr),$._default===missing ? undefined :$._default)} $B.search_in_mro=function(klass,attr){var test=false if(test){console.log('search',attr,'in mro of',klass)} if(klass.hasOwnProperty(attr)){if(test){console.log('found in klass',klass[attr])} return klass[attr]}else if(klass.__dict__){var v=_b_.dict.$get_string(klass.__dict__,attr,false) if(v !==false){if(test){console.log('found in klass dict',klass.__dict__,v)} return v}} var mro=klass.__mro__ for(var i=0,len=mro.length;i < len;i++){if(mro[i].hasOwnProperty(attr)){if(test){console.log('found in mro',i,mro[i])} return mro[i][attr]}else if(mro[i].__dict__){var v=_b_.dict.$get_string(mro[i].__dict__,attr,false) if(v !==false){if(test){console.log('found in dict of mro',i,v)} return v}}}} $B.call_with_mro=function(obj,attr){var args=Array.from(arguments).slice(2) var obj_class=$B.get_class(obj) var in_mro=$B.search_in_mro(obj_class,attr) if(in_mro===undefined){$B.RAISE(_b_.AttributeError,`no attribute ${attr}`)} var getter=$B.search_in_mro($B.get_class(in_mro),'__get__') if(getter){return $B.$call(getter(in_mro,obj,obj_class))(...args)}else{if(typeof in_mro !=='function'){var call_in_mro=$B.search_in_mro($B.get_class(in_mro),'__call__') if(call_in_mro){return call_in_mro(in_mro,...args)}else{$B.RAISE(_b_.TypeError,`not callable {op}`)}}else{return in_mro(obj,...args)}}} $B.$getattr=function(obj,attr,_default){ var res if(obj===undefined ||obj===null){$B.RAISE_ATTRIBUTE_ERROR("Javascript object '"+obj+ "' has no attribute",obj,attr)} if(obj.$method_cache && obj.$method_cache[attr]&& obj.__class__ && obj.__class__[attr]==obj.$method_cache[attr][1]){ return obj.$method_cache[attr][0]} var rawname=attr if(obj===undefined){console.log("get attr",attr,"of undefined")} var is_class=obj.$is_class ||obj.$factory var klass=obj.__class__ var $test=false if($test){console.log("attr",attr,"of",obj,"class",klass ?? $B.get_class(obj),"isclass",is_class)} if(klass===undefined){klass=$B.get_class(obj) if(klass===undefined){ if($test){console.log("no class",attr,obj.hasOwnProperty(attr),obj[attr])} res=obj[attr] if(res !==undefined){if(typeof res=="function"){var f=function(){ return res.apply(obj,arguments)} f.$infos={__name__:attr,__qualname__:attr} $B.set_function_infos(f,{name:attr,qualname:attr} ) return f}else{return $B.jsobj2pyobj(res)}} if(_default !==undefined){return _default} throw $B.attr_error(rawname,obj)}} switch(attr){case '__call__': if(typeof obj=='function'){res=function(){return obj.apply(null,arguments)} res.__class__=method_wrapper res.$infos={__name__:"__call__"} return res} break case '__class__': if(klass.__dict__){var klass_from_dict=_b_.None if($B.$isinstance(klass.__dict__,_b_.dict)){klass_from_dict=$B.$call($B.$getattr(klass.__dict__,'get'))('__class__')} if(klass_from_dict !==_b_.None){if(klass_from_dict.$is_property){return klass_from_dict.fget(obj)} return klass_from_dict}} return klass case '__dict__': if(is_class){var dict={},key if(obj.__dict__){for(key of _b_.dict.$keys_string(obj.__dict__)){dict[key]=_b_.dict.$getitem_string(obj.__dict__,key) if(key=='__new__' && dict[key].__class__ !==_b_.staticmethod){dict[key]=_b_.staticmethod.$factory(dict[key])}}}else{for(key in obj){if(! key.startsWith("$")){dict[key]=obj[key] if(key=='__new__' && dict[key].__class__ !==_b_.staticmethod){dict[key]=_b_.staticmethod.$factory(dict[key])}}}} dict.__dict__=$B.getset_descriptor.$factory(obj,'__dict__',function(klass){ if(klass.__dict__ !==undefined){return klass.__dict__} if(klass.$tp_dict){return $B.obj_dict(klass.$tp_dict)} return $B.empty_dict()} ) return{ __class__:$B.mappingproxy, $jsobj:dict,$version:0}}else if(! klass.$native){if(obj[attr]!==undefined){return obj[attr]}else if(obj.__dict__){return obj.__dict__}else if(obj.$function_infos ||obj.$infos){if(! obj.$infos){$B.make_function_infos(obj,...obj.$function_infos)} if(obj.hasOwnProperty("__dict__")){return obj.__dict__}else if(obj.$infos.hasOwnProperty("__func__")&& obj.$infos.__func__){obj.$infos.__func__.__dict__=obj.$infos.__func__.__dict__ ?? $B.empty_dict()}}else if(obj.__class__ && obj.__class__.__dict__){}else if(! obj.__class__){} return $B.obj_dict(obj,function(attr){return attr.startsWith('$')||['__class__'].indexOf(attr)>-1} )} break case '__mro__': if(obj.__mro__){return _b_.tuple.$factory([obj].concat(obj.__mro__))}else if(obj.__dict__ && _b_.dict.$contains_string(obj.__dict__,'__mro__')){return _b_.dict.$getitem_string(obj.__dict__,'__mro__')} throw $B.attr_error(attr,obj) case '__subclasses__': if(klass.$factory ||klass.$is_class){var subclasses=obj.$subclasses ||[] return function(){return $B.$list(subclasses)}} break} if(typeof obj=='function'){var value=obj[attr] if(value !==undefined){if(attr=='__module__'){return value}}} if((! is_class)&& klass.$native){if(obj.$method_cache && obj.$method_cache[attr]){return obj.$method_cache[attr]} if($test){console.log("native class",klass,klass[attr])} if(klass[attr]===undefined){var parent_attr for(var parent_class of klass.__mro__){if(parent_class[attr]!==undefined){parent_attr=parent_class[attr] break}} if($test){console.log("parent class attr",parent_attr)} if(parent_attr !==undefined){klass[attr]=parent_attr}else{if($test){console.log("obj[attr]",obj[attr])} var attrs=obj.__dict__ if(attrs && _b_.dict.$contains_string(attrs,attr)){return _b_.dict.$getitem_string(attrs,attr)} if(_default===undefined){throw $B.attr_error(attr,obj)} return _default}}else if(['__name__','__qualname__'].includes(attr)){attr_error(attr,obj)} if(klass.$descriptors && klass.$descriptors[attr]!==undefined){return klass[attr](obj)} if(typeof klass[attr]=='function'){var func=klass[attr] if(attr=='__new__'){func.$type="staticmethod"} if(func.$type=="staticmethod"){return func} var self=klass[attr].__class__==$B.method ? klass :obj,method=klass[attr].bind(null,self) method.__class__=$B.method method.$infos={__func__:func,__name__:attr,__self__:self,__qualname__:klass.__qualname__+"."+attr} if(typeof obj=="object"){ obj.__class__=klass obj.$method_cache=obj.$method_cache ||{} if(obj.$method_cache){ obj.$method_cache[attr]=method}} return method}else if(klass[attr].__class__===_b_.classmethod){return _b_.classmethod.__get__(klass[attr],obj,klass)}else if(klass[attr]!==undefined){return klass[attr]} attr_error(rawname,klass)} var attr_func if(is_class){if($test){console.log('obj is class',obj) console.log('is a type ?',_b_.isinstance(klass,_b_.type)) console.log('is type',klass===_b_.type)} if(klass===_b_.type){attr_func=_b_.type.__getattribute__}else{attr_func=$B.$call($B.$getattr(klass,'__getattribute__'))} if($test){console.log('attr func',attr_func)}}else{attr_func=klass.__getattribute__ if(attr_func===undefined){for(var cls of klass.__mro__){attr_func=cls['__getattribute__'] if(attr_func !==undefined){break}}} if($test){console.log('attr func',attr_func)}} if(typeof attr_func !=='function'){console.log(attr+' is not a function '+attr_func,klass)} var odga=_b_.object.__getattribute__ if($test){console.log("attr_func is odga ?",attr_func,attr_func===odga,'\n','\nobj[attr]',obj[attr])} if(attr_func===odga){res=obj[attr] if(Array.isArray(obj)&& Array.prototype[attr]!==undefined){ res=undefined}else if(res===null){return null}else if(res !==undefined){if($test){console.log(obj,attr,obj[attr],res.__set__ ||res.$is_class)} if(res.$is_property){return _b_.property.__get__(res)} if(res.__set__===undefined ||res.$is_class){if($test){console.log("return",res,res+'',res.__set__,res.$is_class)} return res}}} var getattr try{res=attr_func(obj,attr) if($test){console.log("result of attr_func",res)}}catch(err){if($test){console.log('attr',attr,'of',obj) console.log('attr_func raised error',err.__class__,err.args,err.name) console.log(err) console.log(Error().stack)} if(klass===$B.module){ getattr=obj.__getattr__ if($test){console.log('use module getattr',getattr) console.log(getattr+'')} if(getattr){try{return getattr(attr)}catch(err){if($test){console.log('encore erreur',err)} if(_default !==undefined){return _default} throw err}}} getattr=$B.search_in_mro(klass,'__getattr__') if($test){console.log('try getattr',getattr)} if(getattr){if($test){console.log('try with getattr',getattr)} try{return getattr(obj,attr)}catch(err){if($B.is_exc(err,[_b_.AttributeError])){if(_default !==undefined){return _default}} throw err}} if(_default !==undefined){return _default} throw err} if(res !==undefined){return res} if(_default !==undefined){return _default} attr_error(rawname,is_class ? obj :klass)} _b_.globals=function(){ check_nb_args_no_kw('globals',0,arguments) var res=$B.obj_dict($B.frame_obj.frame[3]) res.$jsobj.__BRYTHON__=$B.jsobj2pyobj($B) res.$is_namespace=true return res} _b_.hasattr=function(obj,attr){check_nb_args_no_kw('hasattr',2,arguments) try{$B.$getattr(obj,attr) return true}catch(err){return false}} _b_.hash=function(obj){check_nb_args_no_kw('hash',1,arguments) return $B.$hash(obj)} $B.$hash=function(obj){if(obj.__hashvalue__ !==undefined){return obj.__hashvalue__} if(typeof obj==="boolean"){return obj ? 1 :0} if(obj.$is_class || obj.__class__===_b_.type || obj.__class__===$B.function){return obj.__hashvalue__=$B.$py_next_hash--} if(typeof obj=="string"){return _b_.str.__hash__(obj)}else if(typeof obj=="number"){return obj}else if(typeof obj=="boolean"){return obj ? 1 :0}else if(obj.__class__===_b_.float){return _b_.float.$hash_func(obj)} var klass=obj.__class__ ||$B.get_class(obj) if(klass===undefined){$B.RAISE(_b_.TypeError,"unhashable type: '"+ _b_.str.$factory($B.jsobj2pyobj(obj))+"'")} var hash_method=_b_.type.__getattribute__(klass,'__hash__',_b_.None) if(hash_method===_b_.None){$B.RAISE(_b_.TypeError,"unhashable type: '"+ $B.class_name(obj)+"'")} function check_int(v){if((! Number.isInteger(v))&& ! $B.$isinstance(v,_b_.int)){$B.RAISE(_b_.TypeError,'__hash__ method should return an integer')} return v} var res if(hash_method===_b_.object.__hash__){if(_b_.type.__getattribute__(klass,'__eq__')!==_b_.object.__eq__){$B.RAISE(_b_.TypeError,"unhashable type: '"+ $B.class_name(obj)+"'",'hash')}else{return obj.__hashvalue__=check_int(_b_.object.__hash__(obj))}}else{return check_int($B.$call(hash_method)(obj))}} var help=_b_.help=function(obj){if(obj===undefined){obj='help'} if(typeof obj=='string'){var lib_url='https://docs.python.org/3/library' var parts=obj.split('.'),head=[],url while(parts.length > 0){head.push(parts.shift()) if($B.stdlib[head.join('.')]){url=head.join('.')}else{break}} if(url){var doc_url if(['browser','javascript','interpreter']. indexOf(obj.split('.')[0])>-1){doc_url='/static_doc/'+($B.language=='fr' ? 'fr' :'en')}else{doc_url=lib_url} window.open(`${doc_url}/${url}.html#`+obj) return} if(_b_[obj]){if(obj==obj.toLowerCase()){url=lib_url+`/functions.html#${obj}`}else if(['False','True','None','NotImplemented','Ellipsis','__debug__']. indexOf(obj)>-1){url=lib_url+`/constants.html#${obj}`}else if(_b_[obj].$is_class && _b_[obj].__bases__.indexOf(_b_.Exception)>-1){url=lib_url+`/exceptions.html#${obj}`} if(url){window.open(url) return}} $B.$import('pydoc') return $B.$call($B.$getattr($B.imported.pydoc,'help'))(obj)} if(obj.__class__===$B.module){return help(obj.__name__)} try{_b_.print($B.$getattr(obj,'__doc__'))}catch(err){return ''}} help.__repr__=help.__str__=function(){return "Type help() for interactive help, or help(object) "+ "for help about object."} _b_.hex=function(obj){check_nb_args_no_kw('hex',1,arguments) return bin_hex_oct(16,obj)} _b_.id=function(obj){check_nb_args_no_kw('id',1,arguments) if(obj.$id !==undefined){return obj.$id}else if($B.$isinstance(obj,[_b_.str,_b_.int,_b_.float])&& ! $B.$isinstance(obj,$B.long_int)){return $B.$getattr(_b_.str.$factory(obj),'__hash__')()}else{return obj.$id=$B.UUID()}} _b_.__import__=function(){ 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) return $B.$__import__($.name,$.globals,$.locals,$.fromlist)} _b_.input=function(msg){var res=prompt(msg ||'')||'' if($B.imported["sys"]&& $B.imported["sys"].ps1){ var ps1=$B.imported["sys"].ps1,ps2=$B.imported["sys"].ps2 if(msg==ps1 ||msg==ps2){console.log(msg,res)}} return res} _b_.isinstance=function(obj,cls){check_nb_args_no_kw('isinstance',2,arguments) return $B.$isinstance(obj,cls)} $B.$isinstance=function(obj,cls){if(obj===null){return cls===$B.imported.javascript.NullType} if(obj===undefined){return false} var kls if(Array.isArray(cls)){for(kls of cls){if($B.$isinstance(obj,kls)){return true}} return false} if(cls.__class__===$B.UnionType){for(kls of cls.items){if($B.$isinstance(obj,kls)){return true}} return false} if(cls.__class__===$B.GenericAlias){ $B.RAISE(_b_.TypeError,'isinstance() arg 2 cannot be a parameterized generic')} if((!cls.__class__)&&(! cls.$is_class)){if(! $B.$getattr(cls,'__instancecheck__',false)){$B.RAISE(_b_.TypeError,"isinstance() arg 2 must be a type "+ "or tuple of types")}} if(cls===_b_.int &&(obj===True ||obj===False)){return true} if(cls===_b_.bool){switch(typeof obj){case "string": return false case "number": return false case "boolean": return true}} var klass=obj.__class__ if(klass==undefined){if(typeof obj=='string'){if(cls==_b_.str){return true}else if($B.builtin_classes.includes(cls)){return false}}else if(typeof obj=='number' && Number.isFinite(obj)){if(Number.isFinite(obj)&& cls==_b_.int){return true}} klass=$B.get_class(obj)} if(klass===undefined){return false} if(klass===cls){return true} var mro=klass.__mro__ for(var i=0;i < mro.length;i++){if(mro[i]===cls){return true}} var instancecheck=$B.$getattr(cls.__class__ ||$B.get_class(cls),'__instancecheck__',_b_.None) if(cls.__name__=='DemoComponent2169'){console.log('use instance check',obj,cls,instancecheck) console.log('class of obj',$B.get_class(obj)) console.log('same as cls ?',$B.get_class(obj)===cls) console.log('result',instancecheck(cls,obj))} if(instancecheck !==_b_.None){return instancecheck(cls,obj)} return false} var issubclass=_b_.issubclass=function(klass,classinfo){check_nb_args_no_kw('issubclass',2,arguments) var mro if(!klass.__class__ || !(klass.$factory !==undefined ||klass.$is_class !==undefined)){var meta=$B.$getattr(klass,'__class__',null) if(meta===null){console.log('no class for',klass) $B.RAISE(_b_.TypeError,"issubclass() arg 1 must be a class")}else{mro=[_b_.object]}}else{mro=klass.__mro__} if($B.$isinstance(classinfo,_b_.tuple)){for(var i=0;i < classinfo.length;i++){if(issubclass(klass,classinfo[i])){return true}} return false} if(classinfo.__class__===$B.GenericAlias){$B.RAISE(_b_.TypeError,'issubclass() arg 2 cannot be a parameterized generic')} if(klass===classinfo ||mro.indexOf(classinfo)>-1){return true} var sch=$B.$getattr(classinfo.__class__ ||$B.get_class(classinfo),'__subclasscheck__',_b_.None) if(sch==_b_.None){return false} return sch(classinfo,klass)} var iterator_class=$B.make_class("iterator",function(getitem){return{ __class__:iterator_class,getitem:getitem,counter:-1}} ) iterator_class.__next__=function(self){self.counter++ try{return self.getitem(self.counter)}catch(err){$B.RAISE(_b_.StopIteration,'')}} $B.set_func_names(iterator_class,"builtins") const callable_iterator=$B.make_class("callable_iterator",function(func,sentinel){return{ __class__:callable_iterator,func:func,sentinel:sentinel}} ) callable_iterator.__iter__=function(self){return self} callable_iterator.__next__=function(self){var res=self.func() if($B.rich_comp("__eq__",res,self.sentinel)){$B.RAISE(_b_.StopIteration,)} return res} $B.set_func_names(callable_iterator,"builtins") $B.$iter=function(obj,sentinel){ var test=false if(test){console.log('iter',obj)} if(sentinel===undefined){var klass=obj.__class__ ||$B.get_class(obj) var in_mro=$B.search_in_mro(klass,'__iter__') if(in_mro){var getter=$B.search_in_mro($B.get_class(in_mro),'__get__') if(getter){if(obj.$is_class){in_mro=getter(in_mro,_b_.None,klass)}else{in_mro=getter(in_mro,obj,klass)}} var in_mro_klass=$B.get_class(in_mro) var call=$B.search_in_mro(in_mro_klass,'__call__') if(call){var iterator=call(in_mro) return iterator}} 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)},len return iterator_class.$factory(gi)}catch(err){$B.RAISE(_b_.TypeError,"'"+$B.class_name(obj)+ "' object is not iterable")}} throw err} var res=$B.$call(_iter)(obj) try{$B.$getattr(res,'__next__')}catch(err){if($B.$isinstance(err,_b_.AttributeError)){$B.RAISE(_b_.TypeError,"iter() returned non-iterator of type '"+ $B.class_name(res)+"'")}} return res}else{return callable_iterator.$factory(obj,sentinel)}} var iter=_b_.iter=function(){ var $=$B.args('iter',1,{obj:null},['obj'],arguments,{},'args','kw'),sentinel if($.args.length > 0){sentinel=$.args[0]} return $B.$iter($.obj,sentinel)} var len=_b_.len=function(obj){check_nb_args_no_kw('len',1,arguments) var klass=obj.__class__ ||$B.get_class(obj) try{var method=$B.$getattr(klass,'__len__')}catch(err){$B.RAISE(_b_.TypeError,"object of type '"+ $B.class_name(obj)+"' has no len()")} let res=$B.$call(method)(obj) if(!$B.$isinstance(res,_b_.int)){$B.RAISE(_b_.TypeError,`'${$B.class_name(res)}' object cannot be interpreted as an integer`)} if(!$B.rich_comp('__ge__',res,0)){$B.RAISE(_b_.ValueError,'ValueError: __len__() should return >= 0')} return res} _b_.locals=function(){ check_nb_args('locals',0,arguments) var locals_obj=$B.frame_obj.frame[1] var class_locals=locals_obj.$target if(class_locals){return class_locals} var res=$B.obj_dict($B.clone(locals_obj),function(key){return key.startsWith('$')} ) res.$is_namespace=true return res} var map=_b_.map=$B.make_class("map",function(){var $=$B.args('map',2,{func:null,it1:null},['func','it1'],arguments,{},'args',null),func=$B.$call($.func) var iter_args=[$B.make_js_iterator($.it1)] for(var arg of $.args){iter_args.push($B.make_js_iterator(arg))} return{ __class__:map,args:iter_args,func:func}} ) map.__iter__=function(self){return self} map.__next__=function(self){var args=[] for(var iter of self.args){var arg=iter.next() if(arg.done){$B.RAISE(_b_.StopIteration,'')} args.push(arg.value)} return self.func.apply(null,args)} $B.set_func_names(map,"builtins") function $extreme(args,op){ var $op_name='min' if(op==='__gt__'){$op_name="max"} var $=$B.args($op_name,0,{},[],args,{},'args','kw') var has_default=false,func=false for(var item of _b_.dict.$iter_items($.kw)){switch(item.key){case 'key': func=item.value func=func===_b_.None ? func :$B.$call(func) break case 'default': var default_value=item.value has_default=true break default: $B.RAISE(_b_.TypeError,"'"+item.key+ "' is an invalid keyword argument for this function")}} if((! func)||func===_b_.None){func=x=> x} if($.args.length==0){$B.RAISE(_b_.TypeError,$op_name+ " expected 1 arguments, got 0")}else if($.args.length==1){ var $iter=$B.make_js_iterator($.args[0]),res=null,x_value,extr_value for(var x of $iter){if(res===null){extr_value=func(x) res=x}else{x_value=func(x) if($B.rich_comp(op,x_value,extr_value)){res=x extr_value=x_value}}} if(res===null){if(has_default){return default_value}else{$B.RAISE(_b_.ValueError,$op_name+ "() arg is an empty sequence")}}else{return res}}else{if(has_default){$B.RAISE(_b_.TypeError,"Cannot specify a default for "+ $op_name+"() with multiple positional arguments")} var _args if($B.last(args).$kw){_args=[$.args].concat($B.last(args))}else{_args=[$.args]} return $extreme.call(null,_args,op)}} _b_.max=function(){return $extreme(arguments,'__gt__')} var memoryview=_b_.memoryview=$B.make_class('memoryview',function(obj){check_nb_args_no_kw('memoryview',1,arguments) if(obj.__class__===memoryview){return obj} if($B.get_class(obj).$buffer_protocol){obj.$exports=obj.$exports ?? 0 obj.$exports++ var res={__class__:memoryview,obj:obj,mbuf:null,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} return res}else{$B.RAISE(_b_.TypeError,"memoryview: a bytes-like object "+ "is required, not '"+$B.class_name(obj)+"'")}} ) memoryview.$match_sequence_pattern=true, memoryview.$buffer_protocol=true memoryview.$not_basetype=true memoryview.$is_sequence=true memoryview.$getbuffer=function(self){self.$exports++} memoryview.nbytes=$B.getset_descriptor.$factory( memoryview,'nbytes',function(_self){var product=1 for(var x of _self.shape){product*=x} return x*_self.itemsize} ) memoryview.__enter__=function(_self){return _self} memoryview.__exit__=function(_self){memoryview.release(_self)} memoryview.__del__=function(self){if(! self.$released){memoryview.release(self)}} memoryview.__eq__=function(self,other){if(other.__class__ !==memoryview){return false} return $B.$getattr(self.obj,'__eq__')(other.obj)} memoryview.__getitem__=function(self,key){var res if($B.$isinstance(key,_b_.int)){var start=key*self.itemsize if(self.format=="I"){res=self.obj.source[start] var coef=256 for(var i=1;i < 4;i++){res+=self.obj.source[start+i]*coef coef*=256} return res}else if("B".indexOf(self.format)>-1){if(key > self.obj.source.length-1){$B.RAISE(_b_.KeyError,key)} return self.obj.source[key]}else{ return self.obj.source[key]}} res=self.obj.__class__.__getitem__(self.obj,key) if(key.__class__===_b_.slice){return memoryview.$factory(res)}} memoryview.__len__=function(self){return len(self.obj)/self.itemsize} memoryview.__setitem__=function(self,key,value){try{$B.$setitem(self.obj,key,value)}catch(err){$B.RAISE(_b_.TypeError,"cannot modify read-only memory")}} var struct_format={'x':{'size':1},'b':{'size':1},'B':{'size':1},'c':{'size':1},'s':{'size':1},'p':{'size':1},'h':{'size':2},'H':{'size':2},'i':{'size':4},'I':{'size':4},'l':{'size':4},'L':{'size':4},'q':{'size':8},'Q':{'size':8},'f':{'size':4},'d':{'size':8},'P':{'size':8}} memoryview.cast=function(self,format,shape){if(! struct_format.hasOwnProperty(format)){$B.RAISE(_b_.ValueError,`unknown format: '${format}'`)} var new_itemsize=struct_format[format].size if(shape===undefined){shape=_b_.len(self)}else{if(! $B.$isinstance(shape,[_b_.list,_b_.tuple])){$B.RAISE(_b_.TypeError,'shape must be a list or a tuple')} var nb=1 for(var item of shape){if(! $B.$isinstance(item,_b_.int)){$B.RAISE(_b_.TypeError,'memoryview.cast(): elements of shape must be integers')} nb*=item} if(nb*new_itemsize !=_b_.len(self)){$B.RAISE(_b_.TypeError,'memoryview: product(shape) * itemsize != buffer size')}} switch(format){case "B": return memoryview.$factory(self.obj) case "I": var res=memoryview.$factory(self.obj),objlen=len(self.obj) res.itemsize=4 res.format="I" if(objlen % 4 !=0){$B.RAISE(_b_.TypeError,"memoryview: length is not "+ "a multiple of itemsize")} return res}} memoryview.hex=function(self){var res='',bytes=_b_.bytes.$factory(self) bytes.source.forEach(function(item){res+=item.toString(16)}) return res} memoryview.readonly=$B.getset_descriptor.$factory( memoryview,'readonly',function(_self){return $B.$isinstance(_self.obj,_b_.bytes)} ) memoryview.release=function(self){if(self.$released){return} self.$released=true self.obj.$exports-=1} memoryview.tobytes=function(self){if($B.$isinstance(self.obj,[_b_.bytes,_b_.bytearray])){return{ __class__:_b_.bytes,source:self.obj.source}}else if($B.imported.array && $B.$isinstance(self.obj,$B.imported.array.array)){return $B.imported.array.array.tobytes(self.obj)} $B.RAISE(_b_.TypeError,'cannot run tobytes with '+$B.class_name(self.obj))} 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=[] for(var i=0;i < self.obj.source.length;i+=4){var item=self.obj.source[i],coef=256 for(var j=1;j < 4;j++){item+=coef*self.obj.source[i+j] coef*=256} res.push(item)} return res}}} $B.set_func_names(memoryview,"builtins") _b_.min=function(){return $extreme(arguments,'__lt__')} var next=_b_.next=function(obj){check_no_kw('next',obj) var missing={},$=$B.args("next",2,{obj:null,def:null},['obj','def'],arguments,{def:missing},null,null) var klass=obj.__class__ ||$B.get_class(obj),ga=$B.$call($B.$getattr(klass,"__next__")) if(ga !==undefined){try{return $B.$call(ga)(obj)}catch(err){if(err.__class__===_b_.StopIteration && $.def !==missing){return $.def} throw err}} $B.RAISE(_b_.TypeError,"'"+$B.class_name(obj)+ "' object is not an iterator")} var NotImplementedType=$B.NotImplementedType= $B.make_class("NotImplementedType",function(){return NotImplemented} ) NotImplementedType.__repr__=NotImplementedType.__str__=function(){return "NotImplemented"} $B.set_func_names(NotImplementedType,"builtins") var NotImplemented=_b_.NotImplemented={__class__:NotImplementedType} _b_.oct=function(obj){check_nb_args_no_kw('oct',1,arguments) return bin_hex_oct(8,obj)} _b_.ord=function(c){check_nb_args_no_kw('ord',1,arguments) if(typeof c.valueOf()=='string'){if(c.length==1){return c.charCodeAt(0)}else if(c.length==2){var code=c.codePointAt(0) if(code >=0x10000 && code <=0x10FFFF){return code}} $B.RAISE(_b_.TypeError,'ord() expected a character, but '+ 'string of length '+c.length+' found')} switch($B.get_class(c)){case _b_.str: if(c.length==1){return c.charCodeAt(0)} $B.RAISE(_b_.TypeError,'ord() expected a character, but '+ 'string of length '+c.length+' found') case _b_.bytes: case _b_.bytearray: if(c.source.length==1){return c.source[0]} $B.RAISE(_b_.TypeError,'ord() expected a character, but '+ 'string of length '+c.source.length+' found') default: $B.RAISE(_b_.TypeError,'ord() expected a character, but '+ $B.class_name(c)+' was found')}} var complex_modulo=()=> $B.EXC(_b_.ValueError,'complex modulo') var all_ints=()=> $B.EXC(_b_.TypeError,'pow() 3rd argument not '+ 'allowed unless all arguments are integers') _b_.pow=function(){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 if(z===_b_.None){return $B.rich_op('__pow__',x,y)}else{if($B.$isinstance(x,_b_.int)){if($B.$isinstance(y,_b_.float)){throw all_ints()}else if($B.$isinstance(y,_b_.complex)){throw complex_modulo()}else if($B.$isinstance(y,_b_.int)){if($B.$isinstance(z,_b_.complex)){throw complex_modulo()}else if(! $B.$isinstance(z,_b_.int)){throw all_ints()}} return _b_.int.__pow__(x,y,z)}else if($B.$isinstance(x,_b_.float)){throw all_ints()}else if($B.$isinstance(x,_b_.complex)){throw complex_modulo()}}} var $print=_b_.print=function(){var $ns=$B.args('print',0,{},[],arguments,{},'args','kw') var kw=$ns['kw'],end=_b_.dict.get(kw,'end','\n'),sep=_b_.dict.get(kw,'sep',' '),file=_b_.dict.get(kw,'file',$B.get_stdout()) var args=$ns['args'],writer=$B.$getattr(file,'write') for(var i=0,len=args.length;i < len;i++){var arg=_b_.str.$factory(args[i]) writer(arg) if(i < len-1){writer(sep)}} writer(end) var flush=$B.$getattr(file,'flush',None) if(flush !==None){$B.$call(flush)()} return None} $print.__name__='print' $print.is_func=true var quit=_b_.quit=function(){throw _b_.SystemExit} quit.__repr__=quit.__str__=function(){return "Use quit() or Ctrl-Z plus Return to exit"} var repr=_b_.repr=function(obj){check_nb_args_no_kw('repr',1,arguments) var klass=$B.get_class(obj) return $B.$call($B.$getattr(klass,"__repr__"))(obj)} var reversed=_b_.reversed=$B.make_class("reversed",function(seq){ check_nb_args_no_kw('reversed',1,arguments) var klass=seq.__class__ ||$B.get_class(seq),rev_method=$B.$getattr(klass,'__reversed__',null) if(rev_method !==null){return $B.$call(rev_method)(seq)} try{var method=$B.$getattr(klass,'__getitem__')}catch(err){$B.RAISE(_b_.TypeError,"argument to reversed() must be a sequence")} var res={__class__:reversed,$counter :_b_.len(seq),getter:function(i){return $B.$call(method)(seq,i)}} return res} ) reversed.__iter__=function(self){return self} reversed.__next__=function(self){self.$counter-- if(self.$counter < 0){$B.RAISE(_b_.StopIteration,'')} return self.getter(self.$counter)} $B.set_func_names(reversed,"builtins") _b_.round=function(){var $=$B.args('round',2,{number:null,ndigits:null},['number','ndigits'],arguments,{ndigits:None},null,null),arg=$.number,n=$.ndigits===None ? 0 :$.ndigits var klass if(! $B.$isinstance(arg,[_b_.int,_b_.float])){klass=arg.__class__ ||$B.get_class(arg) try{return $B.$call($B.$getattr(klass,"__round__")).apply(null,arguments)}catch(err){if(err.__class__===_b_.AttributeError){$B.RAISE(_b_.TypeError,"type "+$B.class_name(arg)+ " doesn't define __round__ method")}else{throw err}}} if(! $B.$isinstance(n,_b_.int)){$B.RAISE(_b_.TypeError,"'"+$B.class_name(n)+ "' object cannot be interpreted as an integer")} klass=$B.get_class(arg) if($B.$isinstance(arg,_b_.float)){return _b_.float.__round__(arg,$.ndigits)} var mult=Math.pow(10,n),x=arg*mult,floor=Math.floor(x),diff=Math.abs(x-floor),res if(diff==0.5){if(floor % 2){floor+=1} res=_b_.int.__truediv__(floor,mult)}else{res=_b_.int.__truediv__(Math.round(x),mult)} if(res.value===Infinity ||res.value===-Infinity){$B.RAISE(_b_.OverflowError,"rounded value too large to represent")} if($.ndigits===None){ return Math.floor(res.value)}else{ return $B.$call(klass)(res)}} _b_.setattr=function(){var $=$B.args('setattr',3,{obj:null,attr:null,value:null},['obj','attr','value'],arguments,{},null,null),obj=$.obj,attr=$.attr,value=$.value if(!(typeof attr=='string')){$B.RAISE(_b_.TypeError,"setattr(): attribute name must be string")} return $B.$setattr(obj,attr,value)} $B.$setattr1=function(obj,attr,value,inum){try{$B.$setattr(obj,attr,value)}catch(err){$B.set_inum(inum) throw err}} $B.$setattr=function(obj,attr,value){if(obj===undefined){console.log('obj undef',attr,value)} var $test=false switch(attr){case '__dict__': if(! $B.$isinstance(value,_b_.dict)){$B.RAISE(_b_.TypeError,"__dict__ must be set to a dictionary, "+ "not a '"+$B.class_name(value)+"'")} if(obj.$function_infos && ! obj.$infos){$B.make_function_infos(obj,...obj.$function_infos)} if(obj.$infos){obj.$infos.__dict__=value return None} obj.__dict__=value return None case '__class__': function error(msg){$B.RAISE(_b_.TypeError,msg)} if(value.__class__){if(value.__module__=="builtins"){error("__class__ assignement only "+ "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]!==_b_.object && value.__bases__[i].__module__=="builtins"){error("__class__ assignment: '"+$B.class_name(obj)+ "' object layout differs from '"+ $B.class_name(value)+"'")}}}} obj.__class__=value return None case '__doc__': if(obj.__class__===_b_.property){obj[attr]=value} break} if($test){console.log("set attr",attr,"of",obj,"to",value)} if(obj.$factory ||obj.$is_class){var metaclass=obj.__class__ if(metaclass===_b_.type){return _b_.type.__setattr__(obj,attr,value)} return $B.$call($B.$getattr(metaclass,'__setattr__'))(obj,attr,value)} var res=obj[attr],klass=obj.__class__ ||$B.get_class(obj) if($test){console.log('set attr',attr,'of obj',obj,'class',klass,"obj[attr]",obj[attr])} if(res===undefined && klass){res=$B.search_in_mro(klass,attr)} if($test){console.log('set attr',attr,'klass',klass,'found in class',res)} if(res !==undefined && res !==null){ if(res.__set__ !==undefined){res.__set__(res,obj,value) return None} var rcls=res.__class__,__set1__ if(rcls !==undefined){__set1__=$B.search_in_mro(rcls,'__set__')} if(__set1__ !==undefined){var __set__=$B.$getattr(res,'__set__',null) if(__set__ &&(typeof __set__=='function')){__set__.apply(res,[obj,value]) return None}}else if(klass && klass.$descriptors !==undefined && klass[attr]!==undefined){var setter=klass[attr].setter if(typeof setter=='function'){setter(obj,value) return None}else{$B.RAISE_ATTRIBUTE_ERROR('readonly attribute',obj,attr)}}} klass.$tp_setattr=klass.$tp_setattr ?? $B.search_in_mro(klass,'__setattr__') var _setattr=klass.$tp_setattr if(_setattr===_b_.object.__setattr__){_setattr=false} var special_attrs=["__module__"] if(klass && klass.__slots__ && special_attrs.indexOf(attr)==-1 && ! _setattr){var _slots=true for(var kl of klass.__mro__){if(kl===_b_.object ||kl===_b_.type){break} if(! kl.__slots__){ _slots=false break}} if(_slots){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.__name__+item}else{return item}})}else{return klass.__slots__}} return[]} var has_slot=false if($B.$is_member(attr,mangled_slots(klass))){has_slot=true}else{for(var cls of klass.__mro__){if(mangled_slots(cls).indexOf(attr)>-1){has_slot=true break}}} if(! has_slot){throw $B.attr_error(attr,klass)}}} if($test){console.log("attr",attr,"use _setattr",_setattr)} if(!_setattr){if(obj[attr]!==undefined){obj[attr]=value}else if(obj.__dict__===undefined){$B.RAISE_ATTRIBUTE_ERROR(`'${$B.class_name(obj)}' `+ `object has no attribute '${attr}' and no __dict__ for `+ `setting new attributes`,obj,attr)}else{_b_.dict.$setitem(obj.__dict__,attr,value) if(obj.$method_cache && obj.$method_cache[attr]){delete obj.$method_cache[attr]}} if($test){console.log("no setattr, obj",obj)}}else{if($test){console.log('apply _setattr',obj,attr)} if(typeof _setattr !=='function'){console.log('not a function',_setattr) console.log('attr',attr,'of',obj)} _setattr(obj,attr,value)} return None} _b_.sorted=function(){var $=$B.args('sorted',1,{iterable:null},['iterable'],arguments,{},null,'kw') var _list=_b_.list.$factory($.iterable),args=[_list].concat(Array.from(arguments).slice(1)) _b_.list.sort.apply(null,args) return _list} _b_.sum=function(){var $=$B.args('sum',2,{iterable:null,start:null},['iterable','start'],arguments,{start:0},null,null),iterable=$.iterable,start=$.start if($B.$isinstance(start,[_b_.str,_b_.bytes])){$B.RAISE(_b_.TypeError,"sum() can't sum bytes"+ " [use b''.join(seq) instead]")} var res=start iterable=iter(iterable) while(true){try{var _item=next(iterable) res=$B.rich_op('__add__',res,_item)}catch(err){if(err.__class__===_b_.StopIteration){break}else{throw err}}} return res} var $$super=_b_.super=$B.make_class("super",function(_type,object_or_type){var no_object_or_type=object_or_type===undefined if(_type===undefined && object_or_type===undefined){var frame=$B.frame_obj.frame,pyframe=$B.imported["_sys"]._getframe(),code=$B.frame.f_code.__get__(pyframe),co_varnames=code.co_varnames if(co_varnames.length > 0){_type=frame[1].__class__ if(_type===undefined){$B.RAISE(_b_.RuntimeError,"super(): no arguments")} object_or_type=frame[1][code.co_varnames[0]]}else{$B.RAISE(_b_.RuntimeError,"super(): no arguments")}} if((! no_object_or_type)&& Array.isArray(object_or_type)){object_or_type=object_or_type[0]} var $arg2 if(object_or_type !==undefined){if(object_or_type===_type || (object_or_type.$is_class && _b_.issubclass(object_or_type,_type))){$arg2='type'}else if($B.$isinstance(object_or_type,_type)){$arg2='object'}else{$B.RAISE(_b_.TypeError,'super(type, obj): obj must be an instance '+ 'or subtype of type')}} return{ __class__:$$super,__thisclass__:_type,__self_class__:object_or_type,$arg2}} ) $$super.__get__=function(self,instance){ return $$super.$factory(self.__thisclass__,instance)} $$super.__getattribute__=function(self,attr){if(self.__thisclass__.$is_js_class){if(attr=="__init__"){ return function(){mro[0].$js_func.call(self.__self_class__,...arguments)}}} var object_or_type=self.__self_class__,mro=self.$arg2=='type' ? object_or_type.__mro__ : $B.get_class(object_or_type).__mro__ var search_start=mro.indexOf(self.__thisclass__)+1,search_classes=mro.slice(search_start) var $test=false if($test){console.log('super.__ga__, self',self,'search classes',search_classes)} var f for(var klass of search_classes){if(klass===undefined){console.log('klass undef in super',self) console.log('mro',mro)} if(klass[attr]!==undefined){f=klass[attr] break}} if(f===undefined){if($$super[attr]!==undefined){return(function(x){return function(){var args=[x] for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} return $$super[attr].apply(null,args)}})(self)} if($test){console.log("no attr",attr,self,"mro",mro)} throw $B.attr_error(attr,self)} if($test){console.log("super",attr,self,"mro",mro,"found in mro[0]",mro[0],f,f+'')} if(f.$type=="staticmethod" ||attr=="__new__"){return f}else if(f.__class__===_b_.classmethod){return f.__func__.bind(null,object_or_type)}else if(f.$is_property){return f.fget(object_or_type)}else if(typeof f !="function"){return f}else{if(f.__class__===$B.method){ f=f.$infos.__func__} var callable=$B.$call(f) var method=function(){var res=callable(self.__self_class__,...arguments) if($test){console.log("calling super",self.__self_class__,attr,f,"res",res)} return res} method.__class__=$B.method var module if(f.$infos !==undefined){module=f.$infos.__module__}else if(f.__class__===_b_.property){module=f.fget.$infos.__module}else if(f.$is_class){module=f.__module__} method.$infos={__self__:self.__self_class__,__func__:f,__name__:attr,__module__:module,__qualname__:klass.__name__+"."+attr} return method}} $$super.__init__=function(cls){if(cls===undefined){$B.RAISE(_b_.TypeError,"descriptor '__init__' of 'super' "+ "object needs an argument")} if(cls.__class__ !==$$super){$B.RAISE(_b_.TypeError,"descriptor '__init__' requires a"+ " 'super' object but received a '"+$B.class_name(cls)+"'")}} $$super.__repr__=function(self){$B.builtins_repr_check($$super,arguments) var res="" if(self.__self_class__ !==undefined){res+=', <'+self.__self_class__.__class__.__name__+' object>'}else{res+=', NULL'} return res+'>'} $B.set_func_names($$super,"builtins") _b_.vars=function(){var def={},$=$B.args('vars',1,{obj:null},['obj'],arguments,{obj:def},null,null) if($.obj===def){return _b_.locals()}else{try{return $B.$getattr($.obj,'__dict__')}catch(err){if(err.__class__===_b_.AttributeError){$B.RAISE(_b_.TypeError,"vars() argument must have __dict__ attribute")} throw err}}} var zip=_b_.zip=$B.make_class("zip",function(){var res={__class__:zip,items:[]} if(arguments.length==0){return res} var $ns=$B.args('zip',0,{},[],arguments,{},'args','kw') var _args=$ns['args'],strict=$B.$bool(_b_.dict.get($ns.kw,'strict',false)) var iters=[] for(var arg of _args){iters.push($B.make_js_iterator(arg))} return{ __class__:zip,iters,strict}} ) zip.__iter__=function(self){return self} zip.__next__=function(self){var res=[],len=self.iters.length for(var i=0;i < len;i++){var v=self.iters[i].next() if(v.done){if(self.strict){if(i > 0){$B.RAISE(_b_.ValueError,`zip() argument ${i + 1} is longer than argument ${i}`)}else{for(var j=1;j < len;j++){var v1=self.iters[j].next() if(! v1.done){$B.RAISE(_b_.ValueError,`zip() argument ${j + 1} is longer than argument ${i + 1}`)}}}} $B.RAISE(_b_.StopIteration,'')} res.push(v.value)} return $B.fast_tuple(res)} $B.set_func_names(zip,"builtins") function no_set_attr(klass,attr){if(klass[attr]!==undefined){$B.RAISE_ATTRIBUTE_ERROR("'"+klass.__name__+ "' object attribute '"+attr+"' is read-only",klass,attr)}else{throw $B.attr_error(attr,klass)}} var True=_b_.True=true var False=_b_.False=false var ellipsis=$B.ellipsis=$B.make_class("ellipsis",function(){return Ellipsis} ) ellipsis.__repr__=function(){return 'Ellipsis'} var Ellipsis=_b_.Ellipsis={__class__:ellipsis} for(var comp in $B.$comps){ switch($B.$comps[comp]){case 'ge': case 'gt': case 'le': case 'lt': ellipsis['__'+$B.$comps[comp]+'__']= function(){return _b_.NotImplemented}}} $B.set_func_names(ellipsis) _b_.__BRYTHON__=__BRYTHON__ $B.builtin_funcs=["__build_class__","abs","aiter","all","anext","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" ] var builtin_function=$B.builtin_function_or_method=$B.make_class( "builtin_function_or_method",function(f){f.__class__=builtin_function return f}) builtin_function.__getattribute__=$B.function.__getattribute__ builtin_function.__reduce_ex__=builtin_function.__reduce__=function(self){return self.$function_infos[$B.func_attrs.__name__]} builtin_function.__repr__=builtin_function.__str__=function(self){return ''} $B.set_func_names(builtin_function,"builtins") var method_wrapper=$B.make_class("method_wrapper") method_wrapper.__repr__=method_wrapper.__str__=function(self){return ""} $B.set_func_names(method_wrapper,"builtins") $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" ] var other_builtins=['Ellipsis','False','None','True','__debug__','__import__','copyright','credits','license','NotImplemented' ] var builtin_names=$B.builtin_funcs. concat($B.builtin_classes). concat(other_builtins) for(var name of builtin_names){try{if($B.builtin_funcs.indexOf(name)>-1){_b_[name].__class__=builtin_function _b_[name].$infos={__module__:'builtins',__name__:name,__qualname__:name} $B.set_function_infos(_b_[name],{__module__:'builtins',__name__:name,__qualname__:name} )}}catch(err){ console.log('error for',name,err)}} _b_.object.__init__.__class__=$B.wrapper_descriptor _b_.object.__new__.__class__=builtin_function})(__BRYTHON__); ; ;(function($B){var _b_=$B.builtins var DEFAULT_MIN_MERGE=32 var DEFAULT_MIN_GALLOPING=7 var DEFAULT_TMP_STORAGE_LENGTH=256 var POWERS_OF_TEN=[1e0,1e1,1e2,1e3,1e4,1e5,1e6,1e7,1e8,1e9] function log10(x){if(x < 1e5){if(x < 1e2){return x < 1e1 ? 0 :1} if(x < 1e4){return x < 1e3 ? 2 :3} return 4} if(x < 1e7){return x < 1e6 ? 5 :6} if(x < 1e9){return x < 1e8 ? 7 :8} return 9} function alphabeticalCompare(a,b){if(a===b){return 0} if(~~a===a && ~~b===b){if(a===0 ||b===0){return a < b ?-1 :1} if(a < 0 ||b < 0){if(b >=0){return-1} if(a >=0){return 1} a=-a b=-b} var al=log10(a),bl=log10(b) var t=0 if(al < bl){a*=POWERS_OF_TEN[bl-al-1] b/=10 t=-1}else if(al > bl){b*=POWERS_OF_TEN[al-bl-1] a/=10; t=1;} if(a===b){return t} return a < b ?-1 :1} var aStr=String(a) var bStr=String(b) if(aStr===bStr){return 0} return aStr < bStr ?-1 :1} function minRunLength(n){var r=0 while(n >=DEFAULT_MIN_MERGE){r |=(n & 1) n >>=1} return n+r} function makeAscendingRun(array,lo,hi,compare){var runHi=lo+1 if(runHi===hi){return 1;} if(compare(array[runHi++],array[lo])< 0){while(runHi < hi && compare(array[runHi],array[runHi-1])< 0){runHi++} reverseRun(array,lo,runHi)}else{while(runHi < hi && compare(array[runHi],array[runHi-1])>=0){runHi++}} return runHi-lo} function reverseRun(array,lo,hi){hi-- while(lo < hi){var t=array[lo] array[lo++]=array[hi] array[hi--]=t}} function binaryInsertionSort(array,lo,hi,start,compare){if(start===lo){start++} for(;start < hi;start++){var pivot=array[start] var left=lo var right=start while(left < right){var mid=(left+right)>>> 1 if(compare(pivot,array[mid])< 0){right=mid}else{left=mid+1}} var n=start-left switch(n){case 3: array[left+3]=array[left+2] case 2: array[left+2]=array[left+1] case 1: array[left+1]=array[left] break; default: while(n > 0){array[left+n]=array[left+n-1] n--;}} array[left]=pivot}} function gallopLeft(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1 if(compare(value,array[start+hint])> 0){maxOffset=length-hint while(offset < maxOffset && compare(value,array[start+hint+offset])> 0){lastOffset=offset offset=(offset << 1)+1 if(offset <=0){offset=maxOffset}} if(offset > maxOffset){offset=maxOffset} lastOffset+=hint offset+=hint}else{maxOffset=hint+1 while(offset < maxOffset && compare(value,array[start+hint-offset])<=0){lastOffset=offset offset=(offset << 1)+1 if(offset <=0){offset=maxOffset}} if(offset > maxOffset){offset=maxOffset} var tmp=lastOffset lastOffset=hint-offset offset=hint-tmp} lastOffset++ while(lastOffset < offset){var m=lastOffset+((offset-lastOffset)>>> 1) if(compare(value,array[start+m])> 0){lastOffset=m+1}else{offset=m}} return offset} function gallopRight(value,array,start,length,hint,compare){var lastOffset=0,maxOffset=0,offset=1 if(compare(value,array[start+hint])< 0){maxOffset=hint+1 while(offset < maxOffset && compare(value,array[start+hint-offset])< 0){lastOffset=offset offset=(offset << 1)+1 if(offset <=0){offset=maxOffset}} if(offset > maxOffset){offset=maxOffset} var tmp=lastOffset lastOffset=hint-offset offset=hint-tmp}else{maxOffset=length-hint while(offset < maxOffset && compare(value,array[start+hint+offset])>=0){lastOffset=offset offset=(offset << 1)+1 if(offset <=0){offset=maxOffset}} if(offset > maxOffset){offset=maxOffset} lastOffset+=hint offset+=hint} lastOffset++ while(lastOffset < offset){var m=lastOffset+((offset-lastOffset)>>> 1) if(compare(value,array[start+m])< 0){offset=m}else{lastOffset=m+1}} return offset} var TIM_SORT_ASSERTION="TimSortAssertion" var TimSortAssertion=function(message){this.name=TIM_SORT_ASSERTION this.message=message} var TimSort=function(array,compare){var self={array:array,compare:compare,minGallop:DEFAULT_MIN_GALLOPING,length :array.length,tmpStorageLength:DEFAULT_TMP_STORAGE_LENGTH,stackLength:0,runStart:null,runLength:null,stackSize:0, pushRun:function(runStart,runLength){this.runStart[this.stackSize]=runStart this.runLength[this.stackSize]=runLength this.stackSize+=1}, mergeRuns:function(){while(this.stackSize > 1){var n=this.stackSize-2 if((n >=1 && this.runLength[n-1]<= this.runLength[n]+this.runLength[n+1])|| (n >=2 && this.runLength[n-2]<= this.runLength[n]+this.runLength[n-1])){if(this.runLength[n-1]< this.runLength[n+1]){n--}}else if(this.runLength[n]> this.runLength[n+1]){break} this.mergeAt(n)}}, forceMergeRuns:function(){while(this.stackSize > 1){var n=this.stackSize-2 if(n > 0 && this.runLength[n-1]< this.runLength[n+1]){n--} this.mergeAt(n)}}, mergeAt:function(i){var compare=this.compare,array=this.array,start1=this.runStart[i],length1=this.runLength[i],start2=this.runStart[i+1],length2=this.runLength[i+1] this.runLength[i]=length1+length2 if(i===this.stackSize-3){this.runStart[i+1]=this.runStart[i+2] this.runLength[i+1]=this.runLength[i+2]} this.stackSize--; var k=gallopRight(array[start2],array,start1,length1,0,compare) start1+=k length1-=k if(length1===0){return} length2=gallopLeft(array[start1+length1-1],array,start2,length2,length2-1,compare) if(length2===0){return} if(length1 <=length2){this.mergeLow(start1,length1,start2,length2)}else{this.mergeHigh(start1,length1,start2,length2)}}, mergeLow:function(start1,length1,start2,length2){var compare=this.compare,array=this.array,tmp=this.tmp,i=0 for(let i=0;i < length1;i++){tmp[i]=array[start1+i]} var cursor1=0,cursor2=start2,dest=start1 array[dest++]=array[cursor2++] if(--length2===0){for(let i=0;i < length1;i++){array[dest+i]=tmp[cursor1+i]} return} if(length1===1){for(let i=0;i < length2;i++){array[dest+i]=array[cursor2+i]} array[dest+length2]=tmp[cursor1] return} var minGallop=this.minGallop while(true){var count1=0,count2=0,exit=false do{if(compare(array[cursor2],tmp[cursor1])< 0){array[dest++]=array[cursor2++] count2++ count1=0 if(--length2===0){exit=true break}}else{array[dest++]=tmp[cursor1++] count1++ count2=0 if(--length1===1){exit=true break}}}while((count1 |count2)< minGallop) if(exit){break} do{ count1=gallopRight(array[cursor2],tmp,cursor1,length1,0,compare) if(count1 !==0){for(let i=0;i < count1;i++){array[dest+i]=tmp[cursor1+i]} dest+=count1 cursor1+=count1 length1-=count1 if(length1 <=1){exit=true break}} array[dest++]=array[cursor2++] if(--length2===0){exit=true break} count2=gallopLeft(tmp[cursor1],array,cursor2,length2,0,compare) if(count2 !==0){for(let i=0;i < count2;i++){array[dest+i]=array[cursor2+i]} dest+=count2 cursor2+=count2 length2-=count2 if(length2===0){exit=true break}} array[dest++]=tmp[cursor1++] if(--length1===1){exit=true break} minGallop--;}while(count1 >=DEFAULT_MIN_GALLOPING || count2 >=DEFAULT_MIN_GALLOPING); if(exit){break} if(minGallop < 0){minGallop=0} minGallop+=2} this.minGallop=minGallop if(minGallop < 1){this.minGallop=1} if(length1===1){for(let i=0;i < length2;i++){array[dest+i]=array[cursor2+i]} array[dest+length2]=tmp[cursor1]}else if(length1===0){throw new TimSortAssertion('mergeLow preconditions were not respected')}else{for(let i=0;i < length1;i++){array[dest+i]=tmp[cursor1+i]}}}, mergeHigh:function(start1,length1,start2,length2){let compare=this.compare,array=this.array,tmp=this.tmp for(let i=0;i < length2;i++){tmp[i]=array[start2+i]} let cursor1=start1+length1-1,cursor2=length2-1,dest=start2+length2-1,customCursor=0,customDest=0 array[dest--]=array[cursor1--] if(--length1===0){customCursor=dest-(length2-1) for(let i=0;i < length2;i++){array[customCursor+i]=tmp[i]} return} if(length2===1){dest-=length1 cursor1-=length1 customDest=dest+1 customCursor=cursor1+1 for(let i=length1-1;i >=0;i--){array[customDest+i]=array[customCursor+i]} array[dest]=tmp[cursor2] return} var minGallop=this.minGallop while(true){let count1=0,count2=0,exit=false do{if(compare(tmp[cursor2],array[cursor1])< 0){array[dest--]=array[cursor1--] count1++ count2=0 if(--length1===0){exit=true break}}else{array[dest--]=tmp[cursor2--] count2++ count1=0 if(--length2===1){exit=true break}}}while((count1 |count2)< minGallop) if(exit){break} do{count1=length1-gallopRight(tmp[cursor2],array,start1,length1,length1-1,compare) if(count1 !==0){dest-=count1 cursor1-=count1 length1-=count1 customDest=dest+1 customCursor=cursor1+1 for(let i=count1-1;i >=0;i--){array[customDest+i]=array[customCursor+i]} if(length1===0){exit=true break}} array[dest--]=tmp[cursor2--] if(--length2===1){exit=true break} count2=length2-gallopLeft(array[cursor1],tmp,0,length2,length2-1,compare) if(count2 !==0){dest-=count2 cursor2-=count2 length2-=count2 customDest=dest+1 customCursor=cursor2+1 for(let i=0;i < count2;i++){array[customDest+i]=tmp[customCursor+i]} if(length2 <=1){exit=true break}} array[dest--]=array[cursor1--] if(--length1===0){exit=true break} minGallop--}while(count1 >=DEFAULT_MIN_GALLOPING || count2 >=DEFAULT_MIN_GALLOPING) if(exit){break} if(minGallop < 0){minGallop=0} minGallop+=2} this.minGallop=minGallop if(minGallop < 1){this.minGallop=1} if(length2===1){dest-=length1 cursor1-=length1 customDest=dest+1 customCursor=cursor1+1 for(let i=length1-1;i >=0;i--){array[customDest+i]=array[customCursor+i]} array[dest]=tmp[cursor2]}else if(length2==0){throw new TimSortAssertion("mergeHigh preconditions were not respected")}else{customCursor=dest-(length2-1) for(let i=0;i < length2;i++){array[customCursor+i]=tmp[i]}}}} if(self.length < 2*DEFAULT_TMP_STORAGE_LENGTH){self.tmpStorageLength=self.length >>> 1} self.tmp=new Array(self.tmpStorageLength) self.stackLength= (self.length < 120 ? 5 : self.length < 1542 ? 10 : self.length < 119151 ? 19 :40) self.runStart=new Array(self.stackLength) self.runLength=new Array(self.stackLength) return self} function tim_sort(array,compare,lo,hi){if(!Array.isArray(array)){$B.RAISE(_b_.TypeError,"Can only sort arrays")} if(!compare){compare=alphabeticalCompare}else if(typeof compare !=="function"){hi=lo lo=compare compare=alphabeticalCompare} if(!lo){lo=0} if(!hi){hi=array.length} var remaining=hi-lo if(remaining < 2){return} var runLength=0 if(remaining < DEFAULT_MIN_MERGE){runLength=makeAscendingRun(array,lo,hi,compare) binaryInsertionSort(array,lo,hi,lo+runLength,compare) return} var ts=new TimSort(array,compare) var minRun=minRunLength(remaining) do{runLength=makeAscendingRun(array,lo,hi,compare) if(runLength < minRun){var force=remaining if(force > minRun){force=minRun} binaryInsertionSort(array,lo,lo+force,lo+runLength,compare) runLength=force} ts.pushRun(lo,runLength) ts.mergeRuns() remaining-=runLength lo+=runLength}while(remaining !==0) ts.forceMergeRuns()} function tim_sort_safe(array,compare){ try{ tim_sort(array,compare,0,array.length)}catch(e){if(e.name==TIM_SORT_ASSERTION){array.sort(compare);}else{ throw e;}}} $B.$TimSort=tim_sort_safe $B.$AlphabeticalCompare=alphabeticalCompare})(__BRYTHON__); ; (function($B){var _b_=$B.builtins $B.del_exc=function(frame){delete frame[1].$current_exception} $B.set_exc=function(exc,frame){exc.__traceback__=exc.__traceback__===_b_.None ? make_tb():exc.__traceback__ if(! exc.__class__){console.log('no class',exc)} exc.__class__=exc.__class__ ?? _b_.JavascriptError exc.args=exc.args ??[exc.message] if(frame===undefined){var msg='Internal error: no frame for exception '+_b_.repr(exc) console.error(['Traceback (most recent call last):',$B.print_stack(exc.$frame_obj),msg].join('\n')) if($B.get_option('debug',exc)> 1){console.log(exc.args) console.log(exc.stack)} throw Error(msg)}else{frame[1].$current_exception=$B.exception(exc)}} $B.set_exc_and_trace=function(frame,exc){$B.set_exc(exc,frame) if((! exc.$in_trace_func)&& frame.$f_trace !==_b_.None){frame.$f_trace=$B.trace_exception()}} $B.set_exc_and_leave=function(frame,exc){$B.set_exc_and_trace(frame,exc) $B.leave_frame() throw exc} $B.get_exc=function(){var frame=$B.frame_obj.frame return frame[1].$current_exception} $B.set_exception_offsets=function(exc,position){ exc.$positions=exc.$positions ||{} exc.$positions[$B.frame_obj.count-1]=position return exc} $B.$raise=function(arg,cause){ var active_exc=$B.get_exc() if(arg===undefined){if(active_exc !==undefined){throw active_exc} $B.RAISE(_b_.RuntimeError,"No active exception to reraise")}else{if($B.$isinstance(arg,_b_.BaseException)){if(arg.__class__===_b_.StopIteration && $B.frame_obj.frame.$is_generator){ arg=$B.EXC(_b_.RuntimeError,"generator raised StopIteration")} arg.__context__=active_exc===undefined ? _b_.None :active_exc arg.__cause__=cause ||_b_.None arg.__suppress_context__=cause !==undefined throw arg}else if(arg.$is_class && _b_.issubclass(arg,_b_.BaseException)){if(arg===_b_.StopIteration){if($B.frame_obj.frame[1].$is_generator){ $B.RAISE(_b_.RuntimeError,"generator raised StopIteration")}} var exc=$B.$call(arg)() exc.__context__=active_exc===undefined ? _b_.None :active_exc exc.__cause__=cause ||_b_.None exc.__suppress_context__=cause !==undefined throw exc}else{$B.RAISE(_b_.TypeError,"exceptions must derive from BaseException")}}} $B.print_stack=function(frame_obj){ var stack=make_frames_stack(frame_obj ||$B.frame_obj) var trace=[] for(var frame of stack){var lineno=frame.$lineno,filename=frame.__file__ if(lineno !==undefined){var local=frame[0]==frame[2]? "" :frame[0] trace.push(` File "${filename}" line ${lineno}, in ${local}`) var src=$B.file_cache[filename] if(src){var lines=src.split("\n"),line=lines[lineno-1] trace.push(" "+line.trim())}}} return trace.join("\n")} $B.count_frames=function(frame_obj){frame_obj=frame_obj ||$B.frame_obj return frame_obj==null ? 0 :frame_obj.count} $B.get_frame_at=function(pos,frame_obj){frame_obj=frame_obj ||$B.frame_obj var nb=frame_obj.count-pos-1 for(var i=0;i < nb;i++){if(frame_obj.prev===null){break} frame_obj=frame_obj.prev} return frame_obj.frame} function make_frames_list(){var t=[] var frame_obj=$B.frame_obj while(frame_obj){t.push(frame_obj.frame) frame_obj=frame_obj.prev} return t} var make_tb=$B.make_tb=function(frames_list){frames_list=frames_list ?? make_frames_list() if(frames_list.length==0){return _b_.None} var _frame=frames_list.pop() var res={__class__:traceback,tb_frame:frame.$factory(_frame),tb_lineno:_frame.$lineno,tb_lasti:_frame.inum ??-1,tb_next:make_tb(frames_list)} return res} var traceback=$B.traceback=$B.make_class("traceback",function(exc){return make_tb()} ) $B.set_func_names(traceback,"builtins") var frame=$B.frame=$B.make_class("frame",function(frame_list){frame_list.__class__=frame return frame_list} ) frame.__bool__=function(){return true} frame.__delattr__=function(_self,attr){if(attr=="f_trace"){_self.$f_trace=_b_.None}} frame.__dir__=function(){return _b_.object.__dir__(frame).concat(['clear','f_back','f_builtins','f_code','f_globals','f_lasti','f_lineno','f_locals','f_trace','f_trace_lines','f_trace_opcodes'])} frame.__getattr__=function(_self,attr){ if(attr=="f_back"){ var frame_obj=$B.frame_obj while(frame_obj !==null){if(frame_obj.frame===_self){break} frame_obj=frame_obj.prev} if(frame_obj.prev !==null){return frame.$factory(frame_obj.prev.frame)} return _b_.None}else if(attr=="clear"){return function(){}}else if(attr=="f_trace"){return _self.$f_trace ?? _b_.None}else if(attr=="f_lasti"){ return 0} throw $B.attr_error(attr,_self)} frame.__setattr__=function(_self,attr,value){if(attr=="f_trace"){ _self.$f_trace=value}} frame.__str__=frame.__repr__=function(_self){return ''} frame.f_builtins={__get__:function(_self){return $B.$getattr(_self[3].__builtins__,'__dict__')}} frame.f_code={__get__:function(_self){var res var positions=[[0,0,0,0]] if(_self[4]){res=$B.$getattr(_self[4],'__code__') positions=_self.positions ?? positions}else if(_self.f_code){ res=_self.f_code}else{res={co_name:(_self[0]==_self[2]? '' :_self[0]),co_filename:_self.__file__,co_varnames:$B.fast_tuple([]),co_firstlineno:1} res.co_qualname=res.co_name positions=_self.positions ?? positions} res.__class__=_b_.code positions=positions.map($B.decode_position) res.co_positions=()=> $B.$list(positions) res.co_positions.__class__=$B.function return res}} frame.f_globals={__get__:function(_self){if(_self.f_globals){return _self.f_globals}else if(_self.f_locals && _self[1]==_self[3]){return _self.f_globals=_self.f_locals}else{return _self.f_globals=$B.obj_dict(_self[3])}}} frame.f_lineno={__get__:function(_self){return _self.$lineno}} frame.f_locals={__get__:function(_self){ if(_self.f_locals){return _self.f_locals}else if(_self.f_globals && _self[1]==_self[3]){return _self.f_locals=_self.f_globals}else{return _self.f_locals=$B.obj_dict(_self[1])}}} frame.f_trace={__get__:function(_self){return _self.$f_trace}} $B.set_func_names(frame,"builtins") $B._frame=frame $B.make_f_code=function(frame,varnames){ frame.f_code={co_argcount:1,co_firstlineno:frame.$lineno,co_name:"",co_filename:frame.__file__,co_flags:115,co_freevars:$B.fast_tuple([]),co_kwonlyargcount:0,co_posonlyargount:0,co_qualname:"genexpr",co_varnames:$B.fast_tuple(['.0'].concat(varnames))}} $B.restore_frame_obj=function(frame_obj,locals){$B.frame_obj=frame_obj $B.frame_obj.frame[1]=locals} var make_frames_stack=$B.make_frames_stack=function(frame_obj){var stack=[] while(frame_obj !==null){stack[stack.length]=frame_obj.frame frame_obj=frame_obj.prev} stack.reverse() return stack} $B.exception=function(js_exc){ var exc if(! js_exc.__class__){if(js_exc.$py_exc){ return js_exc.$py_exc} if($B.get_option('debug',exc)> 1){console.log('Javascript error',js_exc)} var msg=js_exc.name+': '+js_exc.message exc=$B.EXC(_b_.JavascriptError,msg) exc.$js_exc=js_exc if($B.is_recursion_error(js_exc)){msg="maximum recursion depth exceeded" exc=$B.EXC(_b_.RecursionError,msg)} exc.__cause__=_b_.None exc.__context__=_b_.None exc.__suppress_context__=false exc.__traceback__=traceback.$factory(js_exc) exc.args=_b_.tuple.$factory([msg]) exc.$py_error=true js_exc.$py_exc=exc}else{exc=js_exc} exc.__traceback__=exc.__traceback__ ?? traceback.$factory(exc) return exc} $B.is_exc=function(exc,exc_list){ if(exc.__class__===undefined){exc=$B.exception(exc)} var this_exc_class=exc.$is_class ? exc :exc.__class__ for(var i=0;i < exc_list.length;i++){var exc_class=exc_list[i] if(this_exc_class===undefined){console.log("exc class undefined",exc)} if(_b_.issubclass(this_exc_class,exc_class)){return true}} return false} $B.is_recursion_error=function(js_exc){ var msg=js_exc+"",parts=msg.split(":") if(parts.length==1){return false} var err_type=parts[0].trim(),err_msg=parts[1].trim() return(err_type=='InternalError' && err_msg=='too much recursion')|| (err_type=='Error' && err_msg=='Out of stack space')|| (err_type=='RangeError' && err_msg=='Maximum call stack size exceeded')} $B.RAISE=function(error_type,message){throw $B.$call(error_type)(message)} $B.RAISE_ATTRIBUTE_ERROR=function(message,obj,name){var exc=$B.EXC(_b_.AttributeError,message) exc.obj=obj exc.name=name throw exc} $B.EXC=function(error_type,message){return $B.$call(error_type)(message)} function make_builtin_exception(exc_name,base,set_value){ if(Array.isArray(exc_name)){for(var name of exc_name){make_builtin_exception(name,base,set_value)} return} var exc_class=$B.make_class(exc_name) exc_class.__bases__=[base] exc_class.__mro__=_b_.type.$mro(exc_class).slice(1) $B.set_func_names(exc_class,'builtins') _b_[exc_name]=exc_class} make_builtin_exception("BaseException",_b_.object) function check_no_keywords(obj,kw){if(_b_.len(kw)){$B.RAISE(_b_.TypeError,`${$B.class_name(obj)}() takes no keyword arguments`)}} _b_.BaseException.__init__=function(){var $=$B.args('__init__',1,{self:null},['self'],arguments,{},'args','kw') check_no_keywords($.self,$.kw) $.self.args=$B.fast_tuple($.args)} _b_.BaseException.__repr__=function(self){var res=self.__class__.__name__+'(' if(self.args[0]!==undefined){res+=_b_.repr(self.args[0])} if(self.args.length > 1){res+=', '+_b_.repr($B.fast_tuple(self.args.slice(1)))} return res+')'} _b_.BaseException.__str__=function(self){if(self.args.length > 0 && self.args[0]!==_b_.None){return _b_.str.$factory(self.args[0])} return ''} _b_.BaseException.__new__=function(cls){var $=$B.args('__new__',1,{cls:null},['cls'],arguments,{},'args','kw') return{ __class__:$.cls,__dict__:$B.empty_dict(),args:$B.fast_tuple($.args),notes:_b_.None,__traceback__:_b_.None,__cause__:_b_.None,__context__:_b_.None,__suppress_context__:false}} _b_.BaseException.__getattr__=function(self,attr){switch(attr){case '__context__': var frame=$B.frame_obj.frame,ctx=frame[1].$current_exception return ctx ||_b_.None case '__cause__': case '__suppress_context__': return self[attr]?? _b_.None default: throw $B.attr_error(attr,self)}} _b_.BaseException.add_note=function(self,note){ if(! $B.$isinstance(note,_b_.str)){$B.RAISE(_b_.TypeError,'note must be a str, not '+ `'${$B.class_name(note)}'`)} if(self.__notes__ !==undefined){self.__notes__.push(note)}else{self.__notes__=$B.$list([note])}} _b_.BaseException.with_traceback=function(_self,tb){_self.__traceback__=tb return _self} $B.set_func_names(_b_.BaseException,'builtins') make_builtin_exception(["SystemExit","KeyboardInterrupt","GeneratorExit","Exception"],_b_.BaseException) make_builtin_exception("JavascriptError",_b_.Exception) make_builtin_exception(["ArithmeticError","AssertionError","BufferError","EOFError","LookupError","MemoryError","OSError","ReferenceError","RuntimeError","SystemError","TypeError","ValueError","Warning"],_b_.Exception) make_builtin_exception("StopIteration",_b_.Exception) _b_.StopIteration.__init__=function(){var $=$B.args("StopIteration",1,{self:null},['self'],arguments,{},'args','kw') check_no_keywords($.self,$.kw) _b_.BaseException.__init__($.self,...$.args) if($.args.length > 0){$.self.value=$.args[0]}} _b_.StopIteration.value=$B.getset_descriptor.$factory( _b_.StopIteration,'value',function(_self){return _self.value ?? _b_.None},function(_self,value){_self.value=value} ) $B.set_func_names(_b_.StopIteration,'builtins') make_builtin_exception("StopAsyncIteration",_b_.Exception) make_builtin_exception("ImportError",_b_.Exception) _b_.ImportError.__init__=function(){var $=$B.args("ImportError",1,{self:null},['self'],arguments,{},'args','kw') _b_.BaseException.__init__($.self,...$.args) $B.set_expected_kwargs($.self,['name','path'],$.kw)} $B.set_func_names(_b_.ImportError,'builtins') make_builtin_exception("SyntaxError",_b_.Exception) _b_.SyntaxError.__init__=function(){var $=$B.args('SyntaxError',1,{self:null},['self'],arguments,{},'args','kw') var _self=$.self,args=$.args,kw=$.kw check_no_keywords(_self,kw) _self.msg=args[0]?? _b_.None _self.args=$B.fast_tuple(Array.from(args)) var details=[] if(args.length > 1){details=args[1] if(details.length > 0){details=_b_.tuple.$factory(details) if(details.length < 4){$B.RAISE(_b_.TypeError,`function takes at least 4 arguments (${args.length} given)`)} if(details.length > 6){$B.RAISE(_b_.TypeError,`function takes at most 6 arguments (${args.length} given)`)}}} let attrs=['filename','lineno','offset','text','end_lineno','end_offset'],expected_types=[_b_.str,_b_.int,_b_.int,_b_.str,_b_.int,_b_.int] for(var i=0;i < attrs.length;i++){if(details[i]!==undefined){if(! $B.$isinstance(details[i],expected_types[i])){$B.RAISE(_b_.TypeError,`item #${i + 1} (${attrs[i]}) `+ `of the second argument of SyntaxError should be `+ `'${expected_types[i].__name__}', not `+ `'${$B.class_name(details[i])}'`)} _self[attrs[i]]=details[i]}else{_self[attrs[i]]=_b_.None}}} $B.set_func_names(_b_.SyntaxError,'builtins') make_builtin_exception(["FloatingPointError","OverflowError","ZeroDivisionError"],_b_.ArithmeticError) make_builtin_exception("ModuleNotFoundError",_b_.ImportError) make_builtin_exception(["IndexError","KeyError"],_b_.LookupError) make_builtin_exception(["BlockingIOError","ChildProcessError","ConnectionError","FileExistsError","FileNotFoundError","InterruptedError","IsADirectoryError","NotADirectoryError","PermissionError","ProcessLookupError","TimeoutError"],_b_.OSError) make_builtin_exception(["BrokenPipeError","ConnectionAbortedError","ConnectionRefusedError","ConnectionResetError"],_b_.ConnectionError) make_builtin_exception(["NotImplementedError","RecursionError","PythonFinalizationError"],_b_.RuntimeError) make_builtin_exception(["IndentationError","_IncompleteInputError"],_b_.SyntaxError,"msg") make_builtin_exception("TabError",_b_.IndentationError) make_builtin_exception("UnicodeError",_b_.ValueError) make_builtin_exception(["UnicodeDecodeError","UnicodeEncodeError","UnicodeTranslateError"],_b_.UnicodeError) make_builtin_exception(["DeprecationWarning","PendingDeprecationWarning","RuntimeWarning","SyntaxWarning","UserWarning","FutureWarning","ImportWarning","UnicodeWarning","BytesWarning","ResourceWarning","EncodingWarning"],_b_.Warning) _b_.EnvironmentError=_b_.OSError _b_.WindowsError=_b_.OSError _b_.IOError=_b_.OSError _b_.KeyError.__str__=function(self){if(self.args.length==1){return _b_.repr(self.args[0])} return _b_.BaseException.__str__(self)} $B.set_func_names(_b_.KeyError,'builtins') $B.set_expected_kwargs=function(obj,expected,kwargs){for(var item of _b_.dict.$iter_items(kwargs)){if(expected.includes(item.key)){obj[item.key]=item.value}else{var msg=`${$B.class_name(obj)}() got an unexpected `+ `keyword argument '${item.key}'` var suggestions=calculate_suggestions(expected,item.key) if(suggestions){msg+=`. Did you mean '${suggestions}'?`} $B.RAISE(_b_.TypeError,msg)}}} _b_.AttributeError=$B.make_class('AttributeError') _b_.AttributeError.__init__=function(){var $=$B.args("AttributeError",1,{self:null},['self'],arguments,{},'args','kw') _b_.BaseException.__init__($.self,...$.args) $B.set_expected_kwargs($.self,['name','obj'],$.kw)} _b_.AttributeError.__bases__=[_b_.Exception] _b_.AttributeError.__mro__=_b_.type.$mro(_b_.AttributeError) _b_.AttributeError.__str__=function(self){return self.args[0]} $B.set_func_names(_b_.AttributeError,'builtins') $B.attr_error=function(name,obj){var msg if(obj.$is_class){msg=`type object '${obj.__name__}'`}else{msg=`'${$B.class_name(obj)}' object`} msg+=` has no attribute '${name}'` return $B.$call(_b_.AttributeError)(msg,{$kw:[{name,obj}]})} _b_.NameError=$B.make_class('NameError') _b_.NameError.__bases__=[_b_.Exception] _b_.NameError.__mro__=_b_.type.$mro(_b_.NameError).slice(1) _b_.NameError.__init__=function(){var $=$B.args('__init__',1,{self:null},['self'],arguments,{},'args','kw') _b_.BaseException.__init__($.self,...$.args) $B.set_expected_kwargs($.self,['name'],$.kw)} _b_.NameError.__str__=function(self){return self.args[0]} $B.set_func_names(_b_.NameError,'builtins') make_builtin_exception("UnboundLocalError",_b_.NameError) _b_.UnboundLocalError.__str__=function(self){return self.args[0]} $B.set_func_names(_b_.UnboundLocalError,'builtins') $B.name_error=function(name){var exc=$B.$call(_b_.NameError)(`name '${name}' is not defined`) exc.name=name return exc} $B.recursion_error=function(frame){var exc=$B.$call(_b_.RecursionError)("maximum recursion depth exceeded") $B.set_exc(exc,frame) return exc} function calculate_suggestions(list,name){return $B.imported._suggestions._generate_suggestions(list,name)} $B.offer_suggestions_for_attribute_error=function(exc){var name=exc.name,obj=exc.obj if(name===_b_.None ||name===undefined || obj===_b_.None ||obj===undefined){return _b_.None} var dir=_b_.dir(obj),suggestions=calculate_suggestions(dir,name) return suggestions ||_b_.None} $B.offer_suggestions_for_name_error=function(exc,frame){var name=exc.name if(typeof name !='string'){return _b_.None} var tb=exc.__traceback__ if(tb===undefined ||tb===_b_.None){return _b_.None} while(tb.tb_next !==_b_.None){tb=tb.tb_next} var frame=tb.tb_frame var locals=Object.keys(frame[1]).filter(x=> !(x.startsWith('$'))) var suggestion=calculate_suggestions(locals,name) if(suggestion){return suggestion} if(frame[2]!=frame[0]){var globals=Object.keys(frame[3]).filter(x=> !(x.startsWith('$'))) suggestion=calculate_suggestions(globals,name) if(suggestion){return suggestion}} if(frame[4]&& frame[4].$is_method){ var instance_name=frame[4].$infos.__code__.co_varnames[0],instance=frame[1][instance_name] if(_b_.hasattr(instance,name)){return `self.${name}`}} return _b_.None} $B.offer_suggestions_for_unexpected_keyword_error=function(arg_names,key){if(key===_b_.None){return _b_.None} var suggestions=calculate_suggestions(arg_names,key) return suggestions ||_b_.None} _b_.BaseExceptionGroup=$B.make_class("BaseExceptionGroup") _b_.BaseExceptionGroup.__new__=function(){var missing={},$=$B.args("BaseExceptionGroup",3,{cls:null,message:null,exceptions:null},['cls','message','exceptions'],arguments,{exceptions:missing},null,null) var cls=$.cls var exceptions=$.exceptions===missing ?[]:$.exceptions if(exceptions !==_b_.None){var exc_list=_b_.list.$factory(exceptions) var all_exceptions=true for(var exc of exc_list){if(! $B.$isinstance(exc,_b_.Exception)){all_exceptions=false break}} if(all_exceptions){cls=_b_.ExceptionGroup}} var args=Array.from(arguments).slice(1) var exc=_b_.BaseException.__new__(cls,...args) exc.message=$.message exc.exceptions=exceptions return exc} _b_.BaseExceptionGroup.__bases__=[_b_.BaseException] _b_.BaseExceptionGroup.__class_getitem__=$B.$class_getitem _b_.BaseExceptionGroup.__mro__=_b_.type.$mro(_b_.BaseExceptionGroup) _b_.BaseExceptionGroup.__str__=function(self){return `${self.message} (${self.exceptions.length} sub-exception`+ `${self.exceptions.length > 1 ? 's' : ''})`} _b_.BaseExceptionGroup.split=function(self,condition){ var matching_excs=[],non_matching_excs=[] for(var exc of self.exceptions){if($B.$isinstance(exc,_b_.BaseExceptionGroup)){var subsplit=_b_.BaseExceptionGroup.split(exc,condition),matching=subsplit[0],non_matching=subsplit[1] if(matching===_b_.None){non_matching_excs.push(exc)}else if(matching.exceptions.length==exc.exceptions.length){matching_excs.push(exc)}else{if(matching.exceptions.length > 0){matching_excs=matching_excs.concat(matching)} if(non_matching.exceptions.length > 0){non_matching_excs=non_matching_excs.concat(non_matching)}}}else if(condition(exc)){matching_excs.push(exc)}else{non_matching_excs.push(exc)}} if(matching_excs.length==0){matching_excs=_b_.None} if(non_matching_excs.length==0){non_matching_excs=_b_.None} var res=[] for(var item of[matching_excs,non_matching_excs]){var eg=_b_.BaseExceptionGroup.$factory(self.message,item) eg.__cause__=self.__cause__ eg.__context__=self.__context__ eg.__traceback__=self.__traceback__ res.push(eg)} return $B.fast_tuple(res)} _b_.BaseExceptionGroup.subgroup=function(self,condition){return _b_.BaseExceptionGroup.split(self,condition)[0]} $B.set_func_names(_b_.BaseExceptionGroup,"builtins") _b_.BaseExceptionGroup.__class_getitem__= _b_.classmethod.$factory(_b_.BaseExceptionGroup.__class_getitem__) _b_.ExceptionGroup=$B.make_class("ExceptionGroup",function(){var missing={},$=$B.args("ExceptionGroup",2,{message:null,exceptions:null},['message','exceptions'],arguments,{exceptions:missing},null,null) var err=Error() err.args=$B.fast_tuple(Array.from(arguments)) err.__class__=_b_.ExceptionGroup err.__traceback__=_b_.None err.$py_error=true err.message=$.message err.exceptions=$.exceptions===missing ?[]:$.exceptions if(err.exceptions !==_b_.None){var exc_list=_b_.list.$factory(err.exceptions) for(var exc of exc_list){if(! $B.$isinstance(exc,_b_.Exception)){$B.RAISE(_b_.TypeError,'Cannot nest BaseExceptions in an ExceptionGroup')}}} err.__cause__=_b_.None err.__context__=_b_.None err.__suppress_context__=false return err} ) _b_.ExceptionGroup.__bases__=[_b_.BaseExceptionGroup,_b_.Exception] _b_.ExceptionGroup.__mro__=_b_.type.$mro(_b_.ExceptionGroup) $B.set_func_names(_b_.ExceptionGroup,"builtins") function make_report(lines,positions){ var[lineno,end_lineno,col_offset,end_col_offset]=positions lines=lines.slice(lineno-1,end_lineno) var min_indent=get_min_indent(lines) lines=lines.map(line=> ' '+line.substr(min_indent).trimRight()) if(lines.length > 3){lines=[lines[0],` ...<${lines.length - 2} lines>...`,lines[lines.length-1]]} return lines.join('\n')} function make_trace_lines(lines,lineno,expr){ var line_start=expr.lineno+lineno-2 var line_end=expr.end_lineno+lineno-2 return make_report(lines,[line_start,line_end,expr.col_offset,expr.end_col_offset])} function get_indent(line){return line.length-line.trimLeft().length} function get_min_indent(lines){var min_indent=2**16 for(var line of lines){if(! line.trim()){continue} var indent=get_indent(line) if(indent < min_indent){min_indent=indent}} return min_indent} function fill_marks(lines,first_lineno,first_col_offset){ var args=Array.from(arguments).slice(3) var start_lineno=first_lineno var start_col_offset=first_col_offset var marks=' '.repeat(first_col_offset) var line var indent for(var i=0;i < args.length;i+=3){var[mark,lineno,col_offset]=args.slice(i,i+3) if(lineno==start_lineno){marks+=mark.repeat(col_offset-start_col_offset)}else{line=lines[start_lineno-1] marks+=mark.repeat(line.length-start_col_offset)+'\n' for(var lnum=start_lineno+1;lnum < lineno;lnum++){line=lines[lnum-1].trimRight() indent=get_indent(line) marks+=' '.repeat(indent)+mark.repeat(line.length-indent)+'\n'} line=lines[lineno-1].trimRight() indent=get_indent(line) marks+=' '.repeat(indent)+mark.repeat(col_offset-indent)} start_lineno=lineno start_col_offset=col_offset} var marks_lines=marks.split('\n') var min_indent=get_min_indent(lines.slice(first_lineno-1,lineno)) var err_lines=[] for(var lnum=0;lnum < marks_lines.length;lnum++){err_lines.push(' '+ lines[first_lineno+lnum-1].trimRight().substr(min_indent)) err_lines.push(' '+marks_lines[lnum].substr(min_indent))} return err_lines.join('\n')} function make_line_setter(lineno){ return function(coords){return{ lineno:coords.lineno+lineno-2,end_lineno:coords.end_lineno+lineno-2,col_offset:coords.col_offset,end_col_offset:coords.end_col_offset}}} function handle_BinOp_error(lines,lineno,ast_obj,tokens){ var reset_lineno=make_line_setter(lineno) var operator for(var token of tokens){if(token.type==$B.py_tokens.OP){if(is_before(ast_obj.right,token.lineno,token.col_offset) && token.string !='('){operator=reset_lineno(token)}}} var end_binop=reset_lineno(tokens[tokens.length-1]) var left=reset_lineno(ast_obj.left) return fill_marks(lines,lineno,left.col_offset,'~',operator.lineno,operator.col_offset,'^',operator.end_lineno,operator.end_col_offset,'~',end_binop.end_lineno,end_binop.end_col_offset)} function handle_Call_error(lines,lineno,ast_obj,tokens){ var reset_lineno=make_line_setter(lineno) var opening_parenth var closing_parenth for(var token of tokens){if(token.type==$B.py_tokens.OP){if(token.string=='(' && ! opening_parenth && token.lineno==ast_obj.func.end_lineno && token.col_offset >=ast_obj.func.end_col_offset){opening_parenth=reset_lineno(token)}else if(token.string==')'){closing_parenth=reset_lineno(token)}}} var func=reset_lineno(ast_obj.func) return fill_marks(lines,lineno,func.col_offset,'~',opening_parenth.lineno,opening_parenth.col_offset,'^',closing_parenth.end_lineno,closing_parenth.end_col_offset)} function handle_Expr_error(lines,lineno,ast_obj){var reset_lineno=make_line_setter(lineno) var expr=reset_lineno(ast_obj) return fill_marks(lines,lineno,expr.col_offset,'^',expr.end_lineno,expr.end_col_offset)} function is_before(obj,lineno,col){ return lineno < obj.lineno || (lineno==obj.lineno && col < obj.col_offset)} function handle_Subscript_error(lines,lineno,ast_obj,tokens){ var reset_lineno=make_line_setter(lineno) for(var token of tokens){if(token.type==$B.py_tokens.OP){if(token.string=='[' && is_before(ast_obj.slice,token.lineno,token.col_offset)){var opening_bracket=reset_lineno(token)}else if(token.string==']'){var closing_bracket=reset_lineno(token)}}} var value=reset_lineno(ast_obj.value) return fill_marks(lines,lineno,value.col_offset,'~',opening_bracket.lineno,opening_bracket.col_offset,'^',closing_bracket.end_lineno,closing_bracket.end_col_offset)} function trace_from_stack(err){function handle_repeats(src,count_repeats){if(count_repeats > 0){var len=trace.length for(var i=0;i < 2;i++){if(src){trace.push(trace[len-2]) trace.push(trace[len-1])}else{trace.push(trace[len-1])} count_repeats-- if(count_repeats==0){break}} if(count_repeats > 0){trace.push(`[Previous line repeated ${count_repeats} more`+ ` time${count_repeats > 1 ? 's' : ''}]`)}}} var trace=[],save_filename,save_lineno,save_scope,count_repeats=0,tb=err.__traceback__ var is_syntax_error=$B.is_exc(err,[_b_.SyntaxError]) while(tb !==_b_.None){let frame=tb.tb_frame,lineno=tb.tb_lineno,filename=frame.__file__,scope=frame[0]==frame[2]? '' :frame[0] if(filename==save_filename && scope==save_scope && lineno==save_lineno){count_repeats++ tb=tb.tb_next continue} handle_repeats(src,count_repeats) save_filename=filename save_lineno=lineno save_scope=scope count_repeats=0 trace.push(` File "${filename}", line ${lineno}, in `+ (frame[0]==frame[2]? '' :frame[0])) var src if(! filename.startsWith('<')){src=$B.file_cache[filename]} if(src){var lines=src.split('\n') var positions=false if(! is_syntax_error && frame.inum && frame.positions){positions=$B.decode_position( frame.positions[Math.floor(frame.inum/2)])} if(positions){let[lineno,end_lineno,col_offset,end_col_offset]=positions if(lines[lineno-1]===undefined){console.log('no line, lines\n',lines,'lineno',lineno) console.log('filename',filename,'src',src) continue} var head=lines[lineno-1].substr(0,col_offset) var segment=' '.repeat(col_offset) if(lineno==end_lineno){segment+=lines[lineno-1].substring(col_offset,end_col_offset)}else{segment+=lines[lineno-1].substr(col_offset)+'\n' for(var lnum=lineno+1;lnum < end_lineno;lnum++){segment+=lines[lnum-1]+'\n'} segment+=lines[end_lineno-1].substr(0,end_col_offset)} try{let parser=new $B.Parser(`(\n${segment}\n)`,'test','file') var ast=$B._PyPegen.run_parser(parser) var tokens=parser.tokens tokens=tokens.slice(1,tokens.length-3)}catch(err){ trace.push(make_report(lines,positions)) tb=tb.tb_next continue} if(!(ast instanceof $B.ast.Module)){console.log('not a module',ast) continue} var expr=ast.body[0] var marks='' switch(expr.constructor){case $B.ast.Expr: try{switch(expr.value.constructor){case $B.ast.BinOp: trace.push(handle_BinOp_error( lines,lineno,expr.value,tokens)) break case $B.ast.Call: trace.push(handle_Call_error( lines,lineno,expr.value,tokens)) break case $B.ast.Subscript: trace.push(handle_Subscript_error( lines,lineno,expr.value,tokens)) break default: trace.push(handle_Expr_error( lines,lineno,expr.value)) break}}catch(err){if($B.get_option('debug')> 1){console.log('error in error handlers',err)} trace.push(make_trace_lines(lines,lineno,expr))} break default: trace.push(make_trace_lines(lines,lineno,expr))}}else{trace.push(' '+lines[lineno-1].trim())}}else{if($B.get_option('debug')> 1){console.log('no src for filename',filename)}} tb=tb.tb_next} if(count_repeats > 1){let len=trace.length for(let i=0;i < 2;i++){if(src){trace.push(trace[len-2]) trace.push(trace[len-1])}else{trace.push(trace[len-1])}} trace.push(`[Previous line repeated ${count_repeats - 2} more times]`)} return trace.join('\n')+'\n'} var python_keywords function _find_keyword_typos(err){ if(err.msg !="invalid syntax" && ! err.msg.includes("Perhaps you forgot a comma")){return} let[line,offset,source]=err._metadata let end_line=self.lineno===_b_.None ? 0 :self.lineno let lines=source.split('\n') var error_code if(line > 0){error_code=[lines[line-1]]}else{error_code=lines.slice(0,end_line)} var indent=Math.min(...error_code.map(x=> x.length-x.trimLeft().length)) var error_code_lines=error_code.map(x=> x.substr(indent)) error_code=error_code_lines.join('\n') if(error_code.length > 1024){return} if(python_keywords===undefined){python_keywords=Object.keys($B.python_keywords)} for(let token of $B.tokenizer(error_code,'','exec')){if(token.type==$B.py_tokens['NAME']){if(python_keywords.includes(token.string)){continue} var suggestions=calculate_suggestions(python_keywords,token.string) if(suggestions){console.log(token.lineno) var new_line=token.line.substr(0,token.col_offset)+ suggestions+token.line.substr(token.end_col_offset) var new_lines=error_code_lines.slice() new_lines.splice(token.lineno-1,1,new_line) var candidate=new_lines.join('\n') var found=false try{var parser=new $B.Parser(candidate,'','file') parser.flags=$B.PyCF_ALLOW_INCOMPLETE_INPUT var _ast=$B._PyPegen.run_parser(parser) found=true}catch(err){if($B.is_exc(err,[_b_._IncompleteInputError])){found=true}} if(found){err.args[1][2]=err.offset=token.col_offset err.args[1][5]=err.end_offset=token.end_col_offset err.args[0]=err.msg=`invalid syntax. Did you mean '${suggestions}'?` return}}}}} $B.error_trace=function(err){var trace='',has_stack=err.__traceback__ !==_b_.None var debug=$B.get_option('debug',err) if(debug > 1){console.log("handle error",err.__class__,err.args,err.__traceback__)} if(has_stack){trace='Traceback (most recent call last):\n'} if(err.__class__===_b_.SyntaxError || err.__class__===_b_.IndentationError){trace+=trace_from_stack(err) if(err.args.length > 0){var filename=err.filename,line=err.text if(line !==_b_.None){var indent=line.length-line.trimLeft().length trace+=` File "${filename}", line ${err.args[1][1]}\n`+ ` ${line.trim()}\n`}} if(err.__class__ !==_b_.IndentationError && err.text && err.text !==_b_.None){if(err._metadata){_find_keyword_typos(err)} if($B.get_option('debug')> 2){console.log('debug from error',$B.get_option('debug',err)) console.log('error args',err.args[1]) console.log('err line',line) console.log('indent',indent)} var end_lineno=err.end_lineno===_b_.None ? err.lineno :err.end_lineno var end_offset=err.end_offset===_b_.None ? err.offset :err.end_offset var start=err.offset-indent-1,end_offset=end_offset-1+ (end_offset==err.offset ? 1 :0),marks=' '+' '.repeat(Math.max(0,start)),nb_marks=1 if(end_lineno > err.lineno){nb_marks=line.length-start-indent}else{nb_marks=end_offset-start-indent} if(nb_marks==0 && end_offset==line.substr(indent).length){nb_marks=1} marks+='^'.repeat(nb_marks)+'\n' trace+=marks} trace+=`${err.__class__.__name__}: ${err.args[0] ?? ''}`}else if(err.__class__ !==undefined){var name=$B.class_name(err) trace+=trace_from_stack(err) var args_str=_b_.str.$factory(err) trace+=name+(args_str ? ': '+args_str :'') if(err.__class__===_b_.NameError){let suggestion=$B.offer_suggestions_for_name_error(err) if(suggestion !==_b_.None && suggestion !==err.name){trace+=`. Did you mean: '${suggestion}'?`} if($B.stdlib_module_names.indexOf(err.name)>-1){ trace+=`. Did you forget to import '${err.name}'?`}}else if(err.__class__===_b_.AttributeError){let suggestion=$B.offer_suggestions_for_attribute_error(err) if(suggestion !==_b_.None){trace+=`. Did you mean: '${suggestion}'?`}}else if(err.__class__===_b_.ImportError){if(err.$suggestion !==_b_.None){trace+=`. Did you mean: '${err.$suggestion}'?`}}}else{trace=err+""} if(err.$js_exc){trace+='\n' if($B.get_option('debug',err)> 1){trace+=err.$js_exc.stack}} return trace} $B.get_stderr=function(){return $B.imported.sys ? $B.imported.sys.stderr :$B.imported._sys.stderr} $B.get_stdout=function(){return $B.imported.sys ? $B.imported.sys.stdout :$B.imported._sys.stdout} $B.show_error=function(err){if($B.get_option('debug',err)> 2){console.debug(err.stack)} var trace=$B.error_trace($B.exception(err)) try{var stderr=$B.get_stderr() $B.$getattr(stderr,'write')(trace) var flush=$B.$getattr(stderr,'flush',_b_.None) if(flush !==_b_.None){flush()}}catch(print_exc_err){console.debug(trace)}} $B.handle_error=function(err){ console.log('handle error',$B.frame_obj) if(err.$handled){return} err.$handled=true $B.show_error(err) throw err}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,None=_b_.None,range={__class__:_b_.type,__mro__:[_b_.object],__qualname__:'range',$is_class:true,$native:true,$match_sequence_pattern:true, $is_sequence:true,$not_basetype:true, $descriptors:{start:true,step:true,stop:true}} range.__contains__=function(self,other){if(range.__len__(self)==0){return false} try{other=$B.int_or_bool(other)}catch(err){ try{range.index(self,other) return true}catch(err){return false}} var start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step) other=_b_.int.$to_bigint(other) var sub=other-start,fl=sub/step,res=step*fl if(res==sub){if(stop > start){return other >=start && stop > other}else{return start >=other && other > stop}}else{return false}} range.__delattr__=function(self,attr){$B.RAISE_ATTRIBUTE_ERROR("readonly attribute",self,attr)} range.__eq__=function(self,other){if($B.$isinstance(other,range)){var len=range.__len__(self) if(! $B.rich_comp('__eq__',len,range.__len__(other))){return false} if(len==0){return true} if(! $B.rich_comp('__eq__',self.start,other.start)){return false} if(len==1){return true} return $B.rich_comp('__eq__',self.step,other.step)} return false} function compute_item(r,i){var len=range.__len__(r) if(len==0){return r.start}else if(i > len){return r.stop} return $B.rich_op('__add__',r.start,$B.rich_op('__mul__',r.step,i))} range.__getitem__=function(self,rank){if($B.$isinstance(rank,_b_.slice)){var norm=_b_.slice.$conv_for_seq(rank,range.__len__(self)),substep=$B.rich_op('__mul__',self.step,norm.step),substart=compute_item(self,norm.start),substop=compute_item(self,norm.stop) return range.$factory(substart,substop,substep)} try{rank=$B.PyNumber_Index(rank)}catch(err){$B.RAISE(_b_.TypeError,"range indices must be integers "+ `or slices, not ${$B.class_name(rank)}`)} if($B.rich_comp('__gt__',0,rank)){rank=$B.rich_op('__add__',rank,range.__len__(self))} var res=$B.rich_op('__add__',self.start,$B.rich_op('__mul__',rank,self.step)) if(($B.rich_comp('__gt__',self.step,0)&& ($B.rich_comp('__ge__',res,self.stop)|| $B.rich_comp('__gt__',self.start,res)))|| ($B.rich_comp('__gt__',0,self.step)&& ($B.rich_comp('__ge__',self.stop,res)|| $B.rich_comp('__gt__',res,self.start)))){$B.RAISE(_b_.IndexError,"range object index out of range")} return res} range.__hash__=function(self){var len=range.__len__(self) if(len==0){return _b_.hash(_b_.tuple.$factory([0,None,None]))} if(len==1){return _b_.hash(_b_.tuple.$factory([1,self.start,None]))} return _b_.hash(_b_.tuple.$factory([len,self.start,self.step]))} var RangeIterator=$B.make_class("range_iterator",function(obj){return{__class__:RangeIterator,obj:obj}} ) RangeIterator.__iter__=function(self){return self} RangeIterator.__next__=function(self){return _b_.next(self.obj)} $B.set_func_names(RangeIterator,"builtins") range.__iter__=function(self){var res={__class__ :range,start:self.start,stop:self.stop,step:self.step} if(self.$safe){res.$counter=self.start-self.step}else{res.$counter=$B.rich_op('__sub__',self.start,self.step)} return RangeIterator.$factory(res)} range.__len__=function(self){var len,start=_b_.int.$to_bigint(self.start),stop=_b_.int.$to_bigint(self.stop),step=_b_.int.$to_bigint(self.step) if(self.step > 0){if(self.start >=self.stop){return 0} len=1n+(stop-start-1n)/step}else{if(self.stop >=self.start){return 0} len=1n+(start-stop-1n)/-step} return _b_.int.$int_or_long(len)} range.__next__=function(self){if(self.$safe){self.$counter+=self.step if((self.step > 0 && self.$counter >=self.stop) ||(self.step < 0 && self.$counter <=self.stop)){$B.RAISE(_b_.StopIteration,"")}}else{self.$counter=$B.rich_op('__add__',self.$counter,self.step) if(($B.rich_comp('__gt__',self.step,0)&& $B.rich_comp('__ge__',self.$counter,self.stop)) ||($B.rich_comp('__gt__',0,self.step)&& $B.rich_comp('__ge__',self.stop,self.$counter))){$B.RAISE(_b_.StopIteration,"")}} return self.$counter} range.__reversed__=function(self){var n=$B.rich_op('__sub__',range.__len__(self),1) return range.$factory($B.rich_op('__add__',self.start,$B.rich_op('__mul__',n,self.step)),$B.rich_op('__sub__',self.start,self.step),$B.rich_op('__mul__',-1,self.step))} range.__repr__=function(self){$B.builtins_repr_check(range,arguments) var res="range("+_b_.str.$factory(self.start)+", "+ _b_.str.$factory(self.stop) if(self.step !=1){res+=", "+_b_.str.$factory(self.step)} return res+")"} range.__setattr__=function(self,attr){$B.RAISE_ATTRIBUTE_ERROR("readonly attribute",self,attr)} range.start=function(self){return self.start} range.step=function(self){return self.step},range.stop=function(self){return self.stop} 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 while(true){try{if(comp(_next(it))){nb++}}catch(err){if($B.$isinstance(err,_b_.StopIteration)){return nb} throw err}}}} range.index=function(){var $=$B.args("index",2,{self:null,other:null},["self","other"],arguments,{},null,null),self=$.self,other=$.other 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 while(true){try{if(comp(_next(it))){return nb} nb++}catch(err){if($B.$isinstance(err,_b_.StopIteration)){$B.RAISE(_b_.ValueError,_b_.str.$factory(other)+ " not in range")} throw err}}} var sub=$B.rich_op('__sub__',other,self.start),fl=$B.rich_op('__floordiv__',sub,self.step),res=$B.rich_op('__mul__',self.step,fl) if($B.rich_comp('__eq__',res,sub)){if(($B.rich_comp('__gt__',self.stop,self.start)&& $B.rich_comp('__ge__',other,self.start)&& $B.rich_comp('__gt__',self.stop,other))|| ($B.rich_comp('__ge__',self.start,self.stop)&& $B.rich_comp('__ge__',self.start,other) && $B.rich_comp('__gt__',other,self.stop))){return fl}else{$B.RAISE(_b_.ValueError,_b_.str.$factory(other)+ ' not in range')}}else{$B.RAISE(_b_.ValueError,_b_.str.$factory(other)+ " not in range")}} 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 if(stop===null && step===null){if(start==null){$B.RAISE(_b_.TypeError,"range expected 1 arguments, got 0")} stop=$B.PyNumber_Index(start) safe=typeof stop==="number" return{__class__:range,start:0,stop:stop,step:1,$is_range:true,$safe:safe}} if(step===null){step=1} start=$B.PyNumber_Index(start) stop=$B.PyNumber_Index(stop) step=$B.PyNumber_Index(step) if(step==0){$B.RAISE(_b_.ValueError,"range arg 3 must not be zero")} safe=(typeof start=="number" && typeof stop=="number" && typeof step=="number") return{__class__:range,start:start,stop:stop,step:step,$is_range:true,$safe:safe}} $B.set_func_names(range,"builtins") var slice={__class__:_b_.type,__mro__:[_b_.object],__qualname__:'slice',$is_class:true,$native:true,$not_basetype:true, $descriptors:{start:true,step:true,stop:true}} slice.__eq__=function(self,other){var conv1=conv_slice(self),conv2=conv_slice(other) return conv1[0]==conv2[0]&& conv1[1]==conv2[1]&& conv1[2]==conv2[2]} slice.__repr__=function(self){$B.builtins_repr_check(slice,arguments) return "slice("+_b_.str.$factory(self.start)+", "+ _b_.str.$factory(self.stop)+", "+_b_.str.$factory(self.step)+")"} slice.__setattr__=function(self,attr){$B.RAISE_ATTRIBUTE_ERROR("readonly attribute",self,attr)} function conv_slice(self){var attrs=["start","stop","step"],res=[] for(var i=0;i < attrs.length;i++){var val=self[attrs[i]] if(val===_b_.None){res.push(val)}else{try{res.push($B.PyNumber_Index(val))}catch(err){$B.RAISE(_b_.TypeError,"slice indices must be "+ "integers or None or have an __index__ method")}}} return res} slice.$conv_for_seq=function(self,len){ var step=self.step===None ? 1 :$B.PyNumber_Index(self.step),step_is_neg=$B.rich_comp('__gt__',0,step),len_1=$B.rich_op('__sub__',len,1) if(step==0){$B.RAISE(_b_.ValueError,'slice step cannot be zero')} var start,stop if(self.start===None){start=step_is_neg ? len_1 :0}else{start=$B.PyNumber_Index(self.start) if($B.rich_comp('__gt__',0,start)){start=$B.rich_op('__add__',start,len) if($B.rich_comp('__gt__',0,start)){start=0}} if($B.rich_comp('__ge__',start,len)){start=step < 0 ? len_1 :len}} if(self.stop===None){stop=step_is_neg ?-1 :len}else{stop=$B.PyNumber_Index(self.stop) if($B.rich_comp('__gt__',0,stop)){stop=$B.rich_op('__add__',stop,len)} if($B.rich_comp('__ge__',stop,len)){stop=step_is_neg ? len_1 :len}} return{start:start,stop:stop,step:step}} slice.start=function(self){return self.start} slice.step=function(self){return self.step} slice.stop=function(self){return self.stop} slice.indices=function(self){ var $=$B.args("indices",2,{self:null,length:null},["self","length"],arguments,{},null,null) var len=$B.PyNumber_Index($.length) if(len < 0){$B.RAISE(_b_.ValueError,"length should not be negative")} var _step=(self.step==_b_.None)? 1 :self.step,_start,_stop if(_step < 0){_start=self.start _stop=self.stop _start=(_start==_b_.None)? len-1 : (_start < 0)? _b_.max(-1,_start+len):_b_.min(len-1,self.start) _stop=(self.stop==_b_.None)?-1 : (_stop < 0)? _b_.max(-1,_stop+len):_b_.min(len-1,self.stop)}else{_start=(self.start==_b_.None)? 0 :_b_.min(len,self.start) _stop=(self.stop==_b_.None)? len :_b_.min(len,self.stop) if(_start < 0){_start=_b_.max(0,_start+len)} if(_stop < 0){_stop=_b_.max(0,_stop+len)}} return _b_.tuple.$factory([_start,_stop,_step])} slice.$fast_slice=function(start,stop,step){return{__class__:_b_.slice,start,stop,step}} slice.$factory=function(){var $=$B.args("slice",3,{start:null,stop:null,step:null},["start","stop","step"],arguments,{stop:null,step:null},null,null) return slice.$fast_slice($.start,$.stop,$.step)} slice.$fast_slice=function(start,stop,step){if(stop===null && step===null){stop=start start=_b_.None step=_b_.None}else{step=step===null ? _b_.None :step} var res={__class__ :slice,start:start,stop:stop,step:step} conv_slice(res) return res} $B.set_func_names(slice,"builtins") _b_.range=range _b_.slice=slice})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var from_unicode={},to_unicode={} function bytes_value(obj){return obj.__class__===bytes ? obj :fast_bytes(obj.source)} $B.to_bytes=function(obj){var res if($B.$isinstance(obj,[bytes,bytearray])){res=obj.source}else{var ga=$B.$getattr(obj,"tobytes",null) if(ga !==null){res=$B.$call(ga)().source}else{$B.RAISE(_b_.TypeError,"object doesn't support the buffer protocol")}} return res} function _strip(self,cars,lr){if(cars===undefined){cars=[] var ws='\r\n \t' for(let i=0,len=ws.length;i < len;i++){cars.push(ws.charCodeAt(i))}}else if($B.$isinstance(cars,bytes)){cars=cars.source}else{$B.RAISE(_b_.TypeError,"Type str doesn't support the buffer API")} if(lr=='l'){let i,len for(i=0,len=self.source.length;i < len;i++){if(cars.indexOf(self.source[i])==-1){break}} return bytes.$factory(self.source.slice(i))} let i for(i=self.source.length-1;i >=0;i--){if(cars.indexOf(self.source[i])==-1){break}} return bytes.$factory(self.source.slice(0,i+1))} function invalid(other){return ! $B.$isinstance(other,[bytes,bytearray])} var bytearray={__class__:_b_.type,__mro__:[_b_.object],__qualname__:'bytearray',$buffer_protocol:true,$is_sequence:true,$is_class:true} var mutable_methods=["copy","count","index","remove","reverse"] for(var method of mutable_methods){bytearray[method]=(function(m){return function(self){var args=[self.source],pos=1 for(var i=1,len=arguments.length;i < len;i++){args[pos++]=arguments[i]} return _b_.list[m].apply(null,args)}})(method)} function no_resizing(){$B.RAISE(_b_.BufferError,"Existing exports of data: object cannot be re-sized")} bytearray.__add__=function(self,other){try{var other_bytes=$B.to_bytes(other)}catch(err){$B.RAISE(_b_.TypeError,`can't concat ${$B.class_name(other)} to bytes`)} if(other_bytes.length > 0){check_exports(self)} return{ __class__:self.__class__,source:self.source.concat(other_bytes)}} bytearray.__delitem__=function(self,arg){if(self.$exports){if($B.$isinstance(arg,_b_.slice)){var slice=_b_.slice.$conv_for_seq(arg,self.source.length) if(slice.stop-slice.start > 0){no_resizing()}}else{no_resizing()}} return _b_.list.__delitem__(self.source,arg)} bytearray.__hash__=_b_.None var bytearray_iterator=$B.make_iterator_class('bytearray_iterator') bytearray.__iter__=function(self){return bytearray_iterator.$factory(self.source)} bytearray.__mro__=[_b_.object] bytearray.__repr__=bytearray.__str__=function(self){return 'bytearray('+bytes.__repr__(self)+")"} function check_exports(self){if(self.$exports==0){return} var frame_obj=$B.frame_obj var has_exports=false while(frame_obj !==null){var locals=frame_obj.frame[1] for(var key in locals){try{var value=locals[key] if(value.__class__===_b_.memoryview && value.obj===self){has_exports=true break}}catch(err){}} frame_obj=frame_obj.prev} if(has_exports){if(self.$exports){no_resizing()}}else{ self.$exports=0}} bytearray.__setitem__=function(self,arg,value){if($B.$isinstance(arg,_b_.int)){if(! $B.$isinstance(value,_b_.int)){$B.RAISE(_b_.TypeError,'an integer is required')}else if(value > 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} var pos=arg if(arg < 0){pos=self.source.length+pos} if(pos >=0 && pos < self.source.length){self.source[pos]=value}else{$B.RAISE(_b_.IndexError,'list index out of range')}}else if($B.$isinstance(arg,_b_.slice)){var start=arg.start===_b_.None ? 0 :arg.start var stop=arg.stop===_b_.None ? self.source.length :arg.stop if(start < 0){start=self.source.length+start} if(stop < 0){stop=self.source.length+stop} if(stop > self.source.length){check_exports(self)} self.source.splice(start,stop-start) try{var $temp=_b_.list.$factory(value)}catch(err){$B.RAISE(_b_.TypeError,"can only assign an iterable")} if($temp.length !=stop-start){check_exports(self)} for(var i=$temp.length-1;i >=0;i--){if(! $B.$isinstance($temp[i],_b_.int)){$B.RAISE(_b_.TypeError,'an integer is required')}else if($temp[i]> 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} self.source.splice(start,0,$temp[i])}}else{$B.RAISE(_b_.TypeError,'list indices must be integer, not '+ $B.class_name(arg))}} bytearray.append=function(self,b){check_exports(self) if(arguments.length !=2){$B.RAISE(_b_.TypeError,"append takes exactly one argument ("+(arguments.length-1)+ " given)")} if(! $B.$isinstance(b,_b_.int)){$B.RAISE(_b_.TypeError,"an integer is required")} if(b > 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} self.source[self.source.length]=b} bytearray.clear=function(self){check_exports(self) self.source=[]} bytearray.extend=function(self,b){check_exports(self) if(self.in_iteration){ no_resizing()} if(b.__class__===bytearray ||b.__class__===bytes){self.source=self.source.concat(b.source) return _b_.None} for(var item of $B.make_js_iterator(b)){bytearray.append(self,$B.PyNumber_Index(item))} return _b_.None} bytearray.insert=function(self,pos,b){check_exports(self) if(arguments.length !=3){$B.RAISE(_b_.TypeError,"insert takes exactly 2 arguments ("+(arguments.length-1)+ " given)")} if(! $B.$isinstance(b,_b_.int)){$B.RAISE(_b_.TypeError,"an integer is required")} if(b > 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} _b_.list.insert(self.source,pos,b)} bytearray.pop=function(self){check_exports(self) var args=[self.source].concat(Array.from(arguments).slice(1)) return _b_.list.pop.apply(null,args)} bytearray.resize=function(self,size){check_exports(self) size=$B.PyNumber_Index(size) if(size < 0){$B.RAISE(_b_.ValueError,`Can only resize to positive sizes, got -${size}`)} if(size > self.source.length){for(var i=0,len=size-self.source.length;i < len;i++){self.source.push(0)}}else{self.source=self.source.slice(0,size)} return _b_.None} bytearray.$factory=function(){var args=[bytearray] for(var i=0,len=arguments.length;i < len;i++){args.push(arguments[i])} var res=bytearray.__new__.apply(null,args) res.$exports=0 return res} var bytes={__class__ :_b_.type,__mro__:[_b_.object],__qualname__:'bytes',$buffer_protocol:true,$is_sequence:true,$is_class:true} bytes.__add__=function(self,other){try{var other_bytes=$B.to_bytes(other) return{ __class__:self.__class__,source:self.source.concat(other_bytes)}}catch(err){$B.RAISE(_b_.TypeError,"can't concat str to bytes")}} bytes.__buffer__=function(_self,flags){return $B.$call(_b_.memoryview)(_self)} bytes.__bytes__=function(self){return self} bytes.__contains__=function(self,other){if(typeof other=="number"){return self.source.indexOf(other)>-1} if(self.source.length < other.source.length){return false} var len=other.source.length for(var i=0;i < self.source.length-other.source.length+1;i++){var flag=true for(var j=0;j < len;j++){if(other.source[i+j]!=self.source[j]){flag=false break}} if(flag){return true}} return false} var bytes_iterator=$B.make_iterator_class("bytes_iterator") bytes.__iter__=function(self){return bytes_iterator.$factory(self.source)} bytes.__eq__=function(self,other){if(invalid(other)){return false} if(self.source.length !==other.source.length){return false} for(var i=0,len=self.source.length;i < len;i++){if(self.source[i]!==other.source[i]){return false}} return true} bytes.__ge__=function(self,other){if(invalid(other)){return _b_.NotImplemented} return _b_.list.__ge__(self.source,other.source)} bytes.__getitem__=function(self,arg){if($B.$isinstance(arg,_b_.int)){let pos=arg if(arg < 0){pos=self.source.length+pos} if(pos >=0 && pos < self.source.length){return self.source[pos]} $B.RAISE(_b_.IndexError,"index out of range")}else if($B.$isinstance(arg,_b_.slice)){let s=_b_.slice.$conv_for_seq(arg,self.source.length),start=s.start,stop=s.stop,step=s.step let res=[],pos=0 if(step > 0){stop=Math.min(stop,self.source.length) if(stop <=start){return bytes.$factory([])} for(let i=start;i < stop;i+=step){res[pos++]=self.source[i]}}else{if(stop >=start){return bytes.$factory([])} stop=Math.max(0,stop) for(let i=start;i >=stop;i+=step){res[pos++]=self.source[i]}} return bytes.$factory(res)}else if($B.$isinstance(arg,_b_.bool)){return self.source.__getitem__(_b_.int.$factory(arg))}} bytes.$getnewargs=function(self){return $B.fast_tuple([bytes_value(self)])} bytes.__getnewargs__=function(){return bytes.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} bytes.__gt__=function(self,other){if(invalid(other)){return _b_.NotImplemented} return _b_.list.__gt__(self.source,other.source)} bytes.__hash__=function(self){if(self===undefined){return bytes.__hashvalue__ ||$B.$py_next_hash--} var hash=1 for(var i=0,len=self.source.length;i < len;i++){hash=(101*hash+self.source[i])& 0xFFFFFFFF} return hash} bytes.__init__=function(){return _b_.None} bytes.__le__=function(self,other){if(invalid(other)){return _b_.NotImplemented} return _b_.list.__le__(self.source,other.source)} bytes.__len__=function(self){return self.source.length} bytes.__lt__=function(self,other){if(invalid(other)){return _b_.NotImplemented} return _b_.list.__lt__(self.source,other.source)} bytes.__mod__=function(self,args){ var s=decode(self,"latin-1","strict"),res=$B.printf_format(s,'bytes',args) return _b_.str.encode(res,"ascii")} bytes.__mul__=function(){var $=$B.args('__mul__',2,{self:null,other:null},['self','other'],arguments,{},null,null),other=$B.PyNumber_Index($.other) var t=[],source=$.self.source,slen=source.length for(var i=0;i < other;i++){for(var j=0;j < slen;j++){t.push(source[j])}} var res=bytes.$factory() res.source=t return res} bytes.__ne__=function(self,other){return ! bytes.__eq__(self,other)} bytes.__new__=function(){var missing={},$=$B.args("__new__",4,{cls:null,source:null,encoding:null,errors:null},["cls","source","encoding","errors"],arguments,{source:missing,encoding:missing,errors:missing},null,null),source=$.source if($.source===missing){return{ __class__:$.cls,source:[]}}else if(typeof $.source=="string" ||$B.$isinstance($.source,_b_.str)){if($.encoding===missing){$B.RAISE(_b_.TypeError,'string argument without an encoding')} $.errors=$.errors===missing ? 'strict' :$.errors let res=encode($.source,$.encoding,$.errors) if(! $B.$isinstance(res,bytes)){$B.RAISE(_b_.TypeError,`'${$.encoding}' codec returns `+ `${$B.class_name(res)}, not bytes`)} res.__class__=$.cls return res} if($.encoding !==missing){$B.RAISE(_b_.TypeError,"encoding without a string argument")} if(typeof $.source=="number" ||$B.$isinstance($.source,_b_.int)){var size=$B.PyNumber_Index($.source) source=[] for(var i=0;i < size;i++){source[i]=0}}else if($B.$isinstance($.source,[_b_.bytes,_b_.bytearray])){source=$.source.source}else if($B.$isinstance($.source,_b_.memoryview)){source=$.source.obj.source}else if($B.imported.array && $B.$isinstance($.source,$B.imported.array.array)){source=$B.imported.array.array.tobytes($.source).source}else{var int_list if(Array.isArray($.source)){int_list=$.source}else{try{int_list=_b_.list.$factory($.source)}catch(err){var bytes_method=$B.$getattr(source,'__bytes__',_b_.None) if(bytes_method===_b_.None){$B.RAISE(_b_.TypeError,"cannot convert "+ `'${$B.class_name(source)}' object to bytes`)} let res=$B.$call(bytes_method)() if(! $B.$isinstance(res,_b_.bytes)){$B.RAISE(_b_.TypeError,`__bytes__ returned `+ `non-bytes (type ${$B.class_name(res)})`)} if(res.source===undefined){console.log('!!!!!!!',$.source)} return res}} source=[] for(var item of int_list){item=$B.PyNumber_Index(item) if(item >=0 && item < 256){source.push(item)}else{$B.RAISE(_b_.ValueError,"bytes must be in range (0, 256)")}}} if(source===undefined){console.log('bytes.__new__, no source',$.source)} return{ __class__:$.cls,source}} bytes.$new=function(cls,source,encoding,errors){ var self={__class__:cls},int_list=[],pos=0 if(source===undefined){}else if(typeof source=="number" ||$B.$isinstance(source,_b_.int)){let i=source while(i--){int_list[pos++]=0}}else{if(typeof source=="string" ||$B.$isinstance(source,_b_.str)){if(encoding===undefined){$B.RAISE(_b_.TypeError,"string argument without an encoding")} int_list=encode(source,encoding ||"utf-8",errors ||"strict")}else{if(encoding !==undefined){console.log('encoding',encoding) $B.RAISE(_b_.TypeError,"encoding without a string argument")} if(Array.isArray(source)){int_list=source}else{try{int_list=_b_.list.$factory(source)}catch(err){var bytes_method=$B.$getattr(source,'__bytes__',_b_.None) if(bytes_method===_b_.None){$B.RAISE(_b_.TypeError,"cannot convert "+ `'${$B.class_name(source)}' object to bytes`)} var res=$B.$call(bytes_method)() if(! $B.$isinstance(res,_b_.bytes)){$B.RAISE(_b_.TypeError,`__bytes__ returned `+ `non-bytes (type ${$B.class_name(res)})`)} return res} for(let i=0;i < int_list.length;i++){try{var item=_b_.int.$factory(int_list[i])}catch(err){$B.RAISE(_b_.TypeError,"'"+ $B.class_name(int_list[i])+"' object "+ "cannot be interpreted as an integer")} if(item < 0 ||item > 255){$B.RAISE(_b_.ValueError,"bytes must be in range"+ "(0, 256)")}}}}} self.source=int_list self.encoding=encoding self.errors=errors return self} bytes.__release_buffer__=function(_self,buffer){_b_.memoryview.release(buffer)} bytes.__repr__=bytes.__str__=function(self){var t=$B.special_string_repr, res="" for(var i=0,len=self.source.length;i < len;i++){var s=self.source[i] if(t[s]!==undefined){res+=t[s]}else if(s < 32 ||s >=128){var hx=s.toString(16) hx=(hx.length==1 ? '0' :'')+hx res+='\\x'+hx}else if(s=="\\".charCodeAt(0)){res+="\\\\"}else{res+=String.fromCharCode(s)}} if(res.indexOf("'")>-1 && res.indexOf('"')==-1){return 'b"'+res+'"'}else{return "b'"+res.replace(new RegExp("'","g"),"\\'")+"'"}} bytes.capitalize=function(self){var src=self.source,len=src.length,buffer=src.slice() if(buffer[0]> 96 && buffer[0]< 123){buffer[0]-=32} for(var i=1;i < len;++i){if(buffer[i]> 64 && buffer[i]< 91){buffer[i]+=32}} return bytes.$factory(buffer)} bytes.center=function(){var $=$B.args('center',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) var diff=$.width-$.self.source.length if(diff <=0){return bytes.$factory($.self.source)} var ljust=bytes.ljust($.self,$.self.source.length+Math.floor(diff/2),$.fillbyte) return bytes.rjust(ljust,$.width,$.fillbyte)} 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) var n=0,index=-1,len=0 if(typeof $.sub=="number"){if($.sub < 0 ||$.sub > 255) $B.RAISE(_b_.ValueError,"byte must be in range(0, 256)") len=1}else if(!$.sub.__class__){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name($.sub)+"'")}else if(!$.sub.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name($.sub)+"'")}else{len=$.sub.source.length} do{index=bytes.find($.self,$.sub,Math.max(index+len,$.start),$.end) if(index !=-1){n++}}while(index !=-1) return n} bytes.decode=function(){var $=$B.args("decode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null) switch($.errors){case 'strict': case 'ignore': case 'replace': case 'surrogateescape': case 'surrogatepass': case 'xmlcharrefreplace': case 'backslashreplace': return decode($.self,$.encoding,$.errors) default:}} 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) if($B.$isinstance($.suffix,bytes)){var end=$.end==-1 ? $.self.source.length :$.end var res=true for(let i=$.suffix.source.length-1,len=$.suffix.source.length; i >=0 && res;--i){res=$.self.source[end-len+i]==$.suffix.source[i]} return res}else if($B.$isinstance($.suffix,_b_.tuple)){for(let i=0;i < $.suffix.length;++i){if($B.$isinstance($.suffix[i],bytes)){if(bytes.endswith($.self,$.suffix[i],$.start,$.end)){return true}}else{$B.RAISE(_b_.TypeError,"endswith first arg must be "+ "bytes or a tuple of bytes, not "+ $B.class_name($.suffix))}} return false}else{$B.RAISE(_b_.TypeError,"endswith first arg must be bytes "+ "or a tuple of bytes, not "+$B.class_name($.suffix))}} bytes.expandtabs=function(){var $=$B.args('expandtabs',2,{self:null,tabsize:null},['self','tabsize'],arguments,{tabsize:8},null,null) var tab_spaces=[] for(let i=0;i < $.tabsize;++i){tab_spaces.push(32)} var buffer=$.self.source.slice() for(let i=0;i < buffer.length;++i){if(buffer[i]===9){var nb_spaces=$.tabsize-i % $.tabsize var tabs=new Array(nb_spaces) tabs.fill(32) buffer.splice.apply(buffer,[i,1].concat(tabs))}} return _b_.bytes.$factory(buffer)} bytes.find=function(self,sub){var start,end 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{start=0 end=-1} if(typeof sub=="number"){if(sub < 0 ||sub > 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} return self.source.slice(0,end==-1 ? undefined :end).indexOf(sub,start)}else if(! sub.__class__){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name(sub)+"'")}else if(! sub.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name(sub)+"'")} end=end==-1 ? self.source.length :Math.min(self.source.length,end) var len=sub.source.length for(var i=start;i <=end-len;i++){var chunk=self.source.slice(i,i+len),found=true for(var j=0;j < len;j++){if(chunk[j]!=sub.source[j]){found=false break}} if(found){return i}} return-1} bytes.fromhex=function(){var $=$B.args('fromhex',2,{cls:null,string:null},['cls','string'],arguments,{},null,null),string=$.string.replace(/\s/g,''),source=[] for(var i=0;i < string.length;i+=2){if(i+2 > string.length){$B.RAISE(_b_.ValueError,"non-hexadecimal number found "+ "in fromhex() arg")} source.push(_b_.int.$factory(string.substr(i,2),16))} return $.cls.$factory(source)} bytes.hex=function(){ var $=$B.args('hex',3,{self:null,sep:null,bytes_per_sep:null},['self','sep','bytes_per_sep'],arguments,{sep:"",bytes_per_sep:1},null,null),self=$.self,sep=$.sep,bytes_per_sep=$.bytes_per_sep,res="",digits="0123456789abcdef",bps=bytes_per_sep,jstart=bps,len=self.source.length; if(bytes_per_sep < 0){bps=-bytes_per_sep; jstart=bps}else if(bytes_per_sep==0){sep=''}else{jstart=len % bps if(jstart==0){jstart=bps}} for(var i=0,j=jstart;i < len;i++){var c=self.source[i] if(j==0){res+=sep j=bps} j-- res+=digits[c >> 4] res+=digits[c & 0x0f]} return res} bytes.index=function(){var $=$B.args('index',4,{self:null,sub:null,start:null,end:null},['self','sub','start','end'],arguments,{start:0,end:-1},null,null) var index=bytes.find($.self,$.sub,$.start,$.end) console.log('index',index) if(index==-1){$B.RAISE(_b_.ValueError,"subsection not found")} return index} bytes.isalnum=function(){var $=$B.args('isalnum',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,res=len > 0 for(var i=0;i < len && res;++i){res=(src[i]> 96 && src[i]< 123)|| (src[i]> 64 && src[i]< 91)|| (src[i]> 47 && src[i]< 58)} return res} bytes.isalpha=function(){var $=$B.args('isalpha',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,res=len > 0 for(var i=0;i < len && res;++i){res=(src[i]> 96 && src[i]< 123)||(src[i]> 64 && src[i]< 91)} return res} bytes.isdigit=function(){var $=$B.args('isdigit',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,res=len > 0 for(let i=0;i < len && res;++i){res=src[i]> 47 && src[i]< 58} return res} bytes.islower=function(){var $=$B.args('islower',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,res=false for(let i=0;i < len;++i){ res=res ||(src[i]> 96 && src[i]< 123) if(src[i]> 64 && src[i]< 91){return false}} return res} bytes.isspace=function(){var $=$B.args('isspace',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length for(let i=0;i < len;++i){switch(src[i]){case 9: case 10: case 11: case 12: case 13: case 32: break default: return false}} return true} bytes.isupper=function(){var $=$B.args('isupper',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,res=false for(let i=0;i < len;++i){ res=res ||(src[i]> 64 && src[i]< 91) if(src[i]> 96 && src[i]< 123){return false}} return res} bytes.istitle=function(){var $=$B.args('istitle',1,{self:null},['self'],arguments,{},null,null),self=$.self var src=self.source,len=src.length,current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false for(var i=0;i < len;++i){is_lowercase=src[i]> 96 && src[i]< 123 is_uppercase=src[i]> 64 && src[i]< 91 current_char_is_letter=is_lowercase ||is_uppercase if(current_char_is_letter && (prev_char_was_letter && is_uppercase)|| (! prev_char_was_letter && is_lowercase)){return false} prev_char_was_letter=current_char_is_letter} return true} bytes.join=function(){var $ns=$B.args('join',2,{self:null,iterable:null},['self','iterable'],arguments,{}),self=$ns['self'],iterable=$ns['iterable'] var next_func=$B.$getattr(_b_.iter(iterable),'__next__'),res=self.__class__.$factory(),empty=true while(true){try{var item=next_func() if(empty){empty=false}else{res=bytes.__add__(res,self)} res=bytes.__add__(res,item)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break} throw err}} return res} var _lower=function(char_code){if(char_code >=65 && char_code <=90){return char_code+32}else{return char_code}} bytes.lower=function(self){var _res=[],pos=0 for(var i=0,len=self.source.length;i < len;i++){if(self.source[i]){_res[pos++]=_lower(self.source[i])}} return bytes.$factory(_res)} bytes.ljust=function(){var $=$B.args('ljust',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) if(!$.fillbyte.__class__){$B.RAISE(_b_.TypeError,"argument 2 must be a byte string of length 1, "+ "not '"+$B.class_name($.fillbyte)+"'")}else if(!$.fillbyte.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"argument 2 must be a byte string of length 1, "+ "not '"+$B.class_name($.fillbyte)+"'")} var padding=[],count=$.width-$.self.source.length for(var i=0;i < count;++i){padding.push($.fillbyte.source[0])} return bytes.$factory($.self.source.concat(padding))} bytes.lstrip=function(self,cars){return _strip(self,cars,'l')} bytes.maketrans=function(from,to){var _t=[] to=$B.to_bytes(to) for(let i=0;i < 256;i++){_t[i]=i} for(let i=0,len=from.source.length;i < len;i++){var _ndx=from.source[i] _t[_ndx]=to[i]} return bytes.$factory(_t)} bytes.partition=function(){var $=$B.args('partition',2,{self:null,sep:null},['self','sep'],arguments,{},null,null) if(! $.sep.__class__){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")}else if(! $.sep.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")} var len=$.sep.source.length,src=$.self.source,i=bytes.find($.self,$.sep) return _b_.tuple.$factory([bytes.$factory(src.slice(0,i)),bytes.$factory(src.slice(i,i+len)),bytes.$factory(src.slice(i+len)) ])} bytes.removeprefix=function(){var $=$B.args("removeprefix",2,{self:null,prefix:null},["self","prefix"],arguments,{},null,null) if(!$B.$isinstance($.prefix,[bytes,bytearray])){$B.RAISE(_b_.ValueError,"prefix should be bytes, not "+ `'${$B.class_name($.prefix)}'`)} if(bytes.startswith($.self,$.prefix)){return bytes.__getitem__($.self,_b_.slice.$factory($.prefix.source.length,_b_.None))} return bytes.__getitem__($.self,_b_.slice.$factory(0,_b_.None))} bytes.removesuffix=function(){var $=$B.args("removesuffix",2,{self:null,suffix:null},["self","suffix"],arguments,{},null,null) if(!$B.$isinstance($.suffix,[bytes,bytearray])){$B.RAISE(_b_.ValueError,"suffix should be bytes, not "+ `'${$B.class_name($.suffix)}'`)} if(bytes.endswith($.self,$.suffix)){return bytes.__getitem__($.self,_b_.slice.$factory(0,$.suffix.source.length+1))} return bytes.__getitem__($.self,_b_.slice.$factory(0,_b_.None))} 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=[] var self=$.self,src=self.source,len=src.length,old=$.old,$new=$.new var count=$.count >=0 ? $.count :src.length if(! $.old.__class__){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name($.old)+"'")}else if(! $.old.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name($.sep)+"'")} if(! $.new.__class__){$B.RAISE(_b_.TypeError,"second argument must be a bytes-like "+ "object, not '"+$B.class_name($.old)+"'")}else if(! $.new.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"second argument must be a bytes-like "+ "object, not '"+$B.class_name($.sep)+"'")} 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])} i+=(old.source.length-1) count--}else{res.push(src[i])}} return bytes.$factory(res)} bytes.rfind=function(self,subbytes){var sub,start,end if(arguments.length==2 && subbytes.__class__===bytes){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) sub=$.sub start=$.start end=$.end} if(typeof sub=="number"){if(sub < 0 ||sub > 255){$B.RAISE(_b_.ValueError,"byte must be in range(0, 256)")} return $.self.source.slice(start,$.end==-1 ? undefined :$.end). lastIndexOf(sub)+start}else if(! sub.__class__){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name($.sub)+"'")}else if(! sub.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"first argument must be a bytes-like "+ "object, not '"+$B.class_name(sub)+"'")} end=end==-1 ? self.source.length :Math.min(self.source.length,end) var len=sub.source.length for(var i=end-len;i >=start;--i){var chunk=self.source.slice(i,i+len),found=true for(var j=0;j < len;j++){if(chunk[j]!=sub.source[j]){found=false break}} if(found){return i}} return-1} 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) var index=bytes.rfind($.self,$.sub,$.start,$.end) if(index==-1){$B.RAISE(_b_.ValueError,"subsection not found")} return index} bytes.rjust=function(){var $=$B.args('rjust',3,{self:null,width:null,fillbyte:null},['self','width','fillbyte'],arguments,{fillbyte:bytes.$factory([32])},null,null) if(!$.fillbyte.__class__){$B.RAISE(_b_.TypeError,"argument 2 must be a byte string of length 1, "+ "not '"+$B.class_name($.fillbyte)+"'")}else if(!$.fillbyte.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"argument 2 must be a byte string of length 1, "+ "not '"+$B.class_name($.fillbyte)+"'")} var padding=[],count=$.width-$.self.source.length for(var i=0;i < count;++i){padding.push($.fillbyte.source[0])} return bytes.$factory(padding.concat($.self.source))} bytes.rpartition=function(){var $=$B.args('rpartition',2,{self:null,sep:null},['self','sep'],arguments,{},null,null) if(!$.sep.__class__){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")}else if(!$.sep.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")} var len=$.sep.source.length,src=$.self.source,i=bytes.rfind($.self,$.sep) return _b_.tuple.$factory([bytes.$factory(src.slice(0,i)),bytes.$factory(src.slice(i,i+len)),bytes.$factory(src.slice(i+len)) ])} bytes.rstrip=function(self,cars){return _strip(self,cars,'r')} bytes.split=function(){var $=$B.args('split',2,{self:null,sep:null},['self','sep'],arguments,{sep:bytes.$factory([32])},null,null),res=[],start=0,stop=0 if(! $.sep.__class__ ){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")}else if(! $.sep.__class__.$buffer_protocol){$B.RAISE(_b_.TypeError,"a bytes-like object is required, "+ "not '"+$B.class_name($.sep)+"'")} var seps=$.sep.source,len=seps.length,src=$.self.source,blen=src.length while(stop < blen){var match=true for(var i=0;i < len && match;i++){if(src[stop+i]!=seps[i]){match=false}} if(match){res.push(bytes.$factory(src.slice(start,stop))) start=stop+len stop=start}else{stop++}} if(match ||(stop > start)){res.push(bytes.$factory(src.slice(start,stop)))} return $B.$list(res)} bytes.splitlines=function(){var $=$B.args('splitlines',2,{self:null,keepends:null},['self','keepends'],arguments,{keepends:false},null,null) if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError('integer argument expected, got '+ $B.get_class($.keepends).__name)} var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),source=$.self.source,start=0,pos=0 if(! source.length){return res} while(pos < source.length){if(pos < source.length-1 && source[pos]==0x0d && source[pos+1]==0x0a){res.push(bytes.$factory(source.slice(start,keepends ? pos+2 :pos))) start=pos=pos+2}else if(source[pos]==0x0d ||source[pos]==0x0a){res.push(bytes.$factory(source.slice(start,keepends ? pos+1 :pos))) start=pos=pos+1}else{pos++}} if(start < source.length){res.push(bytes.$factory(source.slice(start)))} return $B.$list(res)} bytes.startswith=function(){var $=$B.args('startswith',3,{self:null,prefix:null,start:null},['self','prefix','start'],arguments,{start:0},null,null),start=$.start if($B.$isinstance($.prefix,bytes)){let res=true for(let i=0;i < $.prefix.source.length && res;i++){res=$.self.source[start+i]==$.prefix.source[i]} return res}else if($B.$isinstance($.prefix,_b_.tuple)){let items=[] for(let i=0;i < $.prefix.length;i++){if($B.$isinstance($.prefix[i],bytes)){items=items.concat($.prefix[i].source)}else{$B.RAISE(_b_.TypeError,"startswith first arg must be "+ "bytes or a tuple of bytes, not "+ $B.class_name($.prefix))}} let prefix=bytes.$factory(items) return bytes.startswith($.self,prefix,start)}else{$B.RAISE(_b_.TypeError,"startswith first arg must be bytes "+ "or a tuple of bytes, not "+$B.class_name($.prefix))}} bytes.strip=function(self,cars){var res=bytes.lstrip(self,cars) return bytes.rstrip(res,cars)} bytes.swapcase=function(self){var src=self.source,len=src.length,buffer=src.slice() 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}} return bytes.$factory(buffer)} bytes.title=function(self){var src=self.source,len=src.length,buffer=src.slice(),current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false for(var i=0;i < len;++i){is_lowercase=buffer[i]> 96 && buffer[i]< 123 is_uppercase=buffer[i]> 64 && buffer[i]< 91 current_char_is_letter=is_lowercase ||is_uppercase 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}} prev_char_was_letter=current_char_is_letter} return bytes.$factory(buffer)} bytes.translate=function(self,table,_delete){if(_delete===undefined){_delete=[]}else if($B.$isinstance(_delete,bytes)){_delete=_delete.source}else{$B.RAISE(_b_.TypeError,"Type "+ $B.get_class(_delete).__name+" doesn't support the buffer API")} var res=[],pos=0 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} res[pos++]=table.source[self.source[i]]}} return bytes.$factory(res)} var _upper=function(char_code){if(char_code >=97 && char_code <=122){return char_code-32}else{return char_code}} bytes.upper=function(self){var _res=[],pos=0 for(var i=0,len=self.source.length;i < len;i++){if(self.source[i]){_res[pos++]=_upper(self.source[i])}} return bytes.$factory(_res)} bytes.zfill=function(self,width){var buffer=self.source.slice(),prefix_offset=(buffer[0]==43 ||buffer[0]==45)? 1 :0 var count=width-self.source.length var padding=[] for(var i=0;i < count;++i){padding.push(48)} buffer.splice.apply(buffer,[prefix_offset,0].concat(padding)) return bytes.$factory(buffer)} function $UnicodeEncodeError(encoding,code_point,position){$B.RAISE(_b_.UnicodeEncodeError,"'"+encoding+ "' codec can't encode character "+_b_.hex(code_point)+ " in position "+position)} function _hex(_int){var h=_int.toString(16) return '0x'+'0'.repeat(2-h.length)+h} var aliases={ascii:['646','us-ascii'],big5:['big5-tw','csbig5'],big5hkscs:['big5-hkscs','hkscs'],cp037:['IBM037','IBM039'],cp273:['273','IBM273','csIBM273'],cp424:['EBCDIC-CP-HE','IBM424'],cp437:['437','IBM437'],cp500:['EBCDIC-CP-BE','EBCDIC-CP-CH','IBM500'],cp775:['IBM775'],cp850:['850','IBM850'],cp852:['852','IBM852'],cp855:['855','IBM855'],cp857:['857','IBM857'],cp858:['858','IBM858'],cp860:['860','IBM860'],cp861:['861','CP-IS','IBM861'],cp862:['862','IBM862'],cp863:['863','IBM863'],cp864:['IBM864'],cp865:['865','IBM865'],cp866:['866','IBM866'],cp869:['869','CP-GR','IBM869'],cp932:['932','ms932','mskanji','ms-kanji'],cp949:['949','ms949','uhc'],cp950:['950','ms950'],cp1026:['ibm1026'],cp1125:['1125','ibm1125','cp866u','ruscii'],cp1140:['ibm1140'],cp1250:['windows-1250'],cp1251:['windows-1251'],cp1252:['windows-1252'],cp1253:['windows-1253'],cp1254:['windows-1254'],cp1255:['windows-1255'],cp1256:['windows-1256'],cp1257:['windows-1257'],cp1258:['windows-1258'],euc_jp:['eucjp','ujis','u-jis'],euc_jis_2004:['jisx0213','eucjis2004'],euc_jisx0213:['eucjisx0213'],euc_kr:['euckr','korean','ksc5601','ks_c-5601','ks_c-5601-1987','ksx1001','ks_x-1001'],gb2312:['chinese','csiso58gb231280','euc-cn','euccn','eucgb2312-cn','gb2312-1980','gb2312-80','iso-ir-58'],gbk:['936','cp936','ms936'],gb18030:['gb18030-2000'],hz:['hzgb','hz-gb','hz-gb-2312'],iso2022_jp:['csiso2022jp','iso2022jp','iso-2022-jp'],iso2022_jp_1:['iso2022jp-1','iso-2022-jp-1'],iso2022_jp_2:['iso2022jp-2','iso-2022-jp-2'],iso2022_jp_2004:['iso2022jp-2004','iso-2022-jp-2004'],iso2022_jp_3:['iso2022jp-3','iso-2022-jp-3'],iso2022_jp_ext:['iso2022jp-ext','iso-2022-jp-ext'],iso2022_kr:['csiso2022kr','iso2022kr','iso-2022-kr'],latin_1:['iso-8859-1','iso8859-1','8859','cp819','latin','latin1','L1'],iso8859_2:['iso-8859-2','latin2','L2'],iso8859_3:['iso-8859-3','latin3','L3'],iso8859_4:['iso-8859-4','latin4','L4'],iso8859_5:['iso-8859-5','cyrillic'],iso8859_6:['iso-8859-6','arabic'],iso8859_7:['iso-8859-7','greek','greek8'],iso8859_8:['iso-8859-8','hebrew'],iso8859_9:['iso-8859-9','latin5','L5'],iso8859_10:['iso-8859-10','latin6','L6'],iso8859_11:['iso-8859-11','thai'],iso8859_13:['iso-8859-13','latin7','L7'],iso8859_14:['iso-8859-14','latin8','L8'],iso8859_15:['iso-8859-15','latin9','L9'],iso8859_16:['iso-8859-16','latin10','L10'],johab:['cp1361','ms1361'],kz1048:['kz_1048','strk1048_2002','rk1048'],mac_cyrillic:['maccyrillic'],mac_greek:['macgreek'],mac_iceland:['maciceland'],mac_latin2:['maclatin2','maccentraleurope','mac_centeuro'],mac_roman:['macroman','macintosh'],mac_turkish:['macturkish'],ptcp154:['csptcp154','pt154','cp154','cyrillic-asian'],shift_jis:['csshiftjis','shiftjis','sjis','s_jis'],shift_jis_2004:['shiftjis2004','sjis_2004','sjis2004'],shift_jisx0213:['shiftjisx0213','sjisx0213','s_jisx0213'],utf_32:['U32','utf32'],utf_32_be:['UTF-32BE'],utf_32_le:['UTF-32LE'],utf_16:['U16','utf16'],utf_16_be:['UTF-16BE'],utf_16_le:['UTF-16LE'],utf_7:['U7','unicode-1-1-utf-7'],utf_8:['U8','UTF','utf8','cp65001'],mbcs:['ansi','dbcs'],bz2_codec:['bz2'],hex_codec:['hex'],quopri_codec:['quopri','quotedprintable','quoted_printable'],uu_codec:['uu'],zlib_codec:['zip','zlib'],rot_13:['rot13']} var codecs_aliases={} for(var name in aliases){for(var alias of aliases[name]){codecs_aliases[alias.toLowerCase().replace(/-/g,'_')]=name}} function normalise(encoding){ var enc=encoding.toLowerCase() .replace(/ /g,'_') .replace(/-/g,'_') if(codecs_aliases[enc]!==undefined){enc=codecs_aliases[enc]} return enc} function load_decoder(enc){ if(to_unicode[enc]===undefined){var mod=_b_.__import__("encodings."+enc) if(mod[enc].getregentry){to_unicode[enc]=$B.$getattr(mod[enc].getregentry(),"decode")}}} function load_encoder(enc){ if(from_unicode[enc]===undefined){var mod=_b_.__import__("encodings."+enc) if(mod[enc].getregentry){from_unicode[enc]=$B.$getattr(mod[enc].getregentry(),"encode")}}} var decode=$B.decode=function(obj,encoding,errors){var s="",b=obj.source,enc=normalise(encoding) switch(enc){case "utf_8": case "utf-8": case "utf8": case "U8": case "UTF": if(globalThis.TextDecoder){var decoder=new TextDecoder('utf-8',{fatal:true}),array=new Uint8Array(b) try{return decoder.decode(array)}catch(err){}} var pos=0,err_info while(pos < b.length){let byte=b[pos] err_info=null if(!(byte & 0x80)){ s+=String.fromCodePoint(byte) pos++}else if((byte >> 5)==6){ if(b[pos+1]===undefined){err_info=[byte,pos,"end"]}else if((b[pos+1]& 0xc0)!=0x80){err_info=[byte,pos,"continuation"]} if(err_info !==null){if(errors=="ignore"){pos++}else{$B.RAISE(_b_.UnicodeDecodeError,"'utf-8' codec can't decode byte 0x"+ err_info[0].toString(16)+" in position "+ err_info[1]+ (err_info[2]=="end" ? ": unexpected end of data" : ": invalid continuation byte"))}}else{let cp=byte & 0x1f cp <<=6 cp+=b[pos+1]& 0x3f s+=String.fromCodePoint(cp) pos+=2}}else if((byte >> 4)==14){ 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]} if(err_info !==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i < err_info[3];i++){s+=String.fromCodePoint(0xdc80+b[i]-0x80)} pos=err_info[3]}else{$B.RAISE(_b_.UnicodeDecodeError,"'utf-8' codec can't decode byte 0x"+ err_info[0].toString(16)+" in position "+ err_info[1]+ (err_info[2]=="end" ? ": unexpected end of data" : ": invalid continuation byte"))}}else{let cp=byte & 0xf cp=cp << 12 cp+=(b[pos+1]& 0x3f)<< 6 cp+=b[pos+2]& 0x3f s+=String.fromCodePoint(cp) pos+=3}}else if((byte >> 3)==30){ 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]} if(err_info !==null){if(errors=="ignore"){pos=err_info[3]}else if(errors=="surrogateescape"){for(let i=pos;i < err_info[3];i++){s+=String.fromCodePoint(0xdc80+b[i]-0x80)} pos=err_info[3]}else{$B.RAISE(_b_.UnicodeDecodeError,"'utf-8' codec can't decode byte 0x"+ err_info[0].toString(16)+" in position "+ err_info[1]+ (err_info[2]=="end" ? ": unexpected end of data" : ": invalid continuation byte"))}}else{let cp=byte & 0xf cp=cp << 18 cp+=(b[pos+1]& 0x3f)<< 12 cp+=(b[pos+2]& 0x3f)<< 6 cp+=(b[pos+3]& 0x3f) s+=String.fromCodePoint(cp) pos+=4}}else{if(errors=="ignore"){pos++}else if(errors=="surrogateescape"){s+=String.fromCodePoint(0xdc80+b[pos]-0x80) pos++}else{$B.RAISE(_b_.UnicodeDecodeError,"'utf-8' codec can't decode byte 0x"+ byte.toString(16)+" in position "+pos+ ": invalid start byte")}}} return s case "latin_1": case "windows1252": case "iso-8859-1": case "iso8859-1": case "8859": case "cp819": case "latin": case "latin1": case "L1": b.forEach(function(item){s+=String.fromCharCode(item)}) break case "unicode_escape": if(obj.__class__===bytes ||obj.__class__===bytearray){obj=decode(obj,"latin-1","strict")} return obj.replace(/\\n/g,"\n"). replace(/\\a/g,"\u0007"). replace(/\\b/g,"\b"). replace(/\\f/g,"\f"). replace(/\\t/g,"\t"). replace(/\\'/g,"'"). replace(/\\"/g,'"') case "raw_unicode_escape": if(obj.__class__===bytes ||obj.__class__===bytearray){obj=decode(obj,"latin-1","strict")} return obj.replace(/\\u([a-fA-F0-9]{4})/g,function(mo){let cp=parseInt(mo.substr(2),16) return String.fromCharCode(cp)}) case "ascii": for(let i=0,len=b.length;i < len;i++){let cp=b[i] if(cp <=127){s+=String.fromCharCode(cp)}else{if(errors=="ignore"){}else if(errors=="backslashreplace"){s+='\\x'+cp.toString(16)}else{let msg="'ascii' codec can't decode byte 0x"+ cp.toString(16)+" in position "+i+ ": ordinal not in range(128)" $B.RAISE(_b_.UnicodeDecodeError,msg)}}} break default: try{load_decoder(enc)}catch(err){$B.RAISE(_b_.LookupError,"unknown encoding: "+enc)} var decoded=to_unicode[enc](obj)[0] for(let i=0,len=decoded.length;i < len;i++){if(decoded.codePointAt(i)==0xfffe){$B.RAISE(_b_.UnicodeDecodeError,"'charmap' codec "+ `can't decode byte ${_hex(b[i])} in position ${i}: `+ "character maps to ")}} return decoded} return s} 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 var t=[],pos=0,enc=normalise(encoding) switch(enc){case "utf-8": case "utf_8": case "utf8": if(globalThis.TextEncoder){var encoder=new TextEncoder('utf-8',{fatal:true}) try{var array=encoder.encode(s) return fast_bytes(Array.from(array))}catch(err){}} for(let i=0,len=s.length;i < len;i++){let cp=s.charCodeAt(i) if(cp <=0x7f){t.push(cp)}else if(cp <=0x7ff){t.push(0xc0+(cp >> 6),0x80+(cp & 0x3f))}else if(cp <=0xffff){t.push(0xe0+(cp >> 12),0x80+((cp & 0xfff)>> 6),0x80+(cp & 0x3f))}else{console.log("4 bytes")}} break case "latin": case "latin1": case "latin-1": case "latin_1": case "L1": case "iso8859_1": case "iso_8859_1": case "8859": case "cp819": case "windows1252": for(let i=0,len=s.length;i < len;i++){let cp=s.charCodeAt(i) if(cp <=255){t[pos++]=cp}else if(errors !="ignore"){$UnicodeEncodeError(encoding,i)}} break case "ascii": for(let i=0,len=_b_.str.__len__(s);i < len;i++){let cp=s.charCodeAt(i), char=_b_.str.__getitem__(s,i) if(cp <=127){t[pos++]=cp}else if(errors=="backslashreplace"){let hex=_b_.hex(_b_.ord(char)) if(hex.length < 5){hex='\\x'+'0'.repeat(4-hex.length)+hex.substr(2)}else if(hex.length < 7){hex='\\u'+'0'.repeat(6-hex.length)+hex.substr(2)}else{hex='\\U'+'0'.repeat(10-hex.length)+hex.substr(2)} for(let char of hex){t[pos++]=char.charCodeAt(0)}}else if(errors !=='ignore'){$UnicodeEncodeError(encoding,i)}} break case "raw_unicode_escape": for(let i=0,len=s.length;i < len;i++){let cp=s.charCodeAt(i) if(cp < 256){t[pos++]=cp}else{let us=cp.toString(16) if(us.length % 2){us="0"+us} us="\\u"+us for(let j=0;j < us.length;j++){t[pos++]=us.charCodeAt(j)}}} break default: try{load_encoder(enc)}catch(err){$B.RAISE(_b_.LookupError,"unknown encoding: "+encoding)} return from_unicode[enc](s)[0]} return fast_bytes(t)} function fast_bytes(t){return{ __class__:_b_.bytes,source:t ??[]}} $B.fast_bytes=fast_bytes bytes.$factory=function(){return bytes.__new__.bind(null,bytes).apply(null,arguments)} bytes.__class__=_b_.type bytes.$is_class=true $B.set_func_names(bytes,"builtins") bytes.fromhex=_b_.classmethod.$factory(bytes.fromhex) 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)}} $B.set_func_names(bytearray,"builtins") bytearray.fromhex=bytes.fromhex _b_.bytes=bytes _b_.bytearray=bytearray})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,$N=_b_.None function make_new_set(type){var res={__class__:type,$store:Object.create(null),$version:0,$used:0} res[Symbol.iterator]=function*(){var version=res.$version for(var item of set_iter(res)){yield item if(res.$version !=version){$B.RAISE(_b_.RuntimeError,'Set changed size during iteration')}}} return res} function make_new_set_base_type(so){return $B.$isinstance(so,set)? set.$factory(): frozenset.$factory()} function set_add(so,item,hash){hash=hash ?? $B.$hash(item) var stored=so.$store[hash] if(stored && set_contains(so,item,hash)){return}else{stored=so.$store[hash]=[] stored[stored.length]=item so.$used++ so.$version++}} function set_contains(so,key,hash){return !! set_lookkey(so,key,hash)} function set_copy(obj){var res=make_new_set_base_type(obj) for(var hash in obj.$store){res.$store[hash]=obj.$store[hash].slice()} res.$used=obj.$used return res} var set=$B.make_class('set') set.$native=true function set_copy_and_difference(so,other){var result=set_copy(so) set_difference_update(result,other) return result} function set_difference(so,other){var other_size,other_is_dict if($B.$isinstance(other,[set,frozenset])){other_size=set.__len__(other)}else if($B.$isinstance(other,_b_.dict)){other_size=_b_.dict.__len__(other) other_is_dict=true}else{return set_copy_and_difference(so,other)} if(set.__len__(so)>> 2 > other_size){return set_copy_and_difference(so,other);} var result=make_new_set() if(other_is_dict){for(let entry of set_iter_with_hash(so)){if(! _b_.dict.$lookup_by_key(other,entry.item,entry.hash).found){set_add(result,entry.item,entry.hash)}} return result} for(let entry of set_iter_with_hash(so)){if(! set_contains(other,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}} result.__class__=so.__class__ return result} function set_difference_update(so,other){if(so===other){return set.clear(so);} if($B.$isinstance(other,[set,frozenset])){for(let entry of set_iter_with_hash(other)){set_discard_entry(so,entry.item,entry.hash)}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){set_discard_entry(so,entry.key,entry.hash)}}else{var iterator=$B.make_js_iterator(other) for(let key of iterator){set_discard_key(so,key)}}} const DISCARD_NOTFOUND=0 function set_discard_entry(so,key,hash){var entry=set_lookkey(so,key,hash) if(! entry){return DISCARD_NOTFOUND} if(so.$store[entry.hash]!==undefined){ set_remove(so,entry.hash,entry.index)}} function set_discard_key(so,key){return set_discard_entry(so,key);} function*set_iter(so){var ordered_keys=Object.keys(so.$store).sort() for(var hash of ordered_keys){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield item}}}} function*set_iter_with_hash(so){for(var hash in so.$store){if(so.$store[hash]!==undefined){for(var item of so.$store[hash]){yield{item,hash}}}}} function set_remove(so,hash,index){so.$store[hash].splice(index,1) if(so.$store[hash].length==0){delete so.$store[hash]} so.$used--} function set_intersection(so,other){ if(so===other){return set_copy(so)} var result=make_new_set_base_type(so) if($B.$isinstance(other,[set,frozenset])){if(other.$used > so.$used){var tmp=so so=other other=tmp} for(let entry of set_iter_with_hash(other)){if(set_contains(so,entry.item,entry.hash)){set_add(result,entry.item,entry.hash)}}}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){if(set_contains(so,entry.key,entry.hash)){set_add(result,entry.key,entry.hash)}}}else{let iterator=$B.make_js_iterator(other) for(var other_item of iterator){var test=set_contains(so,other_item) if(test){set_add(result,other_item)}}} return result} function set_intersection_multi(so,args){var result=set_copy(so) if(args.length==0){return result} for(var other of args){result=set_intersection(result,other)} return result;} function set_lookkey(so,key,hash){ if(hash===undefined){try{hash=$B.$hash(key)}catch(err){if($B.$isinstance(key,set)){hash=$B.$hash(frozenset.$factory(key))}else{if(err.args && err.args[0]){err.args[0]=`cannot use '${$B.class_name(key)}' as `+ `a set element (${err.args[0]})`} throw err}}} var items=so.$store[hash] if(items===undefined){return false} for(var index=0,len=so.$store[hash].length;index < len;index++){if($B.is_or_equals(key,items[index])){return{hash,index}}} return false} function set_swap_bodies(a,b){var temp=set_copy(a) set.clear(a) a.$used=b.$used a.$store=b.$store b.$used=temp.$used b.$store=temp.$store} function set_symmetric_difference_update(so,other){if(so==other){return set.clear(so)} if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(other)){let rv=set_discard_entry(so,entry.key,entry.hash) if(rv==DISCARD_NOTFOUND){set_add(so,entry.key,entry.hash)}}}else if($B.$isinstance(other,[set,frozenset])){for(let entry of set_iter_with_hash(other)){let rv=set_discard_entry(so,entry.item,entry.hash) if(rv==DISCARD_NOTFOUND){set_add(so,entry.item,entry.hash)}}}else{return set_symmetric_difference_update(so,set.$factory(other))} return _b_.None} set.__and__=function(self,other){if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} return set_intersection(self,other)} set.__class_getitem__=$B.$class_getitem set.__contains__=function(self,item){return set_contains(self,item)} set.__eq__=function(self,other){if($B.$isinstance(other,[_b_.set,_b_.frozenset])){if(self.$used !=other.$used){return false} for(var hash in self.$store){if(other.$store[hash]===undefined){return false} var in_self=self.$store[hash],in_other=other.$store[hash] if(in_self===undefined ||in_other===undefined){ return false} if(in_self.length !=in_other.length){return false} if(in_self.length==1){if(! $B.is_or_equals(in_self[0],in_other[0])){return false}}else{in_self=in_self.slice() in_other=in_other.slice() for(var self_item of in_self){var found=false for(var i=0,len=in_other.length;i < len;i++){if($B.is_or_equals(self_item,in_other[i])){in_other.splice(i,1) found=true break}} if(! found){return false}}}} return true} return _b_.NotImplemented} set.__format__=function(self){return set.__repr__(self)} set.__ge__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.__le__(other,self)} return _b_.NotImplemented} set.__gt__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.__lt__(other,self)} return _b_.NotImplemented} set.__hash__=_b_.None set.__init__=function(self,iterable){if(iterable===undefined){return _b_.None} $B.check_nb_args_no_kw('set',2,arguments) if(Object.keys(self.$store).length > 0){set.clear(self)} set.update(self,iterable) return _b_.None} var set_iterator=$B.make_class('set_iterator',function(so){return{ __class__:set_iterator,so,it:set_iter(so),version:so.$version}} ) set_iterator.__iter__=function(self){return self} set_iterator.__length_hint__=function(self){return self.so.$used} set_iterator.__next__=function(self){var res=self.it.next() if(res.done){$B.RAISE(_b_.StopIteration,)} if(self.so.$version !=self.version){$B.RAISE(_b_.RuntimeError,"Set changed size during iteration")} return res.value} set_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([set_make_items(self.so)])])} $B.set_func_names(set_iterator,'builtins') set.__iter__=function(self){return set_iterator.$factory(self)} function set_make_items(so){ var items=[] for(var hash in so.$store){items=items.concat(so.$store[hash])} return $B.$list(items)} set.__le__=function(self,other){ if($B.$isinstance(other,[set,frozenset])){return set.issubset(self,other)} return _b_.NotImplemented} set.__len__=function(self){return self.$used} set.__lt__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.__le__(self,other)&& set.__len__(self)< set.__len__(other)}else{return _b_.NotImplemented}} set.__mro__=[_b_.object] set.__new__=function(cls,iterable){if(cls===undefined){$B.RAISE(_b_.TypeError,"set.__new__(): not enough arguments")} var self=make_new_set(cls) if(iterable===undefined){return self} if(cls===set){$B.check_nb_args_no_kw('__new__',2,arguments)} return self} set.__or__=function(self,other){if($B.$isinstance(other,[set,frozenset])){return set.union(self,other)} return _b_.NotImplemented} set.__rand__=function(self,other){ return set.__and__(self,other)} set.__reduce__=function(self){return $B.fast_tuple([self.__class__,$B.fast_tuple([set_make_items(self)]),_b_.None])} set.__reduce_ex__=function(self){return set.__reduce__(self)} set.__repr__=function(self){$B.builtins_repr_check(set,arguments) return set_repr(self)} function set_repr(self){ var klass_name=$B.class_name(self) if(self.$used===0){return klass_name+"()"} var head=klass_name+"({",tail="})" if(head=="set({"){head="{";tail="}"} var res=[] if($B.repr.enter(self)){return klass_name+"(...)"} for(var item of set_iter(self)){var r=_b_.repr(item) if(r===self ||r===item){res.push("{...}")} else{res.push(r)}} res=res.join(", ") $B.repr.leave(self) return head+res+tail} set.__ror__=function(self,other){ return set.__or__(self,other)} set.__rsub__=function(self,other){ return set.__sub__(self,other)} set.__rxor__=function(self,other){ return set.__xor__(self,other)} set.__sub__=function(self,other){ if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} return set_difference(self,other)} set.__xor__=function(self,other){ if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} var res=make_new_set() for(let entry of set_iter_with_hash(self)){if(! set_contains(other,entry.item,entry.hash)){set_add(res,entry.item,entry.hash)}} for(let entry of set_iter_with_hash(other)){if(! set_contains(self,entry.item,entry.hash)){set_add(res,entry.item,entry.hash)}} res.__class__=self.__class__ return res} $B.make_rmethods(set) set.add=function(self,item){$B.check_nb_args_no_kw('set.add',2,arguments) set_add(self,item) return _b_.None} set.clear=function(self){$B.check_nb_args_no_kw('set.clear',1,arguments) self.$used=0 self.$store=Object.create(null) self.$version++ return $N} set.copy=function(self){$B.check_nb_args_no_kw('copy',1,arguments) return set_copy(self)} set.difference_update=function(self){var $=$B.args("difference_update",1,{self:null},["self"],arguments,{},"args",null) for(var arg of $.args){set_difference_update(self,arg)} self.$version++ return _b_.None} set.discard=function(self,item){$B.check_nb_args_no_kw('set.discard',2,arguments) var result=set_discard_entry(self,item) if(result !=DISCARD_NOTFOUND){self.$version++} return _b_.None} set.intersection_update=function(){ var $=$B.args("intersection_update",1,{self:null},["self"],arguments,{},"args",null),self=$.self,args=$.args var temp=set_intersection_multi(self,args) set_swap_bodies(self,temp) self.$version++ return _b_.None} set.isdisjoint=function(self,other){ $B.check_nb_args_no_kw('set.isdisjoint',2,arguments) var intersection=set_intersection(self,other) return intersection.$used==0} set.pop=function(self){if(arguments.length > 1){$B.RAISE(_b_.TypeError,`set.pop() takes no arguments`+ ` (${arguments.length - 1} given)`)} for(var hash in self.$store){break} if(hash===undefined){$B.RAISE(_b_.KeyError,'pop from an empty set')} var item item=self.$store[hash].pop() if(self.$store[hash].length==0){delete self.$store[hash]} self.$used-- self.$version++ return item} set.remove=function(self,item){ $B.check_nb_args_no_kw('set.remove',2,arguments) var result=set_discard_entry(self,item) if(result==DISCARD_NOTFOUND){$B.RAISE(_b_.KeyError,item)} self.$version++ return _b_.None} set.symmetric_difference_update=function(self,s){ $B.check_nb_args_no_kw('set.symmetric_difference_update',2,arguments) return set_symmetric_difference_update(self,s)} set.update=function(self){ var $=$B.args("update",1,{self:null},["self"],arguments,{},"args",null) for(var iterable of $.args){if(Array.isArray(iterable)){for(let i=0;i < iterable.length;i++){set_add(self,iterable[i])}}else if($B.$isinstance(iterable,[set,frozenset])){for(let entry of set_iter_with_hash(iterable)){set_add(self,entry.item,entry.hash)}}else if($B.$isinstance(iterable,_b_.dict)){for(let entry of _b_.dict.$iter_items(iterable)){set_add(self,entry.key,entry.hash)}}else{var iterator=$B.make_js_iterator(iterable) for(let item of iterator){set_add(self,item)}}} self.$version++ return _b_.None} set.difference=function(){var $=$B.args("difference",1,{self:null},["self"],arguments,{},"args",null) if($.args.length==0){return set.copy($.self)} var res=set_copy($.self) for(var arg of $.args){if($B.$isinstance(arg,[set,frozenset])){for(var entry of set_iter_with_hash(arg)){set_discard_entry(res,entry.item,entry.hash)}}else{var other=set.$factory(arg) res=set.difference(res,other)}} return res} set.intersection=function(){var $=$B.args("difference",1,{self:null},["self"],arguments,{},"args",null) if($.args.length==0){return set.copy($.self)} return set_intersection_multi($.self,$.args)} set.symmetric_difference=function(self,other){ $B.check_nb_args_no_kw('set.symmetric_difference',2,arguments) var res=set_copy(self) set_symmetric_difference_update(res,other) return res} set.union=function(){var $=$B.args("union",1,{self:null},["self"],arguments,{},"args",null) let res=set_copy($.self) if($.args.length==0){return res} for(let arg of $.args){if($B.$isinstance(arg,[set,frozenset])){for(let entry of set_iter_with_hash(arg)){set_add(res,entry.item,entry.hash)}}else if(arg.__class__===_b_.dict){ for(let entry of _b_.dict.$iter_items(arg)){set_add(res,entry.key,entry.hash)}}else{let other=set.$factory(arg) res=set.union(res,other)}} return res} set.issubset=function(self,other){ $B.check_nb_args_no_kw('set.issubset',2,arguments) if($B.$isinstance(other,[set,frozenset])){if(set.__len__(self)> set.__len__(other)){return false} for(let entry of set_iter_with_hash(self)){if(! set_lookkey(other,entry.item,entry.hash)){return false}} return true}else if($B.$isinstance(other,_b_.dict)){for(let entry of _b_.dict.$iter_items(self)){if(! set_lookkey(other,entry.key,entry.hash)){return false}} return true}else{var member_func=$B.member_func(other) for(let entry of set_iter_with_hash(self)){if(! member_func(entry.item)){return false}} return true}} set.issuperset=function(self,other){ $B.check_nb_args_no_kw('set.issuperset',2,arguments) if($B.$isinstance(other,[set,frozenset])){return set.issubset(other,self)}else{return set.issubset(set.$factory(other),self)}} set.__iand__=function(self,other){if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} set.intersection_update(self,other) return self} set.__isub__=function(self,other){if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} set_difference_update(self,other) return self} set.__ixor__=function(self,other){if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} set.symmetric_difference_update(self,other) return self} set.__ior__=function(self,other){if(! $B.$isinstance(other,[set,frozenset])){return _b_.NotImplemented} set.update(self,other) return self} set.$literal=function(items){let res=make_new_set(set) for(let item of items){if(item.constant){set_add(res,item.constant[0],item.constant[1])}else if(item.starred){for(let _item of $B.make_js_iterator(item.starred)){set_add(res,_item)}}else{set_add(res,item.item)}} return res} set.$factory=function(){var args=[set].concat(Array.from(arguments)),self=set.__new__.apply(null,args) set.__init__(self,...arguments) return self} $B.set_func_names(set,"builtins") set.__class_getitem__=_b_.classmethod.$factory(set.__class_getitem__) var frozenset=$B.make_class('frozenset') frozenset.$native=true for(var attr in set){switch(attr){case "add": case "clear": case "discard": case "pop": case "remove": case "update": break default: 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]}}}} frozenset.__hash__=function(self){if(self===undefined){return frozenset.__hashvalue__ ||$B.$py_next_hash--} if(self.__hashvalue__ !==undefined){return self.__hashvalue__} var _hash=1927868237 _hash*=self.$used for(var entry of set_iter_with_hash(self)){var _h=entry.hash _hash ^=((_h ^ 89869747)^(_h << 16))*3644798167} _hash=_hash*69069+907133923 if(_hash==-1){_hash=590923713} return self.__hashvalue__=_hash} frozenset.__init__=function(){ return _b_.None} frozenset.__new__=function(cls,iterable){if(cls===undefined){$B.RAISE(_b_.TypeError,"frozenset.__new__(): not enough arguments")} var self=make_new_set(cls) if(iterable===undefined){return self} $B.check_nb_args_no_kw('__new__',2,arguments) if(cls===frozenset && iterable.__class__===frozenset){return iterable} set.update(self,iterable) return self} frozenset.__repr__=function(self){$B.builtins_repr_check(frozenset,arguments) return set_repr(self)} frozenset.copy=function(self){if(self.__class__===frozenset){return self} return set_copy(self)} frozenset.$factory=function(){var args=[frozenset].concat(Array.from(arguments)),self=frozenset.__new__.apply(null,args) frozenset.__init__(self,...arguments) return self} $B.set_func_names(frozenset,"builtins") _b_.set=set _b_.frozenset=frozenset})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,_window=globalThis var Module=$B.module=$B.make_class("module",function(name,doc,$package){return{ $tp_class:Module,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc ||_b_.None,__package__:$package ||_b_.None}} ) Module.__annotations__=_b_.property.$factory( function(){return 'coucou'} ) Module.__dir__=function(self){if(self.__dir__){return $B.$call(self.__dir__)()} var res=[] for(var key in self){if(key.startsWith('$')||key=='__class__'){continue} res[res.length]=key} return $B.$list(res.sort())} Module.__new__=function(cls,name,doc,$package){return{ __class__:cls,__builtins__:_b_.__builtins__,__name__:name,__doc__:doc ||_b_.None,__package__:$package ||_b_.None}} Module.__repr__=Module.__str__=function(self){var res=""} Module.__setattr__=function(self,attr,value){if(self.__name__=='__builtins__'){ $B.builtins[attr]=value}else if(self.__name__=='builtins'){_b_[attr]=value}else{self[attr]=value}} $B.set_func_names(Module,"builtins") $B.make_import_paths=function(filename){ var filepath=$B.script_domain ? $B.script_domain+'/'+filename :filename var elts=filepath.split('/') elts.pop() var script_dir=elts.join('/'),path=[$B.brython_path+'Lib',$B.brython_path+'libs',script_dir,$B.brython_path+'Lib/site-packages'] var meta_path=[],path_hooks=[] if($B.use_VFS){meta_path.push($B.finders.VFS)} var static_stdlib_import=$B.get_option_from_filename('static_stdlib_import',filename) if(static_stdlib_import !==false && $B.protocol !="file"){ meta_path.push($B.finders.stdlib_static) if(path.length > 3){path.shift() path.shift()}} var pythonpath=$B.get_option_from_filename('pythonpath',filename) if(pythonpath){ var ix=path.indexOf(script_dir) if(ix===-1){console.log('bizarre, script_dir',script_dir,'not in path',path)}else{var fullpaths=[] for(var p of pythonpath){if(p=='.'){fullpaths.push(script_dir)}else if(p.startsWith('/')){ fullpaths.push($B.script_domain+p)}else if(p.split('://')[0].startsWith('http')){ fullpaths.push(p)}else if(! p.startsWith($B.script_domain)){fullpaths.push(script_dir+'/'+p)}else{fullpaths.push(p)}} path.splice(ix,1,...fullpaths)}} if($B.protocol !=="file"){meta_path.push($B.finders.path) path_hooks.push($B.url_hook)} $B.import_info[filename]={meta_path,path_hooks,path}} function $download_module(mod,url){var xhr=new XMLHttpRequest(),fake_qs="?v="+(new Date().getTime()),res=null,mod_name=mod.__name__ if($B.get_option('cache')){xhr.open("GET",url,false)}else{xhr.open("GET",url+fake_qs,false)} var timer=_window.setTimeout(function(){xhr.abort()},5000) xhr.send() if($B.$CORS){if(xhr.status==200 ||xhr.status==0){res=xhr.responseText}else{res=$B.EXC(_b_.ModuleNotFoundError,"No module named '"+ mod_name+"'")}}else{if(xhr.readyState==4){if(xhr.status==200){res=xhr.responseText mod.$last_modified= xhr.getResponseHeader("Last-Modified")}else{ console.info("Trying to import "+mod_name+ ", not found at url "+url) res=$B.EXC(_b_.ModuleNotFoundError,"No module named '"+ mod_name+"'")}}} _window.clearTimeout(timer) if(res==null){$B.RAISE(_b_.ModuleNotFoundError,"No module named '"+ mod_name+"' (res is null)")} if($B.$isinstance(res,_b_.BaseException)){throw res} return res} $B.$download_module=$download_module $B.addToImported=function(name,modobj){if($B.imported[name]){for(var attr in $B.imported[name]){if(! modobj.hasOwnProperty(attr)){modobj[attr]=$B.imported[name][attr]}}} $B.imported[name]=modobj if(modobj===undefined){$B.RAISE(_b_.ImportError,'imported not set by module')} modobj.__class__=Module modobj.__name__=name for(var attr in modobj){if(typeof modobj[attr]=="function" && ! modobj[attr].$infos){modobj[attr].$infos={__module__:name,__name__:attr,__qualname__:attr,__code__:{co_filename:modobj.__file__,co_code:modobj[attr]+'',co_flags:$B.COMPILER_FLAGS.OPTIMIZED |$B.COMPILER_FLAGS.NEWLOCALS}} modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&& ! modobj[attr].hasOwnProperty('__module__')){modobj[attr].__module__=name}}} function run_js(module_contents,path,_module){var keys_before=new Set(Object.keys(globalThis)) try{new Function(module_contents)()}catch(err){throw $B.exception(err)} var new_keys=(new Set(Object.keys(globalThis))).difference(keys_before) var modobj=$B.imported[_module.__name__] if(modobj===undefined){$B.RAISE(_b_.ImportError,'imported not set by module')} modobj.__class__=Module modobj.__name__=_module.__name__ for(var new_key of new_keys){modobj[new_key]=globalThis[new_key] delete globalThis[new_key]} for(var attr in modobj){if(typeof modobj[attr]=="function" && ! modobj[attr].$infos){modobj[attr].$infos={__module__:_module.__name__,__name__:attr,__qualname__:attr} modobj[attr].$in_js_module=true}else if($B.$isinstance(modobj[attr],_b_.type)&& ! modobj[attr].hasOwnProperty('__module__')){modobj[attr].__module__=_module.__name__}} return true} function run_py(module_contents,path,module,compiled){ var filename=module.__file__ $B.file_cache[filename]=module_contents $B.url2name[filename]=module.__name__ var root,js,mod_name=module.__name__, src if(! compiled){src={src:module_contents,filename,imported:true} try{root=$B.py2js(src,module,module.__name__,$B.builtins_scope)}catch(err){err.$frame_obj=$B.frame_obj if($B.get_option('debug',err)> 1){console.log('error in imported module',module) console.log('stack',$B.make_frames_stack(err.$frame_obj))} throw err}} try{js=compiled ? module_contents :root.to_js() if($B.get_option('debug')==10){console.log("code for module "+module.__name__) console.log($B.format_indent(js,0))} src=js js="var $module = (function(){\n"+js var prefix='locals_' js+='return '+prefix js+=module.__name__.replace(/\./g,"_")+"})(__BRYTHON__)\n"+ "return $module" var module_id=prefix+module.__name__.replace(/\./g,'_') var mod=(new Function(module_id,js))(module)}catch(err){err.$frame_obj=err.$frame_obj ||$B.frame_obj if($B.get_option('debug',err)> 2){console.log(err+" for module "+module.__name__) console.log("module",module) console.log(root) if($B.get_option('debug',err)> 1){console.log($B.format_indent(js,0))} for(let attr in err){console.log(attr,err[attr])} console.log("message: "+err.$message) console.log("filename: "+err.fileName) console.log("linenum: "+err.lineNumber) console.log(js.split('\n').slice(err.lineNumber-3,err.lineNumber+3).join('\n')) console.log(err.stack)} throw err} var imports=Object.keys(root.imports).join(",") try{ for(let attr in mod){module[attr]=mod[attr]} module.__initializing__=false return{ content:src,name:mod_name,imports,is_package:module.$is_package,path,timestamp:$B.timestamp,source_ts:module.__spec__.loader_state.timestamp}}catch(err){console.log(""+err+" "+" for module "+module.__name__) for(let attr in err){console.log(attr+" "+err[attr])} if($B.get_option('debug')> 0){console.log("line info "+__BRYTHON__.line_info)} throw err}} $B.run_py=run_py $B.run_js=run_js var ModuleSpec=$B.make_class("ModuleSpec",function(fields){fields.__class__=ModuleSpec fields.__dict__=$B.empty_dict() return fields} ) ModuleSpec.__str__=ModuleSpec.__repr__=function(self){var res=`ModuleSpec(name='${self.name}', `+ `loader=${_b_.str.$factory(self.loader)}, `+ `origin='${self.origin}'` if(self.submodule_search_locations !==_b_.None){res+=`, submodule_search_locations=`+ `${_b_.str.$factory(self.submodule_search_locations)}`} return res+')'} $B.set_func_names(ModuleSpec,"builtins") function parent_package(mod_name){ var parts=mod_name.split(".") parts.pop() return parts.join(".")} var VFSFinder=$B.make_class("VFSFinder",function(){return{ __class__:VFSFinder}} ) VFSFinder.find_spec=function(cls,fullname){var stored,is_package,timestamp if(!$B.use_VFS){return _b_.None} stored=$B.VFS[fullname] if(stored===undefined){return _b_.None} is_package=stored[3]||false timestamp=stored.timestamp if(stored){var is_builtin=$B.builtin_module_names.indexOf(fullname)>-1 return ModuleSpec.$factory({name :fullname,loader:VFSLoader.$factory(), origin :is_builtin? "built-in" :"brython_stdlib", submodule_search_locations:is_package? $B.$list([]):_b_.None,loader_state:{stored:stored,timestamp:timestamp}, cached:_b_.None,parent:is_package? fullname :parent_package(fullname),has_location:_b_.False})}} $B.set_func_names(VFSFinder,"") for(let method in VFSFinder){if(typeof VFSFinder[method]=="function"){VFSFinder[method]=_b_.classmethod.$factory( VFSFinder[method])}} const VFSLoader=$B.make_class("VFSLoader",function(){return{ __class__:VFSLoader}} ) VFSLoader.create_module=function(){ return _b_.None} VFSLoader.exec_module=function(self,modobj){ var stored=modobj.__spec__.loader_state.stored,timestamp=modobj.__spec__.loader_state.timestamp var ext=stored[0],module_contents=stored[1],imports=stored[2] modobj.$is_package=stored[3]||false var path="VFS."+modobj.__name__ path+=modobj.$is_package ? "/__init__.py" :ext modobj.__file__=path $B.file_cache[modobj.__file__]=$B.VFS[modobj.__name__][1] $B.url2name[modobj.__file__]=modobj.__name__ if(ext=='.js'){run_js(module_contents,modobj.__path__,modobj)}else if($B.precompiled.hasOwnProperty(modobj.__name__)){if($B.get_option('debug')> 1){console.info("load",modobj.__name__,"from precompiled")} var parts=modobj.__name__.split(".") for(var i=0;i < parts.length;i++){var parent=parts.slice(0,i+1).join(".") if($B.imported.hasOwnProperty(parent)&& $B.imported[parent].__initialized__){continue} var mod_js=$B.precompiled[parent],is_package=modobj.$is_package if(mod_js===undefined){ continue} if(Array.isArray(mod_js)){mod_js=mod_js[0]} var mod=$B.imported[parent]=Module.$factory(parent,undefined,is_package) mod.__initialized__=true mod.__spec__=modobj.__spec__ if(is_package){mod.__path__="" mod.__package__=parent mod.$is_package=true}else{let elts=parent.split(".") elts.pop() mod.__package__=elts.join(".")} mod.__file__=path try{var parent_id=parent.replace(/\./g,"_"),prefix='locals_' mod_js+="return "+prefix+parent_id var $module=new Function(prefix+parent_id,mod_js)( mod)}catch(err){if($B.get_option('debug')> 1){console.log('error in module',mod) console.log(err) for(var k in err){console.log(k,err[k])} console.log(Object.keys($B.imported)) console.log(modobj,"mod_js",mod_js)} throw err} for(var attr in $module){mod[attr]=$module[attr]} $module.__file__=path if(i > 0){ $B.builtins.setattr( $B.imported[parts.slice(0,i).join(".")],parts[i],$module)}} return $module}else{var mod_name=modobj.__name__ if($B.get_option('debug')> 1){console.log("run Python code from VFS",mod_name)} var path=$B.brython_path+'/'+modobj.__file__ var record=run_py(module_contents,path,modobj) record.imports=imports.join(',') record.is_package=modobj.$is_package record.timestamp=$B.timestamp record.source_ts=timestamp $B.precompiled[mod_name]=record.is_package ?[record.content]: record.content let elts=mod_name.split(".") if(elts.length > 1){elts.pop()} if($B.get_page_option('indexeddb')&& $B.indexedDB && $B.idb_name){ var idb_cx=indexedDB.open($B.idb_name) idb_cx.onsuccess=function(evt){var db=evt.target.result,tx=db.transaction("modules","readwrite"),store=tx.objectStore("modules"),request=store.put(record) request.onsuccess=function(){if($B.get_option('debug')> 1){console.info(modobj.__name__,"stored in db")}} request.onerror=function(){console.info("could not store "+modobj.__name__)}}}}} $B.set_func_names(VFSLoader,"builtins") var StdlibStaticFinder=$B.make_class("StdlibStaticFinder",function(){return{ __class__:StdlibStaticFinder}} ) StdlibStaticFinder.find_spec=function(self,fullname){ if($B.stdlib && $B.get_option('static_stdlib_import')){var address=$B.stdlib[fullname] if(address===undefined){var elts=fullname.split(".") if(elts.length > 1){elts.pop() var $package=$B.stdlib[elts.join(".")] if($package && $package[1]){address=["py"]}}} if(address !==undefined){var ext=address[0],is_pkg=address[1]!==undefined,path=$B.brython_path+ ((ext=="py")? "Lib/" :"libs/")+ fullname.replace(/\./g,"/"),metadata={ext:ext,is_package:is_pkg,path:path+(is_pkg? "/__init__.py" : ((ext=="py")? ".py" :".js")),address:address},_module=Module.$factory(fullname) metadata.code=$download_module(_module,metadata.path) var res=ModuleSpec.$factory({name :fullname,loader:PathLoader.$factory(), origin :metadata.path,submodule_search_locations:is_pkg? $B.$list([path]):_b_.None,loader_state:metadata, cached:_b_.None,parent:is_pkg ? fullname :parent_package(fullname),has_location:_b_.True}) return res}} return _b_.None} $B.set_func_names(StdlibStaticFinder,"") for(let method in StdlibStaticFinder){if(typeof StdlibStaticFinder[method]=="function"){StdlibStaticFinder[method]=_b_.classmethod.$factory( StdlibStaticFinder[method])}} StdlibStaticFinder.$factory=function(){return{__class__:StdlibStaticFinder}} var PathFinder=$B.make_class("PathFinder",function(){return{ __class__:PathFinder}} ) PathFinder.find_spec=function(cls,fullname,path){if($B.VFS && $B.VFS[fullname]){ return _b_.None} if($B.is_none(path)){ path=get_info('path')} for(var i=0,li=path.length;i < li;++i){var path_entry=path[i] if(path_entry[path_entry.length-1]!="/"){path_entry+="/"} var finder=$B.path_importer_cache[path_entry] if(finder===undefined){ var path_hooks=get_info('path_hooks') for(var j=0,lj=path_hooks.length;j < lj;++j){var hook=path_hooks[j] try{finder=$B.$call(hook)(path_entry) $B.path_importer_cache[path_entry]=finder break}catch(e){if(e.__class__ !==_b_.ImportError){throw e}}}} if($B.is_none(finder)){continue} var find_spec=$B.$getattr(finder,"find_spec"),spec=$B.$call(find_spec)(fullname) if(!$B.is_none(spec)){return spec}} return _b_.None} $B.set_func_names(PathFinder,"") for(let method in PathFinder){if(typeof PathFinder[method]=="function"){PathFinder[method]=_b_.classmethod.$factory( PathFinder[method])}} var PathEntryFinder=$B.make_class("PathEntryFinder",function(path_entry,hint){return{ __class__:PathEntryFinder,path_entry:path_entry,hint:hint}} ) PathEntryFinder.find_spec=function(self,fullname){ var loader_data={},notfound=true,hint=self.hint,base_path=self.path_entry+fullname.match(/[^.]+$/g)[0],modpaths=[],py_ext=$B.get_option('python_extension') var tryall=hint===undefined if(tryall ||hint=='py'){ modpaths=modpaths.concat([[base_path+py_ext,"py",false],[base_path+"/__init__"+py_ext,"py",true],[base_path+'.js','js',false]])} for(var j=0;notfound && j < modpaths.length;++j){try{var file_info=modpaths[j],module={__name__:fullname,$is_package:false} loader_data.code=$download_module(module,file_info[0],undefined) notfound=false loader_data.ext=file_info[1] loader_data.is_package=file_info[2] loader_data.timestamp=Date.parse(module.$last_modified) if(hint===undefined){self.hint=file_info[1] $B.path_importer_cache[self.path_entry]=self} if(loader_data.is_package){ $B.path_importer_cache[base_path+'/']= $B.$call(url_hook)(base_path+'/',self.hint)} loader_data.path=file_info[0]}catch(err){if(err.__class__ !==_b_.ModuleNotFoundError){throw err}}} if(!notfound){return ModuleSpec.$factory({name :fullname,loader:PathLoader.$factory(),origin :loader_data.path, submodule_search_locations:loader_data.is_package? $B.$list([base_path]):_b_.None,loader_state:loader_data, cached:_b_.None,parent:loader_data.is_package? fullname : parent_package(fullname),has_location:_b_.True})} return _b_.None} $B.set_func_names(PathEntryFinder,"builtins") var PathLoader=$B.make_class("PathLoader",function(){return{ __class__:PathLoader}} ) PathLoader.create_module=function(){ return _b_.None} PathLoader.exec_module=function(self,module){ var metadata=module.__spec__.loader_state module.$is_package=metadata.is_package if(metadata.ext=="py"){run_py(metadata.code,metadata.path,module)}else{run_js(metadata.code,metadata.path,module)}} var url_hook=$B.url_hook=function(path_entry){ path_entry=path_entry.endsWith("/")? path_entry :path_entry+"/" return PathEntryFinder.$factory(path_entry)} function get_info(info){var filename=$B.get_filename(),import_info=$B.import_info[filename] if(import_info===undefined && info=='meta_path'){$B.make_import_paths(filename)} return $B.import_info[filename][info]} function import_engine(mod_name,_path,from_stdlib){ var meta_path=get_info('meta_path').slice(),_sys_modules=$B.imported,_loader,spec if(from_stdlib){ var path_ix=meta_path.indexOf($B.finders["path"]) if(path_ix >-1){meta_path.splice(path_ix,1)}} for(var i=0,len=meta_path.length;i < len;i++){var _finder=meta_path[i],find_spec=$B.$getattr(_finder,"find_spec",_b_.None) if(find_spec==_b_.None){ var find_module=$B.$getattr(_finder,"find_module",_b_.None) if(find_module !==_b_.None){_loader=find_module(mod_name,_path) if(_loader !==_b_.None){ var load_module=$B.$getattr(_loader,"load_module"),module=$B.$call(load_module)(mod_name) _sys_modules[mod_name]=module return module}}}else{spec=find_spec(mod_name,_path) if(!$B.is_none(spec)){module=$B.imported[spec.name] if(module !==undefined){ return _sys_modules[spec.name]=module} _loader=$B.$getattr(spec,"loader",_b_.None) break}}} if(_loader===undefined){ var message=mod_name if($B.protocol=="file"){message+=" (warning: cannot import local files with protocol 'file')"} var exc=$B.EXC(_b_.ModuleNotFoundError,message) exc.name=mod_name throw exc} if($B.is_none(module)){if(spec===_b_.None){$B.RAISE(_b_.ModuleNotFoundError,mod_name)} var _spec_name=$B.$getattr(spec,"name") if(!$B.is_none(_loader)){var create_module=$B.$getattr(_loader,"create_module",_b_.None) if(!$B.is_none(create_module)){module=$B.$call(create_module)(spec)}} if(module===undefined){$B.RAISE(_b_.ImportError,mod_name)} if($B.is_none(module)){ module=$B.module.$factory(mod_name)}} module.__name__=_spec_name module.__loader__=_loader module.__package__=$B.$getattr(spec,"parent","") module.__spec__=spec var locs=$B.$getattr(spec,"submodule_search_locations") if(module.$is_package=!$B.is_none(locs)){module.__path__=locs} if($B.$getattr(spec,"has_location")){module.__file__=$B.$getattr(spec,"origin")} var cached=$B.$getattr(spec,"cached") if(! $B.is_none(cached)){module.__cached__=cached} if($B.is_none(_loader)){if(!$B.is_none(locs)){_sys_modules[_spec_name]=module}else{$B.RAISE(_b_.ImportError,mod_name)}}else{var exec_module=$B.$getattr(_loader,"exec_module",_b_.None) if($B.is_none(exec_module)){ module=$B.$getattr(_loader,"load_module")(_spec_name)}else{_sys_modules[_spec_name]=module try{exec_module(module)}catch(e){delete _sys_modules[_spec_name] throw e}}} return _sys_modules[_spec_name]} $B.path_importer_cache={} function import_error(mod_name){var exc=$B.EXC(_b_.ImportError,mod_name) exc.name=mod_name throw exc} $B.$__import__=function(mod_name,globals,locals,fromlist){var $test=false if($test){console.log("__import__",mod_name,'fromlist',fromlist);alert()} var from_stdlib=false if(globals.$jsobj && globals.$jsobj.__file__){var file=globals.$jsobj.__file__ if((file.startsWith($B.brython_path+"Lib/")&& ! file.startsWith($B.brython_path+"Lib/site-packages/"))|| file.startsWith($B.brython_path+"libs/")|| file.startsWith("VFS.")){from_stdlib=true}} var modobj=$B.imported[mod_name],parsed_name=mod_name.split('.'),has_from=fromlist.length > 0 if(modobj==_b_.None){ import_error(mod_name)} if(modobj===undefined){ if($B.is_none(fromlist)){fromlist=[]} for(var i=0,modsep="",_mod_name="",len=parsed_name.length-1,__path__=_b_.None;i <=len;++i){var _parent_name=_mod_name; _mod_name+=modsep+parsed_name[i] modsep="." modobj=$B.imported[_mod_name] if($test){console.log("iter",i,_mod_name,"\nmodobj",modobj,"\n__path__",__path__,Array.isArray(__path__)) alert()} if(modobj==_b_.None){ import_error(_mod_name)}else if(modobj===undefined){try{import_engine(_mod_name,__path__,from_stdlib)}catch(err){delete $B.imported[_mod_name] throw err} if($B.is_none($B.imported[_mod_name])){import_error(_mod_name)}else{ if(_parent_name){_b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])}}}else if($B.imported[_parent_name]&& $B.imported[_parent_name][parsed_name[i]]===undefined){ _b_.setattr($B.imported[_parent_name],parsed_name[i],$B.imported[_mod_name])} if(i < len){try{__path__=$B.$getattr($B.imported[_mod_name],"__path__")}catch(e){ if(i==len-1 && $B.imported[_mod_name][parsed_name[len]]&& $B.imported[_mod_name][parsed_name[len]].__class__=== $B.module){return $B.imported[_mod_name][parsed_name[len]]} if(has_from){ import_error(mod_name)}else{ var exc=$B.EXC(_b_.ModuleNotFoundError) exc.__traceback__=$B.make_tb() exc.msg="No module named '"+mod_name+"'; '"+ _mod_name+"' is not a package" exc.args=$B.fast_tuple([exc.msg]) exc.name=mod_name exc.path=_b_.None throw exc}}}}}else{if($B.imported[parsed_name[0]]&& 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) throw err}}} if(fromlist.length > 0){ return $B.imported[mod_name]}else{ let package_name=mod_name while(parsed_name.length > 1){var module=parsed_name.pop(); package_name=parsed_name.join('.') if($B.imported[package_name]===undefined){ $B.$import(package_name,[],{},locals) $B.imported[package_name][module]=$B.imported[mod_name] mod_name=module}} return $B.imported[package_name]}} $B.$import=function(mod_name,fromlist,aliases,locals,inum){ var test=false if(test){console.log('import',mod_name,fromlist,aliases)} if(mod_name=='_frozen_importlib_external'){ var ns,alias if(aliases[mod_name]){[ns,alias]=aliases[mod_name]}else{[ns,alias]=[locals,mod_name]} $B.$import_from("importlib",["_bootstrap_external"],{_bootstrap_external:[ns,alias]},locals,0) let _bootstrap=$B.imported.importlib._bootstrap,_bootstrap_external=$B.imported.importlib['_bootstrap_external'] _bootstrap_external._set_bootstrap_module(_bootstrap) _bootstrap._bootstap_external=_bootstrap_external let _frozen_importlib=$B.imported._frozen_importlib if(_frozen_importlib){_frozen_importlib._bootstrap_external=_bootstrap_external} return} var level=0,frame=$B.frame_obj.frame,current_module=frame[2],parts=current_module.split('.') while(mod_name.length > 0 && mod_name.startsWith('.')){level++ mod_name=mod_name.substr(1) if(parts.length==0){$B.RAISE(_b_.ImportError,"Parent module '' not loaded, "+ "cannot perform relative import")} current_module=parts.join('.') parts.pop()} if(level > 0){mod_name=current_module+ (mod_name.length > 0 ? '.'+mod_name :'')} parts=mod_name.split(".") if(mod_name[mod_name.length-1]=="."){parts.pop()} var norm_parts=[],prefix=true for(var p of parts){if(prefix && p==""){ var elt=norm_parts.pop() if(elt===undefined){$B.RAISE(_b_.ImportError,"Parent module '' not loaded, "+ "cannot perform relative import")}}else{prefix=false; norm_parts.push(p)}} mod_name=norm_parts.join(".") fromlist=fromlist===undefined ?[]:fromlist aliases=aliases===undefined ?{}:aliases locals=locals===undefined ?{}:locals if(test){console.log('step 2, mod_name',mod_name,'fromlist',fromlist)} if($B.get_option('debug')==10){console.log("$import "+mod_name) console.log("use VFS ? "+$B.use_VFS) console.log("use static stdlib paths ? "+ $B.get_option('static_stdlib_import'))} var current_frame=$B.frame_obj.frame,_globals=current_frame[3],__import__=_globals["__import__"],globals=$B.obj_dict(_globals) if(__import__===undefined){ __import__=$B.$__import__} var importer=typeof __import__=="function" ? __import__ : $B.$getattr(__import__,"__call__") if(test){console.log('use importer',importer,'mod_name',mod_name,'fromlist',fromlist)} try{var modobj=importer(mod_name,globals,undefined,fromlist,0)}catch(err){if(test){console.log('set error',err.__class__)} $B.set_inum(inum) throw err} if(test){console.log('step 3, mod_name',mod_name,'fromlist',fromlist) console.log('modobj',modobj)} if(! fromlist ||fromlist.length==0){ let alias=aliases[mod_name] if(alias){var[ns,name]=alias ns[name]=$B.imported[mod_name]}else{locals[norm_parts[0]]=modobj}}else{var __all__=fromlist,thunk={} if(fromlist && fromlist[0]=="*"){if(test){console.log('import *',modobj)} __all__=$B.$getattr(modobj,"__all__",thunk); if(__all__ !==thunk){ aliases={}}} if(__all__===thunk){ for(var attr in modobj){if(attr[0]!=="_"){locals[attr]=modobj[attr]}}}else{ for(let name of __all__){var[ns,alias]=[locals,name] if(aliases[name]){[ns,alias]=aliases[name]} try{ ns[alias]=$B.$getattr(modobj,name) if(ns[alias]&& ns[alias].$js_func){ ns[alias]=ns[alias].$js_func}}catch($err1){if(! $B.is_exc($err1,[_b_.AttributeError])){$B.set_inum(inum) throw $err1} try{if(test){console.log('try to import',mod_name+'.'+name)} $B.$getattr(__import__,'__call__')(mod_name+'.'+name,globals,undefined,[],0) ns[alias]=$B.$getattr(modobj,name)}catch($err3){if(test){console.log('error 3',$err3)} $B.set_inum(inum) if(! $B.is_exc($err3,[_b_.ImportError])){throw $err3} if(mod_name==="__future__"){ var exc=$B.EXC(_b_.SyntaxError,"future feature "+name+" is not defined") throw exc} var $frame=[mod_name,modobj,mod_name,modobj],suggestion=$B.offer_suggestions_for_name_error($err3,$frame) if($err3.$py_error){$err3.__class__=_b_.ImportError $err3.args[0]=`cannot import name '${name}' `+ `from '${mod_name}'` if(modobj.__file__){$err3.args[0]+=` (${modobj.__file__})`} $err3.$suggestion=suggestion throw $err3} if($B.get_option('debug')> 2){console.log('no name',name,'in module',modobj) console.log($err3) console.log($B.frame_obj.frame)} $B.RAISE(_b_.ImportError,"cannot import name '"+name+"'")}}}} return locals}} $B.$import_from=function(module,names,aliases,level,locals,inum){ var current_module_name=$B.frame_obj.frame[2],parts=current_module_name.split('.'),relative=level > 0,current_module if(relative){ current_module=$B.imported[parts.join('.')] if(current_module===undefined){$B.set_inum(inum) $B.RAISE(_b_.ImportError,'attempted relative import with no known parent package')} if(! current_module.$is_package){if(parts.length==1){$B.set_inum(inum) $B.RAISE(_b_.ImportError,'attempted relative import with no known parent package')}else{parts.pop() current_module=$B.imported[parts.join('.')]}} while(level > 0){current_module=$B.imported[parts.join('.')] if(! current_module.$is_package){$B.set_inum(inum) $B.RAISE(_b_.ImportError,'attempted relative import with no known parent package')} level-- parts.pop()} if(module){ var submodule=current_module.__name__+'.'+module $B.$import(submodule,[],{},{},inum) current_module=$B.imported[submodule]} if(names.length > 0 && names[0]=='*'){ for(var key in current_module){if(key.startsWith('$')||key.startsWith('_')){continue} locals[key]=current_module[key]}}else{for(var name of names){var ns,alias if(aliases[name]){[ns,alias]=aliases[name]}else{[ns,alias]=[locals,name]} if(current_module[name]!==undefined){ ns[alias]=current_module[name]}else{ var sub_module=current_module.__name__+'.'+name $B.$import(sub_module,[],{},{}) ns[alias]=$B.imported[sub_module]}}}}else{ $B.$import(module,names,aliases,locals,inum)}} $B.$meta_path=[VFSFinder,StdlibStaticFinder,PathFinder] $B.finders={VFS:VFSFinder,stdlib_static:StdlibStaticFinder,path:PathFinder} function optimize_import_for_path(path,filetype){if(path.slice(-1)!="/"){path=path+"/" } var value=(filetype=='none')? _b_.None : url_hook(path,filetype) $B.path_importer_cache[path]=value} var Loader={__class__:$B.$type,__mro__:[_b_.object],__name__ :"Loader"} var _importlib_module={__class__ :Module,__name__ :"_importlib",Loader:Loader,VFSFinder:VFSFinder,StdlibStatic:StdlibStaticFinder,ImporterPath:PathFinder,UrlPathFinder:url_hook,optimize_import_for_path :optimize_import_for_path} _importlib_module.__repr__=_importlib_module.__str__=function(){return ""} $B.imported["_importlib"]=_importlib_module})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var escape2cp=$B.escape2cp={b:'\b',f:'\f',n:'\n',r:'\r',t:'\t',v:'\v'} $B.surrogates=function(s){var s1='',escaped=false for(var char of s){if(escaped){var echar=escape2cp[char] if(echar !==undefined){s1+=echar}else{s1+='\\'+char} escaped=false}else if(char=='\\'){escaped=true}else{s1+=char}} var surrogates=[],j=0 for(var i=0,len=s1.length;i < len;i++){var cp=s1.codePointAt(i) if(cp >=0x10000){surrogates.push(j) i++} j++} return surrogates} $B.String=function(s){var srg=$B.surrogates(s) return srg.length==0 ? s :$B.make_String(s,srg)} $B.make_String=function(s,surrogates){var res=new String(s) res.__class__=str res.surrogates=surrogates return res} function pypos2jspos(s,pypos){ if(s.surrogates===undefined){return pypos} var nb=0 while(s.surrogates[nb]< pypos){nb++} return pypos+nb} function jspos2pypos(s,jspos){ if(s.surrogates===undefined){return jspos} var nb=0 while(s.surrogates[nb]+nb < jspos){nb++} return jspos-nb} function to_string(args){if(typeof args=='string'){return args} if(Array.isArray(args)){for(var i=0,len=args.length;i < len;i++){args[i]=to_string(args[i])} return args}else{if(args.__class__ && !(args instanceof String)){return args.$brython_value}else{return args}}} var str={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:'str',$is_class:true,$is_sequence:true,$native:true} str.$to_string=to_string function normalize_start_end($){var len if(typeof $.self=="string"){len=$.self.length}else{len=str.__len__($.self)} if($.start===null ||$.start===_b_.None){$.start=0}else if($.start < 0){$.start+=len $.start=Math.max(0,$.start)} if($.end===null ||$.end===_b_.None){$.end=len}else if($.end < 0){$.end+=len $.end=Math.max(0,$.end)} if(! $B.$isinstance($.start,_b_.int)||! $B.$isinstance($.end,_b_.int)){$B.RAISE(_b_.TypeError,"slice indices must be integers "+ "or None or have an __index__ method")} if($.self.surrogates){$.js_start=pypos2jspos($.self,$.start) $.js_end=pypos2jspos($.self,$.end)}} function reverse(s){ return s.split("").reverse().join("")} function check_str(obj,prefix){if(obj instanceof String ||typeof obj=="string"){return} if(! $B.$isinstance(obj,str)){$B.RAISE(_b_.TypeError,(prefix ||'')+ "must be str, not "+$B.class_name(obj))}} function to_chars(s){ s=to_string(s) return Array.from(s)} str.__add__=function(_self,other){if(! $B.$isinstance(other,str)){try{return $B.$getattr(other,"__radd__")(_self)}catch(err){$B.RAISE(_b_.TypeError,"Can't convert "+ $B.class_name(other)+" to str implicitly")}} [_self,other]=to_string([_self,other]) if(typeof _self=='string' && typeof other=='string'){return _self+other} return $B.String(_self+other)} str.__contains__=function(_self,item){if(! $B.$isinstance(item,str)){$B.RAISE(_b_.TypeError,"'in ' requires "+ "string as left operand, not "+$B.class_name(item))} [_self,item]=to_string([_self,item]) return _self.includes(item)} str.__delitem__=function(){$B.RAISE(_b_.TypeError,"'str' object doesn't support item deletion")} str.__dir__=_b_.object.__dir__ str.__eq__=function(_self,other){if($B.$isinstance(other,str)){[_self,other]=to_string([_self,other]) return _self+''==other+''} return _b_.NotImplemented} function preformat(_self,fmt){if(fmt.empty){return _b_.str.$factory(_self)} if(fmt.type && fmt.type !="s"){$B.RAISE(_b_.ValueError,"Unknown format code '"+fmt.type+ "' for object of type 'str'")} return _self} str.__format__=function(_self,format_spec){[_self,format_spec]=to_string([_self,format_spec]) var fmt=new $B.parse_format_spec(format_spec,_self) if(fmt.sign !==undefined){$B.RAISE(_b_.ValueError,"Sign not allowed in string format specifier")} if(fmt.precision){_self=_self.substr(0,fmt.precision)} fmt.align=fmt.align ||"<" return $B.format_width(preformat(_self,fmt),fmt)} str.__getitem__=function(_self,arg){_self=to_string(_self) if($B.$isinstance(arg,_b_.int)){var len=str.__len__(_self) var pos=arg if(arg < 0){pos+=len} if(pos >=0 && pos < len){var jspos=pypos2jspos(_self,pos) if(_self.codePointAt(jspos)>=0x10000){return $B.String(_self.substr(jspos,2))}else{return _self[jspos]}} $B.RAISE(_b_.IndexError,"string index out of range")} if($B.$isinstance(arg,_b_.slice)){return _b_.str.$getitem_slice(_self,arg)} if($B.$isinstance(arg,_b_.bool)){return _self.__getitem__(_b_.int.$factory(arg))} $B.RAISE(_b_.TypeError,"string indices must be integers")} str.$getitem_slice=function(_self,slice){var len=str.__len__(_self),s=_b_.slice.$conv_for_seq(slice,len),start=pypos2jspos(_self,s.start),stop=pypos2jspos(_self,s.stop),step=s.step var res="" if(step > 0){if(stop <=start){return ""} for(let i=start;i < stop;i+=step){res+=_self[i]}}else{if(stop >=start){return ''} for(let i=start;i > stop;i+=step){res+=_self[i]}} return $B.String(res)} var prefix=2,suffix=3 str.$getnewargs=function(self){return $B.fast_tuple([to_string(self)])} str.__getnewargs__=function(){return str.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} function cyrb53(str){let h1=0xdeadbeef,h2=0x41c6ce57; for(let i=0,ch;i < str.length;i++){ch=str.charCodeAt(i); h1=Math.imul(h1 ^ ch,2654435761); h2=Math.imul(h2 ^ ch,1597334677);} h1=Math.imul(h1 ^(h1 >>> 16),2246822507); h1 ^=Math.imul(h2 ^(h2 >>> 13),3266489909); h2=Math.imul(h2 ^(h2 >>> 16),2246822507); h2 ^=Math.imul(h1 ^(h1 >>> 13),3266489909); return 4294967296*(2097151 & h2)+(h1 >>> 0);}; str.__hash__=function(_self){ var s=to_string(_self) let h1=0xdeadbeef,h2=0x41c6ce57; for(let i=0,ch;i < s.length;i++){ch=s.charCodeAt(i); h1=Math.imul(h1 ^ ch,2654435761); h2=Math.imul(h2 ^ ch,1597334677);} h1=Math.imul(h1 ^(h1 >>> 16),2246822507); h1 ^=Math.imul(h2 ^(h2 >>> 13),3266489909); h2=Math.imul(h2 ^(h2 >>> 16),2246822507); h2 ^=Math.imul(h1 ^(h1 >>> 13),3266489909); return 4294967296*(2097151 & h2)+(h1 >>> 0);} str.__init__=function(){ return _b_.None} var str_iterator=$B.make_class("str_iterator",function(s){return{ __class__:str_iterator,it:s[Symbol.iterator]()}} ) str_iterator.__iter__=function(_self){return _self} str_iterator.__next__=function(_self){var res=_self.it.next() if(res.done){$B.RAISE(_b_.StopIteration,'')} return res.value} $B.set_func_names(str_iterator,'builtins') str.__iter__=function(_self){return str_iterator.$factory(_self)} str.__len__=function(_self){_self=to_string(_self) if(_self.surrogates===undefined){return _self.length} if(_self.len !==undefined){return _self.len} var len=_self.len=_self.length-_self.surrogates.length return len} var number_check=function(s,flags){if(! $B.$isinstance(s,[_b_.int,_b_.float])){var type=flags.conversion_type $B.RAISE(_b_.TypeError,`%${type} format: a real number `+ `is required, not ${$B.class_name(s)}`)}} var get_char_array=function(size,char){if(size <=0){return ""} return new Array(size+1).join(char)} var format_padding=function(s,flags,minus_one){var padding=flags.padding if(! padding){ return s} s=s.toString() padding=parseInt(padding,10) if(minus_one){ padding-=1} if(! flags.left){return get_char_array(padding-s.length,flags.pad_char)+s}else{ return s+get_char_array(padding-s.length,flags.pad_char)}} const max_precision=2**31-4,max_repeat=2**30-1 var format_int_precision=function(val,flags){var precision=flags.precision if(! precision){return _b_.str.$factory(val)} precision=parseInt(precision,10) if(precision > max_precision){$B.RAISE(_b_.OverflowError,'precision too large')} var s if(val.__class__===$B.long_int){s=$B.long_int.to_base(val,10)}else{s=val.toString()} if(precision-s.length > max_repeat){$B.RAISE(_b_.OverflowError,'precision too large')} if(s[0]==="-"){return "-"+"0".repeat(Math.max(0,precision-s.length+1))+ s.slice(1)} return "0".repeat(Math.max(0,precision-s.length))+s} var format_float_precision=function(val,upper,flags,modifier){var precision=flags.precision if(isFinite(val)){return modifier(val,precision,flags,upper)} if(val===Infinity){val="inf"}else if(val===-Infinity){val="-inf"}else{val="nan"} if(upper){return val.toUpperCase()} return val} var format_sign=function(val,flags){if(flags.sign){if(val >=0 ||isNaN(val)||val===Number.POSITIVE_INFINITY){return "+"}}else if(flags.space){if(val >=0 ||isNaN(val)){return " "}} return ''} var str_format=function(val,flags){ flags.pad_char=" " return format_padding(str.$factory(val),flags)} var num_format=function(val,flags){number_check(val,flags) if($B.$isinstance(val,_b_.float)){val=parseInt(val.value)}else if(! $B.$isinstance(val,_b_.int)){val=parseInt(val)}else if($B.$isinstance(val,_b_.bool)){val=val ? 1 :0} var s=format_int_precision(val,flags) if(flags.pad_char==="0"){if(val < 0){s=s.substring(1) return "-"+format_padding(s,flags,true)} var sign=format_sign(val,flags) if(sign !==""){return sign+format_padding(s,flags,true)}} return format_padding(format_sign(val,flags)+s,flags)} var repr_format=function(val,flags){flags.pad_char=" " return format_padding(_b_.repr(val),flags)} var ascii_format=function(val,flags,type){flags.pad_char=" " var ascii if(type=='bytes'){var repr=_b_.repr(val) ascii=_b_.str.encode(repr,'ascii','backslashreplace') ascii=_b_.bytes.decode(ascii,'ascii')}else{ascii=_b_.ascii(val)} return format_padding(ascii,flags)} var _float_helper=function(val,flags){number_check(val,flags) if(flags.precision===undefined){if(! flags.decimal_point){flags.precision=6}else{flags.precision=0}}else{flags.precision=parseInt(flags.precision,10) validate_precision(flags.precision)} return $B.$isinstance(val,_b_.int)? val :val.value} var validate_precision=function(precision){ if(precision > 20){precision=20}} function handle_special_values(value,upper){var special if(isNaN(value)){special=upper ? "NAN" :"nan"}else if(value==Number.POSITIVE_INFINITY){special=upper ? "INF" :"inf"}else if(value==Number.NEGATIVE_INFINITY){special=upper ? "-INF" :"-inf"} return special} var floating_point_format=function(val,upper,flags){val=_float_helper(val,flags) var special=handle_special_values(val,upper) if(special){return format_padding(format_sign(val,flags)+special,flags)} var p=flags.precision if(p==0){p=1} var exp_format=val.toExponential(p-1),e_index=exp_format.indexOf('e'),exp=parseInt(exp_format.substr(e_index+1)),res function remove_zeros(v){if(flags.alternate){return v} if(v.indexOf('.')>-1){while(v.endsWith('0')){v=v.substr(0,v.length-1)} if(v.endsWith('.')){v=v.substr(0,v.length-1)}} return v} if(-4 <=exp && exp < p){ flags.precision=Math.max(0,p-1-exp) res=floating_point_decimal_format(val,upper,flags) res=remove_zeros(res)}else{ flags.precision=Math.max(0,p-1) var delim=upper ? 'E' :'e',exp_fmt=floating_point_exponential_format(val,upper,flags),parts=exp_fmt.split(delim) parts[0]=remove_zeros(parts[0]) res=parts.join(delim)} return format_padding(format_sign(val,flags)+res,flags)} var roundDownToFixed=$B.roundDownToFixed=function(v,d){if(d==0 && v.toString().indexOf('e')>-1){ return BigInt(v).toString()} const mul=Math.pow(10,d); var is_neg=v < 0 if(is_neg){v=-v} var res_floor=(Math.floor(v*mul)/mul).toFixed(d),res_ceil=(Math.ceil(v*mul)/mul).toFixed(d),res if(v-res_floor==res_ceil-v){ var last=res_floor[res_floor.length-1] res=last.match(/[02468]/)? res_floor :res_ceil}else{res=v-res_floor < res_ceil-v ? res_floor :res_ceil} return is_neg ? '-'+res :res} var floating_point_decimal_format=function(val,upper,flags){val=_float_helper(val,flags) var unpadded=format_float_precision(val,upper,flags,function(val,precision,flags){ var res=roundDownToFixed(val,precision) if(precision===0 && flags.alternate){res+='.'} if(Object.is(val,-0)){res='-'+res} return res}) return format_padding(format_sign(val,flags)+unpadded,flags)} var _floating_exp_helper=function(val,precision,flags,upper){var is_neg=false,val_pos=val.toString() if(val < 0){is_neg=true val_pos=val_pos.substr(1)}else if(Object.is(val,-0)){is_neg=true} var parts=val_pos.split('.'),exp=0,exp_sign='+',mant if(parts[0]=='0'){if(parts[1]){exp_sign='-' exp++ var i=0 while(parts[1][i]=='0'){i++} exp+=i mant=parts[1][i] if(parts[1][i+1]){mant+='.'+parts[1].substr(i+1)}}else{mant='0'}}else{exp=parts[0].length-1 mant=parts[0][0] if(parts[0].length > 1){mant+='.'+parts[0].substr(1)+(parts[1]||'')}else if(parts[1]){mant+='.'+parts[1]}} mant=parseFloat(mant) mant=roundDownToFixed(parseFloat(mant),precision) if(parseFloat(mant)==10){ parts=mant.split('.') parts[0]='1' mant=parts.join('.') exp=parseInt(exp)+(exp_sign=='+' ? 1 :-1) if(exp==0){exp_sign='+'}} if(flags.alternate && mant.indexOf('.')==-1){mant+='.'} if(exp.toString().length==1){ exp='0'+exp} return `${is_neg ? '-' : ''}${mant}${upper ? 'E' : 'e'}${exp_sign}${exp}`} var floating_point_exponential_format=function(val,upper,flags){val=_float_helper(val,flags) return format_padding(format_sign(val,flags)+ format_float_precision(val,upper,flags,_floating_exp_helper),flags)} $B.formatters={floating_point_format,floating_point_decimal_format,floating_point_exponential_format} var signed_hex_format=function(val,upper,flags){var ret if(! $B.$isinstance(val,_b_.int)){$B.RAISE(_b_.TypeError,`%X format: an integer is required, not ${$B.class_name(val)}`)}else if($B.$isinstance(val,_b_.bool)){val=val ? 1 :0} if(val.__class__===$B.long_int){ret=val.value.toString(16)}else{ret=parseInt(val) ret=ret.toString(16)} ret=format_int_precision(ret,flags) if(upper){ret=ret.toUpperCase()} if(flags.pad_char==="0"){if(val < 0){ret=ret.substring(1) ret="-"+format_padding(ret,flags,true)} var sign=format_sign(val,flags) if(sign !==""){ret=sign+format_padding(ret,flags,true)}} if(flags.alternate){if(ret.charAt(0)==="-"){if(upper){ret="-0X"+ret.slice(1)} else{ret="-0x"+ret.slice(1)}}else{if(upper){ret="0X"+ret} else{ret="0x"+ret}}} return format_padding(format_sign(val,flags)+ret,flags)} var octal_format=function(val,flags){number_check(val,flags) var ret if(val.__class__===$B.long_int){ret=$B.long_int.to_base(8)}else{ret=parseInt(val) ret=ret.toString(8)} ret=format_int_precision(ret,flags) if(flags.pad_char==="0"){if(val < 0){ret=ret.substring(1) ret="-"+format_padding(ret,flags,true)} var sign=format_sign(val,flags) if(sign !==""){ret=sign+format_padding(ret,flags,true)}} if(flags.alternate){if(ret.charAt(0)==="-"){ret="-0o"+ret.slice(1)} else{ret="0o"+ret}} return format_padding(ret,flags)} function series_of_bytes(val,flags){if(val.__class__ && val.__class__.$buffer_protocol){var it=_b_.iter(val),ints=[] while(true){try{ints.push(_b_.next(it))}catch(err){if(err.__class__===_b_.StopIteration){var b=_b_.bytes.$factory(ints) return format_padding(_b_.bytes.decode(b,"ascii"),flags)} throw err}}}else{try{var bytes_obj=$B.$getattr(val,"__bytes__")() return format_padding(_b_.bytes.decode(bytes_obj),flags)}catch(err){if(err.__class__===_b_.AttributeError){$B.RAISE(_b_.TypeError,"%b does not accept '"+ $B.class_name(val)+"'")} throw err}}} var single_char_format=function(val,flags,type){if(type=='bytes'){if($B.$isinstance(val,_b_.int)){if(val.__class__===$B.long_int ||val < 0 ||val > 255){$B.RAISE(_b_.OverflowError,"%c arg not in range(256)")}}else if($B.$isinstance(val,[_b_.bytes,_b_.bytearray])){if(val.source.length > 1){$B.RAISE(_b_.TypeError,"%c requires an integer in range(256) or a single byte")} val=val.source[0]}}else{if($B.$isinstance(val,_b_.str)){if(_b_.str.__len__(val)==1){return val} $B.RAISE(_b_.TypeError,"%c requires int or char")}else if(! $B.$isinstance(val,_b_.int)){$B.RAISE(_b_.TypeError,"%c requires int or char")} if((val.__class__===$B.long_int && (val.value < 0 ||val.value >=0x110000))|| (val < 0 ||val >=0x110000)){$B.RAISE(_b_.OverflowError,'%c arg not in range(0x110000)')}} return format_padding(_b_.chr(val),flags)} var num_flag=function(c,flags){if(c==="0" && ! flags.padding && ! flags.decimal_point && ! flags.left){flags.pad_char="0" return} if(!flags.decimal_point){flags.padding=(flags.padding ||"")+c}else{flags.precision=(flags.precision ||"")+c}} var decimal_point_flag=function(val,flags){if(flags.decimal_point){ throw new UnsupportedChar()} flags.decimal_point=true} var neg_flag=function(val,flags){flags.pad_char=" " flags.left=true} var space_flag=function(val,flags){flags.space=true} var sign_flag=function(val,flags){flags.sign=true} var alternate_flag=function(val,flags){flags.alternate=true} var char_mapping={"b":series_of_bytes,"s":str_format,"d":num_format,"i":num_format,"u":num_format,"o":octal_format,"r":repr_format,"a":ascii_format,"g":function(val,flags){return floating_point_format(val,false,flags)},"G":function(val,flags){return floating_point_format(val,true,flags)},"f":function(val,flags){return floating_point_decimal_format(val,false,flags)},"F":function(val,flags){return floating_point_decimal_format(val,true,flags)},"e":function(val,flags){return floating_point_exponential_format(val,false,flags)},"E":function(val,flags){return floating_point_exponential_format(val,true,flags)},"x":function(val,flags){return signed_hex_format(val,false,flags)},"X":function(val,flags){return signed_hex_format(val,true,flags)},"c":single_char_format,"0":function(val,flags){return num_flag("0",flags)},"1":function(val,flags){return num_flag("1",flags)},"2":function(val,flags){return num_flag("2",flags)},"3":function(val,flags){return num_flag("3",flags)},"4":function(val,flags){return num_flag("4",flags)},"5":function(val,flags){return num_flag("5",flags)},"6":function(val,flags){return num_flag("6",flags)},"7":function(val,flags){return num_flag("7",flags)},"8":function(val,flags){return num_flag("8",flags)},"9":function(val,flags){return num_flag("9",flags)},"-":neg_flag," ":space_flag,"+":sign_flag,".":decimal_point_flag,"#":alternate_flag} var UnsupportedChar=function(){this.name="UnsupportedChar"} const conversion_flags='#0- +',length_modifiers='hlL',conversion_types='diouxXeEfFgGcrsa' function parse_mod_format(s,type,pos){var flags={pad_char:' '},len=s.length,start_pos=pos,mo pos++ while(pos < len){var char=s[pos] if(char=='('){var end=s.substr(pos).indexOf(')') if(end==-1){$B.RAISE(_b_.ValueError,'incomplete format key')}else{flags.mapping_key=s.substr(pos+1,end-1) pos+=end+1}}else if(conversion_flags.indexOf(char)>-1){flags.conversion_flag=char if(char=='#'){flags.alternate=true}else if(char=='-'){flags.left=true}else if(char=='+'){flags.sign='+'}else if(char=='0'){flags.pad_char='0'}else if(char==' '){flags.space=true} pos++}else if(char=='*'){flags.padding='*' pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.padding=mo[0] pos+=mo[0].length}else if(char=='.'){pos++ if(s[pos]=='*'){flags.precision='*' pos++}else if(mo=/^\d+/.exec(s.substr(pos))){flags.precision=mo[0] pos+=mo[0].length}else{flags.precision="0"}}else if(length_modifiers.indexOf(char)>-1){flags.length_modifier=char pos++}else if((conversion_types.indexOf(char)>-1)|| (char=='b' && type=='bytes')){if(type=='bytes'){if(char=='s'){ char='b'}else if(char=='r'){char='a'}} flags.conversion_type=char flags.end=pos flags.string=s.substring(start_pos,pos+1) if(flags.left && flags.pad_char=='0'){ flags.pad_char=' '} return flags}else{$B.RAISE(_b_.ValueError,`invalid character in format: ${char}`)}} $B.RAISE(_b_.ValueError,'invalid format')} function is_mapping(obj){return _b_.hasattr(obj,'keys')&& _b_.hasattr(obj,'__getitem__')} $B.printf_format=function(s,type,args){ var argpos=null,getitem if($B.$isinstance(args,_b_.tuple)){argpos=0}else{getitem=$B.$getattr(args,"__getitem__",_b_.None)} var ret='', nbph=0, pos=0, len=s.length while(pos < len){var fmtpos=s.indexOf("%",pos) if(fmtpos < 0){ret+=s.substring(pos) break} ret+=s.substring(pos,fmtpos) pos=fmtpos if(s[pos+1]=='%'){ret+='%' pos+=2}else{nbph++ if(nbph > 1){ if((! $B.$isinstance(args,_b_.tuple))&& ! is_mapping(args)){$B.RAISE(_b_.TypeError,"not enough arguments for format string")}} var fmt=parse_mod_format(s,type,pos) pos=fmt.end+1 if(fmt.padding=='*'){ if(args[argpos]===undefined){$B.RAISE(_b_.ValueError,'no value for field width *')} fmt.padding=args[argpos] argpos++} if(fmt.precision=='*'){ if(args[argpos]===undefined){$B.RAISE(_b_.ValueError,'no value for precision *')} fmt.precision=args[argpos] argpos++} var func=char_mapping[fmt.conversion_type],value if(fmt.mapping_key !==undefined){value=getitem(fmt.mapping_key)}else{if(argpos===null){value=args}else{value=args[argpos] if(value===undefined){$B.RAISE(_b_.TypeError,"not enough arguments for format string")} argpos++}} ret+=func(value,fmt,type)}} if(argpos !==null){if(args.length > argpos){$B.RAISE(_b_.TypeError,"not enough arguments for format string")}else if(args.length < argpos){$B.RAISE(_b_.TypeError,"not all arguments converted during string formatting")}}else if(nbph==0){$B.RAISE(_b_.TypeError,"not all arguments converted during string formatting")} return ret} str.__mod__=function(_self,args){_self=to_string(_self) var res=$B.printf_format(_self,'str',args) return $B.String(res)} str.__mro__=[_b_.object] str.__mul__=function(self,other){$B.check_nb_args_no_kw('str.__mul__',2,arguments) var _self=to_string(self) if(! $B.$isinstance(other,_b_.int)){$B.RAISE(_b_.TypeError,"Can't multiply sequence by non-int of type '"+ $B.class_name(other)+"'")} return _self.repeat(other < 0 ? 0 :other)} str.__ne__=function(_self,other){var eq=str.__eq__(_self,other) return eq===_b_.NotImplemented ? eq :! eq} str.__new__=function(cls,value){if(cls===undefined){$B.RAISE(_b_.TypeError,"str.__new__(): not enough arguments")}else if(cls===_b_.str){return value}else{return{ __class__:cls,$brython_value:str.$factory(value),__dict__:$B.empty_dict()}}} str.__repr__=function(_self){ _self=to_string(_self) var t=$B.special_string_repr, repl='',chars=to_chars(_self) for(var i=0;i < chars.length;i++){var cp=_b_.ord(chars[i]) if(t[cp]!==undefined){repl+=t[cp]}else if(/\p{Cn}/u.test(chars[i])){var s=cp.toString(16) while(s.length < 4){s='0'+s} repl+='\\u'+s}else if(cp < 0x20 ||(cp >=0x7f && cp < 0xa0)){cp=cp.toString(16) if(cp.length < 2){cp='0'+cp} repl+='\\x'+cp}else if(cp >=0x300 && cp <=0x36F){repl+="\u200B"+chars[i]+' '}else if(cp.toString(16)=='feff'){repl+='\\ufeff'}else{repl+=chars[i]}} var res=repl if(res.search('"')==-1 && res.search("'")==-1){return "'"+res+"'"}else if(_self.search('"')==-1){return '"'+res+'"'} var qesc=new RegExp("'","g") res="'"+res.replace(qesc,"\\'")+"'" return res} str.__rmod__=function(self,other){$B.check_nb_args_no_kw('str.__rmod__',2,arguments) if(! $B.$isinstance(other,str)){return _b_.NotImplemented} return str.__mod__(other,self)} str.__rmul__=function(_self,other){_self=to_string(_self) if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other) var res='' while(other > 0){res+=_self other--} return res} return _b_.NotImplemented} str.__setattr__=function(_self,attr,value){if(typeof _self==="string"){if(str.hasOwnProperty(attr)){$B.RAISE_ATTRIBUTE_ERROR("'str' object attribute '"+ attr+"' is read-only",_self,attr)}else{$B.RAISE_ATTRIBUTE_ERROR( `'str' object has no attribute '${attr}' and no __dict__ `+ 'for setting new attributes',_self,attr)}} _b_.dict.$setitem(_self.__dict__,attr,value) return _b_.None} str.__setitem__=function(){$B.RAISE(_b_.TypeError,"'str' object does not support item assignment")} var combining=[] for(var cp=0x300;cp <=0x36F;cp++){combining.push(String.fromCharCode(cp))} var combining_re=new RegExp("("+combining.join("|")+")","g") str.__str__=function(_self){_self=to_string(_self) var repl='',chars=to_chars(_self) if(chars.length==_self.length){return _self.replace(combining_re,"\u200B$1")} for(var i=0;i < chars.length;i++){var cp=_b_.ord(chars[i]) if(cp >=0x300 && cp <=0x36F){repl+="\u200B"+chars[i]}else{repl+=chars[i]}} return repl} var body=`var _b_ = __BRYTHON__.builtins if(typeof other !== typeof _self){ return _b_.NotImplemented}else if(typeof _self == "string"){ return _self > other}else{ return _self.$brython_value > other.$brython_value}` var comps={">":"gt",">=":"ge","<":"lt","<=":"le"} for(var op in comps){str[`__${comps[op]}__`]=Function('_self','other',body.replace(/>/gm,op))} str.capitalize=function(self){$B.check_nb_args_no_kw('str.capitalize',1,arguments) var _self=to_string(self) if(_self.length==0){return ""} return _self.charAt(0).toUpperCase()+_self.substr(1).toLowerCase()} str.casefold=function(self){$B.check_nb_args_no_kw('set.remove',1,arguments) var res="",char,cf,_self=to_string(self),chars=to_chars(_self) for(var i=0,len=chars.length;i < len;i++){char=chars[i] cf=$B.unicode_casefold[char] if(cf){cf.forEach(function(cp){res+=String.fromCharCode(cp)})}else{res+=char.toLowerCase()}} return res} str.center=function(){var $=$B.args("center",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self) if($.width <=_self.length){return _self} var pad=parseInt(($.width-_self.length)/2),res=$.fillchar.repeat(pad) res+=_self+res if(res.length < $.width){res+=$.fillchar} return res} str.count=function(){var $=$B.args("count",4,{self:null,sub:null,start:null,stop:null},["self","sub","start","stop"],arguments,{start:null,stop:null},null,null),_self,sub if(! $B.$isinstance($.sub,str)){$B.RAISE(_b_.TypeError,"Can't convert '"+$B.class_name($.sub)+ "' object to str implicitly")} [_self,sub]=to_string([$.self,$.sub]) var substr=_self if($.start !==null){var _slice if($.stop !==null){_slice=_b_.slice.$factory($.start,$.stop)}else{_slice=_b_.slice.$factory($.start,_self.length)} substr=str.__getitem__.apply(null,[_self].concat(_slice))}else{if(_self.length+sub.length==0){return 1}} if(sub.length==0){if($.start==_self.length){return 1}else if(substr.length==0){return 0} return substr.length+1} var n=0,pos=0 while(pos < substr.length){pos=substr.indexOf(sub,pos) if(pos >=0){n++ pos+=sub.length}else{break}} return n} str.encode=function(){var $=$B.args("encode",3,{self:null,encoding:null,errors:null},["self","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),_self=to_string($.self) if($.encoding=="rot13" ||$.encoding=="rot_13"){ var res="" for(var i=0,len=_self.length;i < len ;i++){var char=_self.charAt(i) if(("a" <=char && char <="m")||("A" <=char && char <="M")){res+=String.fromCharCode(char.charCodeAt(0)+13)}else if(("m" < char && char <="z")|| ("M" < char && char <="Z")){res+=String.fromCharCode(char.charCodeAt(0)-13)}else{res+=char}} return res} return _b_.bytes.__new__(_b_.bytes,$.self,$.encoding,$.errors)} str.endswith=function(){ var $=$B.args("endswith",4,{self:null,suffix:null,start:null,end:null},["self","suffix","start","end"],arguments,{start:0,end:null},null,null),_self normalize_start_end($); _self=to_string($.self) var suffixes=$.suffix if(! $B.$isinstance(suffixes,_b_.tuple)){suffixes=[suffixes]} var chars=to_chars(_self),s=chars.slice($.start,$.end) for(var i=0,len=suffixes.length;i < len;i++){var suffix=suffixes[i] if(! $B.$isinstance(suffix,str)){$B.RAISE(_b_.TypeError,"endswith first arg must be str or a tuple of str, not int")} suffix=suffix.__class__ ? suffix.$brython_value :suffix if(suffix.length <=s.length && s.slice(s.length-suffix.length).join('')==suffix){return true}} return false} str.expandtabs=function(){var $=$B.args("expandtabs",2,{self:null,tabsize:null},["self","tabsize"],arguments,{tabsize:8},null,null),_self=to_string($.self) var s=$B.PyNumber_Index($.tabsize),col=0,pos=0,res="",chars=to_chars(_self) if(s==1){return _self.replace(/\t/g," ")} while(pos < chars.length){var car=chars[pos] switch(car){case "\t": while(col % s > 0){res+=" "; col++} break case "\r": case "\n": res+=car col=0 break default: res+=car col++ break} pos++} return res} str.find=function(){ var $=$B.args("str.find",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub check_str($.sub) normalize_start_end($); [_self,sub]=to_string([$.self,$.sub]); var len=str.__len__(_self),sub_len=str.__len__(sub) if(sub_len==0 && $.start==len){return len} if(len+sub_len==0){return-1} var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.slice(js_start,js_end).indexOf(sub) if(ix==-1){return-1} return jspos2pypos(_self,js_start+ix)} $B.parse_format=function(fmt_string){ var elts=fmt_string.split(":"),name,conv,spec,name_ext=[] if(elts.length==1){ name=fmt_string}else{ name=elts[0] spec=elts.splice(1).join(":")} elts=name.split("!") if(elts.length > 1){name=elts[0] conv=elts[1]} if(name !==undefined){ function name_repl(match){name_ext.push(match) return ""} var name_ext_re=/\.[_a-zA-Z][_a-zA-Z0-9]*|\[[_a-zA-Z][_a-zA-Z0-9]*\]|\[[0-9]+\]/g name=name.replace(name_ext_re,name_repl)} return{name:name,name_ext:name_ext,conv:conv,spec:spec ||"",string:fmt_string}} $B.split_format=function(s){ var pos=0,_len=s.length,car,text="",parts=[],rank=0 while(pos < _len){car=s.charAt(pos) if(car=="{" && s.charAt(pos+1)=="{"){ text+="{" pos+=2}else if(car=="}" && s.charAt(pos+1)=="}"){ text+="}" pos+=2}else if(car=="{"){ parts.push(text) var end=pos+1,nb=1 while(end < _len){if(s.charAt(end)=="{"){nb++;end++} else if(s.charAt(end)=="}"){nb--;end++ if(nb==0){ var fmt_string=s.substring(pos+1,end-1) var fmt_obj=$B.parse_format(fmt_string) fmt_obj.raw_name=fmt_obj.name fmt_obj.raw_spec=fmt_obj.spec if(!fmt_obj.name){fmt_obj.name=rank+"" rank++} if(fmt_obj.spec !==undefined){ function replace_nested(name,key){if(key==""){ return "{"+rank+++"}"} return "{"+key+"}"} fmt_obj.spec=fmt_obj.spec.replace(/\{(.*?)\}/g,replace_nested)} parts.push(fmt_obj) text="" break}}else{end++}} if(nb > 0){$B.RAISE(_b_.ValueError,"wrong format "+s)} pos=end}else{text+=car pos++}} if(text){parts.push(text)} return parts} str.format=function(){ var last_arg=$B.last(arguments),$,mapping,getitem if(last_arg.$nat=="mapping"){mapping=last_arg.mapping getitem=$B.$getattr(mapping,"__getitem__") var args=[] for(let i=0,len=arguments.length-1;i < len;i++){args.push(arguments[i])} $=$B.args("format",1,{self:null},["self"],args,{},"$args",null)}else{$=$B.args("format",1,{self:null},["self"],arguments,{},"$args","$kw") mapping=$.$kw, getitem=function(key){return _b_.dict.$getitem(mapping,key)}} var _self=to_string($.self),parts=$B.split_format(_self) var res="",fmt for(let i=0;i < parts.length;i++){ if(typeof parts[i]=="string"){res+=parts[i]; continue} fmt=parts[i] if(fmt.spec !==undefined){ function replace_nested(name,key){if(/\d+/.exec(key)){ return _b_.tuple.__getitem__($.$args,parseInt(key))}else{ return _b_.dict.__getitem__($.$kw,key)}} fmt.spec=fmt.spec.replace(/\{(.*?)\}/g,replace_nested)} var value if(fmt.name.charAt(0).search(/\d/)>-1){ let pos=parseInt(fmt.name) value=_b_.tuple.__getitem__($.$args,pos)}else{ value=getitem(fmt.name)} for(var j=0;j < fmt.name_ext.length;j++){var ext=fmt.name_ext[j] if(ext.charAt(0)=="."){ value=$B.$getattr(value,ext.substr(1))}else{ var key=ext.substr(1,ext.length-2) if(key.charAt(0).search(/\d/)>-1){key=parseInt(key)} value=$B.$getattr(value,"__getitem__")(key)}} if(fmt.conv=="a"){value=_b_.ascii(value)}else if(fmt.conv=="r"){value=_b_.repr(value)}else if(fmt.conv=="s"){value=_b_.str.$factory(value)} if(value.$is_class ||value.$factory){ res+=value.__class__.__format__(value,fmt.spec)}else{res+=$B.$getattr(value,"__format__")(fmt.spec)}} return res} str.format_map=function(self,mapping){$B.check_nb_args_no_kw('str.format_map',2,arguments) var _self=to_string(self) return str.format(_self,{$nat:'mapping',mapping})} str.index=function(){ var res=str.find.apply(null,arguments) if(res===-1){$B.RAISE(_b_.ValueError,"substring not found")} return res} str.isascii=function(self){ $B.check_nb_args_no_kw('str.isascii',1,arguments) var _self=to_string(self) for(var i=0,len=_self.length;i < len;i++){if(_self.charCodeAt(i)> 127){return false}} return true} var unicode_categories_contain_character=function(categories,cp){for(var cat of categories){if($B.in_unicode_category(cat,cp)){return true}} return false} var alpha_categories=['Ll','Lu','Lm','Lt','Lo'] var alnum_categories=['Ll','Lu','Lm','Lt','Lo','Nd'] str.isalnum=function(self){ $B.check_nb_args_no_kw('str.isalnum',1,arguments) var _self=to_string(self); if(_self.length==0){return false} for(var char of _self){if(!unicode_categories_contain_character(alnum_categories,_b_.ord(char))){return false}} return true} str.isalpha=function(self){ $B.check_nb_args_no_kw('str.isalpha',1,arguments) var _self=to_string(self); if(_self.length==0){return false} for(var char of _self){if(!unicode_categories_contain_character(alpha_categories,_b_.ord(char))){return false}} return true} str.isdecimal=function(self){ $B.check_nb_args_no_kw('str.isdecimal',1,arguments) var cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if(! $B.in_unicode_category('Nd',cp)){return false}} return _self.length > 0} str.isdigit=function(self){ $B.check_nb_args_no_kw('str.isdigit',1,arguments) var cp,_self=to_string(self) for(var char of _self){if(/\p{Nd}/u.test(char)){continue} cp=_b_.ord(char) if(! $B.in_unicode_category('No_digits',cp)){return false}} return _self.length > 0} str.isidentifier=function(self){ $B.check_nb_args_no_kw('str.isidentifier',1,arguments) var _self=to_string(self) if(_self.length==0){return false} var chars=to_chars(_self) if(! $B.is_XID_Start(_b_.ord(chars[0]))){return false}else{for(var char of chars){var cp=_b_.ord(char) if(! $B.is_XID_Continue(cp)){return false}}} return true} str.islower=function(self){ $B.check_nb_args_no_kw('str.islower',1,arguments) var has_cased=false,cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if($B.in_unicode_category('Ll',cp)){has_cased=true continue}else if($B.in_unicode_category('Lu',cp)|| $B.in_unicode_category('Lt',cp)){return false}} return has_cased} const numeric_re=/\p{Nd}|\p{Nl}|\p{No}/u str.isnumeric=function(self){ $B.check_nb_args_no_kw('str.isnumeric',1,arguments) var _self=to_string(self) for(var char of _self){if((! numeric_re.test(char))&& ! $B.in_unicode_category('Lo_numeric',_b_.ord(char))){return false}} return _self.length > 0} var unprintable_re=/\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}|\p{Zl}|\p{Zp}|\p{Zs}/u str.isprintable=function(self){ $B.check_nb_args_no_kw('str.isprintable',1,arguments) var _self=to_string(self) for(var char of _self){if(char==' '){continue} if(unprintable_re.test(char)){return false}} return true} str.isspace=function(self){ $B.check_nb_args_no_kw('str.isspace',1,arguments) var cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if(! $B.in_unicode_category('Zs',cp)&& $B.unicode_bidi_whitespace.indexOf(cp)==-1){return false}} return _self.length > 0} str.istitle=function(self){ $B.check_nb_args_no_kw('str.istitle',1,arguments) var _self=to_string(self) return _self.length > 0 && str.title(_self)==_self} str.isupper=function(self){ $B.check_nb_args_no_kw('str.isupper',1,arguments) var is_upper=false,cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if($B.in_unicode_category('Lu',cp)){is_upper=true continue}else if($B.in_unicode_category('Ll',cp)|| $B.in_unicode_category('Lt',cp)){return false}} return is_upper} str.join=function(self,iterable){$B.check_nb_args_no_kw('str.join',2,arguments) var _self=to_string(self) iterable=_b_.iter(iterable) var res=[],count=0 while(1){try{var obj2=_b_.next(iterable) if(! $B.$isinstance(obj2,str)){$B.RAISE(_b_.TypeError,"sequence item "+count+ ": expected str instance, "+$B.class_name(obj2)+ " found")} res.push(obj2)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break}else{throw err}}} return res.join(_self)} str.ljust=function(){var $=$B.args("ljust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self),len=str.__len__(_self); if($.width <=len){return _self} return _self+$.fillchar.repeat($.width-len)} str.lower=function(self){$B.check_nb_args_no_kw('str.lower',1,arguments) var _self=to_string(self) return _self.toLowerCase()} str.lstrip=function(){var $=$B.args("lstrip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null),_self=$.self,chars=$.chars if(chars===_b_.None){return _self.trimStart()} [_self,chars]=to_string([_self,chars]) while(_self.length > 0){var flag=false for(var char of chars){if(_self.startsWith(char)){_self=_self.substr(char.length) flag=true break}} if(! flag){return $.self.surrogates ? $B.String(_self):_self}} return ''} str.maketrans=function(){var $=$B.args("maketrans",3,{x:null,y:null,z:null},["x","y","z"],arguments,{y:null,z:null},null,null) var _t=$B.empty_dict() if($.y===null && $.z===null){ if(! $B.$isinstance($.x,_b_.dict)){$B.RAISE(_b_.TypeError,"maketrans only argument must be a dict")} var items=_b_.list.$factory(_b_.dict.items($.x)) for(let i=0,len=items.length;i < len;i++){let k=items[i][0],v=items[i][1] if(! $B.$isinstance(k,_b_.int)){if($B.$isinstance(k,_b_.str)&& k.length==1){k=_b_.ord(k)}else{$B.RAISE(_b_.TypeError,"dictionary key "+k+ " is not int or 1-char string")}} if(v !==_b_.None && ! $B.$isinstance(v,[_b_.int,_b_.str])){$B.RAISE(_b_.TypeError,"dictionary value "+v+ " is not None, integer or string")} _b_.dict.$setitem(_t,k,v)} return _t}else{ if(!($B.$isinstance($.x,_b_.str)&& $B.$isinstance($.y,_b_.str))){$B.RAISE(_b_.TypeError,"maketrans arguments must be strings")}else if($.x.length !==$.y.length){$B.RAISE(_b_.TypeError,"maketrans arguments must be strings or same length")}else{var toNone={} if($.z !==null){ if(! $B.$isinstance($.z,_b_.str)){$B.RAISE(_b_.TypeError,"maketrans third argument must be a string")} for(let i=0,len=$.z.length;i < len;i++){toNone[_b_.ord($.z.charAt(i))]=true}} for(let i=0,len=$.x.length;i < len;i++){var key=_b_.ord($.x.charAt(i)),value=$.y.charCodeAt(i) _b_.dict.$setitem(_t,key,value)} for(let k in toNone){_b_.dict.$setitem(_t,parseInt(k),_b_.None)} return _t}}} str.maketrans.$type="staticmethod" str.partition=function(self,sep){$B.check_nb_args_no_kw('str.partition',2,arguments) var _self if(sep==""){$B.RAISE(_b_.ValueError,"empty separator")} check_str(sep); [_self,sep]=to_string([self,sep]) var chars=to_chars(_self),i=_self.indexOf(sep) if(i==-1){return _b_.tuple.$factory([_self,"",""])} return _b_.tuple.$factory([chars.slice(0,i).join(''),sep,chars.slice(i+sep.length).join('')])} str.removeprefix=function(self,prefix){$B.check_nb_args_no_kw('str.removeprefix',2,arguments) var _self if(!$B.$isinstance(prefix,str)){$B.RAISE(_b_.ValueError,"prefix should be str, not "+ `'${$B.class_name(prefix)}'`)} [_self,prefix]=to_string([self,prefix]) if(str.startswith(_self,prefix)){return _self.substr(prefix.length)} return _self.substr(0)} str.removesuffix=function(self,suffix){$B.check_nb_args_no_kw('str.removesuffix',2,arguments) var _self if(!$B.$isinstance(suffix,str)){$B.RAISE(_b_.ValueError,"suffix should be str, not "+ `'${$B.class_name(suffix)}'`)} [_self,suffix]=to_string([self,suffix]) if(suffix.length > 0 && str.endswith(_self,suffix)){return _self.substr(0,_self.length-suffix.length)} return _self.substr(0)} str.replace=function(){ var $=$B.args("replace",4,{self:null,old:null,new:null,count:null},["self","old","new","count"],arguments,{count:-1},null,null),count=$.count,_self=$.self,old=$.old,_new=$.new check_str(old,"replace() argument 1 ") check_str(_new,"replace() argument 2 ") if(! $B.$isinstance(count,[_b_.int,_b_.float])){$B.RAISE(_b_.TypeError,"'"+$B.class_name(count)+ "' object cannot be interpreted as an integer")}else if($B.$isinstance(count,_b_.float)){$B.RAISE(_b_.TypeError,"integer argument expected, got float")} if(count==0){return _self} if(count.__class__==$B.long_int){count=parseInt(count.value)} [old,_new]=to_string([old,_new]) var elts if(old==""){if(_new==""){return _self} if(_self==""){return _new} elts=_self.split("") if(count >-1 && elts.length >=count){var rest=elts.slice(count).join("") return _new+elts.slice(0,count).join(_new)+rest}else{return _new+elts.join(_new)+_new}}else{elts=str.split(_self,old,count)} var res=_self,pos=-1 if(old.length==0){res=_new for(var i=0;i < elts.length;i++){res+=elts[i]+_new} return res+rest} if(count < 0){count=res.length} while(count > 0){pos=res.indexOf(old,pos) if(pos < 0){break} res=res.substr(0,pos)+_new+res.substr(pos+old.length) pos=pos+_new.length count--} return res} str.rfind=function(){ var $=$B.args("rfind",4,{self:null,sub:null,start:null,end:null},["self","sub","start","end"],arguments,{start:0,end:null},null,null),_self,sub normalize_start_end($) check_str($.sub); [_self,sub]=to_string([$.self,$.sub]) var len=str.__len__(_self),sub_len=str.__len__(sub) if(sub_len==0){if($.js_start > len){return-1}else{return str.__len__(_self)}} var js_start=pypos2jspos(_self,$.start),js_end=pypos2jspos(_self,$.end),ix=_self.substring(js_start,js_end).lastIndexOf(sub) if(ix==-1){return-1} return jspos2pypos(_self,js_start+ix)-$.start} str.rindex=function(){ var res=str.rfind.apply(null,arguments) if(res==-1){$B.RAISE(_b_.ValueError,"substring not found")} return res} str.rjust=function(){var $=$B.args("rjust",3,{self:null,width:null,fillchar:null},["self","width","fillchar"],arguments,{fillchar:" "},null,null),_self=to_string($.self) var len=str.__len__(_self) if($.width <=len){return _self} return $B.String($.fillchar.repeat($.width-len)+_self)} str.rpartition=function(self,sep){$B.check_nb_args_no_kw('str.rpartition',2,arguments) check_str(sep) var _self=reverse(self),sep=reverse(sep) var items=str.partition(_self,sep).reverse() for(var i=0;i < items.length;i++){items[i]=items[i].split("").reverse().join("")} return items} str.rsplit=function(){var $=$B.args("rsplit",3,{self:null,sep:null,maxsplit:null},["self","sep","maxsplit"],arguments,{sep:_b_.None,maxsplit:-1},null,null),sep=$.sep,_self; [_self,sep]=to_string([$.self,$.sep]) var rev_str=reverse(_self),rev_sep=sep===_b_.None ? sep :reverse(sep),rev_res=str.split(rev_str,rev_sep,$.maxsplit) rev_res.reverse() for(var i=0;i < rev_res.length;i++){rev_res[i]=reverse(rev_res[i])} return $B.$list(rev_res)} str.rstrip=function(){var $=$B.args("rstrip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null),chars=$.chars,_self=to_string($.self) if(chars===_b_.None){return _self.trimEnd()} chars=to_string(chars) while(_self.length > 0){var flag=false for(var char of chars){if(_self.endsWith(char)){_self=_self.substr(0,_self.length-char.length) flag=true break}} if(! flag){return _self.surrogates ? $B.String(_self):_self}} return ''} str.split=function(){var $=$B.args("split",3,{self:null,sep:null,maxsplit:null},["self","sep","maxsplit"],arguments,{sep:_b_.None,maxsplit:-1},null,null),maxsplit=$.maxsplit,sep=$.sep,pos=0,_self=to_string($.self) if(maxsplit.__class__===$B.long_int){maxsplit=parseInt(maxsplit.value)} if(sep==""){$B.RAISE(_b_.ValueError,"empty separator")} if(sep===_b_.None){let res=[] while(pos < _self.length && _self.charAt(pos).search(/\s/)>-1){pos++} if(pos===_self.length-1){return $B.$list([_self])} let name="" while(1){if(_self.charAt(pos).search(/\s/)==-1){if(name==""){name=_self.charAt(pos)}else{name+=_self.charAt(pos)}}else{if(name !==""){res.push(name) if(maxsplit !==-1 && res.length==maxsplit+1){res.pop() res.push(name+_self.substr(pos)) return $B.$list(res.map($B.String))} name=""}} pos++ if(pos > _self.length-1){if(name){res.push(name)} break}} return $B.$list(res.map($B.String))}else{if(! $B.$isinstance(sep,_b_.str)){$B.RAISE(_b_.TypeError,'must be str or None, not '+ $B.class_name(sep))} sep=to_string(sep) let res=[],s="",seplen=sep.length if(maxsplit==0){return $B.$list([$.self])} while(pos < _self.length){if(_self.substr(pos,seplen)==sep){res.push(s) pos+=seplen if(maxsplit >-1 && res.length >=maxsplit){res.push(_self.substr(pos)) return $B.$list(res.map($B.String))} s=""}else{s+=_self.charAt(pos) pos++}} res.push(s) return $B.$list(res.map($B.String))}} str.splitlines=function(){var $=$B.args('splitlines',2,{self:null,keepends:null},['self','keepends'],arguments,{keepends:false},null,null) if(!$B.$isinstance($.keepends,[_b_.bool,_b_.int])){throw _b_.TypeError('integer argument expected, got '+ $B.get_class($.keepends).__name)} var keepends=_b_.int.$factory($.keepends),res=$B.$list([]),start=0,pos=0,_self=to_string($.self) if(! _self.length){return res} while(pos < _self.length){if(_self.substr(pos,2)=='\r\n'){res.push(_self.slice(start,keepends ? pos+2 :pos)) start=pos=pos+2}else if(_self[pos]=='\r' ||_self[pos]=='\n'){res.push(_self.slice(start,keepends ? pos+1 :pos)) start=pos=pos+1}else{pos++}} if(start < _self.length){res.push(_self.slice(start))} return $B.$list(res.map($B.String))} str.startswith=function(){ var $=$B.args("startswith",4,{self:null,prefix:null,start:null,end:null},["self","prefix","start","end"],arguments,{start:0,end:null},null,null),_self normalize_start_end($) var prefixes=$.prefix if(! $B.$isinstance(prefixes,_b_.tuple)){prefixes=[prefixes]} _self=to_string($.self) prefixes=to_string(prefixes) var s=_self.substring($.start,$.end) for(var prefix of prefixes){if(! $B.$isinstance(prefix,str)){$B.RAISE(_b_.TypeError,"endswith first arg must be str "+ "or a tuple of str, not int")} if(s.substr(0,prefix.length)==prefix){return true}} return false} str.strip=function(){var $=$B.args("strip",2,{self:null,chars:null},["self","chars"],arguments,{chars:_b_.None},null,null) var _self=to_string($.self) if($.chars===_b_.None){return _self.trim()} return str.rstrip(str.lstrip(_self,$.chars),$.chars)} str.swapcase=function(self){$B.check_nb_args_no_kw('str.swapcase',1,arguments) var res="",cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if($B.in_unicode_category('Ll',cp)){res+=char.toUpperCase()}else if($B.in_unicode_category('Lu',cp)){res+=char.toLowerCase()}else{res+=char}} return res} str.title=function(self){$B.check_nb_args_no_kw('str.title',1,arguments) var state,cp,res="",_self=to_string(self) for(var char of _self){cp=_b_.ord(char) if($B.in_unicode_category('Ll',cp)){if(! state){res+=char.toUpperCase() state="word"}else{res+=char}}else if($B.in_unicode_category('Lu',cp)|| $B.in_unicode_category('Lt',cp)){res+=state ? char.toLowerCase():char state="word"}else{state=null res+=char}} return res} str.translate=function(self,table){$B.check_nb_args_no_kw('str.translate',2,arguments) var res=[],getitem=$B.$getattr(table,"__getitem__"),cp,_self=to_string(self) for(var char of _self){cp=_b_.ord(char) try{var repl=getitem(cp) if(repl !==_b_.None){if(typeof repl=="string"){res.push(repl)}else if(typeof repl=="number"){res.push(String.fromCharCode(repl))}}}catch(err){res.push(char)}} return res.join("")} str.upper=function(self){$B.check_nb_args_no_kw('str.upper',1,arguments) var _self=to_string(self) return _self.toUpperCase()} str.zfill=function(self,width){$B.check_nb_args_no_kw('str.zfill',2,arguments) var _self=to_string(self) var len=str.__len__(_self) if(width <=len){return _self} switch(_self.charAt(0)){case "+": case "-": return _self.charAt(0)+ "0".repeat(width-len)+_self.substr(1) default: return "0".repeat(width-len)+_self}} str.$factory=function(arg,encoding){if(arguments.length==0){return ""} if(arg===undefined){return $B.UndefinedType.__str__()}else if(arg===null){return ''} var test=false if(test){console.log('call str of',arg)} if(encoding !==undefined){ var $=$B.args("str",3,{arg:null,encoding:null,errors:null},["arg","encoding","errors"],arguments,{encoding:"utf-8",errors:"strict"},null,null),encoding=$.encoding,errors=$.errors if(! $B.$isinstance(encoding,str)){$B.RAISE(_b_.TypeError,`str() argument 'encoding' must be str, not ${$B.class_name(encoding)}`)} if(! $B.$isinstance(errors,str)){$B.RAISE(_b_.TypeError,`str() argument 'errors' must be str, not ${$B.class_name(errors)}`)}} if(typeof arg=="string" ||arg instanceof String){return arg.toString()}else if(typeof arg=="number" && Number.isInteger(arg)){return arg.toString()} try{if(arg.__class__ && arg.__class__===_b_.bytes && encoding !==undefined){ return _b_.bytes.decode(arg,encoding,errors)} var klass=arg.__class__ ||$B.get_class(arg) if(klass===undefined){return $B.JSObj.__str__($B.jsobj2pyobj(arg))} var method=$B.search_in_mro(klass,'__str__') if(method===undefined){method=$B.search_in_mro(klass,'__repr__')} if(method===undefined){$B.RAISE_ATTRIBUTE_ERROR('no __str__ or __repr__',klass,'__str__')}}catch(err){console.log("no __str__ for",arg) console.log("err ",err) if($B.get_option('debug')> 1){console.log(err)} console.log("Warning - no method __str__ or __repr__, "+ "default to toString",arg) throw err} var getter=$B.search_in_mro($B.get_class(method),'__get__') var res if(getter){if(typeof getter=='function'){if(arg.$is_class){method=getter(method,_b_.None,klass) res=$B.$call(method)(arg)}else{method=getter(method,arg,klass) res=$B.$call(method)()}}else{var call_in_mro=$B.search_in_mro($B.get_class(getter,'__call__')) if(call_in_mro){res=call_in_mro(getter,arg)}else{$B.RAISE(_b_.TypeError,'__str__ or __repr__ is not callable')}}}else{res=$B.$call(method)(arg)} if(typeof res=="string" ||$B.$isinstance(res,str)){return res} $B.RAISE(_b_.TypeError,"__str__ returned non-string "+ `(type ${$B.class_name(res)})`)} $B.set_func_names(str,"builtins") _b_.str=str $B.parse_format_spec=function(spec,obj){if(spec==""){this.empty=true}else{var pos=0,aligns="<>=^",digits="0123456789",types="bcdeEfFgGnosxX%",align_pos=aligns.indexOf(spec.charAt(0)) if(align_pos !=-1){if(spec.charAt(1)&& aligns.indexOf(spec.charAt(1))!=-1){ this.fill=spec.charAt(0) this.align=spec.charAt(1) pos=2}else{ this.align=aligns[align_pos] this.fill=" " pos++}}else{align_pos=aligns.indexOf(spec.charAt(1)) if(spec.charAt(1)&& align_pos !=-1){ this.align=aligns[align_pos] this.fill=spec.charAt(0) pos=2}} var car=spec.charAt(pos) if(car=="+" ||car=="-" ||car==" "){this.sign=car pos++ car=spec.charAt(pos)} if(car=="z"){this.z=true pos++ car=spec.charAt(pos)} if(car=="#"){this.alternate=true; pos++; car=spec.charAt(pos)} if(car=="0"){ this.fill="0" if(align_pos==-1){this.align="="} pos++ car=spec.charAt(pos)} while(car && digits.indexOf(car)>-1){if(this.width===undefined){this.width=car}else{this.width+=car} pos++ car=spec.charAt(pos)} if(this.width !==undefined){this.width=parseInt(this.width)} if(this.width===undefined && car=="{"){ var end_param_pos=spec.substr(pos).search("}") this.width=spec.substring(pos,end_param_pos) pos+=end_param_pos+1} if(car=="," ||car=="_"){this.comma=true this.grouping_option=car pos++ car=spec.charAt(pos) if(car=="," ||car=="_"){if(car==this.grouping_option){$B.RAISE(_b_.ValueError,`Cannot specify '${car}' with '${car}'.`)}else{$B.RAISE(_b_.ValueError,"Cannot specify both ',' and '_'.")}}} if(car=="."){if(digits.indexOf(spec.charAt(pos+1))==-1){$B.RAISE(_b_.ValueError,"Missing precision in format spec")} this.precision=spec.charAt(pos+1) pos+=2 car=spec.charAt(pos) while(car && digits.indexOf(car)>-1){this.precision+=car pos++ car=spec.charAt(pos)} this.precision=parseInt(this.precision)} if(car && types.indexOf(car)>-1){this.type=car pos++ car=spec.charAt(pos)} if(pos !==spec.length){var err_msg=`Invalid format specifier '${spec}'` if(obj){err_msg+=` for object of type '${$B.class_name(obj)}'`} $B.RAISE(_b_.ValueError,err_msg)}} this.toString=function(){return(this.fill===undefined ? "" :_b_.str.$factory(this.fill))+ (this.align ||"")+ (this.sign ||"")+ (this.alternate ? "#" :"")+ (this.sign_aware ? "0" :"")+ (this.width ||"")+ (this.comma ? "," :"")+ (this.precision ? "."+this.precision :"")+ (this.type ||"")}} $B.format_width=function(s,fmt){if(fmt.width && s.length < fmt.width){var fill=fmt.fill ||" ",align=fmt.align ||"<",missing=fmt.width-s.length switch(align){case "<": return s+fill.repeat(missing) case ">": return fill.repeat(missing)+s case "=": if("+-".indexOf(s.charAt(0))>-1){return s.charAt(0)+fill.repeat(missing)+s.substr(1)}else{return fill.repeat(missing)+s} case "^": var left=parseInt(missing/2) return fill.repeat(left)+s+fill.repeat(missing-left)}} return s} function fstring_expression(start){this.type="expression" this.start=start this.expression="" this.conversion=null this.fmt=null} function fstring_error(msg,pos){var error=Error(msg) error.position=pos throw error} $B.parse_fstring=function(string){ var elts=[],pos=0,current="",ctype=null,nb_braces=0,expr_start,car while(pos < string.length){if(ctype===null){car=string.charAt(pos) if(car=="{"){if(string.charAt(pos+1)=="{"){ctype="string" current="{" pos+=2}else{ctype="expression" expr_start=pos+1 nb_braces=1 pos++}}else if(car=="}"){if(string.charAt(pos+1)==car){ctype="string" current="}" pos+=2}else{fstring_error(" f-string: single '}' is not allowed",pos)}}else{ctype="string" current=car pos++}}else if(ctype=="string"){ var i=pos while(i < string.length){car=string.charAt(i) if(car=="{"){if(string.charAt(i+1)=="{"){current+="{" i+=2}else{elts.push(current) ctype="expression" expr_start=i+1 pos=i+1 break}}else if(car=="}"){if(string.charAt(i+1)==car){current+=car i+=2}else{fstring_error(" f-string: single '}' is not allowed",pos)}}else{current+=car i++}} pos=i+1}else if(ctype=="debug"){ while(string.charAt(i)==" "){i++} if(string.charAt(i)=="}"){ elts.push(current) ctype=null current="" pos=i+1}}else{ let i=pos,nb_paren=0 nb_braces=1 current=new fstring_expression(expr_start) while(i < string.length){car=string.charAt(i) if(car=="{" && nb_paren==0){nb_braces++ current.expression+=car i++}else if(car=="}" && nb_paren==0){nb_braces-=1 if(nb_braces==0){ if(current.expression==""){fstring_error("f-string: empty expression not allowed",pos)} elts.push(current) ctype=null current="" pos=i+1 break} current.expression+=car i++}else if(car=="\\"){ throw Error("f-string expression part cannot include a"+ " backslash")}else if(nb_paren==0 && car=="!" && current.fmt===null && ":}".indexOf(string.charAt(i+2))>-1){if(current.expression.length==0){throw Error("f-string: empty expression not allowed")} if("ars".indexOf(string.charAt(i+1))==-1){throw Error("f-string: invalid conversion character:"+ " expected 's', 'r', or 'a'")}else{current.conversion=string.charAt(i+1) i+=2}}else if(car=="(" ||car=='['){nb_paren++ current.expression+=car i++}else if(car==")" ||car==']'){nb_paren-- current.expression+=car i++}else if(car=='"'){ if(string.substr(i,3)=='"""'){let end=string.indexOf('"""',i+3) if(end==-1){fstring_error("f-string: unterminated string",pos)}else{var trs=string.substring(i,end+3) trs=trs.replace("\n","\\n\\") current.expression+=trs i=end+3}}else{let end=string.indexOf('"',i+1) if(end==-1){fstring_error("f-string: unterminated string",pos)}else{current.expression+=string.substring(i,end+1) i=end+1}}}else if(nb_paren==0 && car==":"){ current.fmt=true var cb=0,fmt_complete=false for(var j=i+1;j < string.length;j++){if(string[j]=='{'){if(string[j+1]=='{'){j+=2}else{cb++}}else if(string[j]=='}'){if(string[j+1]=='}'){j+=2}else if(cb==0){fmt_complete=true var fmt=string.substring(i+1,j) current.format=$B.parse_fstring(fmt) i=j break}else{cb--}}} if(! fmt_complete){fstring_error('invalid format',pos)}}else if(car=="="){ var ce=current.expression,last_char=ce.charAt(ce.length-1),last_char_re=('()'.indexOf(last_char)>-1 ? "\\" :"")+last_char if(ce.length==0 || nb_paren > 0 || string.charAt(i+1)=="=" || "=!<>:".search(last_char_re)>-1){ current.expression+=car i+=1}else{ var tail=car while(string.charAt(i+1).match(/\s/)){tail+=string.charAt(i+1) i++} elts.push(current.expression+tail) while(ce.match(/\s$/)){ce=ce.substr(0,ce.length-1)} current.expression=ce ctype="debug" i++}}else{current.expression+=car i++}} if(nb_braces > 0){fstring_error("f-string: expected '}'",pos)}}} if(current.length > 0){elts.push(current)} for(var elt of elts){if(typeof elt=="object"){if(elt.fmt_pos !==undefined && elt.expression.charAt(elt.fmt_pos)!=':'){throw Error()}}} return elts} $B.codepoint2jsstring=function(i){if(i >=0x10000 && i <=0x10FFFF){var code=(i-0x10000) return String.fromCodePoint(0xD800 |(code >> 10))+ String.fromCodePoint(0xDC00 |(code & 0x3FF))}else{return String.fromCodePoint(i)}} $B.jsstring2codepoint=function(c){if(c.length==1){return c.charCodeAt(0)} var code=0x10000 code+=(c.charCodeAt(0)& 0x03FF)<< 10 code+=(c.charCodeAt(1)& 0x03FF) return code} var Interpolation=$B.make_class('Interpolation',function(value,expression,conversion,format_spec){return{ __class__:Interpolation,value,expression,conversion,format_spec}} ) Interpolation.__repr__=function(self){var res='Interpolation(',items=[] for(var attr of['value','expression','conversion','format_spec']){items.push(`${_b_.repr(self[attr])}`)} return res+items.join(', ')+')'} $B.set_func_names(Interpolation,'builtins') var Template=$B.make_class('Template',function(){ var strings=$B.fast_tuple([]),interpolations=$B.fast_tuple([]) var expect_str=true for(var item of arguments){if(Array.isArray(item)){ if(expect_str){strings.push('')} interpolations.push(Interpolation.$factory(...item))}else{strings.push(item) expect_str=false}} if(expect_str){strings.push('')} return{ __class__:Template,strings,interpolations}}) Template.__iter__=function(self){self.$counter=-1 self.$len=self.strings.length+self.interpolations.length return self} Template.__next__=function(self){self.$counter++ if(self.$counter >=self.$len){$B.RAISE(_b_.StopIteration,'')} var type='si'[self.$counter % 2] var rank=Math.floor(self.$counter/2) switch(type){case 's': var s=self.strings[rank] if(s.length > 0){return s} return Template.__next__(self) case 'i': return self.interpolations[rank]}} Template.values=_b_.property.$factory( function(self){var values=[] for(var itp of self.interpolations){values.push(itp.value)} return $B.fast_tuple(values)} ) $B.set_func_names(Template,'builtins') $B.Template=function(){return Template.$factory(...arguments)}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function $err(op,other){var msg="unsupported operand type(s) for "+op+ " : 'int' and '"+$B.class_name(other)+"'" $B.RAISE(_b_.TypeError,msg)} function int_value(obj){ if(typeof obj=="boolean"){return obj ? 1 :0} return obj.$brython_value !==undefined ? obj.$brython_value :obj} function bigint_value(obj){ if(typeof obj=="boolean"){return obj ? 1n :0n}else if(typeof obj=="number"){return BigInt(obj)}else if(obj.__class__===$B.long_int){return obj.value}else if($B.$isinstance(obj,_b_.int)){return bigint_value(obj.$brython_value)}} var int={__class__:_b_.type,__dir__:_b_.object.__dir__,__mro__:[_b_.object],__qualname__:'int',$is_class:true,$native:true,$descriptors:{"numerator":true,"denominator":true,"imag":true,"real":true},$is_int_subclass:true,$is_number:true} var int_or_long=int.$int_or_long=function(bigint){var res=Number(bigint) return Number.isSafeInteger(res)? res :$B.fast_long_int(bigint)} int.$to_js_number=function(obj){ if(typeof obj=="number"){return obj}else if(obj.__class__===$B.long_int){return Number(obj.value)}else if($B.$isinstance(obj,_b_.int)){return int.$to_js_value(obj.$brython_value)} return null} int.$to_bigint=bigint_value int.$int_value=int_value int.as_integer_ratio=function(){var $=$B.args("as_integer_ratio",1,{self:null},["self"],arguments,{},null,null) return $B.fast_tuple([$.self,1])} int.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null},["bytes","byteorder","signed"],arguments,{byteorder:'big',signed:false},null,null) var x=$.bytes,byteorder=$.byteorder,signed=$.signed,_bytes,_len if($B.$isinstance(x,[_b_.bytes,_b_.bytearray])){_bytes=x.source _len=x.source.length}else{_bytes=_b_.list.$factory(x) _len=_bytes.length for(let i=0;i < _len;i++){_b_.bytes.$factory([_bytes[i]])}} if(byteorder=="big"){_bytes.reverse()}else if(byteorder !="little"){$B.RAISE(_b_.ValueError,"byteorder must be either 'little' or 'big'")} var num=_bytes[0] if(signed && num >=128){num=num-256} num=BigInt(num) var _mult=256n for(let i=1;i < _len;i++){num+=_mult*BigInt(_bytes[i]) _mult*=256n} if(! signed){return int_or_long(num)} if(_bytes[_len-1]< 128){return int_or_long(num)} return int_or_long(num-_mult)} int.to_bytes=function(){var $=$B.args("to_bytes",3,{self:null,len:null,byteorder:null,signed:null},["self","len","byteorder","signed"],arguments,{len:1,byteorder:'big',signed:false},null,null),self=$.self,len=$.len,byteorder=$.byteorder,signed=$.signed if(! $B.$isinstance(len,_b_.int)){$B.RAISE(_b_.TypeError,"integer argument expected, got "+ $B.class_name(len))} if(["little","big"].indexOf(byteorder)==-1){$B.RAISE(_b_.ValueError,"byteorder must be either 'little' or 'big'")} if($B.$isinstance(self,$B.long_int)){return $B.long_int.to_bytes(self,len,byteorder,signed)} if(self < 0){if(! signed){$B.RAISE(_b_.OverflowError,"can't convert negative int to unsigned")} self=Math.pow(256,len)+self} var res=[],value=self while(value > 0){var quotient=Math.floor(value/256),rest=value-256*quotient res.push(rest) if(res.length > len){$B.RAISE(_b_.OverflowError,"int too big to convert")} value=quotient} while(res.length < len){res.push(0)} if(byteorder=="big"){res.reverse()} return{ __class__:_b_.bytes,source:res}} int.__abs__=function(self){return Math.abs(int_value(self))} var op_model= `var _b_ = __BRYTHON__.builtins if(typeof other == "number"){ return _b_.int.$int_or_long(BigInt(self) + BigInt(other))}else if(other.__class__ === $B.long_int){ return _b_.int.$int_or_long(BigInt(self) + other.value)}else if(typeof other == "boolean"){ return _b_.int.$int_or_long(BigInt(self) + (other ? 1n : 0n))}else if($B.$isinstance(other, _b_.int)){ return _b_.int.__add__(self, other.$brython_value)} return _b_.NotImplemented ` int.__add__=Function('self','other',op_model) int.__bool__=function(self){return int_value(self).valueOf()==0 ? false :true} int.__ceil__=function(self){return Math.ceil(int_value(self))} int.__divmod__=function(self,other){if(! $B.$isinstance(other,int)){return _b_.NotImplemented} return $B.fast_tuple([int.__floordiv__(self,other),int.__mod__(self,other)])} int.__eq__=function(self,other){var self_as_int=int_value(self) if(self_as_int.__class__===$B.long_int){return $B.long_int.__eq__(self_as_int,other)} if($B.$isinstance(other,int)){return int_value(self)==int_value(other)} return _b_.NotImplemented} int.__float__=function(self){return $B.fast_float(int_value(self))} function preformat(self,fmt){if(fmt.empty){return _b_.str.$factory(self)} if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){$B.RAISE(_b_.ValueError,"Unknown format code '"+fmt.type+ "' for object of type 'int'")} var res switch(fmt.type){case undefined: case "d": res=self.toString() break case "b": res=(fmt.alternate ? "0b" :"")+self.toString(2) break case "c": res=_b_.chr(self) break case "o": res=(fmt.alternate ? "0o" :"")+self.toString(8) break case "x": res=(fmt.alternate ? "0x" :"")+self.toString(16) break case "X": res=(fmt.alternate ? "0X" :"")+self.toString(16).toUpperCase() break case "n": return self } if(fmt.sign !==undefined){if((fmt.sign==" " ||fmt.sign=="+" )&& self >=0){res=fmt.sign+res}} return res} int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self) if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){ return _b_.float.__format__($B.fast_float(self),format_spec)} fmt.align=fmt.align ||">" var res=preformat(self,fmt) if(fmt.comma){var sign=res[0]=="-" ? "-" :"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[] for(var i=0;i < nb;i++){chunks.push(rest.substring(len-3*i-3,len-3*i))} chunks.reverse() res=sign+chunks.join(",")} return $B.format_width(res,fmt)} int.__floordiv__=function(self,other){if(typeof other=="number"){if(other==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} return Math.floor(self/other)}else if(typeof other=="boolean"){if(other===false){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} return self}else if(other !==null && other.__class__===$B.long_int){return Math.floor(self/Number(other.value))}else if($B.$isinstance(other,_b_.int)){return int.__floordiv__(self,other.$brython_value)} return _b_.NotImplemented} int.$getnewargs=function(self){return $B.fast_tuple([int_value(self)])} int.__getnewargs__=function(){return int.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} int.__hash__=function(self){if(self.$brython_value !==undefined){ if(self.__hashvalue__ !==undefined){return self.__hashvalue__} if(typeof self.$brython_value=="number"){return self.__hashvalue__=self.$brython_value}else{ return self.__hashvalue__=$B.long_int.__hash__(self.$brython_value)}} return self.valueOf()} int.__index__=(self)=> int_value(self) int.__init__=()=> _b_.None int.__int__=(self)=> self int.__invert__=function(self){if(Math.abs(self)< 2**31){return ~self} return $B.rich_op('__sub__',$B.rich_op('__mul__',self,-1),1)} int.__mod__=function(self,other){ if($B.$isinstance(other,_b_.tuple)&& other.length==1){other=other[0]} if(other.__class__===$B.long_int){self=BigInt(self) other=other.value if(other==0){$B.RAISE(_b_.ZeroDivisionError,"integer division or modulo by zero")} return int_or_long((self % other+other)% other)} if($B.$isinstance(other,int)){other=int_value(other) if(other===false){other=0} else if(other===true){other=1} if(other==0){$B.RAISE(_b_.ZeroDivisionError,"integer division or modulo by zero")} return(self % other+other)% other} return _b_.NotImplemented} int.__mul__=Function('self','other',op_model.replace(/\+/g,'*').replace(/add/g,"mul")) int.__ne__=function(self,other){var res=int.__eq__(self,other) return(res===_b_.NotImplemented)? res :!res} int.__neg__=function(self){var self_as_int=int_value(self) if(self_as_int.__class__===$B.long_int){return $B.long_int.__neg__(self_as_int)} return-self} int.__new__=function(cls,value,base){if(cls===undefined){$B.RAISE(_b_.TypeError,"int.__new__(): not enough arguments")}else if(! $B.$isinstance(cls,_b_.type)){$B.RAISE(_b_.TypeError,"int.__new__(X): X is not a type object")} if(cls===int){return int.$factory(value,base)} if(cls===bool){$B.RAISE(_b_.TypeError,"int.__new__(bool) is not safe, use bool.__new__()")} return{ __class__:cls,__dict__:$B.empty_dict(),$brython_value:int.$factory(value,base),toString:function(){return value}}} int.__pos__=function(self){return self} function extended_euclidean(a,b){ var d,u,v if(b==0){return[a,1n,0n]}else{[d,u,v]=extended_euclidean(b,a % b) return[d,v,u-(a/b)*v]}} int.__pow__=function(self,other,z){if(! $B.$isinstance(other,int)){return _b_.NotImplemented} if(typeof other=="boolean"){other=other ? 1 :0} if(typeof other=="number" ||$B.$isinstance(other,int)){if(z !==undefined && z !==_b_.None){ self=bigint_value(self) other=bigint_value(other) z=bigint_value(z) if(z==1){return 0} var result=1n,exponent=other,base=self % z if(base < 0){base+=z} if(exponent < 0){var gcd,inv,_ [gcd,inv,_]=extended_euclidean(self,z) if(gcd !=1){$B.RAISE(_b_.ValueError,"not relative primes: "+ self+' and '+z)} return int.__pow__(int_or_long(inv),int_or_long(-exponent),int_or_long(z))} while(exponent > 0){if(exponent % 2n==1n){result=(result*base)% z} exponent=exponent >> 1n base=(base*base)% z} return int_or_long(result)}else{if(typeof other=="number"){if(other >=0){return int_or_long(BigInt(self)**BigInt(other))}else{return $B.fast_float(Math.pow(self,other))}}else if(other.__class__===$B.long_int){if(other.value >=0){return int_or_long(BigInt(self)**other.value)}else{return $B.fast_float(Math.pow(self,other))}}else if($B.$isinstance(other,_b_.int)){return int_or_long(int.__pow__(self,other.$brython_value))} return _b_.NotImplemented}} if($B.$isinstance(other,_b_.float)){other=_b_.float.numerator(other) if(self >=0){return $B.fast_float(Math.pow(self,other))}else{ return _b_.complex.__pow__($B.make_complex(self,0),other)}}else if($B.$isinstance(other,_b_.complex)){var preal=Math.pow(self,other.$real),ln=Math.log(self) return $B.make_complex(preal*Math.cos(ln),preal*Math.sin(ln))} var rpow=$B.$getattr(other,"__rpow__",_b_.None) if(rpow !==_b_.None){return rpow(self)} $err("**",other)} int.__repr__=function(self){$B.builtins_repr_check(int,arguments) var value=int_value(self),x=value.__class__===$B.long_int ? value.value :value if($B.int_max_str_digits !=0 && x >=10n**BigInt($B.int_max_str_digits)){$B.RAISE(_b_.ValueError,`Exceeds the limit `+ `(${$B.int_max_str_digits}) for integer string conversion`)} return x.toString()} int.__setattr__=function(self,attr,value){if(typeof self=="number" ||typeof self=="boolean"){var cl_name=$B.class_name(self) if(_b_.dir(self).indexOf(attr)>-1){$B.RAISE_ATTRIBUTE_ERROR("attribute '"+attr+ `' of '${cl_name}' objects is not writable`,self,attr)}else{$B.RAISE_ATTRIBUTE_ERROR(`'${cl_name}' object`+ ` has no attribute '${attr}'`,self,attr)}} _b_.dict.$setitem(self.__dict__,attr,value) return _b_.None} int.__sub__=Function('self','other',op_model.replace(/\+/g,'-').replace(/__add__/g,'__sub__')) int.__truediv__=function(self,other){if($B.$isinstance(other,int)){other=int_value(other) if(other==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} if(other.__class__===$B.long_int){return $B.fast_float(self/parseInt(other.value))} return $B.fast_float(self/other)} return _b_.NotImplemented} int.bit_count=function(self){var s=_b_.bin(_b_.abs(self)),nb=0 for(var x of s){if(x=='1'){nb++}} return nb} int.bit_length=function(self){var s=_b_.bin(self) s=$B.$getattr(s,"lstrip")("-0b") return s.length } int.numerator=(self)=> int_value(self) int.denominator=()=> 1 int.imag=()=> 0 int.real=(self)=> self for(var attr of['numerator','denominator','imag','real']){int[attr].setter=(function(x){return function(self){$B.RAISE_ATTRIBUTE_ERROR(`attribute '${x}' of `+ `'${$B.class_name(self)}' objects is not writable`,self,x)}})(attr)} var model= `var _b_ = __BRYTHON__.builtins if(typeof other == "number"){ // transform into BigInt: JS converts numbers to 32 bits return _b_.int.$int_or_long(BigInt(self) & BigInt(other))}else if(typeof other == "boolean"){ return self & (other ? 1 : 0)}else if(other.__class__ === $B.long_int){ return _b_.int.$int_or_long(BigInt(self) & other.value)}else if($B.$isinstance(other, _b_.int)){ // int subclass return _b_.int.__and__(self, other.$brython_value)} return _b_.NotImplemented` int.__and__=Function('self','other',model) int.__lshift__=Function('self','other',model.replace(/&/g,'<<').replace(/__and__/g,'__lshift__')) int.__rshift__=Function('self','other',model.replace(/&/g,'>>').replace(/__and__/g,'__rshift__')) int.__or__=Function('self','other',model.replace(/&/g,'|').replace(/__and__/g,'__or__')) int.__xor__=Function('self','other',model.replace(/&/g,'^').replace(/__and__/g,'__xor__')) int.__ge__=function(self,other){self=int_value(self) if(typeof other=="number"){return self >=other}else if(other !==null && other.__class__===$B.long_int){return self >=other.value}else if(typeof other=="boolean"){return self >=other ? 1 :0}else if($B.$isinstance(other,_b_.int)){return self >=other.$brython_value} return _b_.NotImplemented} int.__gt__=function(self,other){var res=int.__le__(self,other) return res===_b_.NotImplemented ? res :! res} int.__le__=function(self,other){self=int_value(self) if(typeof other=="number"){return self <=other}else if(other !==null && other.__class__===$B.long_int){return self <=other.value}else if(typeof other=="boolean"){return self <=other ? 1 :0}else if($B.$isinstance(other,_b_.int)){return self <=other.$brython_value} return _b_.NotImplemented} int.__lt__=function(self,other){var res=int.__ge__(self,other) return res===_b_.NotImplemented ? res :! res} var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"] for(var r_opname of r_opnames){if(int["__r"+r_opname+"__"]===undefined && int['__'+r_opname+'__']){int["__r"+r_opname+"__"]=(function(name){return function(self,other){if($B.$isinstance(other,int)){other=int_value(other) return int["__"+name+"__"](other,self)} return _b_.NotImplemented}})(r_opname)}} var $valid_digits=function(base){var digits="" if(base===0){return "0"} if(base < 10){for(let i=0;i < base;i++){digits+=String.fromCharCode(i+48)} return digits} digits="0123456789" for(let i=10;i < base;i++){digits+=String.fromCharCode(i+55)} return digits} int.$factory=function(){var missing={},$=$B.args("int",2,{x:null,base:null},["x","base"],arguments,{x:missing,base:missing},null,null,1),value=$.x,base=$.base===undefined ? missing :$.base,initial_value=value,explicit_base=base !==missing if(value===missing ||value===undefined){if(base !==missing){$B.RAISE(_b_.TypeError,"int() missing string argument")} return 0} if($B.$isinstance(value,[_b_.bytes,_b_.bytearray])){ value=$B.$getattr(value,'decode')('latin-1')}else if(explicit_base && ! $B.$isinstance(value,_b_.str)){$B.RAISE(_b_.TypeError,"int() can't convert non-string with explicit base")}else if($B.$isinstance(value,_b_.memoryview)){value=$B.$getattr(_b_.memoryview.tobytes(value),'decode')('latin-1')} if(! $B.$isinstance(value,_b_.str)){if(base !==missing){$B.RAISE(_b_.TypeError,"int() can't convert non-string with explicit base")}else{ for(let special_method of['__int__','__index__','__trunc__']){let num_value=$B.$getattr($B.get_class(value),special_method,_b_.None) if(num_value !==_b_.None){let res=$B.$call(num_value)(value) if(special_method=='__trunc__'){$B.warn(_b_.DeprecationWarning,'The delegation of int() to __trunc__ is deprecated.') let index_method=$B.$getattr(res,'__index__',null) if(index_method===null){$B.RAISE(_b_.TypeError,'__trunc__ returned'+ ` non-Integral (type ${$B.class_name(res)})`)} res=$B.$call(index_method)()} if($B.$isinstance(res,_b_.int)){if(typeof res !=="number" && res.__class__ !==$B.long_int){$B.warn(_b_.DeprecationWarning,special_method+ ' returned non-int (type '+$B.class_name(res)+ '). The ability to return an instance of a '+ 'strict subclass of int is deprecated, and may '+ 'be removed in a future version of Python.')} return int_value(res)}else{let klass=$B.get_class(res),index_method=$B.$getattr(klass,'__index__',null) if(index_method===null){$B.RAISE(_b_.TypeError,special_method+ `returned non-int (type ${$B.class_name(res)})`)} return int_value(res)}}} $B.RAISE(_b_.TypeError,"int() argument must be a string, a bytes-like object "+ `or a real number, not '${$B.class_name(value)}'`)}} if(value.length==0){$B.RAISE(_b_.ValueError,`invalid literal for int() with base 10: ${_b_.repr(value)}`)} base=base===missing ? 10:$B.PyNumber_Index(base) if(!(base >=2 && base <=36)){ if(base !=0){$B.RAISE(_b_.ValueError,"invalid base")}} function invalid(base){$B.RAISE(_b_.ValueError,"invalid literal for int() with base "+ base+": "+_b_.repr(initial_value))} if(typeof value !="string"){ value=_b_.str.$to_string(value)} var _value=value.trim(), sign='' if(_value.startsWith('+')||_value.startsWith('-')){sign=_value[0] _value=_value.substr(1)} if(_value.length==2 && base==0 && (_value=="0b" ||_value=="0o" ||_value=="0x")){$B.RAISE(_b_.ValueError,"invalid value")} if(_value.endsWith('_')){invalid(base)} if(value.indexOf('__')>-1){ invalid(base)} if(_value.length > 2){let _pre=_value.substr(0,2).toUpperCase() if(base==0){if(_pre=="0B"){base=2}else if(_pre=="0O"){base=8}else if(_pre=="0X"){base=16}else if(_value.startsWith('0')){_value=_value.replace(/_/g,'') if(_value.match(/^0+$/)){return 0} invalid(base)}}else if(_pre=="0X" && base !=16){invalid(base)}else if(_pre=="0O" && base !=8){invalid(base)} if((_pre=="0B" && base==2)||_pre=="0O" ||_pre=="0X"){_value=_value.substr(2) if(_value.startsWith('_')){ _value=_value.substr(1)}}} if(base==0){ base=10} var _digits=$valid_digits(base),_re=new RegExp("^[+-]?["+_digits+"]"+ "["+_digits+"_]*$","i"),match=_re.exec(_value),res if(match===null){ res=0 var digit for(var char of _value){if(/\p{Nd}/u.test(char)){ let cp=char.codePointAt(0) for(let start of $B.digits_starts){if(cp-start < 10){digit=cp-start break}}}else{if(base > 10 && _digits.indexOf(char.toUpperCase())>-1){digit=char.toUpperCase().charCodeAt(0)-55}else{invalid(base)}} if(digit < base){res=$B.rich_op('__mul__',res,base) res=$B.rich_op('__add__',res,digit)}else{invalid(base)}} return res}else{_value=_value.replace(/_/g,"")} if(base==2){res=BigInt('0b'+_value)}else if(base==8){res=BigInt('0o'+_value)}else if(base==16){res=BigInt('0x'+_value)}else{if($B.int_max_str_digits !=0 && _value.length > $B.int_max_str_digits){$B.RAISE(_b_.ValueError,"Exceeds the limit "+ `(${$B.int_max_str_digits}) for integer string conversion: `+ `value has ${value.length} digits; use `+ "sys.set_int_max_str_digits() to increase the limit.")} if(base==10){res=BigInt(_value)}else{ base=BigInt(base) res=0n let coef=1n,char for(let i=_value.length-1;i >=0;i--){char=_value[i].toUpperCase() res+=coef*BigInt(_digits.indexOf(char)) coef*=base}}} if(sign=='-'){res=-res} return int_or_long(res)} $B.set_func_names(int,"builtins") _b_.int=int $B.$bool=function(obj,bool_class){ if(obj===null ||obj===undefined ){return false} switch(typeof obj){case "boolean": return obj case "number": case "string": if(obj){return true} return false default: if(obj.$is_class){return true} var klass=$B.get_class(obj),missing={},bool_method=$B.search_in_mro(klass,'__bool__') if(bool_method===undefined){var len_method=$B.$getattr(klass,'__len__',missing) if(len_method===missing){return true} return _b_.len(obj)> 0}else{var res=$B.call_with_mro(obj,'__bool__') if(res !==true && res !==false){$B.RAISE(_b_.TypeError,"__bool__ should return "+ "bool, returned "+$B.class_name(res))} return res}}} var bool={__bases__:[int],__class__:_b_.type,__mro__:[int,_b_.object],__qualname__:'bool',$is_class:true,$not_basetype:true, $is_number:true,$native:true,$descriptors:{"numerator":true,"denominator":true,"imag":true,"real":true}} bool.__and__=function(self,other){if($B.$isinstance(other,bool)){return self && other}else if($B.$isinstance(other,int)){return int.__and__(bool.__index__(self),int.__index__(other))} return _b_.NotImplemented} bool.__float__=function(self){return self ? $B.fast_float(1):$B.fast_float(0)} bool.__hash__=bool.__index__=bool.__int__=function(self){if(self.valueOf())return 1 return 0} bool.__neg__=function(self){return-$B.int_or_bool(self)} bool.__or__=function(self,other){if($B.$isinstance(other,bool)){return self ||other}else if($B.$isinstance(other,int)){return int.__or__(bool.__index__(self),int.__index__(other))} return _b_.NotImplemented} bool.__pos__=$B.int_or_bool bool.__repr__=function(self){$B.builtins_repr_check(bool,arguments) return self ? "True" :"False"} bool.__xor__=function(self,other){if($B.$isinstance(other,bool)){return self ^ other ? true :false}else if($B.$isinstance(other,int)){return int.__xor__(bool.__index__(self),int.__index__(other))} return _b_.NotImplemented} bool.__invert__=function(self){$B.warn(_b_.DeprecationWarning,`Bitwise inversion '~' on bool is deprecated.This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool.Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int.`) return int.__invert__(self)} bool.$factory=function(){ var $=$B.args("bool",1,{x:null},["x"],arguments,{x:false},null,null,1) return $B.$bool($.x,true)} bool.__new__=function(cls,value){if(cls===undefined){$B.RAISE(_b_.TypeError,"bool.__new__(): not enough arguments")}else if(!$B.$isinstance(cls,_b_.type)){$B.RAISE(_b_.TypeError,`bool.__new__(X): X is not a type object (${$B.class_name(cls) })`)}else if(!_b_.issubclass(cls,bool)){let class_name=$B.class_name(cls) $B.RAISE(_b_.TypeError,`bool.__new__(${class_name}): ${class_name} is not a subtype of bool`)} if(arguments.length > 2){$B.RAISE(_b_.TypeError,`bool expected at most 1 argument, got ${arguments.length - 1}`)} return bool.$factory(value)} bool.from_bytes=function(){var $=$B.args("from_bytes",3,{bytes:null,byteorder:null,signed:null },["bytes","byteorder","signed"],arguments,{byteorder:'big',signed:false },null,null) let int_result=int.from_bytes($.bytes,$.byteorder,$.signed) return bool.$factory(int_result)} bool.numerator=int.numerator bool.denominator=int.denominator bool.real=(self)=> self ? 1 :0 bool.imag=int.imag for(var attr of['real']){bool[attr].setter=(function(x){return function(self){$B.RAISE_ATTRIBUTE_ERROR(`attribute '${x}' of `+ `'${$B.class_name(self)}' objects is not writable`,self,x)}})(attr)} _b_.bool=bool $B.set_func_names(bool,"builtins")})(__BRYTHON__); ; (function($B){ var _b_=$B.builtins var long_int={__class__:_b_.type,__mro__:[_b_.int,_b_.object],__qualname__:'int',$infos:{__module__:"builtins",__name__:"int"},$is_class:true,$native:true,$descriptors:{"numerator":true,"denominator":true,"imag":true,"real":true}} var int_or_long=_b_.int.$int_or_long function preformat(self,fmt){if(fmt.empty){return _b_.str.$factory(self)} if(fmt.type && 'bcdoxXn'.indexOf(fmt.type)==-1){$B.RAISE(_b_.ValueError,"Unknown format code '"+fmt.type+ "' for object of type 'int'")} var res switch(fmt.type){case undefined: case "d": res=self.toString() break case "b": res=(fmt.alternate ? "0b" :"")+BigInt(self.value).toString(2) break case "c": res=_b_.chr(self) break case "o": res=(fmt.alternate ? "0o" :"")+BigInt(self.value).toString(8) break case "x": res=(fmt.alternate ? "0x" :"")+BigInt(self.value).toString(16) break case "X": res=(fmt.alternate ? "0X" :"")+BigInt(self.value).toString(16).toUpperCase() break case "n": return self } if(fmt.sign !==undefined){if((fmt.sign==" " ||fmt.sign=="+" )&& self >=0){res=fmt.sign+res}} return res} long_int.$to_js_number=function(self){return Number(self.value)} long_int.__format__=function(self,format_spec){var fmt=new $B.parse_format_spec(format_spec,self) if(fmt.type && 'eEfFgG%'.indexOf(fmt.type)!=-1){ return _b_.float.__format__(self,format_spec)} fmt.align=fmt.align ||">" var res=preformat(self,fmt) if(fmt.comma){var sign=res[0]=="-" ? "-" :"",rest=res.substr(sign.length),len=rest.length,nb=Math.ceil(rest.length/3),chunks=[] for(var i=0;i < nb;i++){chunks.push(rest.substring(len-3*i-3,len-3*i))} chunks.reverse() res=sign+chunks.join(",")} return $B.format_width(res,fmt)} long_int.__abs__=function(self){return $B.fast_long_int(self.value > 0 ? self.value :-self.value)} long_int.__add__=function(self,other){if(typeof other=="number"){return int_or_long(self.value+BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value+other.value)}else if(typeof other=="boolean"){return int_or_long(self.value+(other ? 1n :0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__add__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__divmod__=function(self,other){var a=self.value,b=_b_.int.$to_bigint(other),quotient if((a >=0 && b > 0)||(a <=0 && b < 0)){quotient=a/b}else{quotient=a/b-1n} var rest=a-quotient*b return $B.fast_tuple([int_or_long(quotient),int_or_long(rest)])} long_int.__eq__=function(self,other){if(other.__class__===$B.long_int){return self.value==other.value}else if(typeof other=="number" ||typeof other=="boolean"){return false}else if($B.$isinstance(other,_b_.int)){return long_int.__eq__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__float__=function(self){if(! isFinite(Number(self.value))){$B.RAISE(_b_.OverflowError,"int too large to convert to float")} return $B.fast_float(Number(self.value))} long_int.__floordiv__=function(self,other){if(typeof other=="number"){return int_or_long(self.value/BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value/other.value)}else if(typeof other=="boolean"){return int_or_long(self.value/(other ? 1n :0n))}else if($B.$isinstance(other,_b_.int)){return int_or_long(self.value/other.$brython_value)} return _b_.NotImplemented} long_int.__ge__=function(self,other){if(typeof other=="number"){return self.value >=other}else if(other.__class__===$B.long_int){return self.value >=other.value}else if(typeof other=="boolean"){return self.value >=(other ? 1 :0)}else if($B.$isinstance(other,_b_.int)){return self.value >=other.$brython_value} return _b_.NotImplemented} long_int.__gt__=function(self,other){var res=long_int.__le__(self,other) return res===_b_.NotImplemented ? res :! res} long_int.__hash__=function(self){var modulus=2305843009213693951n,sign=self.value >=0 ? 1n :-1n,self_pos=self.value*sign var _hash=sign*(self_pos % modulus) return self.__hashvalue__=int_or_long(_hash)} long_int.__index__=function(self){return self} long_int.__invert__=function(self){return int_or_long(-1n-self.value)} long_int.__le__=function(self,other){if(typeof other=="number"){return self.value <=other}else if(other.__class__===$B.long_int){return self.value <=other.value}else if(typeof other=="boolean"){return self.value <=(other ? 1 :0)}else if($B.$isinstance(other,_b_.int)){return self.value <=other.$brython_value} return _b_.NotImplemented} long_int.__lt__=function(self,other){var res=long_int.__ge__(self,other) return res===_b_.NotImplemented ? res :! res} long_int.__lshift__=function(self,other){if(typeof other=="number"){return int_or_long(self.value << BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value << other.value)}else if(typeof other=="boolean"){return int_or_long(self.value <<(other ? 1n :0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__lshift__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__mod__=function(self,other){if(typeof other=="number"){return int_or_long(self.value % BigInt(other))}else if(other.__class__===$B.long_int){var n=self.value,m=other.value return int_or_long(((n % m)+m)% m)}else if(typeof other=="boolean"){return int_or_long(self.value %(other ? 1n :0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__mod__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__mro__=[_b_.int,_b_.object] long_int.__mul__=function(self,other){if(typeof other=="number"){return int_or_long(self.value*BigInt(other))}else if(typeof other=="boolean"){return int_or_long(self.value*(other ? 1n :0n))}else if(other.__class__===$B.long_int){return int_or_long(self.value*other.value)}else if($B.$isinstance(other,_b_.int)){ return long_int.__mul__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__ne__=function(self,other){var res=long_int.__eq__(self,other) return res===_b_.NotImplemented ? res :!res} long_int.__neg__=function(self){return $B.fast_long_int(-self.value)} long_int.__pos__=function(self){return self} long_int.__pow__=function(self,power,z){if(z !==undefined){return _b_.int.__pow__(self,power,z)} if(typeof power=="number"){return int_or_long(self.value**BigInt(power))}else if(typeof power=="boolean"){return int_or_long(self.value**power ? 1n :0n)}else if(power.__class__===$B.long_int){return int_or_long(self.value**power.value)}else if($B.$isinstance(power,_b_.int)){ return long_int.__pow__(self,power.$brython_value)} return _b_.NotImplemented} long_int.__rshift__=function(self,other){if(typeof other=="number"){return int_or_long(self.value >> BigInt(other))}else if(other.__class__===$B.long_int){return int_or_long(self.value >> other.value)}else if(typeof other=="boolean"){return int_or_long(self.value >>(other ? 1n :0n))}else if($B.$isinstance(other,_b_.int)){return long_int.__rshift__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__repr__=function(self){$B.builtins_repr_check($B.long_int,arguments) if($B.int_max_str_digits !=0 && self.value >=10n**BigInt($B.int_max_str_digits)){$B.RAISE(_b_.ValueError,`Exceeds the limit `+ `(${$B.int_max_str_digits}) for integer string conversion`)} return self.value.toString()} long_int.__sub__=function(self,other){if(typeof other=="number"){return int_or_long(self.value-BigInt(other))}else if(typeof other=="boolean"){return int_or_long(self.value-(other ? 1n :0n))}else if(other.__class__===$B.long_int){return int_or_long(self.value-other.value)}else if($B.$isinstance(other,_b_.int)){ return long_int.__sub__(self,other.$brython_value)} return _b_.NotImplemented} long_int.__truediv__=function(self,other){if(typeof other=="number"){return $B.fast_float(Number(self.value)/other)}else if(typeof other=="boolean"){return $B.fast_float(Number(self.value)*(other ? 1 :0))}else if(other.__class__===$B.long_int){return $B.fast_float(Number(self.value)/Number(other.value))}else if($B.$isinstance(other,_b_.int)){ return long_int.__truediv__(self,other.$brython_value)} return _b_.NotImplemented} long_int.bit_count=function(self){var s=self.value.toString(2),nb=0 for(var x of s){if(x=='1'){nb++}} return nb} long_int.bit_length=function(self){return self.value.toString(2).length} function _infos(self){ var nbits=$B.long_int.bit_length(self),pow2=2n**BigInt(nbits-1),rest=BigInt(self.value)-pow2,relative_rest=new Number(rest/pow2) return{nbits,pow2,rest,relative_rest}} long_int.$log2=function(x){if(x.value < 0){$B.RAISE(_b_.ValueError,'math domain error')} var infos=_infos(x) return _b_.float.$factory(infos.nbits-1+ Math.log(1+infos.relative_rest/Math.LN2))} long_int.$log10=function(x){if(x.value < 0){$B.RAISE(_b_.ValueError,'math domain error')} var x_string=x.value.toString(),exp=x_string.length-1,mant=parseFloat(x_string[0]+'.'+x_string.substr(1)) return _b_.float.$factory(exp+Math.log10(mant))} long_int.numerator=(self)=> self long_int.denominator=()=> 1 long_int.imag=()=> 0 long_int.real=(self)=> self var body= `var $B = __BRYTHON__, _b_ = $B.builtins if(typeof other == "number"){ return _b_.int.$int_or_long(self.value & BigInt(other))}else if(typeof other == "boolean"){ return _b_.int.$int_or_long(self.value & (other ? 1n : 0n))}else if(other.__class__ === $B.long_int){ return _b_.int.$int_or_long(self.value & other.value)}else if($B.$isinstance(other, _b_.int)){ // int subclass return $B.long_int.__and__(self, other.$brython_value)} return _b_.NotImplemented` long_int.__and__=Function('self','other',body) long_int.__or__=Function('self','other',body.replace(/&/g,'|').replace(/__and__/g,'__or__')) long_int.__xor__=Function('self','other',body.replace(/&/g,'^').replace(/__and__/g,'__xor__')) long_int.to_bytes=function(self,len,byteorder,signed){ var res=[],v=self.value if(! $B.$bool(signed)&& v < 0){$B.RAISE(_b_.OverflowError,"can't convert negative int to unsigned")} while(v > 0){var quot=v/256n,rest=v-quot*256n v=quot res.push(Number(rest)) if(res.length > len){$B.RAISE(_b_.OverflowError,"int too big to convert")}} while(res.length < len){res.push(0)} if(byteorder=='big'){res.reverse()} return _b_.bytes.$factory(res)} function digits(base){ var is_digits={} for(let i=0;i < base;i++){if(i==10){break} is_digits[i]=i} if(base > 10){ for(let i=0;i < base-10;i++){is_digits[String.fromCharCode(65+i)]=10+i is_digits[String.fromCharCode(97+i)]=10+i}} return is_digits} long_int.$from_int=function(value){return{__class__:long_int,value:value.toString(),pos:value > 0}} long_int.$factory=function(value,base){ var is_digits=digits(base) for(let i=0;i < value.length;i++){if(is_digits[value.charAt(i)]===undefined){$B.RAISE(_b_.ValueError,'int argument is not a valid number: "'+value+'"')}} var res if(base==10){res=BigInt(value)}else if(base==16){res=BigInt('0x'+value)}else if(base==8){res=BigInt('0o'+value)}else{base=BigInt(base) res=0n let coef=1n,char for(let i=value.length-1;i >=0;i--){char=value[i].toUpperCase() res+=coef*BigInt(is_digits[char]) coef*=base}} return{__class__:$B.long_int,value:res}} function extended_euclidean_algorithm(a,b){ var s=0,old_s=1,t=1,old_t=0,r=b,old_r=a,quotient,tmp while($B.rich_comp('__ne__',r,0)){quotient=$B.rich_op('__floordiv__',old_r,r) tmp=$B.rich_op('__sub__',old_r,$B.rich_op('__mul__',quotient,r)) old_r=r r=tmp tmp=$B.rich_op('__sub__',old_s,$B.rich_op('__mul__',quotient,s)) old_s=s s=tmp tmp=$B.rich_op('__sub__',old_t,$B.rich_op('__mul__',quotient,t)) old_t=t t=tmp} return[old_r,old_s,old_t]} function inverse_of(n,p){ var gcd,x,y [gcd,x,y]=extended_euclidean_algorithm(n,p) if($B.rich_comp('__ne__',gcd,1)){ throw Error( `${n} has no multiplicative inverse ' 'modulo ${p}`)}else{return $B.rich_op('__mod__',x,p)}} $B.inverse_of=inverse_of $B.set_func_names(long_int,"builtins") $B.long_int=long_int $B.fast_long_int=function(value){if(typeof value !=='bigint'){console.log('expected bigint, got',value) throw Error('not a big int')} return{ __class__:$B.long_int,value:value}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function float_value(obj){return obj.__class__===float ? obj :fast_float(obj.value)} function copysign(x,y){var x1=Math.abs(x) var y1=y var sign=Math.sign(y1) sign=(sign==1 ||Object.is(sign,+0))? 1 :-1 return x1*sign} var float={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:'float',$is_class:true,$native:true,$descriptors:{"numerator":true,"denominator":true,"imag":true,"real":true}} float.$float_value=float_value float.$to_js_number=function(self){if(self.__class__===float){return self.value}else{return float.$to_js_number(self.value)}} float.numerator=(self)=> self float.denominator=()=> 1 float.imag=()=> 0 float.real=(self)=> self float.__float__=function(self){return self} $B.shift1_cache={} float.as_integer_ratio=function(self){if(isinf(self)){$B.RAISE(_b_.OverflowError,"Cannot pass infinity to "+ "float.as_integer_ratio.")} if(isnan(self)){$B.RAISE(_b_.ValueError,"Cannot pass NaN to "+ "float.as_integer_ratio.")} var tmp=frexp(self),fp=tmp[0],exponent=tmp[1] for(var i=0;i < 300;i++){if(fp==Math.floor(fp)){break}else{fp*=2 exponent--}} var numerator=_b_.int.$factory(fp),py_exponent=_b_.abs(exponent),denominator=1,x if($B.shift1_cache[py_exponent]!==undefined){x=$B.shift1_cache[py_exponent]}else{x=$B.$getattr(1,"__lshift__")(py_exponent) $B.shift1_cache[py_exponent]=x} py_exponent=x if(exponent > 0){numerator=$B.rich_op("__mul__",numerator,py_exponent)}else{denominator=py_exponent} return $B.fast_tuple([_b_.int.$factory(numerator),_b_.int.$factory(denominator)])} function check_self_is_float(x,method){if(x.__class__===_b_.float ||$B.$isinstance(x,_b_.float)){return true} $B.RAISE(_b_.TypeError,`descriptor '${method}' requires a `+ `'float' object but received a '${$B.class_name(x)}'`)} float.__abs__=function(self){check_self_is_float(self,'__abs__') return fast_float(Math.abs(self.value))} float.__bool__=function(self){check_self_is_float(self,'__bool__') return _b_.bool.$factory(self.value)} float.__ceil__=function(self){check_self_is_float(self,'__ceil__') if(isnan(self)){$B.RAISE(_b_.ValueError,'cannot convert float NaN to integer')}else if(isinf(self)){$B.RAISE(_b_.OverflowError,'cannot convert float infinity to integer')} return Math.ceil(self.value)} function _float_div_mod(vx,wx){ var mod=vx % wx var div=(vx-mod)/wx if(mod){ if((wx < 0)!=(mod < 0)){mod+=wx; div-=1.0;}}else{ mod=copysign(0.0,wx)} var floordiv if(div){floordiv=Math.floor(div); if(div-floordiv > 0.5){floordiv+=1.0;}}else{ floordiv=copysign(0.0,vx/wx);} return{floordiv,mod}} float.__divmod__=function(self,other){check_self_is_float(self,'__divmod__') if(! $B.$isinstance(other,[_b_.int,float])){return _b_.NotImplemented} var vx=self.value,wx=float.$factory(other).value var divmod=_float_div_mod(vx,wx) return $B.fast_tuple([$B.fast_float(divmod.floordiv),$B.fast_float(divmod.mod)])} float.__eq__=function(self,other){check_self_is_float(self,'__eq__') if(isNaN(self.value)&& ($B.$isinstance(other,float)&& isNaN(other.value))){return false} if($B.$isinstance(other,_b_.int)){if(other.__class__===$B.long_int){return BigInt(self.value)==other.value} return self.value==other} if($B.$isinstance(other,float)){return self.value==other.value} if($B.$isinstance(other,_b_.complex)){if(! $B.rich_comp('__eq__',0,other.$imag)){return false} return float.__eq__(self,other.$real)} return _b_.NotImplemented} float.__floor__=function(self){check_self_is_float(self,'__floor__') if(isnan(self)){$B.RAISE(_b_.ValueError,'cannot convert float NaN to integer')}else if(isinf(self)){$B.RAISE(_b_.OverflowError,'cannot convert float infinity to integer')} return Math.floor(self.value)} float.__floordiv__=function(self,other){check_self_is_float(self,'__floordiv__') if(! $B.$isinstance(other,[_b_.int,float])){return _b_.NotImplemented} var vx=self.value,wx=float.$factory(other).value var divmod=_float_div_mod(vx,wx) return $B.fast_float(divmod.floordiv)} const DBL_MANT_DIG=53,LONG_MAX=$B.MAX_VALUE,DBL_MAX_EXP=2**10,LONG_MIN=$B.MIN_VALUE,DBL_MIN_EXP=-1021 float.fromhex=function(klass,s){function hex_from_char(char){return parseInt(char,16)} function finished(){ while(s[pos]&& s[pos].match(/\s/)){pos++;} if(pos !=s.length){throw parse_error()} if(negate){x=float.__neg__(x)} return klass===_b_.float ? x :$B.$call(klass)(x)} function overflow_error(){$B.RAISE(_b_.OverflowError,"hexadecimal value too large to represent as a float");} function parse_error(){$B.RAISE(_b_.ValueError,"invalid hexadecimal floating-point string");} function insane_length_error(){$B.RAISE(_b_.ValueError,"hexadecimal string too long to convert");} s=s.trim() if(s.match(/^\+?inf(inity)?$/i)){return INF}else if(s.match(/^-inf(inity)?$/i)){return NINF}else if(s.match(/^[+-]?nan$/i)){return NAN} var pos=0,negate,ldexp=_b_.float.$funcs.ldexp if(s[pos]=='-'){pos++; negate=1;}else if(s[pos]=='+'){pos++} if(s.substr(pos,2).toLowerCase()=='0x'){pos+=2} var coeff_start=pos,coeff_end while(hex_from_char(s[pos])>=0){pos++;} var save_pos=pos; if(s[pos]=='.'){pos++; while(hex_from_char(s[pos])>=0){pos++;} coeff_end=pos-1;}else{coeff_end=pos;} var ndigits=coeff_end-coeff_start,fdigits=coeff_end-save_pos; if(ndigits==0){throw parse_error()} if(ndigits > Math.min(DBL_MIN_EXP-DBL_MANT_DIG-LONG_MIN/2,LONG_MAX/2+1-DBL_MAX_EXP)/4){throw insane_length_error()} var exp if(s[pos]=='p' ||s[pos]=='P'){pos++; var exp_start=pos; if(s[pos]=='-' ||s[pos ]=='+'){pos++;} if(!('0' <=s[pos]&& s[pos]<='9')){throw parse_error()} pos++; while('0' <=s[pos]&& s[pos]<='9'){pos++;} exp=parseInt(s.substr(exp_start));}else{exp=0;} function HEX_DIGIT(j){if(! Number.isInteger(j)){throw Error('j pas entier')} return hex_from_char(s[j < fdigits ? coeff_end-j : coeff_end-1-j])} while(ndigits > 0 && HEX_DIGIT(ndigits-1)==0){ndigits--;} if(ndigits==0 ||exp < LONG_MIN/2){x=ZERO; return finished()} if(exp > LONG_MAX/2){console.log('overflow, exp',exp) throw overflow_error();} exp=exp-4*fdigits; var top_exp=exp+4*(ndigits-1); for(let digit=BigInt(HEX_DIGIT(ndigits-1));digit !=0;digit/=2n){top_exp++;} if(top_exp < DBL_MIN_EXP-DBL_MANT_DIG){x=ZERO return finished()} if(top_exp > DBL_MAX_EXP){throw overflow_error()} var lsb=Math.max(top_exp,DBL_MIN_EXP)-DBL_MANT_DIG; var x=0.0; if(exp >=lsb){ for(let i=ndigits-1;i >=0;i--){x=16.0*x+HEX_DIGIT(i)} x=ldexp($B.fast_float(x),exp) return finished()} var half_eps=1 <<((lsb-exp-1)% 4),key_digit=parseInt((lsb-exp-1)/4) for(let i=ndigits-1;i > key_digit;i--){x=16.0*x+HEX_DIGIT(i)} let digit=HEX_DIGIT(key_digit) x=16.0*x+(digit &(16-2*half_eps)) if((digit & half_eps)!=0){var round_up=0; if((digit &(3*half_eps-1))!=0 ||(half_eps==8 && key_digit+1 < ndigits &&(HEX_DIGIT(key_digit+1)& 1)!=0)){round_up=1;}else{for(let i=key_digit-1;i >=0;i--){if(HEX_DIGIT(i)!=0){round_up=1; break;}}} if(round_up){x+=2*half_eps; if(top_exp==DBL_MAX_EXP && x==ldexp(2*half_eps,DBL_MANT_DIG).value){ throw overflow_error()}}} x=ldexp(x,(exp+4*key_digit)); return finished()} float.__getformat__=function(arg){if(arg=="double" ||arg=="float"){return "IEEE, little-endian"} if(typeof arg !=='string'){$B.RAISE(_b_.TypeError," __getformat__() argument must be str, not "+ $B.class_name(arg))} $B.RAISE(_b_.ValueError,"__getformat__() argument 1 must be "+ "'double' or 'float'")} var format_sign=function(val,flags){switch(flags.sign){case '+': return(val >=0 ||isNaN(val))? '+' :'' case '-': return '' case ' ': return(val >=0 ||isNaN(val))? ' ' :''} if(flags.space){if(val >=0){return " "}} return ''} function preformat(self,fmt){var value=self.value if(fmt.empty){return _b_.str.$factory(self)} if(fmt.type && 'eEfFgGn%'.indexOf(fmt.type)==-1){$B.RAISE(_b_.ValueError,"Unknown format code '"+fmt.type+ "' for object of type 'float'")} var special if(isNaN(value)){special="efg".indexOf(fmt.type)>-1 ? "nan" :"NAN"}else if(value==Number.POSITIVE_INFINITY){special="efg".indexOf(fmt.type)>-1 ? "inf" :"INF"}else if(value==Number.NEGATIVE_INFINITY){special="efg".indexOf(fmt.type)>-1 ? "-inf" :"-INF"} if(special){return format_sign(value,fmt)+special} if(fmt.precision===undefined && fmt.type !==undefined){fmt.precision=6} if(fmt.type=="%"){value*=100} if(fmt.type=="e"){let res=value.toExponential(fmt.precision),exp=parseInt(res.substr(res.search("e")+1)) if(Math.abs(exp)< 10){res=res.substr(0,res.length-1)+"0"+ res.charAt(res.length-1)} return res} var res if(fmt.precision !==undefined){ let prec=fmt.precision if(prec==0){return Math.round(value)+""} res=$B.roundDownToFixed(value,prec) let pt_pos=res.indexOf(".") if(fmt.type !==undefined && (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 if(missing > 0){res+="0".repeat(missing)}}}else if(fmt.type && fmt.type.toLowerCase()=="g"){let exp_fmt=preformat(self,{type:"e"}).split("e"),exp=parseInt(exp_fmt[1]) 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})} let parts=res.split("e") if(fmt.alternate){if(parts[0].search(/\./)==-1){parts[0]+='.'}}else{let signif=parts[0] if(signif.indexOf('.')> 0){while(signif.endsWith("0")){signif=signif.substr(0,signif.length-1)}} if(signif.endsWith(".")){signif=signif.substr(0,signif.length-1)} parts[0]=signif} res=parts.join("e") if(fmt.type=="G"){res=res.toUpperCase()} return res}else if(fmt.type===undefined){ fmt.type="g" res=preformat(self,fmt) if(res.indexOf('.')==-1){let exp=res.length-1 exp=exp < 10 ? '0'+exp :exp let is_neg=res.startsWith('-'),point_pos=is_neg ? 2 :1,mant=res.substr(0,point_pos)+'.'+ res.substr(point_pos) return `${mant}e+${exp}`} fmt.type=undefined}else{let res1=value.toExponential(fmt.precision-1),exp=parseInt(res1.substr(res1.search("e")+1)) if(exp <-4 ||exp >=fmt.precision-1){var elts=res1.split("e") while(elts[0].endsWith("0")){elts[0]=elts[0].substr(0,elts[0].length-1)} res=elts.join("e")}}}else{res=_b_.str.$factory(self)} if(fmt.type===undefined ||"gGn".indexOf(fmt.type)!=-1){ if(res.search("e")==-1){while(res.charAt(res.length-1)=="0"){res=res.substr(0,res.length-1)}} if(res.charAt(res.length-1)=="."){if(fmt.type===undefined){res+="0"}else{res=res.substr(0,res.length-1)}}} if(fmt.sign !==undefined){if((fmt.sign==" " ||fmt.sign=="+" )&& value > 0){res=fmt.sign+res}} if(fmt.type=="%"){res+="%"} return res} float.__format__=function(self,format_spec){check_self_is_float(self,'__format__') var fmt=new $B.parse_format_spec(format_spec,self) return float.$format(self,fmt)} float.$format=function(self,fmt){ fmt.align=fmt.align ||">" var pf=preformat(self,fmt) if(fmt.z && Object.is(parseFloat(pf),-0)){ pf=pf.substr(1)} var raw=pf.split('.'),_int=raw[0] if(fmt.comma){var len=_int.length,nb=Math.ceil(_int.length/3),chunks=[] for(var i=0;i < nb;i++){chunks.push(_int.substring(len-3*i-3,len-3*i))} chunks.reverse() raw[0]=chunks.join(",")} return $B.format_width(raw.join("."),fmt)} float.$getnewargs=function(self){return $B.fast_tuple([float_value(self)])} float.__getnewargs__=function(){return float.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} var nan_hash=$B.$py_next_hash-- var mp2_31=Math.pow(2,31) $B.float_hash_cache=new Map() float.__hash__=function(self){check_self_is_float(self,'__hash__') return float.$hash_func(self)} float.$hash_func=function(self){if(self.__hashvalue__ !==undefined){return self.__hashvalue__} var _v=self.value var in_cache=$B.float_hash_cache.get(_v) if(in_cache !==undefined){return in_cache} if(_v===Infinity){return 314159}else if(_v===-Infinity){return-314159}else if(isNaN(_v)){return self.__hashvalue__=nan_hash}else if(_v===Number.MAX_VALUE){return self.__hashvalue__=$B.fast_long_int(2234066890152476671n)} if(Number.isInteger(_v)){return _b_.int.__hash__(_v)} var r=frexp(self) r[0]*=mp2_31 var hipart=parseInt(r[0]) r[0]=(r[0]-hipart)*mp2_31 var x=hipart+parseInt(r[0])+(r[1]<< 15) x &=0xFFFFFFFF $B.float_hash_cache.set(_v,x) if($B.float_hash_cache.size > 10000){ $B.float_hash_cache.clear()} return self.__hashvalue__=x} function isninf(x){var x1=float_value(x).value return x1==-Infinity ||x1==Number.NEGATIVE_INFINITY} function isinf(x){var x1=float_value(x).value return x1==Infinity ||x1==-Infinity || x1==Number.POSITIVE_INFINITY ||x1==Number.NEGATIVE_INFINITY} function isnan(x){var x1=float_value(x).value return isNaN(x1)} function fabs(x){if(x==0){return fast_float(0)} return x > 0 ? float.$factory(x):float.$factory(-x)} function frexp(x){ var x1=x if($B.$isinstance(x,float)){ if(isnan(x)||isinf(x)){return[x,0]} x1=float_value(x).value}else if($B.$isinstance(x,$B.long_int)){var exp=x.value.toString(2).length,power=2n**BigInt(exp) return[$B.fast_float(Number(x.value)/Number(power)),exp]} if(x1==0){return[0,0]} var sign=1,ex=0,man=x1 if(man < 0.){sign=-sign man=-man} while(man < 0.5){man*=2.0 ex--} while(man >=1.0){man*=0.5 ex++} man*=sign return[man,ex]} function ldexp(mantissa,exponent){if(isninf(mantissa)){return NINF}else if(isinf(mantissa)){return INF} if($B.$isinstance(mantissa,_b_.float)){mantissa=mantissa.value} if(mantissa==0){return ZERO}else if(isNaN(mantissa)){return NAN} if($B.$isinstance(exponent,$B.long_int)){if(exponent.value < 0){return ZERO}else{$B.RAISE(_b_.OverflowError,'overflow')}}else if(! isFinite(mantissa*Math.pow(2,exponent))){$B.RAISE(_b_.OverflowError,'overflow')} var steps=Math.min(3,Math.ceil(Math.abs(exponent)/1023)); var result=mantissa; for(var i=0;i < steps;i++){result*=Math.pow(2,Math.floor((exponent+i)/steps));} return fast_float(result);} float.$funcs={isinf,isninf,isnan,fabs,frexp,ldexp} float.hex=function(self){ self=float_value(self) var TOHEX_NBITS=DBL_MANT_DIG+3-(DBL_MANT_DIG+2)% 4 if(isNaN(self.value)||! isFinite(self.value)){return _b_.repr(self)} if(self.value==0){return Object.is(self.value,0)? "0x0.0p0" :"-0x0.0p0"} var _a=frexp(fabs(self.value)),_m=_a[0],_e=_a[1],_shift=1-Math.max(-1021-_e,0) _m=ldexp(fast_float(_m),_shift).value _e-=_shift var _int2hex="0123456789ABCDEF".split(""),_s=_int2hex[Math.floor(_m)] _s+='.' _m-=Math.floor(_m) for(var i=0;i <(TOHEX_NBITS-1)/4;i++){_m*=16.0 _s+=_int2hex[Math.floor(_m)] _m-=Math.floor(_m)} var _esign="+" if(_e < 0){_esign="-" _e=-_e} if(self.value < 0){return "-0x"+_s+"p"+_esign+_e} return "0x"+_s+"p"+_esign+_e} float.__init__=function(){return _b_.None} float.__int__=function(self){check_self_is_float(self,'__int__') if(Number.isInteger(self.value)){var res=BigInt(self.value),res_num=Number(res) return Number.isSafeInteger(res_num)? res_num : $B.fast_long_int(res)} return Math.trunc(self.value)} float.is_integer=function(self){return Number.isInteger(self.value)} float.from_number=function(){var $=$B.args('from_number',1,{number:null},['number'],arguments,{},null,null) var number=$.number if($B.$isinstance(number,_b_.float)){return float_value(number)} var klass=$B.get_class(number) var __float__=$B.search_in_mro(klass,'__float__') if(__float__){return __float__(number)} var __index__=$B.search_in_mro(klass,'__index__') if(__index__){var res=__index__(number) if($B.$isinstance(res,_b_.int)){return fast_float(res)} $B.RAISE(_b_.TypeError,'__index__ returned non-int of type '+ $B.class_name(res))} $B.RAISE(_b_.TypeError,'TypeError: must be real number, not '+ $B.class_name(number))} float.__mod__=function(self,other){ check_self_is_float(self,'__mod__') if(other==0){$B.RAISE(_b_.ZeroDivisionError,"float modulo")} if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other) return fast_float((self.value % other+other)% other)} if($B.$isinstance(other,float)){ var q=Math.floor(self.value/other.value),r=self.value-other.value*q if(r==0 && other.value < 0){return fast_float(-0)} return fast_float(r)} return _b_.NotImplemented} float.__mro__=[_b_.object] float.__mul__=function(self,other){if($B.$isinstance(other,_b_.int)){if(other.__class__==$B.long_int){return fast_float(self.value*parseFloat(other.value))} other=_b_.int.numerator(other) return fast_float(self.value*other)} if($B.$isinstance(other,float)){return fast_float(self.value*other.value)} return _b_.NotImplemented} float.__ne__=function(self,other){var res=float.__eq__(self,other) return res===_b_.NotImplemented ? res :! res} float.__neg__=function(self){return fast_float(-self.value)} float.__new__=function(cls,value){if(cls===undefined){$B.RAISE(_b_.TypeError,"float.__new__(): not enough arguments")}else if(! $B.$isinstance(cls,_b_.type)){$B.RAISE(_b_.TypeError,"float.__new__(X): X is not a type object")} return{ __class__:cls,value:float.$factory(value).value}} float.__pos__=function(self){return fast_float(+self.value)} float.__pow__=function(self,other){var other_int=$B.$isinstance(other,_b_.int) if(other_int ||$B.$isinstance(other,float)){if(! other_int){other=other.value} if(self.value==1){return fast_float(1)}else if(other==0){return fast_float(1)} if(isNaN(other)){return fast_float(Number.NaN)} if(isNaN(self.value)){return fast_float(Number.NaN)} if(self.value==-1 && ! isFinite(other)){ return fast_float(1)}else if(self.value==0 && isFinite(other)&& other < 0){$B.RAISE(_b_.ZeroDivisionError,"0.0 cannot be raised "+ "to a negative power")}else if(self.value==0 && isFinite(other)&& other >=0){ if(Number.isInteger(other)&& other % 2==1){return self} return fast_float(0)}else if(self.value==Number.NEGATIVE_INFINITY && ! isNaN(other)){ if(other % 2==-1){return fast_float(-0.0)}else if(other < 0){return fast_float(0)}else if(other % 2==1){return fast_float(Number.NEGATIVE_INFINITY)}else{return fast_float(Number.POSITIVE_INFINITY)}}else if(self.value==Number.POSITIVE_INFINITY && ! isNaN(other)){return other > 0 ? self :fast_float(0)} if(other==Number.NEGATIVE_INFINITY && ! isNaN(self.value)){ return Math.abs(self.value)< 1 ? fast_float(Number.POSITIVE_INFINITY): fast_float(0)}else if(other==Number.POSITIVE_INFINITY && ! isNaN(self.value)){ return Math.abs(self.value)< 1 ? fast_float(0): fast_float(Number.POSITIVE_INFINITY)} if(self.value < 0 && ! Number.isInteger(other)){return _b_.complex.__pow__($B.make_complex(self.value,0),fast_float(other))} return fast_float(Math.pow(self.value,other))} return _b_.NotImplemented} float.__repr__=function(self){$B.builtins_repr_check(float,arguments) self=self.value if(self==Infinity){return 'inf'}else if(self==-Infinity){return '-inf'}else if(isNaN(self)){return 'nan'}else if(self===0){if(1/self===-Infinity){return '-0.0'} return '0.0'} var res=self+"" if(res.search(/[.eE]/)==-1){res+=".0"} var split_e=res.split(/e/i) if(split_e.length==2){let mant=split_e[0],exp=split_e[1] if(exp.startsWith('-')){let exp_str=parseInt(exp.substr(1))+'' if(exp_str.length < 2){exp_str='0'+exp_str} return mant+'e-'+exp_str}} var x,y [x,y]=res.split('.') var sign='' if(x[0]=='-'){x=x.substr(1) sign='-'} if(x.length > 16){let exp=x.length-1,int_part=x[0],dec_part=x.substr(1)+y while(dec_part.endsWith("0")){dec_part=dec_part.substr(0,dec_part.length-1)} let mant=int_part if(dec_part.length > 0){mant+='.'+dec_part} return sign+mant+'e+'+exp}else if(x=="0"){let exp=0 while(exp < y.length && y.charAt(exp)=="0"){exp++} if(exp > 3){ let rest=y.substr(exp) exp=(exp+1).toString() while(rest.endsWith("0")){rest=rest.substr(0,res.length-1)} let mant=rest[0] if(rest.length > 1){mant+='.'+rest.substr(1)} if(exp.length==1){exp='0'+exp} return sign+mant+'e-'+exp}} return _b_.str.$factory(res)} float.__round__=function(){var $=$B.args('__round__',2,{self:null,ndigits:null},['self','ndigits'],arguments,{ndigits:_b_.None},null,null) return float.$round($.self,$.ndigits)} float.$round=function(x,ndigits){function overflow(){$B.RAISE(_b_.OverflowError,"cannot convert float infinity to integer")} var no_digits=ndigits===_b_.None if(isnan(x)){if(ndigits===_b_.None){$B.RAISE(_b_.ValueError,"cannot convert float NaN to integer")} return NAN}else if(isninf(x)){return ndigits===_b_.None ? overflow():NINF}else if(isinf(x)){return ndigits===_b_.None ? overflow():INF} x=float_value(x) ndigits=ndigits===_b_.None ? 0 :ndigits if(ndigits==0){var res=Math.round(x.value) if(Math.abs(x.value-res)==0.5){ if(res % 2){return res-1}} if(no_digits){ return res} return $B.fast_float(res)} if(ndigits.__class__===$B.long_int){ndigits=Number(ndigits.value)} var pow1,pow2,y,z; if(ndigits >=0){if(ndigits > 22){ pow1=10**(ndigits-22) pow2=1e22;}else{pow1=10**ndigits pow2=1.0;} y=(x.value*pow1)*pow2; if(!isFinite(y)){return x}}else{pow1=10**-ndigits; pow2=1.0; if(isFinite(pow1)){y=x.value/pow1}else{return ZERO}} z=Math.round(y); if(fabs(y-z).value==0.5){ z=2.0*Math.round(y/2);} if(ndigits >=0){z=(z/pow2)/pow1;}else{z*=pow1;} if(! isFinite(z)){$B.RAISE(_b_.OverflowError,"overflow occurred during round");} return fast_float(z);} float.__setattr__=function(self,attr,value){if(self.__class__===float){if(float[attr]===undefined){$B.RAISE_ATTRIBUTE_ERROR("'float' object has no attribute '"+ attr+"'",self,attr)}else{$B.RAISE_ATTRIBUTE_ERROR("'float' object attribute '"+ attr+"' is read-only",self,attr)}} self[attr]=value return _b_.None} float.__truediv__=function(self,other){if($B.$isinstance(other,_b_.int)){if(other.valueOf()==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")}else if($B.$isinstance(other,$B.long_int)){return float.$factory(self.value/Number(other.value))} return float.$factory(self.value/other)}else if($B.$isinstance(other,float)){if(other.value==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} return float.$factory(self.value/other.value)} return _b_.NotImplemented} var op_func_body= `var $B = __BRYTHON__, _b_ = __BRYTHON__.builtins if($B.$isinstance(other, _b_.int)){ if(typeof other == "boolean"){ return other ? $B.fast_float(self.value - 1) : self }else if(other.__class__ === $B.long_int){ return _b_.float.$factory(self.value - parseInt(other.value)) }else{ return $B.fast_float(self.value - other) } } if($B.$isinstance(other, _b_.float)){ return $B.fast_float(self.value - other.value) } return _b_.NotImplemented` var ops={"+":"add","-":"sub"} for(let op in ops){let body=op_func_body.replace(/-/gm,op) float[`__${ops[op]}__`]=Function('self','other',body)} var comp_func_body=` var $B = __BRYTHON__, _b_ = $B.builtins if($B.$isinstance(other, _b_.int)){ if(other.__class__ === $B.long_int){ return self.value > parseInt(other.value) } return self.value > other.valueOf()} if($B.$isinstance(other, _b_.float)){ return self.value > other.value} if($B.$isinstance(other, _b_.bool)) { return self.value > _b_.bool.__hash__(other)} var int_method = $B.$getattr(other, "__int__", null) if(int_method !== null){ var v = int_method() return _b_.int.__gt__(self.value, v)} var index_method = $B.$getattr(other, "__index__", null) if(index_method !== null){ var v = index_method() return _b_.int.__gt__(self.value, v)} // See if other has the opposite operator, eg <= for > var inv_op = $B.$getattr(other, "__le__", _b_.None) if(inv_op !== _b_.None){ return inv_op(self)} $B.RAISE(_b_.TypeError, "unorderable types: float() > " + $B.class_name(other) + "()") ` for(let op in $B.$comps){let body=comp_func_body.replace(/>/gm,op). replace(/__gt__/gm,`__${$B.$comps[op]}__`). replace(/__le__/,`__${$B.$inv_comps[op]}__`) float[`__${$B.$comps[op]}__`]=Function('self','other',body)} var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or","divmod"] for(var r_opname of r_opnames){if(float["__r"+r_opname+"__"]===undefined && float['__'+r_opname+'__']){float["__r"+r_opname+"__"]=(function(name){return function(self,other){var other_as_num=_b_.int.$to_js_number(other) if(other_as_num !==null){var other_as_float=$B.fast_float(other_as_num) return float["__"+name+"__"](other_as_float,self)} return _b_.NotImplemented}})(r_opname)}} function to_digits(s){ var arabic_digits="\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669",res="" for(var i=0;i < s.length;i++){var x=arabic_digits.indexOf(s[i]) if(x >-1){res+=x}else{res+=s[i]}} return res} const fast_float=$B.fast_float=function(value){return{__class__:_b_.float,value}} float.$factory=function(value){if(value===undefined){return fast_float(0)} $B.check_nb_args_no_kw('float',1,arguments) switch(value){case true: return fast_float(1) case false: return fast_float(0)} var original_value=value if(typeof value=="number"){return fast_float(value)} if(value.__class__===float){return value} if($B.$isinstance(value,_b_.memoryview)){value=_b_.memoryview.tobytes(value)} if($B.$isinstance(value,_b_.bytes)){try{value=$B.$getattr(value,"decode")("utf-8")}catch(err){$B.RAISE(_b_.ValueError,"could not convert string to float: "+ _b_.repr(original_value))}} if(typeof value=="string"){if(value.trim().length==0){$B.RAISE(_b_.ValueError,`could not convert string to float: ${_b_.repr(value)}`)} value=value.trim() switch(value.toLowerCase()){case "+inf": case "inf": case "+infinity": case "infinity": return fast_float(Number.POSITIVE_INFINITY) case "-inf": case "-infinity": return fast_float(Number.NEGATIVE_INFINITY) case "+nan": case "nan": return fast_float(Number.NaN) case "-nan": return fast_float(-Number.NaN) default: var parts=value.split('e') if(parts[1]){if(parts[1].startsWith('+')||parts[1].startsWith('-')){parts[1]=parts[1].substr(1)}} parts=parts[0].split('.').concat(parts.splice(1)) for(var part of parts){if(part.startsWith('_')||part.endsWith('_')){$B.RAISE(_b_.ValueError,'invalid float literal '+ value)}} if(value.indexOf('__')>-1){$B.RAISE(_b_.ValueError,'invalid float literal '+ value)} value=value.charAt(0)+value.substr(1).replace(/_/g,"") value=to_digits(value) if(isFinite(value)){return fast_float(parseFloat(value))}else{$B.RAISE(_b_.ValueError,"could not convert string to float: "+ _b_.repr(original_value))}}} let klass=$B.get_class(value),float_method=$B.$getattr(klass,'__float__',null) if(float_method===null){var index_method=$B.$getattr(klass,'__index__',null) if(index_method===null){$B.RAISE(_b_.TypeError,"float() argument must be a string or a "+ "real number, not '"+$B.class_name(value)+"'")} let index=$B.$call(index_method)(value),index_klass=$B.get_class(index) if(index_klass===_b_.int){return fast_float(index)}else if(index_klass===$B.long_int){return $B.long_int.__float__(index)}else if(index_klass.__mro__.indexOf(_b_.int)>-1){let msg=`${$B.class_name(value)}.__index__ returned `+ `non-int (type ${$B.class_name(index)}). The `+ 'ability to return an instance of a strict subclass'+ ' of int is deprecated, and may be removed in a '+ 'future version of Python.' $B.warn(_b_.DeprecationWarning,msg) return fast_float(index)} $B.RAISE(_b_.TypeError,'__index__ returned non-int'+ ` (type ${$B.class_name(index)})`)} let res=$B.$call(float_method)(value) klass=$B.get_class(res) if(klass !==_b_.float){if(klass.__mro__.indexOf(_b_.float)>-1){let msg=`${$B.class_name(value)}.__float__ returned `+ `non-float (type ${$B.class_name(res)}). The `+ 'ability to return an instance of a strict subclass'+ ' of float is deprecated, and may be removed in a '+ 'future version of Python.' $B.warn(_b_.DeprecationWarning,msg) return float.$factory(res.value)} $B.RAISE(_b_.TypeError,'__float__ returned non-float'+ ` (type ${$B.class_name(res)})`)} return res} $B.set_func_names(float,"builtins") float.fromhex=_b_.classmethod.$factory(float.fromhex) _b_.float=float $B.MAX_VALUE=fast_float(Number.MAX_VALUE) $B.MIN_VALUE=fast_float(2.2250738585072014e-308) const NINF=fast_float(Number.NEGATIVE_INFINITY),INF=fast_float(Number.POSITIVE_INFINITY),NAN=fast_float(Number.NaN),ZERO=fast_float(0)})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function $UnsupportedOpType(op,class1,class2){$B.RAISE(_b_.TypeError,"unsupported operand type(s) for "+ op+": '"+class1+"' and '"+class2+"'")} var complex={__class__:_b_.type,__dir__:_b_.object.__dir__,__qualname__:'complex',$is_class:true,$native:true,$descriptors:{real:true,imag:true}} complex.__abs__=function(self){var _rf=isFinite(self.$real.value),_if=isFinite(self.$imag.value) if((_rf && isNaN(self.$imag.value))||(_if && isNaN(self.$real.value))|| (isNaN(self.$imag.value)&& isNaN(self.$real.value))){return $B.fast_float(NaN)} if(! _rf ||! _if){return $B.fast_float(Infinity)} var mag=Math.sqrt(Math.pow(self.$real.value,2)+ Math.pow(self.$imag.value,2)) if(!isFinite(mag)&& _rf && _if){ $B.RAISE(_b_.OverflowError,"absolute value too large")} return $B.fast_float(mag)} complex.__add__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value+other.$real.value,self.$imag.value+other.$imag.value)} if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other) return make_complex( $B.rich_op('__add__',self.$real,other).value,self.$imag.value)} if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value+other.value,self.$imag.value)} return _b_.NotImplemented} complex.__bool__=function(self){return(! $B.rich_comp('__eq__',self.$real,0))|| ! $B.rich_comp('__eq__',self.$imag,0)} complex.__complex__=function(self){ if(self.__class__===complex){return self} return $B.make_complex(self.$real,self.$imag)} complex.__eq__=function(self,other){if($B.$isinstance(other,complex)){return self.$real.value==other.$real.value && self.$imag.value==other.$imag.value} if($B.$isinstance(other,_b_.int)){if(self.$imag.value !=0){return false} return self.$real.value==other.valueOf()} if($B.$isinstance(other,_b_.float)){if(! $B.rich_comp('__eq__',0,self.$imag)){return false} return self.$real.value==other.value} return _b_.NotImplemented} const max_precision=2**31-4 complex.__format__=function(self,format_spec){if(format_spec.length==0){return _b_.str.$factory(self)} var fmt=new $B.parse_format_spec(format_spec,self),type=fmt.conversion_type var skip_re,add_parens if(type===undefined ||'eEfFgGn'.indexOf(type)>-1){if(fmt.precision > max_precision){$B.RAISE(_b_.ValueError,'precision too big')} if(fmt.fill_char=='0'){$B.RAISE(_b_.ValueError,"Zero padding is not allowed in complex format specifier")} if(fmt.align=='='){$B.RAISE(_b_.ValueError,"'=' alignment flag is not allowed in complex format "+ "specifier")} var re=self.$real.value,precision=parseInt(fmt.precision,10) if(type===undefined){type='r' if(re==0 && Object.is(re,0)){skip_re=1}else{add_parens=1}}else if(type=='n'){type='g'} if(precision < 0){precision=6}else if(type=='r'){type='g'} var format=$B.clone(fmt) format.conversion_type=type format.precision=precision var res='' if(! skip_re){res+=_b_.float.$format(self.$real,format) if(self.$imag.value >=0){res+='+'}} var formatted_im=_b_.float.$format(self.$imag,format) var pos=-1,last_num for(var char of formatted_im){pos++ if(char.match(/\d/)){last_num=pos}} formatted_im=formatted_im.substr(0,last_num+1)+'j'+ formatted_im.substr(last_num+1) res+=formatted_im if(add_parens){res='('+res+')'} return res} $B.RAISE(_b_.ValueError,`invalid type for complex: ${type}`)} complex.$getnewargs=function(self){return $B.fast_tuple([self.$real,self.$imag])} complex.__getnewargs__=function(){return complex.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} complex.__hash__=function(self){ return $B.$hash(self.$real)+$B.$hash(self.$imag)*1000003} complex.__init__=function(){return _b_.None} complex.__invert__=function(self){return ~self} complex.__mro__=[_b_.object] complex.__mul__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value*other.$real.value- self.$imag.value*other.$imag.value,self.$imag.value*other.$real.value+ self.$real.value*other.$imag.value)}else if($B.$isinstance(other,_b_.int)){return make_complex(self.$real.value*other.valueOf(),self.$imag.value*other.valueOf())}else if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value*other.value,self.$imag.value*other.value)}else if($B.$isinstance(other,_b_.bool)){if(other.valueOf()){return self} return make_complex(0,0)} return _b_.NotImplemented} complex.__ne__=function(self,other){var res=complex.__eq__(self,other) return res===_b_.NotImplemented ? res :! res} complex.__neg__=function(self){return make_complex(-self.$real.value,-self.$imag.value)} complex.__new__=function(cls){if(cls===undefined){$B.RAISE(_b_.TypeError,'complex.__new__(): not enough arguments')} var res,missing={},$=$B.args("complex",3,{cls:null,real:null,imag:null},["cls","real","imag"],arguments,{real:0,imag:missing},null,null) cls=$.cls var first=$.real,second=$.imag if(typeof first=="string"){if(second !==missing){$B.RAISE(_b_.TypeError,"complex() can't take second arg "+ "if first is a string")}else{var arg=first first=first.trim() if(first.startsWith("(")&& first.endsWith(")")){first=first.substr(1) first=first.substr(0,first.length-1)} var complex_re=/^\s*([+-]*[0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)([+-]?)([0-9_]*\.?[0-9_]*(e[+-]*[0-9_]*)?)(j?)\s*$/i var parts=complex_re.exec(first) function to_num(s){var res=parseFloat(s.charAt(0)+s.substr(1).replace(/_/g,"")) if(isNaN(res)){$B.RAISE(_b_.ValueError,"could not convert string "+ "to complex: '"+arg+"'")} return res} if(parts===null){$B.RAISE(_b_.ValueError,"complex() arg is a malformed string")} if(parts[_real]&& parts[_imag].startsWith('.')&& parts[_sign]==''){$B.RAISE(_b_.ValueError,'complex() arg is a malformed string')}else if(parts[_real]=="." ||parts[_imag]=="." || parts[_real]==".e" ||parts[_imag]==".e" || parts[_real]=="e" ||parts[_imag]=="e"){$B.RAISE(_b_.ValueError,"complex() arg is a malformed string")}else if(parts[_j]!=""){if(parts[_sign]==""){first=0 if(parts[_real]=="+" ||parts[_real]==""){second=1}else if(parts[_real]=='-'){second=-1}else{second=to_num(parts[_real])}}else{first=to_num(parts[_real]) second=parts[_imag]=="" ? 1 :to_num(parts[_imag]) second=parts[_sign]=="-" ?-second :second}}else{if(parts[_sign]&& parts[_imag]==''){$B.RAISE(_b_.ValueError,'complex() arg is a malformed string')} first=to_num(parts[_real]) second=0} res=make_complex(first,second) res.__class__=cls res.__dict__=$B.empty_dict() return res}} if(first.__class__===complex && cls===complex && second===missing){return first} var arg1=_convert(first),r,i if(arg1===null){$B.RAISE(_b_.TypeError,"complex() first argument must be a "+ `string or a number, not '${$B.class_name(first)}'`)} if(typeof second=="string"){$B.RAISE(_b_.TypeError,"complex() second arg can't be a string")} var arg2=_convert(second===missing ? 0 :second) if(arg2===null){$B.RAISE(_b_.TypeError,"complex() second argument must be a "+ `number, not '${$B.class_name(second)}'`)} if(arg1.method=='__complex__'){if(arg2.method=='__complex__'){r=$B.rich_op('__sub__',arg1.result.$real,arg2.result.$imag) i=$B.rich_op('__add__',arg1.result.$imag,arg2.result.$real)}else{r=arg1.result.$real i=$B.rich_op('__add__',arg1.result.$imag,arg2.result)}}else{if(arg2.method=='__complex__'){r=$B.rich_op('__sub__',arg1.result,arg2.result.$imag) i=arg2.result.$real}else{r=arg1.result i=arg2.result}} res=make_complex(r,i) res.__class__=cls res.__dict__=$B.empty_dict() return res} complex.__pos__=function(self){return self} function complex2expo(cx){var norm=Math.sqrt((cx.$real.value*cx.$real.value)+ (cx.$imag.value*cx.$imag.value)),sin=cx.$imag.value/norm,cos=cx.$real.value/norm,angle if(cos==0){angle=sin==1 ? Math.PI/2 :3*Math.PI/2}else if(sin==0){angle=cos==1 ? 0 :Math.PI}else{angle=Math.atan(sin/cos)} return{norm:norm,angle:angle}} function c_powi(x,n){if(n > 0){return c_powu(x,n)}else{return c_quot(c_1,c_powu(x,-n))}} function c_powu(x,n){var mask=1,r=c_1,p=x while(mask > 0 && n >=mask){if(n & mask){r=c_prod(r,p)} mask <<=1 p=c_prod(p,p)} return r} function c_prod(a,b){return make_complex( a.$real.value*b.$real.value-a.$imag.value*b.$imag.value,a.$real.value*b.$imag.value+a.$imag.value*b.$real.value)} function c_quot(a,b){var abs_breal=Math.abs(b.$real.value),abs_bimag=Math.abs(b.$imag.value) if($B.rich_comp('__ge__',abs_breal,abs_bimag)){ if(abs_breal==0.0){$B.RAISE(_b_.ZeroDivisionError,)}else{let ratio=b.$imag.value/b.$real.value,denom=b.$real.value+b.$imag.value*ratio return make_complex((a.$real.value+a.$imag.value*ratio)/denom,(a.$imag.value-a.$real.value*ratio)/denom)}}else if(abs_bimag >=abs_breal){ let ratio=b.$real.value/b.$imag.value,denom=b.$real.value*ratio+b.$imag.value; if(b.$imag.value==0.0){$B.RAISE(_b_.ZeroDivisionError,)} return make_complex( (a.$real.value*ratio+a.$imag.value)/denom,(a.$imag.value*ratio-a.$real.value)/denom)}else{ return $B.make_complex('nan','nan')}} complex.__pow__=function(self,other,mod){ if(mod !==undefined && mod !==_b_.None){$B.RAISE(_b_.ValueError,'complex modulo')} if($B.rich_comp('__eq__',other,1)){var funcs=_b_.float.$funcs if(funcs.isinf(self.$real)||funcs.isninf(self.$real)|| funcs.isinf(self.$imag)||funcs.isninf(self.$imag)){$B.RAISE(_b_.OverflowError,'complex exponentiation')} return self} var small_int=null if($B.$isinstance(other,_b_.int)&& _b_.abs(other)< 100){small_int=other}else if($B.$isinstance(other,_b_.float)&& Number.isInteger(other.value)&& Math.abs(other.value < 100)){small_int=other.value}else if($B.$isinstance(other,complex)&& other.$imag.value==0 && Number.isInteger(other.$real.value)&& Math.abs(other.$real.value)< 100){small_int=other.$real.value} if(small_int !==null){return c_powi(self,small_int)} if($B.$isinstance(other,_b_.float)){other=_b_.float.$to_js_number(other)} if(self.$real.value==0 && self.$imag.value==0){if($B.$isinstance(other,complex)&& (other.$imag.value !=0 ||other.$real.value < 0)){$B.RAISE(_b_.ZeroDivisionError,'0.0 to a negative or complex power')} return $B.make_complex(0,0)} var exp=complex2expo(self),angle=exp.angle,res=Math.pow(exp.norm,other) if($B.$isinstance(other,_b_.int)){return make_complex(res*Math.cos(angle*other),res*Math.sin(angle*other))}else if($B.$isinstance(other,_b_.float)){return make_complex(res*Math.cos(angle*other.value),res*Math.sin(angle*other.value))}else if($B.$isinstance(other,complex)){ var x=other.$real.value,y=other.$imag.value var pw=Math.pow(exp.norm,x)*Math.pow(Math.E,-y*angle),theta=y*Math.log(exp.norm)-x*angle if(pw==Number.POSITIVE_INFINITY ||pw===Number.NEGATIVE_INFINITY){$B.RAISE(_b_.OverflowError,'complex exponentiation')} return make_complex(pw*Math.cos(theta),pw*Math.sin(theta))}else{$B.RAISE(_b_.TypeError,"unsupported operand type(s) "+ "for ** or pow(): 'complex' and '"+ $B.class_name(other)+"'")}} complex.__radd__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other ? 1 :0} if($B.$isinstance(other,_b_.int)){return make_complex(other+self.$real.value,self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value+self.$real.value,self.$imag.value)} return _b_.NotImplemented} complex.__repr__=function(self){$B.builtins_repr_check(complex,arguments) var real=Number.isInteger(self.$real.value)? self.$real.value+'' : _b_.str.$factory(self.$real),imag=Number.isInteger(self.$imag.value)? self.$imag.value+'' : _b_.str.$factory(self.$imag) if(imag.endsWith('.0')){imag=imag.substr(0,imag.length-2)} if(Object.is(self.$imag.value,-0)){imag="-0"} var sign=imag.startsWith('-')? '' :'+' if(self.$real.value==0){if(Object.is(self.$real.value,-0)){return "(-0"+sign+imag+"j)"}else{return imag+"j"}} if(self.$imag.value > 0 ||isNaN(self.$imag.value)){return "("+real+"+"+imag+"j)"} if(self.$imag.value==0){if(1/self.$imag.value < 0){return "("+real+"-0j)"} return "("+real+"+0j)"} return "("+real+sign+imag+"j)"} complex.__rmul__=function(self,other){if($B.$isinstance(other,_b_.bool)){other=other ? 1 :0} if($B.$isinstance(other,_b_.int)){return make_complex(other*self.$real.value,other*self.$imag.value)}else if($B.$isinstance(other,_b_.float)){return make_complex(other.value*self.$real.value,other.value*self.$imag.value)} return _b_.NotImplemented} complex.__sub__=function(self,other){if($B.$isinstance(other,complex)){return make_complex(self.$real.value-other.$real.value,self.$imag.value-other.$imag.value)} if($B.$isinstance(other,_b_.int)){other=_b_.int.numerator(other) return make_complex(self.$real.value-other.valueOf(),self.$imag.value)} if($B.$isinstance(other,_b_.float)){return make_complex(self.$real.value-other.value,self.$imag.value)} return _b_.NotImplemented} complex.__truediv__=function(self,other){if($B.$isinstance(other,complex)){if(other.$real.value==0 && other.$imag.value==0){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} var _num=self.$real.value*other.$real.value+ self.$imag.value*other.$imag.value,_div=other.$real.value*other.$real.value+ other.$imag.value*other.$imag.value var _num2=self.$imag.value*other.$real.value- self.$real.value*other.$imag.value return make_complex($B.fast_float(_num/_div),$B.fast_float(_num2/_div))} if($B.$isinstance(other,_b_.int)){if(! other.valueOf()){$B.RAISE(_b_.ZeroDivisionError,'division by zero')} return complex.__truediv__(self,complex.$factory(other.valueOf()))} if($B.$isinstance(other,_b_.float)){if(! other.value){$B.RAISE(_b_.ZeroDivisionError,"division by zero")} return complex.$factory(_b_.float.__truediv__(self.$real,other),_b_.float.__truediv__(self.$imag,other))} return _b_.NotImplemented} complex.conjugate=function(self){return make_complex(self.$real.value,-self.$imag.value)} complex.__ior__=complex.__or__ var r_opnames=["add","sub","mul","truediv","floordiv","mod","pow","lshift","rshift","and","xor","or"] for(var r_opname of r_opnames){if(complex["__r"+r_opname+"__"]===undefined && complex['__'+r_opname+'__']){complex["__r"+r_opname+"__"]=(function(name){return function(self,other){if($B.$isinstance(other,_b_.int)){other=make_complex(other,0) return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,_b_.float)){other=make_complex(other.value,0) return complex["__"+name+"__"](other,self)}else if($B.$isinstance(other,complex)){return complex["__"+name+"__"](other,self)} return _b_.NotImplemented}})(r_opname)}} var comp_func_body=` var _b_ = __BRYTHON__.builtins if(other === undefined || other == _b_.None){ return _b_.NotImplemented } $B.RAISE(_b_.TypeError, "no ordering relation " + "is defined for complex numbers")` for(var $op in $B.$comps){complex['__'+$B.$comps[$op]+'__']=Function('self','other',comp_func_body.replace(/>/gm,$op))} complex.real=function(self){return self.$real} complex.real.setter=function(self,value){$B.RAISE_ATTRIBUTE_ERROR("readonly attribute",self,'real')} complex.imag=function(self){return self.$imag} complex.imag.setter=function(){$B.RAISE_ATTRIBUTE_ERROR("readonly attribute",self,'imag')} var _real=1,_real_mantissa=2,_sign=3,_imag=4,_imag_mantissa=5,_j=6 var expected_class={"__complex__":complex,"__float__":_b_.float,"__index__":_b_.int} function _convert(obj){ var klass=obj.__class__ ||$B.get_class(obj) for(var method_name in expected_class){var missing={},method=$B.$getattr(klass,method_name,missing) if(method !==missing){var res=method(obj) if(!$B.$isinstance(res,expected_class[method_name])){$B.RAISE(_b_.TypeError,method_name+"returned non-"+ expected_class[method_name].__name__+ "(type "+$B.get_class(res)+")")} if(method_name=='__index__' && $B.rich_comp('__gt__',res,__BRYTHON__.MAX_VALUE)){$B.RAISE(_b_.OverflowError,'int too large to convert to float')} if(method_name=='__complex__' && res.__class__ !==complex){$B.warn(_b_.DeprecationWarning,"__complex__ returned "+ `non-complex (type ${$B.class_name(res)}). `+ "The ability to return an instance of a strict subclass "+ "of complex is deprecated, and may be removed in a future "+ "version of Python.")} return{result:res,method:method_name}}} return null} var make_complex=$B.make_complex=function(real,imag){return{ __class__:complex,$real:_b_.float.$factory(real),$imag:_b_.float.$factory(imag)}} var c_1=make_complex(1,0) complex.$factory=function(){return complex.__new__(complex,...arguments)} $B.set_func_names(complex,"builtins") _b_.complex=complex})(__BRYTHON__); ; (function($B){ var _b_=$B.builtins var set_ops=["eq","le","lt","ge","gt","sub","rsub","and","rand","or","ror","xor","rxor"] function is_sublist(t1,t2){ for(var i=0,ilen=t1.length;i < ilen;i++){var x=t1[i],flag=false for(var j=0,jlen=t2.length;j < jlen;j++){if($B.rich_comp("__eq__",x,t2[j])){t2.splice(j,1) flag=true break}} if(! flag){return false}} return true} const dict_view_op={__eq__:function(t1,t2){return t1.length==t2.length && is_sublist(t1,t2)},__ne__:function(t1,t2){return ! dict_view_op.__eq__(t1,t2)},__lt__:function(t1,t2){return t1.length < t2.length && is_sublist(t1,t2)},__gt__:function(t1,t2){return dict_view_op.__lt__(t2,t1)},__le__:function(t1,t2){return t1.length <=t2.length && is_sublist(t1,t2)},__ge__:function(t1,t2){return dict_view_op.__le__(t2,t1)},__and__:function(t1,t2){var items=[] for(var i=0,ilen=t1.length;i < ilen;i++){var x=t1[i] for(var j=0,jlen=t2.length;j < jlen;j++){if($B.rich_comp("__eq__",x,t2[j])){t2.splice(j,1) items.push(x) break}}} return $B.$list(items)},__or__:function(t1,t2){var items=t1 for(var j=0,jlen=t2.length;j < jlen;j++){var y=t2[j],flag=false for(var i=0,ilen=t1.length;i < ilen;i++){if($B.rich_comp("__eq__",y,t1[i])){t2.splice(j,1) flag=true break}} if(! flag){items.push(y)}} return items}} function make_view_comparison_methods(klass){for(var i=0,len=set_ops.length;i < len;i++){var op="__"+set_ops[i]+"__" klass[op]=(function(op){return function(self,other){ if(self.__class__.__name__=='dict_keys' || (self.__class__.__name__=='dict_items' && dict.$set_like(self.dict))){return _b_.set[op](_b_.set.$factory(self),_b_.set.$factory(other))}else{ if(other.__class__ !==klass){return false} var other_items=_b_.list.$factory(other) return dict_view_op[op](self.items,other_items)}}})(op)}} $B.str_dict=function(){} var dict={__class__:_b_.type,__mro__:[_b_.object],__qualname__:'dict',$is_class:true,$native:true,$match_mapping_pattern:true } dict.$to_obj=function(d){ var res={} for(var entry of dict.$iter_items(d)){res[entry.key]=entry.value} return res} dict.$iter_keys_check=function*(d){for(var entry of dict.$iter_items(d)){yield entry.key}} dict.$iter_values_check=function*(d){for(var entry of dict.$iter_items(d)){yield entry.value}} dict.$set_like=function(self){ for(var v of self._values){if(v===undefined){continue}else if(typeof v=='string' || typeof v=='number' || typeof v=='boolean'){continue}else if([_b_.tuple,_b_.float,_b_.complex].indexOf(v.__class__)>-1){continue}else if(! _b_.hasattr(v.__class__,'__hash__')){return false}} return true} dict.$iter_items=function*(d){if(d.$all_str){for(let key in d.$strings){if(key !='$dict_strings'){yield{key,value:d.$strings[key]}}}} if(d.$jsobj){for(let key in d.$jsobj){if(!d.$exclude ||! d.$exclude(key)){yield{key,value:d.$jsobj[key]}}}}else{var version=d.$version for(var i=0,len=d._keys.length;i < len;i++){if(d._keys[i]!==undefined){yield{key:d._keys[i],value:d._values[i],hash:d._hashes[i]} if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}} if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}} dict.$iter_items_check=function*(d){if(d.$jsobj){for(var key in d.$jsobj){yield[key,d.$jsobj[key]]}}else{var version=d.$version for(var i=0,len=d._keys.length;i < len;i++){if(d._keys[i]!==undefined){yield[d._keys[i],d._values[i]] if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}} if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}} var $copy_dict=function(left,right){ right.$version=right.$version ||0 var right_version=right.$version if(right.$all_str){if(left.$all_str){for(let key in right.$strings){left.$strings[key]=right.$strings[key]}}else{for(let key in right.$strings){dict.$setitem(left,key,right.$strings[key])}}}else{for(var entry of dict.$iter_items(right)){dict.$setitem(left,entry.key,entry.value,entry.hash) if(right.$version !=right_version){$B.RAISE(_b_.RuntimeError,"dict mutated during update")}}}} dict.__bool__=function(){var $=$B.args("__bool__",1,{self:null},["self"],arguments,{},null,null) return dict.__len__($.self)> 0} dict.__class_getitem__=$B.$class_getitem dict.$lookup_by_key=function(d,key,hash){hash=hash===undefined ? _b_.hash(key):hash var indices=d.table[hash],index if(indices !==undefined){for(var i=0,len=indices.length;i < len;i++){index=indices[i] if(d._keys[index]===undefined){d.table[hash].splice(i,1) if(d.table[hash].length==0){delete d.table[hash] return{found:false,hash}} continue} if($B.is_or_equals(d._keys[index],key)){return{found:true,key:d._keys[index],value:d._values[index],hash,rank:i,index}}}} return{found:false,hash}} dict.__contains__=function(){var $=$B.args("__contains__",2,{self:null,key:null},["self","key"],arguments,{},null,null),self=$.self,key=$.key return _b_.dict.$contains(self,key)} dict.$contains=function(self,key){if(self.$all_str){if(typeof key=='string'){return self.$strings.hasOwnProperty(key)} var hash=$B.$getattr($B.get_class(key),'__hash__') if(hash===_b_.object.__hash__){return false} convert_all_str(self)} if(self.$jsobj){return self.$jsobj[key]!==undefined} return dict.$lookup_by_key(self,key).found} dict.__delitem__=function(){var $=$B.args("__eq__",2,{self:null,key:null},["self","key"],arguments,{},null,null),self=$.self,key=$.key if(self[$B.JSOBJ]){delete self[$B.JSOBJ][key]} if(self.$all_str){if(typeof key=='string'){if(self.$strings.hasOwnProperty(key)){dict.$delete_string(self,key) return _b_.None}else{$B.RAISE(_b_.KeyError,key)}} if(! dict.__contains__(self,key)){$B.RAISE(_b_.KeyError,_b_.str.$factory(key))}} if(self.$jsobj){if(self.$jsobj[key]===undefined){$B.RAISE(_b_.KeyError,key)} delete self.$jsobj[key] return _b_.None} var lookup=dict.$lookup_by_key(self,key) if(lookup.found){self.table[lookup.hash].splice(lookup.rank,1) if(self.table[lookup.hash].length==0){delete self.table[lookup.hash]} delete self._values[lookup.index] delete self._keys[lookup.index] delete self._hashes[lookup.index] self.$version++ return _b_.None} $B.RAISE(_b_.KeyError,_b_.str.$factory(key))} dict.__eq__=function(){var $=$B.args("__eq__",2,{self:null,other:null},["self","other"],arguments,{},null,null),self=$.self,other=$.other return dict.$eq(self,other)} dict.$eq=function(self,other){if(! $B.$isinstance(other,dict)){return _b_.NotImplemented} if(self.$all_str && other.$all_str){if(dict.__len__(self)!==dict.__len__(other)){return false} for(let k in self.$strings){if(! other.$strings.hasOwnProperty(k)){return false} if(! $B.is_or_equals(self.$strings[k],other.$strings[k])){return false}} return true} if(self.$jsobj && other.$jsobj){if(dict.__len__(self)!==dict.__len__(other)){return false} for(var k in self.$jsobj){if(! other.$jsobj.hasOwnProperty(k)){return false} if(! $B.is_or_equals(self.$jsobj[k],other.$jsobj[k])){return false}} return true} if(self.$all_str){let d=dict.copy(self) convert_all_str(d) return dict.$eq(d,other)} if(other.$all_str){let d=dict.copy(other) convert_all_str(d) return dict.$eq(self,d)} if(self.$jsobj){return dict.$eq(jsobj2dict(self.$jsobj),other)} if(other.$jsobj){return dict.$eq(self,jsobj2dict(other.$jsobj))} if(dict.__len__(self)!=dict.__len__(other)){return false} for(var hash in self.table){var self_pairs=[] for(let index of self.table[hash]){self_pairs.push([self._keys[index],self._values[index]])} var other_pairs=[] if(other.table[hash]!==undefined){for(let index of other.table[hash]){other_pairs.push([other._keys[index],other._values[index]])}} for(let self_pair of self_pairs){let flag=false,key=self_pair[0],value=self_pair[1] for(let other_pair of other_pairs){if($B.is_or_equals(key,other_pair[0])&& $B.is_or_equals(value,other_pair[1])){flag=true break}} if(! flag){return false}}} return true} dict.__getitem__=function(){var $=$B.args("__getitem__",2,{self:null,arg:null},["self","arg"],arguments,{},null,null),self=$.self,arg=$.arg return dict.$getitem(self,arg)} dict.$contains_string=function(self,key){ if(self.$all_str){return self.$strings.hasOwnProperty(key)} if(self.$jsobj && self.$jsobj.hasOwnProperty(key)){return true} if(self.table && self.table[_b_.hash(key)]!==undefined){return true} return false} dict.$delete_string=function(self,key){ if(self.$all_str){var ix=self.$strings[key] if(ix !==undefined){delete self.$strings[key]}} if(self.$jsobj){delete self.$jsobj[key]} if(self.table){delete self.table[_b_.hash(key)]}} dict.$missing={} dict.$get_string=function(self,key,_default){ if(self.$all_str && self.$strings.hasOwnProperty(key)){return self.$strings[key]} if(self.$jsobj && self.$jsobj.hasOwnProperty(key)){return self.$jsobj[key]} if(self.table && dict.__len__(self)){var indices=self.table[_b_.hash(key)] if(indices !==undefined){return self._values[indices[0]]}} return _default ?? _b_.dict.$missing} dict.$getitem_string=function(self,key){ if(self.$all_str && self.$strings.hasOwnProperty(key)){return self.$strings[key]} if(self.$jsobj && self.$jsobj.hasOwnProperty(key)){return self.$jsobj[key]} if(self.table){var indices=self.table[_b_.hash(key)] if(indices !==undefined){return self._values[indices[0]]}} $B.RAISE(_b_.KeyError,key)} dict.$keys_string=function(self){ var res=[] if(self.$all_str){return Object.keys(self.$strings)} if(self.$jsobj){res=res.concat(Object.keys(self.$jsobj))} if(self.table){res=res.concat(self._keys.filter((x)=> x !==undefined))} return res} dict.$setitem_string=function(self,key,value){ if(self.$all_str){self.$strings[key]=value return _b_.None}else{var h=_b_.hash(key),indices=self.table[h] if(indices !==undefined){self._values[indices[0]]=value return _b_.None}} var index=self._keys.length self.$strings[key]=index self._keys.push(key) self._values.push(value) self.$version++ return _b_.None} dict.$getitem=function(self,key,ignore_missing){ if(self.$all_str){if(typeof key=='string'){if(self.$strings.hasOwnProperty(key)){return self.$strings[key]}}else{var hash_method=$B.$getattr($B.get_class(key),'__hash__') if(hash_method !==_b_.object.__hash__){convert_all_str(self) let lookup=dict.$lookup_by_key(self,key) if(lookup.found){return lookup.value}}}}else if(self.$jsobj){if(self.$exclude && self.$exclude(key)){$B.RAISE(_b_.KeyError,key)} if(self.$jsobj.hasOwnProperty(key)){return self.$jsobj[key]} if(! self.table){$B.RAISE(_b_.KeyError,key)}}else{let lookup=dict.$lookup_by_key(self,key) if(lookup.found){return lookup.value}} if(! ignore_missing){if(self.__class__ !==dict && ! ignore_missing){try{var missing_method=$B.$getattr(self.__class__,"__missing__",_b_.None)}catch(err){console.log(err)} if(missing_method !==_b_.None){return missing_method(self,key)}}} $B.RAISE(_b_.KeyError,key)} dict.__hash__=_b_.None function init_from_list(self,args){var i=0 for(var item of args){if(item.length !=2){$B.RAISE(_b_.ValueError,"dictionary "+ `update sequence element #${i} has length ${item.length}; 2 is required`)} dict.$setitem(self,item[0],item[1]) i++}} dict.$set_string_no_duplicate=function(d,keys,string,value){if(typeof string !=='string'){$B.RAISE(_b_.TypeError,'keywords must be strings')} if(keys.has(string)){$B.RAISE(_b_.TypeError,'dict() got multiple values for keyword '+ `argument '${string}'`)} d.$strings[string]=value keys.add(string)} function add_mapping(d,obj){for(var entry of _b_.dict.$iter_items(obj)){dict.$setitem(d,entry.key,entry.value,entry.hash)}} function add_iterable(d,js_iterable){var i=0 for(var entry of js_iterable){var items=Array.from($B.make_js_iterator(entry)) if(items.length !==2){$B.RAISE(_b_.ValueError,"dictionary "+ `update sequence element #${i} has length ${items.length}; 2 is required`)} dict.$setitem(d,items[0],items[1]) i++}} dict.__init__=function(self,first,second){if(first===undefined){return _b_.None} if(second===undefined){ if((! first.$kw)&& $B.$isinstance(first,$B.JSObj)){for(let key in first){dict.$setitem(self,key,first[key])} return _b_.None}else if(first.$kw){var keys=new Set() for(let item of first.$kw){if($B.$isinstance(item,dict)){for(let subitem of dict.$iter_items(item)){dict.$set_string_no_duplicate(self,keys,subitem.key,subitem.value)}}else{for(let key in item){dict.$set_string_no_duplicate(self,keys,key,item[key])}}} return _b_.None}else if(first[Symbol.iterator]){init_from_list(self,first) return _b_.None}else if(first.__class__===$B.generator){init_from_list(self,first.js_gen) return _b_.None}} var $=$B.args("dict",1,{self:null},["self"],arguments,{},"first","second") var args=$.first if(args.length > 1){if($B._experimental_dict){console.log('try dict(*args)') for(var arg of args){if(_b_.isinstance(arg,_b_.dict)){add_mapping(self,arg)}else{try{var js_iterable=$B.make_js_iterator(arg)}catch(err){console.log(arg) console.log(err) $B.RAISE(_b_.TypeError,'expected mapping or '+ `iterable, got ${$B.class_name(arg)}`)} add_iterable(self,js_iterable)}}}else{$B.RAISE(_b_.TypeError,"dict expected at most 1 argument"+ `, got ${args.length}`)}}else if(args.length==1){args=args[0] if(args.__class__===dict){for(let entry of dict.$iter_items(args)){dict.$setitem(self,entry.key,entry.value,entry.hash)}}else{var keys=$B.$getattr(args,"keys",null) if(keys !==null){var gi=$B.$getattr(args,"__getitem__",null) if(gi !==null){ gi=$B.$call(gi) let kiter=_b_.iter($B.$call(keys)()) while(true){try{let key=_b_.next(kiter),value=gi(key) dict.__setitem__(self,key,value)}catch(err){if(err.__class__===_b_.StopIteration){break} throw err}}}}else{if(! Array.isArray(args)){args=_b_.list.$factory(args)} init_from_list(self,args)}}} for(let item of _b_.dict.$iter_items($.second)){dict.$setitem(self,item.key,item.value)} return _b_.None} dict.__iter__=function(self){return _b_.iter(dict.keys(self))} dict.__ior__=function(self,other){ dict.update(self,other) return self} dict.__len__=function(self){var _count=0 if(self.$all_str){return Object.keys(self.$strings).length} if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!="$" && ((! self.$exclude)||! self.$exclude(attr))){_count++}} return _count} for(var d of self._keys){if(d !==undefined){_count++}} return _count} dict.__ne__=function(self,other){var res=dict.__eq__(self,other) return res===_b_.NotImplemented ? res :! res} dict.__new__=function(cls){if(cls===undefined){$B.RAISE(_b_.TypeError,"int.__new__(): not enough arguments")} var instance=$B.empty_dict() instance.__class__=cls if(cls !==dict){instance.__dict__=$B.empty_dict()} return instance} dict.__or__=function(self,other){ if(! $B.$isinstance(other,dict)){return _b_.NotImplemented} var res=dict.copy(self) dict.update(res,other) return res} dict.__repr__=function(self){$B.builtins_repr_check(dict,arguments) if(self.$jsobj){ return dict.__repr__(jsobj2dict(self.$jsobj,self.$exclude))} if($B.repr.enter(self)){return "{...}"} let res=[] for(let entry of dict.$iter_items(self)){res.push(_b_.repr(entry.key)+": "+_b_.repr(entry.value))} $B.repr.leave(self) return "{"+res.join(", ")+"}"} dict.$iter_items_reversed=function*(d){var version=d.$version if(d.$all_str){for(var item of Object.entries(d.$strings).reverse()){yield $B.fast_tuple(item) if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}}else{for(var i=d._keys.length-1;i >=0;i--){var key=d._keys[i] if(key !==undefined){yield $B.fast_tuple([key,d._values[i]]) if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}}}} if(d.$version !==version){$B.RAISE(_b_.RuntimeError,'changed in iteration')}} dict.$iter_keys_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[0]}} dict.$iter_values_reversed=function*(d){for(var entry of dict.$iter_items_reversed(d)){yield entry[1]}} function make_reverse_iterator(name,iter_func){ var klass=$B.make_class(name,function(d){return{ __class__:klass,d,iter:iter_func(d),make_iter:function(){return iter_func(d)}}} ) klass.__iter__=function(self){self[Symbol.iterator]=self.make_iter return self} klass.__next__=function(self){var res=self.iter.next() if(res.done){$B.RAISE(_b_.StopIteration,'')} return res.value} klass.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])} $B.set_func_names(klass,'builtins') return klass} const dict_reversekeyiterator=make_reverse_iterator( 'dict_reversekeyiterator',dict.$iter_keys_reversed) dict.__reversed__=function(self){return dict_reversekeyiterator.$factory(self)} dict.__ror__=function(self,other){ if(! $B.$isinstance(other,dict)){return _b_.NotImplemented} var res=dict.copy(other) dict.update(res,self) return res} dict.__setitem__=function(){var $=$B.args("__setitem__",3,{self:null,key:null,value:null},["self","key","value"],arguments,{},null,null) return dict.$setitem($.self,$.key,$.value)} function convert_all_str(d){ d.$all_str=false for(var key in d.$strings){dict.$setitem(d,key,d.$strings[key])}} dict.$setitem=function(self,key,value,$hash,from_setdefault){ if(self[$B.JSOBJ]){ value=$B.pyobj2jsobj(value) self[$B.JSOBJ][key]=value} if(self.$all_str){if(typeof key=='string'){var int=parseInt(key) if(isNaN(int)||int >=0){self.$strings[key]=value return _b_.None}else{ convert_all_str(self)}}else{convert_all_str(self)}} if(self.$jsobj){if(self.$from_js){ value=$B.pyobj2jsobj(value)} if(self.$jsobj.__class__===_b_.type){self.$jsobj[key]=value if(key=="__init__" ||key=="__new__"){ self.$jsobj.$factory=$B.$instance_creator(self.$jsobj)}}else{self.$jsobj[key]=value} return _b_.None} if(key instanceof String){key=key.valueOf()} var hash=$hash !==undefined ? $hash :$B.$hash(key) var index if(self.table[hash]===undefined){index=self._keys.length self.table[hash]=[index]}else{if(! from_setdefault){ var lookup=dict.$lookup_by_key(self,key,hash) if(lookup.found){self._values[lookup.index]=value return _b_.None}} index=self._keys.length if(self.table[hash]===undefined){ self.table[hash]=[index]}else{self.table[hash].push(index)}} self._keys.push(key) self._values.push(value) self._hashes.push(hash) self.$version++ return _b_.None} $B.make_rmethods(dict) dict.clear=function(){ var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self self.table=Object.create(null) self._keys=[] self._values=[] self.$all_str=true self.$strings=new $B.str_dict() if(self.$jsobj){for(var attr in self.$jsobj){if(attr.charAt(0)!=="$" && attr !=="__class__"){delete self.$jsobj[attr]}}} self.$version++ return _b_.None} dict.copy=function(){ var $=$B.args("copy",1,{self:null},["self"],arguments,{},null,null),self=$.self,res=$B.empty_dict() if(self.__class__===_b_.dict){$copy_dict(res,self) return res} var it=$B.make_js_iterator(self) for(var k of it){console.log('iteration yields key',k)} return res} dict.fromkeys=function(){var $=$B.args("fromkeys",3,{cls:null,keys:null,value:null},["cls","keys","value"],arguments,{value:_b_.None},null,null),keys=$.keys,value=$.value var cls=$.cls,res=$B.$call(cls)(),klass=$B.get_class(res), keys_iter=$B.$iter(keys),setitem=klass===dict ? dict.$setitem :$B.$getattr(klass,'__setitem__') while(1){try{var key=_b_.next(keys_iter) setitem(res,key,value)}catch(err){if($B.is_exc(err,[_b_.StopIteration])){return res} throw err}}} dict.get=function(){var $=$B.args("get",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null) try{ return dict.$getitem($.self,$.key,true)}catch(err){if($B.$isinstance(err,_b_.KeyError)){return $._default}else{throw err}}} var dict_items=$B.make_class("dict_items",function(d){return{ __class__:dict_items,dict:d,make_iter:function*(){for(var entry of dict.$iter_items(d)){yield $B.fast_tuple([entry.key,entry.value])}}}} ) dict_items.__iter__=function(self){return dict_itemiterator.$factory(self.make_iter)} dict_items.__len__=function(self){return dict.__len__(self.dict)} dict_items.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter())) return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])} dict_items.__repr__=function(self){var items=Array.from(self.make_iter()) items=items.map($B.fast_tuple) return 'dict_items('+_b_.repr(items)+')'} const dict_reverseitemiterator=make_reverse_iterator( 'dict_reverseitemiterator',dict.$iter_items_reversed) dict_items.__reversed__=function(self){return dict_reverseitemiterator.$factory(self.dict)} make_view_comparison_methods(dict_items) $B.set_func_names(dict_items,'builtins') var dict_itemiterator=$B.make_class('dict_itemiterator',function(make_iter){return{ __class__:dict_itemiterator,iter:make_iter(),make_iter}} ) dict_itemiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter} return self} dict_itemiterator.__next__=function(self){var res=self.iter.next() if(res.done){$B.RAISE(_b_.StopIteration,'')} return $B.fast_tuple(res.value)} dict_itemiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])} $B.set_func_names(dict_itemiterator,'builtins') dict.items=function(self){$B.args('items',1,{self:null},['self'],arguments,{},null,null) return dict_items.$factory(self)} var dict_keys=$B.make_class("dict_keys",function(d){return{ __class__:dict_keys,dict:d,make_iter:function(){return dict.$iter_keys_check(d)}}} ) dict_keys.__iter__=function(self){return dict_keyiterator.$factory(self.make_iter)} dict_keys.__len__=function(self){return dict.__len__(self.dict)} dict_keys.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter())) return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])} dict_keys.__repr__=function(self){var items=Array.from(self.make_iter()) return 'dict_keys('+_b_.repr(items)+')'} dict_keys.__reversed__=function(self){return dict_reversekeyiterator.$factory(self.dict)} make_view_comparison_methods(dict_keys) $B.set_func_names(dict_keys,'builtins') var dict_keyiterator=$B.make_class('dict_keyiterator',function(make_iter){return{ __class__:dict_keyiterator,iter:make_iter(),make_iter}} ) dict_keyiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter} return self} dict_keyiterator.__next__=function(self){var res=self.iter.next() if(res.done){$B.RAISE(_b_.StopIteration,'')} return res.value} dict_keyiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])} $B.set_func_names(dict_keyiterator,'builtins') dict.keys=function(self){$B.args('keys',1,{self:null},['self'],arguments,{},null,null) return dict_keys.$factory(self)} dict.pop=function(){var missing={},$=$B.args("pop",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:missing},null,null),self=$.self,key=$.key,_default=$._default try{var res=dict.__getitem__(self,key) dict.__delitem__(self,key) return res}catch(err){if(err.__class__===_b_.KeyError){if(_default !==missing){return _default} throw err} throw err}} dict.popitem=function(self){$B.check_nb_args_no_kw('popitem',1,arguments) if(dict.__len__(self)==0){$B.RAISE(_b_.KeyError,"'popitem(): dictionary is empty'")} if(self.$all_str){for(var key in self.$strings){} let res=$B.fast_tuple([key,self.$strings[key]]) delete self.$strings[key] self.$version++ return res} var index=self._keys.length-1 while(index >=0){if(self._keys[index]!==undefined){let res=$B.fast_tuple([self._keys[index],self._values[index]]) delete self._keys[index] delete self._values[index] self.$version++ return res} index--}} dict.setdefault=function(){var $=$B.args("setdefault",3,{self:null,key:null,_default:null},["self","key","_default"],arguments,{_default:_b_.None},null,null),self=$.self,key=$.key,_default=$._default _default=_default===undefined ? _b_.None :_default if(self.$all_str){if(typeof key==='string'){if(! self.$strings.hasOwnProperty(key)){self.$strings[key]=_default} return self.$strings[key]}else{ convert_all_str(self)}} if(self.$jsobj){if(! self.$jsobj.hasOwnProperty(key)){self.$jsobj[key]=_default} return self.$jsobj[key]} var lookup=dict.$lookup_by_key(self,key) if(lookup.found){return lookup.value} var hash=lookup.hash dict.$setitem(self,key,_default,hash,true) return _default} dict.update=function(){var $=$B.args("update",1,{"self":null},["self"],arguments,{},"args","kw"),self=$.self,args=$.args,kw=$.kw if(args.length > 0){var o=args[0] if($B.$isinstance(o,dict)){if(o.$jsobj){o=jsobj2dict(o.$jsobj)} $copy_dict(self,o)}else if(_b_.hasattr(o,"keys")){var _keys=_b_.list.$factory($B.$call($B.$getattr(o,"keys"))()) for(let i=0,len=_keys.length;i < len;i++){var _value=$B.$getattr(o,"__getitem__")(_keys[i]) dict.$setitem(self,_keys[i],_value)}}else{let it=_b_.iter(o),i=0,key_value while(true){try{var item=_b_.next(it)}catch(err){if(err.__class__===_b_.StopIteration){break} throw err} try{key_value=_b_.list.$factory(item)}catch(err){$B.RAISE(_b_.TypeError,"cannot convert dictionary"+ " update sequence element #"+i+" to a sequence")} if(key_value.length !==2){$B.RAISE(_b_.ValueError,"dictionary update "+ "sequence element #"+i+" has length "+ key_value.length+"; 2 is required")} dict.$setitem(self,key_value[0],key_value[1]) i++}}} $copy_dict(self,kw) return _b_.None} var dict_values=$B.make_class("dict_values",function(d){return{ __class__:dict_values,dict:d,make_iter:function(){return dict.$iter_values_check(d)}}} ) dict_values.__iter__=function(self){return dict_valueiterator.$factory(self.make_iter)} dict_values.__len__=function(self){return dict.__len__(self.dict)} dict_values.__reduce__=function(self){var items=$B.$list(Array.from(self.make_iter())) return $B.fast_tuple([_b_.iter,$B.fast_tuple([items])])} dict_values.__repr__=function(self){var items=Array.from(self.make_iter()) return 'dict_values('+_b_.repr(items)+')'} const dict_reversevalueiterator=make_reverse_iterator( 'dict_reversevalueiterator',dict.$iter_values_reversed) dict_values.__reversed__=function(self){return dict_reversevalueiterator.$factory(self.dict)} make_view_comparison_methods(dict_values) $B.set_func_names(dict_values,'builtins') var dict_valueiterator=$B.make_class('dict_valueiterator',function(make_iter){return{ __class__:dict_valueiterator,iter:make_iter(),make_iter}} ) dict_valueiterator.__iter__=function(self){self[Symbol.iterator]=function(){return self.iter} return self} dict_valueiterator.__next__=function(self){var res=self.iter.next() if(res.done){$B.RAISE(_b_.StopIteration,'')} return res.value} dict_valueiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([$B.$list(Array.from(self.make_iter()))])])} $B.set_func_names(dict_valueiterator,'builtins') dict.values=function(self){$B.args('values',1,{self:null},['self'],arguments,{},null,null) return dict_values.$factory(self)} dict.$literal=function(items){var res=$B.empty_dict() for(var item of items){dict.$setitem(res,item[0],item[1],item[2])} return res} dict.$factory=function(){var res=$B.empty_dict() var args=[res] for(var arg of arguments){args.push(arg)} dict.__init__.apply(null,args) return res} dict.$from_array=function(arrays){ var res=$B.empty_dict() for(var item of arrays){dict.$setitem(res,item[0],item[1])} return res} _b_.dict=dict $B.set_func_names(dict,"builtins") dict.__class_getitem__=_b_.classmethod.$factory(dict.__class_getitem__) $B.empty_dict=function(){return{ __class__:dict,table:Object.create(null),_keys:[],_values:[],_hashes:[],$strings:new $B.str_dict(),$version:0,$order:0,$all_str:true}} dict.$from_js=function(jsobj){var res=$B.empty_dict() for(var key in jsobj){dict.$setitem(res,key,jsobj[key])} return res} dict.fromkeys=_b_.classmethod.$factory(dict.fromkeys) var mappingproxy=$B.mappingproxy=$B.make_class("mappingproxy",function(obj){var res if($B.$isinstance(obj,dict)){res=$B.obj_dict(dict.$to_obj(obj))}else{res=$B.obj_dict(obj)} res.__class__=mappingproxy res.$version=0 return res} ) mappingproxy.$match_mapping_pattern=true mappingproxy.__repr__=function(self){var d=$B.empty_dict() for(var key in self.$jsobj){dict.$setitem(d,key,self.$jsobj[key])} return dict.__repr__(d)} mappingproxy.__setitem__=function(){$B.RAISE(_b_.TypeError,"'mappingproxy' object does not support "+ "item assignment")} for(var attr in dict){if(mappingproxy[attr]!==undefined || ["__class__","__mro__","__new__","__init__","__delitem__","clear","fromkeys","pop","popitem","setdefault","update"].indexOf(attr)>-1){continue} if(typeof dict[attr]=="function"){mappingproxy[attr]=(function(key){return function(){return dict[key].apply(null,arguments)}})(attr)}else{mappingproxy[attr]=dict[attr]}} $B.set_func_names(mappingproxy,"builtins") function jsobj2dict(x,exclude){exclude=exclude ||function(){return false} var d=$B.empty_dict() for(var attr in x){if(attr.charAt(0)!="$" && ! exclude(attr)){if(x[attr]===null){dict.$setitem(d,attr,_b_.None)}else if(x[attr]===undefined){continue}else if(x[attr].$jsobj===x){dict.$setitem(d,attr,d)}else{dict.$setitem(d,attr,$B.jsobj2pyobj(x[attr]))}}} return d} $B.obj_dict=function(obj,exclude){var klass=obj.__class__ ||$B.get_class(obj) if(!(obj instanceof $B.str_dict)&& klass !==undefined && klass.$native){throw $B.attr_error("__dict__",obj)} var res={__class__:dict,$jsobj:obj,$exclude:exclude ||function(){return false}} return res}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,isinstance=$B.$isinstance function check_not_tuple(self,attr){if(self.__class__===tuple){throw $B.attr_error(attr,self)}} var list={__class__:_b_.type,__qualname__:'list',__mro__:[_b_.object],$is_class:true,$native:true,$match_sequence_pattern:true, $is_sequence:true,__dir__:_b_.object.__dir__} list.__add__=function(self,other){if($B.get_class(self)!==$B.get_class(other)){var this_name=$B.class_name(self) var radd=$B.$getattr(other,'__radd__',null) if(radd===null){$B.RAISE(_b_.TypeError,'can only concatenate '+ this_name+' (not "'+$B.class_name(other)+ '") to '+this_name)} return _b_.NotImplemented} var res=self.slice() for(const item of other){res.push(item)} if(isinstance(self,tuple)){return tuple.$factory(res)}else{return $B.$list(res)}} list.__bool__=function(self){return list.__len__(self)> 0} list.__class_getitem__=$B.$class_getitem list.__contains__=function(){var $=$B.args("__contains__",2,{self:null,item:null},["self","item"],arguments,{},null,null),self=$.self,item=$.item for(var _item of self){if($B.is_or_equals(_item,item)){return true}} return false} list.__delitem__=function(self,arg){if(isinstance(arg,_b_.int)){let pos=arg if(arg < 0){pos=self.length+pos} if(pos >=0 && pos < self.length){self.splice(pos,1) return _b_.None} $B.RAISE(_b_.IndexError,$B.class_name(self)+ " index out of range")} if(isinstance(arg,_b_.slice)){var step=arg.step if(step===_b_.None){step=1} var start=arg.start if(start===_b_.None){start=step > 0 ? 0 :self.length} var stop=arg.stop if(stop===_b_.None){stop=step > 0 ? self.length :0} if(start < 0){start=self.length+start} if(stop < 0){stop=self.length+stop} let res=[],pos=0 if(step > 0){if(stop > start){for(let i=start;i < stop;i+=step){if(self[i]!==undefined){res[pos++]=i}}}}else{if(stop < start){for(let i=start;i > stop;i+=step){if(self[i]!==undefined){res[pos++]=i}} res.reverse()}} let i=res.length while(i--){self.splice(res[i],1)} return _b_.None} if(_b_.hasattr(arg,"__int__")||_b_.hasattr(arg,"__index__")){list.__delitem__(self,_b_.int.$factory(arg)) return _b_.None} $B.RAISE(_b_.TypeError,$B.class_name(self)+ " indices must be integer, not "+$B.class_name(arg))} list.__eq__=function(self,other){if(other[$B.PYOBJ]){other=other[$B.PYOBJ]} var klass=isinstance(self,list)? list :tuple if(isinstance(other,klass)){if(other.length==self.length){var i=self.length while(i--){if(! $B.is_or_equals(self[i],other[i])){return false}} return true} return false} return _b_.NotImplemented} list.__getitem__=function(self,key){ $B.check_nb_args_no_kw("__getitem__",2,arguments) return list.$getitem(self,key)} list.$getitem=function(self,key){var klass=(self.__class__ ||$B.get_class(self)) var factory=function(list_res){list_res.__class__=klass return list_res} var int_key try{int_key=$B.PyNumber_Index(key)}catch(err){} if(int_key !==undefined){let items=self.valueOf(),pos=int_key if(int_key < 0){pos=items.length+pos} if(pos >=0 && pos < items.length){return items[pos]} $B.RAISE(_b_.IndexError,$B.class_name(self)+ " index out of range")} if(key.__class__===_b_.slice ||isinstance(key,_b_.slice)){return _b_.list.$getitem_slice(self,key)} $B.RAISE(_b_.TypeError,$B.class_name(self)+ " indices must be integer, not "+$B.class_name(key))} list.$getitem_slice=function(self,key){var klass=self.__class__ ?? $B.get_class(self) if(key.start===_b_.None && key.stop===_b_.None && key.step===_b_.None){let res=self.slice() res.__class__=klass return res} let s=_b_.slice.$conv_for_seq(key,self.length) let res=[],items=self.valueOf(),pos=0,start=s.start,stop=s.stop,step=s.step res.__class__=klass if(step > 0){if(stop <=start){return res} for(let i=start;i < stop;i+=step){res[pos++]=items[i]} return res}else{if(stop > start){return res} for(let i=start;i > stop;i+=step){res[pos++]=items[i]} return res}} list.__ge__=function(self,other){ if(! isinstance(other,list)){return _b_.NotImplemented} var res=list.__le__(other,self) if(res===_b_.NotImplemented){return res} return res} list.__gt__=function(self,other){ if(! isinstance(other,list)){return _b_.NotImplemented} var res=list.__lt__(other,self) if(res===_b_.NotImplemented){return res} return res} list.__hash__=_b_.None list.__iadd__=function(){var $=$B.args("__iadd__",2,{self:null,x:null},["self","x"],arguments,{},null,null) var x=list.$factory($.x) for(var i=0;i < x.length;i++){$.self.push(x[i])} return $.self} list.__imul__=function(){var $=$B.args("__imul__",2,{self:null,x:null},["self","x"],arguments,{},null,null),len=$.self.length,pos=len try{var x=$B.PyNumber_Index($.x)}catch(err){$B.RAISE(_b_.TypeError,`can't multiply sequence by non-int`+ ` of type '${$B.class_name($.x)}'`)} if(x==0){list.clear($.self) return $.self} for(var i=1;i < x;i++){for(var j=0;j < len;j++){$.self[pos++]=$.self[j]}} return $.self} list.__init__=function(){var $=$B.args('__init__',1,{self:null},['self'],arguments,{},'args','kw'),self=$.self,args=$.args,kw=$.kw if(args.length > 1){$B.RAISE(_b_.TypeError,'expected at most 1 argument, got '+ args.length)} if(_b_.dict.__len__(kw)> 0){$B.RAISE(_b_.TypeError,'list() takes no keyword arguments')} while(self.length > 0){self.pop()} var arg=args[0] if(arg===undefined){return _b_.None} var pos=0 for(var item of $B.make_js_iterator(arg)){self[pos++]=item} return _b_.None} var list_iterator=$B.make_iterator_class("list_iterator") list_iterator.__reduce__=list_iterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([list.$factory(self)]),0])} list.__iter__=function(self){return list_iterator.$factory(self)} list.__le__=function(self,other){ if(! isinstance(other,[list,_b_.tuple])){return _b_.NotImplemented} var i=0 while(i < self.length && i < other.length && $B.is_or_equals(self[i],other[i])){i++} if(i==self.length){ return self.length <=other.length} if(i==other.length){ return false} return $B.rich_comp('__le__',self[i],other[i])} list.__len__=function(self){return self.length} list.__lt__=function(self,other){ if(! isinstance(other,[list,_b_.tuple])){return _b_.NotImplemented} var i=0 while(i < self.length && i < other.length && $B.is_or_equals(self[i],other[i])){i++} if(i==self.length){ return self.length < other.length} if(i==other.length){ return false} return $B.rich_comp('__lt__',self[i],other[i])} list.__mul__=function(self,other){if($B.$isinstance(other,[_b_.float,_b_.complex])){$B.RAISE(_b_.TypeError,"'"+$B.class_name(other)+ "' object cannot be interpreted as an integer")} if(self.length==0){return list.__new__(list)} try{other=$B.PyNumber_Index(other)}catch(err){return _b_.NotImplemented} if(typeof other=='number'){if(other < 0){return list.__new__(list)} if(self.length > $B.max_array_size/other){$B.RAISE(_b_.OverflowError,`cannot fit `+ `'${$B.class_name(other)}' into an index-sized integer`)} var res=[],$temp=self.slice(),len=$temp.length for(var i=0;i < other;i++){for(var j=0;j < len;j++){res.push($temp[j])}} res.__class__=self.__class__ return res}else if(isinstance(other,$B.long_int)){$B.RAISE(_b_.OverflowError,`cannot fit `+ `'${$B.class_name(other)}' into an index-sized integer`)}else{return _b_.NotImplemented}} list.__new__=function(cls){ if(cls===undefined){$B.RAISE(_b_.TypeError,"list.__new__(): not enough arguments")} var res=[] res.__class__=cls res.__dict__=$B.empty_dict() return res} list.__repr__=function(self){$B.builtins_repr_check(list,arguments) return list_repr(self)} function list_repr(self){ if($B.repr.enter(self)){ return '[...]'} var _r=[],res for(var i=0;i < self.length;i++){_r.push(_b_.repr(self[i]))} if(isinstance(self,tuple)){if(self.length==1){res="("+_r[0]+",)"}else{res="("+_r.join(", ")+")"}}else{res="["+_r.join(", ")+"]"} $B.repr.leave(self) return res} var list_reverseiterator=$B.make_iterator_class("list_reverseiterator",true) list_reverseiterator.__reduce__=list_reverseiterator.__reduce_ex__=function(self){return $B.fast_tuple([_b_.iter,$B.fast_tuple([list.$factory(self)]),0])} list.__reversed__=function(self){return list_reverseiterator.$factory(self)} list.__rmul__=function(self,other){return list.__mul__(self,other)} list.__setattr__=function(self,attr,value){if(self.__class__===list ||self.__class__===tuple){var cl_name=$B.class_name(self) if(list.hasOwnProperty(attr)){$B.RAISE_ATTRIBUTE_ERROR("'"+cl_name+ "' object attribute '"+attr+"' is read-only",self,attr)}else{$B.RAISE_ATTRIBUTE_ERROR( `'${cl_name}' object has no attribute '${attr}'`,self,attr)}} _b_.dict.$setitem(self.__dict__,attr,value) return _b_.None} list.__setitem__=function(){var $=$B.args("__setitem__",3,{self:null,key:null,value:null},["self","key","value"],arguments,{},null,null),self=$.self,arg=$.key,value=$.value list.$setitem(self,arg,value)} function set_list_slice(obj,start,stop,value){var res=_b_.list.$factory(value) obj.splice.apply(obj,[start,stop-start].concat(res))} function set_list_slice_step(obj,start,stop,step,value){if(step==1){return set_list_slice(obj,start,stop,value)} if(step==0){$B.RAISE(_b_.ValueError,"slice step cannot be zero")} var repl=_b_.list.$factory(value),j=0,test,nb=0 if(step > 0){test=function(i){return i < stop}}else{test=function(i){return i > stop}} for(var i=start;test(i);i+=step){nb++} if(nb !=repl.length){$B.RAISE(_b_.ValueError,"attempt to assign sequence of size "+repl.length+ " to extended slice of size "+nb)} for(var i=start;test(i);i+=step){obj[i]=repl[j] j++}} list.$setitem=function(self,arg,value){ if(typeof arg=="number" ||isinstance(arg,_b_.int)){var pos=$B.PyNumber_Index(arg) if(arg < 0){pos=self.length+pos} if(pos >=0 && pos < self.length){self[pos]=value}else{$B.RAISE(_b_.IndexError,"list assignment index out of range")} return _b_.None} if(isinstance(arg,_b_.slice)){var s=_b_.slice.$conv_for_seq(arg,self.length) if(arg.step===null){set_list_slice(self,s.start,s.stop,value)}else{set_list_slice_step(self,s.start,s.stop,s.step,value)} return _b_.None} if(_b_.hasattr(arg,"__int__")||_b_.hasattr(arg,"__index__")){list.__setitem__(self,_b_.int.$factory(arg),value) return _b_.None} $B.RAISE(_b_.TypeError,"list indices must be integer, not "+ $B.class_name(arg))} list.append=function(self,x){$B.check_nb_args_no_kw("append",2,arguments) if(self[$B.PYOBJ]){self[$B.PYOBJ].push(x) self.push($B.pyobj2jsobj(x))}else if(self.$is_js_array){self.push($B.pyobj2jsobj(x))}else{self[self.length]=x} return _b_.None} list.clear=function(){var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null) while($.self.length){$.self.pop()} return _b_.None} list.copy=function(){var $=$B.args("copy",1,{self:null},["self"],arguments,{},null,null) var res=$.self.slice() res.__class__=$.self.__class__ return res} list.count=function(){var $=$B.args("count",2,{self:null,x:null},["self","x"],arguments,{},null,null) var res=0 for(var _item of $.self){if($B.is_or_equals(_item,$.x)){res++}} return res} list.extend=function(){var $=$B.args("extend",2,{self:null,t:null},["self","t"],arguments,{},null,null) if(self.$is_js_array){for(var item of $B.make_js_iterator($.t)){$.self[$.self.length]=$B.pyobj2jsobj(item)}}else{for(var item of $B.make_js_iterator($.t)){$.self[$.self.length]=item}} return _b_.None} list.index=function(){var missing={},$=$B.args("index",4,{self:null,x:null,start:null,stop:null},["self","x","start" ,"stop"],arguments,{start:0,stop:missing},null,null),self=$.self,start=$.start,stop=$.stop if(start.__class__===$B.long_int){start=parseInt(start.value)*(start.pos ? 1 :-1)} if(start < 0){start=Math.max(0,start+self.length)} if(stop===missing){stop=self.length}else{if(stop.__class__===$B.long_int){stop=parseInt(stop.value)*(stop.pos ? 1 :-1)} if(stop < 0){stop=Math.min(self.length,stop+self.length)} stop=Math.min(stop,self.length)} for(var i=start;i < stop;i++){if($B.rich_comp('__eq__',$.x,self[i])){return i}} $B.RAISE(_b_.ValueError,_b_.repr($.x)+" is not in "+ $B.class_name(self))} list.insert=function(){var $=$B.args("insert",3,{self:null,i:null,item:null},["self","i","item"],arguments,{},null,null) if(self.$is_js_array){$.self.splice($.i,0,$B.pyobj2jsobj($.item))}else{$.self.splice($.i,0,$.item)} return _b_.None} list.pop=function(){var missing={} var $=$B.args("pop",2,{self:null,pos:null},["self","pos"],arguments,{pos:missing},null,null),self=$.self,pos=$.pos check_not_tuple(self,"pop") if(pos===missing){pos=self.length-1} pos=$B.PyNumber_Index(pos) if(pos < 0){pos+=self.length} var res=self[pos] if(res===undefined){$B.RAISE(_b_.IndexError,"pop index out of range")} self.splice(pos,1) return res} list.remove=function(){var $=$B.args("remove",2,{self:null,x:null},["self","x"],arguments,{},null,null) for(var i=0,len=$.self.length;i < len;i++){if($B.rich_comp("__eq__",$.self[i],$.x)){$.self.splice(i,1) return _b_.None}} $B.RAISE(_b_.ValueError,_b_.str.$factory($.x)+" is not in list")} list.reverse=function(){var $=$B.args("reverse",1,{self:null},["self"],arguments,{},null,null),_len=$.self.length-1,i=parseInt($.self.length/2) while(i--){var buf=$.self[i] $.self[i]=$.self[_len-i] $.self[_len-i]=buf} return _b_.None} function $elts_class(self){ if(self.length==0){return null} var cl=$B.get_class(self[0]),i=self.length while(i--){if($B.get_class(self[i])!==cl){return false}} return cl} list.sort=function(self){var $=$B.args("sort",1,{self:null},["self"],arguments,{},null,"kw") check_not_tuple(self,"sort") var func=_b_.None,reverse=false for(var item of _b_.dict.$iter_items($.kw)){if(item.key=="key"){func=item.value}else if(item.key=="reverse"){reverse=item.value}else{$B.RAISE(_b_.TypeError,"'"+item.key+ "' is an invalid keyword argument for this function")}} if(self.length==0){return _b_.None} if(func !==_b_.None){func=$B.$call(func)} self.$cl=$elts_class(self) var cmp=null; function basic_cmp(a,b){return $B.rich_comp("__lt__",a,b)?-1: $B.rich_comp('__eq__',a,b)? 0 :1} function reverse_cmp(a,b){return basic_cmp(b,a)} if(func===_b_.None && self.$cl===_b_.str){if(reverse){cmp=function(b,a){return $B.$AlphabeticalCompare(a,b)}}else{cmp=function(a,b){return $B.$AlphabeticalCompare(a,b)}}}else if(func===_b_.None && self.$cl===_b_.int){if(reverse){cmp=function(b,a){return a-b}}else{cmp=function(a,b){return a-b}}}else{cmp=reverse ? function(t1,t2){return basic_cmp(t2[0],t1[0])}: function(t1,t2){return basic_cmp(t1[0],t2[0])} if(func===_b_.None){cmp=reverse ? reverse_cmp :basic_cmp self.sort(cmp)}else{var temp=[],saved=self.slice() for(let i=0,len=self.length;i < len;i++){temp.push([func(self[i]),i])} temp.sort(cmp) for(let i=0,len=temp.length;i < len;i++){self[i]=saved[temp[i][1]]}} return self.$is_js_array ? self :_b_.None} $B.$TimSort(self,cmp) return self.$is_js_array ? self :_b_.None} $B.$list=function(t){t.__class__=_b_.list return t} var factory=function(){var klass=this if(arguments.length==0){return $B.$list([])} var $=$B.args(klass.__name__,1,{obj:null},["obj"],arguments,{},null,null),obj=$.obj if(Array.isArray(obj)&& obj.__class__){ obj=obj.slice() obj.__class__=klass return obj} let res=Array.from($B.make_js_iterator(obj)) res.__class__=klass return res} list.$factory=function(){return factory.apply(list,arguments)} list.$unpack=function(obj){ try{return _b_.list.$factory(obj)}catch(err){try{var it=$B.$iter(obj) $B.$call($B.$getattr(it,"__next__"))}catch(err1){if($B.is_exc(err1,[_b_.TypeError])){$B.RAISE(_b_.TypeError,`Value after * must be an iterable, not ${$B.class_name(obj)}`)} throw err1} throw err}} $B.set_func_names(list,"builtins") var tuple={__class__:_b_.type,__mro__:[_b_.object],__qualname__:'tuple',$is_class:true,$native:true,$match_sequence_pattern:true, $is_sequence:true} var tuple_iterator=$B.make_iterator_class("tuple_iterator") tuple.__iter__=function(self){return tuple_iterator.$factory(self)} tuple.$factory=function(){var obj=factory.apply(tuple,arguments) obj.__class__=tuple return obj} $B.fast_tuple=function(array){array.__class__=tuple return array} for(let attr in list){switch(attr){case "__delitem__": case "__iadd__": case "__imul__": case "__setitem__": case "append": case "extend": case "insert": case "pop": case "remove": case "reverse": case "sort": break default: if(tuple[attr]===undefined){if(typeof list[attr]=="function"){tuple[attr]=(function(x){return function(){return list[x].apply(null,arguments)}})(attr)}}}} tuple.__class_getitem__=function(cls,item){ if(! Array.isArray(item)){item=[item]} return $B.GenericAlias.$factory(cls,item)} tuple.__eq__=function(self,other){ if(other===undefined){return self===tuple} return list.__eq__(self,other)} function c_mul(a,b){var s=((parseInt(a)*b)& 0xFFFFFFFF).toString(16) return parseInt(s.substr(0,s.length-1),16)} tuple.$getnewargs=function(self){return $B.fast_tuple([$B.fast_tuple(self.slice())])} tuple.__getnewargs__=function(){return tuple.$getnewargs($B.single_arg('__getnewargs__','self',arguments))} tuple.__hash__=function(self){ var x=0x3456789 for(var i=0,len=self.length;i < len;i++){var y=_b_.hash(self[i]) x=c_mul(1000003,x)^ y & 0xFFFFFFFF} return x} tuple.__init__=function(){ return _b_.None} tuple.__new__=function(){if(arguments.length===undefined){$B.RAISE(_b_.TypeError,"tuple.__new__(): not enough arguments")} var $=$B.args('__new__',1,{cls:null},['cls'],arguments,{},'args','kw'),cls=$.cls,args=$.args,kw=$.kw var self=[] self.__class__=cls self.__dict__=$B.empty_dict() if(args.length > 0){if(args.length==1){for(var item of $B.make_js_iterator(args[0])){self.push(item)}}else{$B.RAISE(_b_.TypeError,'tuple expected at most 1 '+ `argument, got ${args.length}`)}} if(cls===tuple && _b_.dict.__len__(kw)> 0){$B.RAISE(_b_.TypeError,'tuple() takes no keyword arguments')} return self} tuple.__repr__=function(self){$B.builtins_repr_check(tuple,arguments) return list_repr(self)} $B.set_func_names(tuple,"builtins") _b_.list=list _b_.tuple=tuple _b_.object.__bases__=tuple.$factory() _b_.type.__bases__=$B.fast_tuple([_b_.object])})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function to_simple(value){switch(typeof value){case 'string': case 'number': return value case 'boolean': return value ? "true" :"false" case 'object': if(value===_b_.None){return 'null'}else if(value instanceof Number){return value.valueOf()}else if(value instanceof String){return value.valueOf()} break default: $B.RAISE(_b_.TypeError,"keys must be str, int, "+ "float, bool or None, not "+$B.class_name(value))}} $B.pyobj2structuredclone=function(obj,strict){ strict=strict===undefined ? true :strict if(typeof obj=="boolean" ||typeof obj=="number" || typeof obj=="string" ||obj instanceof String){return obj}else if(obj.__class__===_b_.float){return obj.value}else if(obj===_b_.None){return null }else if(Array.isArray(obj)||obj.__class__===_b_.list || obj.__class__===_b_.tuple ||obj.__class__===js_array){let res=new Array(obj.length); for(var i=0,len=obj.length;i < len;++i){res[i]=$B.pyobj2structuredclone(obj[i]);} return res}else if($B.$isinstance(obj,_b_.dict)){if(strict){for(var key of $B.make_js_iterator(_b_.dict.keys(obj))){if(typeof key !=='string'){$B.RAISE(_b_.TypeError,"a dictionary with non-string "+ "keys does not support structured clone")}}} let res={} for(var entry of $B.make_js_iterator(_b_.dict.items(obj))){res[to_simple(entry[0])]=$B.pyobj2structuredclone(entry[1])} return res}else if(obj.__class__===$B.long_int){return obj.value}else if(Object.getPrototypeOf(obj).constructor===Object){var res={} for(var key in obj){res[key]=$B.pyobj2structuredclone(obj[key])} return res}else{return obj} $B.RAISE(_b_.TypeError,`cannot send '${$B.class_name(obj)}' object`)} $B.structuredclone2pyobj=function(obj){if(obj===null){return _b_.None}else if(obj===undefined){return $B.Undefined}else if(typeof obj=="boolean"){return obj}else if(typeof obj=="string" ||obj instanceof String){return $B.String(obj)}else if(typeof obj=="number" ||obj instanceof Number){obj+=0 return Number.isInteger(obj)? obj : {__class__:_b_.float,value:obj}}else if(Array.isArray(obj)||obj.__class__===_b_.list || obj.__class__===_b_.tuple){let res=_b_.list.$factory() for(var i=0,len=obj.length;i < len;i++){res.push($B.structuredclone2pyobj(obj[i]))} return res}else if(typeof obj=="object"){if(Object.getPrototypeOf(obj)===Object.prototype){if(! $B.$isinstance(obj,$B.JSObj)){return obj} let res=$B.empty_dict() for(var key in obj){_b_.dict.$setitem(res,key,$B.structuredclone2pyobj(obj[key]))} return res}else{return obj}}else{$B.RAISE(_b_.TypeError,_b_.str.$factory(obj)+ " does not support the structured clone algorithm")}} const JSOBJ=$B.JSOBJ=Symbol('JSOBJ') const PYOBJ=$B.PYOBJ=Symbol('PYOBJ') const PYOBJFCT=Symbol('PYOBJFCT') const PYOBJFCTS=Symbol('PYOBJFCTS') var jsobj2pyobj=$B.jsobj2pyobj=function(jsobj,_this){ if(jsobj===null){return null} switch(typeof jsobj){case 'boolean': return jsobj case 'undefined': return $B.Undefined case 'number': if(jsobj % 1===0){return Number.isSafeInteger(jsobj)? jsobj :$B.fast_long_int(jsobj)} return _b_.float.$factory(jsobj) case 'bigint': return jsobj case 'string': return $B.String(jsobj)} if(Array.isArray(jsobj)){ try{Object.defineProperty(jsobj,"$is_js_array",{value:true});}catch(err){} return jsobj} let pyobj=jsobj[PYOBJ] if(pyobj !==undefined){return pyobj} if(jsobj instanceof Promise ||typeof jsobj.then=="function"){return jsobj} if(typeof jsobj==="function"){ _this=_this===undefined ? null :_this if(_this===null){const pyobj=jsobj[PYOBJFCT]; if(pyobj !==undefined){return pyobj}}else{const pyobjfcts=_this[PYOBJFCTS] if(pyobjfcts !==undefined){const pyobj=pyobjfcts.get(jsobj) if(pyobj !==undefined){return pyobj}}else{try{_this[PYOBJFCTS]=new Map()}catch(err){}}} var res=function(){var args=new Array(arguments.length) for(var i=0,len=arguments.length;i < len;++i){var arg=arguments[i] if(arg !==null && arg.constructor===Object && arg.$kw){$B.RAISE(_b_.TypeError,'keyword arguments are not supported for '+ 'Javascript functions')} args[i]=pyobj2jsobj(arg)} try{return jsobj2pyobj(jsobj.apply(_this,args))}catch(err){throw $B.exception(err)}} if(_this===null){jsobj[PYOBJFCT]=res;}else if(_this[PYOBJFCTS]!==undefined){_this[PYOBJFCTS].set(jsobj,res)} res[JSOBJ]=jsobj Object.defineProperty(res,'$js_func',{value:jsobj}) Object.defineProperty(res,'$infos',{value:{__name__:jsobj.name,__qualname__:jsobj.name},writable:true}) let value=[] value[$B.func_attrs.name]=jsobj.name value[$B.func_attrs.qualname]=jsobj.name Object.defineProperty(res,'$function_infos',{value,writable:true} ) return res} if(jsobj.$kw){return jsobj} if($B.$isNode(jsobj)){const res=$B.DOMNode.$factory(jsobj) jsobj[PYOBJ]=res res[JSOBJ]=jsobj return res} return jsobj} var pyobj2jsobj=$B.pyobj2jsobj=function(pyobj){ switch(pyobj){case true: case false: return pyobj case $B.Undefined: return undefined case null: return null} let _jsobj=pyobj[JSOBJ] if(_jsobj !==undefined){return _jsobj} var klass=$B.get_class(pyobj) function has_type(cls,base){return cls===base ||cls.__mro__.includes(base)} if(has_type(klass,$B.DOMNode)){return pyobj} if(has_type(klass,_b_.list)||has_type(klass,_b_.tuple)){ var jsobj=pyobj.map(pyobj2jsobj) jsobj[PYOBJ]=pyobj return jsobj} if(has_type(klass,_b_.dict)){ let jsobj={} for(var entry of _b_.dict.$iter_items(pyobj)){var key=entry.key if(typeof key !=="string"){key=_b_.str.$factory(key)} if(typeof entry.value==='function'){ entry.value.bind(jsobj)} jsobj[key]=pyobj2jsobj(entry.value)} pyobj[JSOBJ]=jsobj return jsobj} if(has_type(klass,_b_.str)){ return pyobj.valueOf()} if(klass===$B.long_int){return pyobj.value} if(has_type(klass,_b_.float)){ return pyobj.value} if(klass===$B.function ||klass===$B.method){if(typeof pyobj=='function' && pyobj.prototype && pyobj.prototype.constructor===pyobj && ! pyobj.$function_infos){ return pyobj} if(pyobj.$is_async){ let jsobj=function(){var res=pyobj.apply(null,arguments) return $B.coroutine.send(res)} pyobj[JSOBJ]=jsobj jsobj[PYOBJ]=pyobj return jsobj} let jsobj=function(){try{ var args=new Array(arguments.length) for(var i=0;i < arguments.length;++i){args[i]=jsobj2pyobj(arguments[i])} let res if(pyobj.prototype && pyobj.prototype.constructor===pyobj && ! pyobj.$function_infos){res=new pyobj(...args)}else{res=pyobj.apply(this,args)} return pyobj2jsobj(res)}catch(err){$B.handle_error(err)}} pyobj[JSOBJ]=jsobj jsobj[PYOBJ]=pyobj return jsobj} return pyobj} function pyargs2jsargs(pyargs){var args=new Array(pyargs.length); for(var i=0,len=pyargs.length;i < len;i++){var arg=pyargs[i] if(arg !==undefined && arg !==null && arg.$kw !==undefined){ $B.RAISE(_b_.TypeError,"A Javascript function can't take "+ "keyword arguments")} args[i]=$B.pyobj2jsobj(arg)} return args} $B.JSObj=$B.make_class("JSObject",jsobj2pyobj) function check_big_int(x,y){if(typeof x !="bigint" ||typeof y !="bigint"){$B.RAISE(_b_.TypeError,"unsupported operand type(s) for - : '"+ $B.class_name(x)+"' and '"+$B.class_name(y)+"'")}} var js_ops={__add__:function(_self,other){check_big_int(_self,other) return _self+other},__mod__:function(_self,other){check_big_int(_self,other) return _self % other},__mul__:function(_self,other){check_big_int(_self,other) return _self*other},__pow__:function(_self,other){check_big_int(_self,other) return _self**other},__sub__:function(_self,other){check_big_int(_self,other) return _self-other}} for(var js_op in js_ops){$B.JSObj[js_op]=js_ops[js_op]} $B.JSObj.__bool__=function(_self){if(typeof _self=='object'){for(var key in _self){return true} return false} return !! _self} $B.JSObj.__contains__=function(_self,key){return key in _self} $B.JSObj.__delitem__=function(_self,key){delete _self[key] return _b_.None} $B.JSObj.__dir__=function(_self){var attrs=Object.keys(_self); attrs=attrs.sort() return attrs} $B.JSObj.__eq__=function(_self,other){switch(typeof _self){case "string": return _self==other case "object": if(_self.__eq__ !==undefined){return _self.__eq__(other)} if(Object.keys(_self).length !==Object.keys(other).length){return false} if(_self===other){return true} for(var key in _self){if(! $B.rich_comp('__eq__',_self[key],other[key])){return false}} return true case 'function': if(_self.$js_func && other.$js_func){return _self.$js_func===other.$js_func} return _self===other default: return _self===other}} var iterator=$B.make_class('js_iterator',function(obj){return{ __class__:iterator,keys:Object.keys(obj),values:Object.values(obj),length:Object.keys(obj).length,counter:-1}} ) iterator.__next__=function(_self){_self.counter++ if(_self.counter==_self.length){$B.RAISE(_b_.StopIteration,'')} return _self.keys[_self.counter]} $B.set_func_names(iterator,'builtins') $B.JSObj.__hash__=function(_self){ return _b_.object.__hash__(_self)} $B.JSObj.__iter__=function(_self){return iterator.$factory(_self)} $B.JSObj.__ne__=function(_self,other){return ! $B.JSObj.__eq__(_self,other)} function jsclass2pyclass(js_class){ var proto=js_class.prototype,klass=$B.make_class(js_class.name) klass.__init__=function(self){var args=pyargs2jsargs(Array.from(arguments).slice(1)) var js_obj=new proto.constructor(...args) for(var attr in js_obj){_b_.dict.$setitem(self.__dict__,attr,$B.jsobj2pyobj(js_obj[attr]))} return _b_.None} klass.new=function(){var args=pyargs2jsargs(arguments) return jsobj2pyobj(new proto.constructor(...args))} var key,value for([key,value]of Object.entries(Object.getOwnPropertyDescriptors(proto))){if(key=='constructor'){continue} if(value.get){var getter=(function(v){return function(self){return v.get.call(self.__dict__.$jsobj)}})(value) getter.$infos={__name__:key} var setter if(value.set){setter=(function(v){return function(self,x){v.set.call(self.__dict__.$jsobj,x)}})(value) klass[key]=_b_.property.$factory(getter,setter)}else{klass[key]=_b_.property.$factory(getter)}}else{klass[key]=(function(m){return function(self){var args=Array.from(arguments).slice(1) return proto[m].apply(self.__dict__.$jsobj,args)}})(key)}} for(var name of Object.getOwnPropertyNames(js_class)){klass[name]=(function(k){return function(self){var args=Array.from(arguments).map(pyobj2jsobj) return js_class[k].apply(self,args)}})(name)} var js_parent=Object.getPrototypeOf(proto).constructor if(js_parent.toString().startsWith('class ')){var py_parent=jsclass2pyclass(js_parent) klass.__mro__=[py_parent].concat(klass.__mro__)} var frame=$B.frame_obj.frame if(frame){$B.set_func_names(klass,frame[2])} return klass} $B.JSObj.__getattribute__=function(_self,attr){var test=false if(test){console.log("__ga__",_self,attr)} if(attr=="new" && typeof _self=="function"){ var new_func if(_self.$js_func){new_func=function(){var args=pyargs2jsargs(arguments) return new _self.$js_func(...args)}}else{new_func=function(){var args=pyargs2jsargs(arguments) return new _self(...args)}} Object.defineProperty(new_func,'$infos',{value:{__name__:attr,__qualname__:attr},writable:true} ) let value=[] value[$B.func_attrs.__name__]=attr value[$B.func_attrs.__qualname__]=attr Object.defineProperty(new_func,'$function_infos',{value,writable:true} ) return new_func} var js_attr=_self[attr] if(js_attr==undefined && typeof _self=="function"){js_attr=_self.$js_func[attr]} if(test){console.log('js_attr',js_attr,typeof js_attr,'\n is JS class ?',js_attr===undefined ? false : js_attr.toString().startsWith('class '))} if(js_attr===undefined){if(typeof _self=='object' && attr in _self){ return $B.Undefined} if(typeof _self.getNamedItem=='function'){var res=_self.getNamedItem(attr) if(res !==undefined){return jsobj2pyobj(res)}} var klass=$B.get_class(_self),class_attr=$B.$getattr(klass,attr,null) if(class_attr !==null){if(typeof class_attr=="function"){return function(){var args=new Array(arguments.length+1) args[0]=_self; for(var i=0,len=arguments.length;i < len;i++){args[i+1]=arguments[i]} return jsobj2pyobj(class_attr.apply(null,args))}}else{return class_attr}} throw $B.attr_error(attr,_self)} if(js_attr !==null && js_attr.toString && typeof js_attr=='function' && js_attr.toString().startsWith('class ')){ return jsclass2pyclass(js_attr)}else if(typeof js_attr==='function'){ if(! js_attr.$infos && ! js_attr.$function_infos){js_attr.$js_func=js_attr} return jsobj2pyobj(js_attr,_self.$js_func ||_self)}else{if(test){console.log('jsobj2pyobj on',js_attr)} var res=jsobj2pyobj(js_attr) if(test){console.log(' res',res)} return res}} $B.JSObj.__setattr__=function(_self,attr,value){_self[attr]=$B.pyobj2jsobj(value) return _b_.None} $B.JSObj.__getitem__=function(_self,key){if(typeof key=="string"){try{return $B.JSObj.__getattribute__(_self,key)}catch(err){if($B.is_exc(err,[_b_.AttributeError])){$B.RAISE(_b_.KeyError,err.name)} throw err}}else if(typeof key=="number"){if(_self[key]!==undefined){return jsobj2pyobj(_self[key])} if(typeof _self.length=='number'){if((typeof key=="number" ||typeof key=="boolean")&& typeof _self.item=='function'){var rank=_b_.int.$factory(key) if(rank < 0){rank+=_self.length} let res=_self.item(rank) if(res===null){$B.RAISE(_b_.IndexError,rank)} return jsobj2pyobj(res)}}}else if(key.__class__===_b_.slice && typeof _self.item=='function'){var _slice=_b_.slice.$conv_for_seq(key,_self.length) let res=new Array(Math.floor((_slice.stop-_slice.start)/_slice.step)) let offset=0 for(var i=_slice.start;i < _slice.stop;i+=_slice.step){res[offset++]=_self.item(i)} return res} $B.RAISE(_b_.KeyError,key)} $B.JSObj.__setitem__=$B.JSObj.__setattr__ $B.JSObj.__repr__=function(_self){if(typeof _self=='number'){return _self+''} if(typeof _self=='function' && _self.$js_func.name && globalThis[_self.$js_func.name]===_self.$js_func){return ``} var js_repr=Object.prototype.toString.call(_self) return ``} $B.JSObj.bind=function(_self,evt,func){ var js_func=function(ev){try{return func(jsobj2pyobj(ev))}catch(err){if(err.__class__ !==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)}catch(err1){console.log(err)}}}} Object.defineProperty(_self,'$brython_events',{value:_self.$brython_events ||{},writable:true} ) if(_self.$brython_events){_self.$brython_events[evt]=_self.$brython_events[evt]||[] _self.$brython_events[evt].push([func,js_func])} _self.addEventListener(evt,js_func) return _b_.None} $B.JSObj.bindings=function(_self){var res=$B.empty_dict() if(_self.$brython_events){for(var key in _self.$brython_events){_b_.dict.$setitem(res,key,$B.fast_tuple(_self.$brython_events[key].map(x=> x[0])))}} return res} $B.JSObj.unbind=function(_self,evt,func){if(! _self.$brython_events){return _b_.None} if(! _self.$brython_events[evt]){return _b_.None} var events=_self.$brython_events[evt] if(func===undefined){ for(var item of events){_self.removeEventListener(evt,item[1])} delete _self.$brython_events[evt]}else{for(var i=0,len=events.length;i < len;i++){if(events[i][0]===func){_self.removeEventListener(evt,events[i][1]) events.splice(i,1)}} if(events.length==0){delete _self.$brython_events[evt]}}} $B.JSObj.to_dict=function(_self){ if(typeof _self=='function'){$B.RAISE(_b_.TypeError,"method 'to_dict()' not supported for functions")} var res=$B.empty_dict() for(var key in _self){_b_.dict.$setitem_string(res,key,convert_to_python(_self[key]))} return res} function convert_to_python(obj){ if(obj===null ||obj===undefined){return $B.jsobj2pyobj(obj)} if(obj.__class__){ return obj} if(Array.isArray(obj)){return obj.map(convert_to_python)} if($B.$isinstance(obj,$B.JSObj)){if(typeof obj=='number'){ return $B.fast_float(obj)} var res=$B.empty_dict() for(var key in obj){_b_.dict.$setitem_string(res,key,convert_to_python(obj[key]))} return res} return $B.jsobj2pyobj(obj)} $B.set_func_names($B.JSObj,"builtins") var js_list_meta=$B.make_class('js_list_meta') js_list_meta.__mro__=[_b_.type,_b_.object] js_list_meta.__getattribute__=function(_self,attr){if(_b_.list[attr]===undefined){if(js_array.hasOwnProperty(attr)){return js_array[attr]} $B.RAISE_ATTRIBUTE_ERROR( `${$B.class_name(_self)} has no attribute '${attr}'`,_self,attr)} if(['__delitem__','__setitem__'].indexOf(attr)>-1){ return function(){var args=new Array(arguments.length) args[0]=arguments[0] for(var i=1,len=arguments.length;i < len;i++){args[i]=pyobj2jsobj(arguments[i])} return _b_.list[attr].apply(null,args)}}else if(['__contains__','__eq__','__getitem__','__ge__','__gt__','__le__','__lt__'].indexOf(attr)>-1){ return function(){var pylist=$B.$list(arguments[0].map(jsobj2pyobj)) return jsobj2pyobj(_b_.list[attr].call(null,pylist,...Array.from(arguments).slice(1)))}}else if(js_array.hasOwnProperty(attr)){return js_array[attr]}else if(['__repr__','__str__'].includes(attr)){return function(js_array){var t=jsobj2pyobj(js_array) return _b_.list[attr]($B.$list(t))}} return function(js_array){var t=jsobj2pyobj(js_array) return _b_.list[attr](t)}} $B.set_func_names(js_list_meta,'builtins') $B.SizedJSObj=$B.make_class('SizedJavascriptObject') $B.SizedJSObj.__bases__=[$B.JSObj] $B.SizedJSObj.__mro__=[$B.JSObj,_b_.object] $B.SizedJSObj.__len__=function(_self){return _self.length} $B.set_func_names($B.SizedJSObj,'builtins') $B.IterableJSObj=$B.make_class('IterableJavascriptObject') $B.IterableJSObj.__bases__=[$B.JSObj] $B.IterableJSObj.__mro__=[$B.JSObj,_b_.object] $B.IterableJSObj.__contains__=function(self,key){if(self.contains !==undefined && typeof self.contains=='function'){return self.contains(key)}else{for(var item of $B.IterableJSObj.__iter__(self).it){if($B.is_or_equals(item,key)){return true}} return false}} $B.IterableJSObj.__iter__=function(_self){return{ __class__:$B.IterableJSObj,it:_self[Symbol.iterator]()}} $B.IterableJSObj.__len__=function(_self){return _self.length} $B.IterableJSObj.__next__=function(_self){var value=_self.it.next() if(! value.done){return jsobj2pyobj(value.value)} $B.RAISE(_b_.StopIteration,'')} $B.set_func_names($B.IterableJSObj,'builtins') var js_array=$B.js_array=$B.make_class('Array') js_array.__class__=js_list_meta js_array.__mro__=[$B.JSObj,_b_.object] js_array.__add__=function(_self,other){var res=_self.slice() if($B.$isinstance(other,js_array)){return _self.slice().concat(other)} for(var item of $B.make_js_iterator(other)){res.push(pyobj2jsobj(item))} return res} js_array.__delitem__=function(_self,key){_self.splice(key,1)} js_array.__eq__=function(_self,other){if($B.$isinstance(other,_b_.list)){return _b_.list.__eq__($B.$list(_self.map(jsobj2pyobj)),other)}else if(other.$is_js_array){if(_self.length !=other.length){return false} for(var i=0,len=_self.length;i -1){return $B.SizedJSObj} return $B.JSObj} $B.JSMeta=$B.make_class("JSMeta") $B.JSMeta.__call__=function(cls){ console.log('create',cls) var extra_args=new Array(arguments.length-1),klass=arguments[0] for(var i=1,len=arguments.length;i < len;i++){extra_args[i-1]=arguments[i]} var new_func=_b_.type.__getattribute__(klass,"__new__") var instance=new_func.apply(null,arguments) if(instance instanceof cls.__mro__[0].$js_func){ var init_func=_b_.type.__getattribute__(klass,"__init__") if(init_func !==_b_.object.__init__){ var args=[instance].concat(extra_args) init_func.apply(null,args)}} return instance} $B.JSMeta.__mro__=[_b_.type,_b_.object] $B.JSMeta.__getattribute__=function(cls,attr){if(cls[attr]!==undefined){return cls[attr]}else if($B.JSMeta[attr]!==undefined){if(attr=='__new__'){return function(){var res=new cls.$js_func(...Array.from(arguments).slice(1)) res.__class__=cls return res}} return $B.JSMeta[attr]}else{ return _b_.type.__getattribute__(cls,attr)}} $B.JSMeta.__init_subclass__=function(){} $B.JSMeta.__new__=function(metaclass,class_name,bases,cl_dict){ var body=` var _b_ = __BRYTHON__.builtins return function(){ if(_b_.dict.$contains_string(cl_dict, '__init__')){ var args = [this] for(var i = 0, len = arguments.length; i < len; i++){ args.push(arguments[i]) } _b_.dict.$getitem_string(cl_dict, '__init__').apply(this, args) }else{ return new bases[0].$js_func(...arguments) } }` var proto=bases[0].$js_func.prototype if(proto instanceof Node){$B.RAISE(_b_.TypeError,`class ${class_name} cannot inherit `+ `a subclass of Node`)} var new_js_class=Function('cl_dict','bases',body)(cl_dict,bases) new_js_class.prototype=Object.create(bases[0].$js_func.prototype) new_js_class.prototype.constructor=new_js_class Object.defineProperty(new_js_class,'$js_func',{value:bases[0].$js_func}) new_js_class.__class__=$B.JSMeta new_js_class.__bases__=[bases[0]] new_js_class.__mro__=[bases[0],_b_.object] new_js_class.__qualname__=new_js_class.__name__=class_name new_js_class.$is_js_class=true for(var item of _b_.dict.$iter_items(cl_dict)){new_js_class[item.key]=item.value} return new_js_class} $B.set_func_names($B.JSMeta,"builtins")})(__BRYTHON__); ; (function($B){ var _b_=$B.builtins var $GeneratorReturn={} $B.generator_return=function(value){return{__class__:$GeneratorReturn,value:value}} $B.generator=$B.make_class("generator",function(func,name){ var res=function(){var gen=func.apply(null,arguments) gen.$name=name ||'generator' gen.$func=func gen.$has_run=false return{ __class__:$B.generator,js_gen:gen}} res.$infos=func.$infos res.$is_genfunc=true res.$name=name return res} ) $B.generator.__iter__=function(self){return self} $B.generator.__next__=function(self){return $B.generator.send(self,_b_.None)} $B.generator.__str__=function(self){var name=self.js_gen.$name ||'generator' if(self.js_gen.$func && self.js_gen.$func.$infos){name=self.js_gen.$func.$infos.__qualname__} return ``} $B.generator.close=function(self){var save_frame_obj=$B.frame_obj if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)} try{$B.generator.throw(self,$B.EXC(_b_.GeneratorExit))}catch(err){if(! $B.is_exc(err,[_b_.GeneratorExit,_b_.StopIteration])){$B.frame_obj=save_frame_obj $B.RAISE(_b_.RuntimeError,"generator ignored GeneratorExit")}} $B.frame_obj=save_frame_obj} $B.generator.send=function(self,value){ var gen=self.js_gen gen.$has_run=true if(gen.$finished){$B.RAISE(_b_.StopIteration,value)} if(gen.gi_running===true){$B.RAISE(_b_.ValueError,"generator already executing")} gen.gi_running=true var save_frame_obj=$B.frame_obj if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)} try{var res=gen.next(value)}catch(err){gen.$finished=true $B.frame_obj=save_frame_obj throw err} if($B.frame_obj !==null && $B.frame_obj.frame===self.$frame){$B.leave_frame()} $B.frame_obj=save_frame_obj if(res.value && res.value.__class__===$GeneratorReturn){gen.$finished=true $B.RAISE(_b_.StopIteration,res.value.value)} gen.gi_running=false if(res.done){$B.RAISE(_b_.StopIteration,res.value)} return res.value} $B.generator.throw=function(){var $=$B.args('throw',4,{self:null,type:null,value:null,traceback:null},['self','type','value','traceback'],arguments,{value:_b_.None,traceback:_b_.None},null,null),self=$.self,type=$.type,value=$.value,traceback=$.traceback var gen=self.js_gen,exc=type if(exc.$is_class){if(! _b_.issubclass(type,_b_.BaseException)){$B.RAISE(_b_.TypeError,"exception value must be an "+ "instance of BaseException")}else if(value===undefined ||value===_b_.None){exc=$B.$call(exc)()}else if($B.$isinstance(value,type)){exc=value}}else{if(value===_b_.None){value=exc}else{exc=$B.$call(exc)(value)}} if(traceback !==_b_.None){exc.$traceback=traceback} var save_frame_obj=$B.frame_obj if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)} var res=gen.throw(exc) $B.frame_obj=save_frame_obj if(res.done){$B.RAISE(_b_.StopIteration,res.value)} return res.value} $B.set_func_names($B.generator,"builtins") $B.async_generator=$B.make_class("async_generator",function(func){var f=function(){var gen=func.apply(null,arguments) var res=Object.create(null) res.__class__=$B.async_generator res.js_gen=gen return res} return f} ) $B.async_generator.__aiter__=function(self){return self} $B.async_generator.__anext__=function(self){return $B.async_generator.asend(self,_b_.None)} $B.async_generator.aclose=function(self){self.js_gen.$finished=true return _b_.None} $B.async_generator.asend=async function(self,value){var gen=self.js_gen if(gen.$finished){$B.RAISE(_b_.StopAsyncIteration,value)} if(gen.ag_running===true){$B.RAISE(_b_.ValueError,"generator already executing")} gen.ag_running=true var save_frame_obj=$B.frame_obj if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)} try{var res=await gen.next(value)}catch(err){gen.$finished=true $B.frame_obj=save_frame_obj throw err} if($B.frame_obj !==null && $B.frame_obj.frame===self.$frame){$B.leave_frame()} $B.frame_obj=save_frame_obj if(res.done){$B.RAISE(_b_.StopAsyncIteration,value)} if(res.value.__class__===$GeneratorReturn){gen.$finished=true $B.RAISE(_b_.StopAsyncIteration,res.value.value)} gen.ag_running=false return res.value} $B.async_generator.athrow=async function(self,type,value,traceback){var gen=self.js_gen,exc=type if(exc.$is_class){if(! _b_.issubclass(type,_b_.BaseException)){$B.RAISE(_b_.TypeError,"exception value must be an "+ "instance of BaseException")}else if(value===undefined){value=$B.$call(exc)()}}else{if(value===undefined){value=exc}else{exc=$B.$call(exc)(value)}} if(traceback !==undefined){exc.$traceback=traceback} var save_frame_obj=$B.frame_obj if(self.$frame){$B.frame_obj=$B.push_frame(self.$frame)} await gen.throw(value) $B.frame_obj=save_frame_obj} $B.set_func_names($B.async_generator,"builtins")})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,object=_b_.object,_window=globalThis function convertDomValue(v){if(v===null ||v===undefined){return _b_.None} return $B.jsobj2pyobj(v)} var py_immutable_to_js=$B.py_immutable_to_js=function(pyobj){if($B.$isinstance(pyobj,_b_.float)){return pyobj.value}else if($B.$isinstance(pyobj,$B.long_int)){return $B.long_int.$to_js_number(pyobj)} return pyobj} function js_immutable_to_py(jsobj){if(typeof jsobj=="number"){if(Number.isSafeInteger(jsobj)){return jsobj}else if(Number.isInteger(jsobj)){return $B.fast_long_int(BigInt(jsobj+''))}else{return $B.fast_float(jsobj)}} return jsobj} function $getPosition(e){var left=0,top=0,width=e.width ||e.offsetWidth,height=e.height ||e.offsetHeight while(e.offsetParent){left+=e.offsetLeft top+=e.offsetTop e=e.offsetParent} left+=e.offsetLeft ||0 top+=e.offsetTop ||0 if(e.parentElement){ var parent_pos=$getPosition(e.parentElement) left+=parent_pos.left top+=parent_pos.top} return{left:left,top:top,width:width,height:height}} var $mouseCoords=$B.$mouseCoords=function(ev){if(ev.type.startsWith("touch")){let res={} res.x=_b_.int.$factory(ev.touches[0].screenX) res.y=_b_.int.$factory(ev.touches[0].screenY) res.__getattr__=function(attr){return this[attr]} res.__class__="MouseCoords" return res} var posx=0,posy=0 if(!ev){ev=_window.event} if(ev.pageX ||ev.pageY){posx=ev.pageX posy=ev.pageY}else if(ev.clientX ||ev.clientY){posx=ev.clientX+document.body.scrollLeft+ document.documentElement.scrollLeft posy=ev.clientY+document.body.scrollTop+ document.documentElement.scrollTop} let res={} res.x=_b_.int.$factory(posx) res.y=_b_.int.$factory(posy) res.__getattr__=function(attr){return this[attr]} res.__class__="MouseCoords" return res} $B.$isNode=function(o){ return( typeof Node==="object" ? o instanceof Node : o && typeof o==="object" && typeof o.nodeType==="number" && typeof o.nodeName==="string" )} $B.$isNodeList=function(nodes){ try{var result=Object.prototype.toString.call(nodes) var re=new RegExp("^\\[object (HTMLCollection|NodeList)\\]$") return(typeof nodes==="object" && re.exec(result)!==null && nodes.length !==undefined && (nodes.length==0 || (typeof nodes[0]==="object" && nodes[0].nodeType > 0)) )}catch(err){return false}} var $DOMEventAttrs_W3C=["NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","type","target","currentTarget","eventPhase","bubbles","cancelable","timeStamp","stopPropagation","preventDefault","initEvent"] var $DOMEventAttrs_IE=["altKey","altLeft","button","cancelBubble","clientX","clientY","contentOverflow","ctrlKey","ctrlLeft","data","dataFld","dataTransfer","fromElement","keyCode","nextPage","offsetX","offsetY","origin","propertyName","reason","recordset","repeat","screenX","screenY","shiftKey","shiftLeft","source","srcElement","srcFilter","srcUrn","toElement","type","url","wheelDelta","x","y"] $B.$isEvent=function(obj){var flag=true for(let attr of $DOMEventAttrs_W3C){if(obj[attr]===undefined){flag=false break}} if(flag){return true} for(let attr of $DOMEventAttrs_IE){if(obj[attr]===undefined){return false}} return true} var $NodeTypes={1:"ELEMENT",2:"ATTRIBUTE",3:"TEXT",4:"CDATA_SECTION",5:"ENTITY_REFERENCE",6:"ENTITY",7:"PROCESSING_INSTRUCTION",8:"COMMENT",9:"DOCUMENT",10:"DOCUMENT_TYPE",11:"DOCUMENT_FRAGMENT",12:"NOTATION"} var Attributes=$B.make_class("Attributes",function(elt){return{__class__:Attributes,elt:elt}} ) Attributes.__contains__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null) if($.self.elt instanceof SVGElement){return $.self.elt.hasAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function"){return $.self.elt.hasAttribute($.key)} return false} Attributes.__delitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null) if(!Attributes.__contains__($.self,$.key)){$B.RAISE(_b_.KeyError,$.key)} if($.self.elt instanceof SVGElement){$.self.elt.removeAttributeNS(null,$.key) return _b_.None}else if(typeof $.self.elt.hasAttribute=="function"){$.self.elt.removeAttribute($.key) return _b_.None}} Attributes.__getitem__=function(){var $=$B.args("__getitem__",2,{self:null,key:null},["self","key"],arguments,{},null,null) if($.self.elt instanceof SVGElement && $.self.elt.hasAttributeNS(null,$.key)){return $.self.elt.getAttributeNS(null,$.key)}else if(typeof $.self.elt.hasAttribute=="function" && $.self.elt.hasAttribute($.key)){return $.self.elt.getAttribute($.key)} $B.RAISE(_b_.KeyError,$.key)} Attributes.__iter__=function(self){self.$counter=0 var attrs=self.elt.attributes,items=[] for(var i=0;i < attrs.length;i++){items.push(attrs[i].name)} self.$items=items return self} Attributes.__next__=function(){var $=$B.args("__next__",1,{self:null},["self"],arguments,{},null,null) if($.self.$counter < $.self.$items.length){var res=$.self.$items[$.self.$counter] $.self.$counter++ return res}else{$B.RAISE(_b_.StopIteration,"")}} Attributes.__setitem__=function(){var $=$B.args("__setitem__",3,{self:null,key:null,value:null},["self","key","value"],arguments,{},null,null) if($.self.elt instanceof SVGElement && typeof $.self.elt.setAttributeNS=="function"){$.self.elt.setAttributeNS(null,$.key,_b_.str.$factory($.value)) return _b_.None}else if(typeof $.self.elt.setAttribute=="function"){$.self.elt.setAttribute($.key,_b_.str.$factory($.value)) return _b_.None} $B.RAISE(_b_.TypeError,"Can't set attributes on element")} Attributes.__repr__=Attributes.__str__=function(self){var attrs=self.elt.attributes,items=[] for(var i=0;i < attrs.length;i++){items.push(attrs[i].name+': "'+ self.elt.getAttributeNS(null,attrs[i].name)+'"')} return '{'+items.join(", ")+'}'} Attributes.get=function(){var $=$B.args("get",3,{self:null,key:null,deflt:null},["self","key","deflt"],arguments,{deflt:_b_.None},null,null) try{return Attributes.__getitem__($.self,$.key)}catch(err){if(err.__class__===_b_.KeyError){return $.deflt}else{throw err}}} Attributes.keys=function(){return Attributes.__iter__.apply(null,arguments)} Attributes.items=function(){var $=$B.args("values",1,{self:null},["self"],arguments,{},null,null),attrs=$.self.elt.attributes,values=[] for(var i=0;i < attrs.length;i++){values.push($B.$list([attrs[i].name,attrs[i].value]))} return _b_.list.__iter__($B.$list(values))} Attributes.values=function(){var $=$B.args("values",1,{self:null},["self"],arguments,{},null,null),attrs=$.self.elt.attributes,values=[] for(var i=0;i < attrs.length;i++){values.push(attrs[i].value)} return _b_.list.__iter__($B.$list(values))} $B.set_func_names(Attributes,"") var DOMEvent=$B.DOMEvent=$B.make_class("DOMEvent",function(evt_name){ return DOMEvent.__new__(DOMEvent,evt_name)} ) DOMEvent.__new__=function(cls,evt_name){var ev=new Event(evt_name) ev.__class__=DOMEvent if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}} if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}} return ev} DOMEvent.__setattr__=function(self,attr,value){self[attr]=value} function dom2svg(svg_elt,coords){ var pt=svg_elt.createSVGPoint() pt.x=coords.x pt.y=coords.y return pt.matrixTransform(svg_elt.getScreenCTM().inverse())} DOMEvent.__getattribute__=function(ev,attr){switch(attr){case '__repr__': case '__str__': return function(){return ''} case 'x': return $mouseCoords(ev).x case 'y': return $mouseCoords(ev).y case 'data': if(ev.dataTransfer !==null && ev.dataTransfer !==undefined){return Clipboard.$factory(ev.dataTransfer)}else if(typeof Worker !=='undefined' && ev.target instanceof Worker){ return $B.structuredclone2pyobj(ev.data)}else if(typeof DedicatedWorkerGlobalScope !=='undefined' && ev.target instanceof DedicatedWorkerGlobalScope){ return $B.structuredclone2pyobj(ev.data)} return convertDomValue(ev.data) case 'target': if(ev.target !==undefined){return DOMNode.$factory(ev.target)} break case 'char': return String.fromCharCode(ev.which) case 'svgX': if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(ev)).x)} $B.RAISE_ATTRIBUTE_ERROR("event target is not an SVG "+ "element",ev,attr) case 'svgY': if(ev.target instanceof SVGSVGElement){return Math.floor(dom2svg(ev.target,$mouseCoords(self)).y)} $B.RAISE_ATTRIBUTE_ERROR("event target is not an SVG "+ "element",ev,attr)} var res=ev[attr] if(res !==undefined){if(typeof res=="function"){var func=function(){var args=[] for(var i=0;i < arguments.length;i++){args.push($B.pyobj2jsobj(arguments[i]))} return res.apply(ev,arguments)} func.$infos={__name__:res.name,__qualname__:res.name} return func} return convertDomValue(res)} throw $B.attr_error(attr,ev)} var $DOMEvent=$B.$DOMEvent=function(ev){ev.__class__=DOMEvent ev.$no_dict=true if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}} if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}} return ev} $B.set_func_names(DOMEvent,"browser") var Clipboard=$B.make_class('Clipboard',function(data){return{ __class__ :Clipboard,__dict__:$B.empty_dict(),data :data}} ) Clipboard.__getitem__=function(self,name){return self.data.getData(name)} Clipboard.__setitem__=function(self,name,value){self.data.setData(name,value)} $B.set_func_names(Clipboard,"") var DOMNode=$B.make_class('DOMNode',function(elt){return elt} ) DOMNode.__add__=function(self,other){ var res=TagSum.$factory() res.children=[self] var pos=1 if($B.$isinstance(other,TagSum)){res.children=res.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.list,_b_.dict,_b_.set,_b_.tuple])){res.children[pos++]=DOMNode.$factory( document.createTextNode(_b_.str.$factory(other)))}else if($B.$isinstance(other,DOMNode)){res.children[pos++]=other}else{ try{res.children=res.children.concat(_b_.list.$factory(other))}catch(err){$B.RAISE(_b_.TypeError,"can't add '"+ $B.class_name(other)+"' object to DOMNode instance")}} return res} DOMNode.__bool__=function(){return true} DOMNode.__contains__=function(self,key){ if(self.nodeType==Node.DOCUMENT_NODE && typeof key=="string"){return document.getElementById(key)!==null} if(self.length !==undefined && typeof self.item=="function"){for(var i=0,len=self.length;i < len;i++){if(self.item(i)===key){return true}}} return false} DOMNode.__del__=function(self){ if(self.parentNode){self.parentNode.removeChild(self)}} DOMNode.__delattr__=function(self,attr){if(self[attr]===undefined){$B.RAISE_ATTRIBUTE_ERROR(`cannot delete DOMNode attribute '${attr}'`,self,attr)} delete self[attr] return _b_.None} DOMNode.__delitem__=function(self,key){if(self.nodeType==Node.DOCUMENT_NODE){ var res=self.getElementById(key) if(res){res.parentNode.removeChild(res)} else{$B.RAISE(_b_.KeyError,key)}}else{ self.parentNode.removeChild(self)}} DOMNode.__dir__=function(self){var res=[] for(let attr in self){if(attr.charAt(0)!="$"){res.push(attr)}} for(let attr in DOMNode){if(res.indexOf(attr)==-1){res.push(attr)}} res.sort() return $B.$list(res)} DOMNode.__eq__=function(self,other){return self==other} DOMNode.__getattribute__=function(self,attr){switch(attr){case "attrs": return Attributes.$factory(self) case "children": case "child_nodes": case "class_name": case "html": case "parent": case "text": return DOMNode[attr](self) case "height": case "left": case "top": case "width": if(self.tagName=="CANVAS" && self[attr]){return self[attr]} if(self instanceof SVGElement){return self[attr].baseVal.value} var computed=window.getComputedStyle(self). getPropertyValue(attr) if(computed !==undefined){if(computed==''){if(self.style[attr]!==undefined){return parseInt(self.style[attr])}else{return 0}} let prop=Math.floor(parseFloat(computed)+0.5) return isNaN(prop)? 0 :prop}else if(self.style[attr]){return parseInt(self.style[attr])}else{$B.RAISE_ATTRIBUTE_ERROR("style."+attr+ " is not set for "+_b_.str.$factory(self),self,attr)} case "x": case "y": if(!(self instanceof SVGElement)){let pos=$getPosition(self) return attr=="x" ? pos.left :pos.top} break case "closest": if(! self[attr]){throw $B.attr_error(self,attr)} return function(){return DOMNode[attr].call(null,self,...arguments)} case "headers": if(self.nodeType==Node.DOCUMENT_NODE){ let req=new XMLHttpRequest(); req.open("GET",document.location,false) req.send(null); var headers=req.getAllResponseHeaders() headers=headers.split("\r\n") let res=$B.empty_dict() for(let header of headers){if(header.strip().length==0){continue} let pos=header.search(":") res.__setitem__(header.substr(0,pos),header.substr(pos+1).lstrip())} return res} break case "location": attr="location" break} if(attr=="select" && self.nodeType==1 && ["INPUT","TEXTAREA"].indexOf(self.tagName.toUpperCase())>-1){return function(selector){if(selector===undefined){self.select() return _b_.None} return DOMNode.select(self,selector)}} if(attr=="query" && self.nodeType==Node.DOCUMENT_NODE){ let res={__class__:Query,_keys :$B.$list([]),_values :{}} let qs=location.search.substr(1).split('&') if(location.search !=""){for(let i=0;i < qs.length;i++){let pos=qs[i].search("="),elts=[qs[i].substr(0,pos),qs[i].substr(pos+1)],key=decodeURIComponent(elts[0]),value=decodeURIComponent(elts[1]) if(res._keys.indexOf(key)>-1){res._values[key].push(value)}else{res._keys.push(key) res._values[key]=[value]}}} return res} var klass=$B.get_class(self) var property=self[attr] if(property !==undefined && self.__class__ && klass.__module__ !="browser.html" && klass.__module__ !="browser.svg" && ! klass.$webcomponent){var from_class=$B.$getattr(klass,attr,null) if(from_class !==null){property=from_class if(typeof from_class==='function'){return property.bind(self,self)}}else{ var bases=self.__class__.__bases__ var show_message=true for(var base of bases){if(base.__module__=="browser.html"){show_message=false break}} if(show_message){from_class=$B.$getattr(self.__class__,attr,_b_.None) if(from_class !==_b_.None){var frame=$B.frame_obj.frame,line=frame.$lineno console.info("Warning: line "+line+", "+self.tagName+ " element has instance attribute '"+attr+"' set."+ " Attribute of class "+$B.class_name(self)+ " is ignored.")}}}} if(property===undefined){ if(self.tagName){var ce=customElements.get(self.tagName.toLowerCase()) if(ce !==undefined && ce.$cls !==undefined){ var save_class=self.__class__ self.__class__=ce.$cls try{let res=_b_.object.__getattribute__(self,attr) self.__class__=save_class return res}catch(err){self.__class__=save_class if(! $B.is_exc(err,[_b_.AttributeError])){throw err}}}}else{return object.__getattribute__(self,attr)}} var res=property if(res !==undefined){if(res===null){return res} if(typeof res==="function"){if(self.__class__ && self.__class__.$webcomponent){var method=$B.$getattr(self.__class__,attr,null) if(method !==null){ return res.bind(self)}} if(res.$function_infos){ return res} var func=(function(f,elt){return function(){var args=[] for(var i=0;i < arguments.length;i++){var arg=arguments[i] if(typeof arg=="function"){ var f1 if(arg.$cache){f1=arg.$cache}else{f1=function(dest_fn){return function(){try{return dest_fn.apply(null,arguments)}catch(err){$B.handle_error(err)}}}(arg) arg.$cache=f1} args.push(f1)}else{args.push($B.pyobj2jsobj(arg))}} var result=f.apply(elt,args) return convertDomValue(result)}})(res,self) func.$infos={__name__ :attr,__qualname__:attr} func.$is_func=true func.$python_function=res return func} if(attr=='style'){return $B.jsobj2pyobj(self[attr])} if(Array.isArray(res)){ return res} return js_immutable_to_py(res)} return object.__getattribute__(self,attr)} DOMNode.__getitem__=function(self,key){if(self.nodeType==Node.DOCUMENT_NODE){ if(typeof key.valueOf()=="string"){let res=self.getElementById(key) if(res){return DOMNode.$factory(res)} $B.RAISE(_b_.KeyError,key)}else{try{let elts=self.getElementsByTagName(key.__name__),res=[] for(let i=0;i < elts.length;i++){res.push(DOMNode.$factory(elts[i]))} return res}catch(err){$B.RAISE(_b_.KeyError,_b_.str.$factory(key))}}}else{if((typeof key=="number" ||typeof key=="boolean")&& typeof self.item=="function"){var key_to_int=_b_.int.$factory(key) if(key_to_int < 0){key_to_int+=self.length} let res=DOMNode.$factory(self.item(key_to_int)) if(res===undefined){$B.RAISE(_b_.KeyError,key)} return res}else if(typeof key=="string" && self.attributes && typeof self.attributes.getNamedItem=="function"){let attr=self.attributes.getNamedItem(key) if(attr !==null){return attr.value} $B.RAISE(_b_.KeyError,key)}}} DOMNode.__hash__=function(self){return self.__hashvalue__===undefined ? (self.__hashvalue__=$B.$py_next_hash--): self.__hashvalue__} DOMNode.__iter__=function(self){ var items=[] if(self.length !==undefined && typeof self.item=="function"){for(let i=0,len=self.length;i < len;i++){items.push(DOMNode.$factory(self.item(i)))}}else if(self.childNodes !==undefined){for(let child of self.childNodes){items.push(DOMNode.$factory(child))}} return $B.$iter(items)} DOMNode.__le__=function(self,other){ if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} if($B.$isinstance(other,TagSum)){for(var i=0;i < other.children.length;i++){self.appendChild(other.children[i])}}else if(typeof other=="string" ||typeof other=="number"){var txt=document.createTextNode(other.toString()) self.appendChild(txt)}else if(other instanceof Node){self.appendChild(other)}else{try{ var items=_b_.list.$factory(other) items.forEach(function(item){DOMNode.__le__(self,item)})}catch(err){$B.RAISE(_b_.TypeError,"can't add '"+ $B.class_name(other)+"' object to DOMNode instance")}} return self } DOMNode.__len__=function(self){return self.length} DOMNode.__mul__=function(self,other){if($B.$isinstance(other,_b_.int)&& other.valueOf()> 0){var res=TagSum.$factory() var pos=res.children.length for(var i=0;i < other.valueOf();i++){res.children[pos++]=DOMNode.clone(self)} return res} $B.RAISE(_b_.ValueError,"can't multiply "+self.__class__+ "by "+other)} DOMNode.__ne__=function(self,other){return ! DOMNode.__eq__(self,other)} DOMNode.__next__=function(self){self.$counter++ if(self.$counter < self.childNodes.length){return DOMNode.$factory(self.childNodes[self.$counter])} $B.RAISE(_b_.StopIteration,"StopIteration")} DOMNode.__radd__=function(self,other){ var res=TagSum.$factory() var txt=DOMNode.$factory(document.createTextNode(other)) res.children=[txt,self] return res} DOMNode.__str__=DOMNode.__repr__=function(self){var attrs=self.attributes,attrs_str="",items=[] if(attrs !==undefined){for(let attr of attrs){items.push(attr.name+'="'+ self.getAttributeNS(null,attr.name)+'"')}} var proto=Object.getPrototypeOf(self) if(proto){var name=proto.constructor.name if(name===undefined){ var proto_str=proto.constructor.toString() name=proto_str.substring(8,proto_str.length-1)} items.splice(0,0,name) return "<"+items.join(" ")+">"} var res=""} DOMNode.__setattr__=function(self,attr,value){ switch(attr){case "left": case "top": case "width": case "height": if($B.$isinstance(value,[_b_.int,_b_.float])&& self.nodeType==1){self.style[attr]=value+"px" return _b_.None}else{$B.RAISE(_b_.ValueError,attr+" value should be"+ " an integer or float, not "+$B.class_name(value))}} if(DOMNode["set_"+attr]!==undefined){return DOMNode["set_"+attr](self,value)} function warn(msg){console.log(msg) var frame=$B.frame_obj.frame if(! frame){return} if($B.get_option('debug')> 0){var file=frame.__file__,lineno=frame.$lineno console.log("module",frame[2],"line",lineno) if($B.file_cache.hasOwnProperty(file)){var src=$B.file_cache[file] console.log(src.split("\n")[lineno-1])}}else{console.log("module",frame[2])}} var proto=Object.getPrototypeOf(self),nb=0 while(!!proto && proto !==Object.prototype && nb++< 10){var descriptors=Object.getOwnPropertyDescriptors(proto) if(!!descriptors && typeof descriptors.hasOwnProperty=="function"){if(descriptors.hasOwnProperty(attr)){if(!descriptors[attr].writable && descriptors[attr].set===undefined){warn("Warning: property '"+attr+ "' is not writable. Use element.attrs['"+ attr+"'] instead.")} break}}else{break} proto=Object.getPrototypeOf(proto)} if(self.style && self.style[attr]!==undefined && attr !='src' ){warn("Warning: '"+attr+"' is a property of element.style")} self[attr]=py_immutable_to_js(value) return _b_.None} DOMNode.__setitem__=function(self,key,value){if(typeof key=="number"){self.childNodes[key]=value}else if(typeof key=="string"){if(self.attributes){if(self instanceof SVGElement){self.setAttributeNS(null,key,value)}else if(typeof self.setAttribute=="function"){self.setAttribute(key,value)}}}} DOMNode.abs_left={__get__:function(self){return $getPosition(self).left},__set__:function(self,value){$B.RAISE_ATTRIBUTE_ERROR("'DOMNode' objectattribute "+ "'abs_left' is read-only",self,'abs_left')}} DOMNode.abs_top={__get__:function(self){return $getPosition(self).top},__set__:function(self,value){$B.RAISE_ATTRIBUTE_ERROR("'DOMNode' objectattribute "+ "'abs_top' is read-only",self,'abs_top')}} DOMNode.attach=DOMNode.__le__ DOMNode.bind=function(){ var $=$B.args("bind",4,{self:null,event:null,func:null,options:null},["self","event","func","options"],arguments,{func:_b_.None,options:_b_.None},null,null),self=$.self,event=$.event,func=$.func,options=$.options if(func===_b_.None){ return function(f){return DOMNode.bind(self,event,f)}} var callback=(function(f){return function(ev){try{return $B.$call(f)($DOMEvent(ev))}catch(err){if(err.__class__ !==undefined){$B.handle_error(err)}else{try{$B.$getattr($B.get_stderr(),"write")(err)} catch(err1){console.log(err)}}}}} )(func) callback.$infos=func.$infos callback.$attrs=func.$attrs ||{} callback.$func=func if(typeof options=="boolean"){self.addEventListener(event,callback,options)}else if(options.__class__===_b_.dict){self.addEventListener(event,callback,_b_.dict.$to_obj(options))}else if(options===_b_.None){self.addEventListener(event,callback,false)} self.$events=self.$events ||{} self.$events[event]=self.$events[event]||[] self.$events[event].push([func,callback]) return self} DOMNode.children=function(self){var res=[] if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} for(var child of self.children){res.push(DOMNode.$factory(child))} return $B.$list(res)} DOMNode.child_nodes=function(self){var res=[] if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} for(var child of self.childNodes){res.push(DOMNode.$factory(child))} return $B.$list(res)} DOMNode.clear=function(){ var $=$B.args("clear",1,{self:null},["self"],arguments,{},null,null),self=$.self if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} while(self.firstChild){self.removeChild(self.firstChild)}} DOMNode.Class=function(self){if(self.className !==undefined){return self.className} return _b_.None} DOMNode.class_name=function(self){return DOMNode.Class(self)} DOMNode.clone=function(self){var res=DOMNode.$factory(self.cloneNode(true)) var events=self.$events ||{} for(var event in events){var evt_list=events[event] evt_list.forEach(function(evt){var func=evt[0] DOMNode.bind(res,event,func)})} return res} DOMNode.closest=function(){ var $=$B.args("closest",2,{self:null,selector:null},["self","selector"],arguments,{},null,null),self=$.self,selector=$.selector if(self.closest===undefined){$B.RAISE_ATTRIBUTE_ERROR(_b_.str.$factory(self)+ " has no attribute 'closest'",self,'closest')} var res=self.closest(selector) if(res===null){$B.RAISE(_b_.KeyError,"no parent with selector "+selector)} return DOMNode.$factory(res)} DOMNode.bindings=function(self){ var res=$B.empty_dict() for(var key in self.$events){_b_.dict.$setitem(res,key,self.$events[key].map(x=> x[1]))} return res} DOMNode.events=function(self,event){self.$events=self.$events ||{} var evt_list=self.$events[event]=self.$events[event]||[],funcs=evt_list.map(x=> x[0]) return $B.$list(funcs)} function make_list(node_list){var res=[] for(var i=0;i < node_list.length;i++){res.push(DOMNode.$factory(node_list[i]))} return $B.$list(res)} DOMNode.get=function(self){ var args=[] for(var i=1;i < arguments.length;i++){args.push(arguments[i])} var $ns=$B.args("get",0,{},[],args,{},null,"kw"),$dict=_b_.dict.$to_obj($ns.kw) if($dict["name"]!==undefined){if(self.getElementsByName===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by name")} return make_list(self.getElementsByName($dict['name']))} if($dict["tag"]!==undefined){if(self.getElementsByTagName===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by tag name")} return make_list(self.getElementsByTagName($dict["tag"]))} if($dict["classname"]!==undefined){if(self.getElementsByClassName===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by class name")} return make_list(self.getElementsByClassName($dict['classname']))} if($dict["id"]!==undefined){if(self.getElementById===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by id")} var id_res=document.getElementById($dict['id']) if(! id_res){return[]} return $B.$list([DOMNode.$factory(id_res)])} if($dict["selector"]!==undefined){if(self.querySelectorAll===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by selector")} return make_list(self.querySelectorAll($dict['selector']))} return $B.$list([])} DOMNode.getContext=function(self){ if(!("getContext" in self)){$B.RAISE_ATTRIBUTE_ERROR("object has no attribute 'getContext'",self,'getContext')} return function(ctx){return $B.jsobj2pyobj(self.getContext(ctx))}} DOMNode.getSelectionRange=function(self){ if(self["getSelectionRange"]!==undefined){return self.getSelectionRange.apply(null,arguments)}} DOMNode.html=function(self){var res=self.innerHTML if(res===undefined){if(self.nodeType==Node.DOCUMENT_NODE && self.body){res=self.body.innerHTML}else{res=_b_.None}} return res} DOMNode.index=function(self,selector){var items if(selector===undefined){items=self.parentElement.childNodes}else{items=self.parentElement.querySelectorAll(selector)} var rank=-1 for(var i=0;i < items.length;i++){if(items[i]===self){rank=i;break}} return rank} DOMNode.inside=function(self,other){ var elt=self while(true){if(other===elt){return true} elt=elt.parentNode if(! elt){return false}}} DOMNode.parent=function(self){if(self.parentElement){return DOMNode.$factory(self.parentElement)} return _b_.None} DOMNode.reset=function(self){ return function(){self.reset()}} DOMNode.scrolled_left={__get__:function(self){return $getPosition(self).left- document.scrollingElement.scrollLeft},__set__:function(self,value){$B.RAISE_ATTRIBUTE_ERROR("'DOMNode' objectattribute "+ "'scrolled_left' is read-only",self,'scrolled_left')}} DOMNode.scrolled_top={__get__:function(self){return $getPosition(self).top- document.scrollingElement.scrollTop},__set__:function(self,value){$B.RAISE_ATTRIBUTE_ERROR("'DOMNode' objectattribute "+ "'scrolled_top' is read-only",self,'scrolled_top')}} DOMNode.select=function(self,selector){ if(self.querySelectorAll===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by selector")} return make_list(self.querySelectorAll(selector))} DOMNode.select_one=function(self,selector){ if(self.querySelector===undefined){$B.RAISE(_b_.TypeError,"DOMNode object doesn't support "+ "selection by selector")} var res=self.querySelector(selector) if(res===null){return _b_.None} return DOMNode.$factory(res)} DOMNode.setSelectionRange=function(){ if(this["setSelectionRange"]!==undefined){return(function(obj){return function(){return obj.setSelectionRange.apply(obj,arguments)}})(this)}else if(this["createTextRange"]!==undefined){return(function(obj){return function(start_pos,end_pos){if(end_pos==undefined){end_pos=start_pos} var range=obj.createTextRange() range.collapse(true) range.moveEnd("character",start_pos) range.moveStart("character",end_pos) range.select()}})(this)}} DOMNode.set_class_name=function(self,arg){self.setAttribute("class",arg)} DOMNode.set_html=function(self,value){if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} self.innerHTML=_b_.str.$factory(value)} DOMNode.set_style=function(self,style){ if(typeof style==='string'){self.style=style return}else if(!$B.$isinstance(style,_b_.dict)){$B.RAISE(_b_.TypeError,"style must be str or dict, not "+ $B.class_name(style))} var items=_b_.list.$factory(_b_.dict.items(style)) for(var i=0;i < items.length;i++){var key=items[i][0],value=items[i][1] if(key.toLowerCase()=="float"){self.style.cssFloat=value self.style.styleFloat=value}else{switch(key){case "top": case "left": case "width": case "height": case "borderWidth": if($B.$isinstance(value,_b_.int)){value=value+"px"}} self.style[key]=value}}} DOMNode.set_text=function(self,value){if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} self.innerText=_b_.str.$factory(value) self.textContent=_b_.str.$factory(value)} DOMNode.set_value=function(self,value){self.value=_b_.str.$factory(value)} DOMNode.submit=function(self){ return function(){self.submit()}} DOMNode.text=function(self){if(self.nodeType==Node.DOCUMENT_NODE){self=self.body} var res=self.innerText ||self.textContent if(res===null){res=_b_.None} return res} DOMNode.toString=function(self){if(self===undefined){return 'DOMNode'} return self.nodeName} DOMNode.trigger=function(self,etype){ if(self.fireEvent){self.fireEvent("on"+etype)}else{var evObj=document.createEvent("Events") evObj.initEvent(etype,true,false) self.dispatchEvent(evObj)}} DOMNode.unbind=function(self,event){ if(! self.$events){return _b_.None} if(event===undefined){for(let evt in self.$events){DOMNode.unbind(self,evt)} return _b_.None} if(self.$events[event]===undefined || self.$events[event].length==0){return _b_.None} var events=self.$events[event] if(arguments.length==2){ for(let evt of events){var callback=evt[1] self.removeEventListener(event,callback,false)} self.$events[event]=[] return _b_.None} for(let i=2;i < arguments.length;i++){let func=arguments[i],flag=false for(let j=0,len=events.length;j < len;j++){if($B.is_or_equals(func,events[j][0])){let _callback=events[j][1] self.removeEventListener(event,_callback,false) events.splice(j,1) flag=true break}} if(! flag){$B.RAISE(_b_.KeyError,'missing callback for event '+event)}}} $B.set_func_names(DOMNode,"builtins") var Query=$B.make_class("query") Query.__contains__=function(self,key){return self._keys.indexOf(key)>-1} Query.__getitem__=function(self,key){ var result=self._values[key] if(result===undefined){$B.RAISE(_b_.KeyError,key)}else if(result.length==1){return result[0]} return result} var Query_iterator=$B.make_iterator_class("query string iterator") Query.__iter__=function(self){return Query_iterator.$factory(self._keys)} Query.__setitem__=function(self,key,value){self._values[key]=[value] return _b_.None} Query.__str__=Query.__repr__=function(self){ var elts=[] for(var key in self._values){for(const val of self._values[key]){elts.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}} if(elts.length==0){return ""}else{return "?"+elts.join("&")}} Query.getfirst=function(self,key,_default){ var result=self._values[key] if(result===undefined){if(_default===undefined){return _b_.None} return _default} return result[0]} Query.getlist=function(self,key){ return $B.$list(self._values[key]??[])} Query.getvalue=function(self,key,_default){try{return Query.__getitem__(self,key)}catch(err){if(_default===undefined){return _b_.None} return _default}} Query.keys=function(self){return self._keys} $B.set_func_names(Query,"") var TagSum=$B.make_class("TagSum",function(){return{ __class__:TagSum,children:[],toString:function(){return "(TagSum)"}}} ) TagSum.appendChild=function(self,child){self.children.push(child)} TagSum.__add__=function(self,other){if($B.get_class(other)===TagSum){self.children=self.children.concat(other.children)}else if($B.$isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.dict,_b_.set,_b_.list])){self.children=self.children.concat( DOMNode.$factory(document.createTextNode(other)))}else{self.children.push(other)} return self} TagSum.__radd__=function(self,other){var res=TagSum.$factory() res.children=self.children.slice() res.children.splice(0,0,DOMNode.$factory(document.createTextNode(other))) return res} TagSum.__repr__=function(self){var res=" " for(var i=0;i < self.children.length;i++){res+=self.children[i] if(self.children[i].toString()=="[object Text]"){res+=" ["+self.children[i].textContent+"]\n"}} return res} TagSum.__str__=TagSum.toString=TagSum.__repr__ TagSum.clone=function(self){var res=TagSum.$factory() for(var i=0;i < self.children.length;i++){res.children.push(self.children[i].cloneNode(true))} return res} $B.set_func_names(TagSum,"") $B.TagSum=TagSum $B.DOMNode=DOMNode})(__BRYTHON__); ; (function($B){$B.pattern_match=function(subject,pattern){var _b_=$B.builtins,frame=$B.frame_obj.frame,locals=frame[1] function bind(pattern,subject){if(pattern.alias){locals[pattern.alias]=subject}} if(pattern.sequence){ if($B.$isinstance(subject,[_b_.str,_b_.bytes,_b_.bytearray])){ return false} let Sequence if($B.imported['collections.abc']){Sequence=$B.imported['collections.abc'].Sequence} let deque if($B.imported['collections']){deque=$B.imported['collections'].deque} let supported=false let klass=subject.__class__ ||$B.get_class(subject) for(let base of[klass].concat(klass.__bases__ ||[])){if(base.$match_sequence_pattern){ supported=true break}else if(base===Sequence ||base==deque){supported=true break}} if((! supported)&& Sequence){ supported=_b_.issubclass(klass,Sequence)} if(! supported){return false} if(pattern.sequence.length==1 && pattern.sequence[0].capture_starred=='_'){return true} let subject_length=_b_.len(subject),nb_fixed_length=0 for(let item of pattern.sequence){if(! item.capture_starred){nb_fixed_length++}} if(subject_length < nb_fixed_length){ return false}else if(subject_length==0 && pattern.sequence.length==0){ return true} let it=_b_.iter(subject),nxt=$B.$getattr(it,'__next__'),store_starred=[],nb_matched_in_subject=0 for(let i=0,len=pattern.sequence.length;i < len;i++){if(pattern.sequence[i].capture_starred){ if(pattern.sequence[i].capture_starred=='_' && i==len-1){bind(pattern,subject) return true} let starred_match_length=subject_length- nb_matched_in_subject-len+i+1 for(let j=0;j < starred_match_length;j++){store_starred.push(nxt())} locals[pattern.sequence[i].capture_starred]= $B.$list(store_starred) nb_matched_in_subject+=starred_match_length}else{let subject_item=nxt() let m=$B.pattern_match(subject_item,pattern.sequence[i]) if(! m){return false} nb_matched_in_subject++}} if(nb_matched_in_subject !=subject_length){return false} bind(pattern,subject) return true} if(pattern.group){if(pattern.group.length==1){ if($B.pattern_match(subject,pattern.group[0])){bind(pattern,subject) return true}}else{ pattern.sequence=pattern.group return $B.pattern_match(subject,pattern)}} if(pattern.or){ for(let item of pattern.or){if($B.pattern_match(subject,item)){bind(pattern,subject) return true}} return false} if(pattern.mapping){ let supported=false let Mapping if($B.imported['collections.abc']){Mapping=$B.imported['collections.abc'].Mapping} let klass=subject.__class__ ||$B.get_class(subject) for(let base of[klass].concat(klass.__bases__ ||[])){ if(base.$match_mapping_pattern ||base===Mapping){supported=true break}} if((! supported)&& Mapping){supported=_b_.issubclass(klass,Mapping)} if(! supported){return false} let matched=[],keys=[] for(let item of pattern.mapping){let key_pattern=item[0],value_pattern=item[1],key if(key_pattern.hasOwnProperty('literal')){key=key_pattern.literal}else if(key_pattern.hasOwnProperty('value')){key=key_pattern.value} if(_b_.list.__contains__(keys,key)){$B.RAISE(_b_.ValueError,'mapping pattern checks '+ 'duplicate key ('+ _b_.str.$factory(key)+')')} keys.push(key) let missing=$B.make_class('missing',function(){return{ __class__:missing}} ) try{let v=$B.$call($B.$getattr(subject,"get"))(key,missing) if(v===missing){ return false} if(! $B.pattern_match(v,value_pattern)){return false} matched.push(key)}catch(err){if($B.is_exc(err,[_b_.KeyError])){return false} throw err}} if(pattern.rest){let rest=$B.empty_dict(),it=_b_.iter(subject),next_key while(true){try{next_key=_b_.next(it)}catch(err){if($B.is_exc(err,[_b_.StopIteration])){locals[pattern.rest]=rest return true} throw err} if(! _b_.list.__contains__(matched,next_key)){_b_.dict.__setitem__(rest,next_key,$B.$getitem(subject,next_key))}}} return true} if(pattern.class){let klass=pattern.class if(! $B.$isinstance(klass,_b_.type)){$B.RAISE(_b_.TypeError,'called match pattern must be a type')} if(! $B.$isinstance(subject,klass)){return false} if(pattern.args.length > 0){if([_b_.bool,_b_.bytearray,_b_.bytes,_b_.dict,_b_.float,_b_.frozenset,_b_.int,_b_.list,_b_.set,_b_.str,_b_.tuple].indexOf(klass)>-1){ if(pattern.args.length > 1){$B.RAISE(_b_.TypeError,'for builtin type '+ $B.class_name(subject)+', a single positional '+ 'subpattern is accepted')} return $B.pattern_match(subject,pattern.args[0])}else{ let match_args=$B.$getattr(klass,'__match_args__',$B.fast_tuple([])) if(! $B.$isinstance(match_args,_b_.tuple)){$B.RAISE(_b_.TypeError,'__match_args__() did not return a tuple')} if(pattern.args.length > match_args.length){$B.RAISE(_b_.TypeError,'__match_args__() returns '+match_args.length+ ' names but '+pattern.args.length+' positional '+ 'arguments were passed')} for(let i=0,len=pattern.args.length;i < len;i++){ let pattern_arg=pattern.args[i],klass_arg=match_args[i] if(typeof klass_arg !=="string"){$B.RAISE(_b_.TypeError,'item in __match_args__ '+ 'is not a string: '+klass_arg)} if(pattern.keywords.hasOwnProperty(klass_arg)){$B.RAISE(_b_.TypeError,'__match_arg__ item '+ klass_arg+' was passed as keyword pattern')} pattern.keywords[klass_arg]=pattern_arg}}} for(let key in pattern.keywords){let v=$B.$getattr(subject,key,null) if(v===null){return false}else if(! $B.pattern_match(v,pattern.keywords[key])){return false}} bind(pattern,subject) return true} if(pattern.capture){if(pattern.capture !='_'){ locals[pattern.capture]=subject} bind(pattern,subject) return true}else if(pattern.capture_starred){ locals[pattern.capture_starred]=$B.$list(subject) return true}else if(pattern.hasOwnProperty('literal')){let literal=pattern.literal if(literal===_b_.None ||literal===_b_.True || literal===_b_.False){ return $B.$is(subject,literal)} if($B.rich_comp('__eq__',subject,literal)){bind(pattern,subject) return true} return false}else if(pattern.hasOwnProperty('value')){if($B.rich_comp('__eq__',subject,pattern.value)){bind(pattern,subject) return true}}else if(subject==pattern){return true} return false}})(__BRYTHON__); ; ;(function($B){var _b_=$B.builtins var coroutine=$B.coroutine=$B.make_class("coroutine") coroutine.close=function(self){self.$sent=true } coroutine.send=function(self){self.$sent=true if(! $B.$isinstance(self,coroutine)){var msg="object is not a coroutine" if(typeof self=="function" && self.$function_infos && self.$function_infos[$B.func_attrs.flags]& 128){msg+='. Maybe you forgot to call the async function ?'} $B.RAISE(_b_.TypeError,msg)} var res=self.$func.apply(null,self.$args) res.then(function(){if(self.$frame_obj){$B.frame_obj=self.$frame_obj}}). catch(function(err){if(err.$frame_obj){$B.frame_obj=err.$frame_obj}}) return res} coroutine.__repr__=coroutine.__str__=function(self){if(self.$func.$function_infos){return ""}else{return ""}} $B.set_func_names(coroutine,"builtins") $B.make_async=func=>{ if(func.$is_genfunc){return func} var f=function(){var args=arguments var res={__class__:coroutine,$args:args,$func:func} if($B.frame_obj !==null){var frame=$B.frame_obj.frame frame.$coroutine=res res.$lineno=frame.$lineno} return res} f.$function_infos=func.$function_infos f.$is_func=true f.$is_async=true f.$args_parser=func.$args_parser return f} $B.promise=function(obj){if(obj.__class__===coroutine){ obj.$frame_obj=$B.frame_obj return coroutine.send(obj)} if(typeof obj=="function"){return obj()} if(obj instanceof Promise ||typeof obj.then=="function"){ obj.frame_obj=$B.frame_obj return obj.then(function(x){$B.frame_obj=obj.frame_obj return $B.jsobj2pyobj(x)}).catch(function(err){$B.frame_obj=obj.frame_obj throw $B.exception(err)})} var awaitable=$B.$getattr(obj,'__await__',null) if(awaitable !==null){ awaitable=$B.$call(awaitable)() if($B.$getattr(awaitable,'__next__',null)===null){$B.RAISE(_b_.TypeError,'__await__() returned non-iterator'+ ` of type '${$B.class_name(awaitable)}'`)} return awaitable} $B.RAISE(_b_.TypeError,`object ${$B.class_name(obj)} `+ `can't be used in 'await' expression`)}})(__BRYTHON__); ; (function($B){$B.builtin_class_flags={builtins:{1073763586:['ModuleNotFoundError','WindowsError','AttributeError','PendingDeprecationWarning','StopAsyncIteration','SystemExit','ResourceWarning','KeyboardInterrupt','FloatingPointError','ChildProcessError','RuntimeWarning','Warning','SystemError','RecursionError','ArithmeticError','PythonFinalizationError','EncodingWarning','TypeError','UnboundLocalError','SyntaxError','UserWarning','AssertionError','ImportError','Exception','RuntimeError','StopIteration','ConnectionRefusedError','ValueError','SyntaxWarning','DeprecationWarning','ConnectionError','OverflowError','BaseException','FileExistsError','EnvironmentError','ImportWarning','InterruptedError','NotImplementedError','ZeroDivisionError','EOFError','PermissionError','MemoryError','ConnectionAbortedError','IndexError','BrokenPipeError','BufferError','KeyError','UnicodeError','UnicodeDecodeError','ReferenceError','FutureWarning','IsADirectoryError','BlockingIOError','OSError','NotADirectoryError','UnicodeTranslateError','ProcessLookupError','FileNotFoundError','GeneratorExit','ConnectionResetError','BaseExceptionGroup','UnicodeWarning','LookupError','NameError','TabError','_IncompleteInputError','IOError','IndentationError','UnicodeEncodeError','TimeoutError','BytesWarning'],1073763848:['ExceptionGroup'],20975874:['bool'],4199682:['bytearray','float'],138417410:['bytes'],21762:['zip','filter','enumerate','property','reversed','map','staticmethod','super','classmethod'],5378:['complex','object'],541087042:['dict'],4216066:['set','frozenset'],20976898:['int'],37770530:['list'],20770:['memoryview'],4386:['range'],20738:['slice'],272635138:['str'],71324962:['tuple'],2155896066:['type'],},types:{20866:['PyCapsule','member_descriptor','getset_descriptor','coroutine','generator','frame','async_generator','classmethod_descriptor','method-wrapper'],22914:['builtin_function_or_method'],20738:['traceback','cell'],4354:['code','NotImplementedType','NoneType','ellipsis'],153858:['function'],20802:['mappingproxy'],153986:['method_descriptor'],22786:['method'],21762:['module'],151938:['wrapper_descriptor'],}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var update=$B.update_obj=function(mod,data){for(let attr in data){mod[attr]=data[attr]}} var modules={} var win=$B.jsobj2pyobj(globalThis) var browser={$package:true,$is_package:true,__initialized__:true,__package__:'browser',__file__:$B.brython_path.replace(new RegExp("/*$","g"),'')+ '/Lib/browser/__init__.py',__BRYTHON__,bind:function(){ var $=$B.args("bind",3,{elt:null,evt:null,options:null},["elt","evt","options"],arguments,{options:_b_.None},null,null) var options=$.options if(typeof options=="boolean"){}else if(options.__class__===_b_.dict){var _options={} for(var key of _b_.dict.$keys_string(options)){_options[key]=_b_.dict.$getitem_string(options,key)} options=_options}else{options==false} return function(callback){if($B.get_class($.elt)===$B.JSObj){ function f(ev){try{return callback($B.jsobj2pyobj(ev))}catch(err){$B.handle_error(err)}} $.elt.addEventListener($.evt,f,options) return callback}else if($B.$isinstance($.elt,$B.DOMNode)){ $B.DOMNode.bind($.elt,$.evt,callback,options) return callback}else if($B.$isinstance($.elt,_b_.str)){ var items=document.querySelectorAll($.elt) for(var i=0;i < items.length;i++){$B.DOMNode.bind($B.DOMNode.$factory(items[i]),$.evt,callback,options)} return callback} try{var it=$B.$iter($.elt) while(true){try{var elt=_b_.next(it) $B.DOMNode.bind(elt,$.evt,callback)}catch(err){if($B.$isinstance(err,_b_.StopIteration)){break} throw err}}}catch(err){if($B.$isinstance(err,_b_.AttributeError)){$B.DOMNode.bind($.elt,$.evt,callback)} throw err} return callback}},console:self.console && $B.jsobj2pyobj(self.console),run_script:function(){var $=$B.args("run_script",2,{src:null,name:null},["src","name"],arguments,{name:"script_"+$B.UUID()},null,null) $B.runPythonSource($.src,$.name)},scope:globalThis,self:win,win:win,window:win} browser.__path__=browser.__file__ if($B.isNode){delete browser.window delete browser.win}else if($B.isWebWorker){browser.is_webworker=true delete browser.window delete browser.win browser.self.send=function(){var $=$B.args('send',1,{message:null},['message'],arguments,{},'args',null),message=$B.pyobj2structuredclone($.message),args=$.args.map($B.pyobj2jsobj) self.postMessage(message,...args)} browser.document=_b_.property.$factory( function(){$B.RAISE(_b_.ValueError,"'document' is not available in Web Workers")},function(self,value){browser.document=value} )}else{browser.is_webworker=false update(browser,{"alert":function(message){window.alert($B.builtins.str.$factory(message ||""))},confirm:$B.jsobj2pyobj(window.confirm),"document":$B.DOMNode.$factory(document),doc:$B.DOMNode.$factory(document), DOMEvent:$B.DOMEvent,DOMNode:$B.DOMNode,load:function(script_url){ var file_obj=$B.builtins.open(script_url) var content=$B.$getattr(file_obj,'read')(); eval(content);},load1:function(script_url,callback){ var script=document.createElement('SCRIPT') script.src=script_url if(callback){script.addEventListener('load',function(){callback()})} document.body.appendChild(script)},mouseCoords:function(ev){return $B.jsobj2pyobj($B.$mouseCoords(ev))},prompt:function(message,default_value){return $B.jsobj2pyobj(window.prompt(message,default_value||''))},reload:function(){ var scripts=document.getElementsByTagName('script'),js_scripts=[] scripts.forEach(function(script){if(script.type===undefined || script.type=='text/javascript'){js_scripts.push(script) if(script.src){console.log(script.src)}}}) for(var mod in $B.imported){if($B.imported[mod].$last_modified){console.log('check',mod,$B.imported[mod].__file__,$B.imported[mod].$last_modified)}else{console.log('no date for mod',mod)}}},URLParameter:function(name){name=name.replace(/[[]/,"\\[").replace(/[\]]/,"\\]"); var regex=new RegExp("[\\?&]"+name+"=([^&#]*)"),results=regex.exec(location.search); results=results===null ? "" : decodeURIComponent(results[1].replace(/\+/g," ")); return $B.builtins.str.$factory(results);}}) modules['browser.html']=(function($B){var _b_=$B.builtins var TagSum=$B.TagSum function makeTagDict(tagName){ var dict={__class__:_b_.type,__name__:tagName,__module__:"browser.html",__qualname__:tagName} dict.__init__=function(){var $ns=$B.args('__init__',1,{self:null},['self'],arguments,{},'args','kw'),self=$ns['self'],args=$ns['args'] if(args.length==1){var first=args[0] if($B.$isinstance(first,[_b_.str,_b_.int,_b_.float])){ self.innerHTML=_b_.str.$factory(first)}else if(first.__class__===TagSum){for(var i=0,len=first.children.length;i < len;i++){self.appendChild(first.children[i])}}else{if($B.$isinstance(first,$B.DOMNode)){self.appendChild(first)}else{try{ var items=_b_.list.$factory(first) for(var item of items){$B.DOMNode.__le__(self,item)}}catch(err){if($B.get_option('debug',err)> 1){console.log(err,err.__class__,err.args) console.log("first",first) console.log(arguments)} throw err}}}} for(var item of _b_.dict.$iter_items($ns.kw)){ var arg=item.key,value=item.value if(arg.toLowerCase().substr(0,2)=="on"){ $B.DOMNode.__setattr__(self,arg,value)}else if(arg.toLowerCase()=="style"){$B.DOMNode.set_style(self,value)}else{if(value !==false){ try{ arg=$B.imported["browser.html"]. attribute_mapper(arg) self.setAttribute(arg,$B.pyobj2jsobj(value))}catch(err){$B.RAISE(_b_.ValueError,"can't set attribute "+arg)}}}}} dict.__mro__=[$B.DOMNode,$B.builtins.object] dict.__new__=function(cls){ var res=document.createElement(tagName) if(cls !==html[tagName]){ res.__class__=cls} return res} dict.__rmul__=function(self,num){return $B.DOMNode.__mul__(self,num)} $B.set_func_names(dict,"browser.html") return dict} function makeFactory(klass){ return(function(k){return function(){var res if(k.__name__=='SVG'){res=$B.DOMNode.$factory( document.createElementNS("http://www.w3.org/2000/svg","svg"),true)}else{try{res=document.createElement(k.__name__)}catch(err){console.log('error '+err) console.log('creating element',k.__name__) throw err}} var init=$B.$getattr(k,"__init__",null) if(init !==null){init(res,...arguments)} return res}})(klass)} var tags=['A','ABBR','ACRONYM','ADDRESS','APPLET','AREA','B','BASE','BASEFONT','BDO','BIG','BLOCKQUOTE','BODY','BR','BUTTON','CAPTION','CENTER','CITE','CODE','COL','COLGROUP','DD','DEL','DFN','DIR','DIV','DL','DT','EM','FIELDSET','FONT','FORM','FRAME','FRAMESET','H1','H2','H3','H4','H5','H6','HEAD','HR','HTML','I','IFRAME','IMG','INPUT','INS','ISINDEX','KBD','LABEL','LEGEND','LI','LINK','MAP','MENU','META','NOFRAMES','NOSCRIPT','OBJECT','OL','OPTGROUP','OPTION','P','PARAM','PRE','Q','S','SAMP','SCRIPT','SELECT','SMALL','SPAN','STRIKE','STRONG','STYLE','SUB','SUP','SVG','TABLE','TBODY','TD','TEXTAREA','TFOOT','TH','THEAD','TITLE','TR','TT','U','UL','VAR', 'ARTICLE','ASIDE','AUDIO','BDI','CANVAS','COMMAND','DATA','DATALIST','EMBED','FIGCAPTION','FIGURE','FOOTER','HEADER','KEYGEN','MAIN','MARK','MATH','METER','NAV','OUTPUT','PROGRESS','RB','RP','RT','RTC','RUBY','SECTION','SOURCE','TEMPLATE','TIME','TRACK','VIDEO','WBR', 'DETAILS','DIALOG','MENUITEM','PICTURE','SUMMARY'] var html={} html.tags=$B.empty_dict() function maketag(tagName,ComponentClass){ if(!(typeof tagName=='string')){$B.RAISE(_b_.TypeError,"html.maketag expects a string as argument")} if(html[tagName]!==undefined){$B.RAISE(_b_.ValueError,"cannot reset class for " +tagName)} var klass=makeTagDict(tagName) klass.$factory=makeFactory(klass,ComponentClass) html[tagName]=klass _b_.dict.$setitem(html.tags,tagName,html[tagName]) return klass} for(var tagName of tags){maketag(tagName)} html.maketag=maketag html.attribute_mapper=function(attr){return attr.replace(/_/g,'-')} return html})(__BRYTHON__)} modules['browser']=browser $B.UndefinedType=$B.make_class("UndefinedType",function(){return $B.Undefined} ) $B.UndefinedType.__mro__=[_b_.object] $B.UndefinedType.__bool__=function(){return false} $B.UndefinedType.__repr__=function(){return ""} $B.UndefinedType.__str__=$B.UndefinedType.__repr__; $B.Undefined={__class__:$B.UndefinedType} $B.set_func_names($B.UndefinedType,"javascript") var super_class=$B.make_class("JavascriptSuper",function(){ var res=_b_.super.$factory() var js_constr=res.__thisclass__.__bases__[0] return function(){var obj=new js_constr.$js_func(...arguments) for(var attr in obj){res.__self_class__.__dict__[attr]=$B.jsobj2pyobj(obj[attr])} return obj}} ) super_class.__getattribute__=function(self,attr){if(attr=="__init__" ||attr=="__call__"){return self.__init__} return $B.$getattr(self.__self_class__,attr)} $B.set_func_names(super_class,"javascript") modules['javascript']={"this":function(){ if($B.js_this===undefined){return $B.builtins.None} return $B.jsobj2pyobj($B.js_this)},Array:$B.js_array,Date:self.Date && $B.jsobj2pyobj(self.Date),extends:function(js_constr){if((!js_constr.$js_func)|| ! js_constr.$js_func.toString().startsWith('class ')){console.log(js_constr) $B.RAISE(_b_.TypeError,'argument of extend must be a Javascript class')} js_constr.__class__=_b_.type return function(obj){obj.__bases__.splice(0,0,js_constr) obj.__mro__.splice(0,0,js_constr) return obj}},import_js:function(){ var $=$B.args('import_js',2,{url:null,alias:null},['url','alias'],arguments,{alias:_b_.None},null,null),url=$.url,alias=$.alias var xhr=new XMLHttpRequest(),result xhr.open('GET',url,false) xhr.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var js=this.responseText+'\nreturn $module',f=new Function(js) var $module=f() if(typeof $module !=='undefined'){result=$B.module.$factory(alias) for(var key in $module){result[key]=$B.jsobj2pyobj($module[key])} result.__file__=url}else{console.log(this.responseText) result=$B.EXC(_b_.ImportError,'Javascript '+ `module at ${url} doesn't define $module`)}}else{result=$B.EXC(_b_.ModuleNotFoundError,url)}}} xhr.send() if($B.$isinstance(result,_b_.BaseException)){$B.handle_error(result)}else{if(alias===_b_.None){ var name=url.split('.') if(name.length > 1){name.pop()} alias=name.join('.') result.__name__=alias} $B.imported[alias]=result var frame=$B.frame_obj.frame frame[1][alias]=result}},import_modules:function(refs,callback,loaded){ if(loaded===undefined){loaded=[]} if(! Array.isArray(refs)){$B.RAISE(_b_.TypeError,`first argument must be a list, got ${$B.class_name(refs)}`)} if(refs.length > 1){var ref=refs.shift() import(ref).then(function(module){loaded.push(module) $B.imported.javascript.import_modules(refs,callback,loaded)}).catch($B.show_error)}else{import(refs[0]).then(function(module){loaded.push(module) return $B.$call(callback).apply(null,loaded)}).catch($B.show_error)}},import_scripts:function(refs,callback,loaded){ console.log('import scripts',refs) if(loaded===undefined){loaded=[]} if(! Array.isArray(refs)){$B.RAISE(_b_.TypeError,`first argument must be a list, got ${$B.class_name(refs)}`)} if(refs.length > 0){var ref=refs.shift() var script=document.createElement('script') script.src=ref script.addEventListener('load',function(){loaded.push(script) $B.imported.javascript.import_scripts(refs,callback,loaded)} ) document.body.appendChild(script)}else{return $B.$call(callback).apply(null,loaded)}},JSObject:$B.JSObj,JSON:{__class__:$B.make_class("JSON"),parse:function(){return $B.structuredclone2pyobj( JSON.parse.apply(this,arguments))},stringify:function(obj,replacer,space){return JSON.stringify($B.pyobj2structuredclone(obj,false),$B.jsobj2pyobj(replacer),space)}},jsobj2pyobj:function(obj){return $B.jsobj2pyobj(obj)},load:function(script_url){console.log('"javascript.load" is deprecrated. '+ 'Use browser.load instead.') var file_obj=$B.builtins.open(script_url) var content=$B.$getattr(file_obj,'read')() eval(content)},Math:self.Math && $B.jsobj2pyobj(self.Math),NULL:null,NullType:$B.make_class('NullType'),Number:self.Number && $B.jsobj2pyobj(self.Number),py2js:function(src,module_name){if(module_name===undefined){module_name='__main__'+$B.UUID()} var js=$B.py2js({src,filename:''},module_name,module_name,$B.builtins_scope).to_js() return $B.format_indent(js,0)},pyobj2jsobj:function(obj){return $B.pyobj2jsobj(obj)},RegExp:self.RegExp && $B.jsobj2pyobj(self.RegExp),String:self.String && $B.jsobj2pyobj(self.String),"super":super_class,UNDEFINED:$B.Undefined,UndefinedType:$B.UndefinedType} modules.javascript.NullType.__module__='javascript' modules.javascript.NullType.__eq__=function(_self,other){ return other===null ||other===$B.Undefined} modules.javascript.NullType.__repr__=function(_self){ return ''} $B.set_func_names(modules.javascript.NullType,'javascript') modules.javascript.UndefinedType.__module__='javascript' var $io=$B.$io=$B.make_class("io",function(out){return{ __class__:$io,__dict__:$B.empty_dict(),out,encoding:'utf-8'}} ) $io.flush=function(self){if(self.buf){ var s=self.buf.join(''),chr0=String.fromCodePoint(0) s=s.replace(new RegExp(chr0,'g'),' ') console[self.out](s) self.buf=[]}} $io.write=function(self,msg){ if(self.buf===undefined){self.buf=[]} if(typeof msg !="string"){$B.RAISE(_b_.TypeError,"write() argument must be str, not "+ $B.class_name(msg))} self.buf.push(msg) return _b_.None} modules['_sys']={_getframe :function(){var $=$B.args("_getframe",1,{depth:null},['depth'],arguments,{depth:0},null,null),depth=$.depth,frame_obj=$B.frame_obj for(var i=0;i < depth;i++){frame_obj=frame_obj.prev} var res=frame_obj.frame res.$pos=$B.count_frames()-depth-1 return res},breakpointhook:function(){var hookname=$B.$options.breakpoint,modname,dot,funcname,hook if(hookname===undefined){hookname="pdb.set_trace"} [modname,dot,funcname]=_b_.str.rpartition(hookname,'.') if(dot==""){modname="builtins"} try{$B.$import(modname) hook=$B.$getattr($B.imported[modname],funcname)}catch(err){console.warn("cannot import breakpoint",hookname) return _b_.None} return $B.$call(hook).apply(null,arguments)},exc_info:function(){var frame_obj=$B.frame_obj,frame,exc while(frame_obj !==null){frame=frame_obj.frame exc=frame[1].$current_exception if(exc){return _b_.tuple.$factory([exc.__class__,exc,$B.$getattr(exc,"__traceback__")])} frame_obj=frame_obj.prev} return _b_.tuple.$factory([_b_.None,_b_.None,_b_.None])},excepthook:function(exc_class,exc_value){$B.show_error(exc_value)},exception:function(){var frame_obj=$B.frame_obj,frame,exc while(frame_obj !==null){frame=frame_obj.frame exc=frame[1].$current_exception if(exc !==undefined){return exc} frame_obj=frame_obj.prev} return _b_.None},executable:$B.strip_host($B.brython_path+'brython.js'),float_repr_style:'short',getdefaultencoding:function(){return 'utf-8'},getrecursionlimit:function(){return $B.recursion_limit},getrefcount:function(){return 0},gettrace:function(){return $B.tracefunc ||_b_.None},getunicodeinternedsize:function(){ return 0},last_exc:_b_.property.$factory( function(){return $B.imported._sys.exception()},function(value){$B.frame_obj.frame.$current_exception=value} ),modules:_b_.property.$factory( function(){return $B.obj_dict($B.imported)},function(){$B.RAISE(_b_.TypeError,"Read only property 'sys.modules'")} ),path:_b_.property.$factory( function(){var filename=$B.get_filename_for_import() return $B.$list($B.import_info[filename].path)},function(self,value){var filename=$B.get_filename_for_import() $B.import_info[filename].path=value} ),meta_path:_b_.property.$factory( function(){var filename=$B.get_filename() return $B.$list($B.import_info[filename].meta_path)},function(self,value){var filename=$B.get_filename() $B.import_info[filename].meta_path=value} ),path_hooks:_b_.property.$factory( function(){var filename=$B.get_filename() return $B.$list($B.import_info[filename].path_hooks)},function(self,value){var filename=$B.get_filename() $B.import_info[filename].path_hooks=value} ),path_importer_cache:_b_.property.$factory( function(){return _b_.dict.$factory($B.jsobj2pyobj($B.path_importer_cache))},function(){$B.RAISE(_b_.TypeError,"Read only property"+ " 'sys.path_importer_cache'")} ),setrecursionlimit:function(value){$B.recursion_limit=value},settrace:function(){var $=$B.args("settrace",1,{tracefunc:null},['tracefunc'],arguments,{},null,null) $B.tracefunc=$.tracefunc $B.frame_obj.frame.$f_trace=$B.tracefunc $B.tracefunc.$current_frame_id=$B.frame_obj.frame[0] return _b_.None},stderr:console.error !==undefined ? $io.$factory("error"): $io.$factory("log"),stdout:$io.$factory("log"),stdin:_b_.property.$factory( function(){return $B.stdin},function(self,value){$B.stdin=value} ),vfs:_b_.property.$factory( function(){if($B.hasOwnProperty("VFS")){return $B.obj_dict($B.VFS)}else{return _b_.None}},function(){$B.RAISE(_b_.TypeError,"Read only property 'sys.vfs'")} )} var WarningMessage=$B.make_class("WarningMessage",function(){var $=$B.make_args("WarningMessage",8,{message:null,category:null,filename:null,lineno:null,file:null,line:null,source:null},['message','category','filename','lineno','file','line','source'],arguments,{file:_b_.None,line:_b_.None,source:_b_.None},null,null) return{ __class__:WarningMessage,message:$.message,category:$.category,filename:$.filename,lineno:$.lineno,file:$.file,line:$.line,source:$.source,_category_name:_b_.bool.$factory($.category)? $B.$getattr($.category,"__name__"):_b_.None}} ) modules._warnings={_defaultaction:"default",_filters_mutated:function(){},_onceregistry:$B.empty_dict(),filters:$B.$list([$B.fast_tuple(['default',_b_.None,_b_.DeprecationWarning,'__main__',0]),$B.fast_tuple(['ignore',_b_.None,_b_.DeprecationWarning,_b_.None,0]),$B.fast_tuple(['ignore',_b_.None,_b_.PendingDeprecationWarning,_b_.None,0]),$B.fast_tuple(['ignore',_b_.None,_b_.ImportWarning,_b_.None,0]),$B.fast_tuple(['ignore',_b_.None,_b_.ResourceWarning,_b_.None,0]) ]),warn:function(){ var $=$B.args('warn',4,{message:null,category:null,stacklevel:null,source:null},['message','category','stacklevel','source'],arguments,{category:_b_.UserWarning,stacklevel:1,source:_b_.None},null,null),message=$.message,category=$.category,stacklevel=$.stacklevel if($B.$isinstance(message,_b_.Warning)){category=$B.get_class(message)} var filters if($B.imported.warnings){filters=$B.imported.warnings.filters}else{filters=modules._warnings.filters} if(filters[0][0]=='error'){var syntax_error=$B.EXC(_b_.SyntaxError,message.args[0]) syntax_error.args[1]=[message.filename,message.lineno,message.offset,message.line] syntax_error.filename=message.filename syntax_error.lineno=message.lineno syntax_error.offset=message.offset syntax_error.line=message.line throw syntax_error} var warning_message,filename,file,lineno,line if(category===_b_.SyntaxWarning){filename=message.filename,lineno=message.lineno,line=message.text var src=$B.file_cache[file] if(src){var lines=src.split('\n'),line=lines[lineno-1]} warning_message={__class__:WarningMessage,message:message,category,filename,lineno,file:_b_.None,line,source:_b_.None,_category_name:category.__name__}}else{let frame_rank=Math.max(0,$B.count_frames()-stacklevel) var frame=$B.get_frame_at(frame_rank) file=frame.__file__ let f_code=$B._frame.f_code.__get__(frame),src=$B.file_cache[file] lineno=message.lineno ||frame.$lineno line=src ? src.split('\n')[lineno-1]:null warning_message={__class__:WarningMessage,message:message,category,filename:message.filename ||f_code.co_filename,lineno,file:_b_.None,line:line ||_b_.None,source:_b_.None,_category_name:category.__name__}} if($B.imported.warnings){$B.imported.warnings._showwarnmsg_impl(warning_message)}else{var trace='' if(file && lineno){trace+=`${file}:${lineno}: `} trace+=$B.class_name(message)+': '+message.args[0] if(line){trace+='\n '+line.trim()} var stderr=$B.get_stderr() $B.$getattr(stderr,'write')(trace+'\n') var flush=$B.$getattr(stderr,'flush',_b_.None) if(flush !==_b_.None){flush()}} return _b_.None},warn_explicit:function(){ console.log("warn_explicit",arguments)}} var MAX_CANDIDATE_ITEMS=750,MOVE_COST=2,CASE_COST=1,SIZE_MAX=65535 function LEAST_FIVE_BITS(n){return((n)& 31)} function levenshtein_distance(a,b,max_cost){ if(a==b){return 0} if(a.length < b.length){[a,b]=[b,a]} while(a.length && a[0]==b[0]){a=a.substr(1) b=b.substr(1)} while(a.length && a[a.length-1]==b[b.length-1]){a=a.substr(0,a.length-1) b=b.substr(0,b.length-1)} if(b.length==0){return a.length*MOVE_COST} if((b.length-a.length)*MOVE_COST > max_cost){return max_cost+1} var buffer=[] for(var i=0;i < a.length;i++){ buffer[i]=(i+1)*MOVE_COST} var result=0 for(var b_index=0;b_index < b.length;b_index++){var code=b[b_index] var distance=result=b_index*MOVE_COST; var minimum=SIZE_MAX; for(var index=0;index < a.length;index++){ var substitute=distance+substitution_cost(code,a[index]) distance=buffer[index] var insert_delete=Math.min(result,distance)+MOVE_COST result=Math.min(insert_delete,substitute) buffer[index]=result if(result < minimum){minimum=result}} if(minimum > max_cost){ return max_cost+1}} return result} function substitution_cost(a,b){if(LEAST_FIVE_BITS(a)!=LEAST_FIVE_BITS(b)){ return MOVE_COST} if(a==b){return 0} if(a.toLowerCase()==b.toLowerCase()){return CASE_COST} return MOVE_COST} modules['_suggestions']={_generate_suggestions:function(dir,name){if(dir.length >=MAX_CANDIDATE_ITEMS){return null} var suggestion_distance=2**52,suggestion=null for(var item of dir){ var max_distance=(name.length+item.length+3)*MOVE_COST/6 max_distance=Math.min(max_distance,suggestion_distance-1) var current_distance= levenshtein_distance(name,item,max_distance) if(current_distance > max_distance){continue} if(!suggestion ||current_distance < suggestion_distance){suggestion=item suggestion_distance=current_distance}} if(suggestion==name){ return null} return suggestion}} var responseType={"text":"text","binary":"arraybuffer","dataURL":"arraybuffer"} function handle_kwargs(kw,method){var result={cache:false,format:'text',mode:'text',headers:{}} for(let item of _b_.dict.$iter_items(kw)){let key=item.key,value=item.value if(key=="data"){var params=value if(typeof params=="string" ||params instanceof FormData){result.body=params}else if($B.$isinstance(params,_b_.bytes)){result.body=new ArrayBuffer(params.source.length) var array=new Int8Array(data) for(let i=0,len=params.source.length;i < len;i++){array[i]=params.source[i]}}else{if(params.__class__ !==_b_.dict){$B.RAISE(_b_.TypeError,"wrong type for data, "+ "expected dict, bytes or str, got "+ $B.class_name(params))} var items=[] for(let subitem of _b_.dict.$iter_items(params)){items.push(encodeURIComponent(subitem.key)+"="+ encodeURIComponent($B.pyobj2jsobj(subitem.value)))} result.body=items.join("&")}}else if(key=="headers"){if(! $B.$isinstance(value,_b_.dict)){$B.RAISE(_b_.ValueError,"headers must be a dict, not "+$B.class_name(value))} for(let subitem of _b_.dict.$iter_items(value)){result.headers[subitem.key.toLowerCase()]=subitem.value}}else if(["cache","format","mode"].includes(key)){result[key]=value}} if(method=="post"){ if(! result.headers.hasOwnProperty("content-type")){result.headers["Content-Type"]="application/x-www-form-urlencoded"}} return result} var HTTPRequest=$B.make_class("Request") HTTPRequest.data=_b_.property.$factory(function(self){if(self.format=="binary"){var view=new Uint8Array(self.response) return _b_.bytes.$factory(Array.from(view))}else if(self.format=="text"){return self.responseText}else if(self.format=="dataURL"){var base64String=btoa(String.fromCharCode.apply(null,new Uint8Array(self.response))) return "data:"+self.getResponseHeader("Content-Type")+ ";base64,"+base64String}}) HTTPRequest.response_headers=_b_.property.$factory(function(self){var headers=self.getAllResponseHeaders() if(headers===null){return _b_.None} var res=$B.empty_dict() if(headers.length > 0){ var lines=headers.trim().split(/[\r\n]+/) lines.forEach(function(line){var parts=line.split(': ') var header=parts.shift() var value=parts.join(': ') _b_.dict.$setitem(res,header,value)})} return res}) var Future=$B.make_class("Future",function(){var methods={} var promise=new Promise(function(resolve,reject){methods.resolve=resolve methods.reject=reject}) promise._methods=methods promise._done=false promise.__class__=Future return promise} ) Future.done=function(){var $=$B.args('done',1,{self:null},['self'],arguments,{},null,null) return !! $.self._done} Future.set_result=function(){var $=$B.args('set_result',2,{self:null,value:null},['self','value'],arguments,{},null,null) $.self._done=true $.self._methods.resolve($.value) return _b_.None} Future.set_exception=function(){var $=$B.args('set_exception',2,{self:null,exception:null},['self','exception'],arguments,{},null,null) $.self._done=true $.self._methods.reject($.exception) return _b_.None} $B.set_func_names(Future,'browser.aio') modules['browser.aio']={ajax:function(){var $=$B.args("ajax",2,{method:null,url:null},["method","url"],arguments,{},null,"kw"),method=$.method.toUpperCase(),url=$.url,kw=$.kw var args=handle_kwargs(kw,"get") if(method=="GET" && ! args.cache){url=url+"?ts"+(new Date()).getTime()+"=0"} if(args.body && method=="GET"){url=url+(args.cache ? "?" :"&")+args.body} var func=function(){return new Promise(function(resolve){var xhr=new XMLHttpRequest() xhr.open(method,url,true) for(var key in args.headers){xhr.setRequestHeader(key,args.headers[key])} xhr.format=args.format xhr.responseType=responseType[args.format] xhr.onreadystatechange=function(){if(this.readyState==4){this.__class__=HTTPRequest resolve(this)}} if(args.body && ['POST','PUT','DELETE','PATCH'].indexOf(method)>-1){xhr.send(args.body)}else{xhr.send()}})} func.$infos={__name__:"ajax_"+method} func.$function_infos=[] func.$function_infos[$B.func_attrs.name]=`ajax_${method}` return{ __class__:$B.coroutine,$args:[url,args],$func:func}},event:function(){ var $=$B.args("event",1,{element:null},["element"],arguments,{},"names",null),element=$.element,names=$.names return new Promise(function(resolve){var callbacks=[] names.forEach(function(name){var callback=function(evt){ callbacks.forEach(function(items){$B.DOMNode.unbind(element,items[0],items[1])}) resolve($B.$DOMEvent(evt))} callbacks.push([name,callback]) $B.DOMNode.bind(element,name,callback)})})},get:function(){return $B.imported['browser.aio'].ajax.bind(null,"GET").apply(null,arguments)},iscoroutine:function(f){return f.__class__===$B.coroutine},iscoroutinefunction:function(f){return(f.$function_infos[$B.func_attrs.flags]& 128)!=0},post:function(){return $B.imported['browser.aio'].ajax.bind(null,"POST").apply(null,arguments)},run:function(){var handle_success=function(){$B.leave_frame()},handle_error=$B.show_error var $=$B.args("run",3,{coro:null,onsuccess:null,onerror:null},["coro","onsuccess","onerror"],arguments,{onsuccess:handle_success,onerror:handle_error},null,null),coro=$.coro,onsuccess=$.onsuccess,onerror=$.onerror var save_frame_obj=$B.frame_obj $B.coroutine.send(coro).then(onsuccess).catch(onerror) $B.frame_obj=save_frame_obj return _b_.None},sleep:function(seconds){if(seconds.__class__===_b_.float){seconds=seconds.value}else if(typeof seconds !="number"){$B.RAISE(_b_.TypeError,"'sleep' argument must be "+ "int or float, not "+$B.class_name(seconds))} var func=function(){return new Promise(resolve=> setTimeout( function(){resolve(_b_.None)},1000*seconds))} func.$infos={__name__:"sleep"} func.$function_infos=[] func.$function_infos[$B.func_attrs.name]='sleep' return{ __class__:$B.coroutine,$args:[seconds],$func:func}},Future,__getattr__:function(attr){ $B.$import('_aio') return $B.$getattr($B.imported._aio,attr)}} function load(name,module_obj){ module_obj.__class__=$B.module module_obj.__name__=name $B.imported[name]=module_obj for(var attr in module_obj){if(typeof module_obj[attr]=='function'){module_obj[attr].$infos={__module__:name,__name__:attr,__qualname__:name+'.'+attr} $B.set_function_infos(module_obj[attr],{__module__:name,__name__:attr,__qualname__:name+'.'+attr} )}}} for(let attr in modules){load(attr,modules[attr])} if(!($B.isWebWorker ||$B.isNode)){modules['browser'].html=modules['browser.html'] modules['browser'].aio=modules['browser.aio']} _b_.__builtins__=$B.module.$factory('__builtins__','Python builtins') for(let attr in _b_){_b_.__builtins__[attr]=_b_[attr] $B.builtins_scope.binding[attr]=true if(_b_[attr].$is_class){if(_b_[attr].__bases__){_b_[attr].__bases__.__class__=_b_.tuple}else{_b_[attr].__bases__=$B.fast_tuple([_b_.object])}}} _b_.__builtins__.__setattr__=function(attr,value){_b_[attr]=value} $B.method_descriptor.__getattribute__=$B.function.__getattribute__ $B.wrapper_descriptor.__getattribute__=$B.function.__getattribute__ _b_.type.__dict__=$B.mappingproxy.$factory(_b_.type.__dict__) for(var name in _b_){var builtin=_b_[name] if(_b_[name].__class__===_b_.type){_b_[name].__qualname__=_b_[name].__qualname__ ?? name _b_[name].__module__='builtins' _b_[name].__name__=_b_[name].__name__ ?? name _b_[name].$is_builtin_class=true $B.builtin_classes.push(_b_[name]) for(var key in _b_[name]){var value=_b_[name][key] if(value===undefined ||value.__class__ || typeof value !='function'){continue}else if(key=="__new__"){value.__class__=$B.builtin_function_or_method}else if(key.startsWith("__")){value.__class__=$B.wrapper_descriptor}else{value.__class__=$B.method_descriptor} value.__objclass__=_b_[name]}}else if(typeof builtin=='function'){builtin.$infos={__name__:name,__qualname__:name,__dict__:$B.empty_dict()} $B.set_function_infos(builtin,{__name__:name,__qualname__:name} )}} for(let attr in $B){if(Array.isArray($B[attr])){$B[attr].__class__=_b_.list}} $B.cell=$B.make_class("cell",function(value){return{ __class__:$B.cell,$cell_contents:value}} ) $B.cell.cell_contents=$B.$call(_b_.property)( function(self){if(self.$cell_contents===null){$B.RAISE(_b_.ValueError,"empty cell")} return self.$cell_contents},function(self,value){self.$cell_contents=value} ) var $comps=Object.values($B.$comps).concat(["eq","ne"]) $comps.forEach(function(comp){var op="__"+comp+"__" $B.cell[op]=(function(op){return function(self,other){if(! $B.$isinstance(other,$B.cell)){return _b_.NotImplemented} if(self.$cell_contents===null){if(other.$cell_contents===null){return op=="__eq__"}else{return["__ne__","__lt__","__le__"].indexOf(op)>-1}}else if(other.$cell_contents===null){return["__ne__","__gt__","__ge__"].indexOf(op)>-1} return $B.rich_comp(op,self.$cell_contents,other.$cell_contents)}})(op)}) $B.set_func_names($B.cell,"builtins") for(let flag in $B.builtin_class_flags.builtins){for(let key of $B.builtin_class_flags.builtins[flag]){if(_b_[key]){_b_[key].__flags__=parseInt(flag)}else{console.log('not in _b_',key)}}} for(let flag in $B.builtin_class_flags.types){for(let key of $B.builtin_class_flags.types[flag]){if($B[key]){$B[key].__flags__=parseInt(flag)}}} $B.AST={__class__:_b_.type,__mro__:[_b_.object],__name__:'AST',__qualname__:'AST',$is_class:true,$convert:function(js_node){if(js_node===undefined){return _b_.None} var constr=js_node.constructor if(constr && constr.$name){$B.create_python_ast_classes() return $B.python_ast_classes[constr.$name].$factory(js_node)}else if(Array.isArray(js_node)){return js_node.map($B.AST.$convert)}else if(js_node.type){ switch(js_node.type){case 'int': var value=js_node.value[1],base=js_node.value[0] var res=parseInt(value,base) if(! Number.isSafeInteger(res)){res=$B.long_int.$factory(value,base)} return res case 'float': return $B.fast_float(parseFloat(js_node.value)) case 'imaginary': return $B.make_complex(0,$B.AST.$convert(js_node.value)) case 'ellipsis': return _b_.Ellipsis case 'str': if(js_node.is_bytes){return _b_.bytes.$factory(js_node.value,'latin-1')} return js_node.value case 'id': if(['False','None','True'].indexOf(js_node.value)>-1){return _b_[js_node.value]} break}}else if(['string','number'].indexOf(typeof js_node)>-1){return js_node}else if(js_node.$name){ return js_node.$name+'()'}else if([_b_.None,_b_.True,_b_.False].indexOf(js_node)>-1){return js_node}else if(js_node.__class__){return js_node}else{console.log('cannot handle',js_node) return js_node}}} $B.stdin={__class__:$io,__original__:true,closed:false,len:1,pos:0,read:function(){return ""},readline:function(){return ""}} $B.__ARGV=$B.$list([]) $B.tracefunc=_b_.None $B.function.__dict__=$B.obj_dict($B.function.__dict__)})(__BRYTHON__); ; (function($B){var _b_=$B.builtins function ast_dump(tree,indent){var attr,value indent=indent ||0 if(tree===_b_.None){ return 'None'}else if(typeof tree=='string'){return `'${tree}'`}else if(typeof tree=='number'){return tree+''}else if(tree.imaginary){return tree.value+'j'}else if(Array.isArray(tree)){if(tree.length==0){return '[]'} res='[\n' var items=[] for(var x of tree){try{items.push(ast_dump(x,indent+1))}catch(err){console.log('error',tree) console.log('for item',x) throw err}} res+=items.join(',\n') return res+']'}else if(tree.$name){return tree.$name+'()'}else if(tree instanceof $B.ast.MatchSingleton){return `MatchSingleton(value=${$B.AST.$convert(tree.value)})`}else if(tree instanceof $B.ast.Constant){value=tree.value if(value.imaginary){return `Constant(value=${_b_.repr(value.value)}j)`} return `Constant(value=${$B.AST.$convert(value)})`} var proto=Object.getPrototypeOf(tree).constructor var res=' '.repeat(indent)+proto.$name+'(' if($B.ast_classes[proto.$name]===undefined){console.log('no ast class',proto)} var attr_names=$B.ast_classes[proto.$name].split(','),attrs=[] attr_names=attr_names.map(x=>(x.endsWith('*')||x.endsWith('?'))? x.substr(0,x.length-1):x) if([$B.ast.Name].indexOf(proto)>-1){for(attr of attr_names){if(tree[attr]!==undefined){attrs.push(`${attr}=${ast_dump(tree[attr])}`)}} return res+attrs.join(', ')+')'} for(attr of attr_names){if(tree[attr]!==undefined){value=tree[attr] attrs.push(attr+'='+ ast_dump(tree[attr],indent+1).trimStart())}} if(attrs.length > 0){res+='\n' res+=attrs.map(x=> ' '.repeat(indent+1)+x).join(',\n')} res+=')' return res} function string_from_ast_value(value){ return value.replace(new RegExp("\\\\'",'g'),"'")} function compiler_error(ast_obj,message,end){prefix='' var exc=$B.EXC(_b_.SyntaxError,message) exc.filename=state.filename if(exc.filename !=''){var src=$B.file_cache[exc.filename],lines=src.split('\n'),line=lines[ast_obj.lineno-1] exc.text=line}else{exc.text=_b_.None} exc.lineno=ast_obj.lineno exc.offset=ast_obj.col_offset+1 end=end ||ast_obj exc.end_lineno=end.end_lineno exc.end_offset=end.end_col_offset+1 exc.args[1]=[exc.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset] exc.__traceback__=$B.make_tb() throw exc} var uuid=Math.floor(Math.random()*1000000) function make_id(){uuid+=1 return uuid} function fast_id(obj){ if(obj.$id !==undefined){return obj.$id} return obj.$id=make_id()} function copy_position(target,origin){target.lineno=origin.lineno target.col_offset=origin.col_offset target.end_lineno=origin.end_lineno target.end_col_offset=origin.end_col_offset} $B.copy_position=copy_position function encode_position(lineno,end_lineno,col_offset,end_col_offset){var res if(end_lineno==lineno){res=`[${lineno},${col_offset},${end_col_offset - col_offset}]`}else{res=`[${lineno},${end_lineno},${col_offset},${end_col_offset}]`} return res} $B.decode_position=function(pos){if(pos.length==3){return[pos[0],pos[0],pos[1],pos[1]+pos[2]]}else{return pos}} function get_source_from_position(scopes,ast_obj){scopes.lines=scopes.lines ?? scopes.src.split('\n') var lines=scopes.lines,start_line=lines[ast_obj.lineno-1],res if(ast_obj.end_lineno==ast_obj.lineno){res=start_line.substring(ast_obj.col_offset,ast_obj.end_col_offset)}else{var res=start_line.substr(ast_obj.col_offset),line_num=ast_obj.lineno+1 while(line_num < ast_obj.end_lineno){res+=lines[line_num-1].trimLeft() line_num++} res+=lines[ast_obj.end_lineno-1].substr(0,ast_obj.end_col_offset).trimLeft()} return res.replace(new RegExp("'",'g'),"\\'")} function get_names(ast_obj){ var res=new Set() if(ast_obj instanceof $B.ast.Name){res.add(ast_obj)}else if(ast_obj instanceof $B.ast.Subscript){for(var item of get_names(ast_obj.value)){res.add(item)}} return res} function last_scope(scopes){var ix=scopes.length-1 while(scopes[ix].parent){ix--} return scopes[ix]} function Scope(name,type,ast){this.name=name this.locals=new Set() this.globals=new Set() this.nonlocals=new Set() this.freevars=new Set() this.type=type this.ast=ast} function copy_scope(scope,ast,id){ var new_scope=new Scope(scope.name,scope.type,ast) if(id !==undefined){ new_scope.id=id} new_scope.parent=scope return new_scope} function qualified_scope_name(scopes,scope){ if(scope !==undefined && !(scope instanceof Scope)){console.log('bizarre',scope) throw Error('scope étrange')} var _scopes if(! scope){_scopes=scopes.slice()}else{var ix=scopes.indexOf(scope) if(ix >-1){_scopes=scopes.slice(0,ix+1)}else{_scopes=scopes.concat(scope)}} var names=[] for(var _scope of _scopes){if(! _scope.parent){names.push(_scope.name)}} return names.join('_').replace(/\./g,'_')} function module_name(scopes){var _scopes=scopes.slice() var names=[] for(var _scope of _scopes){if(! _scope.parent){names.push(_scope.name)}} return names.join('.')} function make_scope_name(scopes,scope){ if(scope===builtins_scope){return `_b_`} return 'locals_'+qualified_scope_name(scopes,scope)} function make_search_namespaces(scopes){var namespaces=[] for(var scope of scopes.slice().reverse()){if(scope.parent ||scope.type=='class'){continue}else if(scope.is_exec_scope){namespaces.push('$B.exec_scope')} namespaces.push(make_scope_name(scopes,scope))} namespaces.push('_b_') return namespaces} function mangle(scopes,scope,name){if(name.startsWith('__')&& ! name.endsWith('__')){var ix=scopes.indexOf(scope) while(ix >=0){if(scopes[ix].ast instanceof $B.ast.ClassDef){var scope_name=scopes[ix].name while(scope_name.length > 0 && scope_name.startsWith('_')){scope_name=scope_name.substr(1)} if(scope_name.length==0){ return name} return '_'+scope_name+name} ix--}} return name} function reference(scopes,scope,name){return make_scope_name(scopes,scope)+'.'+mangle(scopes,scope,name)} function get_binding_scope(name,scopes){var scope=$B.last(scopes),up_scope=last_scope(scopes) name=mangle(scopes,up_scope,name) if(up_scope.globals && up_scope.globals.has(name)){scope=scopes[0]}else if(up_scope.nonlocals.has(name)){for(var i=scopes.indexOf(up_scope)-1;i >=0;i--){if(scopes[i].locals.has(name)|| (scopes[i].maybe_locals && scopes[i].maybe_locals.has(name))){return[name,scopes[i],up_scope]}}} return[name,scope,up_scope]} function bind(name,scopes){var[name,scope,up_scope]=get_binding_scope(name,scopes) if(up_scope.globals && up_scope.globals.has(name)){scope=scopes[0]}else if(up_scope.nonlocals.has(name)){for(var i=scopes.indexOf(up_scope)-1;i >=0;i--){if(scopes[i].locals.has(name)|| (scopes[i].maybe_locals && scopes[i].maybe_locals.has(name))){return scopes[i]}}} scope.locals.add(name) var up_scope=last_scope(scopes) if(up_scope.type=='class' ||up_scope !==scope){up_scope.maybe_locals=up_scope.maybe_locals ?? new Set() up_scope.maybe_locals.add(name)} return scope} var SF=$B.SYMBOL_FLAGS function name_reference(name,scopes,ast_obj){var scope=name_scope(name,scopes) return make_ref(name,scopes,scope,ast_obj)} function make_ref(name,scopes,scope,ast_obj){var test=false if(test){console.log('make ref',name,scopes.slice(),scope)} if(scope.found){var res=reference(scopes,scope.found,name) if(test){console.log('res',res)} return res}else{var inum=add_to_positions(scopes,ast_obj) if(scope.resolve=='all'){var scope_names=make_search_namespaces(scopes) return `$B.resolve_in_scopes('${name}', [${scope_names}], ${inum})`}else if(scope.resolve=='local'){return `$B.resolve_local('${name}', ${inum})`}else if(scope.resolve=='global'){return `$B.resolve_global('${name}', _frame_obj, ${inum})`}else if(Array.isArray(scope.resolve)){return `$B.resolve_in_scopes('${name}', [${scope.resolve}], ${inum})`}else if(scope.resolve=='own_class_name'){if(scopes.eval_annotation){return `$B.resolve_global('${name}', _frame_obj, ${inum})`} return `$B.own_class_name('${name}', ${inum})`}}} function local_scope(name,scope){ var s=scope while(true){if(s.locals.has(name)){return{found:true,scope:s}} if(! s.parent){return{found:false}} s=s.parent}} function name_scope(name,scopes){ var test=false if(test){console.log('name scope',name,scopes.slice())} var flags,block if(scopes.length==0){ return{found:false,resolve:'all'}} var scope=$B.last(scopes),up_scope=last_scope(scopes) name=mangle(scopes,scope,name) if(up_scope.ast===undefined){console.log('no ast',scope)} block=scopes.symtable.table.blocks.get(fast_id(up_scope.ast)) if(block===undefined){console.log('no block',scope,scope.ast,'id',fast_id(up_scope.ast)) console.log('scopes',scopes.slice()) console.log('symtable',scopes.symtable)} if(test){console.log('block symbols',block.symbols)} try{flags=_b_.dict.$getitem_string(block.symbols,name)}catch(err){console.log('name',name,'not in symbols of block',block) console.log('symtables',scopes.symtable) console.log('scopes',scopes.slice()) return{found:false,resolve:'all'}} let __scope=(flags >> SF.SCOPE_OFF)& SF.SCOPE_MASK,is_local=[SF.LOCAL,SF.CELL].indexOf(__scope)>-1 if(test){console.log('block',block,'is local',is_local,'__scope',__scope) console.log('flags',flags,'scopeoff',SF.SCOPE_OFF,'scope mask',SF.SCOPE_MASK)} if(up_scope.ast instanceof $B.ast.ClassDef && name==up_scope.name){return{found:false,resolve:'own_class_name'}} if(name=='__annotations__'){if(block.type==SF.TYPE_CLASS && up_scope.has_annotation){is_local=true}else if(block.type==SF.TYPE_MODULE){is_local=true}} if(test){console.log('is local ???',is_local,'scope',scope)} if(is_local){ var l_scope=local_scope(name,scope) if(test){console.log('l_scope',l_scope)} if(! l_scope.found){if(block.type==SF.TYPE_CLASS){ scope.needs_frames=true if(scope.maybe_locals && scope.maybe_locals.has(name)){return{found:false,resolve:'local'}} return{found:false,resolve:'global'}}else if(block.type==SF.TYPE_MODULE){scope.needs_frames=true return{found:false,resolve:'global'}} return{found:false,resolve:'local'}}else{return{found:l_scope.scope}}}else if(scope.globals.has(name)){var global_scope=scopes[0] if(global_scope.locals.has(name)){return{found:global_scope}} scope.needs_frames=true return{found:false,resolve:'global'}}else if(scope.nonlocals.has(name)){ for(let i=scopes.length-2;i >=0;i--){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast)) if(block && _b_.dict.$contains_string(block.symbols,name)){var fl=_b_.dict.$getitem_string(block.symbols,name),local_to_block= [SF.LOCAL,SF.CELL].indexOf((fl >> SF.SCOPE_OFF)& SF.SCOPE_MASK)>-1 if(! local_to_block){continue} return{found:scopes[i]}}}} if(scope.has_import_star){if(! is_local){scope.needs_frames=true} return{found:false,resolve:is_local ? 'all' :'global'}} for(let i=scopes.length-2;i >=0;i--){block=undefined if(scopes[i].ast){block=scopes.symtable.table.blocks.get(fast_id(scopes[i].ast))} if(scopes[i].globals.has(name)){scope.needs_frames=true return{found:false,resolve:'global'}} if(scopes[i].locals.has(name)&& scopes[i].type !='class'){if(test){console.log('found in locals of',scopes[i])} return{found:scopes[i]}}else if(block && _b_.dict.$contains_string(block.symbols,name)){flags=_b_.dict.$getitem_string(block.symbols,name) let __scope=(flags >> SF.SCOPE_OFF)& SF.SCOPE_MASK if([SF.LOCAL,SF.CELL].indexOf(__scope)>-1){ return{found:false,resolve:'all'}}} if(scopes[i].has_import_star){return{found:false,resolve:'all'}}} if(builtins_scope.locals.has(name)){return{found:builtins_scope}} var scope_names=make_search_namespaces(scopes) return{found:false,resolve:scope_names}} function resolve_in_namespace(name,ns){if(ns.$proxy){ return ns[name]===undefined ?{found:false}: {found:true,value:ns[name]}} if(! ns.hasOwnProperty){if(ns[name]!==undefined){return{found:true,value:ns[name]}}}else if(ns.hasOwnProperty(name)){return{found:true,value:ns[name]}}else if(ns.$dict){try{return{found:true,value:ns.$getitem(ns.$dict,name)}}catch(err){if(ns.$missing){try{return{ found:true,value:$B.$call(ns.$missing)(ns.$dict,name)}}catch(err){if(! $B.is_exc(err,[_b_.KeyError])){throw err}}}}} return{found:false}} $B.resolve=function(name){var checked=new Set(),current_globals,frame_obj=$B.frame_obj,frame while(frame_obj !==null){frame=frame_obj.frame if(current_globals===undefined){current_globals=frame[3]}else if(frame[3]!==current_globals){let v=resolve_in_namespace(name,current_globals) if(v.found){return v.value} checked.add(current_globals) current_globals=frame[3]} let v=resolve_in_namespace(name,frame[1]) if(v.found){return v.value} frame_obj=frame_obj.prev} if(! checked.has(frame[3])){var v=resolve_in_namespace(name,frame[3]) if(v.found){return v.value}} if(builtins_scope.locals.has(name)){return _b_[name]} throw $B.name_error(name)} $B.resolve_local=function(name,inum){ if($B.frame_obj !==null){var frame=$B.frame_obj.frame if(frame[1].hasOwnProperty){if(frame[1].hasOwnProperty(name)){return frame[1][name]}}else{var value=frame[1][name] if(value !==undefined){return value}}} var exc=$B.EXC(_b_.UnboundLocalError,`cannot access local variable `+ `'${name}' where it is not associated with a value`) exc.name=name $B.set_inum(inum) throw exc} $B.resolve_in_scopes=function(name,namespaces,inum){for(var ns of namespaces){if(ns===$B.exec_scope){var exec_top,frame_obj=$B.frame_obj,frame while(frame_obj !==null){frame=frame_obj.frame if(frame.is_exec_top){exec_top=frame break} frame_obj=frame_obj.prev} if(exec_top){for(var ns1 of[exec_top[1],exec_top[3]]){let v=resolve_in_namespace(name,ns1) if(v.found){return v.value}}}}else{let v=resolve_in_namespace(name,ns) if(v.found){return v.value}}} var exc=$B.name_error(name) $B.set_inum(inum) throw exc} $B.resolve_global=function(name,frame_obj,inum){ while(frame_obj !==null){var frame=frame_obj.frame,v=resolve_in_namespace(name,frame[3]) if(v.found){return v.value} if(frame.is_exec_top){break} frame_obj=frame_obj.prev} if(builtins_scope.locals.has(name)){return _b_[name]} $B.set_inum(inum) throw $B.name_error(name)} $B.own_class_name=function(name,inum){$B.set_inum(inum) throw $B.name_error(name)} var $operators=$B.op2method.subset("all") var opname2opsign={} for(var key in $operators){opname2opsign[$operators[key]]=key} var opclass2dunder={} for(var op_type of $B.op_types){ for(var operator in op_type){opclass2dunder[op_type[operator]]='__'+$operators[operator]+'__'}} opclass2dunder['UAdd']='__pos__' opclass2dunder['USub']='__neg__' opclass2dunder['Invert']='__invert__' var builtins_scope=new Scope("__builtins__") for(var name in $B.builtins){builtins_scope.locals.add(name)} function mark_parents(node){if(node.body && node.body instanceof Array){for(let child of node.body){child.$parent=node mark_parents(child)}}else if(node.handlers){ var p={$parent:node,'type':'except_handler'} for(let child of node.handlers){child.$parent=p mark_parents(child)}}} var prefix='',tab=' ' function indent(n){n=n ?? 1 prefix+=tab.repeat(n)} function dedent(n){n=n ?? 1 prefix=prefix.substr(n*tab.length)} function add_body(body,scopes){var res=''; let js; for(var item of body){js=$B.js_from_ast(item,scopes) if(js.length > 0){res+=js+'\n'}} return res.trimRight()} function extract_docstring(ast_obj,scopes){ var js='_b_.None' if(ast_obj.body.length && ast_obj.body[0]instanceof $B.ast.Expr && ast_obj.body[0].value instanceof $B.ast.Constant){ var value=ast_obj.body[0].value.value if(typeof value=='string'){js=ast_obj.body[0].value.to_js(scopes) ast_obj.body.shift()}} return js} function init_comprehension(comp,scopes){if(comp.type=='genexpr'){return init_genexpr(comp,scopes)} return prefix+`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`} function init_genexpr(comp,scopes){var varnames=Object.keys(comp.varnames ||{}).map(x=> `'${x}'`).join(', ') return prefix+`var ${comp.locals_name} = {},\n`+ prefix+tab+tab+`locals = ${comp.locals_name}\n`+ prefix+`locals['.0'] = expr\n`+ prefix+`var frame = ["<${comp.type.toLowerCase()}>", ${comp.locals_name}, `+ `"${comp.module_name}", ${comp.globals_name}]\n`+ prefix+`frame.$has_generators = true\n`+ prefix+`frame.__file__ = '${scopes.filename}'\n`+ prefix+`frame.$lineno = ${comp.ast.lineno}\n`+ prefix+`$B.make_f_code(frame, [${varnames}])\n`+ prefix+`var next_func_${comp.id} = $B.make_js_iterator(expr, frame, ${comp.ast.lineno})\n`+ prefix+`frame.$f_trace = _b_.None\n`+ prefix+`var _frame_obj = $B.frame_obj\n`} function comp_bindings(comp,bindings){if(comp.target instanceof $B.ast.Name){bindings.add(comp.target.id)}else if(comp.target.elts){for(var elt of comp.target.elts){comp_bindings({target:elt},bindings)}} return bindings} function make_comp(scopes){ var bindings=new Set() for(var gen of this.generators){comp_bindings(gen,bindings)} var save_locals=new Set() var plen=prefix.length var comp_prefix=prefix var id=make_id(),type=this.constructor.$name,symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=Object.keys(symtable_block.symbols.$strings).map(x=> `"${x}"`),comp_iter,comp_scope=$B.last(scopes),upper_comp_scope=comp_scope for(var name of comp_scope.locals){if(bindings.has(name)){save_locals.add(name)}} while(upper_comp_scope.parent){upper_comp_scope=upper_comp_scope.parent for(var name of upper_comp_scope.locals){if(bindings.has(name)){save_locals.add(name)}}} var comp_scope_block=scopes.symtable.table.blocks.get( fast_id(upper_comp_scope.ast)),comp_scope_symbols=comp_scope_block.symbols var initial_nb_await_in_scope=upper_comp_scope.nb_await===undefined ? 0 : upper_comp_scope.nb_await for(var symbol of _b_.dict.$iter_items(symtable_block.symbols)){if(symbol.value & SF.DEF_COMP_ITER){comp_iter=symbol.key}} var comp_iter_scope=name_scope(comp_iter,scopes) var first_for=this.generators[0], outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1 var comp={ast:this,id,type,varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])} indent() if(prefix.length > plen+tab.length){console.warn('JS indentation issue')} var js=init_comprehension(comp,scopes) if(comp_iter_scope.found){js+=prefix+`var save_comp_iter = ${name_reference(comp_iter, scopes)}\n`} for(var name of save_locals){js+=prefix+`var save_${name} = ${name_reference(name, scopes)}\n`} if(this instanceof $B.ast.ListComp){js+=prefix+`var result_${id} = $B.$list([])\n`}else if(this instanceof $B.ast.SetComp){js+=prefix+`var result_${id} = _b_.set.$factory()\n`}else if(this instanceof $B.ast.DictComp){js+=prefix+`var result_${id} = $B.empty_dict()\n`} var first=this.generators[0] js+=prefix+`try{\n` indent() js+=prefix+`for(var next_${id} of next_func_${id}){\n` indent() var save_target_flags if(first.target instanceof $B.ast.Name){var target_name=first.target.id if(comp_scope_symbols.$strings.hasOwnProperty(target_name)){save_target_flags=comp_scope_symbols.$strings[target_name] comp_scope_symbols.$strings[target_name]=SF.LOCAL << SF.SCOPE_OFF}} var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load()) copy_position(name,first_for.iter) name.to_js=function(){return `next_${id}`} var assign=new $B.ast.Assign([first.target],name) assign.lineno=this.lineno js+=assign.to_js(scopes)+'\n' for(let _if of first.ifs){nb_paren++ js+=prefix+`if($B.$bool(${$B.js_from_ast(_if, scopes)})){\n` indent()} for(var comprehension of this.generators.slice(1)){js+=comprehension.to_js(scopes) nb_paren++ for(let _if of comprehension.ifs){nb_paren++}} if(this instanceof $B.ast.DictComp){var key=$B.js_from_ast(this.key,scopes),value=$B.js_from_ast(this.value,scopes)}else{var elt=$B.js_from_ast(this.elt,scopes)} if(save_target_flags){comp_scope_symbols.$strings[target_name]=save_target_flags} var final_nb_await_in_scope=upper_comp_scope.nb_await===undefined ? 0 : upper_comp_scope.nb_await var has_await=final_nb_await_in_scope > initial_nb_await_in_scope js=`(${has_await ? 'async ' : ''}function(expr){\n`+js js+=has_await ? 'var save_frame_obj = $B.frame_obj;\n' :'' if(this instanceof $B.ast.ListComp){js+=prefix+`result_${id}.push(${elt})\n`}else if(this instanceof $B.ast.SetComp){js+=prefix+`_b_.set.add(result_${id}, ${elt})\n`}else if(this instanceof $B.ast.DictComp){js+=prefix+`_b_.dict.$setitem(result_${id}, ${key}, ${value})\n`} dedent() for(var i=0;i < nb_paren;i++){js+=prefix+'}\n' dedent()} js+=prefix+`}catch(err){\n` indent() js+=(has_await ? prefix+`$B.restore_frame_obj(save_frame_obj, ${comp.locals_name})\n` :'')+ prefix+`$B.set_exc(err, frame)\n`+ prefix+`throw err\n` dedent() js+=prefix+`}\n`+ (has_await ? prefix+`\n$B.restore_frame_obj(save_frame_obj, ${comp.locals_name});` :'') for(var name of save_locals){js+=prefix+`${name_reference(name, scopes)} = save_${name}\n`} if(comp_iter_scope.found){js+=prefix+`${name_reference(comp_iter, scopes)} = save_comp_iter\n`} js+=prefix+`return result_${id}\n` dedent() js+=prefix+`}`+`)(${outmost_expr})\n` if(prefix.length !=plen){console.log('comprehension, prefix length start',plen,'end',prefix.length) console.log('file',scopes.filename) console.log(this) console.log('>>>\n',js,'\n<<<')} return js} function init_scopes(type,scopes){ var filename=scopes?.symtable?.table?.filename,name=$B.url2name[filename] if(name){name=name.replace(/-/g,'_')}else if(filename===undefined){name='exec' }else if(filename.startsWith('<')&& filename.endsWith('>')){name='exec'}else{name=filename.replace(/\./g,'_')} var top_scope=new Scope(name,`${type}`,this),block=scopes.symtable.table.blocks.get(fast_id(this)) if(block && block.$has_import_star){top_scope.has_import_star=true} scopes.push(top_scope) var namespaces=scopes.namespaces if(namespaces){top_scope.is_exec_scope=true for(let key in namespaces.exec_globals){if(! key.startsWith('$')){top_scope.globals.add(key)}} if(namespaces.exec_locals !==namespaces.exec_globals){if(namespaces.exec_locals[$B.LOCALS_PROXY]){ for(let item of $B.make_js_iterator(namespaces.exec_locals.$target)){top_scope.locals.add(item)}}else{for(let key in namespaces.exec_locals){if(! key.startsWith('$')){top_scope.locals.add(key)}}}}} return name} function compiler_check(obj){var check_func=Object.getPrototypeOf(obj)._check if(check_func){obj._check()}} function check_assign_or_delete(obj,target,action){action=action ?? 'assign to' if(target instanceof $B.ast.Attribute){if(target.attr=='__debug__'){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Name){if(target.id=='__debug__'){compiler_error(obj,`cannot ${action} __debug__`,target)}}else if(target instanceof $B.ast.Tuple){for(var elt of target.elts){check_assign_or_delete(elt,elt,action)}}else if(target instanceof $B.ast.Starred){check_assign_or_delete(obj,target.value,action)}} function check_is_arg(e){if(!(e instanceof $B.ast.Constant)){return true} var value=e.value return(value===_b_.None ||value===false ||value===true ||value===_b_.Ellipsis)} function check_compare(op_name,left,right,scopes){var test_left=check_is_arg(left),test_right=check_is_arg(right) if(! test_left ||! test_right){var item=test_left ? right :left,name=$B.class_name(item.value) $B.warn(_b_.SyntaxWarning,`"${op_name}" with '${name}' literal. `+ `Did you mean "=="?`,scopes.filename,item)}} function check_type_params(ast_obj){var type_params=ast_obj.type_params if(Array.isArray(type_params)){var has_defaults=false for(var type_param of type_params){if(type_param.default_value===undefined && has_defaults){throw compiler_error(type_param,`non-default type `+ `parameter '${type_param.name}' follows default type parameter`)}else if(type_param.default_value){has_defaults=true}}}} function maybe_add_static(attr,scopes){ var last=last_scope(scopes) if(last.type=="def"){var ix=scopes.indexOf(last)-1 while(scopes[ix]){last=last_scope(scopes.slice(0,ix+1)) if(last.type=="class"){last.static_attributes=last.static_attributes ?? new Set() last.static_attributes.add(attr.attr) return}else if(last.type=="def"){ix=scopes.indexOf(last)-1}else{return}}}} function add_to_positions(scopes,ast_obj){ var up_scope=last_scope(scopes) up_scope.positions=up_scope.positions ??[] up_scope.positions[up_scope.positions.length]=encode_position( ast_obj.lineno,ast_obj.end_lineno,ast_obj.col_offset,ast_obj.end_col_offset ) var inum=1+2*(up_scope.positions.length-1) ast_obj.inum=inum return inum} $B.ast.Assert.prototype.to_js=function(scopes){var test=$B.js_from_ast(this.test,scopes),msg=this.msg ? $B.js_from_ast(this.msg,scopes):"''" var inum=add_to_positions(scopes,this.test) var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n` return js+prefix+`$B.assert(${test}, ${msg}, ${inum})`} function annotation_to_str(obj,scopes){return get_source_from_position(scopes,obj)} function annotation_code(scopes,scope,ref){ if(scope.annotate){var annotate=prefix+`var annotate = function(format){\n` indent() annotate+=prefix+`$B.check_annotate_format(format)\n`+ prefix+`var current_frame = $B.frame_obj.frame\n`+ prefix+`var frame = ['__annotate__', {}, current_frame[2], current_frame[3]]\n`+ prefix+`$B.enter_frame(frame, "${scopes.filename}", ${scope.ast.lineno})\n`+ prefix+`frame.positions = [${scope.positions}]\n`+ prefix+`var res = $B.empty_dict()\n`+ prefix+`var anns = {\n` indent() var anns=scope.annotate.map(x=> prefix+x) annotate+=anns.join(',\n')+'\n' dedent() annotate+=prefix+'}\n' annotate+=prefix+`for(var key in anns){\n` indent() annotate+=prefix+`var [lineno, func] = anns[key]\n` annotate+=prefix+`try{\n` indent() annotate+=prefix+`$B.$setitem(res, key, func())\n` dedent() annotate+=prefix+`}catch(err){\n` indent() annotate+=prefix+`$B.set_exc_and_leave(frame, err)\n` dedent() annotate+=prefix+`}\n` dedent() annotate+=prefix+`}\n`+ prefix+`$B.leave_frame()\n`+ prefix+`return res\n` dedent() annotate+=prefix+'}\n' return annotate}else{return prefix+`var annotate\n`}} $B.ast.AnnAssign.prototype.to_js=function(scopes){compiler_check(this) var scope=last_scope(scopes) var js='' if(scopes.postpone_annotations){var inum=add_to_positions(scopes,this)} if(! scope.has_annotation){scope.has_annotation=true if(scopes.postpone_annotations){scope.locals.add('__annotations__') js+=prefix+'locals.__annotations__ = $B.empty_dict()\n'}else{scope.locals.add('__annotate__') scope.annotate=[] if(scope.type=='module'){js+=prefix+`$B.make_module_annotate(locals)\n`}}} if(this.target instanceof $B.ast.Name){var ann_value if(scopes.postpone_annotations){ann_value=`'${annotation_to_str(this.annotation, scopes)}'`}else{ scopes.eval_annotation=true ann_value=$B.js_from_ast(this.annotation,scopes) delete scopes.eval_annotation}} if(this.value){js+=prefix+`var ann = ${$B.js_from_ast(this.value, scopes)}\n` if(this.target instanceof $B.ast.Name && this.simple){let scope=bind(this.target.id,scopes),mangled=mangle(scopes,scope,this.target.id) if(scope.type !="def"){ if(! scopes.postpone_annotations){if(scope.type=='class'){scope.annotate.push(`${mangled}: [${this.lineno}, `+ `() => ${ann_value}]`)}else{js+=prefix+ `locals.$annotations.${mangled} = `+ `[${this.lineno}, () => ${ann_value}]\n`}}else{js+=prefix+`$B.$setitem(locals.__annotations__, `+ `'${mangled}', ${ann_value}, ${inum})\n`}} let target_ref=name_reference(this.target.id,scopes) js+=prefix+`${target_ref} = ann`}else if(this.target instanceof $B.ast.Attribute){js+=prefix+`$B.$setattr(${$B.js_from_ast(this.target.value, scopes)}`+ `, "${this.target.attr}", ann)`}else if(this.target instanceof $B.ast.Subscript){js+=prefix+`$B.$setitem(${$B.js_from_ast(this.target.value, scopes)}`+ `, ${$B.js_from_ast(this.target.slice, scopes)}, ann)`}}else{if(this.target instanceof $B.ast.Name){if(this.simple && scope.type !='def'){let mangled=mangle(scopes,scope,this.target.id) if(! scopes.postpone_annotations){if(scope.type=='class'){scope.annotate.push(`${mangled}: [${this.lineno}, `+ `() => ${ann_value}]`)}else{js+=prefix+ `locals.$annotations.${mangled} = [${this.lineno}, `+ `() => ${ann_value}]\n`}}else{js+=prefix+`$B.$setitem(locals.__annotations__, `+ `'${mangled}', ${ann_value}, ${inum})\n`}}}} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+js} $B.ast.AnnAssign.prototype._check=function(){check_assign_or_delete(this,this.target)} $B.ast.Assign.prototype.to_js=function(scopes){compiler_check(this) var js if(! this.lineno ||this.$loopvar){ js=''}else{js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`} var value=$B.js_from_ast(this.value,scopes) function assign_one(target,value){if(target instanceof $B.ast.Name){let js='' var[name,binding_scope,up_scope]=get_binding_scope(target.id,scopes) if(binding_scope.locals.has(name)){ if(name=='buf1'){console.log('reassign',name)} var ref=$B.js_from_ast(target,scopes) var scope_name=make_scope_name(scopes,binding_scope) return prefix+`var $temp = ${value}\n`+ prefix+`$B.delete_for_reassign('${name}', ${scope_name})\n`+ prefix+$B.js_from_ast(target,scopes)+' = $temp'} return js+prefix+$B.js_from_ast(target,scopes)+' = '+value}else if(target instanceof $B.ast.Starred){return assign_one(target.value,value)}else if(target instanceof $B.ast.Subscript){var inum=add_to_positions(scopes,target) return prefix+`$B.$setitem(${$B.js_from_ast(target.value, scopes)}`+ `, ${$B.js_from_ast(target.slice, scopes)}, ${value}, ${inum})`}else if(target instanceof $B.ast.Attribute){if(target.value.id=='self'){maybe_add_static(target,scopes)} var inum=add_to_positions(scopes,target) var attr=mangle(scopes,last_scope(scopes),target.attr) return prefix+`$B.$setattr1(${$B.js_from_ast(target.value, scopes)}`+ `, "${attr}", ${value}, ${inum})`}} function assign_many(target,value){var js='' var nb_targets=target.elts.length,has_starred=false,nb_after_starred for(var i=0,len=nb_targets;i < len;i++){if(target.elts[i]instanceof $B.ast.Starred){has_starred=true nb_after_starred=len-i-1 break}} var iter_id='it_'+make_id() var inum=add_to_positions(scopes,target) js+=prefix+`var ${iter_id} = $B.unpacker(${value}, ${nb_targets}, `+ `${has_starred}` if(nb_after_starred !==undefined){js+=`, ${nb_after_starred}`} js+=`, ${inum})\n` var assigns=[] for(var elt of target.elts){if(elt instanceof $B.ast.Starred){assigns.push(assign_one(elt,`${iter_id}.read_rest()`))}else if(elt instanceof $B.ast.List || elt instanceof $B.ast.Tuple){assigns.push(assign_many(elt,`${iter_id}.read_one()`))}else{assigns.push(assign_one(elt,`${iter_id}.read_one()`))}} js+=assigns.join('\n') return js} if(this.targets.length==1){let target=this.targets[0] if(!(target instanceof $B.ast.Tuple)&& !(target instanceof $B.ast.List)){js+=assign_one(this.targets[0],value) return js}} var value_id='v'+make_id() js+=prefix+`var ${value_id} = ${value}\n` var assigns=[] for(let target of this.targets){if(!(target instanceof $B.ast.Tuple)&& !(target instanceof $B.ast.List)){assigns.push(assign_one(target,value_id))}else{assigns.push(assign_many(target,value_id))}} js+=assigns.join('\n') return js} $B.ast.Assign.prototype._check=function(){for(var target of this.targets){check_assign_or_delete(this,target)}} $B.ast.AsyncFor.prototype.to_js=function(scopes){if(!(last_scope(scopes).ast instanceof $B.ast.AsyncFunctionDef)){compiler_error(this,"'async for' outside async function")} return $B.ast.For.prototype.to_js.bind(this)(scopes)} $B.ast.AsyncFunctionDef.prototype.to_js=function(scopes){return $B.ast.FunctionDef.prototype.to_js.bind(this)(scopes)} $B.ast.AsyncWith.prototype.to_js=function(scopes){ if(!(last_scope(scopes).ast instanceof $B.ast.AsyncFunctionDef)){compiler_error(this,"'async with' outside async function")} function bind_vars(vars,scopes){if(vars instanceof $B.ast.Name){bind(vars.id,scopes)}else if(vars instanceof $B.ast.Tuple){for(var var_item of vars.elts){bind_vars(var_item,scopes)}}} function add_item(item,js){var id=make_id() var s=prefix+`var mgr_${id} = `+ $B.js_from_ast(item.context_expr,scopes)+',\n' indent(2) s+=prefix+`mgr_type_${id} = _b_.type.$factory(mgr_${id}),\n`+ prefix+`aexit_${id} = $B.$getattr(mgr_type_${id}, '__aexit__'),\n`+ prefix+`aenter_${id} = $B.$getattr(mgr_type_${id}, '__aenter__'),\n`+ prefix+`value_${id} = await $B.promise($B.$call(aenter_${id})(mgr_${id})),\n`+ prefix+`exc_${id} = true\n` if(has_generator){ s+=prefix+`locals.$context_managers = locals.$context_managers || []\n`+ `locals.$context_managers.push(mgr_${id})\n`} dedent(2) s+=prefix+'try{\n' indent() s+=prefix+'try{\n' indent() if(item.optional_vars){ var value={to_js:function(){return `value_${id}`}} copy_position(value,_with) var assign=new $B.ast.Assign([item.optional_vars],value) copy_position(assign,_with) s+=assign.to_js(scopes)+'\n'} s+=js dedent() s+=prefix+`}catch(err_${id}){\n` indent() s+=prefix+`frame.$lineno = ${lineno}\n`+ prefix+`exc_${id} = false\n`+ prefix+`err_${id} = $B.exception(err_${id}, frame)\n`+ prefix+`var $b = await $B.promise(aexit_${id}(mgr_${id}, err_${id}.__class__, \n`+ prefix+tab.repeat(4)+`err_${id}, $B.$getattr(err_${id}, '__traceback__')))\n`+ prefix+`if(! $B.$bool($b)){\n`+ prefix+tab+`throw err_${id}\n`+ prefix+`}\n` dedent() s+=prefix+`}\n` dedent() s+=prefix+`}finally{\n` indent() s+=prefix+`frame.$lineno = ${lineno}\n`+ prefix+`if(exc_${id}){\n`+ prefix+tab+`await $B.promise(aexit_${id}(mgr_${id}, _b_.None, _b_.None, _b_.None))\n`+ prefix+`}\n` dedent() s+=prefix+`}\n` return s} var _with=this,scope=last_scope(scopes),lineno=this.lineno delete scope.is_generator for(let item of this.items.slice().reverse()){if(item.optional_vars){bind_vars(item.optional_vars,scopes)}} indent(2) var js=add_body(this.body,scopes)+'\n' dedent(2) var has_generator=scope.is_generator for(let item of this.items.slice().reverse()){js=add_item(item,js)} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+js} $B.ast.Attribute.prototype.to_js=function(scopes){var attr=mangle(scopes,last_scope(scopes),this.attr) var inum=add_to_positions(scopes,this) return `$B.$getattr_pep657(${$B.js_from_ast(this.value, scopes)}, `+ `'${attr}', ${inum})`} $B.ast.AugAssign.prototype.to_js=function(scopes){compiler_check(this) var js,op_class=this.op.$name ? this.op :this.op.constructor for(var op in $B.op2ast_class){if($B.op2ast_class[op][1]===op_class){var iop=op+'=' break}} var value=$B.js_from_ast(this.value,scopes) if(this.target instanceof $B.ast.Name){var scope=name_scope(this.target.id,scopes) if(! scope.found){ let left_scope=scope.resolve=='global' ? make_scope_name(scopes,scopes[0]):'locals' js=prefix+`${left_scope}.${this.target.id} = $B.augm_assign(`+ make_ref(this.target.id,scopes,scope,this.target)+`, '${iop}', ${value})`}else{let ref=`${make_scope_name(scopes, scope.found)}.${this.target.id}` js=prefix+`${ref} = $B.augm_assign(${ref}, '${iop}', ${value})`}}else if(this.target instanceof $B.ast.Subscript){js=prefix+`$B.$setitem((locals.$tg = ${this.target.value.to_js(scopes)}), `+ `(locals.$key = ${this.target.slice.to_js(scopes)}), `+ `$B.augm_assign($B.$getitem(locals.$tg, locals.$key), '${iop}', ${value}))`}else if(this.target instanceof $B.ast.Attribute){let mangled=mangle(scopes,last_scope(scopes),this.target.attr) js=prefix+`$B.$setattr((locals.$tg = ${this.target.value.to_js(scopes)}), `+ `'${mangled}', $B.augm_assign(`+ `$B.$getattr(locals.$tg, '${mangled}'), '${iop}', ${value}))`}else{let target=$B.js_from_ast(this.target,scopes),value=$B.js_from_ast(this.value,scopes) js=prefix+`${target} = $B.augm_assign(${target}, '${iop}', ${value})`} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+js} $B.ast.AugAssign.prototype._check=function(){check_assign_or_delete(this,this.target)} $B.ast.Await.prototype.to_js=function(scopes){var ix=scopes.length-1 while(scopes[ix].parent){ix--} scopes[ix].nb_await=scopes[ix].nb_await===undefined ? 1 : scopes[ix].nb_await+1 while(scopes[ix].ast instanceof $B.ast.ListComp || scopes[ix].ast instanceof $B.ast.DictComp || scopes[ix].ast instanceof $B.ast.SetComp || scopes[ix].ast instanceof $B.ast.GeneratorExp){scopes[ix].has_await=true ix--} if(scopes[ix].ast instanceof $B.ast.AsyncFunctionDef){scopes[ix].has_await=true return prefix+`await $B.promise(${$B.js_from_ast(this.value, scopes)})`}else if(scopes[ix].ast instanceof $B.ast.FunctionDef){compiler_error(this,"'await' outside async function",this.value)}else{compiler_error(this,"'await' outside function",this.value)}} $B.ast.BinOp.prototype.to_js=function(scopes){var res var inum=add_to_positions(scopes,this) var name=this.op.constructor.$name var op=opclass2dunder[name] if(this.left instanceof $B.ast.Constant && this.right instanceof $B.ast.Constant){ try{res=$B.rich_op(op,this.left.value,this.right.value) if(typeof res=='string' && op !=='__add__'){throw Error()} var ast_obj=new $B.ast.Constant(res) return ast_obj.to_js(scopes)}catch(err){}} return `$B.rich_op('${op}', `+ `${$B.js_from_ast(this.left, scopes)}, `+ `${$B.js_from_ast(this.right, scopes)}, ${inum})`} $B.ast.BoolOp.prototype.to_js=function(scopes){ var tests=[] if(this.$dont_evaluate){ let op=this.op instanceof $B.ast.And ? ' && ' :' || ' for(let i=0,len=this.values.length;i < len;i++){let value=this.values[i] tests.push(`$B.$bool(${$B.js_from_ast(value, scopes)})`)} return '('+tests.join(op)+')'}else{let op=this.op instanceof $B.ast.And ? '! ' :'' for(let i=0,len=this.values.length;i < len;i++){let value=this.values[i] if(i < len-1){tests.push(`${op}$B.$bool(locals.$test = `+ `${$B.js_from_ast(value, scopes)}) ? locals.$test : `)}else{tests.push(`${$B.js_from_ast(value, scopes)}`)}}} return '('+tests.join('')+')'} function in_loop(scopes){for(var scope of scopes.slice().reverse()){if(scope.ast instanceof $B.ast.For || scope.ast instanceof $B.ast.While){return true}} return false} $B.ast.Break.prototype.to_js=function(scopes){if(! in_loop(scopes)){compiler_error(this,"'break' outside loop")} var js='' for(var scope of scopes.slice().reverse()){if(scope.ast instanceof $B.ast.For || scope.ast instanceof $B.ast.While){js+=prefix+`no_break_${scope.id} = false\n` break}} js+=prefix+`break` return js} $B.ast.Call.prototype.to_js=function(scopes){compiler_check(this) var inum=add_to_positions(scopes,this) var func=$B.js_from_ast(this.func,scopes),js=`$B.$call(${func}, ${inum})` var args=make_args.bind(this)(scopes) return js+`(${args})`} $B.ast.Call.prototype._check=function(){for(var kw of this.keywords){if(kw.arg=='__debug__'){compiler_error(this,"cannot assign to __debug__",kw)}}} function make_args(scopes){var js='',named_args=[],named_kwargs=[],starred_kwargs=[] var kwds=new Set() for(var keyword of this.keywords){if(keyword.arg){if(kwds.has(keyword.arg)){compiler_error(keyword,`keyword argument repeated: ${keyword.arg}`)} kwds.add(keyword.arg) named_kwargs.push( `${keyword.arg}: ${$B.js_from_ast(keyword.value, scopes)}`)}else{starred_kwargs.push($B.js_from_ast(keyword.value,scopes))}} var args_list=[] for(let arg of this.args){if(arg instanceof $B.ast.Starred){var starred_arg=$B.js_from_ast(arg.value,scopes) args_list.push(`...$B.make_js_iterator(${starred_arg})`)}else{args_list.push($B.js_from_ast(arg,scopes))}} if(named_kwargs.length+starred_kwargs.length > 0){var kw=`{${named_kwargs.join(', ')}}` for(var starred_kwarg of starred_kwargs){kw+=`, ${starred_kwarg}`} kw=`{$kw:[${kw}]}` args_list.push(kw)} return js+`${args_list.join(', ')}`} $B.ast.ClassDef.prototype.to_js=function(scopes){var enclosing_scope=bind(this.name,scopes) var class_scope=new Scope(this.name,'class',this) var js='',locals_name=make_scope_name(scopes,class_scope),ref=this.name+make_id(),glob=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]),decorators=[],decorated=false for(let dec of this.decorator_list){decorated=true var dec_id='decorator'+make_id() decorators.push(dec_id) js+=prefix+`$B.set_lineno(frame, ${dec.lineno})\n`+ prefix+`var ${dec_id} = ${$B.js_from_ast(dec, scopes)}\n`} js+=prefix+`$B.set_lineno(frame, ${this.lineno}, 'ClassDef')\n` var qualname=this.name var ix=scopes.length-1 while(ix >=0){if(scopes[ix].parent){ix--}else if(scopes[ix].ast instanceof $B.ast.ClassDef){qualname=scopes[ix].name+'.'+qualname ix--}else{break}} var bases=this.bases.map(x=> $B.js_from_ast(x,scopes)) var has_type_params=this.type_params.length > 0 if(has_type_params){check_type_params(this) js+=prefix+`function TYPE_PARAMS_OF_${this.name}(){\n` indent() js+=prefix+`$B.$import('_typing')\n`+ prefix+`var _typing = $B.imported._typing\n` var params=[],need_typing_module for(let item of this.type_params){if(item instanceof $B.ast.TypeVar){params.push(`${item.name}`)}else if(item instanceof $B.ast.TypeVarTuple){params.push(`unpack(${item.name})`) need_typing_module=true}else if(item instanceof $B.ast.ParamSpec){params.push(`${item.name}`)}} bases.push(`generic_base`) if(need_typing_module){js+=prefix+`$B.$import('typing')\n`+ prefix+'var typing = $B.imported.typing\n'+ prefix+`var unpack = $B.$call($B.$getattr(typing.Unpack, '__getitem__'))\n`} var name_map=new Map() for(let item of this.type_params){var name,param_type=item.constructor.$name if(['TypeVar','TypeVarTuple','ParamSpec'].includes(param_type)){name=item.name}else{name=item.name.id} name_map.set(item,name) js+=prefix+`var ${name} = $B.$call(_typing.${param_type})('${name}')\n`} js+=prefix+`var generic_base = _typing.Generic.__class_getitem__(_typing.Generic,`+ ` $B.fast_tuple([${params.join(', ')}]))\n`} var keywords=[],metaclass,meta='' for(var keyword of this.keywords){if(keyword.arg=='metaclass'){metaclass=keyword.value meta=metaclass.to_js(scopes)}else{keywords.push(`["${keyword.arg}", `+ $B.js_from_ast(keyword.value,scopes)+']')}} var docstring=extract_docstring(this,scopes) var inum=add_to_positions(scopes,this) js+=prefix+`var ${ref} = (function(name, module, bases` +(metaclass ? ', meta' :'')+ `){\n` indent() js+=prefix+`$B.frame_obj.frame.inum = ${inum}\n` js+=prefix+`var _frame_obj = $B.frame_obj,\n` indent(2) js+=prefix+`resolved_bases = $B.resolve_mro_entries(bases),\n`+ prefix+`metaclass = $B.get_metaclass(name, module, `+ `resolved_bases` if(metaclass){js+=`, meta`} js+=')\n' dedent(2) js+=prefix+`var ${locals_name} = $B.make_class_namespace(metaclass, `+ `name, module, "${qualname}", bases, resolved_bases),\n` indent(2) js+=prefix+`locals = ${locals_name}\n` dedent(2) js+=prefix+`locals.__doc__ = ${docstring}\n` js+=prefix+`var frame = [name, locals, module, ${globals_name}]\n`+ prefix+`$B.enter_frame(frame, __file__, ${this.lineno})\n`+ prefix+`var _frame_obj = $B.frame_obj\n`+ prefix+`if(frame.$f_trace !== _b_.None){\n`+ prefix+tab+`$B.trace_line()\n`+ prefix+`}\n` if(has_type_params){var tp_refs=[] for(var item of this.type_params){tp_refs.push(`${name_map.get(item)}`)} js+=prefix+`locals.__type_params__ = $B.fast_tuple([${tp_refs.join(', ')}])\n`} scopes.push(class_scope) var index_for_positions=js.length js+=add_body(this.body,scopes)+'\n' if(class_scope.positions){js=js.substr(0,index_for_positions)+ prefix+`frame.positions = [${class_scope.positions}]\n`+ js.substr(index_for_positions)} scopes.pop() var static_attrs=[] if(class_scope.static_attributes){static_attrs=Array.from(class_scope.static_attributes).map(x=> `"${x}"`)} js+=annotation_code(scopes,class_scope,class_ref) js+=prefix+`var kls = $B.$class_constructor('${this.name}', frame, metaclass, `+ `resolved_bases, bases, [${keywords.join(', ')}], `+ `[${static_attrs}], annotate, ${this.lineno})\n`+ prefix+'$B.trace_return_and_leave(frame, _b_.None)\n'+ prefix+'return kls\n' dedent() js+=prefix+`})('${this.name}',${globals_name}.__name__ ?? '${glob}', `+ `$B.fast_tuple([${bases}])`+ (metaclass ? ', '+meta :'')+ `)\n` if(has_type_params){js+=prefix+`return ${ref}\n` dedent() js+=prefix+'}\n'} var class_ref=reference(scopes,enclosing_scope,this.name) js+=prefix if(decorated){class_ref=`decorated${make_id()}` js+='var '} js+=`${class_ref} = ` if(has_type_params){js+=`TYPE_PARAMS_OF_${this.name}()\n`}else{js+=`${ref}\n`} if(decorated){js+=prefix+reference(scopes,enclosing_scope,this.name)+' = ' var decorate=class_ref for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`} js+=decorate+'\n'} return js} $B.ast.Compare.prototype.to_js=function(scopes){var test_left=check_is_arg(this.left) var left=$B.js_from_ast(this.left,scopes),comps=[] var len=this.ops.length,prefix for(var i=0;i < len;i++){var name=this.ops[i].$name ? this.ops[i].$name :this.ops[i].constructor.$name,op=opclass2dunder[name],right=this.comparators[i] if(op===undefined){console.log('op undefined',this.ops[i]) alert()} prefix=i < len-1 ? 'locals.$op = ' :'' if(this.ops[i]instanceof $B.ast.In){comps.push(`$B.$is_member(${left}, `+ `${prefix}${$B.js_from_ast(right, scopes)})`)}else if(this.ops[i]instanceof $B.ast.NotIn){comps.push(`! $B.$is_member(${left}, `+ `${prefix}${$B.js_from_ast(right, scopes)})`)}else if(this.ops[i]instanceof $B.ast.Is){check_compare('is',this.left,right,scopes) comps.push(`$B.$is(${left}, `+ `${prefix}${$B.js_from_ast(right, scopes)})`)}else if(this.ops[i]instanceof $B.ast.IsNot){check_compare('is not',this.left,right,scopes) comps.push(`! $B.$is(${left}, `+ `${prefix}${$B.js_from_ast(right, scopes)})`)}else{comps.push(`$B.rich_comp('${op}', ${left}, `+ `${prefix}${$B.js_from_ast(right, scopes)})`)} if(len > 1){left='locals.$op'}} return comps.join(' && ')} $B.ast.comprehension.prototype.to_js=function(scopes){var id=make_id(),iter=$B.js_from_ast(this.iter,scopes) var js=prefix+`var next_func_${id} = $B.make_js_iterator(${iter}, frame, ${this.lineno})\n`+ prefix+`for(var next_${id} of next_func_${id}){\n` indent() var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load()) copy_position(name,this.target) name.to_js=function(){return `next_${id}`} var assign=new $B.ast.Assign([this.target],name) copy_position(assign,this.target) js+=assign.to_js(scopes)+'\n' for(var _if of this.ifs){js+=prefix+`if($B.$bool(${$B.js_from_ast(_if, scopes)})){\n` indent()} return js} $B.ast.Constant.prototype.to_js=function(){if(this.kind){console.log('constant kind',this.kind)} if(this.value===true ||this.value===false){return this.value+''}else if(this.value===_b_.None){return '_b_.None'}else if(typeof this.value=="string"){var s=this.value,srg=$B.surrogates(s) if(srg.length==0){return `'${s}'`} return `$B.make_String('${s}', [${srg}])`}else if(this.value.__class__===_b_.bytes){return `_b_.bytes.$factory([${this.value.source}])`}else if(typeof this.value=="number"){if(Number.isInteger(this.value)){return this.value}else{return `({__class__: _b_.float, value: ${this.value}})`}}else if(this.value.__class__===$B.long_int){return `$B.fast_long_int(${this.value.value}n)`}else if(this.value.__class__===_b_.float){return `({__class__: _b_.float, value: ${this.value.value}})`}else if(this.value.__class__===_b_.complex){return `$B.make_complex(${this.value.$real.value}, ${this.value.$imag.value})`}else if(this.value===_b_.Ellipsis){return `_b_.Ellipsis`}else{console.log('invalid value',this.value) throw SyntaxError('bad value',this.value)}} $B.ast.Continue.prototype.to_js=function(scopes){if(! in_loop(scopes)){compiler_error(this,"'continue' not properly in loop")} return prefix+'continue'} $B.ast.Delete.prototype.to_js=function(scopes){compiler_check(this) var js='' for(var target of this.targets){var inum=add_to_positions(scopes,target) if(target instanceof $B.ast.Name){var scope=name_scope(target.id,scopes) var locals_id='null' if(scope.found){scope.found.locals.delete(target.id) locals_id='locals_'+ qualified_scope_name(scopes,scope.found) js+=`$B.$delete("${target.id}", ${locals_id}, ${inum})\n`}else{js+=`$B.$delete('${target.id}', '${scope.resolve}', ${inum})\n`}}else if(target instanceof $B.ast.Subscript){js+=`$B.$delitem(${$B.js_from_ast(target.value, scopes)}, `+ `${$B.js_from_ast(target.slice, scopes)}, ${inum})\n`}else if(target instanceof $B.ast.Attribute){js+=`$B.$delattr(${$B.js_from_ast(target.value, scopes)}, `+ `'${target.attr}', ${inum})\n`}} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+js} $B.ast.Delete.prototype._check=function(){for(var target of this.targets){check_assign_or_delete(this,target,'delete')}} $B.ast.Dict.prototype.to_js=function(scopes){var items=[],keys=this.keys,has_packed=false function no_key(i){return keys[i]===_b_.None ||keys[i]===undefined} for(let i=0,len=this.keys.length;i < len;i++){if(no_key(i)){ has_packed=true items.push('_b_.list.$factory(_b_.dict.items('+ $B.js_from_ast(this.values[i],scopes)+'))')}else{var item=`[${$B.js_from_ast(this.keys[i], scopes)}, `+ `${$B.js_from_ast(this.values[i], scopes)}` if(this.keys[i]instanceof $B.ast.Constant){var v=this.keys[i].value if(typeof v=='string'){item+=', '+$B.$hash(string_from_ast_value(v))}else{try{var hash=$B.$hash(this.keys[i].value) item+=`, ${hash}`}catch(err){}}} items.push(item+']')}} if(! has_packed){return `_b_.dict.$literal([${items}])`} var first=no_key(0)? items[0]:`[${items[0]}]`,js='_b_.dict.$literal('+first for(let i=1,len=items.length;i < len;i++){let arg=no_key(i)? items[i]:`[${items[i]}]` js+=`.concat(${arg})`} return js+')'} $B.ast.DictComp.prototype.to_js=function(scopes){return make_comp.bind(this)(scopes)} $B.ast.Expr.prototype.to_js=function(scopes){return prefix+`$B.set_lineno(frame, ${this.lineno});\n`+ prefix+$B.js_from_ast(this.value,scopes)} $B.ast.Expression.prototype.to_js=function(scopes){init_scopes.bind(this)('expression',scopes) var res=$B.js_from_ast(this.body,scopes) var positions=scopes[scopes.length-1].positions if(positions){res=prefix+`(frame.positions = [${positions}], `+ res+')'} return res} $B.ast.For.prototype.to_js=function(scopes){ compiler_check(this) var id=make_id(),iter=$B.js_from_ast(this.iter,scopes),js=prefix+`frame.$lineno = ${this.lineno}\n` var scope=$B.last(scopes),new_scope=copy_scope(scope,this,id) scopes.push(new_scope) if(this instanceof $B.ast.AsyncFor){js+=prefix+`var no_break_${id} = true,\n`+ prefix+tab+tab+`iter_${id} = ${iter},\n`+ prefix+tab+tab+`type_${id} = _b_.type.$factory(iter_${id})\n`+ prefix+`iter_${id} = $B.$call($B.$getattr(type_${id}, "__aiter__"))(iter_${id})\n`+ prefix+`type_${id} = _b_.type.$factory(iter_${id})\n`+ prefix+`var next_func_${id} = $B.$call(`+ `$B.$getattr(type_${id}, '__anext__'))\n`+ prefix+`while(true){\n` indent() js+=prefix+`try{\n`+ prefix+tab+`var next_${id} = await $B.promise(next_func_${id}(iter_${id}))\n`+ prefix+`}catch(err){\n`+ prefix+tab+`if($B.is_exc(err, [_b_.StopAsyncIteration])){\n`+ prefix+tab+tab+`break\n`+ prefix+tab+`}else{\n`+ prefix+tab+tab+`throw err\n`+ prefix+tab+'}\n'+ prefix+`}\n` dedent()}else{js+=prefix+`var no_break_${id} = true,\n`+ prefix+tab+tab+`iterator_${id} = ${iter}\n` if(this.iter.inum){js+=prefix+tab+tab+`iterator_${id}.$inum = ${this.iter.inum}\n`} js+=prefix+`for(var next_${id} of $B.make_js_iterator(`+ `iterator_${id}, frame, ${this.lineno})){\n`} var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load()) copy_position(name,this.iter) name.to_js=function(){return `next_${id}`} var assign=new $B.ast.Assign([this.target],name) assign.$loopvar=true copy_position(assign,this.target) indent() js+=assign.to_js(scopes)+'\n' js+=add_body(this.body,scopes) dedent() js+='\n'+prefix+'}\n' scopes.pop() if(this.orelse.length > 0){js+=prefix+`if(no_break_${id}){\n` indent() js+=add_body(this.orelse,scopes)+'\n' dedent() js+=prefix+'}\n'} return js} $B.ast.FormattedValue.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes) if(this.conversion==114){value=`_b_.repr(${value})`}else if(this.conversion==115){value=`_b_.str.$factory(${value})`}else if(this.conversion==97){value=`_b_.ascii(${value})`} if(this.format_spec){value=`_b_.str.format('{0:' + `+ $B.js_from_ast(this.format_spec,scopes)+ ` + '}', ${value})`}else if(this.conversion==-1){value=`_b_.str.$factory(${value})`} return value} function transform_args(scopes){ var has_posonlyargs=this.args.posonlyargs.length > 0,_defaults=[],nb_defaults=this.args.defaults.length,positional=this.args.posonlyargs.concat(this.args.args),ix=positional.length-nb_defaults,default_names=[],kw_defaults=[],annotations for(let arg of positional.concat(this.args.kwonlyargs).concat( [this.args.vararg,this.args.kwarg])){if(arg && arg.annotation){annotations=annotations ||{} annotations[arg.arg]=arg.annotation}} for(var i=ix;i < positional.length;i++){default_names.push(`${positional[i].arg}`) _defaults.push(`${positional[i].arg}: `+ `${$B.js_from_ast(this.args.defaults[i - ix], scopes)}`)} ix=-1 for(let arg of this.args.kwonlyargs){ix++ if(this.args.kw_defaults[ix]===_b_.None){continue} if(this.args.kw_defaults[ix]===undefined){_defaults.push(`${arg.arg}: _b_.None`)}else{var v=$B.js_from_ast(this.args.kw_defaults[ix],scopes) _defaults.push(`${arg.arg}: `+v) kw_defaults.push(`${arg.arg}: ${v}`)}} var kw_default_names=[] for(var kw of this.args.kwonlyargs){kw_default_names.push(`'${kw.arg}'`)} return{default_names,_defaults,positional,has_posonlyargs,kw_defaults,kw_default_names,annotations}} function type_param_in_def(tp,ref,scopes){var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]) var js='' var name,param_type=tp.constructor.$name if(['TypeVar','TypeVarTuple','ParamSpec'].includes(param_type)){name=tp.name}else{name=tp.name.id} bind(name,scopes) if(tp.bound){ var typevarscope=new Scope(name,'typevarbound',tp) scopes.push(typevarscope) js+=`function BOUND_OF_${name}(){\n`+ `var current_frame = $B.frame_obj.frame,\n`+ `frame = ['BOUND_OF_${name}', {}, '${gname}', ${globals_name}]\n`+ `$B.enter_frame(frame, __file__, ${tp.bound.lineno})\n`+ `try{\n`+ `var res = ${tp.bound.to_js(scopes)}\n`+ `$B.leave_frame()\nreturn res\n`+ `}catch(err){\n`+ `$B.leave_frame()\n`+ `throw err\n}\n}\n` scopes.pop()} js+=prefix+`locals_${ref}.${name} = `+ `$B.$call(_typing.${param_type})('${name}', {$kw: [{infer_variance: true}]})\n`+ prefix+`type_params.push(locals_${ref}.${name})\n` if(tp.bound){if(! tp.bound.elts){js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+ `'__bound__', BOUND_OF_${name})\n`}else{js+=`_typing.${param_type}._set_lazy_eval(locals_${ref}.${name}, `+ `'__constraints__', BOUND_OF_${name})\n`}} return js} $B.ast.FunctionDef.prototype.to_js=function(scopes){compiler_check(this) var symtable_block=scopes.symtable.table.blocks.get(fast_id(this)) var in_class=last_scope(scopes).ast instanceof $B.ast.ClassDef,is_async=this instanceof $B.ast.AsyncFunctionDef,mangle_arg=x=> x if(in_class){var class_scope=last_scope(scopes) mangle_arg=x=> mangle(scopes,class_scope,x)} var func_name_scope=bind(this.name,scopes) var gname=scopes[0].name,globals_name=make_scope_name(scopes,scopes[0]) var decorators=[],decorated=false,decs_declare=this.decorator_list.length > 0 ? prefix+'// declare decorators\n' :'' for(let dec of this.decorator_list){decorated=true var dec_id='decorator'+make_id() decorators.push(dec_id) decs_declare+=prefix+`$B.set_lineno(frame, ${dec.lineno})\n` decs_declare+=prefix+`var ${dec_id} = ${$B.js_from_ast(dec, scopes)}\n`} var docstring=extract_docstring(this,scopes) var parsed_args=transform_args.bind(this)(scopes),positional=parsed_args.positional,kw_defaults=parsed_args.kw_defaults,kw_default_names=parsed_args.kw_default_names var defaults=this.args.defaults.length==0 ? '_b_.None' : `[${this.args.defaults.map(x => x.to_js(scopes))}]` kw_defaults=kw_default_names.length==0 ? '_b_.None' : `{${kw_defaults.join(', ')}}` var id=make_id(),name2=this.name+id var has_type_params=this.type_params.length > 0,type_params='' if(has_type_params){ check_type_params(this) var tp_name=`type_params_${name2}` var type_params_scope=new Scope(tp_name,'type_params',this.type_params) scopes.push(type_params_scope) var type_params_ref=qualified_scope_name(scopes,type_params_scope) var type_params_func=`function TYPE_PARAMS_OF_${name2}(){\n` type_params=prefix+`$B.$import('_typing')\n`+ prefix+`var _typing = $B.imported._typing\n`+ prefix+`var locals_${type_params_ref} = {},\n`+ prefix+tab+tab+`locals = locals_${type_params_ref},\n`+ prefix+tab+tab+`frame = ['${type_params_ref}', locals, '${gname}', ${globals_name}],\n`+ prefix+tab+tab+`type_params = []\n`+ prefix+`$B.enter_frame(frame, '${scopes.filename}', ${this.lineno})\n` for(var item of this.type_params){type_params+=type_param_in_def(item,type_params_ref,scopes)} type_params_func+=type_params} var func_scope=new Scope(this.name,'def',this) scopes.push(func_scope) var args=positional.concat(this.args.kwonlyargs),slots=[],arg_names=[] for(let arg of args){slots.push(arg.arg+': null') bind(arg.arg,scopes)} for(let arg of this.args.posonlyargs){arg_names.push(`'${mangle_arg(arg.arg)}'`)} for(let arg of this.args.args.concat(this.args.kwonlyargs)){arg_names.push(`'${mangle_arg(arg.arg)}'`)} if(this.args.vararg){bind(mangle_arg(this.args.vararg.arg),scopes)} if(this.args.kwarg){bind(mangle_arg(this.args.kwarg.arg),scopes)} var is_generator=symtable_block.generator var function_body indent(is_generator ? 3 :2) if(this.$is_lambda){var _return=new $B.ast.Return(this.body) copy_position(_return,this.body) var body=[_return] function_body=add_body(body,scopes)}else{function_body=add_body(this.body,scopes)} dedent(is_generator ? 3 :2) var parse_args=[name2] var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+prefix if(is_async && ! is_generator){js+='async '} js+=`function ${name2}(){\n` indent() var locals_name=make_scope_name(scopes,func_scope) js+=prefix+`var locals\n` parse_args.push('arguments') var args_vararg=this.args.vararg===undefined ? 'null' : "'"+mangle_arg(this.args.vararg.arg)+"'",args_kwarg=this.args.kwarg===undefined ? 'null': "'"+mangle_arg(this.args.kwarg.arg)+"'" if(positional.length==0 && slots.length==0 && this.args.vararg===undefined && this.args.kwarg===undefined){js+=prefix+`var ${locals_name} = locals = {};\n` js+=prefix+`if(arguments.length !== 0){\n`+ prefix+tab+`${name2}.$args_parser(${parse_args.join(', ')})\n`+ prefix+`}\n`}else if(this.name=='fxd51jy'){js+=prefix+`var ${locals_name} = locals = `+ `$B.args_parser(${name2}, arguments)\n`}else{js+=prefix+`var ${locals_name} = locals = `+ `${name2}.$args_parser(${parse_args.join(', ')})\n`} js+=prefix+`var frame = ["${this.$is_lambda ? '': this.name}", `+ `locals, "${gname}", ${globals_name}, ${name2}]\n`+ prefix+`$B.enter_frame(frame, __file__, ${this.lineno})\n` if(func_scope.positions){js+=prefix+`frame.positions = [${func_scope.positions}]\n`} if(func_scope.needs_stack_length){js+=prefix+`var stack_length = $B.count_frames()\n`} if(func_scope.needs_frames ||is_async){js+=prefix+`var _frame_obj = $B.frame_obj\n`} if(is_async){js+=prefix+'frame.$async = true\n'} if(is_generator){js+=prefix+`locals.$is_generator = true\n` if(is_async){js+=prefix+`var gen_${id} = async function*(){\n`}else{js+=prefix+`var gen_${id} = function*(){\n`} indent()} js+=prefix+`try{\n` indent() js+=prefix+`$B.js_this = this\n` if(in_class){ var ix=scopes.indexOf(class_scope),parent=scopes[ix-1] var scope_ref=make_scope_name(scopes,parent),class_ref=class_scope.name, refs=class_ref.split('.').map(x=> `'${x}'`) bind("__class__",scopes) js+=prefix+`locals.__class__ = `+ `$B.get_method_class(${name2}, ${scope_ref}, "${class_ref}", [${refs}])\n`} js+=function_body+'\n' if((! this.$is_lambda)&& !($B.last(this.body)instanceof $B.ast.Return)){ js+=prefix+'return $B.trace_return_and_leave(frame, _b_.None)\n'} dedent() js+=prefix+`}catch(err){\n` indent() if(func_scope.needs_frames){js+=prefix+`$B.set_exc_and_trace(frame, err)\n`+ `$B.leave_frame()\n`+ `throw err\n`}else{js+=prefix+`$B.set_exc_and_leave(frame, err)\n`} dedent() js+=prefix+`}\n` dedent() js+=prefix+`}` if(is_generator){js+='\n'+prefix+`gen_${id} = ` if(is_async){js+=`$B.async_generator.$factory(`}else{js+=`$B.generator.$factory(`} js+=`gen_${id}, '${this.name}')\n` js+=prefix+`var _gen_${id} = gen_${id}()\n`+ prefix+`_gen_${id}.$frame = frame\n`+ prefix+`$B.leave_frame()\n`+ prefix+`return _gen_${id}\n` dedent() js+=prefix+'}\n'}else{js+='\n'} scopes.pop() var qualname=in_class ? `${func_name_scope.name}.${this.name}` : this.name var flags=$B.COMPILER_FLAGS.OPTIMIZED |$B.COMPILER_FLAGS.NEWLOCALS if(this.args.vararg){flags |=$B.COMPILER_FLAGS.VARARGS} if(this.args.kwarg){flags |=$B.COMPILER_FLAGS.VARKEYWORDS} if(is_generator){flags |=$B.COMPILER_FLAGS.GENERATOR} if(is_async){flags |=$B.COMPILER_FLAGS.COROUTINE} var parameters=[],locals=[],identifiers=_b_.dict.$keys_string(symtable_block.symbols) var free_vars=[] for(var ident of identifiers){var flag=_b_.dict.$getitem_string(symtable_block.symbols,ident),_scope=(flag >> SF.SCOPE_OFF)& SF.SCOPE_MASK if(_scope==SF.FREE){free_vars.push(`'${ident}'`)} if(flag & SF.DEF_PARAM){parameters.push(`'${ident}'`)}else if(flag & SF.DEF_LOCAL){locals.push(`'${ident}'`)}} var varnames=parameters.concat(locals) if(in_class){js+=prefix+`${name2}.$is_method = true\n`} var anns,anns_values,anns_strings,postponed if(this.returns ||parsed_args.annotations){var features=scopes.symtable.table.future.features,postponed=features & $B.CO_FUTURE_ANNOTATIONS if(postponed){ var src=scopes.src if(src===undefined){console.log('no src, filename',scopes)}} var ann_items_values=[] var ann_items_strings=[] if(parsed_args.annotations){for(var arg_ann in parsed_args.annotations){var ann_ast=parsed_args.annotations[arg_ann] if(in_class){arg_ann=mangle(scopes,class_scope,arg_ann)} var ann_str=annotation_to_str(ann_ast,scopes) ann_items_strings.push(`['${arg_ann}', '${ann_str}']`) var value=ann_ast.to_js(scopes) ann_items_values.push(`['${arg_ann}', ${value}]`)}} if(this.returns){var ann_str=annotation_to_str(this.returns,scopes) ann_items_strings.push(`['return', '${ann_str}']`) var ann_value if(scopes.postpone_annotations){ann_value=`'${annotation_to_str(this.returns, scopes)}'`}else{ann_value=this.returns.to_js(scopes)} ann_items_values.push(`['return', ${ann_value}]`)} anns_values=`[${ann_items_values.join(', ')}]` anns_strings=`[${ann_items_strings.join(', ')}]` anns=ann_items_values.length > 0}else{anns=false} var annotations=postponed ? anns_strings :'false' js+=prefix+`${name2}.$function_infos = [`+ `'${gname}', `+ `'${this.$is_lambda ? '': this.name}', `+ `'${this.$is_lambda ? '': qualname}', `+ `__file__, `+ `${defaults}, `+ `${kw_defaults}, `+ `${docstring}, `+ `[${arg_names}], `+ `${args_vararg}, `+ `${args_kwarg},\n`+ prefix+tab+`${positional.length}, `+ `${this.lineno}, `+ `${flags}, `+ `[${free_vars}], `+ `${this.args.kwonlyargs.length}, `+ `${this.args.posonlyargs.length}, `+ `[${varnames}], `+ `${annotations}, `+ `${has_type_params ? 'type_params' : '[]'}]\n`; js+=prefix+`${name2}.$args_parser = $B.make_args_parser_and_parse\n` if(anns && ! postponed){ var inum=add_to_positions(scopes,this) js+=prefix+`${name2}.__annotate__ = function(format){\n` indent() js+=prefix+`var locals = {format}\n`+ prefix+`var frame = ['__annotate__', locals, '${gname}', ${globals_name}]\n`+ prefix+`$B.enter_frame(frame, __file__, ${this.lineno})\n`+ prefix+`frame.positions = $B.frame_obj.prev.frame.positions\n`+ prefix+`frame.positions.push([${this.lineno}, ${this.end_lineno}, ${this.col_offset}, ${this.end_col_offset}])\n`+ prefix+'try{\n' indent() js+=prefix+`if(format == 1 || format == 2){\n`+ prefix+tab+`var res = _b_.dict.$literal(${anns_values})\n`+ prefix+tab+`return $B.trace_return_and_leave(frame, res)\n`+ prefix+'}\n'+ prefix+`frame.inum = 2 * frame.positions.length - 1\n`+ prefix+`$B.RAISE(_b_.NotImplementedError, '')\n` dedent() js+=prefix+`}catch(err){\n` indent() js+=prefix+`$B.set_exc_and_leave(frame, err)\n` dedent() js+=prefix+'}\n' dedent() js+=prefix+`}\n`}else{js+=prefix+`${name2}.__annotate__ = _b_.None\n`} if(is_async && ! is_generator){js+=prefix+`${name2} = $B.make_async(${name2})\n`} var mangled=mangle(scopes,func_name_scope,this.name),func_ref=`${make_scope_name(scopes, func_name_scope)}.${mangled}` if(decorated){func_ref=`decorated${make_id()}` js+=prefix+'var '}else{js+=prefix} js+=`${func_ref} = ${name2}\n` if(has_type_params){scopes.pop()} if(decorated && ! has_type_params){js+=prefix+`${make_scope_name(scopes, func_name_scope)}.${mangled} = ` let decorate=func_ref for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`} js+=decorate} if(has_type_params){ type_params_func+='\n'+js+'\n'+ `${name2}.__type_params__ = $B.fast_tuple(type_params)\n`+ `$B.leave_frame()\n`+ `return ${name2}\n}\n` js=type_params_func if(decorated){ js+=`var ${func_ref} = TYPE_PARAMS_OF_${name2}()\n`+ `${make_scope_name(scopes, func_name_scope)}.${mangled} = ` let decorate=func_ref for(let dec of decorators.reverse()){decorate=`$B.$call(${dec})(${decorate})`} js+=decorate}else{js+=`var locals_${type_params_ref} = TYPE_PARAMS_OF_${name2}()\n`}} js=decs_declare+js return js} $B.ast.FunctionDef.prototype._check=function(){for(var arg of this.args.args){if(arg instanceof $B.ast.arg){if(arg.arg=='__debug__'){compiler_error(arg,'cannot assign to __debug__')}}} for(var arg of this.args.kwonlyargs){if(arg instanceof $B.ast.arg){if(arg.arg=='__debug__'){compiler_error(arg,'cannot assign to __debug__')}}} if(this.args.kwarg && this.args.kwarg.arg=='__debug__'){compiler_error(this.args.kwarg,'cannot assign to __debug__')}} $B.ast.GeneratorExp.prototype.to_js=function(scopes){var id=make_id(),symtable_block=scopes.symtable.table.blocks.get(fast_id(this)),varnames=symtable_block.varnames.map(x=> `"${x}"`) var first_for=this.generators[0], outmost_expr=$B.js_from_ast(first_for.iter,scopes),nb_paren=1 var comp_scope=new Scope(`genexpr_${id}`,'comprehension',this) scopes.push(comp_scope) var comp={ast:this,id,type:'genexpr',varnames,module_name:scopes[0].name,locals_name:make_scope_name(scopes),globals_name:make_scope_name(scopes,scopes[0])} indent() var head=init_comprehension(comp,scopes) var js=prefix+`var gen${id} = $B.generator.$factory(${has_await ? 'async ' : ''}function*(expr){\n` var first=this.generators[0] indent() js+=prefix+`$B.enter_frame(frame, __file__, ${this.lineno})\n`+ prefix+`var next_func_${id} = $B.make_js_iterator(expr, frame, ${this.lineno})\n`+ prefix+`for(var next_${id} of next_func_${id}){\n` indent() js+=prefix+`$B.enter_frame(frame, __file__, ${this.lineno})\n` var name=new $B.ast.Name(`next_${id}`,new $B.ast.Load()) copy_position(name,first_for.iter) name.to_js=function(){return `next_${id}`} var assign=new $B.ast.Assign([first.target],name) assign.lineno=this.lineno js+=assign.to_js(scopes)+'\n' for(let _if of first.ifs){nb_paren++ js+=prefix+`if($B.$bool(${$B.js_from_ast(_if, scopes)})){\n` indent()} for(var comprehension of this.generators.slice(1)){js+=comprehension.to_js(scopes) nb_paren++ for(let _if of comprehension.ifs){nb_paren++}} dedent(2) var elt=$B.js_from_ast(this.elt,scopes),has_await=comp_scope.has_await dedent() indent(3) js+=has_await ? prefix+'var save_frame_obj = $B.frame_obj;\n' :'' js+=prefix+`try{\n`+ prefix+tab+`yield ${elt}\n`+ prefix+`}catch(err){\n`+ (has_await ? prefix+tab+'$B.restore_frame_obj(save_frame_obj, locals)\n' :'')+ prefix+tab+`$B.leave_frame()\n`+ prefix+tab+`throw err\n`+ prefix+`}\n` dedent() js+=(has_await ? prefix+'\n$B.restore_frame_obj(save_frame_obj, locals);' :'') for(var i=0;i < nb_paren-1;i++){js+=prefix+'}\n' dedent()} js+=prefix+'$B.leave_frame()\n' dedent() js+=prefix+'}\n' js+=prefix+'$B.leave_frame()\n' js+=prefix+'}, "")(expr)\n' scopes.pop() var func=`${head}\n${js}\n`+prefix+`return gen${id}` dedent() return prefix+`(function(expr){\n${func}\n`+ prefix+`})(${outmost_expr})\n`} $B.ast.Global.prototype.to_js=function(scopes){var scope=last_scope(scopes) for(var name of this.names){scope.globals.add(name)} return ''} $B.ast.If.prototype.to_js=function(scopes){var scope=$B.last(scopes),new_scope=copy_scope(scope,this) var js=prefix+`if($B.set_lineno(frame, ${this.lineno}) && ` if(this.test instanceof $B.ast.BoolOp){this.test.$dont_evaluate=true js+=`${$B.js_from_ast(this.test, scopes)}){\n`}else{js+=`$B.$bool(${$B.js_from_ast(this.test, scopes)})){\n`} scopes.push(new_scope) indent() js+=add_body(this.body,scopes)+'\n' dedent() js+=prefix+'}' scopes.pop() if(this.orelse.length > 0){if(this.orelse[0]instanceof $B.ast.If && this.orelse.length==1){js+='else '+$B.js_from_ast(this.orelse[0],scopes).trimLeft() indent() js+=add_body(this.orelse.slice(1),scopes) dedent()}else{js+='else{\n' scopes.push(copy_scope(scope,this)) indent() js+=add_body(this.orelse,scopes) dedent() scopes.pop() js+='\n'+prefix+'}'}} return js} $B.ast.IfExp.prototype.to_js=function(scopes){return '($B.$bool('+$B.js_from_ast(this.test,scopes)+') ? '+ $B.js_from_ast(this.body,scopes)+': '+ $B.js_from_ast(this.orelse,scopes)+')'} $B.ast.Import.prototype.to_js=function(scopes){var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n` var inum=add_to_positions(scopes,this) for(var alias of this.names){js+=prefix+`$B.$import("${alias.name}", [], ` if(alias.asname){var binding_scope=bind(alias.asname,scopes) var scope_name=make_scope_name(scopes,binding_scope) js+=`{'${alias.name}': [${scope_name}, '${alias.asname}']}, `}else{js+='{}, ' var binding_scope=bind(alias.name,scopes) var scope_name=make_scope_name(scopes,binding_scope)} var parts=alias.name.split('.') for(var i=0;i < parts.length;i++){scopes.imports[parts.slice(0,i+1).join(".")]=true} js+=`${scope_name}, ${inum})\n`} return js.trimRight()} $B.ast.ImportFrom.prototype.to_js=function(scopes){if(this.module==='__future__'){if(!($B.last(scopes).ast instanceof $B.ast.Module)){compiler_error(this,'from __future__ imports must occur at the beginning of the file',$B.last(this.names))}} var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+`$B.$import_from("${this.module || ''}", ` var names=this.names.map(x=> `"${x.name}"`).join(', '),aliases=[] for(var name of this.names){if(name.asname){ var binding_scope=bind(name.asname,scopes) var scope_name=make_scope_name(scopes,binding_scope) aliases.push(`${name.name}: [${scope_name}, '${name.asname}']`)}} var inum=add_to_positions(scopes,this) js+=`[${names}], {${aliases.join(', ')}}, ${this.level}, locals, ${inum});` for(var alias of this.names){if(alias.asname){}else if(alias.name=='*'){ last_scope(scopes).blurred=true}else{bind(alias.name,scopes)}} return js} $B.ast.Interactive.prototype.to_js=function(scopes){mark_parents(this) var name=init_scopes.bind(this)('module',scopes) var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes) var js=`// Javascript code generated from ast\n`+ `var $B = __BRYTHON__,\n_b_ = $B.builtins,\n` js+=`${global_name} = {}, // $B.imported["${mod_name}"],\n`+ `locals = ${global_name},\n`+ `frame = ["${module_id}", locals, "${module_id}", locals]` js+=`\nvar __file__ = '${scopes.filename ?? ""}'\n`+ `locals.__name__ = '${name}'\n`+ `locals.__doc__ = ${extract_docstring(this, scopes)}\n` if(! scopes.imported){js+=`locals.__annotations__ = locals.__annotations__ || $B.empty_dict()\n`} js+=`$B.enter_frame(frame, __file__, 1)\n` js+='\nvar _frame_obj = $B.frame_obj\n' js+='var stack_length = $B.count_frames()\n' js+=`try{\n`+ add_body(this.body,scopes)+'\n'+ `$B.leave_frame({locals, value: _b_.None})\n`+ `}catch(err){\n`+ `$B.set_exc_and_trace(frame, err)\n`+ `$B.leave_frame({locals, value: _b_.None})\n`+ 'throw err\n'+ `}` scopes.pop() console.log('Interactive',js) return js} $B.ast.Interpolation.prototype.to_js=function(scopes){var conversion=this.conversion==-1 ? "_b_.None" :`'${this.conversion}'` return `[${this.value.to_js(scopes)}, '${this.value.id}', `+ `${conversion}, ${this.format_spec ?? "''"}]`} $B.ast.JoinedStr.prototype.to_js=function(scopes){var items=this.values.map(s=> $B.js_from_ast(s,scopes)) if(items.length==0){return "''"} return items.join(' + ')} $B.ast.Lambda.prototype.to_js=function(scopes){ var id=make_id(),name='lambda_'+$B.lambda_magic+'_'+id var f=new $B.ast.FunctionDef(name,this.args,this.body,[]) f.lineno=this.lineno f.$id=fast_id(this) f.$is_lambda=true indent() var js=f.to_js(scopes),lambda_ref=reference(scopes,last_scope(scopes),name) js=`(function(){\n${js}\n`+ prefix+`return ${lambda_ref}\n` dedent() return js+prefix+`})()`} function list_or_tuple_to_js(func,scopes){if(this.elts.filter(x=> x instanceof $B.ast.Starred).length > 0){var parts=[],simple=[] for(var elt of this.elts){if(elt instanceof $B.ast.Starred){elt.$handled=true parts.push(`[${simple.join(', ')}]`) simple=[] parts.push(`_b_.list.$factory(${$B.js_from_ast(elt, scopes)})`)}else{simple.push($B.js_from_ast(elt,scopes))}} if(simple.length > 0){parts.push(`[${simple.join(', ')}]`)} var js=parts[0] for(var part of parts.slice(1)){js+=`.concat(${part})`} return `${func}(${js})`} var elts=this.elts.map(x=> $B.js_from_ast(x,scopes)) return `${func}([${elts.join(', ')}])`} $B.ast.List.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)('$B.$list',scopes)} $B.ast.ListComp.prototype.to_js=function(scopes){compiler_check(this) return make_comp.bind(this)(scopes)} $B.ast.match_case.prototype.to_js=function(scopes){var js=`($B.set_lineno(frame, ${this.lineno}) && `+ `$B.pattern_match(subject, {`+ `${$B.js_from_ast(this.pattern, scopes)}})` if(this.guard){js+=` && $B.$bool(${$B.js_from_ast(this.guard, scopes)})`} js+=`){\n` indent() js+=add_body(this.body,scopes)+'\n' dedent() js+=prefix+'}' return js} function is_irrefutable(pattern){switch(pattern.constructor){case $B.ast.MatchAs: if(pattern.pattern===undefined){return pattern}else{return is_irrefutable(pattern.pattern)} case $B.ast.MatchOr: for(var i=0;i < pattern.patterns.length;i++){if(is_irrefutable(pattern.patterns[i])){if(i==pattern.patterns.length-1){ return pattern} irrefutable_error(pattern.patterns[i])}} break}} function irrefutable_error(pattern){var msg=pattern.name ? `name capture '${pattern.name}'` :'wildcard' msg+=' makes remaining patterns unreachable' compiler_error(pattern,msg)} function pattern_bindings(pattern){var bindings=[] switch(pattern.constructor){case $B.ast.MatchAs: if(pattern.name){bindings.push(pattern.name)} break case $B.ast.MatchSequence: for(var p of pattern.patterns){bindings=bindings.concat(pattern_bindings(p))} break case $B.ast.MatchOr: bindings=pattern_bindings(pattern.patterns[0]) var err_msg='alternative patterns bind different names' for(var i=1;i < pattern.patterns.length;i++){var _bindings=pattern_bindings(pattern.patterns[i]) if(_bindings.length !=bindings.length){compiler_error(pattern,err_msg)}else{for(var j=0;j < bindings.length;j++){if(bindings[j]!=_bindings[j]){compiler_error(pattern,err_msg)}}}} break} return bindings.sort()} $B.ast.Match.prototype.to_js=function(scopes){var irrefutable var js=prefix+`var subject = ${$B.js_from_ast(this.subject, scopes)}\n`,first=true for(var _case of this.cases){if(! _case.guard){if(irrefutable){irrefutable_error(irrefutable)} irrefutable=is_irrefutable(_case.pattern)} if(first){js+=prefix+'if' first=false}else{js+='else if'} js+=$B.js_from_ast(_case,scopes)} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+js} $B.ast.MatchAs.prototype.to_js=function(scopes){ var scope=$B.last(scopes) var name=this.name===undefined ? '_' :this.name,params if(this.pattern===undefined){params=`capture: '${name}'`}else{var pattern=$B.js_from_ast(this.pattern,scopes) if(this.pattern instanceof $B.ast.MatchAs && this.pattern.name){ pattern=`group: [{${pattern}}]`} params=`${pattern}, alias: '${name}'`} if(scope.bindings){if(scope.bindings.indexOf(name)>-1){compiler_error(this,`multiple assignment to name '${name}' in pattern`)} scope.bindings.push(name)} return params} $B.ast.MatchClass.prototype.to_js=function(scopes){var names=[] for(let pattern of this.patterns.concat(this.kwd_patterns)){let name=pattern.name if(name){if(names.indexOf(name)>-1){compiler_error(pattern,`multiple assignment to name '${name}' in pattern`)} names.push(name)}} names=[] for(let i=0;i < this.kwd_attrs.length;i++){let kwd_attr=this.kwd_attrs[i] if(names.indexOf(kwd_attr)>-1){compiler_error(this.kwd_patterns[i],`attribute name repeated in class pattern: ${kwd_attr}`)} names.push(kwd_attr)} var cls=$B.js_from_ast(this.cls,scopes),patterns=this.patterns.map(x=> `{${$B.js_from_ast(x, scopes)}}`) var kw=[] for(let i=0,len=this.kwd_patterns.length;i < len;i++){kw.push(this.kwd_attrs[i]+': {'+ $B.js_from_ast(this.kwd_patterns[i],scopes)+'}')} return `class: ${cls}, args: [${patterns}], keywords: {${kw.join(', ')}}`} $B.ast.MatchMapping.prototype.to_js=function(scopes){for(let key of this.keys){if(key instanceof $B.ast.Attribute || key instanceof $B.ast.Constant || key instanceof $B.ast.UnaryOp || key instanceof $B.ast.BinOp){continue}else{compiler_error(key,'mapping pattern keys may only match literals and attribute lookups')}} var names=[] for(let pattern of this.patterns){if(pattern instanceof $B.ast.MatchAs && pattern.name){if(names.indexOf(pattern.name)>-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)} names.push(pattern.name)}} var items=[] for(let i=0,len=this.keys.length;i < len;i++){let key_prefix=this.keys[i]instanceof $B.ast.Constant ? 'literal: ' :'value: ',key=$B.js_from_ast(this.keys[i],scopes),value=$B.js_from_ast(this.patterns[i],scopes) items.push(`[{${key_prefix}${key}}, {${value}}]`)} var js='mapping: ['+items.join(', ')+']' if(this.rest){js+=`, rest: '${this.rest}'`} return js} $B.ast.MatchOr.prototype.to_js=function(scopes){is_irrefutable(this) pattern_bindings(this) var items=[] for(var alt of this.patterns){items.push(`{${$B.js_from_ast(alt, scopes)}}`)} var js=items.join(', ') return `or: [${js}]`} $B.ast.MatchSequence.prototype.to_js=function(scopes){var items=[],names=[] for(var pattern of this.patterns){if(pattern instanceof $B.ast.MatchAs && pattern.name){if(names.indexOf(pattern.name)>-1){compiler_error(pattern,`multiple assignments to name '${pattern.name}' in pattern`)} names.push(pattern.name)} items.push('{'+$B.js_from_ast(pattern,scopes)+'}')} return `sequence: [${items.join(', ')}]`} $B.ast.MatchSingleton.prototype.to_js=function(){var value=this.value===true ? '_b_.True' : this.value===false ? '_b_.False' : '_b_.None' return `literal: ${value}`} $B.ast.MatchStar.prototype.to_js=function(){var name=this.name===undefined ? '_' :this.name return `capture_starred: '${name}'`} $B.ast.MatchValue.prototype.to_js=function(scopes){if(this.value instanceof $B.ast.Constant){return `literal: ${$B.js_from_ast(this.value, scopes)}`}else if(this.value instanceof $B.ast.Constant || this.value instanceof $B.ast.UnaryOp || this.value instanceof $B.ast.BinOp || this.value instanceof $B.ast.Attribute){return `value: ${$B.js_from_ast(this.value, scopes)}`}else{compiler_error(this,'patterns may only match literals and attribute lookups')}} $B.ast.Module.prototype.to_js=function(scopes){if(prefix.length !=0){console.log('prefix length at start',prefix.length)} mark_parents(this) var name=init_scopes.bind(this)('module',scopes),namespaces=scopes.namespaces var module_id=name,global_name=make_scope_name(scopes),mod_name=module_name(scopes) var js=`var $B = __BRYTHON__,\n _b_ = $B.builtins,\n` if(! namespaces){js+=` ${global_name} = $B.imported["${mod_name}"],\n`+ ` locals = ${global_name},\n`+ ` frame = ["${module_id}", locals, "${module_id}", locals]`}else{ js+=` locals = ${namespaces.local_name},\n`+ ` globals = ${namespaces.global_name}` if(name){let local_name=('locals_'+name).replace(/\./g,'_') js+=`,\n ${local_name} = locals`}} js+=`\nvar __file__ = '${scopes.filename ?? ""}'\n`+ `locals.__name__ = '${name}'\n`+ `locals.__doc__ = ${extract_docstring(this, scopes)}\n` var insert_positions=js.length if(! namespaces){js+=`$B.enter_frame(frame, __file__, 1)\n` js+='\nvar _frame_obj = $B.frame_obj\n'} if(scopes.postpone_annotations){js+=`locals.__annotations__ = $B.empty_dict()\n`}else{js+=`locals.$annotations = {}\n` bind('__annotate__',scopes)} js+='var stack_length = $B.count_frames()\n' js+=`try{\n` indent() js+=add_body(this.body,scopes)+'\n'+ prefix+`$B.leave_frame({locals, value: _b_.None})\n` dedent() js+=prefix+`}catch(err){\n` indent() js+=prefix+`$B.set_exc_and_trace(frame, err)\n`+ prefix+`$B.leave_frame({locals, value: _b_.None})\n`+ prefix+'throw err\n' dedent() js+=prefix+`}\n` var positions=scopes[scopes.length-1].positions if(positions && positions.length > 0){var rest=js.substr(insert_positions) js=js.substr(0,insert_positions)+ `frame.positions = [${positions}]\n` js+=rest} scopes.pop() if(prefix.length !=0){console.warn('wrong indent !',prefix.length) prefix=''} return js} $B.ast.Name.prototype.to_js=function(scopes){if(this.ctx instanceof $B.ast.Store){ var scope=bind(this.id,scopes) if(scope===$B.last(scopes)&& scope.freevars.has(this.id)){ scope.freevars.delete(this.id)} return reference(scopes,scope,this.id)}else if(this.ctx instanceof $B.ast.Load){ if(this.id=='__debug__'){return '_b_.__debug__'} var scope=name_scope(this.id,scopes) if(this.id=='xzs'){console.log('Name.to_js, scope',scope)} if(scope.found===$B.last(scopes)){return 'locals.'+mangle(scopes,scope.found,this.id)} var res=name_reference(this.id,scopes,this) if(this.id=='__debugger__' && res.startsWith('$B.resolve_in_scopes')){ return 'debugger'} return res}} $B.ast.NamedExpr.prototype.to_js=function(scopes){compiler_check(this) var i=scopes.length-1 while(scopes[i].type=='comprehension'){i--} var enclosing_scopes=scopes.slice(0,i+1) enclosing_scopes.symtable=scopes.symtable bind(this.target.id,enclosing_scopes) return '('+$B.js_from_ast(this.target,enclosing_scopes)+' = '+ $B.js_from_ast(this.value,scopes)+')'} $B.ast.NamedExpr.prototype._check=function(){check_assign_or_delete(this,this.target)} $B.ast.Nonlocal.prototype.to_js=function(scopes){var scope=$B.last(scopes) for(var name of this.names){scope.nonlocals.add(name)} return ''} $B.ast.Pass.prototype.to_js=function(){return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+'void(0)'} $B.ast.Raise.prototype.to_js=function(scopes){var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+'$B.$raise(' if(this.exc){js+=$B.js_from_ast(this.exc,scopes)} if(this.cause){js+=', '+$B.js_from_ast(this.cause,scopes)} return js+')'} $B.ast.Return.prototype.to_js=function(scopes){ if(last_scope(scopes).type !='def'){compiler_error(this,"'return' outside function")} compiler_check(this) var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+`return $B.trace_return_and_leave(frame, `+ (this.value ? $B.js_from_ast(this.value,scopes):' _b_.None')+ ')\n' return js} function remove_escapes(value){for(var key in $B.escape2cp){ value=value.replace(new RegExp('\\\\'+key,'g'),$B.escape2cp[key])} return value} $B.ast.Set.prototype.to_js=function(scopes){var elts=[] for(var elt of this.elts){var js if(elt instanceof $B.ast.Constant){var v=elt.value if(typeof v=='string'){v=remove_escapes(v)} js=`{constant: [${$B.js_from_ast(elt, scopes)}, `+ `${$B.$hash(v)}]}`}else if(elt instanceof $B.ast.Starred){js=`{starred: ${$B.js_from_ast(elt.value, scopes)}}`}else{js=`{item: ${$B.js_from_ast(elt, scopes)}}`} elts.push(js)} return `_b_.set.$literal([${elts.join(', ')}])`} $B.ast.SetComp.prototype.to_js=function(scopes){return make_comp.bind(this)(scopes)} $B.ast.Slice.prototype.to_js=function(scopes){var lower=this.lower ? $B.js_from_ast(this.lower,scopes):'_b_.None',upper=this.upper ? $B.js_from_ast(this.upper,scopes):'_b_.None',step=this.step ? $B.js_from_ast(this.step,scopes):'_b_.None' return `_b_.slice.$fast_slice(${lower}, ${upper}, ${step})`} $B.ast.Starred.prototype.to_js=function(scopes){if(this.$handled){return `_b_.list.$unpack(${$B.js_from_ast(this.value, scopes)})`} if(this.ctx instanceof $B.ast.Store){compiler_error(this,"starred assignment target must be in a list or tuple")}else{compiler_error(this,"can't use starred expression here")}} $B.ast.Subscript.prototype.to_js=function(scopes){var value=$B.js_from_ast(this.value,scopes),slice=$B.js_from_ast(this.slice,scopes) if(this.slice instanceof $B.ast.Slice){return `$B.getitem_slice(${value}, ${slice})`}else{var inum=add_to_positions(scopes,this) return `$B.$getitem(${value}, ${slice}, ${inum})`}} $B.ast.TemplateStr.prototype.to_js=function(scopes){var js=prefix+'$B.Template(' var items=[] var expect_str=true for(var value of this.values){if(value instanceof $B.ast.Constant){items.push(value.to_js(scopes))}else if(value instanceof $B.ast.Interpolation){items.push(value.to_js(scopes))}else{throw Error('unexpected type inf temmplate')}} return js+`${items.join(', ')})\n`} $B.ast.Try.prototype.to_js=function(scopes){compiler_check(this) var id=make_id(),has_except_handlers=this.handlers.length > 0,has_else=this.orelse.length > 0,has_finally=this.finalbody.length > 0 var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+`try{\n` indent() js+=prefix+`var stack_length_${id} = $B.count_frames()\n` js+=prefix+`var save_frame_obj_${id} = $B.frame_obj\n` if(has_else){js+=prefix+`var failed${id} = false\n`} var try_scope=copy_scope($B.last(scopes)) scopes.push(try_scope) js+=add_body(this.body,scopes)+'\n' dedent() if(has_except_handlers){var err='err'+id js+=prefix+'}' js+=`catch(${err}){\n` indent() js+=prefix+`$B.set_exc_and_trace(frame, ${err})\n` if(has_else){js+=prefix+`failed${id} = true\n`} var first=true,has_untyped_except=false for(var handler of this.handlers){if(first){js+=prefix+'if' first=false}else{js+=prefix+'}else if'} js+=`($B.set_lineno(frame, ${handler.lineno})` if(handler.type){js+=` && $B.is_exc(${err}, ` if(handler.type instanceof $B.ast.Tuple){js+=`${$B.js_from_ast(handler.type, scopes)}`}else{js+=`[${$B.js_from_ast(handler.type, scopes)}]`} js+=`)){\n`}else{has_untyped_except=true js+='){\n'} indent() if(handler.name){bind(handler.name,scopes) var mangled=mangle(scopes,try_scope,handler.name) js+=prefix+`locals.${mangled} = ${err}\n`} js+=add_body(handler.body,scopes)+'\n' if(!($B.last(handler.body)instanceof $B.ast.Return)){ js+=prefix+'$B.del_exc(frame)\n' js+=prefix+`$B.frame_obj = save_frame_obj_${id}\n`} dedent()} if(! has_untyped_except){ js+=prefix+`}else{\n`+ prefix+tab+`throw ${err}\n`} js+=prefix+'}\n' dedent()} if(has_else ||has_finally){js+=prefix+'}' js+='finally{\n' indent() if(has_else && has_finally){ indent()} var finalbody=prefix+`var exit = false\n`+ prefix+`if($B.count_frames() < stack_length_${id}){\n`+ prefix+tab+`exit = true\n`+ prefix+tab+`$B.frame_obj = $B.push_frame(frame)\n`+ prefix+`}\n`+ add_body(this.finalbody,scopes) if(this.finalbody.length > 0 && !($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+='\n'+prefix+`if(exit){\n`+ prefix+tab+`$B.leave_frame()\n`+ prefix+`}`} var elsebody=prefix+`if($B.count_frames() == stack_length_${id} `+ `&& ! failed${id}){\n` indent() elsebody+=add_body(this.orelse,scopes) dedent() elsebody+='\n'+prefix+'}' if(has_else && has_finally){dedent() js+=prefix+`try{\n`+ elsebody+ '\n'+prefix+'}'+ `finally{\n`+finalbody+'\n'+ prefix+'}\n'}else if(has_else && ! has_finally){js+=elsebody+'\n'}else{js+=finalbody+'\n'} dedent() js+=prefix+'}\n' }else{js+='}\n' } scopes.pop() return js} $B.ast.TryStar.prototype.to_js=function(scopes){ var id=make_id(),has_except_handlers=this.handlers.length > 0,has_else=this.orelse.length > 0,has_finally=this.finalbody.length > 0 var js=prefix+`$B.set_lineno(frame, ${this.lineno})\n`+ prefix+`try{\n` indent() js+=prefix+`var stack_length_${id} = $B.count_frames()\n` if(has_finally){js+=prefix+`var save_frame_obj_${id} = $B.frame_obj\n`} if(has_else){js+=prefix+`var failed${id} = false\n`} var try_scope=copy_scope($B.last(scopes)) scopes.push(try_scope) js+=add_body(this.body,scopes)+'\n' if(has_except_handlers){var err='err'+id dedent() js+=prefix+'}' js+=`catch(${err}){\n` indent() js+=prefix+`$B.set_exc_and_trace(frame, ${err})\n`+ prefix+`if(! $B.$isinstance(${err}, _b_.BaseExceptionGroup)){\n`+ prefix+tab+`${err} = _b_.BaseExceptionGroup.$factory(_b_.None, [${err}])\n`+ prefix+'}\n'+ prefix+`function fake_split(exc, condition){\n`+ prefix+tab+`return condition(exc) ? `+ `$B.fast_tuple([exc, _b_.None]) : $B.fast_tuple([_b_.None, exc])\n`+ prefix+'}\n' if(has_else){js+=prefix+`failed${id} = true\n`} for(var handler of this.handlers){js+=prefix+`$B.set_lineno(frame, ${handler.lineno})\n` if(handler.type){js+=prefix+"var condition = function(exc){\n"+ prefix+tab+"return $B.$isinstance(exc, "+ `${$B.js_from_ast(handler.type, scopes)})\n`+ prefix+"}\n"+ prefix+`var klass = $B.get_class(${err}),\n` indent() js+=prefix+`split_method = $B.$getattr(klass, 'split'),\n`+ prefix+`split = $B.$call(split_method)(${err}, condition),\n`+ prefix+'matching = split[0],\n'+ prefix+'rest = split[1]\n' dedent() js+=prefix+'if(matching.exceptions !== _b_.None){\n' indent() js+=prefix+'for(var err of matching.exceptions){\n' indent() if(handler.name){bind(handler.name,scopes) var mangled=mangle(scopes,try_scope,handler.name) js+=prefix+`locals.${mangled} = ${err}\n`} js+=add_body(handler.body,scopes)+'\n' if(!($B.last(handler.body)instanceof $B.ast.Return)){ js+=prefix+'$B.del_exc(frame)\n'} dedent() js+=prefix+'}\n' dedent() js+=prefix+'}\n' js+=prefix+`${err} = rest\n`}} js+=prefix+`if(${err}.exceptions !== _b_.None){\n`+ prefix+tab+`throw ${err}\n`+ prefix+'}\n' dedent()} if(has_else ||has_finally){js+=prefix+'}' js+='finally{\n' indent() if(has_else && has_finally){indent()} var finalbody=prefix+`var exit = false\n`+ prefix+`if($B.count_frames() < stack_length_${id}){\n`+ prefix+tab+`exit = true\n`+ prefix+tab+`$B.frame_obj = $B.push_frame(frame)\n`+ prefix+`}\n`+ add_body(this.finalbody,scopes) if(this.finalbody.length > 0 && !($B.last(this.finalbody)instanceof $B.ast.Return)){finalbody+='\n'+prefix+`if(exit){\n`+ prefix+tab+`$B.leave_frame(locals)\n`+ prefix+`}`} var elsebody=prefix+`if($B.count_frames() == stack_length_${id} `+ `&& ! failed${id}){\n` indent() elsebody+=add_body(this.orelse,scopes) dedent() elsebody+='\n'+prefix+'}' if(has_else && has_finally){dedent() js+=prefix+`try{\n`+ elsebody+'\n'+ prefix+'}'+ `finally{\n`+finalbody+'\n'+ prefix+'}'}else if(has_else && ! has_finally){js+=elsebody}else{js+=finalbody} dedent() js+='\n'+prefix+'}\n' }else{js+=prefix+'}\n' } scopes.pop() return js} $B.ast.Tuple.prototype.to_js=function(scopes){return list_or_tuple_to_js.bind(this)('$B.fast_tuple',scopes)} $B.ast.TypeAlias.prototype.to_js=function(scopes){ var type_param_scope=new Scope('type_params','type_params',this.type_params) scopes.push(type_param_scope) var type_alias_scope=new Scope('type_alias','type_alias',this) scopes.push(type_alias_scope) var type_params_names=[] check_type_params(this) for(var type_param of this.type_params){if(type_param instanceof $B.ast.TypeVar){type_params_names.push(type_param.name)}else if(type_param instanceof $B.ast.TypeVarTuple || type_param instanceof $B.ast.ParamSpec){type_params_names.push(type_param.name.id)}} for(var name of type_params_names){bind(name,scopes)} var qualified_name=qualified_scope_name(scopes,type_alias_scope) var value=this.value.to_js(scopes) scopes.pop() scopes.pop() var js=prefix+`$B.$import('_typing')\n` js+=prefix+`var locals_${qualified_scope_name(scopes, type_param_scope)} = {}\n` js+=prefix+`function TYPE_PARAMS_OF_${this.name.id}(){\n` indent() js+=prefix+`var locals_${qualified_name} = {},\n`+ prefix+tab+tab+`locals = locals_${qualified_name}, \n`+ prefix+tab+tab+`type_params = $B.fast_tuple([])\n` for(var i=0,len=this.type_params.length;i < len;i++){js+=prefix+`type_params.push(locals.${type_params_names[i]} = `+ `${this.type_params[i].to_js()})\n`} js+=prefix+`function get_value(){\n`+ prefix+tab+`return ${value}\n`+ prefix+`}\n` js+=prefix+`var res = $B.$call($B.imported._typing.TypeAliasType)`+ `('${this.name.id}', get_value)\n`+ prefix+`$B.$setattr(res, '__module__', $B.frame_obj.frame[2])\n`+ prefix+`$B.$setattr(res, '__type_params__', type_params)\n`+ prefix+`return res\n` dedent() js+=prefix+`}\n`+ prefix+`locals.${this.name.id} = TYPE_PARAMS_OF_${this.name.id}()` return js} $B.ast.TypeVar.prototype.to_js=function(){check_type_params(this) return `$B.$call($B.imported._typing.TypeVar)('${this.name}', `+ `{$kw: [{infer_variance: true}]})`} $B.ast.TypeVarTuple.prototype.to_js=function(){return `$B.$call($B.imported._typing.TypeVarTuple)('${this.name.id}')`} $B.ast.ParamSpec.prototype.to_js=function(){return `$B.$call($B.imported._typing.ParamSpec)('${this.name.id}')`} $B.ast.UnaryOp.prototype.to_js=function(scopes){var operand=$B.js_from_ast(this.operand,scopes) if(this.op instanceof $B.ast.Not){return `! $B.$bool(${operand})`} if(typeof operand=="number" ||operand instanceof Number){if(this.op instanceof $B.ast.UAdd){return operand+''}else if(this.op instanceof $B.ast.USub){return-operand+''}} var method=opclass2dunder[this.op.constructor.$name] return `$B.$getattr($B.get_class(locals.$result = ${operand}), '${method}')(locals.$result)`} $B.ast.While.prototype.to_js=function(scopes){var id=make_id() var scope=$B.last(scopes),new_scope=copy_scope(scope,this,id) scopes.push(new_scope) var js=prefix+`var no_break_${id} = true\n` js+=prefix+`while($B.set_lineno(frame, ${this.lineno}) && ` if(this.test instanceof $B.ast.BoolOp){this.test.$dont_evaluate=true js+=`${$B.js_from_ast(this.test, scopes)}){\n`}else{js+=`$B.$bool(${$B.js_from_ast(this.test, scopes)})){\n`} indent() js+=add_body(this.body,scopes) dedent() js+='\n'+prefix+'}\n' scopes.pop() if(this.orelse.length > 0){js+=prefix+`if(no_break_${id}){\n` indent() js+=add_body(this.orelse,scopes) dedent() js+='\n'+prefix+'}\n'} return js} $B.ast.With.prototype.to_js=function(scopes){ function add_item(item,js){var id=make_id() var s=prefix+`var mgr_${id} = `+ $B.js_from_ast(item.context_expr,scopes)+',\n'+ prefix+`klass = $B.get_class(mgr_${id})\n`+ prefix+`try{\n` indent() s+=prefix+`var exit_${id} = $B.$getattr(mgr_${id}, '__exit__'),\n`+ prefix+tab+`enter_${id} = $B.$getattr(klass, '__enter__')\n` dedent() s+=prefix+`}catch(err){\n` indent() s+=prefix+`var klass_name = $B.class_name(mgr_${id})\n`+ prefix+`frame.inum = ${inum}\n`+ prefix+`$B.RAISE(_b_.TypeError, "'" + klass_name + `+ `"' object does not support the context manager protocol")\n` dedent() s+=prefix+`}\n`+ prefix+`var value_${id} = $B.$call(enter_${id})(mgr_${id}),\n`+ prefix+tab+`exc_${id} = true\n` if(in_generator){ s+=prefix+`locals.$context_managers = locals.$context_managers || []\n`+ prefix+`locals.$context_managers.push(mgr_${id})\n`} s+=prefix+'try{\n' indent() s+=prefix+'try{\n' indent() if(item.optional_vars){var value={to_js:function(){return `value_${id}`}} copy_position(value,_with) var assign=new $B.ast.Assign([item.optional_vars],value) copy_position(assign,_with) s+=assign.to_js(scopes)+'\n'} s+=js dedent() s+=prefix+`}catch(err_${id}){\n` indent() s+=prefix+`frame.$lineno = ${lineno}\n`+ prefix+`exc_${id} = false\n`+ prefix+`err_${id} = $B.exception(err_${id}, frame)\n`+ prefix+`var $b = $B.$call(exit_${id})(err_${id}.__class__, `+ `err_${id}, \n`+ prefix+tab.repeat(4)+`$B.$getattr(err_${id}, '__traceback__'))\n`+ prefix+`if(! $B.$bool($b)){\n`+ prefix+tab+`throw err_${id}\n`+ prefix+`}\n` dedent() s+=prefix+`}\n` dedent() s+=prefix+`}finally{\n` indent() s+=prefix+`frame.$lineno = ${lineno}\n`+ (in_generator ? prefix+`locals.$context_managers.pop()\n` :'')+ prefix+`if(exc_${id}){\n` indent() s+=prefix+`try{\n`+ prefix+tab+`$B.$call(exit_${id})(_b_.None, _b_.None, _b_.None)\n`+ prefix+`}catch(err){\n` indent() s+=prefix+`if($B.count_frames() < stack_length){\n`+ prefix+tab+`$B.frame_obj = $B.push_frame(frame)\n`+ prefix+`}\n`+ prefix+`throw err\n` dedent() s+=prefix+`}\n` dedent() s+=prefix+`}\n` dedent() s+=prefix+`}\n` return s} var _with=this,scope=last_scope(scopes),lineno=this.lineno scope.needs_stack_length=true indent(2) var inum=add_to_positions(scopes,this) var js=add_body(this.body,scopes)+'\n' dedent(2) var in_generator=scopes.symtable.table.blocks.get(fast_id(scope.ast)).generator for(var item of this.items.slice().reverse()){js=add_item(item,js)} return prefix+`$B.set_lineno(frame, ${this.lineno})\n`+js} $B.ast.Yield.prototype.to_js=function(scopes){ var scope=last_scope(scopes) if(scope.type !='def'){compiler_error(this,"'yield' outside function")} last_scope(scopes).is_generator=true var value=this.value ? $B.js_from_ast(this.value,scopes):'_b_.None' return `yield ${value}`} $B.ast.YieldFrom.prototype.to_js=function(scopes){ var scope=last_scope(scopes) if(scope.type !='def'){compiler_error(this,"'yield' outside function")} scope.is_generator=true var value=$B.js_from_ast(this.value,scopes) var n=make_id() var res=`yield* (function* f(){\n` indent() var js=` var _i${n} = _b_.iter(${value.trimRight()}), _r${n} var failed${n} = false try{ var _y${n} = _b_.next(_i${n}) }catch(_e){ $B.set_exc(_e, frame) failed${n} = true $B.pmframe = $B.frame_obj.frame _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() var _s${n} = yield _y${n} $B.frame_obj = $B.push_frame(frame) }catch(_e){ $B.set_exc(_e, frame) if(_e.__class__ === _b_.GeneratorExit){ var failed2${n} = false try{ var _m${n} = $B.$getattr(_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 sys_module = $B.imported._sys, _x${n} = sys_module.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 } } } } return _r${n}` var lines=js.split('\n').slice(1) var head=lines[0].length-lines[0].trimLeft().length for(var line of lines){var trimmed=line.trimLeft(),tlen=trimmed.length if(tlen==0){res+='\n' continue} var line_head=line.length-tlen var line_indent=(line_head-head)/4 if(line_indent < 0){ console.warn('wrong indentation') line_indent=0} res+=prefix+tab.repeat(line_indent)+trimmed+'\n'} dedent() res+=prefix+'})()' return res} var state={} $B.js_from_root=function(arg){var ast_root=arg.ast,symtable=arg.symtable,filename=arg.filename,src=arg.src,namespaces=arg.namespaces,imported=arg.imported if($B.show_ast_dump){console.log($B.ast_dump(ast_root))} if($B.compiler_check){$B.compiler_check(ast_root,symtable)} var scopes=[] state.filename=filename scopes.symtable=symtable scopes.filename=filename scopes.src=src scopes.namespaces=namespaces scopes.imported=imported scopes.imports={} scopes.indent=0 scopes.postpone_annotations=scopes.symtable.table.future.features & $B.CO_FUTURE_ANNOTATIONS var js_tab=$B.get_option('js_tab') tab=' '.repeat(js_tab) var js=ast_root.to_js(scopes) return{js,imports:scopes.imports}} $B.js_from_ast=function(ast,scopes){if(! scopes.symtable){throw Error('perdu symtable')} scopes=scopes ||[] if(ast.to_js !==undefined){if(ast.col_offset===undefined){var klass=ast.constructor.$name if(['match_case'].indexOf(klass)==-1){console.log('no col_offset for',klass) console.log(ast) throw Error('no col offset')}} return ast.to_js(scopes)} console.log("unhandled",ast.constructor.$name,ast,typeof ast) return '// unhandled class ast.'+ast.constructor.$name}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var GLOBAL_PARAM="name '%s' is parameter and global",NONLOCAL_PARAM="name '%s' is parameter and nonlocal",GLOBAL_AFTER_ASSIGN="name '%s' is assigned to before global declaration",NONLOCAL_AFTER_ASSIGN="name '%s' is assigned to before nonlocal declaration",GLOBAL_AFTER_USE="name '%s' is used prior to global declaration",NONLOCAL_AFTER_USE="name '%s' is used prior to nonlocal declaration",GLOBAL_ANNOT="annotated name '%s' can't be global",NONLOCAL_ANNOT="annotated name '%s' can't be nonlocal",IMPORT_STAR_WARNING="import * only allowed at module level",NAMED_EXPR_COMP_IN_CLASS= "assignment expression within a comprehension cannot be used in a class body",NAMED_EXPR_COMP_CONFLICT= "assignment expression cannot rebind comprehension iteration variable '%s'",NAMED_EXPR_COMP_INNER_LOOP_CONFLICT= "comprehension inner loop cannot rebind assignment expression target '%s'",NAMED_EXPR_COMP_ITER_EXPR= "assignment expression cannot be used in a comprehension iterable expression",ANNOTATION_NOT_ALLOWED= "'%s' can not be used within an annotation",DUPLICATE_ARGUMENT="duplicate argument '%s' in function definition",TYPEVAR_BOUND_NOT_ALLOWED="%s cannot be used within a TypeVar bound",TYPEALIAS_NOT_ALLOWED="%s cannot be used within a type alias",TYPEPARAM_NOT_ALLOWED= "%s cannot be used within the definition of a generic",DUPLICATE_TYPE_PARAM="duplicate type parameter '%s'" var SF=$B.SYMBOL_FLAGS var NULL=undefined var ModuleBlock=2,ClassBlock=1,FunctionBlock=0,AnnotationBlock=4,TypeVarBoundBlock=5,TypeAliasBlock=6,TypeParamBlock=7 var PyExc_SyntaxError=_b_.SyntaxError function assert(test){if(! $B.$bool(test)){console.log('test fails',test) throw Error('test fails')}} function LOCATION(x){ return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]} function ST_LOCATION(x){ return[x.lineno,x.col_offset,x.end_lineno,x.end_col_offset]} function _Py_Mangle(privateobj,ident){ var plen,ipriv if(privateobj==NULL ||! ident.startsWith('__')){return ident;} plen=privateobj.length if(ident.endsWith('__')||ident.search(/\./)!=-1){return ident;} ipriv=0; while(privateobj[ipriv]=='_'){ipriv++} if(ipriv==plen){return ident } var prefix=privateobj.substr(ipriv) return '_'+prefix+ident} var lambda=NULL var NoComprehension=0,ListComprehension=1,DictComprehension=2,SetComprehension=3,GeneratorExpression=4 function GET_IDENTIFIER(VAR){return VAR} function Symtable(){this.filename=NULL; this.stack=[] this.blocks=new Map() this.cur=NULL; this.private=NULL;} function id(obj){if(obj.$id !==undefined){return obj.$id} return obj.$id=$B.UUID()} function ste_new(st,name,block,key,lineno,col_offset,end_lineno,end_col_offset){var ste ste={table:st,id:id(key), name:name,directives:NULL,type:block,nested:0,free:0,varargs:0,varkeywords:0,opt_lineno:0,opt_col_offset:0,lineno:lineno,col_offset:col_offset,end_lineno:end_lineno,end_col_offset:end_col_offset} if(st.cur !=NULL && (st.cur.nested || st.cur.type==FunctionBlock)){ste.nested=1;} ste.child_free=0 ste.generator=0 ste.coroutine=0 ste.comprehension=NoComprehension ste.returns_value=0 ste.needs_class_closure=0 ste.comp_inlined=0 ste.comp_iter_target=0 ste.comp_iter_expr=0 ste.symbols=$B.empty_dict() ste.varnames=[] ste.children=[] st.blocks.set(ste.id,ste) return ste} $B._PySymtable_Build=function(mod,filename,future){var st=new Symtable(),seq st.filename=filename; st.future=future ||{} st.type=SF.TYPE_MODULE if(!symtable_enter_block(st,'top',ModuleBlock,mod,0,0,0,0)){return NULL;} st.top=st.cur switch(mod.constructor){case $B.ast.Module: seq=mod.body for(let item of seq){visitor.stmt(st,item)} break case $B.ast.Expression: visitor.expr(st,mod.body) break case $B.ast.Interactive: seq=mod.body for(let item of seq){visitor.stmt(st,item)} break} symtable_analyze(st) return st.top;} function _PyST_GetSymbol(ste,name){if(! _b_.dict.$contains_string(ste.symbols,name)){return 0} return _b_.dict.$getitem_string(ste.symbols,name)} function _PyST_GetScope(ste,name){var symbol=_PyST_GetSymbol(ste,name); return(symbol >> SF.SCOPE_OFFSET)& SF.SCOPE_MASK;} function _PyST_IsFunctionLike(ste){return ste.type==FunctionBlock ||ste.type==TypeVarBoundBlock ||ste.type==TypeAliasBlock ||ste.type==TypeParamBlock;} function PyErr_Format(exc_type,message,arg){if(arg){message=_b_.str.__mod__(message,arg)} return exc_type.$factory(message)} function PyErr_SetString(exc_type,message){return exc_type.$factory(message)} function set_exc_info(exc,filename,lineno,offset,end_lineno,end_offset){exc.filename=filename exc.lineno=lineno exc.offset=offset+1 exc.end_lineno=end_lineno exc.end_offset=end_offset+1 var src=$B.file_cache[filename] if(src !==undefined){var lines=src.split('\n') exc.text=lines[lineno-1]}else{exc.text=''} exc.args[1]=[filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]} function error_at_directive(exc,ste,name){assert(ste.directives) for(var data of ste.directives){if(data[0]==name){set_exc_info(exc,ste.table.filename,data[1],data[2],data[3],data[4]) return 0}} $B.RAISE(_b_.RuntimeError,"BUG: internal directive bookkeeping broken")} function SET_SCOPE(DICT,NAME,I){DICT[NAME]=I} function is_free_in_any_child(entry,key){for(var child_ste of entry.ste_children){var scope=_PyST_GetScope(child_ste,key) if(scope==SF.FREE){return 1}} return 0} function inline_comprehension(ste,comp,scopes,comp_free,inlined_cells){for(var item of _b_.dict.$iter_items(comp.symbols)){ var k=item.key,comp_flags=item.value; if(comp_flags & SF.DEF_PARAM){ continue;} var scope=(comp_flags >> SF.SCOPE_OFFSET)& SF.SCOPE_MASK; var only_flags=comp_flags &((1 << SF.SCOPE_OFFSET)-1) if(scope==SF.CELL ||only_flags & SF.DEF_COMP_CELL){inlined_cells.add(k)} var existing=_b_.dict.$contains_string(ste.symbols,k) if(!existing){ var v_flags=only_flags _b_.dict.$setitem(ste.symbols,k,v_flags); SET_SCOPE(scopes,k,scope);}else{ if((existing & SF.DEF_BOUND)&& !is_free_in_any_child(comp,k)&& ste.type !==ClassBlock){_b_.set.remove(comp_free,k)}}} return 1;} function analyze_name(ste,scopes,name,flags,bound,local,free,global,type_params,class_entry){if(flags & SF.DEF_GLOBAL){if(flags & SF.DEF_NONLOCAL){let exc=PyErr_Format(_b_.SyntaxError,"name '%s' is nonlocal and global",name) error_at_directive(exc,ste,name) throw exc} SET_SCOPE(scopes,name,SF.GLOBAL_EXPLICIT) global.add(name) if(bound){bound.delete(name)} return 1} if(flags & SF.DEF_NONLOCAL){if(!bound){let exc=PyErr_Format(_b_.SyntaxError,"nonlocal declaration not allowed at module level"); error_at_directive(exc,ste,name) throw exc} if(! bound.has(name)){let exc=PyErr_Format(_b_.SyntaxError,"no binding for nonlocal '%s' found",name) error_at_directive(exc,ste,name) throw exc} if(type_params.has(name)){let exc=PyErr_Format(_b_.SyntaxError,"nonlocal binding not allowed for type parameter '%s'",name); error_at_directive(exc,ste,name) throw exc} SET_SCOPE(scopes,name,SF.FREE) ste.free=1 free.add(name) return 1} if(flags & SF.DEF_BOUND){SET_SCOPE(scopes,name,SF.LOCAL) local.add(name) global.delete(name) if(flags & SF.DEF_TYPE_PARAM){type_params.add(name)}else{type_params.delete(name)} return 1} if(class_entry !=NULL){var class_flags=_PyST_GetSymbol(class_entry,name); if(class_flags & SF.DEF_GLOBAL){SET_SCOPE(scopes,name,SF.GLOBAL_EXPLICIT) return 1;}else if(class_flags & SF.DEF_BOUND && !(class_flags & SF.DEF_NONLOCAL)){SET_SCOPE(scopes,name,SF.GLOBAL_IMPLICIT) return 1}} if(bound && bound.has(name)){SET_SCOPE(scopes,name,SF.FREE) ste.free=1 free.add(name) return 1} if(global && global.has(name)){SET_SCOPE(scopes,name,SF.GLOBAL_IMPLICIT) return 1} if(ste.nested){ste.free=1} SET_SCOPE(scopes,name,SF.GLOBAL_IMPLICIT) return 1} function analyze_cells(scopes,free,inlined_cells){var v,v_cell; v_cell=SF.CELL; if(!v_cell){return 0;} for(let name in scopes){v=scopes[name] var scope=v; if(scope !=SF.LOCAL){continue;} if(! free.has(name)&& ! inlined_cells.has(name)){continue;} scopes[name]=v_cell free.delete(name)} return 1} function drop_class_free(ste,free){var res=free.delete('__class__') if(res){ste.needs_class_closure=1} res=free.delete('__classdict__') if(res){ste.needs_class_classdict=1} return 1} function update_symbols(symbols,scopes,bound,free,inlined_cells,classflag){var v,v_scope,v_new,v_free for(let name of _b_.dict.$keys_string(symbols)){var test=false let flags=_b_.dict.$getitem_string(symbols,name) if(test){console.log('in update symbols, name',name,'flags',flags,flags & SF.DEF_COMP_CELL)} if(inlined_cells.has(name)){flags |=SF.DEF_COMP_CELL} v_scope=scopes[name] var scope=v_scope if(test){console.log('name',name,'scopes[name]',scopes[name],' flags |=',scope << SF.SCOPE_OFFSET)} flags |=(scope << SF.SCOPE_OFFSET) v_new=flags if(!v_new){return 0;} if(test){console.log('set symbol',name,'v_new',v_new,'def comp cell',SF.DEF_COMP_CELL,v_new & SF.DEF_COMP_CELL)} _b_.dict.$setitem_string(symbols,name,v_new)} v_free=SF.FREE << SF.SCOPE_OFFSET for(let name of free){v=_b_.dict.$get_string(symbols,name) if(v !==_b_.dict.$missing){ if(classflag && v &(SF.DEF_BOUND |SF.DEF_GLOBAL)){let flags=v |SF.DEF_FREE_CLASS; v_new=flags; if(! v_new){return 0;} _b_.dict.$setitem_string(symbols,name,v_new)} continue;} if(bound && !bound.has(name)){continue;} _b_.dict.$setitem_string(symbols,name,v_free)} return 1} function analyze_block(ste,bound,free,global,typeparams,class_entry){var success=0 let local=new Set() let scopes={} let newglobal=new Set() let newfree=new Set() let newbound=new Set() let inlined_cells=new Set() if(ste.type===ClassBlock){ Set_Union(newglobal,global) if(bound){Set_Union(newbound,bound)}} for(let name of _b_.dict.$keys_string(ste.symbols)){var flags=_b_.dict.$getitem_string(ste.symbols,name) if(!analyze_name(ste,scopes,name,flags,bound,local,free,global,typeparams,class_entry)){return 0}} if(ste.type !=ClassBlock){ if(_PyST_IsFunctionLike(ste)){Set_Union(newbound,local);} if(bound){Set_Union(newbound,bound)} Set_Union(newglobal,global);}else{ newbound.add('__class__') newbound.add('__classdict__')} for(var c of ste.children){var child_free=new Set() let entry=c var new_class_entry=NULL; if(entry.can_see_class_scope){if(ste.type==ClassBlock){new_class_entry=ste}else if(class_entry){new_class_entry=class_entry}} var inline_comp=entry.comprehension && ! entry.generator; if(! analyze_child_block(entry,newbound,newfree,newglobal,typeparams,new_class_entry,child_free)){return 0} if(inline_comp){if(! inline_comprehension(ste,entry,scopes,child_free,inlined_cells)){} entry.comp_inlined=1;} Set_Union(newfree,child_free); if(entry.free ||entry.child_free){ste.child_free=1}} for(let i=ste.children.length-1;i >=0;i--){let entry=ste.children[i]; if(entry.comp_inlined){ste.children.splice(i,0,...entry.children)}} if(_PyST_IsFunctionLike(ste)&& !analyze_cells(scopes,newfree,inlined_cells)){return 0}else if(ste.type===ClassBlock && !drop_class_free(ste,newfree)){return 0} if(!update_symbols(ste.symbols,scopes,bound,newfree,inlined_cells,ste.type===ClassBlock ||ste.can_see_class_scope)){return 0} Set_Union(free,newfree) success=1 return success} function PySet_New(arg){if(arg===NULL){return new Set()} return new Set(arg)} function Set_Union(setA,setB){for(let elem of setB){setA.add(elem)}} function analyze_child_block(entry,bound,free,global,typeparams,class_entry,child_free){ var temp_bound=PySet_New(bound),temp_free=PySet_New(free),temp_global=PySet_New(global),temp_typeparams=PySet_New(typeparams) if(!analyze_block(entry,temp_bound,temp_free,temp_global,temp_typeparams,class_entry)){return 0} Set_Union(child_free,temp_free); return 1;} function symtable_analyze(st){var free=new Set(),global=new Set(),typeparams=new Set() return analyze_block(st.top,NULL,free,global,typeparams,NULL);} function symtable_exit_block(st){var size=st.stack.length st.cur=NULL; if(size){st.stack.pop() if(--size){st.cur=st.stack[size-1]}} return 1} function symtable_enter_block(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset){var prev if(ast===undefined){console.log('call ste new, key undef',st,name)} var ste=ste_new(st,name,block,ast,lineno,col_offset,end_lineno,end_col_offset) st.stack.push(ste) prev=st.cur if(prev){ste.comp_iter_expr=prev.comp_iter_expr} st.cur=ste if(block===AnnotationBlock){return 1} if(block===ModuleBlock){st.global=st.cur.symbols} if(prev){prev.children.push(ste)} return 1;} function symtable_lookup(st,name){var mangled=_Py_Mangle(st.private,name) if(!mangled){return 0;} var ret=_PyST_GetSymbol(st.cur,mangled) return ret;} function symtable_add_def_helper(st,name,flag,ste,_location){var o,dict,val,mangled=_Py_Mangle(st.private,name) if(!mangled){return 0} dict=ste.symbols if(_b_.dict.$contains_string(dict,mangled)){o=_b_.dict.$getitem_string(dict,mangled) val=o if((flag & SF.DEF_PARAM)&&(val & SF.DEF_PARAM)){ let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_ARGUMENT,name); set_exc_info(exc,st.filename,..._location) throw exc} if((flag & SF.DEF_TYPE_PARAM)&&(val & SF.DEF_TYPE_PARAM)){let exc=PyErr_Format(_b_.SyntaxError,DUPLICATE_TYPE_PARAM,name); set_exc_info(exc,st.filename,...location); throw exc} val |=flag}else{val=flag} if(ste.comp_iter_target){ if(val &(SF.DEF_GLOBAL |SF.DEF_NONLOCAL)){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_INNER_LOOP_CONFLICT,name); set_exc_info(exc,st.filename,..._location) throw exc} val |=SF.DEF_COMP_ITER} o=val if(o==NULL){return 0} _b_.dict.$setitem(dict,mangled,o) if(flag & SF.DEF_PARAM){ste.varnames.push(mangled)}else if(flag & SF.DEF_GLOBAL){ val=flag if(st.global.hasOwnProperty(mangled)){ val |=st.global[mangled]} o=val if(o==NULL){return 0} st.global[mangled]=o} return 1} function symtable_add_def(st,name,flag,_location){return symtable_add_def_helper(st,name,flag,st.cur,_location);} function symtable_enter_type_param_block(st,name,ast,has_defaults,has_kwdefaults,kind,_location){var prev=st.cur,current_type=st.cur.type; if(!symtable_enter_block(st,name,TypeParamBlock,ast,..._location)){return 0;} prev.$type_param=st.cur if(current_type===ClassBlock){st.cur.can_see_class_scope=1; if(!symtable_add_def(st,"__classdict__",SF.USE,_location)){return 0;}} if(kind==$B.ast.ClassDef){ if(!symtable_add_def(st,"type_params",SF.DEF_LOCAL,_location)){return 0;} if(!symtable_add_def(st,"type_params",SF.USE,_location)){return 0;} st.st_private=name; var generic_base=".generic_base"; if(!symtable_add_def(st,generic_base,SF.DEF_LOCAL,_location)){return 0;} if(!symtable_add_def(st,generic_base,SF.USE,_location)){return 0;}} if(has_defaults){var defaults=".defaults"; if(!symtable_add_def(st,defaults,SF.DEF_PARAM,_location)){return 0;}} if(has_kwdefaults){var kwdefaults=".kwdefaults"; if(!symtable_add_def(st,kwdefaults,SF.DEF_PARAM,_location)){return 0;}} return 1;} function VISIT_QUIT(ST,X){return X} function VISIT(ST,TYPE,V){var f=visitor[TYPE] if(!f(ST,V)){VISIT_QUIT(ST,0);}} function VISIT_SEQ(ST,TYPE,SEQ){for(var elt of SEQ){if(! visitor[TYPE](ST,elt)){VISIT_QUIT(ST,0)}}} function VISIT_SEQ_TAIL(ST,TYPE,SEQ,START){for(var i=START,len=SEQ.length;i < len;i++){var elt=SEQ[i]; if(! visitor[TYPE](ST,elt)){VISIT_QUIT(ST,0)}}} function VISIT_SEQ_WITH_NULL(ST,TYPE,SEQ){for(var elt of SEQ){if(! elt){continue } if(! visitor[TYPE](ST,elt)){VISIT_QUIT((ST),0)}}} function symtable_record_directive(st,name,lineno,col_offset,end_lineno,end_col_offset){var data,mangled if(!st.cur.directives){st.cur.directives=[]} mangled=_Py_Mangle(st.private,name); if(!mangled){return 0;} data=$B.fast_tuple([mangled,lineno,col_offset,end_lineno,end_col_offset]) st.cur.directives.push(data); return true} function has_kwonlydefaults(kwonlyargs,kw_defaults){for(var i=0,len=kwonlyargs.length;i < len;i++){if(kw_defaults[i]){return 1;}} return 0;} var visitor={} visitor.stmt=function(st,s){switch(s.constructor){case $B.ast.FunctionDef: if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s))) VISIT_QUIT(st,0) if(s.args.defaults) VISIT_SEQ(st,expr,s.args.defaults) if(s.args.kw_defaults) VISIT_SEQ_WITH_NULL(st,expr,s.args.kw_defaults) if(s.type_params.length > 0){if(!symtable_enter_type_param_block( st,s.name,s.type_params,s.args.defaults !=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0);} VISIT_SEQ(st,type_param,s.type_params);} if(!visitor.annotations(st,s,s.args,s.returns)) VISIT_QUIT(st,0) if(s.decorator_list){VISIT_SEQ(st,expr,s.decorator_list)} if(!symtable_enter_block(st,s.name,FunctionBlock,s,...LOCATION(s))){VISIT_QUIT(st,0)} VISIT(st,'arguments',s.args) VISIT_SEQ(st,stmt,s.body) if(!symtable_exit_block(st)){VISIT_QUIT(st,0)} if(s.type_params.length > 0){if(!symtable_exit_block(st)){VISIT_QUIT(st,0)}} break; case $B.ast.ClassDef: var tmp; if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s))) VISIT_QUIT(st,0) VISIT_SEQ(st,expr,s.bases) VISIT_SEQ(st,keyword,s.keywords) if(s.decorator_list) VISIT_SEQ(st,expr,s.decorator_list); if(s.type_params.length > 0){if(!symtable_enter_type_param_block(st,s.name,s.type_params,false,false,s.constructor,LOCATION(s))){VISIT_QUIT(st,0);} VISIT_SEQ(st,type_param,s.type_params);} VISIT_SEQ(st,expr,s.bases); VISIT_SEQ(st,keyword,s.keywords); if(!symtable_enter_block(st,s.name,ClassBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset)) VISIT_QUIT(st,0) tmp=st.private st.private=s.name if(s.type_params.length > 0){if(!symtable_add_def(st,'__type_params__',SF.DEF_LOCAL,LOCATION(s))){VISIT_QUIT(st,0);} if(!symtable_add_def(st,'type_params',SF.USE,LOCATION(s))){VISIT_QUIT(st,0);}} VISIT_SEQ(st,stmt,s.body) st.private=tmp if(! symtable_exit_block(st)) VISIT_QUIT(st,0) if(s.type_params.length > 0){if(!symtable_exit_block(st)) VISIT_QUIT(st,0);} break case $B.ast.TypeAlias: VISIT(st,expr,s.name); assert(s.name instanceof $B.ast.Name); var name=s.name.id,is_in_class=st.cur.type===ClassBlock,is_generic=s.type_params.length > 0 if(is_generic){if(!symtable_enter_type_param_block( st,name,s.type_params,false,false,s.kind,LOCATION(s))){VISIT_QUIT(st,0);} VISIT_SEQ(st,type_param,s.type_params);} if(!symtable_enter_block(st,name,TypeAliasBlock,s,LOCATION(s))){VISIT_QUIT(st,0);} st.cur.can_see_class_scope=is_in_class; if(is_in_class && !symtable_add_def(st,'__classdict__',SF.USE,LOCATION(s.value))){VISIT_QUIT(st,0);} VISIT(st,expr,s.value); if(!symtable_exit_block(st)){VISIT_QUIT(st,0);} if(is_generic){if(!symtable_exit_block(st)) VISIT_QUIT(st,0);} break case $B.ast.Return: if(s.value){VISIT(st,expr,s.value) st.cur.returns_value=1} break case $B.ast.Delete: VISIT_SEQ(st,expr,s.targets) break case $B.ast.Assign: VISIT_SEQ(st,expr,s.targets) VISIT(st,expr,s.value) break case $B.ast.AnnAssign: if(s.target instanceof $B.ast.Name){var e_name=s.target var cur=symtable_lookup(st,e_name.id) if(cur < 0){VISIT_QUIT(st,0)} if((cur &(SF.DEF_GLOBAL |SF.DEF_NONLOCAL)) &&(st.cur.symbols !=st.global) && s.simple){var exc=PyErr_Format(_b_.SyntaxError,cur & SF.DEF_GLOBAL ? GLOBAL_ANNOT :NONLOCAL_ANNOT,e_name.id) exc.args[1]=[st.filename,s.lineno,s.col_offset+1,s.end_lineno,s.end_col_offset+1] throw exc} if(s.simple && ! symtable_add_def(st,e_name.id,SF.DEF_ANNOT |SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}else{if(s.value && !symtable_add_def(st,e_name.id,SF.DEF_LOCAL,LOCATION(e_name))){VISIT_QUIT(st,0)}}}else{VISIT(st,expr,s.target)} if(!visitor.annotation(st,s.annotation)){VISIT_QUIT(st,0)} if(s.value){VISIT(st,expr,s.value)} break case $B.ast.AugAssign: VISIT(st,expr,s.target) VISIT(st,expr,s.value) break case $B.ast.For: VISIT(st,expr,s.target) VISIT(st,expr,s.iter) VISIT_SEQ(st,stmt,s.body) if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)} break case $B.ast.While: VISIT(st,expr,s.test) VISIT_SEQ(st,stmt,s.body) if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)} break case $B.ast.If: VISIT(st,expr,s.test) VISIT_SEQ(st,stmt,s.body) if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)} break case $B.ast.Match: VISIT(st,expr,s.subject) VISIT_SEQ(st,match_case,s.cases) break case $B.ast.Raise: if(s.exc){VISIT(st,expr,s.exc) if(s.cause){VISIT(st,expr,s.cause)}} break case $B.ast.Try: VISIT_SEQ(st,stmt,s.body) VISIT_SEQ(st,excepthandler,s.handlers) VISIT_SEQ(st,stmt,s.orelse) VISIT_SEQ(st,stmt,s.finalbody) break case $B.ast.TryStar: VISIT_SEQ(st,stmt,s.body) VISIT_SEQ(st,stmt,s.orelse) VISIT_SEQ(st,excepthandler,s.handlers) VISIT_SEQ(st,stmt,s.finalbody) break case $B.ast.Assert: VISIT(st,expr,s.test) if(s.msg){VISIT(st,expr,s.msg);} break case $B.ast.Import: VISIT_SEQ(st,alias,s.names) break case $B.ast.ImportFrom: VISIT_SEQ(st,alias,s.names) break case $B.ast.Global: var seq=s.names for(var name of seq){var cur=symtable_lookup(st,name) if(cur < 0){VISIT_QUIT(st,0)} if(cur &(SF.DEF_PARAM |SF.DEF_LOCAL |SF.USE |SF.DEF_ANNOT)){var msg if(cur & SF.DEF_PARAM){msg=GLOBAL_PARAM}else if(cur & SF.USE){msg=GLOBAL_AFTER_USE}else if(cur & SF.DEF_ANNOT){msg=GLOBAL_ANNOT}else{ msg=GLOBAL_AFTER_ASSIGN} var exc=PyErr_Format(_b_.SyntaxError,msg,name) set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset) throw exc} if(! symtable_add_def(st,name,SF.DEF_GLOBAL,LOCATION(s))) VISIT_QUIT(st,0) if(! symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset)) VISIT_QUIT(st,0)} break case $B.ast.Nonlocal: var seq=s.names; for(var name of seq){var cur=symtable_lookup(st,name) if(cur < 0){VISIT_QUIT(st,0)} if(cur &(SF.DEF_PARAM |SF.DEF_LOCAL |SF.USE |SF.DEF_ANNOT)){var msg if(cur & SF.DEF_PARAM){msg=NONLOCAL_PARAM}else if(cur & SF.USE){msg=NONLOCAL_AFTER_USE}else if(cur & SF.DEF_ANNOT){msg=NONLOCAL_ANNOT}else{ msg=NONLOCAL_AFTER_ASSIGN} var exc=PyErr_Format(_b_.SyntaxError,msg,name) set_exc_info(exc,st.filename,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset) throw exc} if(!symtable_add_def(st,name,SF.DEF_NONLOCAL,LOCATION(s))) VISIT_QUIT(st,0) if(!symtable_record_directive(st,name,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset)) VISIT_QUIT(st,0)} break case $B.ast.Expr: VISIT(st,expr,s.value) break case $B.ast.Pass: case $B.ast.Break: case $B.ast.Continue: break case $B.ast.With: VISIT_SEQ(st,'withitem',s.items) VISIT_SEQ(st,stmt,s.body) break case $B.ast.AsyncFunctionDef: if(!symtable_add_def(st,s.name,SF.DEF_LOCAL,LOCATION(s))) VISIT_QUIT(st,0) if(s.args.defaults) VISIT_SEQ(st,expr,s.args.defaults) if(s.args.kw_defaults) VISIT_SEQ_WITH_NULL(st,expr,s.args.kw_defaults) if(!visitor.annotations(st,s,s.args,s.returns)) VISIT_QUIT(st,0) if(s.decorator_list) VISIT_SEQ(st,expr,s.decorator_list) if(s.type_params.length > 0){if(!symtable_enter_type_param_block( st,s.name,s.type_params,s.args.defaults !=NULL,has_kwonlydefaults(s.args.kwonlyargs,s.args.kw_defaults),s.constructor,LOCATION(s))){VISIT_QUIT(st,0);} VISIT_SEQ(st,type_param,s.type_params);} if(!visitor.annotations(st,s,s.args,s.returns)) VISIT_QUIT(st,0); if(!symtable_enter_block(st,s.name,FunctionBlock,s,s.lineno,s.col_offset,s.end_lineno,s.end_col_offset)) VISIT_QUIT(st,0) st.cur.coroutine=1 VISIT(st,'arguments',s.args) VISIT_SEQ(st,stmt,s.body) if(! symtable_exit_block(st)) VISIT_QUIT(st,0) if(s.type_params.length > 0){if(!symtable_exit_block(st)) VISIT_QUIT(st,0);} break case $B.ast.AsyncWith: VISIT_SEQ(st,withitem,s.items) VISIT_SEQ(st,stmt,s.body) break case $B.ast.AsyncFor: VISIT(st,expr,s.target) VISIT(st,expr,s.iter) VISIT_SEQ(st,stmt,s.body) if(s.orelse){VISIT_SEQ(st,stmt,s.orelse)} break default: console.log('unhandled',s) break} VISIT_QUIT(st,1)} function symtable_extend_namedexpr_scope(st,e){assert(st.stack) assert(e instanceof $B.ast.Name) var target_name=e.id var i,size,ste size=st.stack.length assert(size) for(i=size-1;i >=0;i--){ste=st.stack[i] if(ste.comprehension){let target_in_scope=_PyST_GetSymbol(ste,target_name); if(target_in_scope & SF.DEF_COMP_ITER){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_CONFLICT,target_name); set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.ed_lineno,e.end_col_offset) throw exc} continue;} if(_PyST_IsFunctionLike(ste)){let target_in_scope=_PyST_GetSymbol(ste,target_name); if(target_in_scope & SF.DEF_GLOBAL){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e))) VISIT_QUIT(st,0);}else{ if(!symtable_add_def(st,target_name,SF.DEF_NONLOCAL,LOCATION(e))) VISIT_QUIT(st,0);} if(!symtable_record_directive(st,target_name,LOCATION(e))) VISIT_QUIT(st,0); return symtable_add_def_helper(st,target_name,SF.DEF_LOCAL,ste,LOCATION(e));} if(ste.type==ModuleBlock){if(!symtable_add_def(st,target_name,SF.DEF_GLOBAL,LOCATION(e))) VISIT_QUIT(st,0); if(!symtable_record_directive(st,target_name,LOCATION(e))) VISIT_QUIT(st,0); return symtable_add_def_helper(st,target_name,SF.DEF_GLOBAL,ste,LOCATION(e));} if(ste.type==ClassBlock){let exc=PyErr_Format(_b_.SyntaxError,NAMED_EXPR_COMP_IN_CLASS); set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset); throw exc}} assert(0); return 0;} function symtable_handle_namedexpr(st,e){if(st.cur.comp_iter_expr > 0){ var exc=PyErr_Format(PyExc_SyntaxError,NAMED_EXPR_COMP_ITER_EXPR); set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset); throw exc} if(st.cur.comprehension){ if(!symtable_extend_namedexpr_scope(st,e.target)) return 0;} VISIT(st,expr,e.value); VISIT(st,expr,e.target); return 1;} const alias='alias',comprehension='comprehension',excepthandler='excepthandler',expr='expr',keyword='keyword',match_case='match_case',pattern='pattern',stmt='stmt',type_param='type_param',withitem='withitem' visitor.expr=function(st,e){switch(e.constructor){case $B.ast.NamedExpr: if(!symtable_raise_if_annotation_block(st,"named expression",e)){VISIT_QUIT(st,0);} if(!symtable_handle_namedexpr(st,e)) VISIT_QUIT(st,0); break; case $B.ast.BoolOp: VISIT_SEQ(st,expr,e.values); break; case $B.ast.BinOp: VISIT(st,expr,e.left); VISIT(st,expr,e.right); break; case $B.ast.UnaryOp: VISIT(st,expr,e.operand); break; case $B.ast.Lambda:{if(!GET_IDENTIFIER('lambda')) VISIT_QUIT(st,0); if(e.args.defaults) VISIT_SEQ(st,expr,e.args.defaults); if(e.args.kw_defaults) VISIT_SEQ_WITH_NULL(st,expr,e.args.kw_defaults); if(!symtable_enter_block(st,lambda,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset)) VISIT_QUIT(st,0); VISIT(st,'arguments',e.args); VISIT(st,expr,e.body); if(!symtable_exit_block(st)) VISIT_QUIT(st,0); break;} case $B.ast.IfExp: VISIT(st,expr,e.test); VISIT(st,expr,e.body); VISIT(st,expr,e.orelse); break; case $B.ast.Dict: VISIT_SEQ_WITH_NULL(st,expr,e.keys); VISIT_SEQ(st,expr,e.values); break; case $B.ast.Set: VISIT_SEQ(st,expr,e.elts); break; case $B.ast.GeneratorExp: if(!visitor.genexp(st,e)) VISIT_QUIT(st,0); break; case $B.ast.ListComp: if(!visitor.listcomp(st,e)) VISIT_QUIT(st,0); break; case $B.ast.SetComp: if(!visitor.setcomp(st,e)) VISIT_QUIT(st,0); break; case $B.ast.DictComp: if(!visitor.dictcomp(st,e)) VISIT_QUIT(st,0); break; case $B.ast.Yield: if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0);} if(e.value){VISIT(st,expr,e.value)} st.cur.generator=1; if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)} break; case $B.ast.YieldFrom: if(!symtable_raise_if_annotation_block(st,"yield expression",e)){VISIT_QUIT(st,0)} VISIT(st,expr,e.value) st.cur.generator=1 if(st.cur.comprehension){return symtable_raise_if_comprehension_block(st,e)} break; case $B.ast.Await: if(!symtable_raise_if_annotation_block(st,"await expression",e)){VISIT_QUIT(st,0)} VISIT(st,expr,e.value) st.cur.coroutine=1 break; case $B.ast.Compare: VISIT(st,expr,e.left); VISIT_SEQ(st,expr,e.comparators); break; case $B.ast.Call: VISIT(st,expr,e.func); VISIT_SEQ(st,expr,e.args); VISIT_SEQ_WITH_NULL(st,keyword,e.keywords); break; case $B.ast.FormattedValue: VISIT(st,expr,e.value); if(e.format_spec){VISIT(st,expr,e.format_spec);} break; case $B.ast.Interpolation: VISIT(st,expr,e.value); if(e.format_spec){VISIT(st,expr,e.format_spec);} break; case $B.ast.JoinedStr: VISIT_SEQ(st,expr,e.values); break; case $B.ast.TemplateStr: VISIT_SEQ(st,expr,e.values); break; case $B.ast.Constant: break; case $B.ast.Attribute: VISIT(st,expr,e.value); break; case $B.ast.Subscript: VISIT(st,expr,e.value); VISIT(st,expr,e.slice); break; case $B.ast.Starred: VISIT(st,expr,e.value); break; case $B.ast.Slice: if(e.lower) VISIT(st,expr,e.lower) if(e.upper) VISIT(st,expr,e.upper) if(e.step) VISIT(st,expr,e.step) break; case $B.ast.Name: var flag=e.ctx instanceof $B.ast.Load ? SF.USE :SF.DEF_LOCAL if(! symtable_add_def(st,e.id,flag,LOCATION(e))) VISIT_QUIT(st,0); if(e.ctx instanceof $B.ast.Load && _PyST_IsFunctionLike(st.cur)&& e.id=="super"){if(!GET_IDENTIFIER('__class__')|| !symtable_add_def(st,'__class__',SF.USE,LOCATION(e))) VISIT_QUIT(st,0);} break; case $B.ast.List: VISIT_SEQ(st,expr,e.elts); break; case $B.ast.Tuple: VISIT_SEQ(st,expr,e.elts); break;} VISIT_QUIT(st,1);} visitor.type_param_bound_or_default=function(st,e,name,key){if(e){var is_in_class=st.cur.can_see_class_scope; if(! symtable_enter_block(st,name,TypeVarBoundBlock,key,LOCATION(e))){return 0} st.cur.can_see_class_scope=is_in_class if(is_in_class && !symtable_add_def(st,'__classdict__',SF.USE,LOCATION(e))){VISIT_QUIT(st,0)} VISIT(st,expr,e) if(!symtable_exit_block(st)){return 0}} return 1} visitor.type_param=function(st,tp){switch(tp.constructor){case $B.ast.TypeVar: if(! symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM |SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0);} if(! visitor.type_param_bound_or_default(st,tp.bound,tp.name,tp)){VISIT_QUIT(st,0)} if(! visitor.type_param_bound_or_default(st,tp.default_value,tp.name,{$id:$B.UUID()})){VISIT_QUIT(st,0)} break; case $B.ast.TypeVarTuple: if(! symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM |SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)} if(! visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)} break; case $B.ast.ParamSpec: if(! symtable_add_def(st,tp.name,SF.DEF_TYPE_PARAM |SF.DEF_LOCAL,LOCATION(tp))){VISIT_QUIT(st,0)} if(! visitor.type_param_bound_or_default(st,tp.default_value,tp.name,tp)){VISIT_QUIT(st,0)} break;} VISIT_QUIT(st,1);} visitor.pattern=function(st,p){switch(p.constructor){case $B.ast.MatchValue: VISIT(st,expr,p.value); break; case $B.ast.MatchSingleton: break; case $B.ast.MatchSequence: VISIT_SEQ(st,pattern,p.patterns); break; case $B.ast.MatchStar: if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p));} break; case $B.ast.MatchMapping: VISIT_SEQ(st,expr,p.keys); VISIT_SEQ(st,pattern,p.patterns); if(p.rest){symtable_add_def(st,p.rest,SF.DEF_LOCAL,LOCATION(p));} break; case $B.ast.MatchClass: VISIT(st,expr,p.cls); VISIT_SEQ(st,pattern,p.patterns); VISIT_SEQ(st,pattern,p.kwd_patterns); break; case $B.ast.MatchAs: if(p.pattern){VISIT(st,pattern,p.pattern);} if(p.name){symtable_add_def(st,p.name,SF.DEF_LOCAL,LOCATION(p));} break; case $B.ast.MatchOr: VISIT_SEQ(st,pattern,p.patterns); break;} VISIT_QUIT(st,1);} function symtable_implicit_arg(st,pos){var id='.'+pos if(!symtable_add_def(st,id,SF.DEF_PARAM,ST_LOCATION(st.cur))){return 0;} return 1;} visitor.params=function(st,args){if(! args){return-1} for(var arg of args){if(! symtable_add_def(st,arg.arg,SF.DEF_PARAM,LOCATION(arg))) return 0} return 1} visitor.annotation=function(st,annotation){var future_annotations=st.future.features & $B.CO_FUTURE_ANNOTATIONS if(future_annotations && !symtable_enter_block(st,'_annotation',AnnotationBlock,annotation,annotation.lineno,annotation.col_offset,annotation.end_lineno,annotation.end_col_offset)){VISIT_QUIT(st,0)} VISIT(st,expr,annotation) if(future_annotations && !symtable_exit_block(st)){VISIT_QUIT(st,0)} return 1} visitor.argannotations=function(st,args){if(!args){return-1} for(var arg of args){if(arg.annotation){VISIT(st,expr,arg.annotation)}} return 1} visitor.annotations=function(st,o,a,returns){var future_annotations=st.future.ff_features & $B.CO_FUTURE_ANNOTATIONS; if(future_annotations && !symtable_enter_block(st,'_annotation',AnnotationBlock,o,o.lineno,o.col_offset,o.end_lineno,o.end_col_offset)){VISIT_QUIT(st,0);} if(a.posonlyargs && !visitor.argannotations(st,a.posonlyargs)) return 0; if(a.args && !visitor.argannotations(st,a.args)) return 0; if(a.vararg && a.vararg.annotation) VISIT(st,expr,a.vararg.annotation); if(a.kwarg && a.kwarg.annotation) VISIT(st,expr,a.kwarg.annotation); if(a.kwonlyargs && !visitor.argannotations(st,a.kwonlyargs)) return 0; if(future_annotations && !symtable_exit_block(st)){VISIT_QUIT(st,0);} if(returns && !visitor.annotation(st,returns)){VISIT_QUIT(st,0);} return 1;} visitor.arguments=function(st,a){ if(a.posonlyargs && !visitor.params(st,a.posonlyargs)) return 0; if(a.args && !visitor.params(st,a.args)) return 0; if(a.kwonlyargs && !visitor.params(st,a.kwonlyargs)) return 0; if(a.vararg){if(!symtable_add_def(st,a.vararg.arg,SF.DEF_PARAM,LOCATION(a.vararg))) return 0; st.cur.varargs=1;} if(a.kwarg){if(!symtable_add_def(st,a.kwarg.arg,SF.DEF_PARAM,LOCATION(a.kwarg))) return 0; st.cur.varkeywords=1;} return 1;} visitor.excepthandler=function(st,eh){if(eh.type) VISIT(st,expr,eh.type); if(eh.name) if(!symtable_add_def(st,eh.name,SF.DEF_LOCAL,LOCATION(eh))) return 0; VISIT_SEQ(st,stmt,eh.body); return 1;} visitor.withitem=function(st,item){VISIT(st,expr,item.context_expr); if(item.optional_vars){VISIT(st,expr,item.optional_vars);} return 1;} visitor.match_case=function(st,m){VISIT(st,pattern,m.pattern); if(m.guard){VISIT(st,expr,m.guard);} VISIT_SEQ(st,stmt,m.body); return 1;} visitor.alias=function(st,a){ var store_name,name=(a.asname==NULL)? a.name :a.asname; var dot=name.search('\\.'); if(dot !=-1){store_name=name.substring(0,dot); if(!store_name) return 0;}else{store_name=name;} if(name !="*"){var r=symtable_add_def(st,store_name,SF.DEF_IMPORT,LOCATION(a)); return r;}else{if(st.cur.type !=ModuleBlock){var lineno=a.lineno,col_offset=a.col_offset,end_lineno=a.end_lineno,end_col_offset=a.end_col_offset; var exc=PyErr_SetString(PyExc_SyntaxError,IMPORT_STAR_WARNING); set_exc_info(exc,st.filename,lineno,col_offset,end_lineno,end_col_offset); throw exc} st.cur.$has_import_star=true return 1;}} visitor.comprehension=function(st,lc){st.cur.comp_iter_target=1; VISIT(st,expr,lc.target); st.cur.comp_iter_target=0; st.cur.comp_iter_expr++; VISIT(st,expr,lc.iter); st.cur.comp_iter_expr--; VISIT_SEQ(st,expr,lc.ifs); if(lc.is_async){st.cur.coroutine=1;} return 1;} visitor.keyword=function(st,k){VISIT(st,expr,k.value); return 1;} function symtable_handle_comprehension(st,e,scope_name,generators,elt,value){var is_generator=(e.constructor===$B.ast.GeneratorExp); var outermost=generators[0] st.cur.comp_iter_expr++; VISIT(st,expr,outermost.iter); st.cur.comp_iter_expr--; if(!scope_name || !symtable_enter_block(st,scope_name,FunctionBlock,e,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset)){return 0;} switch(e.constructor){case $B.ast.ListComp: st.cur.comprehension=ListComprehension; break; case $B.ast.SetComp: st.cur.comprehension=SetComprehension; break; case $B.ast.DictComp: st.cur.comprehension=DictComprehension; break; default: st.cur.comprehension=GeneratorExpression; break;} if(outermost.is_async){st.cur.coroutine=1;} if(!symtable_implicit_arg(st,0)){symtable_exit_block(st); return 0;} st.cur.comp_iter_target=1; VISIT(st,expr,outermost.target); st.cur.comp_iter_target=0; VISIT_SEQ(st,expr,outermost.ifs); VISIT_SEQ_TAIL(st,comprehension,generators,1); if(value) VISIT(st,expr,value); VISIT(st,expr,elt); st.cur.generator=is_generator; var is_async=st.cur.coroutine && !is_generator; if(!symtable_exit_block(st)){return 0;} if(is_async){st.cur.coroutine=1;} return 1;} visitor.genexp=function(st,e){return symtable_handle_comprehension(st,e,'genexpr',e.generators,e.elt,NULL);} visitor.listcomp=function(st,e){return symtable_handle_comprehension(st,e,'listcomp',e.generators,e.elt,NULL);} visitor.setcomp=function(st,e){return symtable_handle_comprehension(st,e,'setcomp',e.generators,e.elt,NULL);} visitor.dictcomp=function(st,e){return symtable_handle_comprehension(st,e,'dictcomp',e.generators,e.key,e.value);} function symtable_raise_if_annotation_block(st,name,e){var type=st.cur.type,exc if(type==AnnotationBlock) exc=PyErr_Format(PyExc_SyntaxError,ANNOTATION_NOT_ALLOWED,name); else if(type==TypeVarBoundBlock) exc=PyErr_Format(PyExc_SyntaxError,TYPEVAR_BOUND_NOT_ALLOWED,name); else if(type==TypeAliasBlock) exc=PyErr_Format(PyExc_SyntaxError,TYPEALIAS_NOT_ALLOWED,name); else if(type==TypeParamBlock) exc=PyErr_Format(PyExc_SyntaxError,TYPEPARAM_NOT_ALLOWED,name); else return 1; set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset); throw exc} function symtable_raise_if_comprehension_block(st,e){var type=st.cur.comprehension; var exc=PyErr_SetString(PyExc_SyntaxError,(type==ListComprehension)? "'yield' inside list comprehension" : (type==SetComprehension)? "'yield' inside set comprehension" : (type==DictComprehension)? "'yield' inside dict comprehension" : "'yield' inside generator expression"); exc.$frame_obj=$B.frame_obj set_exc_info(exc,st.filename,e.lineno,e.col_offset,e.end_lineno,e.end_col_offset); throw exc}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,NULL=undefined,DOT='.',ELLIPSIS='...' const STAR_TARGETS=1,DEL_TARGETS=2,FOR_TARGETS=3 function make_string_for_ast_value(value){value=value.replace(/\n/g,'\\n\\\n') value=value.replace(/\r/g,'\\r\\\r') if(value[0]=="'"){var unquoted=value.substr(1,value.length-2) return unquoted} if(value.indexOf("'")>-1){var s='',escaped=false for(var char of value){if(char=='\\'){if(escaped){s+='\\\\'} escaped=!escaped}else{if(char=="'" && ! escaped){ s+='\\'}else if(escaped){s+='\\'} s+=char escaped=false}} value=s} return value.substr(1,value.length-2)} var escapeseq={a:'\a',b:'\b',f:'\f',n:'\n',r:'\r',t:'\t',v:'\v','"':'"',"'":"'"} function encode_bytestring(s){var s1='' var escape=false for(var char of s){if(char=='\\'){if(escape){s1+=char} escape=! escape}else if(escape){var repl=escapeseq[char] s1+=repl ?? char escape=false}else{s1+=char}} s=s1 var t=[] for(var i=0,len=s1.length;i < len;i++){var cp=s1.codePointAt(i) if(cp > 255){throw Error()} t.push(cp)} return t} function EXTRA_EXPR(head,tail){return{ lineno:head.lineno,col_offset:head.col_offset,end_lineno:tail.end_lineno,end_col_offset:tail.end_col_offset}} function set_list(list,other){for(var item of other){list.push(item)}} var positions=['lineno','col_offset','end_lineno','end_col_offset'] function set_position_from_list(ast_obj,EXTRA){for(var i=0;i < 4;i++){ast_obj[positions[i]]=EXTRA[i]}} function set_position_from_token(ast_obj,token){ast_obj.lineno=token.lineno ast_obj.col_offset=token.col_offset ast_obj.end_lineno=token.end_lineno ast_obj.end_col_offset=token.end_col_offset} function set_position_from_obj(ast_obj,obj){for(var position of positions){ast_obj[position]=obj[position]}} function _get_names(p,names_with_defaults){var seq=[] for(var pair of names_with_defaults){seq.push(pair.arg)} return seq} function _get_defaults(p,names_with_defaults){var seq=[] for(var pair of names_with_defaults){seq.push(pair.value)} return seq} function _make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs){if(slash_without_default !=NULL){set_list(posonlyargs,slash_without_default)}else if(slash_with_default !=NULL){var slash_with_default_names= _get_names(p,slash_with_default.names_with_defaults); if(!slash_with_default_names){return-1;} set_list(posonlyargs,$B._PyPegen.join_sequences( p,slash_with_default.plain_names,slash_with_default_names))} return posonlyargs==NULL ?-1 :0;} function _make_posargs(p,plain_names,names_with_default,posargs){if(plain_names !=NULL && names_with_default !=NULL){var names_with_default_names=_get_names(p,names_with_default); if(!names_with_default_names){return-1;} var seqs=$B._PyPegen.join_sequences( p,plain_names,names_with_default_names) set_list(posargs,seqs);}else if(plain_names==NULL && names_with_default !=NULL){set_list(posargs,_get_names(p,names_with_default))} else if(plain_names !=NULL && names_with_default==NULL){set_list(posargs,plain_names)} return posargs==NULL ?-1 :0;} function _make_posdefaults(p,slash_with_default,names_with_default,posdefaults){if(slash_with_default !=NULL && names_with_default !=NULL){var slash_with_default_values= _get_defaults(p,slash_with_default.names_with_defaults); if(!slash_with_default_values){return-1;} var names_with_default_values=_get_defaults(p,names_with_default); if(!names_with_default_values){return-1;} set_list(posdefaults,$B._PyPegen.join_sequences( p,slash_with_default_values,names_with_default_values))}else if(slash_with_default==NULL && names_with_default !=NULL){set_list(posdefaults,_get_defaults(p,names_with_default))} else if(slash_with_default !=NULL && names_with_default==NULL){set_list(posdefaults,_get_defaults(p,slash_with_default.names_with_defaults))} return posdefaults==NULL ?-1 :0;} function _make_kwargs(p,star_etc,kwonlyargs,kwdefaults){if(star_etc !=NULL && star_etc.kwonlyargs !=NULL){set_list(kwonlyargs,_get_names(p,star_etc.kwonlyargs))}else{ set_list(kwonlyargs,[])} if(kwonlyargs==NULL){return-1;} if(star_etc !=NULL && star_etc.kwonlyargs !=NULL){set_list(kwdefaults,_get_defaults(p,star_etc.kwonlyargs))} else{ set_list(kwdefaults,[])} if(kwdefaults==NULL){return-1;} return 0;} function _seq_number_of_starred_exprs(seq){var n=0 for(var k of seq){if(! k.is_keyword){n++;}} return n} $B._PyPegen={} $B._PyPegen.PyErr_Occurred=function(){ return false} $B._PyPegen.constant_from_string=function(p,token){var prepared=$B.prepare_string(p,token) var is_bytes=prepared.value.startsWith('b') if(! is_bytes){var value=make_string_for_ast_value(prepared.value)}else{var value=prepared.value.substr(2,prepared.value.length-3) try{value=_b_.bytes.$factory(encode_bytestring(value))}catch(err){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,token.lineno,token.col_offset,token.end_lineno,token.end_col_offset,'bytes can only contain ASCII literal characters')}} var ast_obj=new $B.ast.Constant(value) set_position_from_token(ast_obj,token) return ast_obj} $B._PyPegen.constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string) set_position_from_token(ast_obj,t) return ast_obj} $B._PyPegen.decoded_constant_from_token=function(p,t){var ast_obj=new $B.ast.Constant(t.string) set_position_from_token(ast_obj,t) return ast_obj} function is_whitespace(char){return ' \n\r\t\f'.includes(char)} function _get_interpolation_conversion(p,debug,conversion,format){if(conversion !=NULL){var conversion_expr=conversion.result return conversion_expr.id}else if(debug && !format){ return 'r'} return-1;} function _strip_interpolation_expr(exprstr){var len=exprstr.length for(var c of exprstr){if(is_whitespace(c)||c=='='){len--}else{break}} return exprstr.substr(0,len)} $B._PyPegen.interpolation=function(p,expression,debug,conversion,format,closing_brace,position,arena){var lineno=position.lineno,col_offset=position.col_offset,end_lineno=position.end_lineno,end_col_offset=position.end_col_offset var conversion_val=_get_interpolation_conversion(p,debug,conversion,format); var debug_end_line,debug_end_offset; var debug_metadata; var exprstr; if(conversion){debug_end_line=conversion.result.lineno debug_end_offset=conversion.result.col_offset; debug_metadata=exprstr=conversion.metadata;}else if(format){debug_end_line=format.result.lineno; debug_end_offset=format.result.col_offset+1; debug_metadata=exprstr=format.metadata;}else{debug_end_line=end_lineno; debug_end_offset=end_col_offset; debug_metadata=exprstr=closing_brace.metadata;} var final_exprstr=_strip_interpolation_expr(exprstr); if(final_exprstr){p.arena.a_objects.push(final_exprstr)} var interpolation=$B._PyAST.Interpolation( expression,final_exprstr,conversion_val,format ? format.result :NULL) set_position_from_obj(interpolation,position) if(!debug){return interpolation;} var debug_text=$B._PyAST.Constant(debug_metadata) set_position_from_list(debug_text,[lineno,col_offset+1,debug_end_line,debug_end_offset-1]) var values=[debug_text,interpolation] var ast_obj=$B._PyAST.JoinedStr(values) set_position_from_list(ast_obj,[lineno,col_offset,debug_end_line,debug_end_offset]) console.log('JoinedStr',ast_obj) return ast_obj} $B._PyPegen.formatted_value=function(p,expression,debug,conversion,format,closing_brace,arena){var conversion_val=_get_interpolation_conversion(p,debug,conversion,format) if(typeof conversion_val=='string'){ if(conversion_val.length > 1 ||! 'sra'.includes(conversion_val)){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion.result,`f-string: invalid conversion character ${conversion_val}: `+ "expected 's', 'r', or 'a'")} conversion_val=conversion_val.charCodeAt(0)} var formatted_value=new $B.ast.FormattedValue(expression,conversion_val,format===undefined ? format :format.result) set_position_from_obj(formatted_value,arena) if(debug){var debug_end_line,debug_end_offset,debug_metadata if(conversion){debug_end_line=conversion.result.lineno debug_end_offset=conversion.result.col_offset debug_metadata=conversion.metadata}else if(format){debug_end_line=format.result.lineno debug_end_offset=format.result.col_offset+1 debug_metadata=format.metadata}else{debug_end_line=p.end_lineno debug_end_offset=p.end_col_offset debug_metadata=closing_brace.metadata} var debug=new $B.ast.Constant(debug_metadata) debug.lineno=p.lineno debug.col_offset=p.col_offset+1 debug.end_lineno=debug_end_line debug.end_col_offset=debug_end_offset var joined_str=new $B.ast.JoinedStr([debug,formatted_value]) set_position_from_obj(joined_str,arena) return joined_str} return formatted_value} $B._PyPegen.decode_fstring_part=function(p,is_raw,constant,token){var bstr=constant.value var len; if(bstr=="{{" ||bstr=="}}"){len=1}else{len=bstr.length} is_raw=is_raw ||! bstr.includes('\\') var str=bstr if(str==NULL){_Pypegen_raise_decode_error(p); return NULL;} p.arena.a_objects.push(str) return $B._PyAST.Constant(str,NULL,constant.lineno,constant.col_offset,constant.end_lineno,constant.end_col_offset,p.arena);} function _get_resized_exprs(p,a,raw_expressions,b,string_kind){var n_items=raw_expressions.length var total_items=n_items for(var item of raw_expressions){if(item instanceof $B.ast.JoinedStr){total_items+=item.values.length-1;}} var quote_str=a.bytes if(quote_str==NULL){return NULL;} var is_raw=quote_str.includes('r')||quote_str.includes('R') var seq=[] var index=0; for(var i=0;i < n_items;i++){var item=raw_expressions[i] if(item instanceof $B.ast.JoinedStr){var values=item.values if(values.length !=2){PyErr_Format(PyExc_SystemError,string_kind==TSTRING ? "unexpected TemplateStr node without debug data in t-string at line %d" :"unexpected JoinedStr node without debug data in f-string at line %d",item.lineno); return NULL;} var first=values[0] seq[index++]=first var second=values[1] seq[index++]=second continue;} if(item instanceof $B.ast.Constant){item=$B._PyPegen.decode_fstring_part(p,is_raw,item,b); if(item==NULL){return NULL;} if(item.value.length==0){continue;}} seq[index++]=item} var resized_exprs if(index !=total_items){resized_exprs=_Py_asdl_expr_seq_new(index,p.arena); if(resized_exprs==NULL){return NULL;} for(var i=0;i < index;i++){resized_exprs[i]=seq[i]}}else{resized_exprs=seq;} return resized_exprs;} $B._PyPegen.template_str=function(p,a,raw_expressions,b){var resized_exprs=_get_resized_exprs(p,a,raw_expressions,b,'TSTRING') var ast_obj=new $B.ast.TemplateStr(resized_exprs) set_position_from_list(ast_obj,[a.lineno,a.col_offset,b.end_lineno,b.end_col_offset]) return ast_obj} $B._PyPegen.joined_str=function(p,a,items,c){var ast_obj=new $B.ast.JoinedStr(items) ast_obj.lineno=a.lineno ast_obj.col_offset=a.col_offset ast_obj.end_lineno=c.end_lineno ast_obj.end_col_offset=c.end_col_offset return ast_obj} $B._PyPegen.setup_full_format_spec=function(p,colon,spec,arena){var ast_obj=new $B.ast.JoinedStr(spec) set_position_from_obj(ast_obj,arena) return result_token_with_metadata(p,ast_obj,colon.metadata)} function result_token_with_metadata(p,result,metadata){return{result,metadata}} $B._PyPegen.check_fstring_conversion=function(p,conv_token,conv){if(conv_token.lineno !=conv.lineno || conv_token.end_col_offset !=conv.col_offset){$B._PyPegen.raise_error_known_location(p,_b_.SyntaxError,conv.lineno,conv.col_offset,conv.end_lineno,conv.end_col_offset,"f-string: conversion type must come right after the exclamanation mark" )} return result_token_with_metadata(p,conv,conv_token.metadata)} $B._PyPegen.seq_count_dots=function(seq){if(seq===undefined){return 0} var number_of_dots=0; for(var token of seq){if(token.num_type==$B.py_tokens.DOT){number_of_dots+=token.string.length}else if(token.num_type==$B.py_tokens.ELLIPSIS){number_of_dots+=3}} return number_of_dots;} $B._PyPegen.map_names_to_ids=function(p,seq){return seq.map(e=> e.id)} $B._PyPegen.alias_for_star=function(p,lineno,col_offset,end_lineno,end_col_offset,arena){var str="*" return $B._PyAST.alias(str,NULL,lineno,col_offset,end_lineno,end_col_offset,arena);} $B._PyPegen.cmpop_expr_pair=function(p,cmpop,expr){return{cmpop,expr}} $B._PyPegen.get_cmpops=function(p,seq){var new_seq=[] for(var pair of seq){new_seq.push(pair.cmpop)} return new_seq} $B._PyPegen.get_exprs=function(p,seq){var new_seq=[] for(var pair of seq){new_seq.push(pair.expr)} return new_seq} function _set_seq_context(p,seq,ctx){var new_seq=[] for(var e of seq){new_seq.push($B._PyPegen.set_expr_context(p,e,ctx))} return new_seq} function _set_name_context(p,e,ctx){return $B._PyAST.Name(e.id,ctx,EXTRA_EXPR(e,e))} function _set_tuple_context(p,e,ctx){return $B._PyAST.Tuple( _set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e));} function _set_list_context(p,e,ctx){return $B._PyAST.List( _set_seq_context(p,e.elts,ctx),ctx,EXTRA_EXPR(e,e));} function _set_subscript_context(p,e,ctx){return $B._PyAST.Subscript(e.value,e.slice,ctx,EXTRA_EXPR(e,e));} function _set_attribute_context(p,e,ctx){return $B._PyAST.Attribute(e.value,e.attr,ctx,EXTRA_EXPR(e,e));} function _set_starred_context(p,e,ctx){return $B._PyAST.Starred($B._PyPegen.set_expr_context(p,e.value,ctx),ctx,EXTRA_EXPR(e,e));} $B._PyPegen.set_expr_context=function(p,expr,ctx){var _new=NULL; switch(expr.constructor){case $B.ast.Name: _new=_set_name_context(p,expr,ctx); break; case $B.ast.Tuple: _new=_set_tuple_context(p,expr,ctx); break; case $B.ast.List: _new=_set_list_context(p,expr,ctx); break; case $B.ast.Subscript: _new=_set_subscript_context(p,expr,ctx); break; case $B.ast.Attribute: _new=_set_attribute_context(p,expr,ctx); break; case $B.ast.Starred: _new=_set_starred_context(p,expr,ctx); break; default: _new=expr;} return _new;} $B._PyPegen.key_value_pair=function(p,key,value){return{key,value}} $B._PyPegen.get_expr_name=function(e){switch(e.constructor.$name){case 'Attribute': case 'Subscript': case 'Starred': case 'Name': case 'List': case 'Tuple': case 'Lambda': return e.constructor.$name.toLowerCase() case 'Call': return "function call" case 'BoolOp': case 'BinOp': case 'UnaryOp': return "expression" case 'GeneratorExp': return "generator expression"; case 'Yield': case 'YieldFrom': return "yield expression"; case 'Await': return "await expression"; case 'ListComp': return "list comprehension"; case 'SetComp': return "set comprehension"; case 'DictComp': return "dict comprehension"; case 'Dict': return "dict literal"; case 'Set': return "set display"; case 'JoinedStr': case 'FormattedValue': return "f-string expression"; case 'Constant': var value=e.value if(value===_b_.None){return "None";} if(value===false){return "False";} if(value===true){return "True";} if(value===_b_.Ellipsis){return "ellipsis";} return "literal"; case 'Compare': return "comparison"; case 'IfExp': return "conditional expression"; case 'NamedExpr': return "named expression"; default: return NULL;}} $B._PyPegen.get_keys=function(p,seq){return seq===undefined ?[]:seq.map(pair=> pair.key)} $B._PyPegen.get_values=function(p,seq){return seq===undefined ?[]:seq.map(pair=> pair.value)} $B._PyPegen.key_pattern_pair=function(p,key,pattern){return{key,pattern}} $B._PyPegen.get_pattern_keys=function(p,seq){return seq===undefined ?[]:seq.map(x=> x.key)} $B._PyPegen.get_patterns=function(p,seq){return seq===undefined ?[]:seq.map(x=> x.pattern)} $B._PyPegen.check_legacy_stmt=function(p,name){return["print","exec"].includes(name)} $B._PyPegen.dummy_name=function(p){var cache=NULL; if(cache !=NULL){return cache;} var id="dummy"+Math.random().toString(36).substr(2),ast_obj=new $B.ast.Name(id,new $B.ast.Load()) set_position_from_list(ast_obj,[1,0,1,0]) return ast_obj} $B._PyPegen.add_type_comment_to_arg=function(p,a,tc){if(tc==NULL){return a} var bytes=_b_.bytes.$factory(tc),tco=$B._PyPegen.new_type_comment(p,bytes); var ast_obj=$B._PyAST.arg(a.arg,a.annotation,tco,a.lineno,a.col_offset,a.end_lineno,a.end_col_offset,p.arena); console.log('arg with type comment',ast_obj) return ast_obj} $B._PyPegen.check_barry_as_flufl=function(p,t){return false} $B._PyPegen.empty_arguments=function(p){return $B._PyAST.arguments([],[],NULL,[],[],NULL,[],p.arena)} $B._PyPegen.augoperator=function(p,kind){return{kind}} $B._PyPegen.function_def_decorators=function(p,decorators,function_def){var constr=function_def instanceof $B.ast.AsyncFunctionDef ? $B.ast.AsyncFunctionDef :$B.ast.FunctionDef var ast_obj=new constr( function_def.name,function_def.args,function_def.body,decorators,function_def.returns,function_def.type_comment,function_def.type_params,p.arena) for(var position of positions){ast_obj[position]=function_def[position]} return ast_obj} $B._PyPegen.class_def_decorators=function(p,decorators,class_def){var ast_obj=$B._PyAST.ClassDef( class_def.name,class_def.bases,class_def.keywords,class_def.body,decorators,class_def.type_params,p.arena) set_position_from_obj(ast_obj,class_def) return ast_obj} $B._PyPegen.keyword_or_starred=function(p,element,is_keyword){return{ element,is_keyword}} $B._PyPegen.make_arguments=function(p,slash_without_default,slash_with_default,plain_names,names_with_default,star_etc){ var posonlyargs=[] if(_make_posonlyargs(p,slash_without_default,slash_with_default,posonlyargs)==-1){return NULL;} var posargs=[] if(_make_posargs(p,plain_names,names_with_default,posargs)==-1){return NULL;} var posdefaults=[] if(_make_posdefaults(p,slash_with_default,names_with_default,posdefaults)==-1){return NULL;} var vararg=NULL; if(star_etc !=NULL && star_etc.vararg !=NULL){vararg=star_etc.vararg;} var kwonlyargs=[],kwdefaults=[]; if(_make_kwargs(p,star_etc,kwonlyargs,kwdefaults)==-1){return NULL;} var kwarg=NULL; if(star_etc !=NULL && star_etc.kwarg !=NULL){kwarg=star_etc.kwarg;} var ast_obj=$B._PyAST.arguments(posonlyargs,posargs,vararg,kwonlyargs,kwdefaults,kwarg,posdefaults,p.arena) if(ast_obj.posonlyargs===undefined){console.log('pas de posonlyargs',ast_bj) alert()} return ast_obj} $B._PyPegen.name_default_pair=function(p,arg,value,tc){return{ arg:$B._PyPegen.add_type_comment_to_arg(p,arg,tc),value:value}} $B._PyPegen.raise_error=function(p,errtype,errmsg){if(p.fill==0){var va=[errmsg] $B._PyPegen.raise_error_known_location(p,errtype,0,0,0,-1,errmsg,va); return NULL} var t=p.known_err_token !=NULL ? p.known_err_token :p.tokens[p.fill-1]; var va=errmsg $B._PyPegen.raise_error_known_location(p,errtype,t.lineno,t.col_offset,t.end_lineno,t.end_col_offset,errmsg,va);} $B._PyPegen.raise_error_known_location=function(p,errtype,lineno,col_offset,end_lineno,end_col_offset,errmsg,va){var exc=$B.EXC(errtype,errmsg) exc.filename=p.filename if(p.known_err_token){var token=p.known_err_token exc.lineno=token.lineno exc.offset=token.col_offset+1 exc.end_lineno=token.end_lineno exc.end_offset=token.end_col_offset exc.text=token.line}else{exc.lineno=lineno exc.offset=col_offset+1 exc.end_lineno=end_lineno exc.end_offset=end_col_offset+1 var src=$B.file_cache[p.filename] if(src !==undefined){var lines=src.split('\n'),line=lines[exc.lineno-1] exc.text=line+'\n'}else{exc.text=_b_.None}} exc.args[1]=$B.fast_tuple([p.filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]) throw exc} $B._PyPegen.seq_delete_starred_exprs=function(p,kwargs){var len=kwargs.length,new_len=len-_seq_number_of_starred_exprs(kwargs) if(new_len==0){return NULL;} var new_seq=[] for(var k of kwargs){if(k.is_keyword){new_seq.push(k.element)}} return new_seq} $B._PyPegen.seq_extract_starred_exprs=function(p,kwargs){var new_len=_seq_number_of_starred_exprs(kwargs); if(new_len==0){return NULL;} var new_seq=[] var idx=0; for(var k of kwargs){if(! k.is_keyword){new_seq[idx++]=k.element}} return new_seq} $B._PyPegen.slash_with_default=function(p,plain_names,names_with_defaults){return{plain_names,names_with_defaults}} $B._PyPegen.star_etc=function(p,vararg,kwonlyargs,kwarg){return{vararg,kwonlyargs,kwarg}} $B._PyPegen.collect_call_seqs=function(p,a,b,lineno,col_offset,end_lineno,end_col_offset,arena){var args_len=a.length,total_len=args_len; if(b==NULL){return $B._PyAST.Call($B._PyPegen.dummy_name(p),a,[],lineno,col_offset,end_lineno,end_col_offset,arena);} var starreds=$B._PyPegen.seq_extract_starred_exprs(p,b),keywords=$B._PyPegen.seq_delete_starred_exprs(p,b); if(starreds){total_len+=starreds.length} var args=[] for(var i=0;i < args_len;i++){args[i]=a[i]} for(;i < total_len;i++){args[i]=starreds[i-args_len]} return $B._PyAST.Call($B._PyPegen.dummy_name(p),args,keywords,lineno,col_offset,end_lineno,end_col_offset,arena);} $B._PyPegen.join_sequences=function(p,a,b){return a.concat(b)} function make_conversion_code(conv){switch(conv){case null: return-1 case 'a': return 97 case 'r': return 114 case 's': return 115}} function make_formatted_value(p,fmt_values){ if(! fmt_values){return} var seq=[] for(var item of fmt_values){if(typeof item=='string'){var fmt_ast=new $B.ast.Constant(item) set_position_from_obj(fmt_ast,p.arena)}else{var src=item.expression.trimStart() var _ast=new $B.Parser(src,p.filename,'eval').parse() var raw_value=_ast.body var fmt_ast=new $B.ast.FormattedValue(raw_value,make_conversion_code(item.conversion),make_formatted_value(p,item.fmt)) set_position_from_obj(fmt_ast,_ast)} seq.push(fmt_ast)} var ast_obj=new $B.ast.JoinedStr(seq) set_position_from_obj(ast_obj,p.arena) return ast_obj} function _build_concatenated_str(p,strings){var len=strings.length var n_flattened_elements=0; for(var elem of strings){if(elem instanceof $B.ast.JoinedStr || elem instanceof $B.ast.TemplateStr){n_flattened_elements+=elem.values.length}else{n_flattened_elements++}} var flattened=[] var current_pos=0; for(var elem of strings){if(elem instanceof $B.ast.JoinedStr || elem instanceof $B.ast.TemplateStr){for(var subvalue of elem.values){flattened[current_pos++]=subvalue}}else{flattened[current_pos++]=elem}} var n_elements=0 var prev_is_constant=0 for(var elem of flattened){ if(elem instanceof $B.ast.Constant && typeof elem.value=='string' && elem.value.length==0){continue} if(!prev_is_constant ||!(elem instanceof $B.ast.Constant)){n_elements++;} prev_is_constant=elem instanceof $B.ast.Constant} var values=[] current_pos=0; for(var i=0,len=flattened.length;i < len;i++){var elem=flattened[i] if(elem instanceof $B.ast.Constant){if(i+1 < n_flattened_elements && flattened[i+1]instanceof $B.ast.Constant){var first_elem=elem; var kind=elem.__class__ var concat_str='' var last_elem=elem; var j for(j=i;j < n_flattened_elements;j++){var current_elem=flattened[j] if(current_elem instanceof $B.ast.Constant){concat_str+=current_elem.value last_elem=current_elem;}else{break;}} i=j-1 p.arena.a_objects.push(concat_str) elem=new $B.ast.Constant(concat_str,kind) set_position_from_list(elem,[first_elem.lineno,first_elem.col_offset,last_elem.end_lineno,last_elem.end_col_offset]);} if(elem.value.length==0){continue}} values[current_pos++]=elem} return values} function _build_concatenated_template_str(p,strings){var values=_build_concatenated_str(p,strings) var ast_obj=new $B.ast.TemplateStr(values) var last=strings[strings.length-1] set_position_from_list(ast_obj,[strings[0].lineno,strings[0].col_offset,last.end_lineno,last.end_col_offset]) return ast_obj} function _build_concatenated_joined_str(p,strings){var values=_build_concatenated_str(p,strings) var ast_obj=new $B.ast.JoinedStr(values) var last=strings[strings.length-1] set_position_from_list(ast_obj,[strings[0].lineno,strings[0].col_offset,last.end_lineno,last.end_col_offset]) return ast_obj} $B._PyPegen.concatenate_strings=function(p,strings){var res='',first=strings[0],last=$B.last(strings),type var state=NULL,value,values=[] function error(message){var a={lineno:first.start[0],col_offset:first.start[1],end_lineno :last.end[0],end_col_offset:last.end[1]} $B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,message)} function set_position_from_list(ast_obj,items){var first=items[0],last=items[items.length-1] ast_obj.lineno=first.lineno ast_obj.col_offset=first.col_offset ast_obj.end_lineno=last.end_lineno ast_obj.end_col_offset=last.end_col_offset} function escape_single_quotes(token){for(var fs_item of token.values){if(fs_item instanceof $B.ast.Constant){ var parts=fs_item.value.split('\\\'') parts=parts.map(x=> x.replace(new RegExp("'","g"),"\\'")) fs_item.value=parts.join('\\\'') fs_item.value=fs_item.value.replace(/\n/g,'\\n') .replace(/\r/g,'\\r')}}} var items=[],has_fstring=false,has_tstring=false,state for(var string of strings){if(string instanceof $B.ast.JoinedStr){ has_fstring=true if(state=='bytestring'){error('cannot mix bytes and nonbytes literals')} escape_single_quotes(string) state='string'}else if(string instanceof $B.ast.TemplateStr){ has_tstring=true if(state=='bytestring'){error('cannot mix bytes and nonbytes literals')} escape_single_quotes(string) state='string'}else{items.push(string) var is_bytes=string.value.__class__===_b_.bytes if((is_bytes && state=='string')|| (state=='bytestring' && ! is_bytes)){error('cannot mix bytes and nonbytes literals')} state=is_bytes ? 'bytestring' :'string'}} if(state=='bytestring'){ var bytes=[] for(var item of items){bytes=bytes.concat(item.value.source)} value=_b_.bytes.$factory(bytes) var ast_obj=new $B.ast.Constant(value) set_position_from_list(ast_obj,items) return ast_obj} function group_consec_strings(items){if(items.length==1){return items[0]} var values=items.map(x=> x.value) let ast_obj=new $B.ast.Constant(values.join('')) set_position_from_list(ast_obj,items) return ast_obj} var items1=[],consec_strs=[],item_type=null for(var i=0,len=items.length;i < len;i++){item=items[i] if(item_type===null){item_type=Object.getPrototypeOf(item)} if(item instanceof $B.ast.Constant){consec_strs.push(item)}else{if(consec_strs.length > 0){items1.push(group_consec_strings(consec_strs))} consec_strs=[] items1.push(item)}} if(consec_strs.length > 0){items1.push(group_consec_strings(consec_strs))} if(! has_fstring && ! has_tstring){return items1[0]} if(has_tstring){return _build_concatenated_template_str(p,strings)} return _build_concatenated_joined_str(p,strings)} $B._PyPegen.concatenate_tstrings=$B._PyPegen.concatenate_strings $B._PyPegen.checked_future_import=function(p,module,names,level,lineno,col_offset,end_lineno,end_col_offset,arena){if(level==0 && module=="__future__"){for(var i=0;i < names.length;i++){var alias=names[i] if(alias.name=="barry_as_FLUFL"){p.flags |=PyPARSE_BARRY_AS_BDFL;}}} return $B._PyAST.ImportFrom(module,names,level,lineno,col_offset,end_lineno,end_col_offset,arena);} $B._PyPegen.register_stmts=function(p,stmts){if(! p.call_invalid_rules){return stmts} var len=stmts.length if(len==0){return stmts} var last_stmt=stmts[len-1] p.last_stmt_location.lineno=last_stmt.lineno p.last_stmt_location.col_offset=last_stmt.col_offset p.last_stmt_location.end_lineno=last_stmt.end_lineno p.last_stmt_location.end_col_offset=last_stmt.end_col_offset return stmts} $B._PyPegen.ensure_imaginary=function(p,exp){if(!(exp instanceof $B.ast.Constant)|| exp.value.__class__ !=_b_.complex){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp,"imaginary number required in complex literal"); return NULL} return exp} $B._PyPegen.ensure_real=function(p,exp){if(!(exp instanceof $B.ast.Constant)||exp.value.type=='imaginary'){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION( exp,"real number required in complex literal"); return NULL} return exp} $B._PyPegen.set_expr_context=function(p,a,ctx){a.ctx=ctx return a} $B._PyPegen.singleton_seq=function(p,a){return[a]} $B._PyPegen.seq_insert_in_front=function(p,a,seq){return seq ?[a].concat(seq):[a]} $B._PyPegen.seq_flatten=function(p,seqs){var res=[] for(var seq of seqs){for(var item of seq){res.push(item)}} return res} $B._PyPegen.join_names_with_dot=function(p,first_name,second_name){var str=first_name.id+'.'+second_name.id return $B._PyAST.Name(str,new $B.ast.Load(),EXTRA_EXPR(first_name,second_name))} $B._PyPegen.make_module=function(p,a){return new $B.ast.Module(a)} $B._PyPegen.new_type_comment=function(p,s){if(s.length===0){return NULL} return s} $B._PyPegen.get_last_comprehension_item=function(comprehension){if(comprehension.ifs==NULL ||comprehension.ifs.length==0){return comprehension.iter;} return $B.last(comprehension.ifs);} $B._PyPegen.arguments_parsing_error=function(p,e){var kwarg_unpacking=0; for(let keyword of e.keywords){if(! keyword.arg){kwarg_unpacking=1;}} var msg=NULL; if(kwarg_unpacking){msg="positional argument follows keyword argument unpacking";}else{ msg="positional argument follows keyword argument";} return $B.helper_functions.RAISE_SYNTAX_ERROR(p,msg);} $B._PyPegen.nonparen_genexp_in_call=function(p,args,comprehensions){ var len=args.args.length if(len <=1){return NULL;} var last_comprehension=$B.last(comprehensions); return $B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,args.args[len-1],$B._PyPegen.get_last_comprehension_item(last_comprehension),"Generator expression must be parenthesized" );} $B._PyPegen.get_invalid_target=function(e,targets_type){if(e==NULL){return NULL;} function VISIT_CONTAINER(CONTAINER,TYPE){for(var elt of CONTAINER.elts){var child=$B._PyPegen.get_invalid_target(elt,targets_type); if(child !=NULL){return child;}}} switch(e.constructor){case $B.ast.List: case $B.ast.Tuple: return VISIT_CONTAINER(e,e.constructor); case $B.ast.Starred: if(targets_type==DEL_TARGETS){return e;} return $B._PyPegen.get_invalid_target(e.value,targets_type); case $B.ast.Compare: if(targets_type==FOR_TARGETS){var cmpop=e.ops[0] if(cmpop instanceof $B.ast.In){return $B._PyPegen.get_invalid_target(e.left,targets_type);} return NULL;} return e; case $B.ast.Name: case $B.ast.Subscript: case $B.ast.Attribute: return NULL; default: return e;}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins var s_escaped='abfnrtvxuU"0123456789'+"'"+'\\',is_escaped={} for(var i=0;i < s_escaped.length;i++){is_escaped[s_escaped.charAt(i)]=true} function escaped_to_byte(char){var table={a:7,b:8,f:12,n:10,r:13,t:9,v:11} if(table[char]!==undefined){return table[char]} return char.charCodeAt(0)} function to_bytes(s){var pos=0,bytes=[] while(pos < s.length){if(s[pos]=='\\'){bytes[bytes.length]=escaped_to_byte(s[pos+1]) pos+=2}else{bytes[bytes.length]=s.charCodeAt(pos) pos++}} return bytes} function string_error(p,token,msg){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,token,msg)} function SurrogatePair(value){this.value=value} function test_escape(p,token,context,text,string_start,antislash_pos){ var seq_end,mo mo=/^[0-7]{1,3}/.exec(text.substr(antislash_pos+1)) if(mo){if(mo[0].length==3 && mo[0][0]>='4'){$B.warn(_b_.SyntaxWarning,`invalid octal escape sequence '\\${mo[0]}'`,p.filename,token)} return[String.fromCharCode(parseInt(mo[0],8)),1+mo[0].length]} switch(text[antislash_pos+1]){case "x": var mo=/^[0-9A-F]{0,2}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=2){seq_end=antislash_pos+mo[0].length+1 string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\xXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]} case "u": var mo=/^[0-9A-F]{0,4}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=4){seq_end=antislash_pos+mo[0].length+1 string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\uXXXX escape"])}else{return[String.fromCharCode(parseInt(mo[0],16)),2+mo[0].length]} case "U": var mo=/^[0-9A-F]{0,8}/i.exec(text.substr(antislash_pos+2)) if(mo[0].length !=8){seq_end=antislash_pos+mo[0].length+1 string_error(p,token,["(unicode error) 'unicodeescape' codec can't decode "+ `bytes in position ${antislash_pos}-${seq_end}: truncated `+ "\\UXXXXXXXX escape"])}else{var value=parseInt(mo[0],16) if(value > 0x10FFFF){string_error(p,token,'invalid unicode escape '+mo[0])}else if(value >=0x10000){return[new SurrogatePair(value),2+mo[0].length]}else{return[String.fromCharCode(value),2+mo[0].length]}}}} $B.prepare_string=function(p,token){var s=token.string,len=s.length,pos=0,string_modifier,_type="string",quote,inner,context={type:'str'} while(pos < len){if(s[pos]=='"' ||s[pos]=="'"){quote=s[pos] string_modifier=s.substr(0,pos) if(s.substr(pos,3)==quote.repeat(3)){_type="triple_string" inner=s.substring(pos+3,s.length-3)}else{inner=s.substring(pos+quote.length,len-quote.length)} break} pos++} var result={quote} var mods={r:'raw',f:'fstring',b:'bytes'} for(var mod of string_modifier){result[mods[mod]]=true} var raw=context.type=='str' && context.raw,string_start=pos+1,bytes=false,fstring=false,sm_length, end=null; if(string_modifier){switch(string_modifier){case 'r': raw=true break case 'u': break case 'b': bytes=true break case 'rb': case 'br': bytes=true raw=true break case 'f': fstring=true sm_length=1 break case 'fr': case 'rf': fstring=true sm_length=2 raw=true break} string_modifier=false} var escaped=false,zone='',end=0,src=inner if(bytes){var source=[]} while(end < src.length){if(escaped){if(src.charAt(end)=="a" && ! raw){zone=zone.substr(0,zone.length-1)+"\u0007"}else{zone+=src.charAt(end) if(raw && src.charAt(end)=='\\'){zone+='\\'}} escaped=false end++}else if(src.charAt(end)=="\\"){if(raw){if(end < src.length-1 && src.charAt(end+1)==quote){zone+='\\\\'+quote end+=2}else{zone+='\\\\' end++} escaped=true}else{if(src.charAt(end+1)=='\n'){ end+=2}else if(src.substr(end+1,2)=='N{'){ var end_lit=end+3,re=new RegExp("[-a-zA-Z0-9 ]+"),search=re.exec(src.substr(end_lit)) if(search===null){string_error(p,token,"(unicode error) "+ "malformed \\N character escape",pos)} var end_lit=end_lit+search[0].length if(src.charAt(end_lit)!="}"){string_error(p,token,"(unicode error) "+ "malformed \\N character escape")} var description=search[0].toUpperCase() if($B.unicodedb===undefined){var xhr=new XMLHttpRequest xhr.open("GET",$B.brython_path+"unicode.txt",false) xhr.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){$B.unicodedb=this.responseText}else{console.log("Warning - could not "+ "load unicode.txt")}}} xhr.send()} if($B.unicodedb !==undefined){var re=new RegExp("^([0-9A-F]+);"+ description+";.*$","m") search=re.exec($B.unicodedb) if(search===null){string_error(p,token,"(unicode error) "+ "unknown Unicode character name")} var cp=parseInt(search[1],16) zone+=String.fromCodePoint(cp) end=end_lit+1}else{end++}}else{var esc=test_escape(p,token,context,src,string_start,end) if(esc){if(esc[0]=='\\'){zone+='\\\\'}else if(esc[0]instanceof SurrogatePair){zone+=String.fromCodePoint(esc[0].value)}else{zone+=esc[0]} end+=esc[1]}else{if(end < src.length-1 && is_escaped[src.charAt(end+1)]===undefined){zone+='\\'} zone+='\\' escaped=true end++}}}}else if(src.charAt(end)=='\n' && _type !='triple_string'){ console.log(pos,end,src.substring(pos,end)) string_error(p,token,["EOL while scanning string literal"])}else{zone+=src.charAt(end) end++}} var $string=zone,string='' for(var i=0;i < $string.length;i++){var $car=$string.charAt(i) if($car==quote){if(raw ||(i==0 || $string.charAt(i-1)!='\\')){string+='\\'}else if(_type=="triple_string"){ var j=i-1 while($string.charAt(j)=='\\'){j--} if((i-j-1)% 2==0){string+='\\'}}} string+=$car} if(fstring){try{var re=new RegExp("\\\\"+quote,"g"),string_no_bs=string.replace(re,quote) var elts=$B.parse_fstring(string_no_bs)}catch(err){string_error(p,token,err.message)}} if(bytes){result.value='b'+quote+string+quote result.bytes=to_bytes(string)}else if(fstring){result.value=elts}else{result.value=quote+string+quote} context.raw=raw; return result}})(__BRYTHON__); ; (function($B){function test_num(num_lit){var len=num_lit.length,pos=0,char,elt=null,subtypes={b:'binary',o:'octal',x:'hexadecimal'},digits_re=/[_\d]/ function error(message){throw SyntaxError(message)} function check(elt){if(elt.value.length==0){var t=subtypes[elt.subtype]||'decimal' error("invalid "+t+" literal")}else if(elt.value[elt.value.length-1].match(/[\-+_]/)){var t=subtypes[elt.subtype]||'decimal' error("invalid "+t+" literal")}else{ elt.value=elt.value.replace(/_/g,"") elt.length=pos return elt}} while(pos < len){var char=num_lit[pos] if(char.match(digits_re)){if(elt===null){elt={value:char}}else{if(char=='_' && elt.value.match(/[._+\-]$/)){ error('consecutive _ at '+pos)}else if(char=='_' && elt.subtype=='float' && elt.value.match(/e$/i)){ error('syntax error')}else if(elt.subtype=='b' && !(char.match(/[01_]/))){error(`invalid digit '${char}' in binary literal`)}else if(elt.subtype=='o' && !(char.match(/[0-7_]/))){error(`invalid digit '${char}' in octal literal`)}else if(elt.subtype===undefined && elt.value.startsWith("0")&& !char.match(/[0_]/)){error("leading zeros in decimal integer literals are not"+ " permitted; use an 0o prefix for octal integers")} elt.value+=char} pos++}else if(char.match(/[oxb]/i)){if(elt.value=="0"){elt.subtype=char.toLowerCase() if(elt.subtype=="x"){digits_re=/[_\da-fA-F]/} elt.value='' pos++}else{error("invalid char "+char)}}else if(char=='.'){if(elt===null){error("invalid char in "+num_lit+" pos "+pos+": "+char)}else if(elt.subtype===undefined){elt.subtype="float" if(elt.value.endsWith('_')){error("invalid decimal literal")} elt.value=elt.value.replace(/_/g,"")+char pos++}else{return check(elt)}}else if(char.match(/e/i)){if(num_lit[pos+1]===undefined){error("nothing after e")}else if(elt && subtypes[elt.subtype]!==undefined){ error("syntax error")}else if(elt && elt.value.endsWith('_')){ error("syntax error")}else if(num_lit[pos+1].match(/[+\-0-9_]/)){if(elt && elt.value){if(elt.exp){elt.length=pos return elt} elt.subtype='float' elt.value+=char elt.exp=true pos++}else{error("unexpected e")}}else{return check(elt)}}else if(char.match(/[\+\-]/i)){if(elt===null){elt={value:char} pos++}else if(elt.value.search(/e$/i)>-1){elt.value+=char pos++}else{return check(elt)}}else if(char.match(/j/i)){if(elt &&(! elt.subtype ||elt.subtype=="float")){elt.imaginary=true check(elt) elt.length++ return elt}else{error("invalid syntax")}}else{break}} return check(elt)} $B.prepare_number=function(n){ n=n.replace(/_/g,"") if(n.startsWith('.')){if(n.endsWith("j")){return{type:'imaginary',value:$B.prepare_number(n.substr(0,n.length-1))}}else{return{type:'float',value:n+''}} pos=j}else if(n.startsWith('0')&& n !='0'){ var num=test_num(n),base if(num.imaginary){return{type:'imaginary',value:$B.prepare_number(num.value)}} if(num.subtype=='float'){return{type:num.subtype,value:num.value+''}} if(num.subtype===undefined){base=10}else{base={'b':2,'o':8,'x':16}[num.subtype]} if(base !==undefined){return{type:'int',value:[base,num.value]}}}else{var num=test_num(n) if(num.subtype=="float"){if(num.imaginary){return{ type:'imaginary',value:$B.prepare_number(num.value)}}else{return{ type:'float',value:num.value+''}}}else{if(num.imaginary){return{ type:'imaginary',value:$B.prepare_number(num.value)}}else{return{ type:'int',value:[10,num.value]}}}}}})(__BRYTHON__); ; (function($B){var _b_=$B.builtins,debug=0 var p={feature_version:$B.version_info[1]} $B.parser_constants={Store:new $B.ast.Store(),Load:new $B.ast.Load(),Del:new $B.ast.Del(),NULL:undefined,alias_ty:$B.ast.alias,keyword_ty:$B.ast.keyword,arguments_ty:$B.ast.arguments,expr_ty:$B.ast.expr,asdl_stmt_seq:Array,asdl_int_seq:Array,asdl_expr_seq:Array,asdl_keyword_seq:Array,asdl_identifier_seq:Array,asdl_pattern_seq:Array,asdl_type_param_seq:Array,AugOperator:$B.ast.AugAssign,IsNot:$B.ast.IsNot,Py_Ellipsis:_b_.Ellipsis,Py_False:false,Py_True:true,Py_None:_b_.None,PyExc_SyntaxError:_b_.SyntaxError,STAR_TARGETS:1,DEL_TARGETS:2,FOR_TARGETS:3,PyBytes_AS_STRING:(b)=> b} for(var op_type of $B.op_types){for(var key in op_type){var klass_name=op_type[key] $B.parser_constants[klass_name]=new $B.ast[klass_name]()}} var NULL=$B.parser_constants.NULL $B._PyAST={} for(var ast_class in $B.ast_classes){ var args=$B.ast_classes[ast_class] if(Array.isArray(args)){continue} args=args.replace(/\*/g,'').replace(/\?/g,'') var arg_names=args.split(',') $B._PyAST[ast_class]=(function(ast_name,ast_args){return function(){var _args=Array.from(arguments).slice(0,ast_args.length+1) var EXTRA=_args.pop() var ast_obj=new $B.ast[ast_name](..._args) set_position_from_EXTRA(ast_obj,EXTRA) return ast_obj}})(ast_class,arg_names)} function get_last_token(p){var last_token=$B.last(p.tokens) if(last_token.type=="ENDMARKER"){var src=$B.file_cache[p.filename] if(src){for(var token of $B.tokenizer(src)){if(token.type=="ENDMARKER"){break} if(token.type !="DEDENT"){last_token=token}}}else{last_token=undefined}} p.known_err_token=last_token} var helper_functions={CHECK:function(type,obj){if(Array.isArray(type)){var check for(var t of type){check=helper_functions.CHECK(t,obj) if(check){return check}} return undefined} if(obj instanceof type){return obj} return undefined},CHECK_VERSION:function(type,version,msg,node){return helper_functions.INVALID_VERSION_CHECK(p,version,msg,node)},CHECK_NULL_ALLOWED:function(type,obj){if(obj !==NULL){if(type instanceof Array){for(var t of type){if(obj instanceof t){return obj}} return}else{return obj instanceof type ? obj :undefined}} return obj},INVALID_VERSION_CHECK:function(p,version,msg,node){if(node==NULL){p.error_indicator=1; return NULL;} if(p.feature_version < version){p.error_indicator=1; return helper_functions.RAISE_SYNTAX_ERROR("%s only supported in Python 3.%i and greater",msg,version);} return node;},NEW_TYPE_COMMENT:function(p,x){return x},PyErr_Occurred:function(){return false},RAISE_ERROR_KNOWN_LOCATION:function(p,errtype,lineno,col_offset,end_lineno,end_col_offset,errmsg){var va=[errmsg] $B._PyPegen.raise_error_known_location(p,errtype,lineno,col_offset,end_lineno,end_col_offset,errmsg,va); return NULL;},RAISE_ERROR:function(p,errtype,msg){var extra_args=[] for(var i=1,len=arguments.length;i < len;i++){extra_args.push(arguments[i])} get_last_token(p) $B._PyPegen.raise_error(p,errtype,msg,...extra_args)},RAISE_SYNTAX_ERROR:function(p,msg){var extra_args=[] for(var i=1,len=arguments.length;i < len;i++){extra_args.push(arguments[i])} get_last_token(p) $B._PyPegen.raise_error(p,_b_.SyntaxError,msg,...extra_args)},RAISE_INDENTATION_ERROR:function(p,msg,arg){if(arg !==undefined){msg=_b_.str.__mod__(msg,arg)} var last_token=$B.last(p.tokens) if(last_token.type=="ENDMARKER"){var src=$B.file_cache[p.filename] if(src){for(var token of $B.tokenizer(src)){if(token.type=="ENDMARKER"){break} last_token=token}}} get_last_token(p) $B._PyPegen.raise_error(p,_b_.IndentationError,msg)},RAISE_SYNTAX_ERROR_KNOWN_LOCATION:function(p,a,err_msg,arg){if(arg !==undefined){err_msg=_b_.str.__mod__(err_msg,arg)} helper_functions.RAISE_ERROR_KNOWN_LOCATION(p,_b_.SyntaxError,a.lineno,a.col_offset,a.end_lineno,a.end_col_offset,err_msg)},RAISE_SYNTAX_ERROR_KNOWN_RANGE:function(p,a,b,msg){var extra_args=arguments[4] if(extra_args){msg=_b_.str.__mod__(msg,extra_args)} helper_functions.RAISE_ERROR_KNOWN_LOCATION(p,_b_.SyntaxError,a.lineno,a.col_offset,b.end_lineno,b.end_col_offset,msg,extra_args)},RAISE_SYNTAX_ERROR_INVALID_TARGET:function(p,type,e){return helper_functions._RAISE_SYNTAX_ERROR_INVALID_TARGET(p,type,e)},_RAISE_SYNTAX_ERROR_INVALID_TARGET(p,type,e){var invalid_target=$B.helper_functions.CHECK_NULL_ALLOWED($B.ast.expr,$B._PyPegen.get_invalid_target(e,type)); if(invalid_target !=NULL){var msg; if(type==$B.parser_constants.STAR_TARGETS || type==$B.parser_constants.FOR_TARGETS){msg="cannot assign to %s";}else{msg="cannot delete %s";} return helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION( p,invalid_target,msg,$B._PyPegen.get_expr_name(invalid_target) )} return NULL;},RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN:function(p,msg){return helper_functions.RAISE_SYNTAX_ERROR(p,msg)},RAISE_SYNTAX_ERROR_STARTING_FROM:function(p,a,msg,...args){var last=p.tokens[p.tokens.length-1] return helper_functions.RAISE_ERROR_KNOWN_LOCATION(p,_b_.SyntaxError,a.lineno,a.col_offset,last.end_lineno,last.end_col_offset-1,msg,...args)},asdl_seq_LEN:(t)=> t.length,asdl_seq_GET:(t,i)=> t[i]} $B.helper_functions=helper_functions function raise_error_known_location(type,filename,lineno,col_offset,end_lineno,end_col_offset,line,message){var exc=$B.EXC(type,message) exc.filename=filename exc.lineno=lineno exc.offset=col_offset+1 exc.end_lineno=end_lineno exc.end_offset=end_col_offset+1 exc.text=line exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]) exc.$frame_obj=$B.frame_obj throw exc} $B.raise_error_known_location=raise_error_known_location function make_error_known_token(type,filename,token,message){var exc=$B.EXC(type,message) exc.filename=filename exc.lineno=token.lineno exc.offset=token.col_offset+1 exc.end_lineno=token.end_lineno exc.end_offset=token.end_col_offset+1 exc.text=token.line exc.args[1]=$B.fast_tuple([filename,exc.lineno,exc.offset,exc.text,exc.end_lineno,exc.end_offset]) exc.$frame_obj=$B.frame_obj return exc} $B.make_error_known_token=make_error_known_token function set_position_from_EXTRA(ast_obj,EXTRA){for(var key in EXTRA){ast_obj[key]=EXTRA[key]}} var Parser=$B.Parser=function(src,filename,mode){ this._tokens=$B.tokenizer(src,filename,mode,this) this.pos=0 this.tok={} this.mark=0 this.fill=0 this.level=0 this.size=1 this.starting_lineno=0 this.starting_col_offset=0 this.last_stmt_location={} this.tokens=[] this.src=src this.filename=filename this.mode=mode this.memo={} this.arena={a_objects:[]} if(filename){p.filename=filename}} Parser.prototype.read_token=function(){while(true){var next=this._tokens[this.pos++] if(next){var value=next if(! value.parser_ignored){ if(value.$error_token){$B.raise_error_known_location(...value)}else if(value.$error_token_known_token){throw make_error_known_token(...value)} this.tokens[this.tokens.length]=value return value}}else{throw Error('tokenizer exhausted')}}}})(__BRYTHON__); ; (function($B){ var _b_=__BRYTHON__.builtins const Load=new $B.ast.Load() const NULL=undefined; const ENDMARKER=0,NAME=1,NUMBER=2,STRING=3 function strchr(s,char){return s.includes(char)} function strlen(s){return s.length} function strncmp(a,b){return a < b ?-1 :a > b ? 1 :0} function PyOS_strtol(s,end,base){return parseFloat(s)} function PyOS_strtoul(s,end,base){return parseFloat(s)} function PyOS_string_to_double(s,x,y){return parseFloat(s)} function PyFloat_FromDouble(x){return x} const NSTATISTICS=2000,memo_statistics={},TYPE_IGNORE='TYPE_IGNORE',ERRORTOKEN='ERRORTOKEN',NEWLINE=$B.py_tokens.NEWLINE,DEDENT=$B.py_tokens.DEDENT,Py_single_input='py_single_input',PyPARSE_ALLOW_INCOMPLETE_INPUT=0x0100 function PyUnicode_IS_ASCII(char){return char.codePointAt(0)< 128} function set_position_from_token(ast_obj,token){for(var attr of['lineno','col_offset','end_lineno','end_col_offset']){ast_obj[attr]=token[attr]}} $B._PyPegen.interactive_exit=function(p){if(p.errcode){(p.errcode)=E_EOF;} return NULL;} $B._PyPegen.byte_offset_to_character_offset_raw=function(str,col_offset){var len=str.length if(col_offset > len+1){col_offset=len+1;} var text=PyUnicode_DecodeUTF8(str,col_offset,"replace"); if(!text){return-1;} return text.length} $B._PyPegen.calculate_display_width=function(line,character_offset){var segment=line.substring(0,character_offset); if(!segment){return-1;} if(PyUnicode_IS_ASCII(segment)){return character_offset;} var width_fn=_PyImport_GetModuleAttrString("unicodedata","east_asian_width"); if(!width_fn){return-1;} var width=0; var len=segment.length for(let i=0;i < len;i++){var chr=segment.substring(i,i+1); if(!chr){Py_DECREF(segment); Py_DECREF(width_fn); return-1;} var width_specifier=PyObject_CallOneArg(width_fn,chr); if(!width_specifier){Py_DECREF(segment); Py_DECREF(width_fn); return-1;} if(width_specifier=="W" || width_specifier=="F"){width+=2;}else{ width+=1;}} return width;} $B._PyPegen.byte_offset_to_character_offset=function(line,col_offset){var str=line return _PyPegen_byte_offset_to_character_offset_raw(str,col_offset);} $B._PyPegen.insert_memo=function(p,mark,type,node){ var m={type,node,mark:p.mark,next:p.tokens[mark].memo} p.tokens[mark].memo=m; return 0;} $B._PyPegen.update_memo=function(p,mark,type,node){for(let m=p.tokens[mark].memo;m !=NULL;m=m.next){if(m.type==type){ m.node=node; m.mark=p.mark; return 0;}} return $B._PyPegen.insert_memo(p,mark,type,node);} function init_normalization(p){if(p.normalize){return 1;} p.normalize=_PyImport_GetModuleAttrString("unicodedata","normalize"); if(!p.normalize) {return 0;} return 1;} function growable_comment_array_init(arr,initial_size){ arr.items=new Array(initial_size*arr.items.length); arr.size=initial_size; arr.num_items=0; return arr.items !=NULL;} function growable_comment_array_add(arr,lineno,comment){return 1} function growable_comment_array_deallocate(arr){} function _get_keyword_or_name_type(p,new_token){return p.keywords[new_token.string]?? NAME} function initialize_token(p,parser_token,new_token,token_type){ parser_token.num_type=(token_type==NAME)? _get_keyword_or_name_type(p,new_token):token_type; if(parser_token.num_type==-1){console.log('bizarre',new_token) console.log('keywords',p.keywords) alert()} parser_token.metadata=NULL; if(new_token.metadata !=NULL){parser_token.metadata=new_token.metadata; new_token.metadata=NULL;} parser_token.level=new_token.level; parser_token.lineno=new_token.lineno; parser_token.col_offset=p.tok.lineno==p.starting_lineno ? p.starting_col_offset+new_token.col_offset :new_token.col_offset; parser_token.end_lineno=new_token.end_lineno; parser_token.end_col_offset=p.tok.lineno==p.starting_lineno ? p.starting_col_offset+new_token.end_col_offset :new_token.end_col_offset; p.arena.lineno=parser_token.lineno p.fill+=1; if(token_type==ERRORTOKEN && p.tok.done==E_DECODE){return _Pypegen_raise_decode_error(p);} return(token_type==ERRORTOKEN ? _Pypegen_tokenizer_error(p):0);} function _PyToken_Init(token){token.metadata=NULL;} function _PyTokenizer_Get(tok,new_token){var token=tok.next().value for(var key in token){new_token[key]=token[key]} return token.num_type} function get_next_token(p,new_token){var token=p.tokens[p.fill]?? p.read_token() for(var key in token){new_token[key]=token[key]} if(token.num_type==$B.py_tokens.ENDMARKER){ if(p.mode=='single'){var end_token=p.tokens[p.tokens.length-2] if(end_token.num_type !=$B.py_tokens.NEWLINE){var newline=$B.clone(end_token) newline.num_type=$B.py_tokens.NEWLINE p.tokens.splice(p.tokens.length-1,0,newline) token=newline}}} return token.num_type} $B._PyPegen.fill_token=function(p){var new_token={metadata:NULL} var type=get_next_token(p,new_token); while(type==TYPE_IGNORE){type=get_next_token(p,new_token);} if(p.start_rule==Py_single_input && type==ENDMARKER && p.parsing_started){type=NEWLINE; p.parsing_started=0; if(p.tok.indent && !(p.flags & PyPARSE_DONT_IMPLY_DEDENT)){p.tok.pendin=-p.tok.indent; p.tok.indent=0;}}else{p.parsing_started=1;} var t=p.tokens[p.fill] return initialize_token(p,t,new_token,type);} $B._PyPegen.clear_memo_statistics=function(){for(let i=0;i < NSTATISTICS;i++){memo_statistics[i]=0;}} $B._PyPegen.get_memo_statistics=function(){var ret=new Array(NSTATISTICS); if(ret==NULL){return NULL;} for(let i=0;i < NSTATISTICS;i++){var value=PyLong_FromLong(memo_statistics[i]); if(value==NULL){return NULL;} if(PyList_SetItem(ret,i,value)< 0){Py_DECREF(ret); return NULL;}} return ret;} $B._PyPegen.is_memoized=function(p,type,pres){if(p.mark==p.fill){if($B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return-1;}} var t=p.tokens[p.mark]; for(var m=t.memo;m !=NULL;m=m.next){if(m.type==type){ p.mark=m.mark; pres.value=m.node; return 1;}} return 0;} $B._PyPegen.lookahead_with_name=function(positive,func,p){var mark=p.mark; var res=func(p); p.mark=mark; return(res !=NULL)==positive;} $B._PyPegen.lookahead_with_string=function(positive,func,p,arg){var mark=p.mark; var res=func(p,arg); p.mark=mark; return(res !=NULL)==positive;} $B._PyPegen.lookahead_with_int=function(positive,func,p,arg){var mark=p.mark; var res=func(p,arg); p.mark=mark; return(res !=NULL)==positive;} $B._PyPegen.lookahead=function(positive,func,p){var mark=p.mark; var res=func(p); p.mark=mark; return(res !=NULL)==positive;} $B._PyPegen.expect_token=function(p,type){if(p.mark==p.fill){if($B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;}} var t=p.tokens[p.mark]; if(t.num_type !=type){return NULL;} p.mark+=1; return t;} $B._PyPegen.expect_forced_result=function(p,result,expected){if(p.error_indicator==1){return NULL;} if(result==NULL){RAISE_SYNTAX_ERROR("expected (%s)",expected); return NULL;} return result;} $B._PyPegen.expect_forced_token=function(p,type,expected){if(p.error_indicator==1){return NULL;} if(p.mark==p.fill){if($B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;}} var t=p.tokens[p.mark]; if(t.num_type !=type){$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,t,`expected '${expected}'`); return NULL;} p.mark+=1; return t;} $B._PyPegen.expect_soft_keyword=function(p,keyword){if(p.mark==p.fill){if($B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;}} var t=p.tokens[p.mark]; if(t.num_type !=NAME){return NULL;} const s=t.string if(!s){p.error_indicator=1; return NULL;} if(strcmp(s,keyword)!=0){return NULL;} return $B._PyPegen.name_token(p);} $B._PyPegen.get_last_nonnwhitespace_token=function(p){ var token=NULL; for(let m=p.mark-1;m >=0;m--){token=p.tokens[m]; if(token.num_type !=ENDMARKER &&(token.num_type < NEWLINE ||token.num_type > DEDENT)){break;}} return token;} $B._PyPegen.new_identifier=function(p,n){var id=n if(! PyUnicode_IS_ASCII(id)){var id2; if(!init_normalization(p)) {return error();} var form=PyUnicode_InternFromString("NFKC"); if(form==NULL) {return error();} var args={form,id}; id2=_PyObject_FastCall(p.normalize,args,2); if(!id2){return error()} if(!PyUnicode_Check(id2)){PyErr_Format(PyExc_TypeError,"unicodedata.normalize() must return a string, not "+ "%.200s",_PyType_Name(Py_TYPE(id2))); return error()} id=id2;} PyUnicode_InternInPlace(id); return id; function error(){p.error_indicator=1; return NULL;}} $B._PyPegen.name_from_token=function(p,t){if(t==NULL){return NULL;} var s=t.string if(!s){p.error_indicator=1; return NULL;} var res=new $B.ast.Name(s,Load) set_position_from_token(res,t) return res} $B._PyPegen.name_token=function(p){var t=$B._PyPegen.expect_token(p,NAME); return $B._PyPegen.name_from_token(p,t);} $B._PyPegen.string_token=function(p){return $B._PyPegen.expect_token(p,STRING);} $B._PyPegen.soft_keyword_token=function(p){var t=$B._PyPegen.expect_token(p,NAME); if(t==NULL){return NULL;} var the_token; var size; the_token=t.string; for(let keyword=p.soft_keywords;keyword !=NULL;keyword++){if(strncmp(keyword,the_token,size)==0){return $B._PyPegen.name_from_token(p,t);}} return NULL;} function prepared_number_value(prepared){switch(prepared.type){case 'float': return $B.fast_float(parseFloat(prepared.value)) case 'imaginary': return $B.make_complex(0,prepared_number_value(prepared.value)) case 'int': var res=parseInt(prepared.value[1],prepared.value[0]) if(! Number.isSafeInteger(res)){var base=prepared.value[0],num_str=prepared.value[1] switch(base){case 8: return $B.fast_long_int(BigInt('0x'+num_str)) case 10: return $B.fast_long_int(BigInt(num_str)) case 16: return $B.fast_long_int(BigInt('0x'+num_str))}} return res}} function parsenumber_raw(s){var prepared=$B.prepare_number(s) return prepared_number_value(prepared)} function parsenumber(s){var dup; var end; var res=NULL; if(strchr(s,'_')==NULL){return parsenumber_raw(s);} dup=s.replace(/_/g,'') res=parsenumber_raw(dup); return res;} $B._PyPegen.number_token=function(p){var t=$B._PyPegen.expect_token(p,NUMBER); if(t==NULL){return NULL;} var num_raw=t.string if(num_raw==NULL){p.error_indicator=1; return NULL;} if(p.feature_version < 6 && strchr(num_raw,'_')!=NULL){p.error_indicator=1; return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "+ "in Python 3.6 and greater");} var c=parsenumber(num_raw); if(c==NULL){p.error_indicator=1; var tstate=_PyThreadState_GET(); if(tstate.current_exception !=NULL && Py_TYPE(tstate.current_exception)==PyExc_ValueError ){var exc=PyErr_GetRaisedException(); RAISE_ERROR_KNOWN_LOCATION( p,PyExc_SyntaxError,t.lineno,-1 ,t.end_lineno,-1 ,"%S - Consider hexadecimal for huge integer literals "+ "to avoid decimal conversion limits.",exc);} return NULL;} var res=new $B.ast.Constant(c,NULL); set_position_from_token(res,t) return res} function bad_single_statement(p){var cur=p.tok.cur; var c=cur; var pos=0 for(;;){while(c==' ' ||c=='\t' ||c=='\n' ||c=='\f'){c=cur[pos++]} if(!c){return 0;} if(c !='#'){return 1;} while(c && c !='\n'){c=cur[pos++]}}} function compute_parser_flags(flags){var parser_flags=0; if(!flags){return 0;} if(flags.cf_flags & PyCF_DONT_IMPLY_DEDENT){parser_flags |=PyPARSE_DONT_IMPLY_DEDENT;} if(flags.cf_flags & PyCF_IGNORE_COOKIE){parser_flags |=PyPARSE_IGNORE_COOKIE;} if(flags.cf_flags & CO_FUTURE_BARRY_AS_BDFL){parser_flags |=PyPARSE_BARRY_AS_BDFL;} if(flags.cf_flags & PyCF_TYPE_COMMENTS){parser_flags |=PyPARSE_TYPE_COMMENTS;} if((flags.cf_flags & PyCF_ONLY_AST)&& flags.cf_feature_version < 7){parser_flags |=PyPARSE_ASYNC_HACKS;} if(flags.cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT){parser_flags |=PyPARSE_ALLOW_INCOMPLETE_INPUT;} return parser_flags;} $B._PyPegen.Parser_New=function(tok,start_rule,flags,feature_version,errcode,source,arena){var p={} if(p==NULL){return PyErr_NoMemory();} tok.type_comments=(flags & PyPARSE_TYPE_COMMENTS)> 0; tok.async_hacks=(flags & PyPARSE_ASYNC_HACKS)> 0; p.tok=tok; p.keywords=NULL; p.n_keyword_lists=-1; p.soft_keywords=NULL; p.tokens=[] if(!p.tokens){PyMem_Free(p); return PyErr_NoMemory();} p.tokens[0]=PyMem_Calloc(1,sizeof(Token)); p.mark=0; p.fill=0; p.size=1; p.errcode=errcode; p.arena=arena; p.start_rule=start_rule; p.parsing_started=0; p.normalize=NULL; p.error_indicator=0; p.starting_lineno=0; p.starting_col_offset=0; p.flags=flags; p.feature_version=feature_version; p.known_err_token=NULL; p.level=0; p.call_invalid_rules=0; p.debug=_Py_GetConfig().parser_debug; return p;} $B._PyPegen.Parser_Free=function(p){} function reset_parser_state_for_error_pass(p){for(let i=0;i < p.fill;i++){p.tokens[i].memo=NULL;} p.mark=0; p.call_invalid_rules=1;} function _is_end_of_source(p){var err=p.tok.done; return p.tokens[p.tokens.length-1].type==$B.py_tokens.ENDMARKER} function inside_fstring(p){var res=false for(var token of p.tokens){if(token.type==$B.py_tokens.FSTRING_START){res=true}else if(token.type==$B.py_tokens.FSTRING_END){res=false}} return res} $B._PyPegen.tokenize_full_source_to_check_for_errors=function(p){var last_token=p.tokens[p.fill-1] $B.tokenizer(p.src,p.filename,p.mode,p) p.tokens=p._tokens if(p.braces.length > 0){var brace=$B.last(p.braces),err_lineno,msg if('([{'.includes(brace.char)){err_lineno=brace.line_num}else{if(p.braces.length > 1){err_lineno=p.braces[p.braces.length-2].line_num}else{err_lineno=brace.line_num}} if(p.tokens.length==0 ||$B.last(p.tokens).lineno >=err_lineno){if('([{'.includes(brace.char)){msg=`'${brace.char}' was never closed`}else if(p.braces.length > 1){var closing=brace.char,opening=p.braces[p.braces.length-2].char if(inside_fstring(p)){msg=`f-string: unmatched '${closing}'`}else{msg=`closing parenthesis '${closing}' does not match `+ `opening parenthesis '${opening}'`}}else{msg=`unmatched '${brace.char}'`} $B.raise_error_known_location(_b_.SyntaxError,p.filename,brace.line_num,brace.pos-brace.line_start,brace.line_num,brace.pos-brace.line_start+1,brace.line,msg)}}} $B._PyPegen.set_syntax_error=function(p,last_token){ if(p.fill==0){$B.helper_functions.RAISE_SYNTAX_ERROR(p,"error at start before reading any input");} $B._PyPegen.tokenize_full_source_to_check_for_errors(p); if(last_token.num_type==ERRORTOKEN && p.tok.done==E_EOF){if(p.tok.level){raise_unclosed_parentheses_error(p);}else{ $B.helper_functions.RAISE_SYNTAX_ERROR(p,"unexpected EOF while parsing");} return} if(last_token.num_type==INDENT ||last_token.num_type==DEDENT){$B.helper_functions.RAISE_INDENTATION_ERROR(p,last_token.num_type==INDENT ? "unexpected indent" :"unexpected unindent"); return} $B._PyPegen.tokenize_full_source_to_check_for_errors(p); return $B.make_error_known_token(_b_.SyntaxError,p.filename,last_token,"invalid syntax");} $B._PyPegen.set_syntax_error_metadata=function(p,exc){if(! exc ||! $B.is_exc(exc,[_b_.SyntaxError])){return} var source=NULL; if(p.src !=NULL){source=p.src;} if(!source && p.tok.fp_interactive && p.tok.interactive_src_start){source=p.tok.interactive_src_start;} var the_source=NULL; if(source){the_source=source} if(!the_source){the_source=_b_.None;} var metadata=[exc.lineno,exc.offset,the_source ] if(!metadata){return;} exc._metadata=metadata;} $B._PyPegen.run_parser=function(p){var res=$B._PyPegen.parse(p); $B.python_keywords=p.keywords if(res==NULL){if((p.flags & $B.PyCF_ALLOW_INCOMPLETE_INPUT)&& _is_end_of_source(p)){return $B.helper_functions.RAISE_ERROR(p,_b_._IncompleteInputError,"incomplete input");} var last_token=p.tokens[p.fill-1]; reset_parser_state_for_error_pass(p); try{$B._PyPegen.parse(p);}catch(err){last_token=p.tokens[p.fill-1] $B._PyPegen.tokenize_full_source_to_check_for_errors(p) throw err} var exc=$B._PyPegen.set_syntax_error(p,last_token); if($B.is_exc(exc,[_b_.SyntaxError])){$B._PyPegen.set_syntax_error_metadata(p,exc);} throw exc} if(p.start_rule==Py_single_input && bad_single_statement(p)){p.tok.done=E_BADSINGLE; return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");} return res;} $B._PyPegen.run_parser_from_file_pointer=function(fp,start_rule,filename_ob,enc,ps1,ps2,flags,errcode,arena){var tok=_PyTokenizer_FromFile(fp,enc,ps1,ps2); if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob); return NULL;} return NULL;} if(!tok.fp ||ps1 !=NULL ||ps2 !=NULL || PyUnicode_CompareWithASCIIString(filename_ob,"")==0){tok.fp_interactive=1;} tok.filename=Py_NewRef(filename_ob); var result=NULL; var parser_flags=compute_parser_flags(flags); var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,PY_MINOR_VERSION,errcode,NULL,arena); if(p==NULL){return error()} result=_PyPegen_run_parser(p); _PyPegen_Parser_Free(p); function error(){_PyTokenizer_Free(tok); return result;}} $B._PyPegen.run_parser_from_string=function(str,start_rule,filename_ob,flags,arena){var exec_input=start_rule==Py_file_input; var tok; if(flags !=NULL && flags.cf_flags & PyCF_IGNORE_COOKIE){tok=_PyTokenizer_FromUTF8(str,exec_input,0);}else{ tok=_PyTokenizer_FromString(str,exec_input,0);} if(tok==NULL){if(PyErr_Occurred()){_PyPegen_raise_tokenizer_init_error(filename_ob);} return NULL;} tok.filename=Py_NewRef(filename_ob); var result=NULL; var parser_flags=compute_parser_flags(flags); var feature_version=flags &&(flags.cf_flags & PyCF_ONLY_AST)? flags.cf_feature_version :PY_MINOR_VERSION; var p=$B._PyPegen.Parser_New(tok,start_rule,parser_flags,feature_version,NULL,str,arena); if(p==NULL){return error()} result=_PyPegen_run_parser(p); _PyPegen_Parser_Free(p); function error(){ return result;}} $B.PyPegen={first_item:function(a,type){return a[0]},last_item:function(a,ptype){return a[a.length-1]}}})(__BRYTHON__); ; function fprintf(dest,format){var args=Array.from(arguments).slice(2) for(var arg of args){format=format.replace(/%\*?[a-z]/,arg)} return format} const stderr=null function D(x){console.log(x)} function UNUSED(){} function strcmp(x,y){return x==y ? 0 :x < y ?-1 :1} const MAXSTACK=6000,NULL=undefined function NEW_TYPE_COMMENT(){} var $B=__BRYTHON__ const Store=new $B.ast.Store(),Load=new $B.ast.Load const EXTRA={} const ENDMARKER=0,NAME=1,NUMBER=2,STRING=3,NEWLINE=4,INDENT=5,DEDENT=6,LPAR=7,RPAR=8,LSQB=9,RSQB=10,COLON=11,COMMA=12,SEMI=13,PLUS=14,MINUS=15,STAR=16,SLASH=17,VBAR=18,AMPER=19,LESS=20,GREATER=21,EQUAL=22,DOT=23,PERCENT=24,LBRACE=25,RBRACE=26,EQEQUAL=27,NOTEQUAL=28,LESSEQUAL=29,GREATEREQUAL=30,TILDE=31,CIRCUMFLEX=32,LEFTSHIFT=33,RIGHTSHIFT=34,DOUBLESTAR=35,PLUSEQUAL=36,MINEQUAL=37,STAREQUAL=38,SLASHEQUAL=39,PERCENTEQUAL=40,AMPEREQUAL=41,VBAREQUAL=42,CIRCUMFLEXEQUAL=43,LEFTSHIFTEQUAL=44,RIGHTSHIFTEQUAL=45,DOUBLESTAREQUAL=46,DOUBLESLASH=47,DOUBLESLASHEQUAL=48,AT=49,ATEQUAL=50,RARROW=51,ELLIPSIS=52,COLONEQUAL=53,EXCLAMATION=54,OP=55,TYPE_IGNORE=56,TYPE_COMMENT=57,SOFT_KEYWORD=58,FSTRING_START=59,FSTRING_MIDDLE=60,FSTRING_END=61,TSTRING_START=62,TSTRING_MIDDLE=63,TSTRING_END=64,COMMENT=65,NL=66,ERRORTOKEN=67,ENCODING=68 const n_keyword_lists=9; const _reserved_keywords={if:682,as:680,in:695,or:588,is:596,del:625,def:699,for:694,try:656,and:589,not:703,from:633,pass:526,with:647,elif:687,else:686,None:623,True:622,raise:525,yield:587,break:527,async:698,class:701,while:689,False:624,await:597,return:522,import:634,assert:532,global:529,except:677,lambda:621,finally:673,continue:528,nonlocal:530,}; const reserved_keywords=Object.create(null) for(var item of Object.entries(_reserved_keywords)){reserved_keywords[item[0]]=item[1]} const soft_keywords=["_","case","match","type",NULL,]; const file_type=1000,interactive_type=1001,eval_type=1002,func_type_type=1003,statements_type=1004,statement_type=1005,single_compound_stmt_type=1006,statement_newline_type=1007,simple_stmts_type=1008,simple_stmt_type=1009,compound_stmt_type=1010,assignment_type=1011,annotated_rhs_type=1012,augassign_type=1013,return_stmt_type=1014,raise_stmt_type=1015,pass_stmt_type=1016,break_stmt_type=1017,continue_stmt_type=1018,global_stmt_type=1019,nonlocal_stmt_type=1020,del_stmt_type=1021,yield_stmt_type=1022,assert_stmt_type=1023,import_stmt_type=1024,import_name_type=1025,import_from_type=1026,import_from_targets_type=1027,import_from_as_names_type=1028,import_from_as_name_type=1029,dotted_as_names_type=1030,dotted_as_name_type=1031,dotted_name_type=1032,block_type=1033,decorators_type=1034,class_def_type=1035,class_def_raw_type=1036,function_def_type=1037,function_def_raw_type=1038,params_type=1039,parameters_type=1040,slash_no_default_type=1041,slash_with_default_type=1042,star_etc_type=1043,kwds_type=1044,param_no_default_type=1045,param_no_default_star_annotation_type=1046,param_with_default_type=1047,param_maybe_default_type=1048,param_type=1049,param_star_annotation_type=1050,annotation_type=1051,star_annotation_type=1052,default_type=1053,if_stmt_type=1054,elif_stmt_type=1055,else_block_type=1056,while_stmt_type=1057,for_stmt_type=1058,with_stmt_type=1059,with_item_type=1060,try_stmt_type=1061,except_block_type=1062,except_star_block_type=1063,finally_block_type=1064,match_stmt_type=1065,subject_expr_type=1066,case_block_type=1067,guard_type=1068,patterns_type=1069,pattern_type=1070,as_pattern_type=1071,or_pattern_type=1072,closed_pattern_type=1073,literal_pattern_type=1074,literal_expr_type=1075,complex_number_type=1076,signed_number_type=1077,signed_real_number_type=1078,real_number_type=1079,imaginary_number_type=1080,capture_pattern_type=1081,pattern_capture_target_type=1082,wildcard_pattern_type=1083,value_pattern_type=1084,attr_type=1085,name_or_attr_type=1086,group_pattern_type=1087,sequence_pattern_type=1088,open_sequence_pattern_type=1089,maybe_sequence_pattern_type=1090,maybe_star_pattern_type=1091,star_pattern_type=1092,mapping_pattern_type=1093,items_pattern_type=1094,key_value_pattern_type=1095,double_star_pattern_type=1096,class_pattern_type=1097,positional_patterns_type=1098,keyword_patterns_type=1099,keyword_pattern_type=1100,type_alias_type=1101,type_params_type=1102,type_param_seq_type=1103,type_param_type=1104,type_param_bound_type=1105,type_param_default_type=1106,type_param_starred_default_type=1107,expressions_type=1108,expression_type=1109,yield_expr_type=1110,star_expressions_type=1111,star_expression_type=1112,star_named_expressions_type=1113,star_named_expression_type=1114,assignment_expression_type=1115,named_expression_type=1116,disjunction_type=1117,conjunction_type=1118,inversion_type=1119,comparison_type=1120,compare_op_bitwise_or_pair_type=1121,eq_bitwise_or_type=1122,noteq_bitwise_or_type=1123,lte_bitwise_or_type=1124,lt_bitwise_or_type=1125,gte_bitwise_or_type=1126,gt_bitwise_or_type=1127,notin_bitwise_or_type=1128,in_bitwise_or_type=1129,isnot_bitwise_or_type=1130,is_bitwise_or_type=1131,bitwise_or_type=1132,bitwise_xor_type=1133,bitwise_and_type=1134,shift_expr_type=1135,sum_type=1136,term_type=1137,factor_type=1138,power_type=1139,await_primary_type=1140,primary_type=1141,slices_type=1142,slice_type=1143,atom_type=1144,group_type=1145,lambdef_type=1146,lambda_params_type=1147,lambda_parameters_type=1148,lambda_slash_no_default_type=1149,lambda_slash_with_default_type=1150,lambda_star_etc_type=1151,lambda_kwds_type=1152,lambda_param_no_default_type=1153,lambda_param_with_default_type=1154,lambda_param_maybe_default_type=1155,lambda_param_type=1156,fstring_middle_type=1157,fstring_replacement_field_type=1158,fstring_conversion_type=1159,fstring_full_format_spec_type=1160,fstring_format_spec_type=1161,fstring_type=1162,tstring_format_spec_replacement_field_type=1163,tstring_format_spec_type=1164,tstring_full_format_spec_type=1165,tstring_replacement_field_type=1166,tstring_middle_type=1167,tstring_type=1168,string_type=1169,strings_type=1170,list_type=1171,tuple_type=1172,set_type=1173,dict_type=1174,double_starred_kvpairs_type=1175,double_starred_kvpair_type=1176,kvpair_type=1177,for_if_clauses_type=1178,for_if_clause_type=1179,listcomp_type=1180,setcomp_type=1181,genexp_type=1182,dictcomp_type=1183,arguments_type=1184,args_type=1185,kwargs_type=1186,starred_expression_type=1187,kwarg_or_starred_type=1188,kwarg_or_double_starred_type=1189,star_targets_type=1190,star_targets_list_seq_type=1191,star_targets_tuple_seq_type=1192,star_target_type=1193,target_with_star_atom_type=1194,star_atom_type=1195,single_target_type=1196,single_subscript_attribute_target_type=1197,t_primary_type=1198,t_lookahead_type=1199,del_targets_type=1200,del_target_type=1201,del_t_atom_type=1202,type_expressions_type=1203,func_type_comment_type=1204,invalid_arguments_type=1205,invalid_kwarg_type=1206,expression_without_invalid_type=1207,invalid_legacy_expression_type=1208,invalid_type_param_type=1209,invalid_expression_type=1210,invalid_named_expression_type=1211,invalid_assignment_type=1212,invalid_ann_assign_target_type=1213,invalid_del_stmt_type=1214,invalid_block_type=1215,invalid_comprehension_type=1216,invalid_dict_comprehension_type=1217,invalid_parameters_type=1218,invalid_default_type=1219,invalid_star_etc_type=1220,invalid_kwds_type=1221,invalid_parameters_helper_type=1222,invalid_lambda_parameters_type=1223,invalid_lambda_parameters_helper_type=1224,invalid_lambda_star_etc_type=1225,invalid_lambda_kwds_type=1226,invalid_double_type_comments_type=1227,invalid_with_item_type=1228,invalid_for_if_clause_type=1229,invalid_for_target_type=1230,invalid_group_type=1231,invalid_import_type=1232,invalid_dotted_as_name_type=1233,invalid_import_from_as_name_type=1234,invalid_import_from_targets_type=1235,invalid_with_stmt_type=1236,invalid_with_stmt_indent_type=1237,invalid_try_stmt_type=1238,invalid_except_stmt_type=1239,invalid_except_star_stmt_type=1240,invalid_finally_stmt_type=1241,invalid_except_stmt_indent_type=1242,invalid_except_star_stmt_indent_type=1243,invalid_match_stmt_type=1244,invalid_case_block_type=1245,invalid_as_pattern_type=1246,invalid_class_pattern_type=1247,invalid_class_argument_pattern_type=1248,invalid_if_stmt_type=1249,invalid_elif_stmt_type=1250,invalid_else_stmt_type=1251,invalid_while_stmt_type=1252,invalid_for_stmt_type=1253,invalid_def_raw_type=1254,invalid_class_def_raw_type=1255,invalid_double_starred_kvpairs_type=1256,invalid_kvpair_type=1257,invalid_starred_expression_unpacking_type=1258,invalid_starred_expression_type=1259,invalid_fstring_replacement_field_type=1260,invalid_fstring_conversion_character_type=1261,invalid_tstring_replacement_field_type=1262,invalid_tstring_conversion_character_type=1263,invalid_string_tstring_concat_type=1264,invalid_arithmetic_type=1265,invalid_factor_type=1266,invalid_type_params_type=1267,_loop0_1_type=1268,_loop0_2_type=1269,_loop1_3_type=1270,_loop0_5_type=1271,_gather_4_type=1272,_tmp_6_type=1273,_tmp_7_type=1274,_tmp_8_type=1275,_tmp_9_type=1276,_tmp_10_type=1277,_tmp_11_type=1278,_tmp_12_type=1279,_tmp_13_type=1280,_loop1_14_type=1281,_tmp_15_type=1282,_loop0_17_type=1283,_gather_16_type=1284,_loop0_19_type=1285,_gather_18_type=1286,_tmp_20_type=1287,_tmp_21_type=1288,_loop0_22_type=1289,_loop1_23_type=1290,_loop0_25_type=1291,_gather_24_type=1292,_tmp_26_type=1293,_loop0_28_type=1294,_gather_27_type=1295,_tmp_29_type=1296,_loop1_30_type=1297,_tmp_31_type=1298,_tmp_32_type=1299,_tmp_33_type=1300,_loop0_34_type=1301,_loop0_35_type=1302,_loop0_36_type=1303,_loop1_37_type=1304,_loop0_38_type=1305,_loop1_39_type=1306,_loop1_40_type=1307,_loop1_41_type=1308,_loop0_42_type=1309,_loop1_43_type=1310,_loop0_44_type=1311,_loop1_45_type=1312,_loop0_46_type=1313,_loop0_47_type=1314,_loop1_48_type=1315,_loop0_50_type=1316,_gather_49_type=1317,_loop0_52_type=1318,_gather_51_type=1319,_loop0_54_type=1320,_gather_53_type=1321,_loop0_56_type=1322,_gather_55_type=1323,_tmp_57_type=1324,_loop1_58_type=1325,_loop1_59_type=1326,_loop1_60_type=1327,_loop0_62_type=1328,_gather_61_type=1329,_tmp_63_type=1330,_tmp_64_type=1331,_tmp_65_type=1332,_tmp_66_type=1333,_tmp_67_type=1334,_loop0_69_type=1335,_gather_68_type=1336,_loop0_71_type=1337,_gather_70_type=1338,_tmp_72_type=1339,_loop0_74_type=1340,_gather_73_type=1341,_loop0_76_type=1342,_gather_75_type=1343,_loop0_78_type=1344,_gather_77_type=1345,_loop1_79_type=1346,_loop1_80_type=1347,_loop0_82_type=1348,_gather_81_type=1349,_loop1_83_type=1350,_loop1_84_type=1351,_loop1_85_type=1352,_tmp_86_type=1353,_loop0_88_type=1354,_gather_87_type=1355,_tmp_89_type=1356,_tmp_90_type=1357,_tmp_91_type=1358,_tmp_92_type=1359,_tmp_93_type=1360,_tmp_94_type=1361,_loop0_95_type=1362,_loop0_96_type=1363,_loop0_97_type=1364,_loop1_98_type=1365,_loop0_99_type=1366,_loop1_100_type=1367,_loop1_101_type=1368,_loop1_102_type=1369,_loop0_103_type=1370,_loop1_104_type=1371,_loop0_105_type=1372,_loop1_106_type=1373,_loop0_107_type=1374,_loop1_108_type=1375,_loop0_109_type=1376,_loop0_110_type=1377,_loop0_111_type=1378,_loop0_112_type=1379,_loop1_113_type=1380,_loop1_114_type=1381,_tmp_115_type=1382,_loop0_117_type=1383,_gather_116_type=1384,_loop1_118_type=1385,_loop0_119_type=1386,_loop0_120_type=1387,_tmp_121_type=1388,_loop0_123_type=1389,_gather_122_type=1390,_tmp_124_type=1391,_loop0_126_type=1392,_gather_125_type=1393,_loop0_128_type=1394,_gather_127_type=1395,_loop0_130_type=1396,_gather_129_type=1397,_loop0_132_type=1398,_gather_131_type=1399,_loop0_133_type=1400,_loop0_135_type=1401,_gather_134_type=1402,_loop1_136_type=1403,_tmp_137_type=1404,_loop0_139_type=1405,_gather_138_type=1406,_loop0_141_type=1407,_gather_140_type=1408,_loop0_143_type=1409,_gather_142_type=1410,_loop0_145_type=1411,_gather_144_type=1412,_loop0_147_type=1413,_gather_146_type=1414,_tmp_148_type=1415,_tmp_149_type=1416,_loop0_151_type=1417,_gather_150_type=1418,_tmp_152_type=1419,_tmp_153_type=1420,_tmp_154_type=1421,_tmp_155_type=1422,_tmp_156_type=1423,_loop1_157_type=1424,_tmp_158_type=1425,_tmp_159_type=1426,_tmp_160_type=1427,_tmp_161_type=1428,_tmp_162_type=1429,_tmp_163_type=1430,_loop0_164_type=1431,_loop0_165_type=1432,_loop0_166_type=1433,_tmp_167_type=1434,_tmp_168_type=1435,_tmp_169_type=1436,_tmp_170_type=1437,_loop0_171_type=1438,_loop0_172_type=1439,_loop0_173_type=1440,_loop1_174_type=1441,_tmp_175_type=1442,_loop0_176_type=1443,_tmp_177_type=1444,_loop0_178_type=1445,_loop1_179_type=1446,_tmp_180_type=1447,_tmp_181_type=1448,_tmp_182_type=1449,_loop0_183_type=1450,_tmp_184_type=1451,_tmp_185_type=1452,_loop1_186_type=1453,_tmp_187_type=1454,_loop0_188_type=1455,_loop0_189_type=1456,_loop0_190_type=1457,_loop0_192_type=1458,_gather_191_type=1459,_tmp_193_type=1460,_loop0_194_type=1461,_tmp_195_type=1462,_loop0_196_type=1463,_loop1_197_type=1464,_loop1_198_type=1465,_tmp_199_type=1466,_tmp_200_type=1467,_loop0_201_type=1468,_tmp_202_type=1469,_tmp_203_type=1470,_tmp_204_type=1471,_tmp_205_type=1472,_loop0_207_type=1473,_gather_206_type=1474,_tmp_208_type=1475,_tmp_209_type=1476,_loop0_211_type=1477,_gather_210_type=1478,_loop0_213_type=1479,_gather_212_type=1480,_loop0_215_type=1481,_gather_214_type=1482,_loop0_217_type=1483,_gather_216_type=1484,_tmp_218_type=1485,_loop0_219_type=1486,_loop1_220_type=1487,_tmp_221_type=1488,_loop0_222_type=1489,_loop1_223_type=1490,_tmp_224_type=1491,_tmp_225_type=1492,_tmp_226_type=1493,_tmp_227_type=1494,_tmp_228_type=1495,_tmp_229_type=1496,_tmp_230_type=1497,_tmp_231_type=1498,_tmp_232_type=1499,_tmp_233_type=1500,_tmp_234_type=1501,_loop0_236_type=1502,_gather_235_type=1503,_tmp_237_type=1504,_tmp_238_type=1505,_tmp_239_type=1506,_tmp_240_type=1507,_tmp_241_type=1508,_tmp_242_type=1509,_tmp_243_type=1510,_loop0_244_type=1511,_tmp_245_type=1512,_tmp_246_type=1513,_tmp_247_type=1514,_tmp_248_type=1515,_tmp_249_type=1516,_tmp_250_type=1517,_tmp_251_type=1518,_loop0_252_type=1519,_tmp_253_type=1520,_tmp_254_type=1521,_loop1_255_type=1522,_loop1_256_type=1523,_tmp_257_type=1524,_tmp_258_type=1525,_tmp_259_type=1526,_tmp_260_type=1527,_tmp_261_type=1528,_tmp_262_type=1529,_tmp_263_type=1530,_tmp_264_type=1531,_tmp_265_type=1532,_tmp_266_type=1533,_tmp_267_type=1534,_tmp_268_type=1535,_tmp_269_type=1536,_tmp_270_type=1537,_tmp_271_type=1538,_tmp_272_type=1539,_tmp_273_type=1540,_tmp_274_type=1541,_tmp_275_type=1542,_tmp_276_type=1543,_tmp_277_type=1544,_tmp_278_type=1545,_tmp_279_type=1546,_tmp_280_type=1547,_tmp_281_type=1548,_loop0_282_type=1549,_tmp_283_type=1550,_tmp_284_type=1551,_tmp_285_type=1552,_tmp_286_type=1553,_tmp_287_type=1554,_tmp_288_type=1555,_tmp_289_type=1556,_tmp_290_type=1557,_tmp_291_type=1558,_loop0_293_type=1559,_gather_292_type=1560,_tmp_294_type=1561,_tmp_295_type=1562,_tmp_296_type=1563,_tmp_297_type=1564,_tmp_298_type=1565,_tmp_299_type=1566,_tmp_300_type=1567 function file_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var endmarker_var; if( (a=statements_rule(p),!p.error_indicator) && (endmarker_var=$B._PyPegen.expect_token(p,ENDMARKER)) ) {_res=$B._PyPegen.make_module(p,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function interactive_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=statement_newline_rule(p)) ) {_res=new $B._PyAST.Interactive(a,p.arena); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function eval_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _loop0_1_var; var a; var endmarker_var; if( (a=expressions_rule(p)) && (_loop0_1_var=_loop0_1_rule(p)) && (endmarker_var=$B._PyPegen.expect_token(p,ENDMARKER)) ) {_res=new $B._PyAST.Expression(a,p.arena); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function func_type_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var _loop0_2_var; var a; var b; var endmarker_var; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=type_expressions_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_literal_2=$B._PyPegen.expect_token(p,51)) && (b=expression_rule(p)) && (_loop0_2_var=_loop0_2_rule(p)) && (endmarker_var=$B._PyPegen.expect_token(p,ENDMARKER)) ) {_res=new $B._PyAST.FunctionType(a,b,p.arena); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function statements_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=_loop1_3_rule(p)) ) {_res=$B._PyPegen.seq_flatten(p,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function statement_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=compound_stmt_rule(p)) ) {_res=$B._PyPegen.register_stmts(p,$B._PyPegen.singleton_seq(p,a )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=simple_stmts_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function single_compound_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=compound_stmt_rule(p)) ) {_res=$B._PyPegen.register_stmts(p,$B._PyPegen.singleton_seq(p,a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function statement_newline_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var newline_var; if( (a=single_compound_stmt_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var simple_stmts_var; if( (simple_stmts_var=simple_stmts_rule(p)) ) {_res=simple_stmts_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.singleton_seq(p,$B.helper_functions.CHECK($B.ast.stmt,new $B._PyAST.Pass(EXTRA ))); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var endmarker_var; if( (endmarker_var=$B._PyPegen.expect_token(p,ENDMARKER)) ) {_res=$B._PyPegen.interactive_exit(p); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function simple_stmts_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var newline_var; if( (a=simple_stmt_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,13) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var newline_var; if( (a=_gather_4_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,13),!p.error_indicator) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function simple_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,simple_stmt_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var assignment_var; if( (assignment_var=assignment_rule(p)) ) {_res=assignment_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var type_alias_var; if( $B._PyPegen.lookahead_with_string(1,$B._PyPegen.expect_soft_keyword,p,"type") && (type_alias_var=type_alias_rule(p)) ) {_res=type_alias_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var e; if( (e=star_expressions_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Expr(e,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var return_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,522) && (return_stmt_var=return_stmt_rule(p)) ) {_res=return_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var import_stmt_var; if( $B._PyPegen.lookahead(1,_tmp_6_rule,p) && (import_stmt_var=import_stmt_rule(p)) ) {_res=import_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var raise_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,525) && (raise_stmt_var=raise_stmt_rule(p)) ) {_res=raise_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var pass_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,526) && (pass_stmt_var=pass_stmt_rule(p)) ) {_res=pass_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var del_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,625) && (del_stmt_var=del_stmt_rule(p)) ) {_res=del_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var yield_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,587) && (yield_stmt_var=yield_stmt_rule(p)) ) {_res=yield_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var assert_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,532) && (assert_stmt_var=assert_stmt_rule(p)) ) {_res=assert_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var break_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,527) && (break_stmt_var=break_stmt_rule(p)) ) {_res=break_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var continue_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,528) && (continue_stmt_var=continue_stmt_rule(p)) ) {_res=continue_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var global_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,529) && (global_stmt_var=global_stmt_rule(p)) ) {_res=global_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var nonlocal_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,530) && (nonlocal_stmt_var=nonlocal_stmt_rule(p)) ) {_res=nonlocal_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,simple_stmt_type,_res); return _res;} function compound_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var function_def_var; if( $B._PyPegen.lookahead(1,_tmp_7_rule,p) && (function_def_var=function_def_rule(p)) ) {_res=function_def_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var if_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,682) && (if_stmt_var=if_stmt_rule(p)) ) {_res=if_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var class_def_var; if( $B._PyPegen.lookahead(1,_tmp_8_rule,p) && (class_def_var=class_def_rule(p)) ) {_res=class_def_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var with_stmt_var; if( $B._PyPegen.lookahead(1,_tmp_9_rule,p) && (with_stmt_var=with_stmt_rule(p)) ) {_res=with_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var for_stmt_var; if( $B._PyPegen.lookahead(1,_tmp_10_rule,p) && (for_stmt_var=for_stmt_rule(p)) ) {_res=for_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var try_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,656) && (try_stmt_var=try_stmt_rule(p)) ) {_res=try_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var while_stmt_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,689) && (while_stmt_var=while_stmt_rule(p)) ) {_res=while_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var match_stmt_var; if( (match_stmt_var=match_stmt_rule(p)) ) {_res=match_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function assignment_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (a=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=expression_rule(p)) && (c=_tmp_11_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,6,"Variable annotation syntax is",new $B._PyAST.AnnAssign($B.helper_functions.CHECK($B.ast.expr,$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store )),b,c,1,EXTRA )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (a=_tmp_12_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=expression_rule(p)) && (c=_tmp_13_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,6,"Variable annotations syntax is",new $B._PyAST.AnnAssign(a,b,c,0,EXTRA )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var tc; if( (a=_loop1_14_rule(p)) && (b=annotated_rhs_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,22) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Assign(a,b,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _cut_var=0; var a; var b; var c; if( (a=single_target_rule(p)) && (b=augassign_rule(p)) && (_cut_var=1) && (c=annotated_rhs_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.AugAssign(a,b.kind,c,EXTRA); break;} p.mark=_mark; if(_cut_var){return NULL;}} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_assignment_var; if( (invalid_assignment_var=invalid_assignment_rule(p)) ) {_res=invalid_assignment_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function annotated_rhs_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var yield_expr_var; if( (yield_expr_var=yield_expr_rule(p)) ) {_res=yield_expr_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var star_expressions_var; if( (star_expressions_var=star_expressions_rule(p)) ) {_res=star_expressions_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function augassign_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,36)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Add()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,37)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Sub()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,38)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Mult()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,50)) ) {_res=$B.helper_functions.CHECK_VERSION($B.parser_constants.AugOperator,5,"The '@' operator is",$B._PyPegen.augoperator(p,new $B.ast.MatMult())); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,39)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Div()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,40)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Mod()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,41)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.BitAnd()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,42)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.BitOr()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,43)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.BitXor()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,44)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.LShift()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,45)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.RShift()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,46)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.Pow()); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,48)) ) {_res=$B._PyPegen.augoperator(p,new $B.ast.FloorDiv()); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function return_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,522)) && (a=star_expressions_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Return(a,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function raise_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; var b; if( (_keyword=$B._PyPegen.expect_token(p,525)) && (a=expression_rule(p)) && (b=_tmp_15_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Raise(a,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,525)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Raise($B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function pass_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,526)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Pass(EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function break_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,527)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Break(EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function continue_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,528)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Continue(EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function global_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,529)) && (a=_gather_16_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Global($B.helper_functions.CHECK($B.parser_constants.asdl_identifier_seq,$B._PyPegen.map_names_to_ids(p,a )),EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function nonlocal_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,530)) && (a=_gather_18_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Nonlocal($B.helper_functions.CHECK($B.parser_constants.asdl_identifier_seq,$B._PyPegen.map_names_to_ids(p,a )),EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function del_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,625)) && (a=del_targets_rule(p)) && $B._PyPegen.lookahead(1,_tmp_20_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Delete(a,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_del_stmt_var; if( (invalid_del_stmt_var=invalid_del_stmt_rule(p)) ) {_res=invalid_del_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function yield_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var y; if( (y=yield_expr_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Expr(y,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function assert_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; var b; if( (_keyword=$B._PyPegen.expect_token(p,532)) && (a=expression_rule(p)) && (b=_tmp_21_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Assert(a,b,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_import_var; if( (invalid_import_var=invalid_import_rule(p)) ) {_res=invalid_import_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var import_name_var; if( (import_name_var=import_name_rule(p)) ) {_res=import_name_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var import_from_var; if( (import_from_var=import_from_rule(p)) ) {_res=import_from_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_name_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,634)) && (a=dotted_as_names_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Import(a,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_from_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,633)) && (a=_loop0_22_rule(p)) && (b=dotted_name_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,634)) && (c=import_from_targets_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.checked_future_import(p,b. id,c,$B._PyPegen.seq_count_dots(a ),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; var b; if( (_keyword=$B._PyPegen.expect_token(p,633)) && (a=_loop1_23_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,634)) && (b=import_from_targets_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ImportFrom($B.parser_constants.NULL,b,$B._PyPegen.seq_count_dots(a ),EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_from_targets_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=import_from_as_names_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var import_from_as_names_var; if( (import_from_as_names_var=import_from_as_names_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,12) ) {_res=import_from_as_names_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,16)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.singleton_seq(p,$B.helper_functions.CHECK($B.ast.alias,$B._PyPegen.alias_for_star(p,EXTRA ))); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_import_from_targets_var; if( (invalid_import_from_targets_var=invalid_import_from_targets_rule(p)) ) {_res=invalid_import_from_targets_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_from_as_names_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=_gather_24_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function import_from_as_name_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_import_from_as_name_var; if( (invalid_import_from_as_name_var=invalid_import_from_as_name_rule(p)) ) {_res=invalid_import_from_as_name_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=$B._PyPegen.name_token(p)) && (b=_tmp_26_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.alias(a. id,(b )?(b ). id :$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function dotted_as_names_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=_gather_27_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function dotted_as_name_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_dotted_as_name_var; if( (invalid_dotted_as_name_var=invalid_dotted_as_name_rule(p)) ) {_res=invalid_dotted_as_name_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=dotted_name_rule(p)) && (b=_tmp_29_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.alias(a. id,(b )?(b ). id :$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function dotted_name_raw(){}; function dotted_name_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,dotted_name_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_0=$B._PyPegen.update_memo(p,_mark,dotted_name_type,_res); if(tmpvar_0){return _res;} p.mark=_mark; var _raw=dotted_name_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function dotted_name_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=dotted_name_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.join_names_with_dot(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var name_var; if( (name_var=$B._PyPegen.name_token(p)) ) {_res=name_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,block_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var dedent_var; var indent_var; var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && (indent_var=$B._PyPegen.expect_token(p,INDENT)) && (a=statements_rule(p)) && (dedent_var=$B._PyPegen.expect_token(p,DEDENT)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var simple_stmts_var; if( (simple_stmts_var=simple_stmts_rule(p)) ) {_res=simple_stmts_var; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_block_var; if( (invalid_block_var=invalid_block_rule(p)) ) {_res=invalid_block_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,block_type,_res); return _res;} function decorators_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=_loop1_30_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function class_def_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; if( (a=decorators_rule(p)) && (b=class_def_raw_rule(p)) ) {_res=$B._PyPegen.class_def_decorators(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var class_def_raw_var; if( (class_def_raw_var=class_def_raw_rule(p)) ) {_res=class_def_raw_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function class_def_raw_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_class_def_raw_var; if( (invalid_class_def_raw_var=invalid_class_def_raw_rule(p)) ) {_res=invalid_class_def_raw_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; var t; if( (_keyword=$B._PyPegen.expect_token(p,701)) && (a=$B._PyPegen.name_token(p)) && (t=type_params_rule(p),!p.error_indicator) && (b=_tmp_31_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (c=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ClassDef(a. id,(b )?(b ). args :$B.parser_constants.NULL,(b )?(b ). keywords :$B.parser_constants.NULL,c,$B.parser_constants.NULL,t,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function function_def_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var d; var f; if( (d=decorators_rule(p)) && (f=function_def_raw_rule(p)) ) {_res=$B._PyPegen.function_def_decorators(p,d,f); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var function_def_raw_var; if( (function_def_raw_var=function_def_raw_rule(p)) ) {_res=function_def_raw_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function function_def_raw_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_def_raw_var; if( (invalid_def_raw_var=invalid_def_raw_rule(p)) ) {_res=invalid_def_raw_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var _literal_2; var a; var b; var n; var params; var t; var tc; if( (_keyword=$B._PyPegen.expect_token(p,699)) && (n=$B._PyPegen.name_token(p)) && (t=type_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,7)) && (params=params_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (a=_tmp_32_rule(p),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (tc=func_type_comment_rule(p),!p.error_indicator) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.FunctionDef(n. id,(params )? params :$B.helper_functions.CHECK($B.ast.arguments,$B._PyPegen.empty_arguments(p )),b,$B.parser_constants.NULL,a,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),t,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var _literal_2; var a; var b; var n; var params; var t; var tc; if( (_keyword=$B._PyPegen.expect_token(p,698)) && (_keyword_1=$B._PyPegen.expect_token(p,699)) && (n=$B._PyPegen.name_token(p)) && (t=type_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,7)) && (params=params_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (a=_tmp_33_rule(p),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (tc=func_type_comment_rule(p),!p.error_indicator) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,5,"Async functions are",new $B._PyAST.AsyncFunctionDef(n. id,(params )? params :$B.helper_functions.CHECK($B.ast.arguments,$B._PyPegen.empty_arguments(p )),b,$B.parser_constants.NULL,a,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),t,EXTRA )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function params_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_parameters_var; if( (invalid_parameters_var=invalid_parameters_rule(p)) ) {_res=invalid_parameters_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var parameters_var; if( (parameters_var=parameters_rule(p)) ) {_res=parameters_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function parameters_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; var c; var d; if( (a=slash_no_default_rule(p)) && (b=_loop0_34_rule(p)) && (c=_loop0_35_rule(p)) && (d=star_etc_rule(p),!p.error_indicator) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.arguments,8,"Positional-only parameters are",$B._PyPegen.make_arguments(p,a,$B.parser_constants.NULL,b,c,d )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=slash_with_default_rule(p)) && (b=_loop0_36_rule(p)) && (c=star_etc_rule(p),!p.error_indicator) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.arguments,8,"Positional-only parameters are",$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,a,$B.parser_constants.NULL,b,c )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=_loop1_37_rule(p)) && (b=_loop0_38_rule(p)) && (c=star_etc_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,a,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=_loop1_39_rule(p)) && (b=star_etc_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=star_etc_rule(p)) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function slash_no_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (a=_loop1_40_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (_literal_1=$B._PyPegen.expect_token(p,12)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=_loop1_41_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function slash_with_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=_loop0_42_rule(p)) && (b=_loop1_43_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (_literal_1=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.slash_with_default(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=_loop0_44_rule(p)) && (b=_loop1_45_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=$B._PyPegen.slash_with_default(p,a,b); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_etc_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_star_etc_var; if( (invalid_star_etc_var=invalid_star_etc_rule(p)) ) {_res=invalid_star_etc_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=param_no_default_rule(p)) && (b=_loop0_46_rule(p)) && (c=kwds_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.star_etc(p,a,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=param_no_default_star_annotation_rule(p)) && (b=_loop0_47_rule(p)) && (c=kwds_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.star_etc(p,a,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var b; var c; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (b=_loop1_48_rule(p)) && (c=kwds_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.star_etc(p,$B.parser_constants.NULL,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=kwds_rule(p)) ) {_res=$B._PyPegen.star_etc(p,$B.parser_constants.NULL,$B.parser_constants.NULL,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function kwds_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_kwds_var; if( (invalid_kwds_var=invalid_kwds_rule(p)) ) {_res=invalid_kwds_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=param_no_default_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_no_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var tc; if( (a=param_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) ) {_res=$B._PyPegen.add_type_comment_to_arg(p,a,tc); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var tc; if( (a=param_rule(p)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=$B._PyPegen.add_type_comment_to_arg(p,a,tc); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_no_default_star_annotation_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var tc; if( (a=param_star_annotation_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) ) {_res=$B._PyPegen.add_type_comment_to_arg(p,a,tc); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var tc; if( (a=param_star_annotation_rule(p)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=$B._PyPegen.add_type_comment_to_arg(p,a,tc); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_with_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var c; var tc; if( (a=param_rule(p)) && (c=default_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) ) {_res=$B._PyPegen.name_default_pair(p,a,c,tc); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var c; var tc; if( (a=param_rule(p)) && (c=default_rule(p)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=$B._PyPegen.name_default_pair(p,a,c,tc); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_maybe_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var c; var tc; if( (a=param_rule(p)) && (c=default_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,12)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) ) {_res=$B._PyPegen.name_default_pair(p,a,c,tc); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var c; var tc; if( (a=param_rule(p)) && (c=default_rule(p),!p.error_indicator) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=$B._PyPegen.name_default_pair(p,a,c,tc); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=$B._PyPegen.name_token(p)) && (b=annotation_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.arg(a. id,b,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function param_star_annotation_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=$B._PyPegen.name_token(p)) && (b=star_annotation_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.arg(a. id,b,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function annotation_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,11)) && (a=expression_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_annotation_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,11)) && (a=star_expression_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,22)) && (a=expression_rule(p)) ) {_res=a; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_default_var; if( (invalid_default_var=invalid_default_rule(p)) ) {_res=invalid_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function if_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_if_stmt_var; if( (invalid_if_stmt_var=invalid_if_stmt_rule(p)) ) {_res=invalid_if_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (a=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) && (c=elif_stmt_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.If(a,b,$B.helper_functions.CHECK($B.parser_constants.asdl_stmt_seq,$B._PyPegen.singleton_seq(p,c )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (a=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) && (c=else_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.If(a,b,c,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function elif_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_elif_stmt_var; if( (invalid_elif_stmt_var=invalid_elif_stmt_rule(p)) ) {_res=invalid_elif_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,687)) && (a=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) && (c=elif_stmt_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.If(a,b,$B.helper_functions.CHECK($B.parser_constants.asdl_stmt_seq,$B._PyPegen.singleton_seq(p,c )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,687)) && (a=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) && (c=else_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.If(a,b,c,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function else_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_else_stmt_var; if( (invalid_else_stmt_var=invalid_else_stmt_rule(p)) ) {_res=invalid_else_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; if( (_keyword=$B._PyPegen.expect_token(p,686)) && (_literal=$B._PyPegen.expect_forced_token(p,11,":")) && (b=block_rule(p)) ) {_res=b; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function while_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_while_stmt_var; if( (invalid_while_stmt_var=invalid_while_stmt_rule(p)) ) {_res=invalid_while_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,689)) && (a=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) && (c=else_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.While(a,b,c,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function for_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_for_stmt_var; if( (invalid_for_stmt_var=invalid_for_stmt_rule(p)) ) {_res=invalid_for_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _cut_var=0; var _keyword; var _keyword_1; var _literal; var b; var el; var ex; var t; var tc; if( (_keyword=$B._PyPegen.expect_token(p,694)) && (t=star_targets_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,695)) && (_cut_var=1) && (ex=star_expressions_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && (b=block_rule(p)) && (el=else_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.For(t,ex,b,el,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA); break;} p.mark=_mark; if(_cut_var){return NULL;}} { if(p.error_indicator){return NULL;} var _cut_var=0; var _keyword; var _keyword_1; var _keyword_2; var _literal; var b; var el; var ex; var t; var tc; if( (_keyword=$B._PyPegen.expect_token(p,698)) && (_keyword_1=$B._PyPegen.expect_token(p,694)) && (t=star_targets_rule(p)) && (_keyword_2=$B._PyPegen.expect_token(p,695)) && (_cut_var=1) && (ex=star_expressions_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && (b=block_rule(p)) && (el=else_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,5,"Async for loops are",new $B._PyAST.AsyncFor(t,ex,b,el,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA )); break;} p.mark=_mark; if(_cut_var){return NULL;}} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_for_target_var; if( (invalid_for_target_var=invalid_for_target_rule(p)) ) {_res=invalid_for_target_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function with_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_with_stmt_indent_var; if( (invalid_with_stmt_indent_var=invalid_with_stmt_indent_rule(p)) ) {_res=invalid_with_stmt_indent_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var a; var b; var tc; if( (_keyword=$B._PyPegen.expect_token(p,647)) && (_literal=$B._PyPegen.expect_token(p,7)) && (a=_gather_49_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.With(a,b,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; var tc; if( (_keyword=$B._PyPegen.expect_token(p,647)) && (a=_gather_51_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.With(a,b,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var a; var b; if( (_keyword=$B._PyPegen.expect_token(p,698)) && (_keyword_1=$B._PyPegen.expect_token(p,647)) && (_literal=$B._PyPegen.expect_token(p,7)) && (a=_gather_53_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,5,"Async with statements are",new $B._PyAST.AsyncWith(a,b,$B.parser_constants.NULL,EXTRA )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var a; var b; var tc; if( (_keyword=$B._PyPegen.expect_token(p,698)) && (_keyword_1=$B._PyPegen.expect_token(p,647)) && (a=_gather_55_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (tc=$B._PyPegen.expect_token(p,TYPE_COMMENT),!p.error_indicator) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,5,"Async with statements are",new $B._PyAST.AsyncWith(a,b,$B.helper_functions.NEW_TYPE_COMMENT(p,tc ),EXTRA )); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_with_stmt_var; if( (invalid_with_stmt_var=invalid_with_stmt_rule(p)) ) {_res=invalid_with_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function with_item_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var e; var t; if( (e=expression_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && (t=star_target_rule(p)) && $B._PyPegen.lookahead(1,_tmp_57_rule,p) ) {_res=new $B._PyAST.withitem(e,t,p.arena); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_with_item_var; if( (invalid_with_item_var=invalid_with_item_rule(p)) ) {_res=invalid_with_item_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var e; if( (e=expression_rule(p)) ) {_res=new $B._PyAST.withitem(e,$B.parser_constants.NULL,p.arena); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function try_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_try_stmt_var; if( (invalid_try_stmt_var=invalid_try_stmt_rule(p)) ) {_res=invalid_try_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var f; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_forced_token(p,11,":")) && (b=block_rule(p)) && (f=finally_block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Try(b,$B.parser_constants.NULL,$B.parser_constants.NULL,f,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var el; var ex; var f; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_forced_token(p,11,":")) && (b=block_rule(p)) && (ex=_loop1_58_rule(p)) && (el=else_block_rule(p),!p.error_indicator) && (f=finally_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Try(b,ex,el,f,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var el; var ex; var f; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_forced_token(p,11,":")) && (b=block_rule(p)) && (ex=_loop1_59_rule(p)) && (el=else_block_rule(p),!p.error_indicator) && (f=finally_block_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,11,"Exception groups are",new $B._PyAST.TryStar(b,ex,el,f,EXTRA )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function except_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_except_stmt_indent_var; if( (invalid_except_stmt_indent_var=invalid_except_stmt_indent_rule(p)) ) {_res=invalid_except_stmt_indent_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var e; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (e=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ExceptHandler(e,$B.parser_constants.NULL,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var b; var e; var t; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (e=expression_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (t=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ExceptHandler(e,(t ). id,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var e; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (e=expressions_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.excepthandler,14,"except expressions without parentheses are",new $B._PyAST.ExceptHandler(e,$B.parser_constants.NULL,b,EXTRA )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ExceptHandler($B.parser_constants.NULL,$B.parser_constants.NULL,b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_except_stmt_var; if( (invalid_except_stmt_var=invalid_except_stmt_rule(p)) ) {_res=invalid_except_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function except_star_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_except_star_stmt_indent_var; if( (invalid_except_star_stmt_indent_var=invalid_except_star_stmt_indent_rule(p)) ) {_res=invalid_except_star_stmt_indent_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var b; var e; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (e=expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ExceptHandler(e,$B.parser_constants.NULL,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var b; var e; var t; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (e=expression_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (t=$B._PyPegen.name_token(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ExceptHandler(e,(t ). id,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var b; var e; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (e=expressions_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (b=block_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.excepthandler,14,"except expressions without parentheses are",new $B._PyAST.ExceptHandler(e,$B.parser_constants.NULL,b,EXTRA )); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_except_star_stmt_var; if( (invalid_except_star_stmt_var=invalid_except_star_stmt_rule(p)) ) {_res=invalid_except_star_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function finally_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_finally_stmt_var; if( (invalid_finally_stmt_var=invalid_finally_stmt_rule(p)) ) {_res=invalid_finally_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; if( (_keyword=$B._PyPegen.expect_token(p,673)) && (_literal=$B._PyPegen.expect_forced_token(p,11,":")) && (a=block_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function match_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var cases; var dedent_var; var indent_var; var newline_var; var subject; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"match")) && (subject=subject_expr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && (indent_var=$B._PyPegen.expect_token(p,INDENT)) && (cases=_loop1_60_rule(p)) && (dedent_var=$B._PyPegen.expect_token(p,DEDENT)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,10,"Pattern matching is",new $B._PyAST.Match(subject,cases,EXTRA )); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_match_stmt_var; if( (invalid_match_stmt_var=invalid_match_stmt_rule(p)) ) {_res=invalid_match_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function subject_expr_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var value; var values; if( (value=star_named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (values=star_named_expressions_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,value,values )),$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var named_expression_var; if( (named_expression_var=named_expression_rule(p)) ) {_res=named_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function case_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_case_block_var; if( (invalid_case_block_var=invalid_case_block_rule(p)) ) {_res=invalid_case_block_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var body; var guard; var pattern; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"case")) && (pattern=patterns_rule(p)) && (guard=guard_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (body=block_rule(p)) ) {_res=new $B._PyAST.match_case(pattern,guard,body,p.arena); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function guard_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var guard; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (guard=named_expression_rule(p)) ) {_res=guard; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function patterns_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var patterns; if( (patterns=open_sequence_pattern_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSequence(patterns,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var pattern_var; if( (pattern_var=pattern_rule(p)) ) {_res=pattern_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var as_pattern_var; if( (as_pattern_var=as_pattern_rule(p)) ) {_res=as_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var or_pattern_var; if( (or_pattern_var=or_pattern_rule(p)) ) {_res=or_pattern_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function as_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var pattern; var target; if( (pattern=or_pattern_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && (target=pattern_capture_target_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchAs(pattern,target. id,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_as_pattern_var; if( (invalid_as_pattern_var=invalid_as_pattern_rule(p)) ) {_res=invalid_as_pattern_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function or_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var patterns; if( (patterns=_gather_61_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.asdl_seq_LEN(patterns )==1 ? $B.helper_functions.asdl_seq_GET(patterns,0 ):new $B._PyAST.MatchOr(patterns,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function closed_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,closed_pattern_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var literal_pattern_var; if( (literal_pattern_var=literal_pattern_rule(p)) ) {_res=literal_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var capture_pattern_var; if( (capture_pattern_var=capture_pattern_rule(p)) ) {_res=capture_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var wildcard_pattern_var; if( (wildcard_pattern_var=wildcard_pattern_rule(p)) ) {_res=wildcard_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var value_pattern_var; if( (value_pattern_var=value_pattern_rule(p)) ) {_res=value_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var group_pattern_var; if( (group_pattern_var=group_pattern_rule(p)) ) {_res=group_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var sequence_pattern_var; if( (sequence_pattern_var=sequence_pattern_rule(p)) ) {_res=sequence_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var mapping_pattern_var; if( (mapping_pattern_var=mapping_pattern_rule(p)) ) {_res=mapping_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var class_pattern_var; if( (class_pattern_var=class_pattern_rule(p)) ) {_res=class_pattern_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,closed_pattern_type,_res); return _res;} function literal_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var value; if( (value=signed_number_rule(p)) && $B._PyPegen.lookahead(0,_tmp_63_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchValue(value,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var value; if( (value=complex_number_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchValue(value,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var value; if( (value=strings_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchValue(value,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,623)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSingleton($B.parser_constants.Py_None,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,622)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSingleton($B.parser_constants.Py_True,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,624)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSingleton($B.parser_constants.Py_False,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function literal_expr_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var signed_number_var; if( (signed_number_var=signed_number_rule(p)) && $B._PyPegen.lookahead(0,_tmp_64_rule,p) ) {_res=signed_number_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var complex_number_var; if( (complex_number_var=complex_number_rule(p)) ) {_res=complex_number_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var strings_var; if( $B._PyPegen.lookahead(1,_tmp_65_rule,p) && (strings_var=strings_rule(p)) ) {_res=strings_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,623)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_None,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,622)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_True,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,624)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_False,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function complex_number_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var imag; var real; if( (real=signed_real_number_rule(p)) && (_literal=$B._PyPegen.expect_token(p,14)) && (imag=imaginary_number_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(real,new $B.ast.Add(),imag,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var imag; var real; if( (real=signed_real_number_rule(p)) && (_literal=$B._PyPegen.expect_token(p,15)) && (imag=imaginary_number_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(real,new $B.ast.Sub(),imag,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function signed_number_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var number_var; if( (number_var=$B._PyPegen.number_token(p)) ) {_res=number_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var number; if( (_literal=$B._PyPegen.expect_token(p,15)) && (number=$B._PyPegen.number_token(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.USub(),number,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function signed_real_number_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var real_number_var; if( (real_number_var=real_number_rule(p)) ) {_res=real_number_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var real; if( (_literal=$B._PyPegen.expect_token(p,15)) && (real=real_number_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.USub(),real,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function real_number_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var real; if( (real=$B._PyPegen.number_token(p)) ) {_res=$B._PyPegen.ensure_real(p,real); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function imaginary_number_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var imag; if( (imag=$B._PyPegen.number_token(p)) ) {_res=$B._PyPegen.ensure_imaginary(p,imag); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function capture_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var target; if( (target=pattern_capture_target_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchAs($B.parser_constants.NULL,target. id,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function pattern_capture_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var name; if( $B._PyPegen.lookahead_with_string(0,$B._PyPegen.expect_soft_keyword,p,"_") && (name=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead(0,_tmp_66_rule,p) ) {_res=$B._PyPegen.set_expr_context(p,name,$B.parser_constants.Store); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function wildcard_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"_")) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchAs($B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function value_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var attr; if( (attr=attr_rule(p)) && $B._PyPegen.lookahead(0,_tmp_67_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchValue(attr,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function attr_raw(){}; function attr_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,attr_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_1=$B._PyPegen.update_memo(p,_mark,attr_type,_res); if(tmpvar_1){return _res;} p.mark=_mark; var _raw=attr_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function attr_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var attr; var value; if( (value=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (attr=$B._PyPegen.name_token(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(value,attr. id,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function name_or_attr_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var attr_var; if( (attr_var=attr_rule(p)) ) {_res=attr_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var name_var; if( (name_var=$B._PyPegen.name_token(p)) ) {_res=name_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function group_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var pattern; if( (_literal=$B._PyPegen.expect_token(p,7)) && (pattern=pattern_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=pattern; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function sequence_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var patterns; if( (_literal=$B._PyPegen.expect_token(p,9)) && (patterns=maybe_sequence_pattern_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSequence(patterns,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var patterns; if( (_literal=$B._PyPegen.expect_token(p,7)) && (patterns=open_sequence_pattern_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchSequence(patterns,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function open_sequence_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var pattern; var patterns; if( (pattern=maybe_star_pattern_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (patterns=maybe_sequence_pattern_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.seq_insert_in_front(p,pattern,patterns); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function maybe_sequence_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var patterns; if( (patterns=_gather_68_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=patterns; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function maybe_star_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var star_pattern_var; if( (star_pattern_var=star_pattern_rule(p)) ) {_res=star_pattern_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var pattern_var; if( (pattern_var=pattern_rule(p)) ) {_res=pattern_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,star_pattern_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var target; if( (_literal=$B._PyPegen.expect_token(p,16)) && (target=pattern_capture_target_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchStar(target. id,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var wildcard_pattern_var; if( (_literal=$B._PyPegen.expect_token(p,16)) && (wildcard_pattern_var=wildcard_pattern_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchStar($B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,star_pattern_type,_res); return _res;} function mapping_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; if( (_literal=$B._PyPegen.expect_token(p,25)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchMapping($B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var rest; if( (_literal=$B._PyPegen.expect_token(p,25)) && (rest=double_star_pattern_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchMapping($B.parser_constants.NULL,$B.parser_constants.NULL,rest. id,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var items; var rest; if( (_literal=$B._PyPegen.expect_token(p,25)) && (items=items_pattern_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (rest=double_star_pattern_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchMapping($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_pattern_keys(p,items )),$B.helper_functions.CHECK($B.parser_constants.asdl_pattern_seq,$B._PyPegen.get_patterns(p,items )),rest. id,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var items; if( (_literal=$B._PyPegen.expect_token(p,25)) && (items=items_pattern_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchMapping($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_pattern_keys(p,items )),$B.helper_functions.CHECK($B.parser_constants.asdl_pattern_seq,$B._PyPegen.get_patterns(p,items )),$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function items_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_70_var; if( (_gather_70_var=_gather_70_rule(p)) ) {_res=_gather_70_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function key_value_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var key; var pattern; if( (key=_tmp_72_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (pattern=pattern_rule(p)) ) {_res=$B._PyPegen.key_pattern_pair(p,key,pattern); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function double_star_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var target; if( (_literal=$B._PyPegen.expect_token(p,35)) && (target=pattern_capture_target_rule(p)) ) {_res=target; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function class_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var cls; if( (cls=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchClass(cls,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var cls; var patterns; if( (cls=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (patterns=positional_patterns_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchClass(cls,patterns,$B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var cls; var keywords; if( (cls=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (keywords=keyword_patterns_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchClass(cls,$B.parser_constants.NULL,$B.helper_functions.CHECK($B.parser_constants.asdl_identifier_seq,$B._PyPegen.map_names_to_ids(p,$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_pattern_keys(p,keywords )))),$B.helper_functions.CHECK($B.parser_constants.asdl_pattern_seq,$B._PyPegen.get_patterns(p,keywords )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var cls; var keywords; var patterns; if( (cls=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (patterns=positional_patterns_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (keywords=keyword_patterns_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.MatchClass(cls,patterns,$B.helper_functions.CHECK($B.parser_constants.asdl_identifier_seq,$B._PyPegen.map_names_to_ids(p,$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_pattern_keys(p,keywords )))),$B.helper_functions.CHECK($B.parser_constants.asdl_pattern_seq,$B._PyPegen.get_patterns(p,keywords )),EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_class_pattern_var; if( (invalid_class_pattern_var=invalid_class_pattern_rule(p)) ) {_res=invalid_class_pattern_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function positional_patterns_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var args; if( (args=_gather_73_rule(p)) ) {_res=args; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function keyword_patterns_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_75_var; if( (_gather_75_var=_gather_75_rule(p)) ) {_res=_gather_75_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function keyword_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var arg; var value; if( (arg=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (value=pattern_rule(p)) ) {_res=$B._PyPegen.key_pattern_pair(p,arg,value); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_alias_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var b; var n; var t; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"type")) && (n=$B._PyPegen.name_token(p)) && (t=type_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.stmt,12,"Type statement is",new $B._PyAST.TypeAlias($B.helper_functions.CHECK($B.ast.expr,$B._PyPegen.set_expr_context(p,n,$B.parser_constants.Store )),t,b,EXTRA )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_params_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_type_params_var; if( (invalid_type_params_var=invalid_type_params_rule(p)) ) {_res=invalid_type_params_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var t; if( (_literal=$B._PyPegen.expect_token(p,9)) && (t=type_param_seq_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {_res=$B.helper_functions.CHECK_VERSION($B.parser_constants.asdl_type_param_seq,12,"Type parameter lists are",t); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_param_seq_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_77_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_param_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,type_param_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=$B._PyPegen.name_token(p)) && (b=type_param_bound_rule(p),!p.error_indicator) && (c=type_param_default_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.TypeVar(a. id,b,c,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_type_param_var; if( (invalid_type_param_var=invalid_type_param_rule(p)) ) {_res=invalid_type_param_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=$B._PyPegen.name_token(p)) && (b=type_param_starred_default_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.TypeVarTuple(a. id,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=$B._PyPegen.name_token(p)) && (b=type_param_default_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ParamSpec(a. id,b,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,type_param_type,_res); return _res;} function type_param_bound_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var e; if( (_literal=$B._PyPegen.expect_token(p,11)) && (e=expression_rule(p)) ) {_res=e; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_param_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var e; if( (_literal=$B._PyPegen.expect_token(p,22)) && (e=expression_rule(p)) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.expr,13,"Type parameter defaults are",e); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_param_starred_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var e; if( (_literal=$B._PyPegen.expect_token(p,22)) && (e=star_expression_rule(p)) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.expr,13,"Type parameter defaults are",e); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function expressions_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=expression_rule(p)) && (b=_loop1_79_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,a,b )),$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.singleton_seq(p,a )),$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,expression_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_expression_var; if( (invalid_expression_var=invalid_expression_rule(p)) ) {_res=invalid_expression_var; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_legacy_expression_var; if( (invalid_legacy_expression_var=invalid_legacy_expression_rule(p)) ) {_res=invalid_legacy_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; var b; var c; if( (a=disjunction_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,682)) && (b=disjunction_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,686)) && (c=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.IfExp(b,a,c,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var disjunction_var; if( (disjunction_var=disjunction_rule(p)) ) {_res=disjunction_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lambdef_var; if( (lambdef_var=lambdef_rule(p)) ) {_res=lambdef_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,expression_type,_res); return _res;} function yield_expr_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; if( (_keyword=$B._PyPegen.expect_token(p,587)) && (_keyword_1=$B._PyPegen.expect_token(p,633)) && (a=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.YieldFrom(a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,587)) && (a=star_expressions_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Yield(a,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_expressions_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=star_expression_rule(p)) && (b=_loop1_80_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,a,b )),$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=star_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.singleton_seq(p,a )),$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var star_expression_var; if( (star_expression_var=star_expression_rule(p)) ) {_res=star_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,star_expression_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=bitwise_or_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Starred(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,star_expression_type,_res); return _res;} function star_named_expressions_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_81_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_named_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=bitwise_or_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Starred(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var named_expression_var; if( (named_expression_var=named_expression_rule(p)) ) {_res=named_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function assignment_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _cut_var=0; var _literal; var a; var b; if( (a=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,53)) && (_cut_var=1) && (b=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.expr,8,"Assignment expressions are",new $B._PyAST.NamedExpr($B.helper_functions.CHECK($B.ast.expr,$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store )),b,EXTRA )); break;} p.mark=_mark; if(_cut_var){return NULL;}} _res=NULL; break;} return _res;} function named_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var assignment_expression_var; if( (assignment_expression_var=assignment_expression_rule(p)) ) {_res=assignment_expression_var; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_named_expression_var; if( (invalid_named_expression_var=invalid_named_expression_rule(p)) ) {_res=invalid_named_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,53) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function disjunction_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,disjunction_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=conjunction_rule(p)) && (b=_loop1_83_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BoolOp(new $B.ast.Or(),$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,a,b )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var conjunction_var; if( (conjunction_var=conjunction_rule(p)) ) {_res=conjunction_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,disjunction_type,_res); return _res;} function conjunction_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,conjunction_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=inversion_rule(p)) && (b=_loop1_84_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BoolOp(new $B.ast.And(),$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,a,b )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var inversion_var; if( (inversion_var=inversion_rule(p)) ) {_res=inversion_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,conjunction_type,_res); return _res;} function inversion_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,inversion_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,703)) && (a=inversion_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.Not(),a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var comparison_var; if( (comparison_var=comparison_rule(p)) ) {_res=comparison_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,inversion_type,_res); return _res;} function comparison_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=bitwise_or_rule(p)) && (b=_loop1_85_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Compare(a,$B.helper_functions.CHECK($B.parser_constants.asdl_int_seq,$B._PyPegen.get_cmpops(p,b )),$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_exprs(p,b )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var bitwise_or_var; if( (bitwise_or_var=bitwise_or_rule(p)) ) {_res=bitwise_or_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function compare_op_bitwise_or_pair_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var eq_bitwise_or_var; if( (eq_bitwise_or_var=eq_bitwise_or_rule(p)) ) {_res=eq_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var noteq_bitwise_or_var; if( (noteq_bitwise_or_var=noteq_bitwise_or_rule(p)) ) {_res=noteq_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lte_bitwise_or_var; if( (lte_bitwise_or_var=lte_bitwise_or_rule(p)) ) {_res=lte_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lt_bitwise_or_var; if( (lt_bitwise_or_var=lt_bitwise_or_rule(p)) ) {_res=lt_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var gte_bitwise_or_var; if( (gte_bitwise_or_var=gte_bitwise_or_rule(p)) ) {_res=gte_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var gt_bitwise_or_var; if( (gt_bitwise_or_var=gt_bitwise_or_rule(p)) ) {_res=gt_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var notin_bitwise_or_var; if( (notin_bitwise_or_var=notin_bitwise_or_rule(p)) ) {_res=notin_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var in_bitwise_or_var; if( (in_bitwise_or_var=in_bitwise_or_rule(p)) ) {_res=in_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var isnot_bitwise_or_var; if( (isnot_bitwise_or_var=isnot_bitwise_or_rule(p)) ) {_res=isnot_bitwise_or_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var is_bitwise_or_var; if( (is_bitwise_or_var=is_bitwise_or_rule(p)) ) {_res=is_bitwise_or_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function eq_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,27)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.Eq(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function noteq_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_86_var; var a; if( (_tmp_86_var=_tmp_86_rule(p)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.NotEq(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lte_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,29)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.LtE(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lt_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,20)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.Lt(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function gte_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,30)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.GtE(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function gt_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,21)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.Gt(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function notin_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; if( (_keyword=$B._PyPegen.expect_token(p,703)) && (_keyword_1=$B._PyPegen.expect_token(p,695)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.NotIn(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function in_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,695)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.In(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function isnot_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; if( (_keyword=$B._PyPegen.expect_token(p,596)) && (_keyword_1=$B._PyPegen.expect_token(p,703)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.IsNot(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function is_bitwise_or_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,596)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.cmpop_expr_pair(p,new $B.ast.Is(),a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function bitwise_or_raw(){}; function bitwise_or_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,bitwise_or_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_2=$B._PyPegen.update_memo(p,_mark,bitwise_or_type,_res); if(tmpvar_2){return _res;} p.mark=_mark; var _raw=bitwise_or_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function bitwise_or_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=bitwise_or_rule(p)) && (_literal=$B._PyPegen.expect_token(p,18)) && (b=bitwise_xor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.BitOr(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var bitwise_xor_var; if( (bitwise_xor_var=bitwise_xor_rule(p)) ) {_res=bitwise_xor_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function bitwise_xor_raw(){}; function bitwise_xor_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,bitwise_xor_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_3=$B._PyPegen.update_memo(p,_mark,bitwise_xor_type,_res); if(tmpvar_3){return _res;} p.mark=_mark; var _raw=bitwise_xor_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function bitwise_xor_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=bitwise_xor_rule(p)) && (_literal=$B._PyPegen.expect_token(p,32)) && (b=bitwise_and_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.BitXor(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var bitwise_and_var; if( (bitwise_and_var=bitwise_and_rule(p)) ) {_res=bitwise_and_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function bitwise_and_raw(){}; function bitwise_and_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,bitwise_and_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_4=$B._PyPegen.update_memo(p,_mark,bitwise_and_type,_res); if(tmpvar_4){return _res;} p.mark=_mark; var _raw=bitwise_and_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function bitwise_and_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=bitwise_and_rule(p)) && (_literal=$B._PyPegen.expect_token(p,19)) && (b=shift_expr_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.BitAnd(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var shift_expr_var; if( (shift_expr_var=shift_expr_rule(p)) ) {_res=shift_expr_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function shift_expr_raw(){}; function shift_expr_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,shift_expr_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_5=$B._PyPegen.update_memo(p,_mark,shift_expr_type,_res); if(tmpvar_5){return _res;} p.mark=_mark; var _raw=shift_expr_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function shift_expr_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=shift_expr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,33)) && (b=sum_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.LShift(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=shift_expr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,34)) && (b=sum_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.RShift(),b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_arithmetic_var; if( (invalid_arithmetic_var=invalid_arithmetic_rule(p)) ) {_res=invalid_arithmetic_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var sum_var; if( (sum_var=sum_rule(p)) ) {_res=sum_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function sum_raw(){}; function sum_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,sum_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_6=$B._PyPegen.update_memo(p,_mark,sum_type,_res); if(tmpvar_6){return _res;} p.mark=_mark; var _raw=sum_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function sum_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=sum_rule(p)) && (_literal=$B._PyPegen.expect_token(p,14)) && (b=term_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Add(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=sum_rule(p)) && (_literal=$B._PyPegen.expect_token(p,15)) && (b=term_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Sub(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var term_var; if( (term_var=term_rule(p)) ) {_res=term_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function term_raw(){}; function term_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,term_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_7=$B._PyPegen.update_memo(p,_mark,term_type,_res); if(tmpvar_7){return _res;} p.mark=_mark; var _raw=term_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function term_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=term_rule(p)) && (_literal=$B._PyPegen.expect_token(p,16)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Mult(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=term_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Div(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=term_rule(p)) && (_literal=$B._PyPegen.expect_token(p,47)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.FloorDiv(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=term_rule(p)) && (_literal=$B._PyPegen.expect_token(p,24)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Mod(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=term_rule(p)) && (_literal=$B._PyPegen.expect_token(p,49)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.expr,5,"The '@' operator is",new $B._PyAST.BinOp(a,new $B.ast.MatMult(),b,EXTRA )); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_factor_var; if( (invalid_factor_var=invalid_factor_rule(p)) ) {_res=invalid_factor_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var factor_var; if( (factor_var=factor_rule(p)) ) {_res=factor_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function factor_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,factor_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,14)) && (a=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.UAdd(),a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,15)) && (a=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.USub(),a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,31)) && (a=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.UnaryOp(new $B.ast.Invert(),a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var power_var; if( (power_var=power_rule(p)) ) {_res=power_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,factor_type,_res); return _res;} function power_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=await_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,35)) && (b=factor_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.BinOp(a,new $B.ast.Pow(),b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var await_primary_var; if( (await_primary_var=await_primary_rule(p)) ) {_res=await_primary_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function await_primary_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,await_primary_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,597)) && (a=primary_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B.helper_functions.CHECK_VERSION($B.ast.expr,5,"Await expressions are",new $B._PyAST.Await(a,EXTRA )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var primary_var; if( (primary_var=primary_rule(p)) ) {_res=primary_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,await_primary_type,_res); return _res;} function primary_raw(){}; function primary_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,primary_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_8=$B._PyPegen.update_memo(p,_mark,primary_type,_res); if(tmpvar_8){return _res;} p.mark=_mark; var _raw=primary_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function primary_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(a,b. id,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=primary_rule(p)) && (b=genexp_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Call(a,$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.singleton_seq(p,b )),$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (b=arguments_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Call(a,(b )?(b ). args :$B.parser_constants.NULL,(b )?(b ). keywords :$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,9)) && (b=slices_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Subscript(a,b,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var atom_var; if( (atom_var=atom_rule(p)) ) {_res=atom_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function slices_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; if( (a=slice_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,12) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_87_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function slice_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (a=expression_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=expression_rule(p),!p.error_indicator) && (c=_tmp_89_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Slice(a,b,c,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=named_expression_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function atom_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var name_var; if( (name_var=$B._PyPegen.name_token(p)) ) {_res=name_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,622)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_True,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,624)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_False,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,623)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_None,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var strings_var; if( $B._PyPegen.lookahead(1,_tmp_90_rule,p) && (strings_var=strings_rule(p)) ) {_res=strings_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var number_var; if( (number_var=$B._PyPegen.number_token(p)) ) {_res=number_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_91_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,7) && (_tmp_91_var=_tmp_91_rule(p)) ) {_res=_tmp_91_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_92_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,9) && (_tmp_92_var=_tmp_92_rule(p)) ) {_res=_tmp_92_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_93_var; if( $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,25) && (_tmp_93_var=_tmp_93_rule(p)) ) {_res=_tmp_93_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,52)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Constant($B.parser_constants.Py_Ellipsis,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function group_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=_tmp_94_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=a; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_group_var; if( (invalid_group_var=invalid_group_rule(p)) ) {_res=invalid_group_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambdef_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var a; var b; if( (_keyword=$B._PyPegen.expect_token(p,621)) && (a=lambda_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Lambda((a )? a :$B.helper_functions.CHECK($B.ast.arguments,$B._PyPegen.empty_arguments(p )),b,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_params_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_lambda_parameters_var; if( (invalid_lambda_parameters_var=invalid_lambda_parameters_rule(p)) ) {_res=invalid_lambda_parameters_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lambda_parameters_var; if( (lambda_parameters_var=lambda_parameters_rule(p)) ) {_res=lambda_parameters_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_parameters_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; var c; var d; if( (a=lambda_slash_no_default_rule(p)) && (b=_loop0_95_rule(p)) && (c=_loop0_96_rule(p)) && (d=lambda_star_etc_rule(p),!p.error_indicator) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.arguments,8,"Positional-only parameters are",$B._PyPegen.make_arguments(p,a,$B.parser_constants.NULL,b,c,d )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=lambda_slash_with_default_rule(p)) && (b=_loop0_97_rule(p)) && (c=lambda_star_etc_rule(p),!p.error_indicator) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.arguments,8,"Positional-only parameters are",$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,a,$B.parser_constants.NULL,b,c )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=_loop1_98_rule(p)) && (b=_loop0_99_rule(p)) && (c=lambda_star_etc_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,a,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=_loop1_100_rule(p)) && (b=lambda_star_etc_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=lambda_star_etc_rule(p)) ) {_res=$B._PyPegen.make_arguments(p,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,$B.parser_constants.NULL,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_slash_no_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (a=_loop1_101_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (_literal_1=$B._PyPegen.expect_token(p,12)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=_loop1_102_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,11) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_slash_with_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=_loop0_103_rule(p)) && (b=_loop1_104_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (_literal_1=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.slash_with_default(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=_loop0_105_rule(p)) && (b=_loop1_106_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,11) ) {_res=$B._PyPegen.slash_with_default(p,a,b); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_star_etc_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_lambda_star_etc_var; if( (invalid_lambda_star_etc_var=invalid_lambda_star_etc_rule(p)) ) {_res=invalid_lambda_star_etc_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var c; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=lambda_param_no_default_rule(p)) && (b=_loop0_107_rule(p)) && (c=lambda_kwds_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.star_etc(p,a,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var b; var c; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (b=_loop1_108_rule(p)) && (c=lambda_kwds_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.star_etc(p,$B.parser_constants.NULL,b,c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=lambda_kwds_rule(p)) ) {_res=$B._PyPegen.star_etc(p,$B.parser_constants.NULL,$B.parser_constants.NULL,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_kwds_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_lambda_kwds_var; if( (invalid_lambda_kwds_var=invalid_lambda_kwds_rule(p)) ) {_res=invalid_lambda_kwds_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=lambda_param_no_default_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_param_no_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=lambda_param_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=lambda_param_rule(p)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,11) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_param_with_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var c; if( (a=lambda_param_rule(p)) && (c=default_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.name_default_pair(p,a,c,$B.parser_constants.NULL); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var c; if( (a=lambda_param_rule(p)) && (c=default_rule(p)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,11) ) {_res=$B._PyPegen.name_default_pair(p,a,c,$B.parser_constants.NULL); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_param_maybe_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var c; if( (a=lambda_param_rule(p)) && (c=default_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.name_default_pair(p,a,c,$B.parser_constants.NULL); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var c; if( (a=lambda_param_rule(p)) && (c=default_rule(p),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,11) ) {_res=$B._PyPegen.name_default_pair(p,a,c,$B.parser_constants.NULL); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function lambda_param_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; if( (a=$B._PyPegen.name_token(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.arg(a. id,$B.parser_constants.NULL,$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_middle_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var fstring_replacement_field_var; if( (fstring_replacement_field_var=fstring_replacement_field_rule(p)) ) {_res=fstring_replacement_field_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var t; if( (t=$B._PyPegen.expect_token(p,FSTRING_MIDDLE)) ) {_res=$B._PyPegen.constant_from_token(p,t); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_replacement_field_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var conversion; var debug_expr; var format; var rbrace; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=annotated_rhs_rule(p)) && (debug_expr=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (conversion=fstring_conversion_rule(p),!p.error_indicator) && (format=fstring_full_format_spec_rule(p),!p.error_indicator) && (rbrace=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.formatted_value(p,a,debug_expr,conversion,format,rbrace,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_fstring_replacement_field_var; if( (invalid_fstring_replacement_field_var=invalid_fstring_replacement_field_rule(p)) ) {_res=invalid_fstring_replacement_field_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_conversion_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var conv; var conv_token; if( (conv_token=$B._PyPegen.expect_token(p,54)) && (conv=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.check_fstring_conversion(p,conv_token,conv); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_full_format_spec_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var colon; var spec; if( (colon=$B._PyPegen.expect_token(p,11)) && (spec=_loop0_109_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.setup_full_format_spec(p,colon,spec,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_format_spec_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var t; if( (t=$B._PyPegen.expect_token(p,FSTRING_MIDDLE)) ) {_res=$B._PyPegen.decoded_constant_from_token(p,t); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var fstring_replacement_field_var; if( (fstring_replacement_field_var=fstring_replacement_field_rule(p)) ) {_res=fstring_replacement_field_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function fstring_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=$B._PyPegen.expect_token(p,FSTRING_START)) && (b=_loop0_110_rule(p)) && (c=$B._PyPegen.expect_token(p,FSTRING_END)) ) {_res=$B._PyPegen.joined_str(p,a,b,c); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_format_spec_replacement_field_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var conversion; var debug_expr; var format; var rbrace; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=annotated_rhs_rule(p)) && (debug_expr=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (conversion=fstring_conversion_rule(p),!p.error_indicator) && (format=tstring_full_format_spec_rule(p),!p.error_indicator) && (rbrace=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.formatted_value(p,a,debug_expr,conversion,format,rbrace,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_tstring_replacement_field_var; if( (invalid_tstring_replacement_field_var=invalid_tstring_replacement_field_rule(p)) ) {_res=invalid_tstring_replacement_field_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_format_spec_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var t; if( (t=$B._PyPegen.expect_token(p,TSTRING_MIDDLE)) ) {_res=$B._PyPegen.decoded_constant_from_token(p,t); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var tstring_format_spec_replacement_field_var; if( (tstring_format_spec_replacement_field_var=tstring_format_spec_replacement_field_rule(p)) ) {_res=tstring_format_spec_replacement_field_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_full_format_spec_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var colon; var spec; if( (colon=$B._PyPegen.expect_token(p,11)) && (spec=_loop0_111_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.setup_full_format_spec(p,colon,spec,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_replacement_field_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var conversion; var debug_expr; var format; var rbrace; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=annotated_rhs_rule(p)) && (debug_expr=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (conversion=fstring_conversion_rule(p),!p.error_indicator) && (format=tstring_full_format_spec_rule(p),!p.error_indicator) && (rbrace=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.interpolation(p,a,debug_expr,conversion,format,rbrace,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_tstring_replacement_field_var; if( (invalid_tstring_replacement_field_var=invalid_tstring_replacement_field_rule(p)) ) {_res=invalid_tstring_replacement_field_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_middle_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var tstring_replacement_field_var; if( (tstring_replacement_field_var=tstring_replacement_field_rule(p)) ) {_res=tstring_replacement_field_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var t; if( (t=$B._PyPegen.expect_token(p,TSTRING_MIDDLE)) ) {_res=$B._PyPegen.constant_from_token(p,t); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tstring_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,tstring_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; var c; if( (a=$B._PyPegen.expect_token(p,TSTRING_START)) && (b=_loop0_112_rule(p)) && (c=$B._PyPegen.expect_token(p,TSTRING_END)) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.expr,14,"t-strings are",$B._PyPegen.template_str(p,a,b,c )); break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,tstring_type,_res); return _res;} function string_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var s; if( (s=$B._PyPegen.string_token(p)) ) {_res=$B._PyPegen.constant_from_string(p,s); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function strings_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,strings_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_string_tstring_concat_var; if( (invalid_string_tstring_concat_var=invalid_string_tstring_concat_rule(p)) ) {_res=invalid_string_tstring_concat_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=_loop1_113_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.concatenate_strings(p,a,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=_loop1_114_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.concatenate_tstrings(p,a,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,strings_type,_res); return _res;} function list_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,9)) && (a=star_named_expressions_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.List(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function tuple_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=_tmp_115_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function set_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=star_named_expressions_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Set(a,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function dict_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=double_starred_kvpairs_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Dict($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_keys(p,a )),$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.get_values(p,a )),EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var invalid_double_starred_kvpairs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (invalid_double_starred_kvpairs_var=invalid_double_starred_kvpairs_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {_res=$B._PyPegen.dummy_name(p,_literal,invalid_double_starred_kvpairs_var,_literal_1); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function double_starred_kvpairs_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_116_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function double_starred_kvpair_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=bitwise_or_rule(p)) ) {_res=$B._PyPegen.key_value_pair(p,$B.parser_constants.NULL,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var kvpair_var; if( (kvpair_var=kvpair_rule(p)) ) {_res=kvpair_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function kvpair_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (b=expression_rule(p)) ) {_res=$B._PyPegen.key_value_pair(p,a,b); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function for_if_clauses_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=_loop1_118_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function for_if_clause_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _cut_var=0; var _keyword; var _keyword_1; var _keyword_2; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,698)) && (_keyword_1=$B._PyPegen.expect_token(p,694)) && (a=star_targets_rule(p)) && (_keyword_2=$B._PyPegen.expect_token(p,695)) && (_cut_var=1) && (b=disjunction_rule(p)) && (c=_loop0_119_rule(p)) ) {_res=$B.helper_functions.CHECK_VERSION($B.ast.comprehension,6,"Async comprehensions are",new $B._PyAST.comprehension(a,b,c,1,p.arena )); break;} p.mark=_mark; if(_cut_var){return NULL;}} { if(p.error_indicator){return NULL;} var _cut_var=0; var _keyword; var _keyword_1; var a; var b; var c; if( (_keyword=$B._PyPegen.expect_token(p,694)) && (a=star_targets_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,695)) && (_cut_var=1) && (b=disjunction_rule(p)) && (c=_loop0_120_rule(p)) ) {_res=new $B._PyAST.comprehension(a,b,c,0,p.arena); break;} p.mark=_mark; if(_cut_var){return NULL;}} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_for_if_clause_var; if( (invalid_for_if_clause_var=invalid_for_if_clause_rule(p)) ) {_res=invalid_for_if_clause_var; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_for_target_var; if( (invalid_for_target_var=invalid_for_target_rule(p)) ) {_res=invalid_for_target_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function listcomp_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,9)) && (a=named_expression_rule(p)) && (b=for_if_clauses_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.ListComp(a,b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_comprehension_var; if( (invalid_comprehension_var=invalid_comprehension_rule(p)) ) {_res=invalid_comprehension_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function setcomp_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=named_expression_rule(p)) && (b=for_if_clauses_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.SetComp(a,b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_comprehension_var; if( (invalid_comprehension_var=invalid_comprehension_rule(p)) ) {_res=invalid_comprehension_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function genexp_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=_tmp_121_rule(p)) && (b=for_if_clauses_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.GeneratorExp(a,b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_comprehension_var; if( (invalid_comprehension_var=invalid_comprehension_rule(p)) ) {_res=invalid_comprehension_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function dictcomp_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=kvpair_rule(p)) && (b=for_if_clauses_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.DictComp(a.key,a.value,b,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_dict_comprehension_var; if( (invalid_dict_comprehension_var=invalid_dict_comprehension_rule(p)) ) {_res=invalid_dict_comprehension_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function arguments_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,arguments_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=args_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,8) ) {_res=a; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_arguments_var; if( (invalid_arguments_var=invalid_arguments_rule(p)) ) {_res=invalid_arguments_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,arguments_type,_res); return _res;} function args_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; var b; if( (a=_gather_122_rule(p)) && (b=_tmp_124_rule(p),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.collect_call_seqs(p,a,b,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=kwargs_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Call($B._PyPegen.dummy_name(p ),$B.helper_functions.CHECK_NULL_ALLOWED($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_extract_starred_exprs(p,a )),$B.helper_functions.CHECK_NULL_ALLOWED($B.parser_constants.asdl_keyword_seq,$B._PyPegen.seq_delete_starred_exprs(p,a )),EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function kwargs_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=_gather_125_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (b=_gather_127_rule(p)) ) {_res=$B._PyPegen.join_sequences(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _gather_129_var; if( (_gather_129_var=_gather_129_rule(p)) ) {_res=_gather_129_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _gather_131_var; if( (_gather_131_var=_gather_131_rule(p)) ) {_res=_gather_131_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function starred_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_starred_expression_unpacking_var; if( (invalid_starred_expression_unpacking_var=invalid_starred_expression_unpacking_rule(p)) ) {_res=invalid_starred_expression_unpacking_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Starred(a,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_starred_expression_var; if( (invalid_starred_expression_var=invalid_starred_expression_rule(p)) ) {_res=invalid_starred_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function kwarg_or_starred_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_kwarg_var; if( (invalid_kwarg_var=invalid_kwarg_rule(p)) ) {_res=invalid_kwarg_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.keyword_or_starred(p,$B.helper_functions.CHECK($B.ast.keyword,new $B._PyAST.keyword(a. id,b,EXTRA )),1); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=starred_expression_rule(p)) ) {_res=$B._PyPegen.keyword_or_starred(p,a,0); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function kwarg_or_double_starred_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_kwarg_var; if( (invalid_kwarg_var=invalid_kwarg_rule(p)) ) {_res=invalid_kwarg_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.keyword_or_starred(p,$B.helper_functions.CHECK($B.ast.keyword,new $B._PyAST.keyword(a. id,b,EXTRA )),1); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=$B._PyPegen.keyword_or_starred(p,$B.helper_functions.CHECK($B.ast.keyword,new $B._PyAST.keyword($B.parser_constants.NULL,a,EXTRA )),1); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_targets_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; if( (a=star_target_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,12) ) {_res=a; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=star_target_rule(p)) && (b=_loop0_133_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple($B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.seq_insert_in_front(p,a,b )),$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_targets_list_seq_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_134_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_targets_tuple_seq_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=star_target_rule(p)) && (b=_loop1_136_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=$B._PyPegen.seq_insert_in_front(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=star_target_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function star_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,star_target_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=_tmp_137_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Starred($B.helper_functions.CHECK($B.ast.expr,$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store )),$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var target_with_star_atom_var; if( (target_with_star_atom_var=target_with_star_atom_rule(p)) ) {_res=target_with_star_atom_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,star_target_type,_res); return _res;} function target_with_star_atom_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,target_with_star_atom_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(a,b. id,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,9)) && (b=slices_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Subscript(a,b,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var star_atom_var; if( (star_atom_var=star_atom_rule(p)) ) {_res=star_atom_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,target_with_star_atom_type,_res); return _res;} function star_atom_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; if( (a=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=target_with_star_atom_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=star_targets_tuple_seq_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple(a,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,9)) && (a=star_targets_list_seq_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.List(a,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function single_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var single_subscript_attribute_target_var; if( (single_subscript_attribute_target_var=single_subscript_attribute_target_rule(p)) ) {_res=single_subscript_attribute_target_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Store); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=single_target_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function single_subscript_attribute_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(a,b. id,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,9)) && (b=slices_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Subscript(a,b,$B.parser_constants.Store,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function t_primary_raw(){}; function t_primary_rule(p) {var _res={value:NULL}; if($B._PyPegen.is_memoized(p,t_primary_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; var _resmark=p.mark; while(1){var tmpvar_9=$B._PyPegen.update_memo(p,_mark,t_primary_type,_res); if(tmpvar_9){return _res;} p.mark=_mark; var _raw=t_primary_raw(p); if(p.error_indicator){return NULL;} if(_raw==NULL ||p.mark <=_resmark) break; _resmark=p.mark; _res=_raw;} p.mark=_resmark; return _res;} function t_primary_raw(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead(1,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(a,b. id,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,9)) && (b=slices_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) && $B._PyPegen.lookahead(1,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Subscript(a,b,$B.parser_constants.Load,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=t_primary_rule(p)) && (b=genexp_rule(p)) && $B._PyPegen.lookahead(1,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Call(a,$B.helper_functions.CHECK($B.parser_constants.asdl_expr_seq,$B._PyPegen.singleton_seq(p,b )),$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (b=arguments_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && $B._PyPegen.lookahead(1,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Call(a,(b )?(b ). args :$B.parser_constants.NULL,(b )?(b ). keywords :$B.parser_constants.NULL,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=atom_rule(p)) && $B._PyPegen.lookahead(1,t_lookahead_rule,p) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function t_lookahead_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,7)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,9)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,23)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function del_targets_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; if( (a=_gather_138_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function del_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,del_target_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,23)) && (b=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Attribute(a,b. id,$B.parser_constants.Del,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=t_primary_rule(p)) && (_literal=$B._PyPegen.expect_token(p,9)) && (b=slices_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,10)) && $B._PyPegen.lookahead(0,t_lookahead_rule,p) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Subscript(a,b,$B.parser_constants.Del,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var del_t_atom_var; if( (del_t_atom_var=del_t_atom_rule(p)) ) {_res=del_t_atom_var; break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,del_target_type,_res); return _res;} function del_t_atom_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){return NULL;} var a; if( (a=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Del); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=del_target_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B._PyPegen.set_expr_context(p,a,$B.parser_constants.Del); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=del_targets_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.Tuple(a,$B.parser_constants.Del,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,9)) && (a=del_targets_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,10)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.List(a,$B.parser_constants.Del,EXTRA); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function type_expressions_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var _literal_3; var a; var b; var c; if( (a=_gather_140_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (_literal_1=$B._PyPegen.expect_token(p,16)) && (b=expression_rule(p)) && (_literal_2=$B._PyPegen.expect_token(p,12)) && (_literal_3=$B._PyPegen.expect_token(p,35)) && (c=expression_rule(p)) ) {_res=$B._PyPegen.seq_append_to_end(p,$B.helper_functions.CHECK(asdl_seq,$B._PyPegen.seq_append_to_end(p,a,b )),c); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=_gather_142_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (_literal_1=$B._PyPegen.expect_token(p,16)) && (b=expression_rule(p)) ) {_res=$B._PyPegen.seq_append_to_end(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var b; if( (a=_gather_144_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (_literal_1=$B._PyPegen.expect_token(p,35)) && (b=expression_rule(p)) ) {_res=$B._PyPegen.seq_append_to_end(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var a; var b; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (_literal_2=$B._PyPegen.expect_token(p,35)) && (b=expression_rule(p)) ) {_res=$B._PyPegen.seq_append_to_end(p,$B.helper_functions.CHECK(asdl_seq,$B._PyPegen.singleton_seq(p,a )),b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=expression_rule(p)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=expression_rule(p)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; if( (a=_gather_146_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function func_type_comment_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var newline_var; var t; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && (t=$B._PyPegen.expect_token(p,TYPE_COMMENT)) && $B._PyPegen.lookahead(1,_tmp_148_rule,p) ) {_res=t; break;} p.mark=_mark;} if(p.call_invalid_rules){ if(p.error_indicator){return NULL;} var invalid_double_type_comments_var; if( (invalid_double_type_comments_var=invalid_double_type_comments_rule(p)) ) {_res=invalid_double_type_comments_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var type_comment_var; if( (type_comment_var=$B._PyPegen.expect_token(p,TYPE_COMMENT)) ) {_res=type_comment_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_arguments_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_150_var; var _tmp_149_var; var a; if( (_tmp_149_var=_tmp_149_rule(p)) && (a=$B._PyPegen.expect_token(p,12)) && (_gather_150_var=_gather_150_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"iterable argument unpacking follows keyword argument unpacking"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=expression_rule(p)) && (b=for_if_clauses_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (_opt_var=_tmp_152_rule(p),!p.error_indicator) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,$B._PyPegen.get_last_comprehension_item($B.PyPegen.last_item(b,$B.ast.comprehension )),"Generator expression must be parenthesized"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var expression_var; var for_if_clauses_var; if( (a=$B._PyPegen.name_token(p)) && (b=$B._PyPegen.expect_token(p,22)) && (expression_var=expression_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"invalid syntax. Maybe you meant '==' or ':=' instead of '='?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (_opt_var=_tmp_153_rule(p),!p.error_indicator) && (a=$B._PyPegen.name_token(p)) && (b=$B._PyPegen.expect_token(p,22)) && $B._PyPegen.lookahead(1,_tmp_154_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"expected argument value expression"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=args_rule(p)) && (b=for_if_clauses_rule(p)) ) {_res=$B._PyPegen.nonparen_genexp_in_call(p,a,b); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var args_var; var b; if( (args_var=args_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (a=expression_rule(p)) && (b=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,$B._PyPegen.get_last_comprehension_item($B.PyPegen.last_item(b,$B.ast.comprehension )),"Generator expression must be parenthesized"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var args_var; if( (a=args_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (args_var=args_rule(p)) ) {_res=$B._PyPegen.arguments_parsing_error(p,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_kwarg_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; if( (a=_tmp_155_rule(p)) && (b=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"cannot assign to %s",$B.parser_constants.PyBytes_AS_STRING(a.bytes )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var expression_var; var for_if_clauses_var; if( (a=$B._PyPegen.name_token(p)) && (b=$B._PyPegen.expect_token(p,22)) && (expression_var=expression_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"invalid syntax. Maybe you meant '==' or ':=' instead of '='?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( $B._PyPegen.lookahead(0,_tmp_156_rule,p) && (a=expression_rule(p)) && (b=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"expression cannot contain assignment, perhaps you meant \"==\"?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; var expression_var; if( (a=$B._PyPegen.expect_token(p,35)) && (expression_var=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"cannot assign to keyword argument unpacking"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function expression_without_invalid_rule(p) {var _prev_call_invalid=p.call_invalid_rules; p.call_invalid_rules=0; if(p.error_indicator){p.call_invalid_rules=_prev_call_invalid; return NULL;} while(1){var _res=NULL; var _mark=p.mark; if(p.mark==p.fill && $B._PyPegen.fill_token(p)< 0){p.error_indicator=1; p.call_invalid_rules=_prev_call_invalid; return NULL;} var EXTRA={lineno:p.tokens[_mark].lineno,col_offset:p.tokens[_mark].col_offset} { if(p.error_indicator){p.call_invalid_rules=_prev_call_invalid; return NULL;} var _keyword; var _keyword_1; var a; var b; var c; if( (a=disjunction_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,682)) && (b=disjunction_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,686)) && (c=expression_rule(p)) ) {var _token=$B._PyPegen.get_last_nonnwhitespace_token(p); if(_token==NULL){p.call_invalid_rules=_prev_call_invalid; return NULL;} EXTRA.end_lineno=_token.end_lineno; EXTRA.end_col_offset=_token.end_col_offset; _res=new $B._PyAST.IfExp(b,a,c,EXTRA); break;} p.mark=_mark;} { if(p.error_indicator){p.call_invalid_rules=_prev_call_invalid; return NULL;} var disjunction_var; if( (disjunction_var=disjunction_rule(p)) ) {_res=disjunction_var; break;} p.mark=_mark;} { if(p.error_indicator){p.call_invalid_rules=_prev_call_invalid; return NULL;} var lambdef_var; if( (lambdef_var=lambdef_rule(p)) ) {_res=lambdef_var; break;} p.mark=_mark;} _res=NULL; break;} p.call_invalid_rules=_prev_call_invalid; return _res;} function invalid_legacy_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; if( (a=$B._PyPegen.name_token(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,7) && (b=star_expressions_rule(p)) ) {_res=$B._PyPegen.check_legacy_stmt(p,a )? $B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"Missing parentheses in call to '%U'. Did you mean %U(...)?",a. id,a. id):$B.parser_constants.NULL; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_type_param_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var colon; var e; if( (_literal=$B._PyPegen.expect_token(p,16)) && (a=$B._PyPegen.name_token(p)) && (colon=$B._PyPegen.expect_token(p,11)) && (e=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,colon,e.kind==Tuple_kind ? "cannot use bound with TypeVarTuple" :"cannot use constraints with TypeVarTuple"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var colon; var e; if( (_literal=$B._PyPegen.expect_token(p,35)) && (a=$B._PyPegen.name_token(p)) && (colon=$B._PyPegen.expect_token(p,11)) && (e=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,colon,e.kind==Tuple_kind ? "cannot use bound with ParamSpec" :"cannot use constraints with ParamSpec"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var string_var; var string_var_1; if( (string_var=$B._PyPegen.string_token(p)) && (a=_loop1_157_rule(p)) && (string_var_1=$B._PyPegen.string_token(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,$B.PyPegen.first_item(a,$B.ast.expr ),$B.PyPegen.last_item(a,$B.ast.expr ),"invalid syntax. Is this intended to be part of the string?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( $B._PyPegen.lookahead(0,_tmp_158_rule,p) && (a=disjunction_rule(p)) && (b=expression_without_invalid_rule(p)) ) {_res=$B._PyPegen.check_legacy_stmt(p,a )? $B.parser_constants.NULL :p.tokens[p.mark-1].level==0 ? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"invalid syntax. Perhaps you forgot a comma?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var a; var b; if( (a=disjunction_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,682)) && (b=disjunction_rule(p)) && $B._PyPegen.lookahead(0,_tmp_159_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"expected 'else' after 'if' expression"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; var b; if( (a=disjunction_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,682)) && (b=disjunction_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,686)) && $B._PyPegen.lookahead(0,expression_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"expected expression after 'else', but statement is given"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var a; var b; var c; if( (a=_tmp_160_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,682)) && (b=disjunction_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,686)) && (c=simple_stmt_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expected expression before 'if', but statement is given"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=$B._PyPegen.expect_token(p,621)) && (_opt_var=lambda_params_rule(p),!p.error_indicator) && (b=$B._PyPegen.expect_token(p,11)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,FSTRING_MIDDLE) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"f-string: lambda expressions are not allowed without parentheses"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var b; if( (a=$B._PyPegen.expect_token(p,621)) && (_opt_var=lambda_params_rule(p),!p.error_indicator) && (b=$B._PyPegen.expect_token(p,11)) && $B._PyPegen.lookahead_with_int(1,$B._PyPegen.expect_token,p,TSTRING_MIDDLE) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"t-string: lambda expressions are not allowed without parentheses"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_named_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res={value:NULL}; if($B._PyPegen.is_memoized(p,invalid_named_expression_type,_res)){return _res.value;} _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var expression_var; if( (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,53)) && (expression_var=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use assignment expressions with %s",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var b; if( (a=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=bitwise_or_rule(p)) && $B._PyPegen.lookahead(0,_tmp_161_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"invalid syntax. Maybe you meant '==' or ':=' instead of '='?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; var bitwise_or_var; if( $B._PyPegen.lookahead(0,_tmp_162_rule,p) && (a=bitwise_or_rule(p)) && (b=$B._PyPegen.expect_token(p,22)) && (bitwise_or_var=bitwise_or_rule(p)) && $B._PyPegen.lookahead(0,_tmp_163_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot assign to %s here. Maybe you meant '==' instead of '='?",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} $B._PyPegen.insert_memo(p,_mark,invalid_named_expression_type,_res); return _res;} function invalid_assignment_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var expression_var; if( (a=invalid_ann_assign_target_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (expression_var=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"only single target (not %s) can be annotated",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _loop0_164_var; var a; var expression_var; if( (a=star_named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (_loop0_164_var=_loop0_164_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (expression_var=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"only single target (not tuple) can be annotated"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var expression_var; if( (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (expression_var=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"illegal target for annotation"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_165_var; var a; if( (_loop0_165_var=_loop0_165_rule(p)) && (a=star_expressions_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_INVALID_TARGET(p,$B.parser_constants.STAR_TARGETS,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_166_var; var a; if( (_loop0_166_var=_loop0_166_rule(p)) && (a=yield_expr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"assignment to yield expression not possible"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var annotated_rhs_var; var augassign_var; if( (a=star_expressions_rule(p)) && (augassign_var=augassign_rule(p)) && (annotated_rhs_var=annotated_rhs_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"'%s' is an illegal expression for augmented assignment",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_ann_assign_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var list_var; if( (list_var=list_rule(p)) ) {_res=list_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var tuple_var; if( (tuple_var=tuple_rule(p)) ) {_res=tuple_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=invalid_ann_assign_target_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_del_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; if( (_keyword=$B._PyPegen.expect_token(p,625)) && (a=star_expressions_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_INVALID_TARGET(p,$B.parser_constants.DEL_TARGETS,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_comprehension_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_167_var; var a; var for_if_clauses_var; if( (_tmp_167_var=_tmp_167_rule(p)) && (a=starred_expression_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"iterable unpacking cannot be used in comprehension"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _tmp_168_var; var a; var b; var for_if_clauses_var; if( (_tmp_168_var=_tmp_168_rule(p)) && (a=star_named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (b=star_named_expressions_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,$B.PyPegen.last_item(b,$B.ast.expr ),"did you forget parentheses around the comprehension target?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_169_var; var a; var b; var for_if_clauses_var; if( (_tmp_169_var=_tmp_169_rule(p)) && (a=star_named_expression_rule(p)) && (b=$B._PyPegen.expect_token(p,12)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"did you forget parentheses around the comprehension target?"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_dict_comprehension_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var bitwise_or_var; var for_if_clauses_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,35)) && (bitwise_or_var=bitwise_or_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,26)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"dict unpacking cannot be used in dict comprehension"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_parameters_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=$B._PyPegen.expect_token(p,17)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"at least one argument must precede /"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop0_171_var; var _tmp_170_var; var a; if( (_tmp_170_var=_tmp_170_rule(p)) && (_loop0_171_var=_loop0_171_rule(p)) && (a=$B._PyPegen.expect_token(p,17)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"/ may appear only once"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop0_172_var; var _opt_var; UNUSED(_opt_var); var a; var invalid_parameters_helper_var; if( (_opt_var=slash_no_default_rule(p),!p.error_indicator) && (_loop0_172_var=_loop0_172_rule(p)) && (invalid_parameters_helper_var=invalid_parameters_helper_rule(p)) && (a=param_no_default_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"parameter without a default follows parameter with a default"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop0_173_var; var _loop1_174_var; var _opt_var; UNUSED(_opt_var); var a; var b; if( (_loop0_173_var=_loop0_173_rule(p)) && (a=$B._PyPegen.expect_token(p,7)) && (_loop1_174_var=_loop1_174_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (b=$B._PyPegen.expect_token(p,8)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"Function parameters cannot be parenthesized"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_176_var; var _loop0_178_var; var _opt_var; UNUSED(_opt_var); var _tmp_177_var; var a; if( (_opt_var=_tmp_175_rule(p),!p.error_indicator) && (_loop0_176_var=_loop0_176_rule(p)) && (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_177_var=_tmp_177_rule(p)) && (_loop0_178_var=_loop0_178_rule(p)) && (a=$B._PyPegen.expect_token(p,17)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"/ must be ahead of *"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop1_179_var; var a; if( (_loop1_179_var=_loop1_179_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (a=$B._PyPegen.expect_token(p,16)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expected comma between / and *"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_default_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=$B._PyPegen.expect_token(p,22)) && $B._PyPegen.lookahead(1,_tmp_180_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expected default value expression"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_star_etc_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_181_var; var a; if( (a=$B._PyPegen.expect_token(p,16)) && (_tmp_181_var=_tmp_181_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"named arguments must follow bare *"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var type_comment_var; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (type_comment_var=$B._PyPegen.expect_token(p,TYPE_COMMENT)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"bare * has associated type comment"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var param_var; if( (_literal=$B._PyPegen.expect_token(p,16)) && (param_var=param_rule(p)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"var-positional argument cannot have default value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_183_var; var _tmp_182_var; var _tmp_184_var; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_182_var=_tmp_182_rule(p)) && (_loop0_183_var=_loop0_183_rule(p)) && (a=$B._PyPegen.expect_token(p,16)) && (_tmp_184_var=_tmp_184_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"* argument may appear only once"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_kwds_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (param_var=param_rule(p)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"var-keyword argument cannot have default value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (param_var=param_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (a=param_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"arguments cannot follow var-keyword argument"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (param_var=param_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (a=_tmp_185_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"arguments cannot follow var-keyword argument"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_parameters_helper_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=slash_with_default_rule(p)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop1_186_var; if( (_loop1_186_var=_loop1_186_rule(p)) ) {_res=_loop1_186_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_lambda_parameters_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (a=$B._PyPegen.expect_token(p,17)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"at least one argument must precede /"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop0_188_var; var _tmp_187_var; var a; if( (_tmp_187_var=_tmp_187_rule(p)) && (_loop0_188_var=_loop0_188_rule(p)) && (a=$B._PyPegen.expect_token(p,17)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"/ may appear only once"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop0_189_var; var _opt_var; UNUSED(_opt_var); var a; var invalid_lambda_parameters_helper_var; if( (_opt_var=lambda_slash_no_default_rule(p),!p.error_indicator) && (_loop0_189_var=_loop0_189_rule(p)) && (invalid_lambda_parameters_helper_var=invalid_lambda_parameters_helper_rule(p)) && (a=lambda_param_no_default_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"parameter without a default follows parameter with a default"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _gather_191_var; var _loop0_190_var; var _opt_var; UNUSED(_opt_var); var a; var b; if( (_loop0_190_var=_loop0_190_rule(p)) && (a=$B._PyPegen.expect_token(p,7)) && (_gather_191_var=_gather_191_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (b=$B._PyPegen.expect_token(p,8)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"Lambda expression parameters cannot be parenthesized"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_194_var; var _loop0_196_var; var _opt_var; UNUSED(_opt_var); var _tmp_195_var; var a; if( (_opt_var=_tmp_193_rule(p),!p.error_indicator) && (_loop0_194_var=_loop0_194_rule(p)) && (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_195_var=_tmp_195_rule(p)) && (_loop0_196_var=_loop0_196_rule(p)) && (a=$B._PyPegen.expect_token(p,17)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"/ must be ahead of *"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop1_197_var; var a; if( (_loop1_197_var=_loop1_197_rule(p)) && (_literal=$B._PyPegen.expect_token(p,17)) && (a=$B._PyPegen.expect_token(p,16)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expected comma between / and *"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_lambda_parameters_helper_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=lambda_slash_with_default_rule(p)) ) {_res=$B._PyPegen.singleton_seq(p,a); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _loop1_198_var; if( (_loop1_198_var=_loop1_198_rule(p)) ) {_res=_loop1_198_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_lambda_star_etc_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _tmp_199_var; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_199_var=_tmp_199_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"named arguments must follow bare *"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var lambda_param_var; if( (_literal=$B._PyPegen.expect_token(p,16)) && (lambda_param_var=lambda_param_rule(p)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"var-positional argument cannot have default value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _loop0_201_var; var _tmp_200_var; var _tmp_202_var; var a; if( (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_200_var=_tmp_200_rule(p)) && (_loop0_201_var=_loop0_201_rule(p)) && (a=$B._PyPegen.expect_token(p,16)) && (_tmp_202_var=_tmp_202_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"* argument may appear only once"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_lambda_kwds_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var lambda_param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (lambda_param_var=lambda_param_rule(p)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"var-keyword argument cannot have default value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var lambda_param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (lambda_param_var=lambda_param_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (a=lambda_param_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"arguments cannot follow var-keyword argument"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var lambda_param_var; if( (_literal=$B._PyPegen.expect_token(p,35)) && (lambda_param_var=lambda_param_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (a=_tmp_203_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"arguments cannot follow var-keyword argument"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_double_type_comments_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var indent_var; var newline_var; var newline_var_1; var type_comment_var; var type_comment_var_1; if( (type_comment_var=$B._PyPegen.expect_token(p,TYPE_COMMENT)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && (type_comment_var_1=$B._PyPegen.expect_token(p,TYPE_COMMENT)) && (newline_var_1=$B._PyPegen.expect_token(p,NEWLINE)) && (indent_var=$B._PyPegen.expect_token(p,INDENT)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"Cannot have two type comments on def"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_with_item_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; var expression_var; if( (expression_var=expression_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && (a=expression_rule(p)) && $B._PyPegen.lookahead(1,_tmp_204_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_INVALID_TARGET(p,$B.parser_constants.STAR_TARGETS,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_for_if_clause_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _opt_var; UNUSED(_opt_var); var _tmp_205_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,694)) && (_tmp_205_var=_tmp_205_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,695) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"'in' expected after for-loop variables"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_for_target_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _opt_var; UNUSED(_opt_var); var a; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,694)) && (a=star_expressions_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_INVALID_TARGET(p,$B.parser_constants.FOR_TARGETS,a); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_group_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=starred_expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use starred expression here"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var a; var expression_var; if( (_literal=$B._PyPegen.expect_token(p,7)) && (a=$B._PyPegen.expect_token(p,35)) && (expression_var=expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use double starred expression here"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_import_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_206_var; var _keyword; var a; var dotted_name_var; if( (a=$B._PyPegen.expect_token(p,634)) && (_gather_206_var=_gather_206_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,633)) && (dotted_name_var=dotted_name_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"Did you mean to use 'from ... import ...' instead?"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var token; if( (_keyword=$B._PyPegen.expect_token(p,634)) && (token=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,token,"Expected one or more names after 'import'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_dotted_as_name_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; var dotted_name_var; if( (dotted_name_var=dotted_name_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && $B._PyPegen.lookahead(0,_tmp_208_rule,p) && (a=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use %s as import target",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_import_from_as_name_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; var name_var; if( (name_var=$B._PyPegen.name_token(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && $B._PyPegen.lookahead(0,_tmp_209_rule,p) && (a=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use %s as import target",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_import_from_targets_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var import_from_as_names_var; var newline_var; if( (import_from_as_names_var=import_from_as_names_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"trailing comma not allowed without surrounding parentheses"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var token; if( (token=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,token,"Expected one or more names after 'import'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_with_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_210_var; var _keyword; var _opt_var; UNUSED(_opt_var); var newline_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,647)) && (_gather_210_var=_gather_210_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _gather_212_var; var _keyword; var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var newline_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,647)) && (_literal=$B._PyPegen.expect_token(p,7)) && (_gather_212_var=_gather_212_rule(p)) && (_opt_var_1=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_with_stmt_indent_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_214_var; var _literal; var _opt_var; UNUSED(_opt_var); var a; var newline_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (a=$B._PyPegen.expect_token(p,647)) && (_gather_214_var=_gather_214_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'with' statement on line %d",a.lineno); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _gather_216_var; var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var a; var newline_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (a=$B._PyPegen.expect_token(p,647)) && (_literal=$B._PyPegen.expect_token(p,7)) && (_gather_216_var=_gather_216_rule(p)) && (_opt_var_1=$B._PyPegen.expect_token(p,12),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'with' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_try_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var newline_var; if( (a=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'try' statement on line %d",a.lineno); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var block_var; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_token(p,11)) && (block_var=block_rule(p)) && $B._PyPegen.lookahead(0,_tmp_218_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected 'except' or 'finally' block"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var _loop0_219_var; var _loop1_220_var; var _opt_var; UNUSED(_opt_var); var a; var b; var expression_var; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_token(p,11)) && (_loop0_219_var=_loop0_219_rule(p)) && (_loop1_220_var=_loop1_220_rule(p)) && (a=$B._PyPegen.expect_token(p,677)) && (b=$B._PyPegen.expect_token(p,16)) && (expression_var=expression_rule(p)) && (_opt_var=_tmp_221_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"cannot have both 'except' and 'except*' on the same 'try'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var _loop0_222_var; var _loop1_223_var; var _opt_var; UNUSED(_opt_var); var a; if( (_keyword=$B._PyPegen.expect_token(p,656)) && (_literal=$B._PyPegen.expect_token(p,11)) && (_loop0_222_var=_loop0_222_rule(p)) && (_loop1_223_var=_loop1_223_rule(p)) && (a=$B._PyPegen.expect_token(p,677)) && (_opt_var=_tmp_224_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot have both 'except' and 'except*' on the same 'try'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_except_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var a; var expressions_var; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (expressions_var=expressions_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"multiple exception types must be parenthesized when using 'as'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var a; var expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (expression_var=expression_rule(p)) && (_opt_var=_tmp_225_rule(p),!p.error_indicator) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var a; var block_var; var expression_var; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (expression_var=expression_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (a=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (block_var=block_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use except statement with %s",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_except_star_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var _literal_2; var a; var expressions_var; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (a=expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,12)) && (expressions_var=expressions_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) && (_literal_2=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"multiple exception types must be parenthesized when using 'as'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var a; var expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (expression_var=expression_rule(p)) && (_opt_var=_tmp_226_rule(p),!p.error_indicator) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _tmp_227_var; var a; if( (a=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (_tmp_227_var=_tmp_227_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected one or more exception types"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var _literal_1; var a; var block_var; var expression_var; if( (_keyword=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (expression_var=expression_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,680)) && (a=expression_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (block_var=block_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use except* statement with %s",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_finally_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var newline_var; if( (a=$B._PyPegen.expect_token(p,673)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'finally' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_except_stmt_indent_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var a; var expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (expression_var=expression_rule(p)) && (_opt_var=_tmp_228_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'except' statement on line %d",a.lineno); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'except' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_except_star_stmt_indent_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); var a; var expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,677)) && (_literal=$B._PyPegen.expect_token(p,16)) && (expression_var=expression_rule(p)) && (_opt_var=_tmp_229_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'except*' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_match_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var newline_var; var subject_expr_var; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"match")) && (subject_expr_var=subject_expr_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.CHECK_VERSION(NULL,10,"expected ':'",$B.helper_functions.RAISE_SYNTAX_ERROR(p,"Pattern matching is" )); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var newline_var; var subject; if( (a=$B._PyPegen.expect_soft_keyword(p,"match")) && (subject=subject_expr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'match' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_case_block_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _opt_var; UNUSED(_opt_var); var newline_var; var patterns_var; if( (_keyword=$B._PyPegen.expect_soft_keyword(p,"case")) && (patterns_var=patterns_rule(p)) && (_opt_var=guard_rule(p),!p.error_indicator) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var a; var newline_var; var patterns_var; if( (a=$B._PyPegen.expect_soft_keyword(p,"case")) && (patterns_var=patterns_rule(p)) && (_opt_var=guard_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'case' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_as_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var a; var or_pattern_var; if( (or_pattern_var=or_pattern_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && (a=$B._PyPegen.expect_soft_keyword(p,"_")) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use '_' as a target"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var a; var or_pattern_var; if( (or_pattern_var=or_pattern_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,680)) && (a=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"cannot use %s as pattern target",$B._PyPegen.get_expr_name(a )); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_class_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var name_or_attr_var; if( (name_or_attr_var=name_or_attr_rule(p)) && (_literal=$B._PyPegen.expect_token(p,7)) && (a=invalid_class_argument_pattern_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,$B.PyPegen.first_item(a,$B.ast.pattern ),$B.PyPegen.last_item(a,$B.ast.pattern ),"positional patterns follow keyword patterns"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_class_argument_pattern_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var a; var keyword_patterns_var; if( (_opt_var=_tmp_230_rule(p),!p.error_indicator) && (keyword_patterns_var=keyword_patterns_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (a=positional_patterns_rule(p)) ) {_res=a; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_if_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var named_expression_var; var newline_var; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (named_expression_var=named_expression_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var a_1; var newline_var; if( (a=$B._PyPegen.expect_token(p,682)) && (a_1=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'if' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_elif_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var named_expression_var; var newline_var; if( (_keyword=$B._PyPegen.expect_token(p,687)) && (named_expression_var=named_expression_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var named_expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,687)) && (named_expression_var=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'elif' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_else_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var newline_var; if( (a=$B._PyPegen.expect_token(p,686)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'else' statement on line %d",a.lineno); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _literal; var block_var; if( (_keyword=$B._PyPegen.expect_token(p,686)) && (_literal=$B._PyPegen.expect_token(p,11)) && (block_var=block_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,687)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"'elif' block follows an 'else' block"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_while_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var named_expression_var; var newline_var; if( (_keyword=$B._PyPegen.expect_token(p,689)) && (named_expression_var=named_expression_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var named_expression_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,689)) && (named_expression_var=named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'while' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_for_stmt_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _keyword_1; var _opt_var; UNUSED(_opt_var); var newline_var; var star_expressions_var; var star_targets_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,694)) && (star_targets_var=star_targets_rule(p)) && (_keyword_1=$B._PyPegen.expect_token(p,695)) && (star_expressions_var=star_expressions_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _opt_var; UNUSED(_opt_var); var a; var newline_var; var star_expressions_var; var star_targets_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (a=$B._PyPegen.expect_token(p,694)) && (star_targets_var=star_targets_rule(p)) && (_keyword=$B._PyPegen.expect_token(p,695)) && (star_expressions_var=star_expressions_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after 'for' statement on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_def_raw_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var _opt_var_2; UNUSED(_opt_var_2); var _opt_var_3; UNUSED(_opt_var_3); var a; var name_var; var newline_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (a=$B._PyPegen.expect_token(p,699)) && (name_var=$B._PyPegen.name_token(p)) && (_opt_var_1=type_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,7)) && (_opt_var_2=params_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_opt_var_3=_tmp_231_rule(p),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after function definition on line %d",a.lineno); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; var _literal; var _literal_1; var _literal_2; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var _opt_var_2; UNUSED(_opt_var_2); var _opt_var_3; UNUSED(_opt_var_3); var _opt_var_4; UNUSED(_opt_var_4); var block_var; var name_var; if( (_opt_var=$B._PyPegen.expect_token(p,698),!p.error_indicator) && (_keyword=$B._PyPegen.expect_token(p,699)) && (name_var=$B._PyPegen.name_token(p)) && (_opt_var_1=type_params_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_forced_token(p,7,"(")) && (_opt_var_2=params_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) && (_opt_var_3=_tmp_232_rule(p),!p.error_indicator) && (_literal_2=$B._PyPegen.expect_forced_token(p,11,":")) && (_opt_var_4=func_type_comment_rule(p),!p.error_indicator) && (block_var=block_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_opt_var,_keyword,name_var,_opt_var_1,_literal,_opt_var_2,_literal_1,_opt_var_3,_literal_2,_opt_var_4,block_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_class_def_raw_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var name_var; var newline_var; if( (_keyword=$B._PyPegen.expect_token(p,701)) && (name_var=$B._PyPegen.name_token(p)) && (_opt_var=type_params_rule(p),!p.error_indicator) && (_opt_var_1=_tmp_233_rule(p),!p.error_indicator) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"expected ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var a; var name_var; var newline_var; if( (a=$B._PyPegen.expect_token(p,701)) && (name_var=$B._PyPegen.name_token(p)) && (_opt_var=type_params_rule(p),!p.error_indicator) && (_opt_var_1=_tmp_234_rule(p),!p.error_indicator) && (_literal=$B._PyPegen.expect_token(p,11)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,INDENT) ) {_res=$B.helper_functions.RAISE_INDENTATION_ERROR(p,"expected an indented block after class definition on line %d",a.lineno); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_double_starred_kvpairs_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_235_var; var _literal; var invalid_kvpair_var; if( (_gather_235_var=_gather_235_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (invalid_kvpair_var=invalid_kvpair_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_gather_235_var,_literal,invalid_kvpair_var); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var bitwise_or_var; var expression_var; if( (expression_var=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (a=$B._PyPegen.expect_token(p,16)) && (bitwise_or_var=bitwise_or_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"cannot use a starred expression in a dictionary value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var expression_var; if( (expression_var=expression_rule(p)) && (a=$B._PyPegen.expect_token(p,11)) && $B._PyPegen.lookahead(1,_tmp_237_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expression expected after dictionary key and ':'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_kvpair_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; if( (a=expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,11) ) {_res=$B.helper_functions.RAISE_ERROR_KNOWN_LOCATION(p,$B.parser_constants.PyExc_SyntaxError,a.lineno,a.end_col_offset-1,a.end_lineno,-1,"':' expected after dictionary key"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; var bitwise_or_var; var expression_var; if( (expression_var=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,11)) && (a=$B._PyPegen.expect_token(p,16)) && (bitwise_or_var=bitwise_or_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,a,"cannot use a starred expression in a dictionary value"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var expression_var; if( (expression_var=expression_rule(p)) && (a=$B._PyPegen.expect_token(p,11)) && $B._PyPegen.lookahead(1,_tmp_238_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"expression expected after dictionary key and ':'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_starred_expression_unpacking_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; var b; var expression_var; if( (a=$B._PyPegen.expect_token(p,16)) && (expression_var=expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) && (b=expression_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"cannot assign to iterable argument unpacking"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_starred_expression_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,16)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR(p,"Invalid star expression"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_fstring_replacement_field_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"f-string: valid expression required before '='"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,54)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"f-string: valid expression required before '!'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"f-string: valid expression required before ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,26)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"f-string: valid expression required before '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,25)) && $B._PyPegen.lookahead(0,annotated_rhs_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting a valid expression after '{'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && $B._PyPegen.lookahead(0,_tmp_239_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting '=', or '!', or ':', or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,22)) && $B._PyPegen.lookahead(0,_tmp_240_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting '!', or ':', or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var annotated_rhs_var; var invalid_fstring_conversion_character_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (invalid_fstring_conversion_character_var=invalid_fstring_conversion_character_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,annotated_rhs_var,_opt_var,invalid_fstring_conversion_character_var); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_241_rule(p),!p.error_indicator) && $B._PyPegen.lookahead(0,_tmp_242_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting ':' or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _loop0_244_var; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_243_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (_loop0_244_var=_loop0_244_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,26) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting '}', or format specs"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_245_rule(p),!p.error_indicator) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,26) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: expecting '}'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_fstring_conversion_character_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) && $B._PyPegen.lookahead(1,_tmp_246_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: missing conversion character"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) && $B._PyPegen.lookahead_with_name(0,$B._PyPegen.name_token,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"f-string: invalid conversion character"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_tstring_replacement_field_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,22)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"t-string: valid expression required before '='"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,54)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"t-string: valid expression required before '!'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,11)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"t-string: valid expression required before ':'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var a; if( (_literal=$B._PyPegen.expect_token(p,25)) && (a=$B._PyPegen.expect_token(p,26)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_LOCATION(p,a,"t-string: valid expression required before '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,25)) && $B._PyPegen.lookahead(0,annotated_rhs_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting a valid expression after '{'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && $B._PyPegen.lookahead(0,_tmp_247_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting '=', or '!', or ':', or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,22)) && $B._PyPegen.lookahead(0,_tmp_248_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting '!', or ':', or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var annotated_rhs_var; var invalid_tstring_conversion_character_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (invalid_tstring_conversion_character_var=invalid_tstring_conversion_character_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,annotated_rhs_var,_opt_var,invalid_tstring_conversion_character_var); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_249_rule(p),!p.error_indicator) && $B._PyPegen.lookahead(0,_tmp_250_rule,p) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting ':' or '}'"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _loop0_252_var; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_251_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,11)) && (_loop0_252_var=_loop0_252_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,26) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting '}', or format specs"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _opt_var; UNUSED(_opt_var); var _opt_var_1; UNUSED(_opt_var_1); var annotated_rhs_var; if( (_literal=$B._PyPegen.expect_token(p,25)) && (annotated_rhs_var=annotated_rhs_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,22),!p.error_indicator) && (_opt_var_1=_tmp_253_rule(p),!p.error_indicator) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,26) ) {_res=$B.helper_functions.$B._PyPegen.PyErr_Occurred()? $B.parser_constants.NULL :$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: expecting '}'"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_tstring_conversion_character_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) && $B._PyPegen.lookahead(1,_tmp_254_rule,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: missing conversion character"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) && $B._PyPegen.lookahead_with_name(0,$B._PyPegen.name_token,p) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN(p,"t-string: invalid conversion character"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_string_tstring_concat_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var a; var b; if( (a=_loop1_255_rule(p)) && (b=tstring_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,$B.PyPegen.last_item(a,$B.ast.expr ),b,"cannot mix t-string literals with string or bytes literals"); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var a; var b; if( (a=_loop1_256_rule(p)) && (b=_tmp_257_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,$B.PyPegen.last_item(a,$B.ast.expr ),b,"cannot mix t-string literals with string or bytes literals"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_arithmetic_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_258_var; var a; var b; var sum_var; if( (sum_var=sum_rule(p)) && (_tmp_258_var=_tmp_258_rule(p)) && (a=$B._PyPegen.expect_token(p,703)) && (b=inversion_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"'not' after an operator must be parenthesized"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_factor_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_259_var; var a; var b; if( (_tmp_259_var=_tmp_259_rule(p)) && (a=$B._PyPegen.expect_token(p,703)) && (b=factor_rule(p)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_KNOWN_RANGE(p,a,b,"'not' after an operator must be parenthesized"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function invalid_type_params_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var token; if( (_literal=$B._PyPegen.expect_token(p,9)) && (token=$B._PyPegen.expect_token(p,10)) ) {_res=$B.helper_functions.RAISE_SYNTAX_ERROR_STARTING_FROM(p,token,"Type parameter list cannot be empty"); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_1_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var newline_var; while( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_2_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var newline_var; while( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_3_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var statement_var; while( (statement_var=statement_rule(p)) ) {_res=statement_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_5_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,13)) && (elem=simple_stmt_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_4_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=simple_stmt_rule(p)) && (seq=_loop0_5_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_6_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,634)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,633)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_7_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,699)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,49)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,698)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_8_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,701)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,49)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_9_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,647)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,698)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_10_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,694)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,698)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_11_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var d; if( (_literal=$B._PyPegen.expect_token(p,22)) && (d=annotated_rhs_rule(p)) ) {_res=d; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_12_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var b; if( (_literal=$B._PyPegen.expect_token(p,7)) && (b=single_target_rule(p)) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=b; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var single_subscript_attribute_target_var; if( (single_subscript_attribute_target_var=single_subscript_attribute_target_rule(p)) ) {_res=single_subscript_attribute_target_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_13_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var d; if( (_literal=$B._PyPegen.expect_token(p,22)) && (d=annotated_rhs_rule(p)) ) {_res=d; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_14_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_260_var; while( (_tmp_260_var=_tmp_260_rule(p)) ) {_res=_tmp_260_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_15_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var z; if( (_keyword=$B._PyPegen.expect_token(p,633)) && (z=expression_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_17_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=$B._PyPegen.name_token(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_16_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=$B._PyPegen.name_token(p)) && (seq=_loop0_17_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_19_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=$B._PyPegen.name_token(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_18_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=$B._PyPegen.name_token(p)) && (seq=_loop0_19_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_20_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,13)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_21_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var z; if( (_literal=$B._PyPegen.expect_token(p,12)) && (z=expression_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_22_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_261_var; while( (_tmp_261_var=_tmp_261_rule(p)) ) {_res=_tmp_261_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_23_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_262_var; while( (_tmp_262_var=_tmp_262_rule(p)) ) {_res=_tmp_262_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_25_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=import_from_as_name_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_24_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=import_from_as_name_rule(p)) && (seq=_loop0_25_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_26_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var z; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (z=$B._PyPegen.name_token(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_28_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=dotted_as_name_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_27_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=dotted_as_name_rule(p)) && (seq=_loop0_28_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_29_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var z; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (z=$B._PyPegen.name_token(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_30_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_263_var; while( (_tmp_263_var=_tmp_263_rule(p)) ) {_res=_tmp_263_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_31_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var z; if( (_literal=$B._PyPegen.expect_token(p,7)) && (z=arguments_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_32_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var z; if( (_literal=$B._PyPegen.expect_token(p,51)) && (z=expression_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_33_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var z; if( (_literal=$B._PyPegen.expect_token(p,51)) && (z=expression_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_34_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_35_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_36_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_37_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_38_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_39_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_40_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_41_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_42_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_43_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_44_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_45_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_46_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_47_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_48_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_50_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=with_item_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_49_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=with_item_rule(p)) && (seq=_loop0_50_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_52_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=with_item_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_51_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=with_item_rule(p)) && (seq=_loop0_52_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_54_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=with_item_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_53_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=with_item_rule(p)) && (seq=_loop0_54_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_56_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=with_item_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_55_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=with_item_rule(p)) && (seq=_loop0_56_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_57_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_58_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var except_block_var; while( (except_block_var=except_block_rule(p)) ) {_res=except_block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_59_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var except_star_block_var; while( (except_star_block_var=except_star_block_rule(p)) ) {_res=except_star_block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_60_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var case_block_var; while( (case_block_var=case_block_rule(p)) ) {_res=case_block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_62_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,18)) && (elem=closed_pattern_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_61_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=closed_pattern_rule(p)) && (seq=_loop0_62_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_63_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,14)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,15)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_64_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,14)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,15)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_65_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var string_var; if( (string_var=$B._PyPegen.string_token(p)) ) {_res=string_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var fstring_start_var; if( (fstring_start_var=$B._PyPegen.expect_token(p,FSTRING_START)) ) {_res=fstring_start_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var tstring_start_var; if( (tstring_start_var=$B._PyPegen.expect_token(p,TSTRING_START)) ) {_res=tstring_start_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_66_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,23)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,7)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_67_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,23)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,7)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_69_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=maybe_star_pattern_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_68_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=maybe_star_pattern_rule(p)) && (seq=_loop0_69_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_71_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=key_value_pattern_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_70_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=key_value_pattern_rule(p)) && (seq=_loop0_71_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_72_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var literal_expr_var; if( (literal_expr_var=literal_expr_rule(p)) ) {_res=literal_expr_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var attr_var; if( (attr_var=attr_rule(p)) ) {_res=attr_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_74_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=pattern_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_73_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=pattern_rule(p)) && (seq=_loop0_74_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_76_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=keyword_pattern_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_75_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=keyword_pattern_rule(p)) && (seq=_loop0_76_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_78_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=type_param_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_77_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=type_param_rule(p)) && (seq=_loop0_78_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_79_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_264_var; while( (_tmp_264_var=_tmp_264_rule(p)) ) {_res=_tmp_264_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_80_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_265_var; while( (_tmp_265_var=_tmp_265_rule(p)) ) {_res=_tmp_265_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_82_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=star_named_expression_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_81_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=star_named_expression_rule(p)) && (seq=_loop0_82_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_83_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_266_var; while( (_tmp_266_var=_tmp_266_rule(p)) ) {_res=_tmp_266_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_84_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_267_var; while( (_tmp_267_var=_tmp_267_rule(p)) ) {_res=_tmp_267_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_85_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var compare_op_bitwise_or_pair_var; while( (compare_op_bitwise_or_pair_var=compare_op_bitwise_or_pair_rule(p)) ) {_res=compare_op_bitwise_or_pair_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_86_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var tok; if( (tok=$B._PyPegen.expect_token(p,28)) ) {_res=$B._PyPegen.check_barry_as_flufl(p,tok)? $B.parser_constants.NULL :tok; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_88_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_268_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_87_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_268_rule(p)) && (seq=_loop0_88_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_89_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var d; if( (_literal=$B._PyPegen.expect_token(p,11)) && (d=expression_rule(p),!p.error_indicator) ) {_res=d; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_90_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var string_var; if( (string_var=$B._PyPegen.string_token(p)) ) {_res=string_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var fstring_start_var; if( (fstring_start_var=$B._PyPegen.expect_token(p,FSTRING_START)) ) {_res=fstring_start_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var tstring_start_var; if( (tstring_start_var=$B._PyPegen.expect_token(p,TSTRING_START)) ) {_res=tstring_start_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_91_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var tuple_var; if( (tuple_var=tuple_rule(p)) ) {_res=tuple_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var group_var; if( (group_var=group_rule(p)) ) {_res=group_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var genexp_var; if( (genexp_var=genexp_rule(p)) ) {_res=genexp_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_92_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var list_var; if( (list_var=list_rule(p)) ) {_res=list_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var listcomp_var; if( (listcomp_var=listcomp_rule(p)) ) {_res=listcomp_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_93_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var dict_var; if( (dict_var=dict_rule(p)) ) {_res=dict_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var set_var; if( (set_var=set_rule(p)) ) {_res=set_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var dictcomp_var; if( (dictcomp_var=dictcomp_rule(p)) ) {_res=dictcomp_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var setcomp_var; if( (setcomp_var=setcomp_rule(p)) ) {_res=setcomp_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_94_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var yield_expr_var; if( (yield_expr_var=yield_expr_rule(p)) ) {_res=yield_expr_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var named_expression_var; if( (named_expression_var=named_expression_rule(p)) ) {_res=named_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_95_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_96_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_97_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_98_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_99_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_100_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_101_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_102_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_103_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_104_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_105_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_106_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_107_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_108_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_109_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var fstring_format_spec_var; while( (fstring_format_spec_var=fstring_format_spec_rule(p)) ) {_res=fstring_format_spec_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_110_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var fstring_middle_var; while( (fstring_middle_var=fstring_middle_rule(p)) ) {_res=fstring_middle_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_111_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var tstring_format_spec_var; while( (tstring_format_spec_var=tstring_format_spec_rule(p)) ) {_res=tstring_format_spec_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_112_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var tstring_middle_var; while( (tstring_middle_var=tstring_middle_rule(p)) ) {_res=tstring_middle_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_113_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_269_var; while( (_tmp_269_var=_tmp_269_rule(p)) ) {_res=_tmp_269_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_114_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var tstring_var; while( (tstring_var=tstring_rule(p)) ) {_res=tstring_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_115_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var y; var z; if( (y=star_named_expression_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (z=star_named_expressions_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.seq_insert_in_front(p,y,z); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_117_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=double_starred_kvpair_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_116_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=double_starred_kvpair_rule(p)) && (seq=_loop0_117_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_118_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var for_if_clause_var; while( (for_if_clause_var=for_if_clause_rule(p)) ) {_res=for_if_clause_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop0_119_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_270_var; while( (_tmp_270_var=_tmp_270_rule(p)) ) {_res=_tmp_270_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_120_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_271_var; while( (_tmp_271_var=_tmp_271_rule(p)) ) {_res=_tmp_271_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_121_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var assignment_expression_var; if( (assignment_expression_var=assignment_expression_rule(p)) ) {_res=assignment_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,53) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_123_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_272_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_122_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_272_rule(p)) && (seq=_loop0_123_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_124_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var k; if( (_literal=$B._PyPegen.expect_token(p,12)) && (k=kwargs_rule(p)) ) {_res=k; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_126_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=kwarg_or_starred_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_125_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=kwarg_or_starred_rule(p)) && (seq=_loop0_126_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_128_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=kwarg_or_double_starred_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_127_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=kwarg_or_double_starred_rule(p)) && (seq=_loop0_128_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_130_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=kwarg_or_starred_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_129_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=kwarg_or_starred_rule(p)) && (seq=_loop0_130_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_132_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=kwarg_or_double_starred_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_131_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=kwarg_or_double_starred_rule(p)) && (seq=_loop0_132_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_133_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_273_var; while( (_tmp_273_var=_tmp_273_rule(p)) ) {_res=_tmp_273_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_135_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=star_target_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_134_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=star_target_rule(p)) && (seq=_loop0_135_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_136_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_274_var; while( (_tmp_274_var=_tmp_274_rule(p)) ) {_res=_tmp_274_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_137_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var star_target_var; if( $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,16) && (star_target_var=star_target_rule(p)) ) {_res=star_target_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_139_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=del_target_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_138_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=del_target_rule(p)) && (seq=_loop0_139_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_141_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=expression_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_140_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=expression_rule(p)) && (seq=_loop0_141_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_143_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=expression_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_142_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=expression_rule(p)) && (seq=_loop0_143_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_145_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=expression_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_144_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=expression_rule(p)) && (seq=_loop0_145_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_147_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=expression_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_146_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=expression_rule(p)) && (seq=_loop0_147_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_148_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var indent_var; var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) && (indent_var=$B._PyPegen.expect_token(p,INDENT)) ) {_res=$B._PyPegen.dummy_name(p,newline_var,indent_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_149_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_275_var; if( (_tmp_275_var=_tmp_275_rule(p)) ) {_res=_tmp_275_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var kwargs_var; if( (kwargs_var=kwargs_rule(p)) ) {_res=kwargs_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_151_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_276_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_150_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_276_rule(p)) && (seq=_loop0_151_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_152_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var args_var; if( (args_var=args_rule(p)) ) {_res=args_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; var for_if_clauses_var; if( (expression_var=expression_rule(p)) && (for_if_clauses_var=for_if_clauses_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,expression_var,for_if_clauses_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_153_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var args_var; if( (args_var=args_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.dummy_name(p,args_var,_literal); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_154_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_155_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,622)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,624)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,623)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_156_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (name_var=$B._PyPegen.name_token(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=$B._PyPegen.dummy_name(p,name_var,_literal); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_157_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_277_var; while( (_tmp_277_var=_tmp_277_rule(p)) ) {_res=_tmp_277_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_158_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var name_var; var string_var; if( (name_var=$B._PyPegen.name_token(p)) && (string_var=$B._PyPegen.string_token(p)) ) {_res=$B._PyPegen.dummy_name(p,name_var,string_var); break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var soft_keyword_var; if( (soft_keyword_var=$B._PyPegen.soft_keyword_token(p)) ) {_res=soft_keyword_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_159_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,686)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_160_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var pass_stmt_var; if( (pass_stmt_var=pass_stmt_rule(p)) ) {_res=pass_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var break_stmt_var; if( (break_stmt_var=break_stmt_rule(p)) ) {_res=break_stmt_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var continue_stmt_var; if( (continue_stmt_var=continue_stmt_rule(p)) ) {_res=continue_stmt_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_161_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,53)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_162_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var list_var; if( (list_var=list_rule(p)) ) {_res=list_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var tuple_var; if( (tuple_var=tuple_rule(p)) ) {_res=tuple_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var genexp_var; if( (genexp_var=genexp_rule(p)) ) {_res=genexp_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,622)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,623)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,624)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_163_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,53)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_164_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var star_named_expressions_var; while( (star_named_expressions_var=star_named_expressions_rule(p)) ) {_res=star_named_expressions_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_165_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_278_var; while( (_tmp_278_var=_tmp_278_rule(p)) ) {_res=_tmp_278_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_166_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_279_var; while( (_tmp_279_var=_tmp_279_rule(p)) ) {_res=_tmp_279_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_167_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,9)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,7)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,25)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_168_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,9)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,25)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_169_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,9)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,25)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_170_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var slash_no_default_var; if( (slash_no_default_var=slash_no_default_rule(p)) ) {_res=slash_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var slash_with_default_var; if( (slash_with_default_var=slash_with_default_rule(p)) ) {_res=slash_with_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_171_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_172_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_173_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_174_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_no_default_var; while( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_175_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var slash_no_default_var; if( (slash_no_default_var=slash_no_default_rule(p)) ) {_res=slash_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var slash_with_default_var; if( (slash_with_default_var=slash_with_default_rule(p)) ) {_res=slash_with_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_176_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_177_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var param_no_default_var; if( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_178_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_179_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_180_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_181_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _tmp_280_var; if( (_literal=$B._PyPegen.expect_token(p,12)) && (_tmp_280_var=_tmp_280_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,_tmp_280_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_182_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var param_no_default_var; if( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_183_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_maybe_default_var; while( (param_maybe_default_var=param_maybe_default_rule(p)) ) {_res=param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_184_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var param_no_default_var; if( (param_no_default_var=param_no_default_rule(p)) ) {_res=param_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_185_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,16)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,35)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,17)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_186_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var param_with_default_var; while( (param_with_default_var=param_with_default_rule(p)) ) {_res=param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_187_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var lambda_slash_no_default_var; if( (lambda_slash_no_default_var=lambda_slash_no_default_rule(p)) ) {_res=lambda_slash_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lambda_slash_with_default_var; if( (lambda_slash_with_default_var=lambda_slash_with_default_rule(p)) ) {_res=lambda_slash_with_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_188_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_189_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_190_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; while( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop0_192_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=lambda_param_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_191_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=lambda_param_rule(p)) && (seq=_loop0_192_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_193_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var lambda_slash_no_default_var; if( (lambda_slash_no_default_var=lambda_slash_no_default_rule(p)) ) {_res=lambda_slash_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lambda_slash_with_default_var; if( (lambda_slash_with_default_var=lambda_slash_with_default_rule(p)) ) {_res=lambda_slash_with_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_194_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_195_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; if( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_196_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_197_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_198_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_with_default_var; while( (lambda_param_with_default_var=lambda_param_with_default_rule(p)) ) {_res=lambda_param_with_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_199_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; var _tmp_281_var; if( (_literal=$B._PyPegen.expect_token(p,12)) && (_tmp_281_var=_tmp_281_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,_tmp_281_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_200_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; if( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_201_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var lambda_param_maybe_default_var; while( (lambda_param_maybe_default_var=lambda_param_maybe_default_rule(p)) ) {_res=lambda_param_maybe_default_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_202_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var lambda_param_no_default_var; if( (lambda_param_no_default_var=lambda_param_no_default_rule(p)) ) {_res=lambda_param_no_default_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_203_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,16)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,35)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,17)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_204_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_205_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _loop0_282_var; var _opt_var; UNUSED(_opt_var); var bitwise_or_var; if( (bitwise_or_var=bitwise_or_rule(p)) && (_loop0_282_var=_loop0_282_rule(p)) && (_opt_var=$B._PyPegen.expect_token(p,12),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,bitwise_or_var,_loop0_282_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_207_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=dotted_name_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_206_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=dotted_name_rule(p)) && (seq=_loop0_207_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_208_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_283_var; var name_var; if( (name_var=$B._PyPegen.name_token(p)) && (_tmp_283_var=_tmp_283_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,name_var,_tmp_283_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_209_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _tmp_284_var; var name_var; if( (name_var=$B._PyPegen.name_token(p)) && (_tmp_284_var=_tmp_284_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,name_var,_tmp_284_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_211_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_285_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_210_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_285_rule(p)) && (seq=_loop0_211_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_213_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_286_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_212_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_286_rule(p)) && (seq=_loop0_213_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_215_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_287_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_214_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_287_rule(p)) && (seq=_loop0_215_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_217_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_288_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_216_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_288_rule(p)) && (seq=_loop0_217_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_218_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,677)) ) {_res=_keyword; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _keyword; if( (_keyword=$B._PyPegen.expect_token(p,673)) ) {_res=_keyword; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_219_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var block_var; while( (block_var=block_rule(p)) ) {_res=block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_220_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var except_block_var; while( (except_block_var=except_block_rule(p)) ) {_res=except_block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_221_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_222_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var block_var; while( (block_var=block_rule(p)) ) {_res=block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _loop1_223_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var except_star_block_var; while( (except_star_block_var=except_star_block_rule(p)) ) {_res=except_star_block_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_224_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var expression_var; if( (expression_var=expression_rule(p)) && (_opt_var=_tmp_289_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,expression_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_225_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_226_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_227_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_228_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_229_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_230_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var positional_patterns_var; if( (positional_patterns_var=positional_patterns_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=$B._PyPegen.dummy_name(p,positional_patterns_var,_literal); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_231_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var expression_var; if( (_literal=$B._PyPegen.expect_token(p,51)) && (expression_var=expression_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,expression_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_232_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var expression_var; if( (_literal=$B._PyPegen.expect_token(p,51)) && (expression_var=expression_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,expression_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_233_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); if( (_literal=$B._PyPegen.expect_token(p,7)) && (_opt_var=arguments_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B._PyPegen.dummy_name(p,_literal,_opt_var,_literal_1); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_234_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var _literal_1; var _opt_var; UNUSED(_opt_var); if( (_literal=$B._PyPegen.expect_token(p,7)) && (_opt_var=arguments_rule(p),!p.error_indicator) && (_literal_1=$B._PyPegen.expect_token(p,8)) ) {_res=$B._PyPegen.dummy_name(p,_literal,_opt_var,_literal_1); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_236_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=double_starred_kvpair_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_235_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=double_starred_kvpair_rule(p)) && (seq=_loop0_236_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_237_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_238_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_239_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_240_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_241_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_242_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_243_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_244_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var fstring_format_spec_var; while( (fstring_format_spec_var=fstring_format_spec_rule(p)) ) {_res=fstring_format_spec_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_245_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_246_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_247_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_248_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,54)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_249_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_250_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_251_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_252_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var fstring_format_spec_var; while( (fstring_format_spec_var=fstring_format_spec_rule(p)) ) {_res=fstring_format_spec_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_253_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var name_var; if( (_literal=$B._PyPegen.expect_token(p,54)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_254_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,26)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop1_255_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_290_var; while( (_tmp_290_var=_tmp_290_rule(p)) ) {_res=_tmp_290_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _loop1_256_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var tstring_var; while( (tstring_var=tstring_rule(p)) ) {_res=tstring_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} if(_n==0 ||p.error_indicator){return NULL;} return _children;} function _tmp_257_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var fstring_var; if( (fstring_var=fstring_rule(p)) ) {_res=fstring_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var string_var; if( (string_var=string_rule(p)) ) {_res=string_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_258_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,14)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,15)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,16)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,17)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,24)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,47)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,49)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_259_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,14)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,15)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,31)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_260_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var z; if( (z=star_targets_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_261_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,23)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,52)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_262_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,23)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,52)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_263_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var f; var newline_var; if( (_literal=$B._PyPegen.expect_token(p,49)) && (f=named_expression_rule(p)) && (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=f; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_264_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var c; if( (_literal=$B._PyPegen.expect_token(p,12)) && (c=expression_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_265_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var c; if( (_literal=$B._PyPegen.expect_token(p,12)) && (c=star_expression_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_266_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var c; if( (_keyword=$B._PyPegen.expect_token(p,588)) && (c=conjunction_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_267_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var c; if( (_keyword=$B._PyPegen.expect_token(p,589)) && (c=inversion_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_268_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var slice_var; if( (slice_var=slice_rule(p)) ) {_res=slice_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var starred_expression_var; if( (starred_expression_var=starred_expression_rule(p)) ) {_res=starred_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_269_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var fstring_var; if( (fstring_var=fstring_rule(p)) ) {_res=fstring_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var string_var; if( (string_var=string_rule(p)) ) {_res=string_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_270_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var z; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (z=disjunction_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_271_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var z; if( (_keyword=$B._PyPegen.expect_token(p,682)) && (z=disjunction_rule(p)) ) {_res=z; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_272_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var starred_expression_var; if( (starred_expression_var=starred_expression_rule(p)) ) {_res=starred_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_291_var; if( (_tmp_291_var=_tmp_291_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,22) ) {_res=_tmp_291_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_273_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var c; if( (_literal=$B._PyPegen.expect_token(p,12)) && (c=star_target_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_274_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var c; if( (_literal=$B._PyPegen.expect_token(p,12)) && (c=star_target_rule(p)) ) {_res=c; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_275_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _gather_292_var; var _literal; var kwargs_var; if( (_gather_292_var=_gather_292_rule(p)) && (_literal=$B._PyPegen.expect_token(p,12)) && (kwargs_var=kwargs_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_gather_292_var,_literal,kwargs_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_276_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var starred_expression_var; if( (starred_expression_var=starred_expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,22) ) {_res=starred_expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_277_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var expression_without_invalid_var; if( $B._PyPegen.lookahead(0,$B._PyPegen.string_token,p) && (expression_without_invalid_var=expression_without_invalid_rule(p)) ) {_res=expression_without_invalid_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_278_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var star_targets_var; if( (star_targets_var=star_targets_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=$B._PyPegen.dummy_name(p,star_targets_var,_literal); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_279_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var star_targets_var; if( (star_targets_var=star_targets_rule(p)) && (_literal=$B._PyPegen.expect_token(p,22)) ) {_res=$B._PyPegen.dummy_name(p,star_targets_var,_literal); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_280_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,35)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_281_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,11)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,35)) ) {_res=_literal; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_282_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _tmp_294_var; while( (_tmp_294_var=_tmp_294_rule(p)) ) {_res=_tmp_294_var; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _tmp_283_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_284_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,12)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _literal; if( (_literal=$B._PyPegen.expect_token(p,8)) ) {_res=_literal; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var newline_var; if( (newline_var=$B._PyPegen.expect_token(p,NEWLINE)) ) {_res=newline_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_285_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var expression_var; if( (expression_var=expression_rule(p)) && (_opt_var=_tmp_295_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,expression_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_286_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var expressions_var; if( (expressions_var=expressions_rule(p)) && (_opt_var=_tmp_296_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,expressions_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_287_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var expression_var; if( (expression_var=expression_rule(p)) && (_opt_var=_tmp_297_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,expression_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_288_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _opt_var; UNUSED(_opt_var); var expressions_var; if( (expressions_var=expressions_rule(p)) && (_opt_var=_tmp_298_rule(p),!p.error_indicator) ) {_res=$B._PyPegen.dummy_name(p,expressions_var,_opt_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_289_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var name_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (name_var=$B._PyPegen.name_token(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,name_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_290_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var fstring_var; if( (fstring_var=fstring_rule(p)) ) {_res=fstring_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var string_var; if( (string_var=string_rule(p)) ) {_res=string_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_291_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var assignment_expression_var; if( (assignment_expression_var=assignment_expression_rule(p)) ) {_res=assignment_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,53) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _loop0_293_rule(p) {if(p.error_indicator){return NULL;} var _res={value:NULL}; _res=NULL; var _mark=p.mark; var _children=[]; var _children_capacity=1; var _n=0; { if(p.error_indicator){return NULL;} var _literal; var elem; while( (_literal=$B._PyPegen.expect_token(p,12)) && (elem=_tmp_299_rule(p)) ) {_res=elem; _children[_n++]=_res; _mark=p.mark;} p.mark=_mark;} return _children;} function _gather_292_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var elem; var seq; if( (elem=_tmp_299_rule(p)) && (seq=_loop0_293_rule(p)) ) {_res=$B._PyPegen.seq_insert_in_front(p,elem,seq); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_294_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _literal; var bitwise_or_var; if( (_literal=$B._PyPegen.expect_token(p,12)) && (bitwise_or_var=bitwise_or_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_literal,bitwise_or_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_295_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var star_target_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (star_target_var=star_target_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,star_target_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_296_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var star_target_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (star_target_var=star_target_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,star_target_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_297_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var star_target_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (star_target_var=star_target_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,star_target_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_298_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var _keyword; var star_target_var; if( (_keyword=$B._PyPegen.expect_token(p,680)) && (star_target_var=star_target_rule(p)) ) {_res=$B._PyPegen.dummy_name(p,_keyword,star_target_var); break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_299_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var starred_expression_var; if( (starred_expression_var=starred_expression_rule(p)) ) {_res=starred_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var _tmp_300_var; if( (_tmp_300_var=_tmp_300_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,22) ) {_res=_tmp_300_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} function _tmp_300_rule(p) {if(p.error_indicator){return NULL;} while(1){var _res=NULL; var _mark=p.mark; { if(p.error_indicator){return NULL;} var assignment_expression_var; if( (assignment_expression_var=assignment_expression_rule(p)) ) {_res=assignment_expression_var; break;} p.mark=_mark;} { if(p.error_indicator){return NULL;} var expression_var; if( (expression_var=expression_rule(p)) && $B._PyPegen.lookahead_with_int(0,$B._PyPegen.expect_token,p,53) ) {_res=expression_var; break;} p.mark=_mark;} _res=NULL; break;} return _res;} $B._PyPegen.parse=function(p){p.keywords=reserved_keywords; p.n_keyword_lists=n_keyword_lists; p.soft_keywords=soft_keywords; switch(p.mode){case 'file': return file_rule(p) case 'eval': return eval_rule(p) case 'single': return interactive_rule(p) default: console.log('unknown mode',p.mode) throw Error(`unknown parse mode: ${p.mode}`)}}; ; (function($B){$B.whenReady=new Promise(function(resolve,reject){resolve()})})(__BRYTHON__); ;