-
Notifications
You must be signed in to change notification settings - Fork 1
/
pxtcompiler.js
1 lines (1 loc) · 309 KB
/
pxtcompiler.js
1
var pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,pxt,pxt,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts,ts;!function(e){let t,n=!1;class r{constructor(e){this.db=e}loadAsync(n,r,s,i){if(!/^v\d+\.\d+\.\d+$/.test(r))return i(n,r);const a=`gh-${s}-${n}#${r}`;return t.cacheGet(a).then((s=>{if(s){const t=e.Util.jsonTryParse(s);if(t)return e.debug(`cache hit ${a}`),Promise.resolve(t)}return i(n,r).then((n=>n?(e.debug(`cached ${a}`),t.cacheSet(a,JSON.stringify(n)).then((()=>n))):n))}))}latestVersionAsync(e,t){return this.db.latestVersionAsync(e,t)}loadConfigAsync(e,t){return this.loadAsync(e,t,"pxt",((e,t)=>this.db.loadConfigAsync(e,t)))}loadPackageAsync(e,t){return this.loadAsync(e,t,"pkg",((e,t)=>this.db.loadPackageAsync(e,t)))}}class s{constructor(e){this.packageFiles=e}resolve(e,t){return""}readFile(t,n){const r="this"==t.id?n:"pxt_modules/"+t.id+"/"+n;return void 0!==this.packageFiles[r]?this.packageFiles[r]:e.appTarget.bundledpkgs[t.id]?e.appTarget.bundledpkgs[t.id][n]:null}writeFile(t,n,r){const s="this"==t.id?"":"pxt_modules/"+t.id+"/";e.debug(`write file ${s+n}`),this.packageFiles[s+n]=r}getHexInfoAsync(e){return Promise.resolve({hex:["SKIP"]})}cacheStoreAsync(e,n){return(null==t?void 0:t.cacheSet)?t.cacheSet(e,n):Promise.resolve()}cacheGetAsync(e){return(null==t?void 0:t.cacheGet)?t.cacheGet(e):Promise.resolve("")}downloadPackageAsync(r){return n?function(e){const n=null==t?void 0:t.pkgOverrideAsync;return(n?n(e.id):Promise.resolve(void 0)).then((t=>t||e.commonDownloadAsync()))}(r).then((t=>{t&&e.U.iterMap(t,((e,t)=>{this.writeFile(r,e,t)}))})):Promise.resolve()}resolveVersionAsync(e){return Promise.resolve("*")}}function i(t){if(t.target.preferredEditor==e.PYTHON_PROJECT_NAME){const n=e.U.clone(t);n.ast=!0,n.target.preferredEditor=e.JAVASCRIPT_PROJECT_NAME;for(let t of n.sourceFiles)e.U.endsWith(t,".py")&&(n.fileSystem[t.slice(0,-3)+".ts"]=" ");const r=pxtc.compile(n);t.apisInfo=pxtc.getApiInfo(r.ast,n.jres)}}function a(t,n){const r=new s(t),a=new e.MainPackage(r);return a.loadAsync().then((()=>{let e=a.getTargetOptions();return e.hasHex&&(e.isNative=n.native),a.getCompileOptionsAsync(e)})).then((e=>(o(a.targetVersion(),e),i(e),e)))}function o(t,n){if(t){e.debug(`applying TS patches relative to ${t}`);for(let r of Object.keys(n.fileSystem))if(-1==r.indexOf("/")&&e.U.endsWith(r,".ts")){const s=n.fileSystem[r],i=e.patching.patchJavaScript(t,s);s!=i&&(e.debug(`applying TS patch to ${r}`),n.fileSystem[r]=i)}}}e.SimpleHost=s,e.prepPythonOptions=i,e.simpleInstallPackagesAsync=function(t){const n=new s(t);return new e.MainPackage(n).loadAsync(!0)},e.simpleGetCompileOptionsAsync=a,e.simpleCompileAsync=function(e,t){return a(e,"boolean"==typeof t?{native:t}:t||{}).then((e=>pxtc.compile(e))).then((e=>(e.success||(e.errors=e.diagnostics.map(ts.pxtc.getDiagnosticString).join("")||"Unknown error."),e)))},e.patchTS=o,e.setupSimpleCompile=function(s){"undefined"==typeof global||global.btoa||(global.btoa=function(e){return Buffer.from(e,"binary").toString("base64")},global.atob=function(e){return Buffer.from(e,"base64").toString("binary")}),"undefined"!=typeof pxtTargetBundle&&(e.debug("setup app bundle"),e.setAppTarget(pxtTargetBundle)),s&&(t=s,n=!0,s.httpRequestAsync&&(e.Util.httpRequestCoreAsync=s.httpRequestAsync),e.github.forceProxy=!0,e.github.db=new r(new e.github.MemoryGithubDb)),e.debug("simple setup done")}}(pxt||(pxt={})),function(e){e.simshim=function(t,n){let r,s=ts.SyntaxKind,i=t.getTypeChecker(),a=e.cpp.nsWriter("declare namespace"),o="";for(let i of t.getSourceFiles()){if(n){let t=n(i.fileName);if(e.debug("SimShim[1]: "+t.dir),!e.U.endsWith(t.dir,"/sim")&&!e.U.startsWith(i.fileName,"sim/"))continue}else if(!e.U.startsWith(i.fileName,"sim/"))continue;e.debug("SimShim[2]: "+i.fileName);for(let e of i.statements){let t=e;e.kind==s.ModuleDeclaration&&"pxsim"==t.name.text&&(r=t,h(t.body))}}let l={};return l[e.appTarget.corepkg]=a.finish(),l;function c(e){let t;return ts.isExpression(e)&&(t=i.getContextualType(e)),t||(t=i.getTypeAtLocation(e)),t}function u(e){let t=i.typeToString(e,r,ts.TypeFormatFlags.UseFullyQualifiedType);switch(t=t.replace(/^pxsim\./,""),t){case"RefAction":return"() => void";case"RefBuffer":return"Buffer";default:return t}}function p(e){let t=pxtc.getComments(e);return/^\s*\/\/%/m.test(t)?t:null}function d(e){let t=p(e);if(!t)return;let n=e.name.getText(),r="//% shim=."+n,s=i.getTypeAtLocation(e);a.write(t),a.write(r),a.write(`public ${n}: ${u(s)};`),a.write("")}function f(e){let t=p(e);if(!t)return;i.getTypeAtLocation(e);let n=e.parameters.map((e=>e.name.getText()+": "+u(c(e))));a.write(t),a.write(`//% shim="new ${o}"`),a.write(`constructor(${n.join(", ")});`),a.write("")}function m(t,n=!1){let r=p(t);if(!r)return;let l=t.name.getText(),d=t.kind==s.MethodDeclaration||t.kind==s.GetAccessor||t.kind==s.SetAccessor,f="//% shim="+(d?"."+l:o+"::"+l),m=i.getSignatureFromDeclaration(t),h=i.getReturnTypeOfSignature(m),g=/Async$/.test(l),b=(x=h,pxtc.isObjectType(x)&&x.objectFlags&ts.ObjectFlags.Reference&&"Promise"==x.symbol.name?x.typeArguments[0]:null);var x;b?(f+=" promise",h=b,g||e.U.userError(`${o}::${l} should be called ${l}Async`)):g&&e.U.userError(`${o}::${l} doesn't return a promise`),e.debug("emitFun: "+l);let y=t.parameters.map((e=>`${e.name.getText()}${e.questionToken?"?":""}: ${u(c(e))}`)),k=l.replace(/Async$/,""),S=d?"public":"function",T=`(${y.join(", ")})`;t.kind==s.GetAccessor&&(S=n?"public":"readonly",T="",f+=" property"),d||a.setNs(o),a.write(r),a.write(f),a.write(`${S} ${k}${T}: ${u(h)};`),a.write("")}function h(e){switch(e.kind){case s.ModuleDeclaration:return function(e){let t=o;o&&(o+="."),o+=e.name.text,h(e.body),o=t}(e);case s.ModuleBlock:return e.statements.forEach(h);case s.FunctionDeclaration:return m(e);case s.ClassDeclaration:return function(e){let t=p(e);if(!t)return;a.setNs(o),a.write(t);let n=o;o&&(o+="."),o+=e.name.text;let r=n?"":"declare",i="";if(e.heritageClauses)for(let t of e.heritageClauses)t.token==s.ExtendsKeyword&&(i=" extends "+u(c(t.types[0])));a.write(`${r} class ${e.name.text}${i} {`),a.incrIndent();for(let t of e.members)switch(t.kind){case s.MethodDeclaration:m(t);break;case s.PropertyDeclaration:d(t);break;case s.Constructor:f(t);break;case s.GetAccessor:let n=e.members.some((e=>e.kind==s.SetAccessor&&e.name.getText()==t.name.getText()));m(t,n)}o=n,a.decrIndent(),a.write("}")}(e)}}}}(pxt||(pxt={})),function(e){!function(t){t.annotate=function(n,r,s){const i=t.target;t.target=s;let a=n.getSourceFiles().filter((e=>e.fileName===r))[0],o=n.getTypeChecker();function l(n,r,s=!1,i=null){let a=s||!(u(n).flags&e.TypeFlags.Void),l=i||c(n);if(n.expression&&l){let e=!1;switch(l.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:t.isStatic(l)||(e=!0);break;case t.SK.Parameter:t.isCtorField(l)&&(e=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:case t.SK.MethodSignature:e=!0}if(e){const e=n.expression;e.kind===t.SK.PropertyAccessExpression?r.unshift(e.expression):r.unshift(n.expression)}}let p={decl:l,qName:l?t.getNodeFullName(o,l):"?",args:r,isExpression:a};t.pxtInfo(n).callInfo=p}function c(n){if(!n)return null;let r,s=o.getSymbolAtLocation(n);if(s&&(r=s.valueDeclaration,!r&&s.declarations)){let t=s.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(s=o.getSymbolAtLocation(t.moduleReference),s&&(r=s.valueDeclaration))}if(!r&&n.kind==t.SK.PropertyAccessExpression){const e=n;r={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:e.name.getText()},name:e.name},t.pxtInfo(r).flags|=2}return r}function u(n){let r;const s=t.pxtInfo(n);return s.typeCache?s.typeCache:(e.isExpression(n)&&(r=o.getContextualType(n)),r||(r=o.getTypeAtLocation(n)),r?e.isStringLiteral(n)?r:t.checkType(r):r)}!function n(r){e.forEachChild(r,(r=>{switch(r.kind){case e.SyntaxKind.CallExpression:l(r,r.arguments.slice(0),null,c(r.expression));break;case e.SyntaxKind.PropertyAccessExpression:l(r,[]);break;case e.SyntaxKind.TaggedTemplateExpression:l(r,[r.template],!0,c(r.tag));break;case e.SyntaxKind.BinaryExpression:!function(n){const r=n.left,s=n.right;let i=u(n.left),a=u(n.right);n.operatorToken.kind!=t.SK.PlusToken&&n.operatorToken.kind!=t.SK.PlusEqualsToken||(t.isStringType(i)||t.isStringType(a)&&n.operatorToken.kind==t.SK.PlusToken)&&(t.pxtInfo(n).exprInfo={leftType:o.typeToString(i),rightType:o.typeToString(a)});switch(n.operatorToken.kind){case e.SyntaxKind.EqualsToken:case e.SyntaxKind.PlusEqualsToken:case e.SyntaxKind.MinusEqualsToken:if(r.kind==t.SK.PropertyAccessExpression){let n=c(r);n&&n.kind==t.SK.GetAccessor?(n=e.getDeclarationOfKind(n.symbol,t.SK.SetAccessor),l(r,[s],!1,n)):n&&(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment||t.target&&t.target.switches.slowFields)&&l(r,[s])}}}(r);break;case e.SyntaxKind.Identifier:const n=c(r);if(n&&n.getSourceFile().fileName!==pxt.MAIN_TS&&n.kind==e.SyntaxKind.VariableDeclaration){const e=t.pxtInfo(r);e.flags|=4,e.commentAttrs||(e.commentAttrs=t.parseComments(n))}}n(r)}))}(a),t.target=i}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){function t(e){let t='"';for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n),s=String.fromCharCode(r);t+="\\"==s||'"'==s?"\\"+s:"\n"==s?"\\n":r<=15?"\\x0"+r.toString(16):r<32||r>127?"\\x"+r.toString(16):s}return t+'"'}e.asmStringLiteral=t;function n(n){let r="pxt::string_inline_ascii_vt",s=e.target.utf8?e.U.toUTF8(n,!0):n,i="";if(s!==n)if(n.length>16){r="pxt::string_skiplist16_packed_vt";let a=[],o=0;for(let t=0;t+16<=n.length;t+=16)o+=e.U.toUTF8(n.slice(t,t+16),!0).length,a.push(o);i=`\n .short ${s.length}, ${n.length}\n .short ${a.map((e=>e.toString())).join(", ")}\n .string ${t(s)}\n`}else r="pxt::string_inline_utf8_vt";return i||(i=`\n .short ${s.length}\n .string ${t(s)}\n`),{vt:r,asm:i}}function r(e,t=""){return`\n .word ${e.length>>1}${t}\n .hex ${e}${e.length%4==0?"":"00"}\n `}e.AssemblerSnippets=class{nop(){return"TBD(nop)"}reg_gets_imm(e,t){return"TBD(reg_gets_imm)"}proc_setup(e,t){return"TBD(proc_setup)"}push_fixed(e){return"TBD(push_fixed)"}push_local(e){return"TBD(push_local)"}push_locals(e){return"TBD(push_locals)"}pop_fixed(e){return"TBD(pop_fixed)"}pop_locals(e){return"TBD(pop_locals)"}proc_return(){return"TBD(proc_return)"}debugger_stmt(e){return""}debugger_bkpt(e){return""}debugger_proc(e){return""}unconditional_branch(e){return"TBD(unconditional_branch)"}beq(e){return"TBD(beq)"}bne(e){return"TBD(bne)"}cmp(e,t){return"TBD(cmp)"}cmp_zero(e){return"TBD(cmp_zero)"}arithmetic(){return""}load_reg_src_off(e,t,n,r,s,i){return"TBD(load_reg_src_off)"}rt_call(e,t,n){return"TBD(rt_call)"}call_lbl(e,t){return"TBD(call_lbl)"}call_reg(e){return"TBD(call_reg)"}helper_prologue(){return"TBD(lambda_prologue)"}helper_epilogue(){return"TBD(lambda_epilogue)"}pop_clean(e){return"TBD"}load_ptr_full(e,t){return"TBD(load_ptr_full)"}emit_int(e,t){return"TBD(emit_int)"}obj_header(e){return`.word ${e}`}string_literal(e,t){const r=n(t);return`\n .balign 4\n .object ${e}\n ${e}: ${this.obj_header(r.vt)}\n ${r.asm}\n`}hex_literal(e,t){return`\n.balign ${/f{16}/i.test(t)?8:4}\n.object ${e}\n${e}: ${this.obj_header("pxt::buffer_vt")}\n${r(t)}\n`}},e.utf8AsmStringLiteral=n,e.hexLiteralAsm=r,e.numBytes=function(e){let t=0;for(let n=e;n>0;n>>>=8)t++;return t||1};e.ProctoAssembler=class{constructor(t,n,r){this.resText="",this.exprStack=[],this.calls=[],this.proc=null,this.baseStackSize=0,this.labelledHelpers={},this.write=t=>{this.resText+=e.asmline(t)},this.t=t,this.bin=n,this.proc=r,this.proc&&this.work()}emitHelpers(){this.emitLambdaTrampoline(),this.emitArrayMethods(),this.emitFieldMethods(),this.emitBindHelper()}redirectOutput(t){let n=this.write,r="";this.write=t=>r+=e.asmline(t);try{t()}finally{this.write=n}return r}stackSize(){return this.baseStackSize+this.exprStack.length}stackAlignmentNeeded(t=0){if(!e.target.stackAlign)return 0;let n=e.target.stackAlign-(this.stackSize()+t&e.target.stackAlign-1);return n==e.target.stackAlign?0:n}getAssembly(){return this.resText}work(){this.write(`\n;\n; Function ${this.proc.getFullName()}\n;\n`);let t=this.proc.label();this.write(`.object ${t} ${JSON.stringify(this.proc.getFullName())}`);let n=t+"_pre",r=t+"_bkpt",s=t+"_locals",i=t+"_end";this.write(`${n}:`),this.emitLambdaWrapper(this.proc.isRoot),this.write(".section code"),this.write(`${t}:`),this.proc.classInfo&&this.proc.info.thisParameter&&!e.target.switches.skipClassCheck&&!e.target.switches.noThisCheckOpt&&(this.write("mov r7, lr"),this.write("ldr r0, [sp, #0]"),this.emitInstanceOf(this.proc.classInfo,"validate"),this.write("mov lr, r7")),this.write(`\n${t}_nochk:\n @stackmark func\n @stackmark args\n`),this.proc.fillDebugInfo=t=>{let a=t.getLabels();this.proc.debugInfo={locals:(1==this.proc.seqNo?this.bin.globals:this.proc.locals).map((e=>e.getDebugInfo())),args:this.proc.args.map((e=>e.getDebugInfo())),name:this.proc.getName(),codeStartLoc:e.U.lookup(a,s),codeEndLoc:e.U.lookup(a,i),bkptLoc:e.U.lookup(a,r),localsMark:e.U.lookup(t.stackAtLabel,s),idx:this.proc.seqNo,calls:this.calls,size:e.U.lookup(a,i)+2-e.U.lookup(a,n)};for(let n of this.calls)n.addr=e.U.lookup(a,n.callLabel),n.stack=e.U.lookup(t.stackAtLabel,n.callLabel),n.callLabel=void 0;for(let n=0;n<this.proc.body.length;++n){let r=this.proc.body[n].breakpointInfo;if(r){let n=e.U.lookup(t.stackAtLabel,`__brkp_${r.id}`);n!==this.proc.debugInfo.localsMark&&(console.log(r),console.log(t.stackAtLabel),e.U.oops(`offset doesn't match: ${n} != ${this.proc.debugInfo.localsMark}`))}}},this.bin.breakpoints&&this.write(this.t.debugger_proc(r)),this.baseStackSize=1;let a=this.proc.locals.length;this.write("push {lr}"),this.write(".locals:\n"),this.proc.perfCounterNo&&(this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::startPerfCounter")),this.write(this.t.proc_setup(a)),this.baseStackSize+=a,this.write("@stackmark locals"),this.write(`${s}:`);for(let t=0;t<this.proc.body.length;++t){let n=this.proc.body[t];switch(n.stmtKind){case e.ir.SK.Expr:this.emitExpr(n.expr);break;case e.ir.SK.StackEmpty:if(this.exprStack.length>0){for(let e of this.proc.body.slice(t-4,t+1))console.log(`PREVSTMT ${e.toString().trim()}`);for(let e of this.exprStack)console.log(`EXPRSTACK ${e.currUses}/${e.totalUses} E: ${e.toString()}`);e.oops("stack should be empty")}this.write("@stackempty locals");break;case e.ir.SK.Jmp:this.emitJmp(n);break;case e.ir.SK.Label:this.write(n.lblName+":"),this.validateJmpStack(n);break;case e.ir.SK.Comment:this.write(`; ${n.expr.data}`);break;case e.ir.SK.Breakpoint:if(this.bin.breakpoints){let e=`__brkp_${n.breakpointInfo.id}`;n.breakpointInfo.isDebuggerStmt?this.write(this.t.debugger_stmt(e)):this.write(this.t.debugger_bkpt(e))}break;default:e.oops()}}e.assert(0<=a&&a<127),a>0&&this.write(this.t.pop_locals(a)),this.proc.perfCounterNo&&(this.write("mov r4, r0"),this.write(this.t.emit_int(this.proc.perfCounterNo,"r0")),this.write("bl pxt::stopPerfCounter"),this.write("mov r0, r4")),this.write(`${i}:`),this.write(this.t.proc_return()),this.write("@stackempty func"),this.write("@stackempty args"),this.write("; endfun")}mkLbl(e){let t=e+this.bin.lblNo++;return"_"!=t[0]&&(t="."+t),t}dumpStack(){let e="[";for(let t of this.exprStack)e+=t.sharingInfo()+": "+t.toString()+"; ";return e+="]",e}terminate(t){e.assert(t.exprKind==e.ir.EK.SharedRef);let n=t.args[0];e.U.assert(n.currUses!=n.totalUses),e.U.assert(this.exprStack[0]===n,"term at top");let r=1;for(;r<this.exprStack.length;){let e=this.exprStack[r];if(e.currUses!=e.totalUses)break;r++}return this.write(`@dummystack ${r}`),this.write(this.t.pop_locals(r)),r}validateJmpStack(t,n=0){let r=this.exprStack.length-n;null==t.lblStackSize?t.lblStackSize=r:t.lblStackSize!=r&&(console.log(t.lblStackSize,r),console.log(this.dumpStack()),e.U.oops("stack misaligned at: "+t.lblName))}emitJmp(t){let n=0;if(t.jmpMode==e.ir.JmpMode.Always)t.expr&&this.emitExpr(t.expr),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)+" ; with expression");else{let r=this.mkLbl("jmpz");this.emitExpr(t.expr),(t.expr.exprKind!=e.ir.EK.RuntimeCall||"thumb::subs"!==t.expr.data&&!e.U.startsWith(t.expr.data,"_cmp_"))&&this.write(this.t.cmp_zero("r0")),t.jmpMode==e.ir.JmpMode.IfNotZero?this.write(this.t.beq(r)):this.write(this.t.bne(r)),t.terminateExpr&&(n=this.terminate(t.terminateExpr)),this.write(this.t.unconditional_branch(t.lblName)),this.write(r+":")}this.validateJmpStack(t.lbl,n)}clearStack(e=!1){let t=0;for(;this.exprStack.length>0&&this.exprStack[0].currUses==this.exprStack[0].totalUses;)t++,this.exprStack.shift();if(t&&this.write(this.t.pop_locals(t)),!e){let e=this.exprStack.filter((e=>e.currUses==e.totalUses&&-1!=e.irCurrUses));if(e.length>0){this.write(this.t.reg_gets_imm("r7",0));for(let t of e)t.irCurrUses=-1,this.write(this.loadFromExprStack("r7",t,0,!0))}}}emitExprInto(t,n){switch(t.exprKind){case e.ir.EK.NumberLiteral:"number"==typeof t.data?this.write(this.t.emit_int(t.data,n)):e.oops();break;case e.ir.EK.PointerLiteral:this.write(this.t.load_ptr_full(t.data,n));break;case e.ir.EK.SharedRef:let r=t.args[0];e.U.assert(!!r.currUses),e.U.assert(r.currUses<r.totalUses),r.currUses++;let s=this.exprStack.indexOf(r);if(e.U.assert(s>=0),0==s&&r.totalUses==r.currUses)this.write(this.t.pop_fixed([n])+` ; tmpref @${this.exprStack.length}`),this.exprStack.shift(),this.clearStack();else{let e=s.toString()+":"+this.exprStack.length;this.write(this.t.load_reg_src_off(n,"sp",e,!0)+" ; tmpref @"+(this.exprStack.length-s))}break;case e.ir.EK.CellRef:let i=t.data;if(i.isGlobal()){let e=this.bitSizeInfo(i.bitSize),t="#"+i.index;(e.needsSignExt||i.index>=e.immLimit)&&(this.write(this.t.emit_int(i.index,n)),t=n),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off(n,"r7",t,!1,!1,e))}else{let[e,t,r]=this.cellref(i);this.write(this.t.load_reg_src_off(n,e,t,r))}break;default:e.oops()}}bitSizeInfo(t){let n={size:e.sizeOfBitSize(t),immLimit:128};return 1==n.size?n.immLimit=32:2==n.size&&(n.immLimit=64),1!=t&&3!=t||(n.needsSignExt=!0),n}emitExpr(t){switch(t.exprKind){case e.ir.EK.JmpValue:this.write("; jmp value (already in r0)");break;case e.ir.EK.Nop:this.write(this.t.nop());break;case e.ir.EK.FieldAccess:return this.emitExpr(t.args[0]),this.emitFieldAccess(t);case e.ir.EK.Store:return this.emitStore(t.args[0],t.args[1]);case e.ir.EK.RuntimeCall:return this.emitRtCall(t);case e.ir.EK.ProcCall:return this.emitProcCall(t);case e.ir.EK.SharedDef:return this.emitSharedDef(t);case e.ir.EK.Sequence:return t.args.forEach((e=>this.emitExpr(e))),this.clearStack();case e.ir.EK.InstanceOf:return this.emitExpr(t.args[0]),this.emitInstanceOf(t.data,t.jsInfo);default:return this.emitExprInto(t,"r0")}}emitFieldAccess(t,n=!1){let r=t.data,s=(n?"st":"ld")+"fld_"+r.classInfo.id+"_"+r.name;r.needsCheck&&!e.target.switches.skipClassCheck&&(this.emitInstanceOf(r.classInfo,"validate"),s+="_chk");let i=4*r.idx+4,a="#"+i;i>124&&(this.write(this.t.emit_int(i,"r3")),a="r3"),n?this.write(`str r1, [r0, ${a}]`):this.write(`ldr r0, [r0, ${a}]`)}writeFailBranch(){this.write(".fail:"),this.write("mov r1, lr"),this.write(this.t.callCPP("pxt::failedCast"))}emitClassCall(t){let n=t.virtualIndex+e.firstMethodOffset();this.write(this.t.emit_int(4*n,"r1"));let r=t.classInfo,s="";t.isThis&&(s+="_this"),this.emitLabelledHelper("classCall_"+r.id+s,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),e.target.switches.skipClassCheck||t.isThis||this.checkSubtype(r),this.write("ldr r1, [r3, r1] ; ld-method"),this.write("bx r1 ; keep lr from caller"),this.writeFailBranch()}))}helperObject(e){return`.object _pxt_helper_${e.replace(/[^\w]+/g,"_")} "helper: ${e}"`}emitBindHelper(){this.write(`\n ${this.helperObject("bind")}\n .section code\n _pxt_bind_helper:\n push {r0, r2}\n movs r0, #2\n ldlit r1, _pxt_bind_lit\n ${this.t.callCPP("pxt::mkAction")}\n pop {r1, r2}\n str r1, [r0, #12]\n str r2, [r0, #16]\n bx r4 ; return\n\n _pxt_bind_lit:\n ${this.t.obj_header("pxt::RefAction_vtable")}\n .short 0, 0 ; no captured vars\n .word .bindCode@fn\n .bindCode:\n ; r0-bind object, r4-#args\n cmp r4, #12\n bge .fail\n lsls r3, r4, #2\n ldlit r2, _pxt_copy_list\n ldr r1, [r2, r3]\n\n ldr r3, [r0, #12]\n ldr r2, [r0, #16]\n adds r4, r4, #1\n bx r1\n `),this.writeFailBranch(),this.write("_pxt_copy_list:"),this.write(e.U.range(12).map((e=>`.word _pxt_bind_${e}@fn`)).join("\n"));for(let e=0;e<12;e++){this.write(`\n _pxt_bind_${e}:\n sub sp, #4\n `);for(let t=0;t<e;++t)this.write(`ldr r1, [sp, #4*${t+1}]`),this.write(`str r1, [sp, #4*${t}]`);this.write(`\n push {r3} ; this-ptr\n mov r1, lr\n str r1, [sp, #4*${e+1}] ; store LR\n blx r2\n ldr r1, [sp, #4*${e+1}]\n add sp, #8\n bx r1\n `)}}ifaceCallCore(t,n,r=!1){this.write("\n ldr r2, [r3, #12] ; load mult\n movs r7, r2\n beq .objlit ; built-in types have mult=0\n muls r7, r1\n lsrs r7, r2\n lsls r7, r7, #1 ; r7 - hash offset\n ldr r3, [r3, #4] ; iface table\n adds r3, r3, r7\n ; r0-this, r1-method idx, r2-free, r3-hash entry, r4-num args, r7-free\n ");for(let t=0;t<e.vtLookups;++t)t>0&&this.write(" adds r3, #2"),this.write("\n ldrh r2, [r3, #0] ; r2-offset of descriptor\n ldrh r7, [r2, r3] ; r7-method idx\n cmp r7, r1\n beq .hit\n ");"get"==n?(this.write("movs r0, #0 ; undefined"),this.write("bx lr")):this.write("b .fail2"),this.write("\n .hit:\n adds r3, r3, r2 ; r3-descriptor\n ldr r2, [r3, #4]\n lsls r7, r2, #31\n beq .field\n ");const s=this.t.emit_int(t,"r4")+"\n bx r2";if("set"==n?this.write(`\n ; check for next descriptor\n ldrh r7, [r3, #8]\n cmp r7, r1\n bne .fail2 ; no setter!\n ldr r2, [r3, #12]\n ${s}\n `):(this.write("\n ; check if it's getter\n ldrh r7, [r3, #2]\n cmp r7, #1\n "),"get"==n?this.write(`\n bne .bind\n ${s}\n .bind:\n mov r4, lr\n bl _pxt_bind_helper\n `):this.write(`\n beq .doublecall\n ${s}\n .doublecall:\n ; call getter\n movs r4, #1\n push {r0, lr}\n blx r2\n pop {r1, r2}\n mov lr, r2\n b .moveArgs\n `)),r||(this.write(`\n .objlit:\n ldrh r2, [r3, #8]\n cmp r2, #${pxt.BuiltInType.RefMap}\n bne .fail\n mov r4, lr\n `),"set"==n&&this.write("ldr r2, [sp, #4] ; ld-val"),this.write(this.t.callCPP("set"==n?"pxtrt::mapSet":"pxtrt::mapGet")),n?this.write("bx r4"):(this.write("mov lr, r4"),this.write("b .moveArgs"))),this.write(".field:"),"set"==n?this.write("\n ldr r3, [sp, #4] ; ld-val\n str r3, [r0, r2] ; store field\n bx lr\n "):"get"==n?this.write("\n ldr r0, [r0, r2] ; load field\n bx lr\n "):this.write("\n ldr r0, [r0, r2] ; load field\n "),!n){this.write(".moveArgs:");for(let e=0;e<t;++e)e==t-1?this.write("movs r1, r0"):this.write(`ldr r1, [sp, #4*${e+1}]`),this.write(`str r1, [sp, #4*${e}]`);this.lambdaCall(t-1)}r&&this.write(".objlit:"),this.writeFailBranch(),this.write(`\n .fail2:\n ${this.t.callCPP("pxt::missingProperty")}\n `)}emitIfaceCall(t,n,r=""){e.U.assert(t.ifaceIndex>0),this.write(this.t.emit_int(t.ifaceIndex,"r1")),this.emitLabelledHelper("ifacecall"+n+"_"+r,(()=>{this.write("ldr r0, [sp, #0] ; ld-this"),this.loadVTable(),this.ifaceCallCore(n,r)}))}checkSubtype(e,t=".fail",n="r2"){e.classNo?(this.write(`ldrh ${n}, [r3, #8]`),this.write(`cmp ${n}, #${e.classNo}`),e.classNo==e.lastSubtypeNo?this.write(`bne ${t}`):(this.write(`blt ${t}`),this.write(`cmp ${n}, #${e.lastSubtypeNo}`),this.write(`bgt ${t}`))):this.write(`b ${t} ; always fails; class never instantiated`)}loadVTable(e="r2",t=".fail",n=".fail"){this.write(`lsls ${e}, r0, #30`),this.write(`bne ${t}`),this.write("cmp r0, #0"),this.write(`beq ${n}`),this.write("ldr r3, [r0, #0]"),this.write("; vtable in R3")}emitInstanceOf(t,n){let r="inst_"+t.id+"_"+n;this.emitLabelledHelper(r,(()=>{"validateNullable"==n?this.loadVTable("r2",".tagged",".undefined"):this.loadVTable("r2",".fail",".fail"),this.checkSubtype(t),"bool"==n?(this.write(`movs r0, #${e.taggedTrue}`),this.write("bx lr"),this.write(".fail:"),this.write(`movs r0, #${e.taggedFalse}`),this.write("bx lr")):"validate"==n?(this.write("bx lr"),this.writeFailBranch()):"validateNullable"==n?(this.write(".undefined:"),this.write("bx lr"),this.write(".tagged:"),this.write(`cmp r0, #${e.taggedNull} ; check for null`),this.write("bne .fail"),this.write("movs r0, #0"),this.write("bx lr"),this.writeFailBranch()):e.U.oops()}))}emitSharedDef(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return this.emitExpr(n);this.emitExpr(n),this.exprStack.unshift(n),this.write(this.t.push_local("r0")+"; tmpstore @"+this.exprStack.length)}clearArgs(t,n){t.length,n.length;let r=t.concat(n);for(let t of r)0==t.currUses&&1==t.totalUses||(console.log(t.toString()),console.log(r.map((e=>e.toString()))),e.U.oops(`wrong uses: ${t.currUses} ${t.totalUses}`)),t.currUses=1;this.clearStack()}builtInClassNo(e){return{id:"builtin"+e,classNo:e,lastSubtypeNo:e}}emitBeginTry(e){this.emitExprInto(e.args[0],"r0"),this.write("bl _pxt_save_exception_state")}emitRtCall(t,n=null){let r=t.data;if("pxt::beginTry"==r)return this.emitBeginTry(t);let s=t.mask||{refMask:0},i=s.conversions||[],a=t.args.map(((e,t)=>({idx:t,expr:e,isSimple:e.isLiteral(),isRef:0!=(s.refMask&1<<t),conv:i.find((e=>e.argIdx==t))})));e.U.assert(a.length<=4);let o=!1;for(let t of e.U.reversed(a))t.expr.isPure()?t.isSimple||t.isRef||o&&!t.expr.isStateless()||(t.isSimple=!0):o=!0;for(let e of a)e.conv&&(e.isSimple=!1);let l=a.filter((e=>!e.isSimple));if(l.every((e=>e.expr.isPure()&&!e.isRef&&!e.conv))){for(let e of l)e.isSimple=!0;l=[]}let c=l[0],u=!0;if(1!=l.length||c.conv||c.isRef){for(let e of l)this.pushArg(e.expr);this.alignExprStack(0);let t=l.filter((e=>!!e.conv));if(t.length){const n=this.redirectOutput((()=>{let n=0;e.target.switches.inlineConversions||(this.t.stackAligned()?n+=2:n+=1);for(let r of t){if(e.isThumb()&&"pxt::toInt"==r.conv.method){this.write(this.loadFromExprStack("r0",r.expr,n)),this.write("asrs r0, r0, #1");let t=e.target.switches.inlineConversions?r.expr.getId():n;this.write("bcs .isint"+t),this.write("lsls r0, r0, #1"),this.alignedCall(r.conv.method,"",n),this.write(".isint"+t+":"),this.write(this.t.push_fixed(["r0"]))}else this.write(this.loadFromExprStack("r0",r.expr,n)),r.conv.refTag?e.target.switches.skipClassCheck||this.emitInstanceOf(this.builtInClassNo(r.conv.refTag),r.conv.refTagNullable?"validateNullable":"validate"):(this.alignedCall(r.conv.method,"",n),r.conv.returnsRef&&this.write(this.loadFromExprStack("r0",r.expr,n,!0))),this.write(this.t.push_fixed(["r0"]));n++}for(let r of e.U.reversed(t))n--,this.write(this.t.pop_fixed(["r"+r.idx]));for(let e of l)e.conv||this.write(this.loadFromExprStack("r"+e.idx,e.expr,n))}));e.target.switches.inlineConversions?this.write(n):this.emitHelper(this.t.helper_prologue()+n+this.t.helper_epilogue(),"conv")}else for(let e of l)this.write(this.loadFromExprStack("r"+e.idx,e.expr))}else this.emitExpr(c.expr),0!=c.idx&&this.write(this.t.mov("r"+c.idx,"r0")),u=!1;for(let e of a)e.isSimple&&this.emitExprInto(e.expr,"r"+e.idx);n?n():"langsupp::ignore"!=r&&this.alignedCall(r,"",0,!0),u&&this.clearArgs(l.filter((e=>!e.isRef)).map((e=>e.expr)),l.filter((e=>e.isRef)).map((e=>e.expr)))}alignedCall(t,n="",r=0,s=!1){(e.U.startsWith(t,"_cmp_")||e.U.startsWith(t,"_pxt_"))&&(s=!1),this.write(this.t.call_lbl(t,s,this.stackAlignmentNeeded(r))+n)}emitLabelledHelper(e,t){if(this.labelledHelpers[e])this.write(this.t.call_lbl(this.labelledHelpers[e]));else{let n=this.redirectOutput(t);this.emitHelper(n,e),this.labelledHelpers[e]=this.bin.codeHelpers[n]}}emitHelper(e,t="hlp"){if(!this.bin.codeHelpers[e]){let n=Object.keys(this.bin.codeHelpers).length;this.bin.codeHelpers[e]=`_${t}_${n}`}this.write(this.t.call_lbl(this.bin.codeHelpers[e]))}pushToExprStack(e){e.totalUses=1,e.currUses=0,this.exprStack.unshift(e)}pushArg(e){this.clearStack(!0);this.exprStack.length;this.emitExpr(e),this.clearStack(!0),this.write(this.t.push_local("r0")+" ; proc-arg"),this.pushToExprStack(e)}loadFromExprStack(t,n,r=0,s=!1){let i=this.exprStack.indexOf(n);return e.assert(i>=0),this.t.load_reg_src_off(t,"sp",(i+r).toString(),!0,s)+" ; estack\n"}pushDummy(){let t=e.ir.numlit(0);t.totalUses=1,t.currUses=1,this.exprStack.unshift(t)}alignExprStack(e){let t=this.stackAlignmentNeeded(e);if(t)for(let e=0;e<t;++e)this.write("push {r5} ; align"),this.pushDummy()}emitFieldMethods(){for(let t of["get","set"]){this.write(`\n ${this.helperObject(t)}\n .section code\n _pxt_map_${t}:\n `),this.loadVTable("r4"),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefMap),".notmap","r4"),this.write(this.t.callCPPPush("set"==t?"pxtrt::mapSetByString":"pxtrt::mapGetByString")),this.write(".notmap:");let n="set"==t?2:1,r=!1;this.write("mov r4, r3 ; save VT"),"set"==t?(e.target.stackAlign&&(r=!0,this.write("push {lr} ; align")),this.write("\n push {r0, r2, lr}\n mov r0, r1\n ")):this.write("\n push {r0, lr}\n mov r0, r1\n "),this.write("\n bl pxtrt::lookupMapKey\n mov r1, r0 ; put key index in r1\n ldr r0, [sp, #0] ; restore obj pointer\n mov r3, r4 ; restore vt\n bl .dowork\n "),this.write(this.t.pop_locals(n+(r?1:0))),this.write("pop {pc}"),this.write(".dowork:"),this.ifaceCallCore(n,t,!0)}}emitArrayMethod(t,n){this.write(`\n ${this.helperObject(t+" "+(n?"buffer":"array"))}\n .section code\n _pxt_${n?"buffer":"array"}_${t}:\n `),this.loadVTable("r4");let r=this.builtInClassNo(n?pxt.BuiltInType.BoxedBuffer:pxt.BuiltInType.RefCollection);e.target.switches.skipClassCheck||this.checkSubtype(r,".fail","r4");const s=e.isStackMachine()||e.target.runtimeIsARM||n?"ldr":"ldrh";this.write(`\n asrs r1, r1, #1\n bcc .notint\n ${s} r4, [r0, #${n?4:8}]\n cmp r1, r4\n bhs .oob\n `);let i="r1";n?(i="#8",this.write("\n adds r4, r0, r1\n ")):this.write("\n lsls r1, r1, #2\n ldr r4, [r0, #4]\n ");let a=n?"b":"",o=n&&"get"==t?"lsls r0, r0, #1\nadds r0, #1":"";"set"==t?this.write(`\n str${a} r2, [r4, ${i}]\n bx lr\n `):this.write(`\n ldr${a} r0, [r4, ${i}]\n ${o}\n bx lr\n `),this.write(`\n .notint:\n lsls r1, r1, #1\n ${this.t.pushLR()}\n push {r0, r2}\n mov r0, r1\n ${this.t.callCPP("pxt::toInt")}\n mov r1, r0\n pop {r0, r2}\n .doop:\n ${this.t.callCPP(`Array_::${t}At`)}\n ${o}\n ${this.t.popPC()}\n `),this.writeFailBranch(),"get"==t?this.write(`\n .oob:\n movs r0, #${n?1:0} ; 0 or undefined\n bx lr\n `):this.write(`\n .oob:\n ${this.t.pushLR()}\n b .doop\n `)}emitArrayMethods(){for(let e of["get","set"])this.emitArrayMethod(e,!0),this.emitArrayMethod(e,!1)}emitLambdaTrampoline(){let t=e.target.stackAlign?"r3,":"";this.write(`\n ${this.helperObject("trampoline")}\n .section code\n _pxt_lambda_trampoline:\n push {${t} r4, r5, r6, r7, lr}\n mov r4, r8\n mov r5, r9\n mov r6, r10\n mov r7, r11\n push {r4, r5, r6, r7} ; save high registers\n mov r4, r1\n mov r5, r2\n mov r6, r3\n mov r7, r0\n `),this.emitInstanceOf(this.builtInClassNo(pxt.BuiltInType.RefAction),"validate"),this.write(`\n mov r0, sp\n push {r4, r5, r6, r7} ; push args and the lambda\n mov r1, sp\n bl pxt::pushThreadContext\n mov r6, r0 ; save ctx or globals\n mov r5, r7 ; save lambda for closure\n mov r0, r5 ; also save lambda pointer in r0 - needed by pxt::bindMethod\n ldr r1, [r5, #8] ; ld fnptr\n movs r4, #3 ; 3 args\n blx r1 ; execute the actual lambda\n mov r7, r0 ; save result\n @dummystack 4\n add sp, #4*4 ; remove arguments and lambda\n mov r0, r6 ; or pop the thread context\n bl pxt::popThreadContext\n mov r0, r7 ; restore result\n pop {r4, r5, r6, r7} ; restore high registers\n mov r8, r4\n mov r9, r5\n mov r10, r6\n mov r11, r7\n pop {${t} r4, r5, r6, r7, pc}`),this.write(`\n ${this.helperObject("exn")}\n .section code\n ; r0 - try frame\n ; r1 - handler PC\n _pxt_save_exception_state:\n push {r0, lr}\n ${this.t.callCPP("pxt::beginTry")}\n pop {r1, r4}\n str r1, [r0, #1*4] ; PC\n mov r1, sp\n str r1, [r0, #2*4] ; SP\n str r5, [r0, #3*4] ; lambda ptr\n bx r4\n `),this.write("\n .section code\n ; r0 - try frame\n ; r1 - thread context\n _pxt_restore_exception_state:\n mov r6, r1\n ldr r1, [r0, #2*4] ; SP\n mov sp, r1\n ldr r5, [r0, #3*4] ; lambda ptr\n ldr r1, [r0, #1*4] ; PC\n movs r0, #1\n orrs r1, r0\n bx r1\n "),this.write(`\n ${this.helperObject("stringconv")}\n .section code\n _pxt_stringConv:\n `),this.loadVTable(),this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.BoxedString),".notstring"),this.write(`\n bx lr\n\n .notstring: ; no string, but vtable in r3\n ldr r7, [r3, #4*${e.firstMethodOffset()-1}]\n cmp r7, #0\n beq .fail\n push {r0, lr}\n movs r4, #1\n blx r7\n str r0, [sp, #0]\n b .numops\n\n .fail: ; not an object or no toString\n push {r0, lr}\n .numops:\n ${this.t.callCPP("numops::toString")}\n pop {r1}\n pop {pc}\n `)}emitProcCall(t){let n=[],r=null,s="",i=t.data;if(i.proc&&i.proc.inlineBody)return this.emitExpr(i.proc.inlineSelf(t.args));let a=-1==i.virtualIndex,o=!1;for(let r of e.U.reversed(t.args)){if(r.isPure()){if(!o||r.isStateless())continue}else o=!0;n.push(r)}if(n.reverse(),n.length<=1){let e=n[0];e&&(r=e,this.clearStack(!0),this.emitExpr(e),e==t.args[t.args.length-1]?s="r0":(s="r3",this.write(this.t.mov("r3","r0")))),n=[]}else for(let e of n)this.pushArg(e);this.alignExprStack(t.args.length);let l=["r1","r2","r3","r4"],c=[];if(n.length){let e=-1;for(let t of n)e=Math.max(this.exprStack.indexOf(t),e);if(e++,e<=l.length){l=l.slice(0,e),this.write(this.t.pop_fixed(l)),c=this.exprStack.splice(0,e);let t=[];for(let r=e-1;r>=0;--r)n.indexOf(c[r])<0&&(t.push(l[r]),this.exprStack.unshift(c[r]));t.length&&this.write(this.t.push_fixed(t))}else l=null,this.write(this.t.reg_gets_imm("r7",0))}let u=e.U.reversed(t.args);a&&u.unshift(u.pop());for(let t of u)if(n.indexOf(t)>=0){if(l)this.write(this.t.push_fixed([l[c.indexOf(t)]]));else{this.write(this.loadFromExprStack("r0",t)),this.write(this.t.push_local("r0")+" ; re-push"),this.write(this.loadFromExprStack("r7",t,1,!0));let n=this.exprStack.indexOf(t),r=e.ir.numlit(0);r.currUses=1,r.totalUses=1,this.exprStack[n]=r}this.exprStack.unshift(t)}else t===r?(this.write(this.t.push_local(s)+" ; the one arg"),this.pushToExprStack(t)):this.pushArg(t);let p=this.mkLbl("_proccall"),d=-1;if(a){let e=t.args.length-1;this.write(this.loadFromExprStack("r0",t.args[0])),this.emitLabelledHelper("lambda_call"+e,(()=>{this.lambdaCall(e),this.writeFailBranch()}))}else if(null!=i.virtualIndex||null!=i.ifaceIndex)null!=i.ifaceIndex?i.isSet?(e.assert(2==t.args.length),this.emitIfaceCall(i,t.args.length,"set")):this.emitIfaceCall(i,t.args.length,i.noArgs?"get":""):this.emitClassCall(i),this.write(p+":");else{let e=i.proc;d=e.seqNo,this.write(this.t.call_lbl(e.label()+(i.isThis?"_nochk":""))),this.write(p+":")}this.calls.push({procIndex:d,stack:0,addr:0,callLabel:p}),a&&t.args[0].isStateless()?this.clearArgs([t.args[0]],t.args.slice(1)):this.clearArgs([],t.args)}lambdaCall(t){this.write("; lambda call"),this.loadVTable(),e.target.switches.skipClassCheck||this.checkSubtype(this.builtInClassNo(pxt.BuiltInType.RefAction)),this.write(`\n movs r4, #${t}\n ldrh r1, [r0, #4]\n cmp r1, #0\n bne .pushR5\n ldr r1, [r0, #8]\n bx r1 ; keep lr from the caller\n .pushR5:\n sub sp, #8\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e+2}]`),this.write(`str r1, [sp, #4*${e}]`);this.write(`\n str r5, [sp, #4*${t}]\n mov r1, lr\n str r1, [sp, #4*${t+1}]\n mov r5, r0\n ldr r7, [r5, #8]\n blx r7 ; exec actual lambda\n ldr r4, [sp, #4*${t+1}] ; restore what was in LR\n ldr r5, [sp, #4*${t}] ; restore lambda ctx\n `);for(let e=0;e<t;++e)this.write(`ldr r1, [sp, #4*${e}]`),this.write(`str r1, [sp, #4*${e+2}]`);this.write("\n add sp, #8\n bx r4\n "),this.write("; end lambda call")}emitStore(t,n){switch(t.exprKind){case e.ir.EK.CellRef:let r=t.data;if(this.emitExpr(n),r.isGlobal()){let e=this.bitSizeInfo(r.bitSize),t="#"+r.index;r.index>=e.immLimit&&(this.write(this.t.emit_int(r.index,"r1")),t="r1"),this.write(this.t.load_reg_src_off("r7","r6","#0")),this.write(this.t.load_reg_src_off("r0","r7",t,!1,!0,e))}else{let[e,t,n]=this.cellref(r);this.write(this.t.load_reg_src_off("r0",e,t,n,!0))}break;case e.ir.EK.FieldAccess:this.emitRtCall(e.ir.rtcall("dummy",[t.args[0],n]),(()=>this.emitFieldAccess(t,!0)));break;default:e.oops()}}cellref(t){if(t.isGlobal())throw e.oops();if(t.iscap){let n=t.index+3;return e.assert(0<=n&&n<32),["r5",n.toString(),!0]}if(t.isarg){return["sp","args@"+t.index.toString()+":"+this.baseStackSize,!1]}return["sp","locals@"+t.index,!1]}emitLambdaWrapper(e){if(this.write(""),this.write(".section code"),this.write(".balign 4"),e&&(this.proc.info.usedAsValue=!0),!this.proc.info.usedAsValue&&!this.proc.info.usedAsIface)return;this.proc.info.usedAsValue&&(this.write(this.proc.label()+"_Lit:"),this.write(this.t.obj_header("pxt::RefAction_vtable")),this.write(".short 0, 0 ; no captured vars"),this.write(`.word ${this.proc.label()}_args@fn`)),this.write(`${this.proc.label()}_args:`);let t=this.proc.args.length;if(0==t)return;this.write(`cmp r4, #${t}`),this.write(`bge ${this.proc.label()}_nochk`);let n=this.stackAlignmentNeeded(t+1),r=n?t+2:t+1;this.write("push {lr}"),this.emitLabelledHelper(`expand_args_${t}`,(()=>{this.write("movs r0, #0"),this.write("movs r1, #0"),n&&this.write("push {r0}");for(let e=t;e>0;e--)e!=t&&(this.write(`cmp r4, #${e}`),this.write(`blt .zero${e}`),this.write(`ldr r0, [sp, #${r-1}*4]`),this.write(`str r1, [sp, #${r-1}*4] ; clear existing`),this.write(`.zero${e}:`)),this.write("push {r0}");this.write("bx lr")})),this.write(`bl ${this.proc.label()}_nochk`);let s=t+(n?1:0);this.write(`@dummystack ${s}`),this.write(`add sp, #4*${s}`),this.write("pop {pc}")}emitCallRaw(t){let n=e.hexfile.lookupFunc(t);e.assert(!!n,"unimplemented raw function: "+t),this.alignedCall(t)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){const t={"numops::adds":"+","numops::subs":"-","numops::div":"/","numops::mod":"%","numops::muls":"*","numops::ands":"&","numops::orrs":"|","numops::eors":"^","numops::bnot":"~","numops::lsls":"<<","numops::asrs":">>","numops::lsrs":">>>","numops::le":"<=","numops::lt":"<","numops::lt_bool":"<","numops::ge":">=","numops::gt":">","numops::eq":"==","pxt::eq_bool":"==","pxt::eqq_bool":"===","numops::eqq":"===","numops::neqq":"!==","numops::neq":"!="},n={"pxsim.Boolean_":"","pxsim.pxtcore":"","pxsim.String_":"","pxsim.ImageMethods":"","pxsim.Array_":"","pxsim.pxtrt":"","pxsim.numops":""},r={"pxsim.Array_.getAt":"","pxsim.Array_.length":"","pxsim.Array_.mk":"","pxsim.Array_.push":"","pxsim.Boolean_.bang":"","pxsim.String_.concat":"","pxsim.String_.stringConv":"","pxsim.numops.toBool":"","pxsim.numops.toBoolDecr":"","pxsim.pxtcore.mkAction":"","pxsim.pxtcore.mkClassInstance":"","pxsim.pxtrt.ldlocRef":"","pxsim.pxtrt.mapGetByString":"","pxsim.pxtrt.stclo":"","pxsim.pxtrt.stlocRef":""};function s(e){let t="";for(let n of Object.keys(e)){const r=n.replace(/\./g,"_");e[n]=r,t+=`const ${r} = ${n};\n`}return t}function i(e){"pxt."==(e=e.replace(/::/g,".")).slice(0,4)&&(e="pxtcore."+e.slice(4));const t="pxsim."+e;if(r.hasOwnProperty(t))return r[t];const s=t.lastIndexOf(".");if(s>0){const e=t.slice(0,s);if(n.hasOwnProperty(e))return n[e]+t.slice(s)}return t}e.isBuiltinSimOp=function(n){return!!e.U.lookup(t,n.replace(/\./g,"::"))},e.shimToJs=i;const a=["runtime","oops","doNothing","pxsim","globals","maybeYield","setupDebugger","isBreakFrame","breakpoint","trace","checkStack","leave","checkResumeConsumed","setupResume","setupLambda","checkSubtype","failedCast","buildResume","mkVTable","bind","leaveAccessor"];e.jsEmit=function(o,l){let c="(function (ectx) {\n'use strict';\n";for(let e of a)c+=`const ${e} = ectx.${e};\n`;c+="const __this = runtime;\n",c+="const pxtrt = pxsim.pxtrt;\n",c+="let yieldSteps = 1;\n",c+="ectx.setupYield(function() { yieldSteps = 100; })\n",c+="pxsim.setTitle("+JSON.stringify(o.getTitle())+");\n";let u={},p={};for(let e of l.configData||[])u[e.key+""]=e.value,p[e.name]=e.key;c+="pxsim.setConfigData("+JSON.stringify(u,null,1)+", "+JSON.stringify(p,null,1)+");\n",c+="pxtrt.mapKeyNames = "+JSON.stringify(o.ifaceMembers,null,1)+";\n";const d=o.setPerfCounters(["SysScreen"]);c+="__this.setupPerfCounters("+JSON.stringify(d,null,1)+");\n",c+=s(r),c+=s(n);let f=0,m=0;o.procs.forEach((n=>{let r;n.cachedJS?(r=n.cachedJS,f+=r.length):(r=function(n,r){if(r.cachedJS)return r.cachedJS;let s="",a=e=>{s+=e+"\n"},o=e=>{s+=" "+e+"\n"},l=e.ir.EK,c=[],u=0,p={},d="";a(`\nfunction ${r.label()}(s) {\nlet r0 = s.r0, step = s.pc;\ns.pc = -1;\n`),r.perfCounterNo&&a(`if (step == 0) __this.startPerfCounter(${r.perfCounterNo});\n`);a("\nwhile (true) {\nif (yieldSteps-- < 0 && maybeYield(s, step, r0) || runtime !== pxsim.runtime) return null;\nswitch (step) {\n case 0:\n"),r.locals.forEach((e=>{o(`${y(e)} = undefined;`)})),r.args.length&&(o("if (s.lambdaArgs) {"),r.args.forEach(((e,t)=>{o(` ${y(e)} = (s.lambdaArgs[${t}]);`)})),o(" s.lambdaArgs = null;"),o("}"));r.classInfo&&r.info.thisParameter&&(o("r0 = s.arg0;"),$(r.classInfo,"validate"));let f=0,m=[];for(let t of r.body)t.stmtKind==e.ir.SK.Label&&t.lblNumUses>0&&(t.lblId=++f);let h=0;for(let t of r.body){switch(t.stmtKind){case e.ir.SK.Expr:w(t.expr);break;case e.ir.SK.StackEmpty:C();break;case e.ir.SK.Jmp:let n=!1;for(let s=h+1;s<r.body.length&&r.body[s].stmtKind==e.ir.SK.Label;++s)if(t.lbl==r.body[s]){n=!0;break}k(t,n);break;case e.ir.SK.Label:t.lblNumUses>0&&a(` case ${t.lblId}:`);break;case e.ir.SK.Comment:a(`// ${t.expr.data}`);break;case e.ir.SK.Breakpoint:x(t);break;default:e.oops()}h++}C(),r.perfCounterNo&&a(`__this.stopPerfCounter(${r.perfCounterNo});\n`);r.isGetter()?o("return leaveAccessor(s, r0)"):o("return leave(s, r0)");a(" default: oops()"),a("} } }");let g=e.nodeLocationInfo(r.action);g.functionName=r.getName(),g.argumentNames=r.args&&r.args.map((e=>e.getName())),a(`${r.label()}.info = ${JSON.stringify(g)}`),r.isGetter()&&a(`${r.label()}.isGetter = true;`);r.isRoot&&a(`${r.label()}.continuations = [ ${m.join(",")} ]`);return a(b(r.label()+"_mk",r.label(),u,Object.keys(p))),a(d),r.cachedJS=s,s;function b(e,t,n,r){let s="";s+=`\nfunction ${e}(s) {\n checkStack(s.depth);\n return {\n parent: s, fn: ${t}, depth: s.depth + 1,\n pc: 0, retval: undefined, r0: undefined, overwrittenPC: false, lambdaArgs: null,\n`;for(let e=0;e<n;++e)s+=` tmp_${e}: undefined,\n`;for(let e of r)s+=` ${e}: undefined,\n`;return s+="} }\n",s}function x(e){let t,s=e.breakpointInfo.id;if(o(`s.lastBrkId = ${s};`),n.breakpoints){t=++f;let i=`return breakpoint(s, ${t}, ${s}, r0);`;e.breakpointInfo.isDebuggerStmt?o(i):(o(`if ((breakpoints[0] && isBreakFrame(s)) || breakpoints[${s}]) ${i}`),n.trace&&o(`else return trace(${s}, s, ${t}, ${r.label()}.info);`))}else{if(!n.trace)return;t=++f,o(`return trace(${s}, s, ${t}, ${r.label()}.info);`)}a(` case ${t}:`)}function y(e){if(e.isGlobal())return"globals."+e.uniqueName();if(e.iscap)return`s.caps[${e.index}]`;const t=e.uniqueName();return p[t]=!0,"s."+t}function k(t,n){if(t.lbl.lblNumUses==e.ir.lblNumUsesJmpNext||n)return e.assert(t.jmpMode==e.ir.JmpMode.Always),void(t.expr&&w(t.expr));e.assert(t.lbl.lblNumUses>0);let r=`{ step = ${t.lbl.lblId}; continue; }`;t.jmpMode==e.ir.JmpMode.Always?(t.expr&&w(t.expr),o(r)):(w(t.expr),t.jmpMode==e.ir.JmpMode.IfNotZero?o(`if (r0) ${r}`):o(`if (!r0) ${r}`))}function S(e){switch(e.exprKind){case l.NumberLiteral:case l.PointerLiteral:case l.SharedRef:case l.CellRef:return!0;default:return!1}}function T(e){return S(e)?I(e):(w(e),"r0")}function I(t){switch(t.exprKind){case l.NumberLiteral:if(!0===t.data)return"true";if(!1===t.data)return"false";if(null===t.data)return"null";if(void 0===t.data)return"undefined";if("number"==typeof t.data)return t.data+"";throw e.oops("invalid data: "+typeof t.data);case l.PointerLiteral:if(t.ptrlabel())return t.ptrlabel().lblId+"";if(null!=t.hexlit())return d+=`const ${t.data} = pxsim.BufferMethods.createBufferFromHex("${t.hexlit()}")\n`,t.data;if("string"==typeof t.jsInfo)return t.jsInfo;e.U.oops();case l.SharedRef:let n=t.args[0];e.U.assert(!!n.currUses),e.U.assert(n.currUses<n.totalUses),n.currUses++;let r=c.indexOf(n);return e.U.assert(r>=0),"s.tmp_"+r;case l.CellRef:return y(t.data);default:throw e.oops()}}function w(e){switch(e.exprKind){case l.JmpValue:o("// jmp value (already in r0)");break;case l.Nop:o("// nop");break;case l.FieldAccess:let t=e.data,n=t.shimName,r=T(e.args[0]);return n?void o(`r0 = ${r}${n};`):void o(`r0 = ${r}.fields["${t.name}"];`);case l.Store:return K(e.args[0],e.args[1]);case l.RuntimeCall:return N(e);case l.ProcCall:return _(e);case l.SharedDef:return v(e);case l.Sequence:return e.args.forEach(w);case l.InstanceOf:return w(e.args[0]),void $(e.data,e.jsInfo);default:o(`r0 = ${I(e)};`)}}function E(e,t="r0"){return`checkSubtype(${t}, ${`${e.id}_VT`})`}function $(t,n,r="r0"){"bool"==n?o(`r0 = ${E(t)};`):"validate"==n?o(`if (!${E(t,r)}) failedCast(${r});`):e.U.oops()}function v(t){let n=t.args[0];if(e.U.assert(n.totalUses>=1),e.U.assert(0===n.currUses),n.currUses=1,1==n.totalUses)return w(n);{const e=c.length;c.push(n);let t=T(n);"r0"!=t&&(t="r0 = "+t),o(`s.tmp_${e} = ${t};`)}}function N(n){let r=e.ir.flattenArgs(n.args);r.precomp.forEach(w);let s=n.data,l=r.flattened.map(I);if("langsupp::ignore"==s)return;let c="";if(c="."==s[0]?`${l[0]}${s}(${l.slice(1).join(", ")})`:"="==s[0]?`(${l[0]})${s.slice(1)} = (${l[1]})`:e.U.startsWith(s,"new ")?`new ${i(s.slice(4))}(${l.join(", ")})`:e.U.lookup(t,s)?2==l.length?`(${l[0]} ${e.U.lookup(t,s)} ${l[1]})`:`(${e.U.lookup(t,s)} ${l[0]})`:`${i(s)}(${l.join(", ")})`,0==n.callingConvention)o(`r0 = ${c};`);else{let e=++f;m.push(e),"String_::stringConv"==s&&o(`if ((${l[0]}) && (${l[0]}).vtable) {`),2==n.callingConvention?o(`(function(cb) { ${c}.then(cb) })(buildResume(s, ${e}));`):(o(`setupResume(s, ${e});`),o(`${c};`)),o("checkResumeConsumed();"),o("return;"),"String_::stringConv"==s&&o(`} else { s.retval = (${l[0]}) + ""; }`),a(` case ${e}:`),o("r0 = s.retval;")}}function _(t){const s=t.data,i=s.proc;if(i&&i.inlineBody)return w(i.inlineSelf(t.args));const l=e.ir.rtcall("<frame>",[]);l.totalUses=1,l.currUses=0;const u=c.length;c.push(l);const p=`s.tmp_${u}`,d=++f,m=-1==s.virtualIndex;if(i)o(`${p} = ${i.label()}_mk(s);`);else{let i="generic";null!=s.ifaceIndex?i="if_"+n.ifaceMembers[s.ifaceIndex]:m?i="lambda":null!=s.virtualIndex?i=s.classInfo.id+"_v"+s.virtualIndex:e.U.oops();const a=t.args.length;i+="_"+a+"_mk",n.recordHelper(r.usingCtx,i,(()=>{const t=e.U.range(a).map((e=>"arg"+e));return b(i,"null",5,t)})),o(`${p} = ${i}(s);`)}t.args.forEach(((e,t)=>{let n=`arg${t}`;m&&(n=0==t?"argL":"arg"+(t-1)),o(`${p}.${n} = ${T(e)};`)}));let h=`s.pc = ${d}; return ${p};`;if(null!=s.callLocationIndex&&(h=`s.callLocIdx = ${s.callLocationIndex}; ${h}`),null!=s.ifaceIndex){e.U.assert(null==i);const r=n.ifaceMembers[s.ifaceIndex];e.U.assert(!!r,`no name for ${s.ifaceIndex}`),o(`if (!${p}.arg0.vtable.iface) {`);let a=t.args.map(((e,t)=>`${p}.arg${t}`));a.splice(1,0,JSON.stringify(r));const l=`pxsim_pxtrt.map${s.isSet?"Set":"Get"}ByString`;s.noArgs?o(` s.retval = ${l}(${a.join(", ")});`):(e.U.assert(!s.isSet),o(` setupLambda(${p}, ${l}(${a.slice(0,2).join(", ")}), ${t.args.length});`),o(` ${h}`)),o("} else {"),o(` ${p}.fn = ${p}.arg0.vtable.iface["${s.isSet?"set/":""}${r}"];`);let c=`${p}.arg0.fields["${r}"]`;s.isSet?(o(` if (${p}.fn === null) { ${c} = ${p}.arg1; }`),o(` else if (${p}.fn === undefined) { failedCast(${p}.arg0) } `)):s.noArgs?(o(` if (${p}.fn == null) { s.retval = ${c}; }`),o(` else if (!${p}.fn.isGetter) { s.retval = bind(${p}); }`)):(o(` if (${p}.fn == null) { setupLambda(${p}, ${c}, ${t.args.length}); ${h} }`),o(` else if (${p}.fn.isGetter) { ${p}.stage2Call = true; ${h}; }`)),o(` else { ${h} }`),o("}"),h=""}else if(-1==s.virtualIndex)e.U.assert(null==i),o(`setupLambda(${p}, ${p}.argL);`);else if(null!=s.virtualIndex){e.U.assert(null==i),e.assert(s.virtualIndex>=0),$(s.classInfo,"validate",p+".arg0");const t=s.classInfo.vtable[s.virtualIndex];o(`${p}.fn = ${p}.arg0.vtable.methods.${t.getName()};`)}else e.U.assert(null!=i);h&&o(h),a(` case ${d}:`),o("r0 = s.retval;"),l.currUses=1}function A(t){switch(t){case 0:return"";case 1:return"pxtrt.toInt8";case 3:return"pxtrt.toInt16";case 5:return"pxtrt.toInt32";case 2:return"pxtrt.toUInt8";case 4:return"pxtrt.toUInt16";case 6:return"pxtrt.toUInt32";default:throw e.oops()}}function K(t,n){switch(t.exprKind){case l.CellRef:let r=t.data,s=T(n);o(`${y(r)} = ${A(r.bitSize)}(${s});`);break;case l.FieldAccess:let i=t.data,a=i.shimName;a||(a=`.fields["${i.name}"]`),w(e.ir.rtcall("="+a,[t.args[0],n]));break;default:e.oops()}}function C(){for(let t of c)t.totalUses!==t.currUses&&e.oops();u=Math.max(c.length,u),c=[]}}(o,n),m+=r.length),c+="\n"+r+"\n"})),c+=e.U.values(o.codeHelpers).join("\n")+"\n",o.usedClassInfos.forEach((t=>{c+=function(t){e.U.assert(void 0!==t.classNo),e.U.assert(void 0!==t.lastSubtypeNo);let n=parseInt(t.attrs.maxBgInstances);n||(n=null);let r=`const ${t.id}_VT = mkVTable({\n name: ${JSON.stringify(e.getName(t.decl))},\n numFields: ${t.allfields.length},\n classNo: ${t.classNo},\n lastSubtypeNo: ${t.lastSubtypeNo},\n maxBgInstances: ${n},\n methods: {\n`;for(let e of t.vtable)r+=` "${e.getName()}": ${e.label()},\n`;r+=" },\n",r+=" iface: {\n";for(let e of t.itable)r+=` "${e.name}": ${e.proc?e.proc.label():"null"},\n`,e.setProc?r+=` "set/${e.name}": ${e.setProc.label()},\n`:e.proc||(r+=` "set/${e.name}": null,\n`);return r+=" },\n",t.toStringMethod&&(r+=" toStringMethod: "+t.toStringMethod.label()+",\n"),r+="});\n",r}(t)})),l.breakpoints&&(c+=`\nconst breakpoints = setupDebugger(${l.breakpoints.length}, [${o.globals.filter((e=>e.isUserVariable)).map((e=>`"${e.uniqueName()}"`)).join(",")}])\n`),c+=`\nreturn ${o.procs[0]?o.procs[0].label():"null"}\n})\n`;const h=c.length,g=e=>(100*e/h).toFixed(2)+"%",b=`// total=${c.length} new=${g(m)} cached=${g(f)} other=${g(h-m-f)}\n`;o.writeFile(e.BINARY_JS,b+c)}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.thumbCmpMap={"numops::lt":"_cmp_lt","numops::gt":"_cmp_gt","numops::le":"_cmp_le","numops::ge":"_cmp_ge","numops::eq":"_cmp_eq","numops::eqq":"_cmp_eqq","numops::neq":"_cmp_neq","numops::neqq":"_cmp_neqq"};const t={"numops::adds":"_numops_adds","numops::subs":"_numops_subs","numops::orrs":"_numops_orrs","numops::eors":"_numops_eors","numops::ands":"_numops_ands","numops::lsls":"_numops_lsls","numops::asrs":"_numops_asrs","numops::lsrs":"_numops_lsrs","pxt::toInt":"_numops_toInt","pxt::fromInt":"_numops_fromInt"};class n extends e.AssemblerSnippets{stackAligned(){return e.target.stackAlign&&e.target.stackAlign>1}pushLR(){return this.stackAligned()?"push {lr, r5} ; r5 for align":"push {lr}"}popPC(){return this.stackAligned()?"pop {pc, r5} ; r5 for align":"pop {pc}"}nop(){return"nop"}mov(e,t){return`mov ${e}, ${t}`}helper_ret(){return"bx r4"}reg_gets_imm(e,t){return`movs ${e}, #${t}`}push_fixed(e){return"push {"+e.join(", ")+"}"}pop_fixed(e){return"pop {"+e.join(", ")+"}"}proc_setup(e,t){let n="";if(e>0){n+=" movs r0, #0\n";for(let t=0;t<e;++t)n+=" push {r0} ;loc\n"}return n}proc_return(){return"pop {pc}"}debugger_stmt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; debugger\n subs r0, r0, #4 ; debugger\n${t}:\n ldr r0, [r0, #0] ; debugger\n`}debugger_bkpt(t){return e.oops(),`\n @stackempty locals\n ldr r0, [r6, #0] ; brk\n${t}:\n ldr r0, [r0, #0] ; brk\n`}debugger_proc(t){return e.oops(),`\n ldr r0, [r6, #0] ; brk-entry\n ldr r0, [r0, #4] ; brk-entry\n${t}:`}push_local(e){return`push {${e}}`}push_locals(e){return`sub sp, #4*${e} ; push locals ${e} (align)`}pop_locals(e){return`add sp, #4*${e} ; pop locals ${e}`}unconditional_branch(e){return"bb "+e}beq(e){return"beq "+e}bne(e){return"bne "+e}cmp(e,t){return"cmp "+e+", "+t}cmp_zero(e){return"cmp "+e+", #0"}load_reg_src_off(e,t,n,r,s,i){n=n.replace(/:\d+$/,""),r&&(n=`#4*${n}`);let a="str",o="ldr";return i&&(32==i.immLimit?a="strb":64==i.immLimit&&(a="strh"),o=i.needsSignExt?a.replace("str","ldrs"):a.replace("str","ldr")),s?`${a} ${e}, [${t}, ${n}]`:`${o} ${e}, [${t}, ${n}]`}rt_call(e,t,n){return e+" "+t+", "+n}alignedCall(e,t){return t?`${this.push_locals(t)}\nbl ${e}\n${this.pop_locals(t)}`:"bl "+e}call_lbl(n,r,s){let i=e.U.lookup(t,n);return i&&(n=i,r=!1),!r&&n.indexOf("::")>0&&(r=!0),r?this.callCPP(n,s):this.alignedCall(n,s)}call_reg(e){return"blx "+e}helper_prologue(){return`\n @stackmark args\n ${this.pushLR()}\n`}helper_epilogue(){return`\n ${this.popPC()}\n @stackempty args\n`}load_ptr_full(t,n){return e.assert(!!t),`\n ldlit ${n}, ${t}\n`}load_vtable(e,t){return`ldr ${e}, [${t}, #0]`}lambda_init(){return"\n mov r5, r0\n mov r4, lr\n bl pxtrt::getGlobalsPtr\n mov r6, r0\n bx r4\n"}saveThreadStack(){return"mov r7, sp\n str r7, [r6, #4]\n"}restoreThreadStack(){return e.target.switches.gcDebug?"movs r7, #0\n str r7, [r6, #4]\n":""}callCPPPush(e){return this.pushLR()+"\n"+this.callCPP(e)+"\n"+this.popPC()+"\n"}callCPP(e,t){return this.saveThreadStack()+this.alignedCall(e,t)+"\n"+this.restoreThreadStack()}inline_decr(e){return`\n lsls r1, r0, #30\n bne .tag${e}\n bl _pxt_decr\n.tag${e}:\n`}arithmetic(){let t="";const n=e=>{let t=".boxed:\n";return t+=`\n ${this.pushLR()}\n push {r0, r1}\n ${this.saveThreadStack()}\n ${e}\n ${this.restoreThreadStack()}\n add sp, #8\n ${this.popPC()}\n `,t},r=e=>{t+=`\n_numops_${e}:\n @scope _numops_${e}\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n`},s=e=>{t+=" blx lr\n",t+=n(`bl numops::${e}`)};for(let e of["adds","subs"])r(e),t+=`\n subs r2, r1, #1\n ${e} r2, r0, r2\n bvs .boxed\n movs r0, r2\n`,s(e);for(let e of["ands","orrs","eors"])r(e),t+=` ${e} r0, r1\n`,"eors"==e&&(t+=" adds r0, r0, #1\n"),s(e);for(let e of["lsls","lsrs","asrs"])r(e),t+="\n ; r3 := (r1 >> 1) & 0x1f\n lsls r3, r1, #26\n lsrs r3, r3, #27\n","asrs"==e?t+="\n asrs r0, r3\n movs r2, #1\n orrs r0, r2\n":(t+="lsrs"==e?"\n asrs r2, r0, #1\n lsrs r2, r3\n lsrs r3, r2, #30\n bne .boxed\n":"\n asrs r2, r0, #1\n lsls r2, r3\n lsrs r3, r2, #30\n beq .ok\n cmp r3, #3\n bne .boxed\n.ok:\n",t+="\n lsls r0, r2, #1\n adds r0, r0, #1\n"),s(e);t+=`\n@scope _numops_toInt\n_numops_toInt:\n asrs r0, r0, #1\n bcc .over\n blx lr\n.over:\n lsls r0, r0, #1\n ${this.callCPPPush("pxt::toInt")}\n\n_numops_fromInt:\n lsls r2, r0, #1\n asrs r1, r2, #1\n cmp r0, r1\n bne .over2\n adds r0, r2, #1\n blx lr\n.over2:\n ${this.callCPPPush("pxt::fromInt")}\n`;for(let r of Object.keys(e.thumbCmpMap))r=r.replace(/.*::/,""),t+=`\n.section code\n.object _pxt_helper_cmp_${r}\n_cmp_${r}:\n lsls r2, r0, #31\n beq .boxed\n lsls r2, r1, #31\n beq .boxed\n subs r0, r1\n b${r.replace("qq","q").replace("neq","ne")} .true\n.false:\n movs r0, #0\n bx lr\n.true:\n movs r0, #1\n bx lr\n`,t+=n(`\n bl numops::${r}\n bl numops::toBoolDecr\n cmp r0, #0`);return t}emit_int(t,n){let r=!1;function s(t){e.assert(0<=t&&t<=255);let s="";return r?t&&(s=`adds ${n}, #${t}\n`):s=`movs ${n}, #${t}\n`,r=!0,s}function i(e=8){return`lsls ${n}, ${n}, #${e}\n`}e.assert(null!=t);let a=Math.floor(t),o=!1;a<0&&(o=!0,a=-a);let l=0;if(a>255){let t=a;for(;0==(1&t);)t>>>=1,l++;e.numBytes(t)<e.numBytes(a)?a=t:l=0}let c="";switch(e.numBytes(a)){case 4:c+=s(a>>>24&255),c+=i();case 3:c+=s(a>>>16&255),c+=i();case 2:c+=s(a>>>8&255),c+=i();case 1:c+=s(255&a);break;default:e.oops()}return l&&(c+=i(l)),o&&(c+=`negs ${n}, ${n}\n`),c.split("\n").length>4?`ldlit ${n}, ${Math.floor(t)}\n`:c}}e.ThumbSnippets=n}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n={"pxtrt::mapSetGeneric":"mapset","pxtrt::mapGetGeneric":"mapget"},r={};function s(e,n,r){const s=t.computeHashMultiplier(e.itable.map((e=>e.idx))),i=t.U.toArray(s.mapping);for(;3&i.length;)i.push(0);let a=`\n${l(e)}_start:\n .short ${8*e.allfields.length+8} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n .short ${i.length} ; entries in iface hashmap\n .short ${e.lastSubtypeNo||e.classNo} ; last sub class-id\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${s.mult} ; hash-mult\n`;c()?a+="\n .word pxt::RefRecord_destroy\n .word pxt::RefRecord_print\n .word pxt::RefRecord_scan\n .word pxt::RefRecord_gcsize\n .word 0,0,0,0 ; keep in sync with VM_NUM_CPP_METHODS\n":a+="\n .word 0,0, 0,0, 0,0, 0,0 ; space for 4 (VM_NUM_CPP_METHODS) native methods\n",a+=`\n .balign 4\n${e.id}_IfaceVT:\n`;const o=i.length>>2;let u="",p=o,d={};for(let t of e.itable){d[t.idx+""]=p;const e=t.proc?t.proc.isGetter()?1:2:0;u+=` .short ${t.idx}, ${e} ; ${t.name}\n`,u+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,p+=1,t.setProc&&(u+=` .short ${t.idx}, 2 ; set ${t.name}\n`,u+=` .word ${t.setProc.vtLabel()}@fn\n`,p+=1)}u+=" .word 0, 0, 0, 0 ; the end\n",p+=1;for(let e=0;e<i.length;++e)r.itEntries++,i[e]&&r.itFullEntries++;return a+=" .short "+t.U.toArray(i).map(((e,t)=>d[e+""]||o)).join(", ")+"\n",a+=u,a+="\n",a}let i;function a(e){const t=e.getTime()/1e3;return`${t>>>0}, ${t/4294967296|0}`}!function(e){e[e.Invalid=0]="Invalid",e[e.InfoHeader=1]="InfoHeader",e[e.OpCodeMap=2]="OpCodeMap",e[e.NumberLiterals=3]="NumberLiterals",e[e.ConfigData=4]="ConfigData",e[e.IfaceMemberNames=5]="IfaceMemberNames",e[e.NumberBoxes=6]="NumberBoxes",e[e.Function=32]="Function",e[e.Literal=33]="Literal",e[e.VTable=34]="VTable"}(i||(i={}));let o={};function l(e){return e.classNo||(o[e.id]=e),e.id+"_VT"}function c(){return t.target.useESP}function u(e){return c()?`0xffffffff, ${e}`:`0xffffffff, 0xffffffff ; -> ${e}`}t.vmEmit=function(p,d,f){let m=`; VM start\n_img_start:\n${t.hexfile.hexPrelude()}\n`;o={};const h={dblText:[],dblBoxText:[],dbls:{},opcodeMap:{},opcodes:t.vm.opcodes.map((e=>"pxt::op_"+e.replace(/ .*/,"")))};for(h.opcodes.unshift(null);h.opcodes.length<128;)h.opcodes.push(null);let g=0;function b(e,t,n,r,s=0){if(m+=`\n; --- ${e}\n.section code\n .set ${e} = ${g}\n`,r)for(let e of r)m+=` .set ${e} = ${g}\n`;m+=`\n_start_${e}:\n .byte ${t}, 0x00\n .short ${s}\n .word _end_${e}-_start_${e}\n`,m+=n(),m+=`\n.balign 8\n_end_${e}:\n`,g++}const x=new Date(0);let y=t.U.toUTF8(d.name,!0);y.length>100&&(y=y.slice(0,100));let k=y.length+1;1&k&&k++;const S=128-k;b("_info",i.InfoHeader,(()=>`\n ; magic - \\0 added by assembler\n .string "\\nPXT64\\n"\n .hex 5471fe2b5e213768 ; magic\n .hex ${t.hexfile.hexTemplateHash()} ; hex template hash\n .hex 0000000000000000 ; @SRCHASH@\n .word ${p.globalsWords} ; num. globals\n .word ${p.nonPtrGlobals} ; non-ptr globals\n .word 0, 0 ; last usage time\n .word ${a(x)} ; installation time\n .word ${a(x)} ; publication time - TODO\n .word _img_end-_img_start ; total image size\n .space 60 ; reserved\n .string ${JSON.stringify(y)}\n .space ${S} ; pad to 128 bytes\n`)),p.procs.forEach((e=>{b(e.label(),i.Function,(()=>function(e,s,i){let a="";const o=e=>{a+=e+"\n"},p=e=>{a+=" "+e+"\n"},d=t.ir.EK;let f=[],m=[],h=!1,g=0,b=0;const x=8388607;pxt.options.debug&&console.log("EMIT",i.toString());y(),a="";for(let e of f)e.reset();return h=!0,t.U.assert(0==b),y(),a;function y(){o(`;\n; ${i.getFullName()}\n;`),p(".section code"),s.procs[0]==i&&o("; main"),p(`.word ${u("pxt::RefAction_vtable")}`),p(`.short 0, ${i.args.length} ; #args`),p(`.short ${i.captured.length}, 0 ; #cap`),p(".word .fnstart-_img_start, 0 ; func+possible padding"),g=i.locals.length+m.length,p(".fnstart:"),p(`pushmany ${g} ; incl. ${m.length} tmps`);for(let e of i.body)switch(e.stmtKind){case t.ir.SK.Expr:E(e.expr);break;case t.ir.SK.StackEmpty:_();for(let e of m)e&&t.oops(`uses: ${e.currUses}/${e.totalUses} ${e.toString()}`);break;case t.ir.SK.Jmp:k(e);break;case t.ir.SK.Label:o(`${e.lblName}:`);break;case t.ir.SK.Comment:o(`; ${e.expr.data}`);break;case t.ir.SK.Breakpoint:break;default:t.oops()}p(`ret ${i.args.length}, ${g}`)}function k(e){let n=e.lbl.lblName;e.jmpMode==t.ir.JmpMode.Always?(e.expr&&E(e.expr),p(`jmp ${n}`)):(E(e.expr),e.jmpMode==t.ir.JmpMode.IfNotZero?p(`jmpnz ${n}`):e.jmpMode==t.ir.JmpMode.IfZero?p(`jmpz ${n}`):t.oops())}function S(e){if(e.isGlobal())return t.U.assert(0==(3&e.index)),"glb "+(e.index>>2)+` ; ${e.getName()}`;if(e.iscap)return"cap "+e.index+` ; ${e.getName()}`;if(e.isarg){let n=i.args.length-e.index-1;return t.assert(n>=0,"arg#"+n),`loc ${b+g+2+n} ; ${e.getName()}`}{let n=e.index+m.length;return t.assert(!h||n<g,"cell#"+n),t.assert(n>=0,"cell#"+n),`loc ${b+n}`}}function T(n){const r=t.hexfile.lookupFunc(n);r||t.U.oops("missing function: "+n);let s=e.opcodeMap[r.name];null==s&&(s=e.opcodes.length,e.opcodes.push(r.name),e.opcodeMap[r.name]=s,r.value=s),p(`callrt ${n}`)}function I(e,n){"bool"==n?p(`checkinst ${l(e)}`):t.U.oops()}function w(n){switch(n.exprKind){case d.NumberLiteral:const r=t.taggedSpecial(n.data);if(null!=r)p(`ldspecial ${r} ; ${n.data}`);else{let r=n.data,s=0,i=0;const a=r<<1>>1!=r;if((0|r)==r){if(Math.abs(r)<=x)return void p(r<0?"ldintneg "+-r:`ldint ${r}`);s=(r<<1|1)>>>0,i=r<0?1:0}else{let e=new Float64Array(1);e[0]=r;let t=new Uint32Array(e.buffer);t[1]+=65536,s=t[0],i=t[1]}let o=s+","+i,l=t.U.lookup(e.dbls,o);if(null==l){if(l=e.dblText.length,e.dblText.push(`.word ${s}, ${i} ; ${l}: ${n.data}`),a){const t="pxt::number_vt";e.dblBoxText.push(`.word ${c()?t:`0xffffffff ; ${t}`}\n`);let n=new Float64Array(1);n[0]=r;let s=new Uint32Array(n.buffer);e.dblBoxText.push(`.word ${s[0]}, ${s[1]} ; ${r}\n`)}e.dbls[o]=l}p(`ldnumber ${l} ; ${n.data}`)}return;case d.PointerLiteral:return void p(`ldlit ${n.data}`);case d.SharedRef:let s=n.args[0];(!s.currUses||s.currUses>=s.totalUses)&&(console.log(s.sharingInfo()),t.U.assert(!1)),s.currUses++;let i=m.indexOf(s);return i<0&&(console.log(m,s),t.assert(!1)),p(`ldloc ${i+b}`+(s.currUses==s.totalUses?" ; LAST":"")),void _();case d.CellRef:return void p("ld"+S(n.data));case d.InstanceOf:E(n.args[0]),I(n.data,n.jsInfo);break;default:throw t.oops("kind: "+n.exprKind)}}function E(e){switch(e.exprKind){case d.JmpValue:p("; jmp value (already in r0)");break;case d.Nop:p("; nop");break;case d.FieldAccess:let t=e.data;E(e.args[0]),p(`ldfld ${t.idx}, ${l(t.classInfo)}`);break;case d.Store:return K(e.args[0],e.args[1]);case d.RuntimeCall:return N(e);case d.ProcCall:return A(e);case d.SharedDef:return $(e);case d.Sequence:return e.args.forEach(E);default:return w(e)}}function $(e){let n=e.args[0];if(t.U.assert(n.totalUses>=1),t.U.assert(0===n.currUses),n.currUses=1,f.push(n),1==n.totalUses)return E(n);{E(n);let e=-1;for(let t=0;t<m.length;++t)if(null==m[t]){e=t;break}e<0?(h&&(console.log(n,m),t.assert(!1,"missed tmp")),e=m.length,m.push(n)):m[e]=n,p(`stloc ${e+b}`)}}function v(){p("push"),b++}function N(e){let s=e.data;if("pxt::beginTry"==s)return void p(`try ${e.args[0].data}`);s=t.U.lookup(r,s)||s,_();let i=t.U.lookup(n,s),a=e.args,o=0;if("pxt::mkClassInstance"!=s){for(let e=0;e<a.length;++e)E(a[e]),e<a.length-1&&(v(),o++);"langsupp::ignore"==s?o&&p(`popmany ${o} ; ignore`):i?p(i):T(s),b-=o}else p(`newobj ${a[0].data}`)}function _(){for(let e=0;e<m.length;++e){let t=m[e];t&&t.currUses==t.totalUses&&(h||f.push(t),m[e]=null)}}function A(e){let n=e.data,r=n.proc;if(r&&r.inlineBody){const t=r.inlineSelf(e.args);return pxt.options.debug&&console.log("INLINE",e.toString(),"->",t.toString()),E(t)}let i=0;const a=e.args.slice(),o=-1==n.virtualIndex?a.shift():null;for(let e of a)E(e),v(),i++;let l=a.length;if(o)E(o),p(`callind ${l}`);else if(null!=n.ifaceIndex){let e=n.ifaceIndex+" ; ."+s.ifaceMembers[n.ifaceIndex];n.isSet?(p(`callset ${e}`),t.U.assert(2==l)):n.noArgs?(p(`callget ${e}`),t.U.assert(1==l)):p(`calliface ${l}, ${e}`)}else null!=n.virtualIndex?t.U.oops():p(`callproc ${r.label()}`);b-=i}function K(e,n){switch(e.exprKind){case d.CellRef:E(n);let r=e.data,s="st"+S(r);if(r.isGlobal()&&0!=r.bitSize){const e=t.sizeOfBitSize(r.bitSize)|(t.isBitSizeSigned(r.bitSize)?16:0);p("bitconv "+e)}p(s);break;case d.FieldAccess:let i=e.data;E(e.args[0]),v(),E(n),p(`stfld ${i.idx}, ${l(i.classInfo)}`),b--;break;default:t.oops()}}}(h,p,e)),[e.label()+"_Lit"])})),m+="_code_end:\n\n",m+="_helpers_end:\n\n",p.usedClassInfos.forEach((e=>{b(l(e),i.VTable,(()=>s(e,0,p)))})),t.U.values(o).forEach((e=>{e.itable=[],e.classNo=65520,b(l(e),i.VTable,(()=>s(e,0,p)))})),o={};let T=0;b("ifaceMemberNames",i.IfaceMemberNames,(()=>` .word ${p.ifaceMembers.length} ; num. entries\n`+p.ifaceMembers.map((e=>` .word ${p.emitString(e)} ; ${T++} .${e}`)).join("\n"))),m+="_vtables_end:\n\n",t.U.iterMap(p.hexlits,((e,n)=>{b(n,i.Literal,(()=>`.word ${u("pxt::buffer_vt")}\n`+t.hexLiteralAsm(e)),[],pxt.BuiltInType.BoxedBuffer)})),t.U.unique(p.ifaceMembers.concat(Object.keys(p.strings)),(e=>e)).forEach((e=>{const n=t.utf8AsmStringLiteral(e);let r=pxt.BuiltInType.BoxedString;"pxt::string_inline_ascii_vt"==n.vt?r=pxt.BuiltInType.BoxedString_ASCII:"pxt::string_skiplist16_packed_vt"==n.vt?r=pxt.BuiltInType.BoxedString_SkipList:"pxt::string_inline_utf8_vt"==n.vt?r=pxt.BuiltInType.BoxedString:t.oops("invalid vt");const s=`.word ${u(n.vt)}\n`+n.asm;b(p.strings[e],i.Literal,(()=>s),[],r)})),b("numberBoxes",i.NumberBoxes,(()=>h.dblBoxText.join("\n")+"\n.word 0, 0, 0 ; dummy entry to make sure not empty")),b("numberLiterals",i.NumberLiterals,(()=>h.dblText.join("\n")+"\n.word 0, 0 ; dummy entry to make sure not empty"));const I=f.configData||[];b("configData",i.ConfigData,(()=>I.map((e=>` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}`)).join("\n")+"\n .word 0, 0"));let w=h.opcodes.map((e=>null==e?"":e)).join("\0")+"\0",E="";for(;w;){let e=w.slice(0,64);w=w.slice(64),1&e.length&&(e+="\0"),E+=".hex "+t.U.toHex(t.U.stringToUint8Array(e))+"\n"}b("opcodeMap",i.OpCodeMap,(()=>E)),m+="_literals_end:\n",m+="_img_end:\n",m+="\n; The end.\n",p.writeFile(t.BINARY_ASM,m);let $=t.assemble(d.target,p,m);const v=$.thumbFile.getSourceMap(),N=function(e){const n=[83,82,67,77,136,21,78,45,170,134,153,113,0,0,0,0];for(const r of Object.keys(e)){for(const e of t.U.stringToUint8Array(r))n.push(e);n.push(0);const i=e[r];let a=0,o=0;for(let e=0;e<i.length;e+=3)s(i[e]-a),s(i[e+1]-o>>1),s(i[e+2]>>1),a=i[e],o=i[e+1];n.push(255)}n.push(0),1&n.length&&n.push(0);const r=[];for(let e=0;e<n.length;e+=2)r.push(n[e]|n[e+1]<<8);return r;function s(e){if(0<=e&&e<240)n.push(e);else{let t=240;e<0&&(e=-e,t|=8);const r=n.length;n.push(null);let s=0;for(;0!=e;)n.push(255&e),e>>>=8,s++;n[r]=t|s}}}(v);$.src&&p.writeFile(t.BINARY_ASM,`; srcmap size: ${N.length<<1} bytes\n`+$.src);{let e="";for(let t of $.buf)e+=String.fromCharCode(255&t,t>>8);const n=t.U.sha256(e);for(let e=0;e<4;++e)$.buf[16+e]=parseInt(n.slice(4*e,4*e+4),16);v.__meta={name:d.name,programHash:$.buf[16]|$.buf[17]<<16}}if(p.writeFile(t.BINARY_SRCMAP,JSON.stringify(v)),pxt.options.debug){let e=$.thumbFile.peepCounts,t=Object.keys(e);t.sort(((t,n)=>e[n]-e[t]));for(let n of t.slice(0,50))console.log(`${n} ${e[n]}`)}if($.buf){let n="";const r=$.buf;for(;15&r.length;)r.push(0);t.U.pushRange(r,N);for(let e of r)n+=String.fromCharCode(255&e,e>>8);if(n=e.pxtc.encodeBase64(n),c()){p.writeFile(t.BINARY_PXT64,n);const s=t.hexfile.patchHex(p,r,!1,!!t.target.useUF2)[0];p.writeFile(pxt.outputName(t.target),e.pxtc.encodeBase64(s))}else p.writeFile(pxt.outputName(t.target),n)}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,s;!function(e){e.DecompileLiterals="decompileLiterals",e.TaggedTemplate="taggedTemplate",e.DecompileIndirectFixedInstances="decompileIndirectFixedInstances",e.DecompileArgumentAsString="decompileArgumentAsString"}(r=n.DecompileParamKeys||(n.DecompileParamKeys={})),function(e){e[e.SingleLine=0]="SingleLine",e[e.MultiLine=1]="MultiLine"}(s=n.CommentKind||(n.CommentKind={})),n.FILE_TOO_LARGE_CODE=9266,n.DECOMPILER_ERROR=9267;const i=e.SyntaxKind,a=/^[^\f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/,o=/^(?:Array<(.+)>)|(?:(.+)\[\])$/,l="math_number",c="math_number_minmax",u="math_integer",p="math_whole_number",d="text",f="logic_boolean",m={"+":{type:"math_arithmetic",op:"ADD"},"-":{type:"math_arithmetic",op:"MINUS"},"/":{type:"math_arithmetic",op:"DIVIDE"},"*":{type:"math_arithmetic",op:"MULTIPLY"},"**":{type:"math_arithmetic",op:"POWER"},"%":{type:"math_modulo",leftName:"DIVIDEND",rightName:"DIVISOR"},"<":{type:"logic_compare",op:"LT"},"<=":{type:"logic_compare",op:"LTE"},">":{type:"logic_compare",op:"GT"},">=":{type:"logic_compare",op:"GTE"},"==":{type:"logic_compare",op:"EQ"},"===":{type:"logic_compare",op:"EQ"},"!=":{type:"logic_compare",op:"NEQ"},"!==":{type:"logic_compare",op:"NEQ"},"&&":{type:"logic_operation",op:"AND"},"||":{type:"logic_operation",op:"OR"}},h=/^\s*\/\/\s*(.*)$/,g=/^\s*(?:(?:(?:\/\*\*?)|(?:\*))(?!\/))?\s*(.*?)(?:\*?\*\/)?$/;class b{constructor(e){this.renames=e,this.renames.sort(((e,t)=>e.span.start-t.span.start))}getRenamesInSpan(e,t){const n=[];for(const r of this.renames){if(r.span.start>t)break;r.span.start>=e&&n.push(r)}return n}getRenameForPosition(e){for(const t of this.renames){if(t.span.start>e)return;if(t.span.start===e)return t}}}function x(e,t,n=!0){if(1===e.length&&"x"!==e&&"y"!==e&&"z"!==e){const r=e.charCodeAt(0);if(r>=97&&r<=122){const e=r-97;for(let r=1;r<26;r++){const s=String.fromCharCode(97+(e+r)%26);if("x"!==s&&"y"!==s&&"z"!==s&&!t[s])return n&&(t[s]=!0),s}}}for(let r=2;;r++){const s=e+r;if(!t[s])return n&&(t[s]=!0),s}}let y;function k(n,s,a=!1,o=!1){switch(n.kind){case i.WhileStatement:case i.IfStatement:case i.Block:return;case i.ExpressionStatement:return k(n.expression,s,a,o);case i.VariableStatement:return function(e,t){for(const n of e.declarationList.declarations){const e=l(n,t);if(e)return e}return}(n,s);case i.CallExpression:return function(n,s,a=!1,o=!1){const l=t.pxtInfo(n).callInfo;if(!l)return t.Util.lf("Function call not supported in the blocks");const c=s.attrs(l);let u;e.isIdentifier(n.expression)&&(u=s.declaredFunctions[n.expression.text]);if(!a&&l.isExpression&&!u){if(s.aliasBlocks[l.qName])l.decompilerBlockAlias=s.aliasBlocks[l.qName];else if(!s.opts.snippetMode)return t.Util.lf("No output expressions as statements")}if("Math.pow"==l.qName)return;if(pxt.Util.startsWith(l.qName,"Math.")){if(F(l.qName.substring(5)))return}if(c.blockId===t.PAUSE_UNTIL_TYPE){const e=n.arguments[0];if(1===n.arguments.length&&x(e))return;return t.Util.lf("Predicates must be inline expressions that return a value")}const p=A(l,c);if(p&&!c.handlerStatement&&!o)return t.Util.lf("Events must be top level");if(!c.blockId||!c.block){const e=pxt.blocks.builtinFunctionInfo[l.qName];if(!e)return u?u.parameters.length!==l.args.length?t.Util.lf("Function calls in blocks must have the same number of arguments as the function definition"):void 0:t.Util.lf("Call statements must have a valid declared function");c.blockId=e.blockId}const d=U(l,s.blocks),f=s.blocks.apis.byQName[l.qName],m=pxt.blocks.compileInfo(f),h=m.parameters.length+(m.thisParameter?1:0);if(c.imageLiteral||c.gridLiteral){if(l.args.length-h>1)return t.Util.lf("Function call has more arguments than are supported by its block");let e=n.arguments[0];if(e.kind!=i.StringLiteral&&e.kind!=i.NoSubstitutionTemplateLiteral)return t.Util.lf("Only string literals supported for image literals");const r=(e.text||"").replace(/\s+/g,""),s=c.imageLiteralRows||5,a=(c.imageLiteralColumns||5)*(c.imageLiteral||c.gridLiteral),o=a*s;return a*s!=r.length?t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",o,r.length):void 0}const g=l.args.length-h;if(g>0&&!b()){let e=g;if(p&&e--,c.defaultInstance&&e--,e>0)return t.Util.lf("Function call has more arguments than are supported by its block")}if(m.parameters.length||p){let e;const t=c.defaultInstance||!!m.thisParameter;if(d.forEach(((n,r)=>{e||t&&0===r||(t&&r--,e=y(n))})),e)return e}if(f){const e=s.blocks.apis.byQName[f.namespace];if(e&&e.attributes.fixedInstances&&!e.attributes.decompileIndirectFixedInstances&&l.args.length){const e=t.pxtInfo(l.args[0]).callInfo;if(!e||!s.attrs(e).fixedInstance)return t.Util.lf("Fixed instance APIs can only be called directly from the fixed instance")}}return;function b(){if(c.mutatePropertyEnum&&2===g&&l.args.length>=2){const e=l.args[l.args.length-2],t=l.args[l.args.length-1];if(e.kind===i.ArrayLiteralExpression&&C(t)){const n=[];if(!e.elements.some((e=>e.kind!==i.PropertyAccessExpression||e.expression.kind!==i.Identifier||(n.push(e.name.text),e.expression.text!==c.mutatePropertyEnum)))){const e=w(t);if(e){const t=e[0];return t.length===n.length&&!n.some((e=>-1===t.indexOf(e)))}}}}return!1}function x(e){if(e.kind!==i.FunctionExpression&&e.kind!==i.ArrowFunction)return!1;const n=e;if(function(e){switch(e.kind){case i.BinaryExpression:{const t=e.operatorToken.kind;return t!=i.PlusEqualsToken&&t!=i.MinusEqualsToken&&t!=i.EqualsToken}case i.PrefixUnaryExpression:{const t=e.operator;return t!=i.PlusPlusToken&&t!=i.MinusMinusToken}case i.PostfixUnaryExpression:{const t=e.operator;return t!=i.PlusPlusToken&&t!=i.MinusMinusToken}case i.CallExpression:{const n=t.pxtInfo(e).callInfo;return t.assert(!!n),n.isExpression}case i.Identifier:case i.ParenthesizedExpression:case i.NumericLiteral:case i.StringLiteral:case i.NoSubstitutionTemplateLiteral:case i.TrueKeyword:case i.FalseKeyword:case i.NullKeyword:case i.TaggedTemplateExpression:return!0;default:return!1}}(n.body))return!0;const r=n.body;if(1===r.statements.length){if(v(r.statements[0]).kind===i.ReturnStatement)return!0}return!1}function y(e){const n=v(e.value),a=e.info,o=e.param;if(a.isEnum){if(l(n))return;if(n.kind===i.CallExpression){const e=t.pxtInfo(n).callInfo,r=s.attrs(e);if(e&&"TD_ID"===r.shim&&e.args&&1===e.args.length){if(l(v(e.args[0])))return}}else if(n.kind===i.Identifier){const e=t.pxtInfo(n).commentAttrs;if(e&&e.enumIdentity)return}return t.Util.lf("Enum arguments may only be literal property access expressions")}if(K(n)&&(o.fieldEditor||o.shadowBlockId)){let e=!(!o.fieldOptions||!o.fieldOptions[r.DecompileLiterals]);if(!e&&o.shadowBlockId){const t=s.blocks.blocksById[o.shadowBlockId];if(t&&t.parameters&&t.parameters.length){const n=t.parameters[0].name;e=!t.attributes.paramFieldEditorOptions||!t.attributes.paramFieldEditorOptions[n]||!!t.attributes.paramFieldEditorOptions[n][r.DecompileLiterals]}else e=!0}if(!e)return t.Util.lf("Field editor does not support literal arguments")}else if(n.kind===i.TaggedTemplateExpression&&o.fieldEditor){let e=o.fieldOptions&&o.fieldOptions[r.TaggedTemplate];if(!e)return t.Util.lf("Tagged templates only supported in custom fields with param.fieldOptions.taggedTemplate set");const s=v(n.tag).getText(),a=e.split(";").map((e=>e.trim()));if(-1===a.indexOf(s))return t.Util.lf("Function only supports template literals with tag '{0}'",a.join(", "));if(n.template.kind!==i.NoSubstitutionTemplateLiteral)return t.Util.lf("Tagged template literals cannot have substitutions")}else if(n.kind===i.ArrowFunction){const e=n;if(e.parameters.length)if("objectdestructuring"===c.mutate){const n=v(e.parameters[0]);if(n.kind===i.Parameter&&n.name.kind!==i.ObjectBindingPattern)return t.Util.lf("Object destructuring mutation callbacks can only have destructuring patters as arguments")}else for(const n of e.parameters)if(n.name.kind!==i.Identifier)return t.Util.lf("Only identifiers allowed as function arguments")}else if(s.blocks.apis.byQName[a.type]){if(s.blocks.apis.byQName[a.type].attributes.fixedInstances){if(L(o))return;if(o.shadowBlockId){const e=s.blocks.blocksById[o.shadowBlockId];if(e){const t=pxt.blocks.compileInfo(e);if(t.parameters&&L(t.parameters[0]))return}}const e=t.pxtInfo(n).callInfo;if(e&&s.attrs(e).fixedInstance)return;return t.Util.lf("Arguments of a fixed instance type must be a reference to a fixed instance declaration")}}return;function l(e){const t=a.type.split("."),n=[];for(;e.kind===i.PropertyAccessExpression;)n.unshift(e.name.text),e=e.expression;if(e.kind!==i.Identifier)return!1;n.unshift(e.text);for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}}}(n,s,a,o);case i.VariableDeclaration:return l(n,s);case i.PostfixUnaryExpression:case i.PrefixUnaryExpression:return function(e){if(e.operand.kind!=i.Identifier)return t.Util.lf("-- and ++ may only be used on an identifier");if(e.operator!==i.PlusPlusToken&&e.operator!==i.MinusMinusToken)return t.Util.lf("Only ++ and -- supported as prefix or postfix unary operators in a statement");return}(n);case i.FunctionExpression:case i.ArrowFunction:return function(e,n){let r=!1;if(e.parameters.length){let s=$(e)[0];if(s&&t.pxtInfo(s).callInfo){let a=t.pxtInfo(s).callInfo;r="objectdestructuring"===n.attrs(a).mutate?e.parameters[0].name.kind!==i.ObjectBindingPattern:e.parameters.some((e=>e.name.kind!==i.Identifier))}}if(r)return t.Util.lf("Unsupported parameters in error function");return}(n,s);case i.BinaryExpression:return function(e,n){if(e.left.kind===i.ElementAccessExpression){if(e.operatorToken.kind!==i.EqualsToken)return t.Util.lf("Element access expressions may only be assigned to using the equals operator")}else{if(e.left.kind===i.PropertyAccessExpression)return e.operatorToken.kind!==i.EqualsToken&&e.operatorToken.kind!==i.PlusEqualsToken?t.Util.lf("Property access expressions may only be assigned to using the = and += operators"):E(e.left,n);if(e.left.kind!==i.Identifier)return t.Util.lf("This expression cannot be assigned to");switch(e.operatorToken.kind){case i.EqualsToken:return E(e.right,n);case i.PlusEqualsToken:case i.MinusEqualsToken:return;default:return t.Util.lf("Unsupported operator token in statement {0}",i[e.operatorToken.kind])}}return}(n,s);case i.ForStatement:return function(e){if(!e.initializer||!e.incrementor||!e.condition)return t.Util.lf("for loops must have an initializer, incrementor, and condition");if(e.initializer.kind!==i.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for loop initializers");const n=e.initializer;if(!n.declarations)return t.Util.lf("for loop with out-of-scope variables not supported");if(1!=n.declarations.length)return t.Util.lf("for loop with multiple variables not supported");const r=n.declarations[0];if(r.initializer.kind!==i.NumericLiteral||"0"!==r.initializer.text)return t.Util.lf("for loop initializers must be initialized to 0");const s=r.name.text;if(!o(s))return t.Util.lf("for loop incrementors may only increment the variable declared in the initializer");if(e.condition.kind!==i.BinaryExpression)return t.Util.lf("for loop conditionals must be binary comparison operations");const a=e.condition;if(a.left.kind!==i.Identifier||a.left.text!==s)return t.Util.lf("left side of for loop conditional must be the variable declared in the initializer");if(a.operatorToken.kind!==i.LessThanToken&&a.operatorToken.kind!==i.LessThanEqualsToken)return t.Util.lf("for loop conditional operator must be either < or <=");return;function o(t){if(e.incrementor.kind===i.PostfixUnaryExpression||e.incrementor.kind===i.PrefixUnaryExpression){const n=e.incrementor;if(n.operator===i.PlusPlusToken&&n.operand.kind===i.Identifier)return n.operand.text===t}return!1}}(n);case i.ForOfStatement:return function(e){if(e.initializer.kind!==i.VariableDeclarationList)return t.Util.lf("only variable declarations are permitted in for of loop initializers");return}(n);case i.FunctionDeclaration:return function(e,n){if(!n)return t.Util.lf("Function declarations must be top level");if(e.parameters.length>0&&s.opts.allowedArgumentTypes)for(const n of e.parameters){if(n.initializer||n.questionToken)return t.Util.lf("Function parameters cannot be optional");const e=n.type?n.type.getText():void 0;if(!e)return t.Util.lf("Function parameters must declare a type");const r=B(e);if(-1===s.opts.allowedArgumentTypes.indexOf(r)&&!t.U.endsWith(r,"[]"))return t.Util.lf("Only types that can be added in blocks can be used for function arguments")}return}(n,o);case i.EnumDeclaration:return function(e,n){if(!n)return t.Util.lf("Enum declarations must be top level");const r=e.name.text;if(!s.blocks.enumsByName[r])return t.Util.lf("Enum declarations in user code must have a block");let a=!1;if(e.members.forEach((e=>{if(e.name.kind!==i.Identifier&&(a=!0),!a&&e.initializer){if(e.initializer.kind===i.NumericLiteral)return;if(e.initializer.kind===i.BinaryExpression){const t=e.initializer;if(t.operatorToken.kind===i.LessThanLessThanToken&&t.left.kind===i.NumericLiteral&&t.right.kind===i.NumericLiteral&&"1"==t.left.text)return}a=!0}})),a)return t.Util.lf("Invalid initializer for enum member");return}(n,o);case i.ModuleDeclaration:return function(e){const t=S(e,s);if(!t)return;return T(e)?t:void 0}(n);case i.ReturnStatement:return function(n){if(r(n))return;return t.Util.lf("Return statements can only be used within top-level function declarations");function r(t){const n=e.getEnclosingBlockScopeContainer(t);if(n)switch(n.kind){case i.SourceFile:case i.ArrowFunction:case i.FunctionExpression:return!1;case i.FunctionDeclaration:return n.parent&&n.parent.kind===i.SourceFile&&!k(n,s,!1,!0);default:return r(n)}return!1}}(n);case i.BreakStatement:case i.ContinueStatement:case i.DebuggerStatement:case i.EmptyStatement:return}return t.Util.lf("Unsupported statement in block: {0}",i[n.kind]);function l(e,n){let r;return e.name.kind!==i.Identifier?r=t.Util.lf("Variable declarations may not use binding patterns"):e.initializer?I(e)||(r=E(e.initializer,n)):r=t.Util.lf("Variable declarations must have an initializer"),r}}function S(n,r){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");const s=r.blocks.kindsByName[n.name.text];if(!s)return t.Util.lf("Only namespaces with 'kind' blocks can be decompiled");const a=t.Util.lf("Namespaces may only contain valid 'kind' exports");for(const t of n.body.statements){if(R(t))return a;if(!e.isVariableStatement(t)||!t.declarationList.declarations)return a;{const n=1===t.declarationList.declarations.length,r=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===i.ExportKeyword,o=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&r&&o))return a;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isCallExpression(n.initializer)||!e.isIdentifier(n.name))return a;const r=n.initializer;if(r.arguments.length)return a;if(e.isPropertyAccessExpression(r.expression)&&e.isIdentifier(r.expression.expression)){if(r.expression.expression.text!==s.name||r.expression.name.text!==s.createFunctionName)return a}else{if(!e.isIdentifier(r.expression))return a;if(r.expression.text!==s.createFunctionName)return a}}}}}function T(n){if(!e.isModuleBlock(n.body))return t.Util.lf("Namespaces cannot be nested.");if(n.name.text!==pxt.sprite.TILE_NAMESPACE)return t.Util.lf("Tileset namespace must be named myTiles");const r=t.Util.lf("The myTiles namespace can only export tile variables with image literal initializers and no duplicate ids"),s=t.Util.lf("Tileset members must have a blockIdentity comment and no other annotations"),a=new RegExp(`${pxt.sprite.TILE_PREFIX}(\\d+)`),o=[],l=/^\s*\/\/%\s*blockIdentity=[^\s]+\s*$/;for(const t of n.body.statements){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());if(!n||!n.length)return s;{const e=n.map((e=>t.getSourceFile().text.substr(e.pos,e.end-e.pos))).filter((e=>!!e));if(1!==e.length||!l.test(e[0]))return s}if(!e.isVariableStatement(t)||!t.declarationList.declarations)return r;{const n=1===t.declarationList.declarations.length,s=t.modifiers&&1===t.modifiers.length&&t.modifiers[0].kind===i.ExportKeyword,l=t.declarationList.flags&e.NodeFlags.Const;if(!(n&&s&&l))return r;{const n=t.declarationList.declarations[0];if(!n.initializer||!e.isTaggedTemplateExpression(n.initializer)||!e.isIdentifier(n.name))return r;const s=n.initializer;if(!e.isIdentifier(s.tag)||"img"!==s.tag.text)return r;const i=a.exec(n.name.text);if(!i||-1!==o.indexOf(i[1]))return r;o.push(i[1])}}}}function I(n){if(n.initializer){if(n.initializer.kind===e.SyntaxKind.NullKeyword||n.initializer.kind===e.SyntaxKind.FalseKeyword||(r=n.initializer).kind===i.ArrayLiteralExpression&&0===r.elements.length)return!0;if(e.isStringOrNumericLiteral(n.initializer)){const e=n.initializer.getText();return"0"===e||N(e)}{const e=t.pxtInfo(n.initializer).callInfo;if(e&&e.isAutoCreate)return!0}}var r;return!1}function w(e){if(1===e.parameters.length&&e.parameters[0].name.kind===i.ObjectBindingPattern){const n=e.parameters[0].name.elements,r={};return[n.map((e=>{if(t(e.propertyName)&&t(e.name)){const t=e.name.text;if(e.propertyName){const n=e.propertyName.text;return r[n]=t,n}return t}return""})),r]}return;function t(e){return!e||e.kind===i.Identifier}}function E(n,r){switch(n.kind){case i.NumericLiteral:case i.TrueKeyword:case i.FalseKeyword:case i.ExpressionStatement:case i.ArrayLiteralExpression:case i.ElementAccessExpression:return;case i.ParenthesizedExpression:return E(n.expression,r);case i.StringLiteral:case i.FirstTemplateToken:case i.NoSubstitutionTemplateLiteral:return function(e){const n=e.text;return a.test(n)?void 0:t.Util.lf("Only whitespace character allowed in string literals is space")}(n);case i.Identifier:const o=t.pxtInfo(n);return(s=n)&&s.kind===i.Identifier&&"undefined"===s.text?t.Util.lf("Undefined is not supported in blocks"):!_(n)||o.commentAttrs&&o.commentAttrs.blockIdentity&&o.commentAttrs.enumIdentity?void 0:t.Util.lf("Variable is declared in another file");case i.BinaryExpression:const l=n.operatorToken.getText();return m[l]?void 0:t.Util.lf("Could not find operator {0}",l);case i.PrefixUnaryExpression:const c=n.operator;return c===i.MinusToken||c===i.PlusToken||c===i.ExclamationToken?void 0:t.Util.lf("Unsupported prefix unary operator{0}",c);case i.PropertyAccessExpression:return function(n,r){const s=t.pxtInfo(n).callInfo;if(s){const a=r.attrs(s),o=r.compInfo(s);if(a.blockIdentity||"lists_length"===a.blockId||"text_length"===a.blockId)return;if(s.decl.kind===i.EnumMember){if(n.expression.kind===i.Identifier){const e=n.expression.text;if(r.declaredEnums[e])return}const[e,s]=$(n);let a=!0;if(e){const n=t.pxtInfo(e).callInfo;if(n&&n.args){const e=r.blocks.apis.byQName[n.qName],t=1==e.kind||2==e.kind;e&&n.args.forEach(((n,r)=>{if(n===s){e.parameters[t?r-1:r].isEnum&&(a=!1)}}))}}return a?t.Util.lf("Enum value without a corresponding block"):void 0}if(a.fixedInstance&&n.parent){if(n.parent.parent&&n.parent.kind===i.PropertyAccessExpression&&n.parent.parent.kind===i.CallExpression){if(n.parent.parent.expression===n.parent)return}else if(n.parent.kind===i.CallExpression&&n.parent.expression!==n)return}else{if(a.blockCombine||a.blockId&&o&&o.thisParameter)return E(n.expression,r);if(e.isIdentifier(n.expression)&&r.declaredKinds[n.expression.text]){const e=n.name.text,t=r.declaredKinds[n.expression.text];if(t&&(-1!==t.kindInfo.initialMembers.indexOf(e)||-1!==t.declaredNames.indexOf(e)))return}}}return t.Util.lf("No call info found")}(n,r);case i.CallExpression:return k(n,r,!0,void 0);case i.TaggedTemplateExpression:return function(e,n){const r=t.pxtInfo(e).callInfo;if(!r)return t.Util.lf("Invalid tagged template");const s=n.attrs(r);if(!s.blockIdentity)return t.Util.lf("Tagged template does not have blockIdentity set");const i=n.blocks.apis.byQName[s.blockIdentity];if(!i)return t.Util.lf("Could not find blockIdentity for tagged template");if(1!==pxt.blocks.compileInfo(i).parameters.length)return t.Util.lf("Tagged template functions must have 1 argument");return}(n,r);case i.AsExpression:return function(n){if("any"===n.type.getText().trim()&&(e.isStringOrNumericLiteral(n.expression)||n.expression.kind===i.TrueKeyword||n.expression.kind===i.FalseKeyword)){const[e]=$(n);if(e.kind===i.BinaryExpression)switch(e.operatorToken.kind){case i.EqualsEqualsToken:case i.EqualsEqualsEqualsToken:case i.ExclamationEqualsToken:case i.ExclamationEqualsEqualsToken:case i.LessThanToken:case i.LessThanEqualsToken:case i.GreaterThanToken:case i.GreaterThanEqualsToken:return}}return t.Util.lf("Casting not supported in blocks")}(n)}var s;return t.Util.lf("Unsupported syntax kind for output expression block: {0}",i[n.kind])}function $(e){return e.parent?e.parent.kind===i.ParenthesizedExpression?$(e.parent):[e.parent,e]:[void 0,e]}function v(e){for(;e.kind===i.ParenthesizedExpression;)e=e.expression;return e}function N(e){return'""'===e||"''"===e||"``"===e}function _(e){return!!(4&t.pxtInfo(e).flags)}function A(e,n){if(n.blockId===t.PAUSE_UNTIL_TYPE)return!1;e.decl.parameters;return e.args.some(((e,t)=>e&&C(e)))}function K(e){if(!e)return!1;switch(e.kind){case i.ParenthesizedExpression:return K(e.expression);case i.ArrayLiteralExpression:const t=e;for(const e of t.elements)if(!K(e)&&e.kind!==i.TaggedTemplateExpression)return!1;return!0;case i.NumericLiteral:case i.StringLiteral:case i.NoSubstitutionTemplateLiteral:case i.TrueKeyword:case i.FalseKeyword:return!0;case i.PrefixUnaryExpression:const n=e;return(n.operator===i.PlusToken||n.operator===i.MinusToken)&&K(n.operand);default:return!1}}function C(e){return e.kind===i.ArrowFunction||e.kind===i.FunctionExpression}function U(e,t){const n=[],r=t.apis.byQName[e.qName];if(r){const s=t.apis.byQName[e.qName].attributes,i=pxt.blocks.compileInfo(r);pxt.blocks.builtinFunctionInfo[e.qName];let a=s.imageLiteral?1:0;i.thisParameter?n.push({value:v(e.args[0]),info:null,param:i.thisParameter}):s.defaultInstance&&n.push({value:v(e.args[0]),info:r.parameters[0],param:{definitionName:"__instance__",actualName:"this"}});const o=!(!i.thisParameter&&!s.defaultInstance);o&&a++;for(let t=a;t<e.args.length;t++)n.push({value:v(e.args[t]),info:r.parameters[o?t-1:t],param:i.parameters[t-a]})}return n}function P(e){return e.body.statements.map((e=>{const t=e.declarationList.declarations[0];return{name:t.name.text,initializer:t.initializer.getText()}}))}function L(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileIndirectFixedInstances]}function F(e){return M(e)||O(e)||D(e)||-1!==pxt.blocks.MATH_FUNCTIONS.binary.indexOf(e)}function M(e){return-1!==pxt.blocks.MATH_FUNCTIONS.unary.indexOf(e)}function O(e){return-1!==pxt.blocks.MATH_FUNCTIONS.infix.indexOf(e)}function D(e){return-1!==pxt.blocks.ROUNDING_FUNCTIONS.indexOf(e)}function B(e){const t=o.exec(e);return t?`${t[1]||t[2]}[]`:e}function R(t){const n=e.getLeadingCommentRangesOfNode(t,t.getSourceFile());return!(!n||!n.length)}function q(t,n,r=!1){const i=[],a=t.getFullText();if(n&&n.length)for(const o of n){const n=e.getLineOfLocalPosition(t,o.end),l=e.getStartPositionOfLine(n+1,t)||a.length,c=e.getStartPositionOfLine(n+2,t)||a.length,u=!r&&!a.substr(l,c-l).trim();let p=a.substr(o.pos,o.end-o.pos);if(p&&(p=p.replace(/\r\n/g,"\n")),o.kind===e.SyntaxKind.SingleLineCommentTrivia){const e=h.exec(p);e?i.push({kind:s.SingleLine,text:e[1],start:o.pos,end:o.end,hasTrailingNewline:!!o.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r}):i.push({kind:s.SingleLine,text:"",start:o.pos,end:o.end,hasTrailingNewline:!!o.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}else{const e=p.split("\n").map((e=>{const t=g.exec(e);return t?t[1]:""}));i.push({kind:s.MultiLine,lines:e,start:o.pos,end:o.end,hasTrailingNewline:!!o.hasTrailingNewLine,followedByEmptyLine:u,isTrailingComment:r})}}return i}function j(e){let n="";for(const r of e)if(r.kind===s.SingleLine){if(r.text===t.ON_START_COMMENT||r.text===t.HANDLER_COMMENT)continue;n+=r.text.trim()+"\n"}else for(const e of r.lines)n+=e.trim()+"\n";return n.trim()}function z(e){const[t]=$(e);return!t||t.kind==i.SourceFile||(t.kind==i.ExpressionStatement?z(t):t.kind==i.VariableDeclarationList&&z(t.parent))}function V(t){const n=t.getFullText(),r=e.createScanner(t.languageVersion,!1,t.languageVariant,n,void 0,t.getFullStart());let s,a,o=[];for(;r.getTextPos()<t.end;){const l=r.scan();if(l===i.SingleLineCommentTrivia||l===i.MultiLineCommentTrivia){s=e.getLeadingCommentRanges(n,r.getTokenPos())||[],a=e.getTrailingCommentRanges(n,r.getTokenPos())||[],a=a.filter((e=>!s.some((t=>t.pos===e.pos)))),o.push(...q(t,s,!1)),o.push(...q(t,a,!0));for(const e of o)e.end>r.getTextPos()&&r.setTextPos(e.end)}}return o.sort(((e,t)=>e.start-t.start)),o}function G(e,t){let n;for(let r=0;r<t.length;r++)n=t[r],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e)}function H(e){let t=!1;if("expr"===e.value.kind){const n=e.value;if(n.type===l&&e.shadowType===c&&(n.type=c,n.fields[0].name="SLIDER",n.mutation=e.shadowMutation),t=n.type===e.shadowType,!t)switch(n.type){case"math_number":case"math_number_minmax":case"math_integer":case"math_whole_number":case"logic_boolean":case"text":t=!e.shadowType}}return t}n.RenameMap=b,n.buildRenameMap=function(n,r,{declarations:s,takenNames:i}={declarations:"variables",takenNames:{}}){let a=e.createLanguageService(new t.LSHost(n));const o=[];let l=(function t(n){e.forEachChild(n,(n=>{if(e.isDeclarationName(n)&&("all"===s||e.isVariableDeclaration(n.parent))){const e=n.getText();if(i[e]){const t=x(e,i),s=a.findRenameLocations(r.fileName,n.pos+1,!1,!1);s&&s.forEach((n=>{o.push({name:t,diff:t.length-e.length,span:n.textSpan})}))}else i[e]=!0}t(n)}))}(r),i);return[new b(o),l]},n.getNewName=x,function(e){e[e.None=0]="None",e[e.InBlocksOnly=1]="InBlocksOnly",e[e.InTextBlocks=2]="InTextBlocks"}(y||(y={})),n.decompileToBlocks=function(a,o,h,g){let b=0,x=o.statements;const L={blocksInfo:a,outfiles:{},diagnostics:[],success:!0,times:{}};h.generateSourceMap&&(L.blockSourceMap=[]);const R={blocks:a,declaredFunctions:{},declaredEnums:{},declaredKinds:{},functionParamIds:{},attrs:ae,compInfo:function(e){const t=a.apis.byQName[e.qName];if(t)return pxt.blocks.compileInfo(t);return},localReporters:[],tileset:[],opts:h||{},aliasBlocks:{}};o.getFullText();let q="";const J=[],Q={},W=[],Y=[],Z=(()=>{let e=0;return()=>""+e++})(),X=a.apis.byQName;Object.keys(X).forEach((e=>{const t=X[e];t.attributes.blockAliasFor&&X[t.attributes.blockAliasFor]&&(R.aliasBlocks[t.attributes.blockAliasFor]=t.qName)}));const ee=V(o),te=n=>{if(n.kind!==i.FunctionDeclaration||k(n,R,!1,!0))if(n.kind!==i.EnumDeclaration||k(n,R,!1,!0))if(e.isModuleDeclaration(n))if(S(n,R))T(n)||(R.tileset=P(n).map((({name:e,initializer:t})=>({projectId:parseInt(e.substr(pxt.sprite.TILE_PREFIX.length)),data:pxt.sprite.imageLiteralToBitmap(t).data()}))));else{const e=n.name.text,t=P(n);R.declaredKinds[e]&&R.declaredKinds[e].declaredNames.push(...t.map((({name:e})=>e)))}else n.kind===i.Block&&e.forEachChild(n,te);else{const e=n.name.text;R.declaredEnums[e]=!0,function(e){const n=[];return e.members.forEach((e=>{t.U.assert(e.name.kind===i.Identifier);const r=e.name.text;let s;if(e.initializer)if(e.initializer.kind===i.NumericLiteral)s=parseInt(e.initializer.text);else{const n=e.initializer;t.U.assert(n.left.kind===i.NumericLiteral),t.U.assert("1"===n.left.text),t.U.assert(n.operatorToken.kind===i.LessThanLessThanToken),t.U.assert(n.right.kind===i.NumericLiteral);s=1<<parseInt(n.right.text)}else s=0===n.length?0:n[n.length-1][1]+1;n.push([r,s])})),n}(n).forEach((([t,n])=>{J.push({name:n+t,type:e})}))}else R.declaredFunctions[et(n.name)]=n};Object.keys(a.kindsByName).forEach((e=>{const t=a.kindsByName[e];R.declaredKinds[e]={kindInfo:t,declaredNames:[]}})),e.forEachChild(o,te);const ne=()=>(Math.PI*Math.random()).toString(36).slice(2);let re;Object.keys(R.declaredFunctions).forEach((e=>{R.functionParamIds[e]={},R.declaredFunctions[e].parameters.forEach((t=>{R.functionParamIds[e][t.name.getText()]=ne()+ne()}))})),Object.keys(R.declaredKinds).forEach((e=>{const t="KIND_"+e;R.declaredKinds[e].declaredNames.forEach((e=>J.push({name:e,type:t})))})),(J.length||R.tileset.length)&&(se("<variables>"),J.forEach((e=>{se(`<variable type="${t.U.htmlEscape(e.type)}">${t.U.htmlEscape(e.name)}</variable>`)})),R.tileset.forEach((e=>{se(`<variable type="${pxt.sprite.BLOCKLY_TILESET_TYPE}">${pxt.sprite.legacy.tileToBlocklyVariable(e)}</variable>`)})),se("</variables>"));try{re=We(x,void 0,!0,void 0,!h.snippetMode);for(const e of ee)e.owner||W.push({refId:Z(),comment:[e]})}catch(r){if(!r.programTooLarge)return pxt.reportException(r),L.success=!1,L.diagnostics=t.patchUpDiagnostics([{file:o,start:o.getFullStart(),length:o.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.DECOMPILER_ERROR}]),L;L.success=!1,L.diagnostics=t.patchUpDiagnostics([{file:o,start:o.getFullStart(),length:o.getFullWidth(),messageText:r.message,category:e.DiagnosticCategory.Error,code:n.FILE_TOO_LARGE_CODE}])}return re?he(re):h.snippetMode||x.length||(Te(e.pxtc.ON_START_TYPE,pe(e.pxtc.ON_START_TYPE,x[0])),Ie()),W.forEach((e=>{!function(e){let n=0;const r=j(e.comment);if(r.trim()){const s=r.split("\n");s.forEach((e=>n=Math.max(n,e.length)));const i=Math.max(Math.min(10*n,480),160);se(`<comment h="${Math.max(Math.min(40*s.length,360),120)}" w="${i}" data="${t.U.htmlEscape(e.refId)}">`),se(t.U.htmlEscape(r)),se("</comment>")}}(e)})),L.outfiles[o.fileName.replace(/(\.blocks)?\.\w*$/i,"")+".blocks"]=`<xml xmlns="http://www.w3.org/1999/xhtml">\n${q}</xml>`,L;function se(e,t="\n"){q+=e+t}function ie(n,r){const s=r||`Language feature "${n.getFullText().trim()}"" not supported in blocks`,i=t.patchUpDiagnostics([{file:o,start:n.getFullStart(),length:n.getFullWidth(),messageText:s,category:e.DiagnosticCategory.Error,code:1001}]);pxt.debug(`decompilation error: ${s}`),t.U.pushRange(L.diagnostics,i),L.success=!1}function ae(e){const n=a.apis.byQName[e.decompilerBlockAlias||e.qName];if(n){const e=n.attributes;if(!e.blockId||a.blocksById[e.blockId]||e.blockId===t.PAUSE_UNTIL_TYPE)return n.attributes}else if(e.decl){const n=t.parseComments(e.decl);if(n)return n}return{paramDefl:{},callingConvention:0}}function oe(n){const r=n.expression,s=t.pxtInfo(r).callInfo,i=ae(s);if(i.blockAllowMultiple)return;if(i.blockHandlerKey)return i.blockHandlerKey;const a=s.args.filter((t=>!e.isArrowFunction(t)&&!C(t))).map((e=>le(e))).join("$$");return i.blockId+"-"+a}function le(e){if(!e)return"";switch(e.kind){case i.ParenthesizedExpression:case i.AsExpression:return le(e.expression);case i.Identifier:return e.text;case i.StringLiteral:case i.FirstTemplateToken:case i.NoSubstitutionTemplateLiteral:return`"${e.text}"`;case i.NumericLiteral:return e.text;case i.TrueKeyword:return"true";case i.FalseKeyword:return"false";case i.BinaryExpression:return`{${le(e.left)}${e.operatorToken.getText()}${le(e.right)}}`;case i.PrefixUnaryExpression:return e.operator+le(e.operand);case i.PropertyAccessExpression:return le(e.expression)+"."+le(e.name);case i.ArrayLiteralExpression:return`[${e.elements.map((e=>le(e)))}]`;case i.ElementAccessExpression:return`${e.expression}[${e.argumentExpression}]`;case i.TaggedTemplateExpression:return`${le(e.tag)}\`${e.template.getText()}\``;case i.CallExpression:return`${le(e.expression)}(${e.arguments.map(le).join(",")})`;default:return e.getText()}}function ce(){if(b++,b>1500){let e=new Error(t.Util.lf("Could not decompile because the script is too large"));throw e.programTooLarge=!0,e}}function ue(t,n){if(t==e.pxtc.ON_START_TYPE)return"xRRgvHNlG#rZ^u`HECiY";const r=function(){const e="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,n=[];for(let r=0;r<20;r++)n[r]=e.charAt(Math.random()*t);return n.join("")}();if(n){const e=n.getFullStart();L.blockSourceMap.push({id:r,startPos:e,endPos:e+n.getFullWidth()})}return r}function pe(e,t){const n={kind:"statement",type:e};return L.blockSourceMap&&(n.id=ue(e,t)),n}function de(e,t){return{kind:"expr",type:e}}function fe(e,t,n,r){return(!n||n===l)&&r&&r.min&&r.max&&(n=c),{kind:"value",name:e,value:t,shadowType:n,shadowMutation:r}}function me(e){if(e.expression.kind==i.CallExpression){const n=e.expression,r=t.pxtInfo(n).callInfo;if(!r)return ie(e),!1;const s=ae(r);return s.blockId&&!s.handlerStatement&&!r.isExpression&&A(r,s)}return!1}function he(e){e&&(Te(e.type,e),be(e),void 0!==e.data&&se(`<data>${t.U.htmlEscape(e.data)}</data>`),e.handlers&&e.handlers.forEach(ke),e.next&&(se("<next>"),he(e.next),se("</next>")),void 0!==e.comment&&se(`<comment pinned="false">${t.U.htmlEscape(j(e.comment))}</comment>`),Ie())}function ge(e,t){se("<mutation ",""),Object.keys(e).forEach((t=>{void 0!==e[t]&&se(`${t}="${e[t]}" `,"")})),t?(se(">"),t.forEach((e=>{se(`<${e.nodeName} `,""),Object.keys(e.attributes).forEach((t=>{se(`${t}="${e.attributes[t]}" `,"")})),se("/>")})),se("</mutation>")):se("/>")}function be(e){e.mutation&&ge(e.mutation,e.mutationChildren),e.fields&&e.fields.forEach(ye),e.inputs&&e.inputs.forEach(xe)}function xe(e){if(se(`<value name="${e.name}">`),H(e))Se(e.value,!0);else{if(void 0!==e.shadowType)switch(e.shadowType){case l:case u:case p:se(`<shadow type="${e.shadowType}"><field name="NUM">0</field></shadow>`);break;case c:se('<shadow type="math_number_minmax">'),e.shadowMutation&&ge(e.shadowMutation),se('<field name="SLIDER">0</field></shadow>');break;case f:se('<shadow type="logic_boolean"><field name="BOOL">TRUE</field></shadow>');break;case d:se('<shadow type="text"><field name="TEXT"></field></shadow>');break;default:se(`<shadow type="${e.shadowType}"/>`)}Se(e.value)}se("</value>")}function ye(e){se(`<field name="${t.U.htmlEscape(e.name)}">${t.U.htmlEscape(e.value.toString())}</field>`)}function ke(e){se(`<statement name="${t.U.htmlEscape(e.name)}">`),he(e.statement),se("</statement>")}function Se(e,n=!1){if("text"===e.kind){se(e.value)}else{const r=e,s=n||r.isShadow,i=s?"shadow":"block";s||ce(),se(`<${i} ${r.id?`id="${r.id}" `:""}type="${t.U.htmlEscape(r.type)}">`),be(r),se(`</${i}>`)}}function Te(e,n){ce();se(`<block ${n&&n.id?`id="${n.id}" `:""}type="${t.U.htmlEscape(e)}">`)}function Ie(){se("</block>")}function we(e){if(E(e,R))return $e(e);switch(e.kind){case i.ExpressionStatement:case i.ParenthesizedExpression:return we(e.expression);case i.Identifier:return function(e){if(_(e)){const n=t.pxtInfo(e);return Be(a.apis.byQName[n.commentAttrs.blockIdentity],n.commentAttrs.enumIdentity)}const n=et(e),r=e.text;let s=null;return R.localReporters.some((e=>{for(let t=0;t<e.length;++t)if(e[t].name===r)return s=e[t],!0;return!1})),s?Fe(n,s.type,!1):(Ze(n,y.InBlocksOnly),Pe("variables_get","VAR",n))}(e);case i.StringLiteral:case i.FirstTemplateToken:case i.NoSubstitutionTemplateLiteral:return Ce(e.text);case i.NumericLiteral:return Ke(e.text);case i.TrueKeyword:return Ue(!0);case i.FalseKeyword:return Ue(!1);case i.BinaryExpression:return function(e){const t=e.operatorToken.getText(),n=m[t];if(ve(e))return _e(e);const r=n.leftName||"A",s=n.rightName||"B";let i,a;"&&"===t||"||"===t?(i=ze(r,e.left),a=ze(s,e.right)):(i=Ae(r,e.left,l),a=Ae(s,e.right,l));const o=de(n.type);o.fields=[],n.op&&o.fields.push(Me("OP",n.op));return o.inputs=[i,a],o}(e);case i.PrefixUnaryExpression:return function(e){switch(e.operator){case i.ExclamationToken:const t=de("logic_negate");return t.inputs=[ze("BOOL",e.operand)],t;case i.PlusToken:return we(e.operand);case i.MinusToken:return e.operand.kind==i.NumericLiteral?Ke("-"+e.operand.text):Oe(e.operand);default:ie(e)}return}(e);case i.PropertyAccessExpression:return De(e);case i.ArrayLiteralExpression:return function(e){const t=de("lists_create_with");return t.inputs=e.elements.map(((e,t)=>Ae("ADD"+t,e))),t.mutation={items:e.elements.length.toString()},t}(e);case i.ElementAccessExpression:return function(e){const t=de("lists_index_get");return t.inputs=[Ae("LIST",e.expression),Ae("INDEX",e.argumentExpression,l)],t}(e);case i.TaggedTemplateExpression:return function(e){const n=t.pxtInfo(e).callInfo;let s;const o=function(e){if(e.parent&&e.parent.kind===i.CallExpression){const n=e.parent,r=t.pxtInfo(n).callInfo,s=n.arguments.indexOf(e);if(r&&-1!==s){const e=a.apis.byQName[r.qName];if(e){const t=pxt.blocks.compileInfo(e);return t&&t.parameters[s]}}}return}(e);if(o&&o.shadowBlockId){const e=R.blocks.blocksById[o.shadowBlockId];e&&"TD_ID"===e.attributes.shim&&(s=e)}s||(s=R.blocks.apis.byQName[ae(n).blockIdentity]);const l=pxt.blocks.compileInfo(s),c=de(s.attributes.blockId);let u;const p=l.parameters[0];u=p.fieldOptions&&p.fieldOptions[r.DecompileArgumentAsString]?e.getText():e.template.text;return c.fields=[Me(p.actualName,u)],c}(e);case i.CallExpression:return qe(e,void 0,void 0,!0);case i.AsExpression:return we(e.expression);default:ie(e,t.Util.lf("Unsupported syntax kind for output expression block: {0}",i[e.kind]))}}function Ee(e,t,n){if(g){const r=g.getRenamesInSpan(t,n);if(r.length){let n=0;r.forEach((r=>{const s=r.span.start+n-t,i=s+r.span.length;n+=r.diff,e=e.slice(0,s)+r.name+e.slice(i)}))}}return e}function $e(e){const n=Ee(e.getFullText(),e.getFullStart(),e.getEnd()).trim();return Xe(e),G(e,ee),Pe(t.TS_OUTPUT_TYPE,"EXPRESSION",n)}function ve(e){if(e.kind===i.BinaryExpression){const n=e;if("+"===n.operatorToken.getText()||n.operatorToken.kind==i.PlusEqualsToken){return!!t.pxtInfo(e).exprInfo}}return!1}function Ne(e,t){ve(e)?(Ne(e.left,t),Ne(e.right,t)):t.push(e)}function _e(e){const t=[];Ne(e,t);const n=[];for(let e=0;e<t.length;e++)(e>0||!N(t[e].getText()))&&n.push(Ae("ADD"+n.length,t[e],d));const r=de("text_join");return r.inputs=n,r.mutation={items:n.length.toString()},r}function Ae(e,t,n,r){let s;if(s="number"==typeof t?Ke(t.toString()):"boolean"==typeof t?Ue(t):"string"==typeof t?Ce(t):we(t),"expr"==s.kind&&"math_number"==s.type){const e=s.fields[0].value;"math_integer"==n&&e%1==0&&(s.type="math_integer"),"math_whole_number"==n&&e%1==0&&e>0&&(s.type="math_whole_number")}return fe(e,s,n,r)}function Ke(e){return Pe("math_number","NUM",e)}function Ce(e){return Pe("text","TEXT",e)}function Ue(e){return Pe("logic_boolean","BOOL",e?"TRUE":"FALSE")}function Pe(e,t,n,r){const s=de(e);return s.fields=[Me(t,n)],s.isShadow=r,s}function Le(e,t){return fe(e,Pe("variables_get_reporter","VAR",t,!0),"variables_get_reporter")}function Fe(e,t,n){const r=pxt.blocks.reporterTypeForArgType(t),s=Pe(r,"VALUE",e,n);return"argument_reporter_custom"===r&&(s.mutation={typename:t}),s}function Me(e,t){return{kind:"field",name:e,value:t}}function Oe(e){const t=de("math_arithmetic");return t.inputs=[Ae("A",0,l),Ae("B",e,l)],t.fields=[Me("OP","MINUS")],t}function De(e,n=!1,r){let s=t.pxtInfo(e).callInfo;if(!s)return void ie(e);if(e.expression.kind===i.Identifier){const t=e.expression.text;if(R.declaredEnums[t]){const n=a.enumsByName[t];if(n&&n.blockId)return Pe(n.blockId,"MEMBER",e.name.text)}else if(R.declaredKinds[t]){return Pe(R.declaredKinds[t].kindInfo.blockId,"MEMBER",e.name.text)}}const o=ae(s);if(r=o.blockId||r,o.blockCombine)return function(e,t){return He(e,t,null,"@get@")}(e,e);if("lists_length"===o.blockId||"text_length"===o.blockId){const n=de(t.U.htmlEscape(o.blockId));return n.inputs=[Ae("VALUE",e.expression)],n}let l=t.U.htmlEscape(o.blockId||s.qName);const[c]=$(e),u=c&&t.pxtInfo(c).callInfo;if(n||!r&&!o.blockIdentity||u&&u.qName===o.blockIdentity)return{kind:"text",value:l};o.enumval&&u&&o.useEnumVal&&(l=o.enumval);const p=R.compInfo(s);if(r&&p&&p.thisParameter){const n=de(r);return n.inputs=[Ae(t.U.htmlEscape(p.thisParameter.definitionName),e.expression,p.thisParameter.shadowBlockId)],n}return Be(o.blockIdentity?a.apis.byQName[o.blockIdentity]:a.blocksById[r],l)}function Be(e,n){let r=/(?:%|\$)([a-zA-Z0-9_]+)/.exec(e.attributes.block);const s=de(t.U.htmlEscape(e.attributes.blockId));return s.fields=[{kind:"field",name:t.U.htmlEscape(r[1]),value:n}],s}function Re(t,n){let r,i=[];for(let e=0;e<ee.length&&(r=ee[e],!r.owner&&r.start>=t.pos&&r.end<=t.end&&(r.owner=t,r.ownerStatement=n,i.push(r)),!(r.start>t.end));e++);if(r&&r.isTrailingComment){const s=e.getLineAndCharacterOfPosition(o,t.end),a=e.getLineAndCharacterOfPosition(o,r.start);if(s.line===a.line){if(r.ownerStatement){r.ownerStatement.comment.splice(r.ownerStatement.comment.indexOf(r),1);for(const e of W)e.comment.splice(e.comment.indexOf(r),1)}r.owner=t,r.ownerStatement=n,i.push(r)}}if(i.length){const e=[];if(z(t)){let t=[];const n=[];i.forEach(((e,r)=>{let a=e.owner&&e.start<e.owner.getStart();e.kind===s.MultiLine&&a&&(t.length&&(n.push(t),t=[]),r!=i.length-1)?n.push([e]):(t.push(e),e.followedByEmptyLine&&a&&(n.push(t),t=[]))})),i=t,n.forEach((t=>{const n=Z();e.push(n),W.push({comment:t,refId:n})}))}n&&(e.length&&(n.data?n.data+=";"+e.join(";"):n.data=e.join(";")),i&&i.length&&(n.comment?n.comment=n.comment.concat(i):n.comment=i))}}function qe(n,s,o,m=!1,h=!1){const g=n;let b,x=!1;const S=k(g,R,m,h);if(S)b=je(g,void 0,S);else switch(g.kind){case i.Block:return We(g.statements,s,h);case i.ExpressionStatement:return qe(g.expression,s,o||g,m,h);case i.VariableStatement:if(b=We(g.declarationList.declarations,void 0,!1,o||g),!b)return T();x=!0;break;case i.FunctionExpression:case i.ArrowFunction:return function(e,t){return qe(e.body,t)}(g,s);case i.BinaryExpression:b=function(e){e.left.text;switch(e.operatorToken.kind){case i.EqualsToken:return e.left.kind===i.Identifier?Ve(e,e.left,e.right):e.left.kind==i.PropertyAccessExpression?Ge(e,e.left,e.right,"@set@"):function(e,t,n){const r=pe("lists_index_set",e);return r.inputs=[Ae("LIST",t.expression),Ae("INDEX",t.argumentExpression,l),Ae("VALUE",n)],r}(e,e.left,e.right);case i.PlusEqualsToken:if(ve(e)){const t=pe("variables_set",e),n=et(e.left);return Ze(n,y.InBlocksOnly),t.inputs=[fe("VALUE",_e(e),l)],t.fields=[Me("VAR",n)],t}return e.left.kind==i.PropertyAccessExpression?Ge(e,e.left,e.right,"@change@"):Ve(e,e.left,e.right,!0);case i.MinusEqualsToken:const n=pe("variables_change",e);return n.inputs=[fe("VALUE",Oe(e.right),l)],n.fields=[Me("VAR",et(e.left))],n;default:return void ie(e,t.Util.lf("Unsupported operator token in statement {0}",i[e.operatorToken.kind]))}}(g);break;case i.PostfixUnaryExpression:case i.PrefixUnaryExpression:b=function(e){const t=e.operator===i.PlusPlusToken;if(!t&&e.operator!==i.MinusMinusToken)return void ie(e);return Ve(e,e.operand,t?1:-1,!0)}(g);break;case i.VariableDeclaration:const n=g;if(I(n))return function(e){Y.push([et(e.name),e])}(n),T();b=function(e){if(function(e){if(e.name.kind!==i.Identifier)return ie(e,t.Util.lf("Variable declarations may not use binding patterns")),!1;if(!e.initializer)return ie(e,t.Util.lf("Variable declarations must have an initializer")),!1;return!0}(e))return Ve(e,e.name,e.initializer);return}(g);break;case i.WhileStatement:b=function(e){const t=pe("device_while",e);return t.inputs=[ze("COND",e.expression)],t.handlers=[{name:"DO",statement:qe(e.statement)}],t}(g);break;case i.IfStatement:b=function(e){let t=Qe(e);const n=pe("controls_if",e);if(n.mutation={elseif:(t.ifStatements.length-1).toString(),else:t.elseStatement?"1":"0"},n.inputs=[],n.handlers=[],t.ifStatements.forEach(((e,t)=>{let r=qe(e.thenStatement);n.inputs.push(ze("IF"+t,e.expression)),n.handlers.push({name:"DO"+t,statement:r})})),t.elseStatement){let e=qe(t.elseStatement);n.handlers.push({name:"ELSE",statement:e})}return n}(g);break;case i.ForStatement:b=function(t){const n=t.initializer,r=(n.declarations[0].name.text,t.condition),s=et(n.declarations[0].name);let a;if(r.operatorToken.kind!==i.LessThanToken||c(t.statement))if(a=pe("pxt_controls_for",t),a.fields=[],a.inputs=[],a.handlers=[],a.inputs=[Le("VAR",s)],r.operatorToken.kind===i.LessThanToken){const e=v(r.right);if(e.kind===i.NumericLiteral){const t=Ke(parseFloat(e.text)-1+"");a.inputs.push(fe("TO",t,p))}else{const t=de("math_arithmetic");t.fields=[Me("OP","MINUS")],t.inputs=[Ae("A",e,l),Ae("B",1,l)],a.inputs.push(fe("TO",t,p))}}else r.operatorToken.kind===i.LessThanEqualsToken&&a.inputs.push(Ae("TO",r.right,p));else a=pe("controls_repeat_ext",t),a.fields=[],a.inputs=[Ae("TIMES",r.right,p)],a.handlers=[];const o=qe(t.statement);return a.handlers=[{name:"DO",statement:o}],a;function c(t){return t.kind===i.Identifier&&et(t)===s||e.forEachChild(t,c)}}(g);break;case i.ForOfStatement:b=function(e){const t=et(e.initializer.declarations[0].name),n=pe("pxt_controls_for_of",e);n.inputs=[Ae("LIST",e.expression),Le("VAR",t)];const r=qe(e.statement);return n.handlers=[{name:"DO",statement:r}],n}(g);break;case i.FunctionDeclaration:b=function(e){const t=et(e.name);R.localReporters.push(e.parameters.map((e=>({name:e.name.getText(),type:e.type.getText()}))));const n=qe(e.body);let r;R.localReporters.pop(),r=pe("function_definition",e),r.mutation={name:t},e.parameters&&(r.mutationChildren=[],e.parameters.forEach((e=>{const n=e.name.getText();let s=B(e.type.getText());pxt.U.endsWith(s,"[]")&&(s="Array"),r.mutationChildren.push({nodeName:"arg",attributes:{name:n,type:s,id:R.functionParamIds[t][n]}})})));return r.handlers=[{name:"STACK",statement:n}],r}(g);break;case i.CallExpression:b=function(n,s){const o=t.pxtInfo(n).callInfo,m=ae(o);if("Math.pow"==o.qName){const e=de("math_arithmetic");return e.inputs=[fe("A",we(n.arguments[0]),l),fe("B",we(n.arguments[1]),l)],e.fields=[Me("OP","POWER")],e}if(pxt.Util.startsWith(o.qName,"Math.")){const e=o.qName.substring(5);if(F(e)){let t;if(D(e))t=de("math_js_round");else{let n;t=de("math_js_op"),n=M(e)?"unary":O(e)?"infix":"binary",t.mutation={"op-type":n}}return t.inputs=o.args.map(((e,t)=>fe("ARG"+t,we(e),"math_number"))),t.fields=[Me("OP",e)],t}}if(m.blockId===t.PAUSE_UNTIL_TYPE){const e=pe(t.PAUSE_UNTIL_TYPE,n),r=n.arguments[0];let s;return s=r.body.kind===i.Block?r.body.statements[0].expression:r.body,e.inputs=[fe("PREDICATE",we(s),"logic_boolean")],e}if(!m.blockId||!m.block){const e=pxt.blocks.builtinFunctionInfo[o.qName];if(!e){const e=et(n.expression);if(R.declaredFunctions[e]){let t,r=!0;if(o.isExpression){const[e]=$(n);r=e&&e.kind===i.ExpressionStatement}return t=pe(r?"function_call":"function_call_output",n),o.args.length&&(t.mutationChildren=[],t.inputs=[],R.declaredFunctions[e].parameters.forEach(((n,r)=>{const s=n.name.getText(),i=R.functionParamIds[e][s];let a=B(n.type.getText());pxt.U.endsWith(a,"[]")&&(a="Array"),t.mutationChildren.push({nodeName:"arg",attributes:{name:s,type:a,id:i}});const l=fe(i,we(o.args[r]));t.inputs.push(l)}))),t.mutation={name:e},t}return je(n)}m.blockId=e.blockId}if(m.imageLiteral||m.gridLiteral)return function(e,n){let r=e.arguments[0];if(r.kind!=i.StringLiteral&&r.kind!=i.NoSubstitutionTemplateLiteral)return void ie(e);const s=ae(n),a=pe(s.blockId,e);a.fields=[];const o=(r.text||"").replace(/\s+/g,""),l=(s.imageLiteralColumns||5)*(s.imageLiteral||s.gridLiteral),c=s.imageLiteralRows||5,u=l*c;if(u!=o.length)return void ie(e,t.Util.lf("Invalid image pattern ({0} expected vs {1} actual)",u,o.length));let p="";for(let e=0;e<c;++e){for(let t=0;t<l;++t)p+=/[#*1]/.test(o[e*l+t])?"#":".";p+="\n"}return a.fields.push(Me("LEDS",`\`${p}\``)),a}(n,o);e.isFunctionLike(o.decl);const h=U(o,R.blocks),g=R.blocks.apis.byQName[o.decompilerBlockAlias||o.qName],b=pxt.blocks.compileInfo(g),x=s?de(m.blockId):pe(m.blockId,n),y=e=>(x.inputs||(x.inputs=[])).push(e),k=e=>(x.fields||(x.fields=[])).push(e);"Math.max"==o.qName&&k({kind:"field",name:"op",value:"max"});let S=0;if(h.forEach(((e,n)=>{let s,h=e.value;const g=e.param,T=e.info,I=b.parameters[b.thisParameter?n-1:n],E=I&&I.range;if(E){const e=E.min,t=E.max;s={min:e.toString(),max:t.toString()}}if(0===n&&m.defaultInstance){if(h.getText()===m.defaultInstance)return;x.mutation={showing:"true"}}if(m.mutatePropertyEnum&&n===o.args.length-2)return;let $;if(g&&g.isOptional&&++S,g&&g.shadowBlockId&&($=a.blocksById[g.shadowBlockId]),h.kind===i.CallExpression){const e=t.pxtInfo(h).callInfo,n=e&&ae(e);n&&"TD_ID"===n.shim&&T.isEnum&&(h=v(e.args[0]))}if(g&&T&&T.isEnum&&h.kind===i.Identifier)k(Me(t.U.htmlEscape(g.definitionName),t.pxtInfo(h).commentAttrs.enumIdentity));else if(g&&g.fieldOptions&&g.fieldOptions[r.DecompileArgumentAsString])k(Me(t.U.htmlEscape(g.definitionName),t.Util.htmlEscape(h.getText())));else switch(h.kind){case i.FunctionExpression:case i.ArrowFunction:const e=function(e){const n=w(e);if(n)return{callbackproperties:n[0].join(","),renamemap:t.Util.htmlEscape(JSON.stringify(n[1]))};return}(h);let S=!1;if(e)x.mutation=e;else{let e=h;const t=a.blocksById[m.blockId].parameters[b.thisParameter?n-1:n],r=(e,t)=>{"reporter"===m.draggableParameters?y(function(e,t,n){const r=pxt.blocks.reporterTypeForArgType(n);return fe(e,Fe(t,n,!0),r)}("HANDLER_DRAG_PARAM_"+e.name,t,e.type)):y(Le("HANDLER_DRAG_PARAM_"+e.name,t))};if(e.parameters.length&&(m.optionalVariableArgs?(x.mutation={numargs:e.parameters.length.toString()},e.parameters.forEach(((e,t)=>{x.mutation["arg"+t]=e.name.text}))):e.parameters.forEach(((e,n)=>{const s=t.handlerParameters[n];m.draggableParameters?r(s,e.name.text):k(Me("HANDLER_"+s.name,e.name.text))}))),m.draggableParameters){if(e.parameters.length<t.handlerParameters.length)for(let n=e.parameters.length;n<t.handlerParameters.length;n++){const e=t.handlerParameters[n];r(e,e.name)}"reporter"===m.draggableParameters&&(R.localReporters.push(t.handlerParameters),S=!0)}}const I=qe(h);(x.handlers||(x.handlers=[])).push({name:"HANDLER",statement:I}),S&&R.localReporters.pop();break;case i.PropertyAccessExpression:const E=t.pxtInfo(h).callInfo,v=t.U.htmlEscape(g.definitionName),N=ae(E);$&&"TD_ID"===$.attributes.shim?y(fe(v,De(h,!1,g.shadowBlockId),g.shadowBlockId,s)):T&&T.isEnum||E&&(N.fixedInstance||N.blockIdentity===o.qName)?k(Me(v,De(h,!0).value)):y(Ae(v,h,g.shadowBlockId,s));break;case i.BinaryExpression:if(g&&g.shadowOptions&&g.shadowOptions.toString){const e=h;if(e.operatorToken.kind===i.PlusToken&&function(e){if(e.kind===i.StringLiteral||e.kind===i.NoSubstitutionTemplateLiteral)return""===e.text;return!1}(e.left)){y(Ae(t.U.htmlEscape(g.definitionName),e.right,g.shadowBlockId||"text"));break}}y(Ae(t.U.htmlEscape(g.definitionName),h,g.shadowBlockId,s));break;default:let _;const A=t.U.htmlEscape(g.definitionName);let C=!0;if("Math.random"==o.qName)_=fe(A,function(e){switch(e.kind){case i.NumericLiteral:return Ke((parseInt(e.text)-1).toString());case i.BinaryExpression:const t=e;if(t.operatorToken.kind==i.PlusToken&&"1"==t.right.text)return we(t.left);default:return we(e)}}(h),l,s),C=!1;else if(K(h)){const e="text"==g.fieldEditor?h.text:h.getText(),n=g.shadowBlockId&&!function(e){switch(e){case l:case c:case u:case p:case d:case f:return!0;default:return!1}}(g.shadowBlockId);if(Je(g)&&g.fieldOptions.onParentBlock)return void k(Me(A,e));if(n){const n=function(e){if(a.blocksById[e]){const t=pxt.blocks.compileInfo(a.blocksById[e]);if(!t.thisParameter&&1===t.parameters.length)return t.parameters[0]}return}(g.shadowBlockId);if(n&&Je(n)){const r=Pe(g.shadowBlockId,n.definitionName,e,!0);g.shadowOptions&&(r.mutation={customfield:t.Util.htmlEscape(JSON.stringify(g.shadowOptions))}),_=fe(A,r,g.shadowBlockId,s),C=!1}}}else if(h.kind===i.TaggedTemplateExpression&&g.fieldOptions&&g.fieldOptions[r.TaggedTemplate])return void k(Me(A,t.Util.htmlEscape(h.getText())));C&&(_=Ae(A,h,g.shadowBlockId,s)),y(_)}})),S)if(x.mutation||(x.mutation={}),m.compileHiddenArguments){let e=0,n=0;for(const r of h){const s=t.U.htmlEscape(r.param.definitionName),i=x.inputs.find((e=>e.name===s));r.param.isOptional?i&&!H(i)&&(n=Math.max(r.param.definitionIndex-e+1,n)):e++}x.mutation._expanded=n.toString()}else x.mutation._expanded=S.toString();return x}(g,m);break;case i.DebuggerStatement:b=function(e){return pe(t.TS_DEBUGGER_TYPE,e)}(g);break;case i.BreakStatement:b=function(e){return pe(t.TS_BREAK_TYPE,e)}(g);break;case i.ContinueStatement:b=function(e){return pe(t.TS_CONTINUE_TYPE,e)}(g);break;case i.EmptyStatement:b=void 0;break;case i.EnumDeclaration:case i.ModuleDeclaration:return G(g,ee),T();case i.ReturnStatement:b=function(e){const n=pe(t.TS_RETURN_STATEMENT_TYPE,e);e.expression?n.inputs=[fe("RETURN_VALUE",we(e.expression),l)]:n.mutation={no_return_value:"true"};return n}(g);break;default:return void ie(g,s?t.Util.lf("Unsupported statement in block: {0}",i[g.kind]):t.Util.lf("Statement kind unsupported in blocks: {0}",i[g.kind]))}if(b){let e=b;for(;e.next;)e=e.next;e.next=T(),e.next&&(e.next.prev=e)}return x||Re(o||g,b),b;function T(){if(s&&s.length)return qe(s.shift(),s,void 0,!1,h)}}function je(e,n,r){h.errorOnGreyBlocks&&ie(e);const s=pe(t.TS_STATEMENT_TYPE,e);s.mutation={},Xe(e);let a=e.getText();a=Ee(a,e.getStart(),e.getEnd()),G(e,ee),n&&(a=n+a);const o=[];if(e.kind===i.VariableStatement)for(const t of e.declarationList.declarations)o.push(et(t.name));else e.kind===i.VariableDeclaration&&o.push(et(e.name));o.length&&(s.mutation.declaredvars=o.join(","));const l=a.split("\n");return s.mutation.numlines=l.length.toString(),r&&h.includeGreyBlockMessages&&(s.mutation.error=t.U.htmlEscape(r)),l.forEach(((e,n)=>{s.mutation[`line${n}`]=t.U.htmlEscape(e)})),s}function ze(n,r){if(function(n){const r=v(n);switch(r.kind){case i.TrueKeyword:case i.FalseKeyword:case i.Identifier:case i.ElementAccessExpression:return;case i.BinaryExpression:return s(r);case i.CallExpression:return a(r);case i.PrefixUnaryExpression:if(r.operator===i.ExclamationToken)return;default:return t.Util.lf("Conditions must evaluate to booleans or identifiers")}function s(e){switch(e.operatorToken.kind){case i.EqualsEqualsToken:case i.EqualsEqualsEqualsToken:case i.ExclamationEqualsToken:case i.ExclamationEqualsEqualsToken:case i.LessThanToken:case i.LessThanEqualsToken:case i.GreaterThanToken:case i.GreaterThanEqualsToken:case i.AmpersandAmpersandToken:case i.BarBarToken:return;default:return t.Util.lf("Binary expressions in conditionals must evaluate to booleans")}}function a(n){const r=t.pxtInfo(n).callInfo;if(r){const t=R.blocks.apis.byQName[r.qName];if(t&&"boolean"==t.retType)return;if(e.isIdentifier(n.expression)&&R.declaredFunctions[n.expression.text])return}return t.Util.lf("Only functions that return booleans are allowed as conditions")}}(r)){return fe(n,$e(r),f)}return Ae(n,r,f)}function Ve(e,t,n,r=!1,s=!1){const i=et(t);Ze(i,y.InBlocksOnly);const a=pe(r?"variables_change":"variables_set",e.parent||e);return a.inputs=[Ae("VALUE",n,l)],a.fields=[Me("VAR",i)],a}function Ge(e,t,n,r){return He(e,t,n,r)}function He(e,n,r,s){const i=t.pxtInfo(n).callInfo,a=R.blocks.apis.byQName[i?i.qName:""];if(!a||!a.attributes.blockCombine)return void ie(n);const o=`${a.namespace}.${a.retType}.${s}`,l=R.blocks.blocks.find((e=>e.qName==o)),c=r?pe(l.attributes.blockId,e):de(l.attributes.blockId),u=l.attributes._def.parameters;let p=i.qName;return l.combinedProperties&&l.combinedProperties.forEach((e=>{0===e.indexOf(i.qName)&&"@"===e.charAt(i.qName.length)&&(p=e)})),c.inputs=[Ae(u[0].name,n.expression)],c.fields=[Me(u[1].name,p)],r&&c.inputs.push(Ae(u[2].name,r)),c}function Je(e){return e&&e.fieldOptions&&e.fieldOptions[r.DecompileLiterals]}function Qe(e){let t={ifStatements:[{expression:e.expression,thenStatement:e.thenStatement}],elseStatement:e.elseStatement};if(e.elseStatement&&e.elseStatement.kind==i.IfStatement){let n=Qe(e.elseStatement);t.ifStatements=t.ifStatements.concat(n.ifStatements),t.elseStatement=n.elseStatement}return t}function We(t,n,r=!1,s,a=!1){const o=[],l=n||[];for(let e=t.length-1;e>=0;e--){const n=t[e];(n.kind===i.FunctionDeclaration||n.kind==i.ExpressionStatement&&me(n))&&!k(n,R,!1,r)?o.unshift(n):l.unshift(n)}const c=[],u={};for(const e of o){const t=e.kind===i.FunctionDeclaration?void 0:oe(e);t&&u[t]?c.push(qe(e,void 0,void 0,!1,!1)):(u[t]=!0,c.push(qe(e,void 0,void 0,!1,r)))}if(c.forEach(he),l.length){const t=l.shift(),n=qe(t,l,s,!1,r);if(a){let r=n,s=t;if(Y.forEach((([e,n])=>{if(Q[e]===y.InBlocksOnly)return;let i;n.initializer;i=Q[e]===y.InTextBlocks?je(n,"let "):Ve(t,n.name,n.initializer,!1,!0),i.next=r,r=i,s=n,Re(s.parent,r)})),r){const t=pe(e.pxtc.ON_START_TYPE,s);return t.handlers=[{name:"HANDLER",statement:r}],t}Ye(n)}return n}a&&Ye(void 0)}function Ye(t){h.alwaysEmitOnStart&&(Te(e.pxtc.ON_START_TYPE,t),Ie())}function Ze(e,t){Q[e]!==y.InTextBlocks&&(Q[e]=t)}function Xe(t){e.forEachChild(t,(e=>{e.kind===i.Identifier&&Ze(et(e),y.InTextBlocks),Xe(e)}))}function et(e){if(g){const t=g.getRenameForPosition(e.getStart());if(t)return t.name}return e.text}},n.getLeadingComments=function(t,n,r){return q(n,r||e.getLeadingCommentRangesOfNode(t,n))},n.getTrailingComments=function(t,n){return q(n,e.getTrailingCommentRanges(n.getFullText(),t.end))},n.getCommentsForStatement=function(e,t){let n,r=[];for(let s=0;s<t.length&&(n=t[s],!n.owner&&n.start>=e.pos&&n.end<=e.end&&(n.owner=e,r.push(n)),!(n.start>e.end));s++);return r},n.buildCommentMap=V}(t.decompiler||(t.decompiler={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){function t(e,n){var r;switch(e){case"void":return"None";case"boolean":return"bool";case"string":return"str"}if(null===(r=n.byQName[e])||void 0===r?void 0:r.pyQName)return n.byQName[e].pyQName;const s=/^(?:Array<(.+)>)|(?:(.+)\[\])|(?:\[.+\])$/.exec(e);return s?`List[${t(s[1]||s[2],n)}]`:e}function n(e,t){return`\`\`\`${t?"python":"ts"}\n${e}\n\`\`\``}e.displayStringForSymbol=function(e,r,s){if(e){switch(e.kind){case 3:case 1:return function(e,r,s){let i="";3===e.kind?i+=r?"def ":"function ":i+="(method) ";i+=r?e.pyQName:e.qName;let a="";e.parameters&&e.parameters.length&&(a=e.parameters.map((e=>`${e.name}: ${r?e.pyTypeString:e.type}`)).join(", "));let o=e.retType||"void";r&&(o=t(o,s));return n(`${i}(${a}): ${o}`,r)}(e,r,s);case 6:case 7:return function(e,t){const r=t?e.pyQName:e.qName;if(6===e.kind)return n(`enum ${r}`,t);let s=`(enum member) ${r}`;e.attributes.enumval&&(s+=` = ${e.attributes.enumval}`);return n(s,!1)}(e,r);case 5:return function(e,t){return n(`namespace ${t?e.pyQName:e.qName}`,!1)}(e,r);case 9:return function(e,t){return n(`interface ${t?e.pyQName:e.qName}`,!1)}(e,r);case 8:return function(e,t){return n(`class ${t?e.pyQName:e.qName}`,t)}(e,r);case 4:return function(e,r,s){let i=r?e.pyQName:`let ${e.qName}`;if(e.retType){let a=e.retType;return r&&(a=t(a,s)),n(`${i}: ${a}`,r)}return n(i,r)}(e,r,s);case 2:return function(e,r,s){const i=`(property) ${r?e.pyQName:e.qName}`;if(e.retType){let a=e.retType;return r&&(a=t(a,s)),n(`${i}: ${a}`,!1)}return n(i,!1)}(e,r,s)}return`**${e.qName}**`}},e.displayStringForKeyword=function(e,t){return`\`\`\`${t?"py":"ts"}\n(keyword) ${e}\n\`\`\``}}(e.service||(e.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n={r0:0,r1:1,r2:2,r3:3,r4:4,r5:5,r6:6,r7:7,r8:8,r9:9,r10:10,r11:10,r12:12,sp:13,r13:13,lr:14,r14:14,pc:15,r15:15};class r extends e.assembler.AbstractProcessor{constructor(){super(),this.addEnc("$r0","R0-7",(e=>this.inrange(7,e,e))),this.addEnc("$r1","R0-7",(e=>this.inrange(7,e,e<<3))),this.addEnc("$r2","R0-15",(e=>this.inrange(15,e,7&e|(8&e)<<4))),this.addEnc("$r3","R0-15",(e=>this.inrange(15,e,e<<3))),this.addEnc("$r4","R0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$r5","R0-7",(e=>this.inrange(7,e,e<<8))),this.addEnc("$r01","R0-7",(e=>this.inrange(7,e,e|e<<3))),this.addEnc("$i0","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i1","#0-1020",(e=>this.inrange(255,e/4,e>>2))),this.addEnc("$i2","#0-510",(e=>this.inrange(127,e/4,e>>2))),this.addEnc("$i3","#0-7",(e=>this.inrange(7,e,e<<6))),this.addEnc("$i4","#0-31",(e=>this.inrange(31,e,e<<6))),this.addEnc("$i5","#0-124",(e=>this.inrange(31,e/4,e>>2<<6))),this.addEnc("$i6","#1-32",(e=>0==e?null:32==e?0:this.inrange(31,e,e<<6))),this.addEnc("$i7","#0-62",(e=>this.inrange(31,e/2,e>>1<<6))),this.addEnc("$i32","#0-2^32",(e=>1)),this.addEnc("$rl0","{R0-7,...}",(e=>this.inrange(255,e,e))),this.addEnc("$rl1","{LR,R0-7,...}",(e=>16384&e?this.inrange(255,-16385&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$rl2","{PC,R0-7,...}",(e=>32768&e?this.inrange(255,-32769&e,256|255&e):this.inrange(255,e,e))),this.addEnc("$la","LABEL",(e=>this.inrange(255,e/4,e>>2))).isWordAligned=!0,this.addEnc("$lb","LABEL",(e=>this.inrangeSigned(127,e/2,e>>1))),this.addEnc("$lb11","LABEL",(e=>this.inrangeSigned(1023,e/2,e>>1))),this.addInst("adcs $r0, $r1",16704,65472),this.addInst("add $r2, $r3",17408,65280),this.addInst("add $r5, pc, $i1",40960,63488),this.addInst("add $r5, sp, $i1",43008,63488),this.addInst("add sp, $i2",45056,65408).canBeShared=!0,this.addInst("adds $r0, $r1, $i3",7168,65024),this.addInst("adds $r0, $r1, $r4",6144,65024),this.addInst("adds $r01, $r4",6144,65024),this.addInst("adds $r5, $i0",12288,63488),this.addInst("adr $r5, $la",40960,63488),this.addInst("ands $r0, $r1",16384,65472),this.addInst("asrs $r0, $r1",16640,65472),this.addInst("asrs $r0, $r1, $i6",4096,63488),this.addInst("bics $r0, $r1",17280,65472),this.addInst("bkpt $i0",48640,65280),this.addInst("blx $r3",18304,65415),this.addInst("bx $r3",18176,65408),this.addInst("cmn $r0, $r1",17088,65472),this.addInst("cmp $r0, $r1",17024,65472),this.addInst("cmp $r2, $r3",17664,65280),this.addInst("cmp $r5, $i0",10240,63488),this.addInst("eors $r0, $r1",16448,65472),this.addInst("ldmia $r5!, $rl0",51200,63488),this.addInst("ldmia $r5, $rl0",51200,63488),this.addInst("ldr $r0, [$r1, $i5]",26624,63488),this.addInst("ldr $r0, [$r1, $r4]",22528,65024),this.addInst("ldr $r5, [pc, $i1]",18432,63488),this.addInst("ldr $r5, $la",18432,63488),this.addInst("ldr $r5, [sp, $i1]",38912,63488).canBeShared=!0,this.addInst("ldr $r5, [sp]",38912,63488).canBeShared=!0,this.addInst("ldrb $r0, [$r1, $i4]",30720,63488),this.addInst("ldrb $r0, [$r1, $r4]",23552,65024),this.addInst("ldrh $r0, [$r1, $i7]",34816,63488),this.addInst("ldrh $r0, [$r1, $r4]",23040,65024),this.addInst("ldrsb $r0, [$r1, $r4]",22016,65024),this.addInst("ldrsh $r0, [$r1, $r4]",24064,65024),this.addInst("lsls $r0, $r1",16512,65472),this.addInst("lsls $r0, $r1, $i4",0,63488),this.addInst("lsrs $r0, $r1",16576,65472),this.addInst("lsrs $r0, $r1, $i6",2048,63488),this.addInst("mov $r2, $r3",17920,65280),this.addInst("movs $r0, $r1",0,65472),this.addInst("movs $r5, $i0",8192,63488),this.addInst("muls $r0, $r1",17216,65472),this.addInst("mvns $r0, $r1",17344,65472),this.addInst("negs $r0, $r1",16960,65472),this.addInst("nop",18112,65535),this.addInst("orrs $r0, $r1",17152,65472),this.addInst("pop $rl2",48128,65024),this.addInst("push $rl1",46080,65024),this.addInst("rev $r0, $r1",47616,65472),this.addInst("rev16 $r0, $r1",47680,65472),this.addInst("revsh $r0, $r1",47808,65472),this.addInst("rors $r0, $r1",16832,65472),this.addInst("sbcs $r0, $r1",16768,65472),this.addInst("sev",48960,65535),this.addInst("stm $r5!, $rl0",49152,63488),this.addInst("stmia $r5!, $rl0",49152,63488),this.addInst("stmea $r5!, $rl0",49152,63488),this.addInst("str $r0, [$r1, $i5]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1]",24576,63488).canBeShared=!0,this.addInst("str $r0, [$r1, $r4]",20480,65024),this.addInst("str $r5, [sp, $i1]",36864,63488).canBeShared=!0,this.addInst("str $r5, [sp]",36864,63488).canBeShared=!0,this.addInst("strb $r0, [$r1, $i4]",28672,63488),this.addInst("strb $r0, [$r1, $r4]",21504,65024),this.addInst("strh $r0, [$r1, $i7]",32768,63488),this.addInst("strh $r0, [$r1, $r4]",20992,65024),this.addInst("sub sp, $i2",45184,65408),this.addInst("subs $r0, $r1, $i3",7680,65024),this.addInst("subs $r0, $r1, $r4",6656,65024),this.addInst("subs $r01, $r4",6656,65024),this.addInst("subs $r5, $i0",14336,63488),this.addInst("svc $i0",57088,65280),this.addInst("sxtb $r0, $r1",45632,65472),this.addInst("sxth $r0, $r1",45568,65472),this.addInst("tst $r0, $r1",16896,65472),this.addInst("udf $i0",56832,65280),this.addInst("uxtb $r0, $r1",45760,65472),this.addInst("uxth $r0, $r1",45696,65472),this.addInst("wfe",48928,65535),this.addInst("wfi",48944,65535),this.addInst("yield",48912,65535),this.addInst("cpsid i",46706,65535),this.addInst("cpsie i",46690,65535),this.addInst("beq $lb",53248,65280),this.addInst("bne $lb",53504,65280),this.addInst("bcs $lb",53760,65280),this.addInst("bcc $lb",54016,65280),this.addInst("bmi $lb",54272,65280),this.addInst("bpl $lb",54528,65280),this.addInst("bvs $lb",54784,65280),this.addInst("bvc $lb",55040,65280),this.addInst("bhi $lb",55296,65280),this.addInst("bls $lb",55552,65280),this.addInst("bge $lb",55808,65280),this.addInst("blt $lb",56064,65280),this.addInst("bgt $lb",56320,65280),this.addInst("ble $lb",56576,65280),this.addInst("bhs $lb",53760,65280),this.addInst("blo $lb",54016,65280),this.addInst("b $lb11",57344,63488),this.addInst("bal $lb11",57344,63488),this.addInst("bl $lb",61440,63488,!0),this.addInst("bb $lb",57344,63488,!0),this.addInst("ldlit $r5, $i32",18432,63488)}toFnPtr(t,n,r){return e.target.runtimeIsARM&&/::/.test(r)?t+n&-2:t+n|1}wordSize(){return 4}is32bit(e){return"bl"==e.name||"bb"==e.name}postProcessAbsAddress(e,t){return t^=1,t-=e.baseOffset}emit32(t,n,r){let s=!!(n%2);s&&(n=n+1&-4);let i=n>>1;if(e.assert(null!=i),(0|i)!=i||!(-2097152<i&&i<2097152))return e.assembler.emitErr("jump out of range",r);let a=2047&i,o=i>>11&1023;return{opcode:4026531840&i?62464|o:61440|o,opcode2:s?59392|a:63488|a,stack:0,numArgs:[n],labelName:r}}expandLdlit(t){let n,r=!1,s=[],i={},a=1;for(let o=0;o<t.lines.length;++o){let l=t.lines[o];if(s.push(l),"instruction"==l.type&&l.instruction&&"ldlit"==l.instruction.name){if(!n){let e=l.location+900,s=o+1;for(;s<t.lines.length&&!(t.lines[s].location>e);++s){let e=t.lines[s].getOp();("b"==e||"bb"==e||"pop"==e&&"pc"==t.lines[s].words[2])&&(n=t.lines[s])}if(n)r=!1;else for(r=!0;--s>o;)if("instruction"==t.lines[s].type){n=t.lines[s];break}}let s=l.words[1],c="#"+l.words[3],u=e.U.lookup(i,c);u||(u="_ldlit_"+ ++a,i[c]=u),l.ldlitLabel=l.words[3],l.update(`ldr ${s}, ${u} ; ${l.ldlitLabel}`)}if(l===n){n=null;let e=[],o="_jmpwords_"+ ++a;r&&e.push("bb "+o),e.push(".object PUSH"),e.push(".balign 4");for(let t of Object.keys(i)){let n=i[t];e.push(n+": .word "+t.slice(1))}r&&e.push(o+":"),e.push(".object POP");for(let n of e){t.buildLine(n,s);let e=s[s.length-1];e.scope=l.scope,e.lineNo=l.lineNo}i={}}}t.lines=s}getAddressFromLabel(e,t,n,r=!1){let s=e.lookupLabel(n);if(null==s)return null;let i=e.location()+4;return r&&(i&=4294967292),s-i}isPop(e){return 48128==e}isPush(e){return 46080==e}isAddSP(e){return 45056==e}isSubSP(e){return 45184==e}peephole(t,n,r){let i=this.encoders.$lb11,a=this.encoders.$lb;function o(e,t){return null!=e.encode(t.numArgs[0]+8)&&null!=e.encode(t.numArgs[0]-8)&&null!=e.encode(t.numArgs[0])}let l=t.getOp(),c=!1;"bne"!=l&&"beq"!=l||("b"==n.getOp()&&0==t.numArgs[0]&&(c=!0),"bb"==n.getOp()&&2==t.numArgs[0]&&(c=!0)),"bb"==l&&o(i,t)?t.update("b "+t.words[1]):"b"==l&&-2==t.numArgs[0]?t.update(""):"bne"==l&&c&&o(a,n)?(t.update("beq "+n.words[1]),n.update("")):"beq"==l&&c&&o(a,n)?(t.update("bne "+n.words[1]),n.update("")):"push"!=l||16384!=t.numArgs[0]||"push"!=n.getOp()||16384&n.numArgs[0]?"pop"==l&&"pop"==n.getOp()&&32768==n.numArgs[0]?(t.update(t.text.replace("}",", pc}")),n.update("")):"push"==l&&"pop"==n.getOp()&&t.numArgs[0]==n.numArgs[0]?(e.assert(t.numArgs[0]>0),t.update(""),n.update("")):"push"==l&&"pop"==n.getOp()&&4==t.words.length&&4==n.words.length?(e.assert("{"==t.words[1]),t.update("mov "+n.words[2]+", "+t.words[2]),n.update("")):r&&"movs $r5, $i0"==t.getOpExt()&&"mov $r0, $r1"==n.getOpExt()&&t.numArgs[0]==n.numArgs[1]&&function(e,t){return!!("pop"==e.getOp()&&e.numArgs[0]&1<<t)}(r,t.numArgs[0])?(t.update("movs r"+n.numArgs[0]+", #"+t.numArgs[1]),n.update("")):"pop"==l&&s(t)>=0&&"push"==n.getOp()&&s(t)==s(n)?(t.update("ldr r"+s(t)+", [sp, #0]"),n.update("")):"push"==l&&"ldr $r5, [sp, $i1]"==n.getOpExt()&&s(t)==n.numArgs[0]&&0==n.numArgs[1]?n.update(""):r&&"push"==l&&s(t)>=0&&function(e,t){return"movs $r5, $i0"==e.getOpExt()&&e.numArgs[0]!=t}(n,s(t))&&"pop"==r.getOp()&&s(t)==s(r)&&(t.update(""),r.update("")):(t.update(n.text.replace("{","{lr, ")),n.update(""))}registerNo(e){if(!e)return null;e=e.toLowerCase();const t=n[e];return void 0===t?null:t}testAssembler(){e.assembler.expectError(this,"lsl r0, r0, #8"),e.assembler.expectError(this,"push {pc,lr}"),e.assembler.expectError(this,"push {r17}"),e.assembler.expectError(this,"mov r0, r1 foo"),e.assembler.expectError(this,"movs r14, #100"),e.assembler.expectError(this,"push {r0"),e.assembler.expectError(this,"push lr,r0}"),e.assembler.expectError(this,"pop {lr,r0}"),e.assembler.expectError(this,"b #+11"),e.assembler.expectError(this,"b #+102400"),e.assembler.expectError(this,"bne undefined_label"),e.assembler.expectError(this,".foobar"),e.assembler.expect(this,"0200 lsls r0, r0, #8\nb500 push {lr}\n2064 movs r0, #100 ; 0x64\nb401 push {r0}\nbc08 pop {r3}\nb501 push {r0, lr}\nbd20 pop {r5, pc}\nbc01 pop {r0}\n4770 bx lr\n0000 .balign 4\ne6c0 .word -72000\nfffe\n"),e.assembler.expect(this,"4291 cmp r1, r2\nd100 bne l6\ne000 b l8\n1840 l6: adds r0, r0, r1\n4718 l8: bx r3\n"),e.assembler.expect(this," @stackmark base\nb403 push {r0, r1}\n @stackmark locals\n9801 ldr r0, [sp, locals@1]\nb401 push {r0}\n9802 ldr r0, [sp, locals@1]\nbc01 pop {r0}\n @stackempty locals\n9901 ldr r1, [sp, locals@1]\n9102 str r1, [sp, base@0]\n @stackempty locals\nb002 add sp, #8\n @stackempty base\n"),e.assembler.expect(this,"b090 sub sp, #4*16\nb010 add sp, #4*16\n"),e.assembler.expect(this,'6261 .string "abc"\n0063 \n'),e.assembler.expect(this,'6261 .string "abcde"\n6463 \n0065 \n'),e.assembler.expect(this,"3042 adds r0, 0x42\n1c0d adds r5, r1, #0\nd100 bne #0\n2800 cmp r0, #0\n6b28 ldr r0, [r5, #48]\n0200 lsls r0, r0, #8\n2063 movs r0, 0x63\n4240 negs r0, r0\n46c0 nop\nb500 push {lr}\nb401 push {r0}\nb402 push {r1}\nb404 push {r2}\nb408 push {r3}\nb520 push {r5, lr}\nbd00 pop {pc}\nbc01 pop {r0}\nbc02 pop {r1}\nbc04 pop {r2}\nbc08 pop {r3}\nbd20 pop {r5, pc}\n9003 str r0, [sp, #4*3]\n")}}function s(t){e.assert("push"==t.getOp()||"pop"==t.getOp());let n=0,r=-1,s=t.numArgs[0];for(;s>0;)1&s&&(r=-1==r?n:-2),s>>=1,n++;return r>=0?r:-1}t.ThumbProcessor=r}(e.thumb||(e.thumb={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,s=t.Util;s.assert;!function(e){e[e.None=0]="None",e[e.NumberLiteral=1]="NumberLiteral",e[e.PointerLiteral=2]="PointerLiteral",e[e.RuntimeCall=3]="RuntimeCall",e[e.ProcCall=4]="ProcCall",e[e.SharedRef=5]="SharedRef",e[e.SharedDef=6]="SharedDef",e[e.FieldAccess=7]="FieldAccess",e[e.Store=8]="Store",e[e.CellRef=9]="CellRef",e[e.Sequence=10]="Sequence",e[e.JmpValue=11]="JmpValue",e[e.Nop=12]="Nop",e[e.InstanceOf=13]="InstanceOf"}(r=n.EK||(n.EK={}));let i,a,o=0;class l{isExpr(){return!1}isStmt(){return!1}getId(){return this._id||(this._id=++o),this._id}}n.Node=l;class c extends l{constructor(e,t,n){super(),this.exprKind=e,this.args=t,this.data=n,this.callingConvention=0}static clone(e){let t=new c(e.exprKind,e.args?e.args.slice(0):null,e.data);return e.jsInfo&&(t.jsInfo=e.jsInfo),e.totalUses&&(t.totalUses=e.totalUses,t.currUses=e.currUses),t.callingConvention=e.callingConvention,t.mask=e.mask,t.isStringLiteral=e.isStringLiteral,t}reset(){this.currUses=0,this.prevTotalUses&&(this.totalUses=this.prevTotalUses)}ptrlabel(){return this.jsInfo instanceof u?this.jsInfo:null}hexlit(){const e=this.jsInfo;return null!=e.hexlit?e.hexlit:null}isExpr(){return!0}isPure(){return this.isStateless()||this.exprKind==r.CellRef}isLiteral(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:return!0;default:return!1}}isStateless(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.SharedRef:return!0;default:return!1}}sharingInfo(){let e=this,t=this.getId();return this.exprKind!=r.SharedRef&&this.exprKind!=r.SharedDef||(e=this.args[0],e?t=e.getId():e={currUses:"",totalUses:""}),`${e.currUses}/${e.totalUses} #${t}`}toString(){return p(this)}canUpdateCells(){switch(this.exprKind){case r.NumberLiteral:case r.PointerLiteral:case r.CellRef:case r.JmpValue:case r.SharedRef:case r.Nop:return!1;case r.SharedDef:case r.FieldAccess:case r.InstanceOf:return this.args[0].canUpdateCells();case r.RuntimeCall:case r.ProcCall:case r.Sequence:case r.Store:return!0;default:throw t.oops()}}}n.Expr=c,function(e){e[e.None=0]="None",e[e.Expr=1]="Expr",e[e.Label=2]="Label",e[e.Jmp=3]="Jmp",e[e.StackEmpty=4]="StackEmpty",e[e.Breakpoint=5]="Breakpoint",e[e.Comment=6]="Comment"}(i=n.SK||(n.SK={})),function(e){e[e.Always=1]="Always",e[e.IfZero=2]="IfZero",e[e.IfNotZero=3]="IfNotZero"}(a=n.JmpMode||(n.JmpMode={})),n.lblNumUsesJmpNext=-101;class u extends l{constructor(e,t){super(),this.stmtKind=e,this.expr=t}isStmt(){return!0}toString(){return p(this)}}function p(e){return function e(s){if(s.isExpr()){let n=s,i=n.args?n.args[0]:null;switch(n.exprKind){case r.NumberLiteral:case r.PointerLiteral:return n.data+"";case r.CellRef:return n.data.toString();case r.JmpValue:return"JMPVALUE";case r.Nop:return"NOP";case r.SharedRef:return`SHARED_REF(#${i.getId()})`;case r.SharedDef:return`SHARED_DEF(#${i.getId()} u(${i.totalUses}): ${e(i)})`;case r.FieldAccess:return`${e(i)}.${n.data.name}`;case r.RuntimeCall:return n.data+"("+n.args.map(e).join(", ")+")";case r.ProcCall:let s=n.data,a="";return a=null!=s.ifaceIndex?`IFACE@${s.ifaceIndex}`:null!=s.virtualIndex?`VTABLE@${s.virtualIndex}`:t.getDeclName(s.proc.action),a+"("+n.args.map(e).join(", ")+")";case r.Sequence:return"("+n.args.map(e).join("; ")+")";case r.InstanceOf:return"("+e(n.args[0])+" instanceof "+n.data.id+")";case r.Store:return`{ ${e(n.args[0])} := ${e(n.args[1])} }`;default:throw t.oops()}}else{let r=s,i=r.expr?e(r.expr):"{null}";switch(r.stmtKind){case n.SK.Expr:return" "+i+"\n";case n.SK.Jmp:let e=`goto ${r.lblName}\n`;switch(r.jmpMode){case a.Always:return r.expr?` { JMPVALUE := ${i} } ${e}`:" "+e;case a.IfZero:return` if (! ${i}) ${e}`;case a.IfNotZero:return` if (${i}) ${e}`;default:throw t.oops()}case n.SK.StackEmpty:return" ;\n";case n.SK.Breakpoint:return" // brk "+r.breakpointInfo.id+"\n";case n.SK.Comment:return" // "+r.expr.data+"\n";case n.SK.Label:return r.lblName+":\n";default:throw t.oops()}}}(e)}n.Stmt=u;class d{constructor(e,n,r){this.index=e,this.def=n,this.info=r,this.isarg=!1,this.iscap=!1,this._isLocal=!1,this._isGlobal=!1,this._debugType="?",this.isUserVariable=!1,this.bitSize=0,n&&(t.isInPxtModules(n)||(this.isUserVariable=!0),r&&t.setCellProps(this))}getName(){return t.getDeclName(this.def)}getDebugInfo(){return{name:this.getName(),type:this._debugType,index:this.index}}toString(){let e="";return this.def&&(e+=this.getName()||"?"),this.isarg&&(e="ARG "+e),"["+e+"]"}uniqueName(){return this.isarg?"arg"+this.index:this.getName().replace(/[^\w]/g,"_")+"___"+t.getNodeId(this.def)}isLocal(){return this._isLocal}isGlobal(){return this._isGlobal}loadCore(){return b(r.CellRef,null,this)}load(){let e=this.loadCore();return t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize?6==this.bitSize?y("pxt::fromUInt",[e]):y("pxt::fromInt",[e]):this.isByRefLocal()?y("pxtrt::ldlocRef",[e]):e}isByRefLocal(){return this.isLocal()&&this.info.captured&&this.info.written}storeDirect(e){return b(r.Store,[this.loadCore(),e])}storeByRef(e){if(this.isByRefLocal())return y("pxtrt::stlocRef",[this.loadCore(),e]);if(t.target.isNative&&!t.isStackMachine()&&0!=this.bitSize){let t=6==this.bitSize?"pxt::toUInt":"pxt::toInt";return this.storeDirect(y(t,[e],1))}return this.storeDirect(e)}get isTemporary(){return!1}}n.Cell=d;class f extends d{constructor(e,t){super(e,null,null),this.index=e,this.owningProc=t,this.uid=f.unnamedCellCounter++}getName(){return"unnamed"+this.uid}uniqueName(){return this.getName()+"___U"+this.index}isByRefLocal(){return!1}get isTemporary(){return!0}}function m(e){const t=()=>{if(!e.args)return 0;let t=0;for(let n of e.args)t+=m(n);return e.mask&&e.mask.conversions&&(t+=4*e.mask.conversions.length),t};switch(e.exprKind){case r.NumberLiteral:return 2;case r.PointerLiteral:return 6;case r.RuntimeCall:return t()+2+2+4;case r.CellRef:return 2;case r.FieldAccess:return t()+(e.data.needsCheck?4:0)+2;case r.ProcCall:case r.SharedRef:case r.SharedDef:case r.Store:case r.Sequence:case r.JmpValue:case r.Nop:case r.InstanceOf:return 1e6;default:throw s.oops()}}function h(e){switch((e=c.clone(e)).exprKind){case r.PointerLiteral:case r.NumberLiteral:return e;case r.RuntimeCall:for(let t=0;t<e.args.length;++t)e.args[t]=h(e.args[t]);return e;case r.CellRef:const t=e.data;return t.repl?(t.replUses++,t.repl):e;case r.FieldAccess:return e.args[0]=h(e.args[0]),e;default:throw s.oops()}}f.unnamedCellCounter=0,n.UnnamedCell=f;function g(e,t){return new u(e,t)}function b(e,t,n){return new c(e,t,n)}function x(e,t){let n=b(r.PointerLiteral,null,e);return n.jsInfo=t,n}function y(e,t,n=0){let s=b(r.RuntimeCall,t,e);return n&&(s.mask={refMask:n}),s}function k(e,i=!1,a=!1){let o=!!i&&e.some((e=>e.canUpdateCells())),l=[];for(let t of s.reversed(e))t.isStateless()||(t.exprKind!=r.CellRef||o)&&(t.canUpdateCells()&&(o=!0),l.push(t));l.reverse(),t.isStackMachine()&&!a&&(l=[]);let c=[],u=e.map((e=>{if(l.indexOf(e)>=0){let t=e,s=e;return e.exprKind==r.SharedDef?(e.args[0].totalUses++,t=n.op(r.SharedRef,[e.args[0]])):(t=n.op(r.SharedRef,[e]),s=n.op(r.SharedDef,[e]),e.totalUses=2,e.currUses=0),c.push(s),t}return e}));return{precomp:c,flattened:u}}n.Procedure=class extends l{constructor(){super(...arguments),this.numArgs=0,this.info=null,this.seqNo=-1,this.isRoot=!1,this.locals=[],this.captured=[],this.args=[],this.parent=null,this.debugInfo=null,this.fillDebugInfo=null,this.classInfo=null,this.perfCounterName=null,this.perfCounterNo=0,this.body=[],this.lblNo=0,this.action=null,this.cachedJS=null,this.usingCtx=null}reset(){this.body=[],this.lblNo=0,this.locals=[],this.captured=[],this.args=[]}isGetter(){return this.action&&this.action.kind==e.SyntaxKind.GetAccessor}vtLabel(){return this.label()+(t.isStackMachine()?"":"_args")}label(){return t.getFunctionLabel(this.action)}toString(){return`\nPROC ${t.getDeclName(this.action)}\n${this.body.map((e=>e.toString())).join("")}\n`}emit(e){this.body.push(e)}emitExpr(e){this.emit(g(i.Expr,e))}mkLabel(e){let t=g(i.Label,null);return t.lblName="."+e+"_"+this.lblNo+++"_"+this.seqNo,t.lbl=t,t}emitLbl(e){this.emit(e)}emitLblDirect(e){let t=g(i.Label,null);t.lblName=e,t.lbl=t,this.emit(t)}getFullName(){let n=t.getDeclName(this.action);if(this.action){let t=e.pxtc.nodeLocationInfo(this.action);n=t.fileName.replace("pxt_modules/","")+"("+(t.line+1)+","+(t.column+1)+"): "+n}return n}getName(){return(this.action&&this.action.name?this.action.name.text:null)||"inline"}mkLocal(e,t){let n=new d(this.locals.length,e,t);return this.locals.push(n),n}mkLocalUnnamed(){let e=new f(this.locals.length,this);return this.locals.push(e),e}localIndex(e,t=!1){return this.captured.filter((t=>t.def==e))[0]||this.locals.filter((t=>t.def==e))[0]||(t?null:this.args.filter((t=>t.def==e))[0])}stackEmpty(){this.emit(g(i.StackEmpty,null))}emitJmpZ(e,t){this.emitJmp(e,t,a.IfZero)}emitJmp(e,t,n=a.Always,s=null){let o=g(i.Jmp,t);o.jmpMode=n,s&&s.exprKind==r.NumberLiteral&&(s=null),o.terminateExpr=s,"string"==typeof e?o.lblName=e:(o.lbl=e,o.lblName=o.lbl.lblName),this.emit(o)}inlineSelf(e){const{precomp:t,flattened:n}=k(e,!1,!0);s.assert(n.length==this.args.length),this.args.map(((e,t)=>{e.repl=n[t],e.replUses=0}));const i=h(this.inlineBody);return this.args.forEach(((e,t)=>{e.repl.exprKind==r.SharedRef&&(e.repl.args[0].prevTotalUses||(e.repl.args[0].prevTotalUses=e.repl.args[0].totalUses),e.repl.args[0].totalUses+=e.replUses-1),e.repl=null,e.replUses=0})),t.length?(t.push(i),b(r.Sequence,t)):i}resolve(){let e=(e,t)=>{if(e.args)for(let n=0;n<e.args.length;++n)e.args[n]=t(e.args[n])},i=t=>{switch(t.exprKind){case r.SharedDef:throw s.oops();case r.SharedRef:let e=t.args[0];if(e.totalUses)return e.totalUses--,t;{e.totalUses=-1,e.currUses=0,e.irCurrUses=0;let n=c.clone(t);return n.exprKind=r.SharedDef,n.args[0]=i(n.args[0]),n}}return e(t,i),t},a=t=>{if(t.exprKind==r.SharedRef)return t;switch(e(t,a),t.exprKind){case r.Sequence:t.args=t.args.filter(((e,n)=>n==t.args.length-1||!e.isPure()||(e.exprKind==r.SharedRef&&e.args[0].totalUses>0&&e.args[0].totalUses--,!1)))}return t},o=t=>{switch(t.exprKind){case r.SharedDef:let e=t.args[0];if(s.assert(e.totalUses<0,"arg.totalUses < 0"),s.assert(0===e.currUses,"arg.currUses === 0"),-1==e.totalUses)return o(e);e.totalUses=1;break;case r.SharedRef:return s.assert(t.args[0].totalUses>0,"e.args[0].totalUses > 0"),t.args[0].totalUses++,t;case r.PointerLiteral:const n=t.ptrlabel();n&&(n.lblNumUses||(n.lblNumUses=0),n.lblNumUses++)}return e(t,o),t},l=t=>{switch(t.exprKind){case r.SharedDef:e(t,l);case r.SharedRef:let n=t.args[0];return s.assert(n.totalUses>0,"arg.totalUses > 0"),1==n.totalUses?(s.assert(t.exprKind==r.SharedDef),n):(n.irCurrUses++,t);default:return e(t,l),t}};this.body=this.body.filter((e=>!e.expr||(e.expr=a(i(e.expr)),e.stmtKind!=n.SK.Expr||!e.expr.isPure())));let u=s.toDictionary(this.body.filter((e=>e.stmtKind==n.SK.Label)),(e=>e.lblName));for(let e=0;e<this.body.length;++e)this.body[e].stmtNo=e;for(let e of this.body)switch(e.expr&&(e.expr=o(e.expr)),e.stmtKind){case n.SK.Expr:break;case n.SK.Jmp:e.lbl=s.lookup(u,e.lblName),e.lbl||t.oops("missing label: "+e.lblName),e.lbl.lblNumUses?e.lbl.lblNumUses++:e.lbl.lblNumUses=1;break;case n.SK.StackEmpty:case n.SK.Label:case n.SK.Breakpoint:case n.SK.Comment:break;default:t.oops()}let p=[],d=null,f=!t.target.debugMode,h=null;for(let e of this.body)e.expr&&(e.expr=a(l(e.expr))),d&&d.lbl==e&&d.stmtKind==n.SK.Jmp&&e.stmtKind==n.SK.Label&&d.jmpMode==n.JmpMode.Always&&1==e.lblNumUses&&(e.lblNumUses=n.lblNumUsesJmpNext),d=e,e.stmtKind==n.SK.Breakpoint?p[e.breakpointInfo.id]=e.breakpointInfo:f&&(e.stmtKind==n.SK.Jmp?e.expr&&(h?f=!1:h=e.expr):e.stmtKind==n.SK.StackEmpty||(e.stmtKind==n.SK.Label?e.lblNumUses!=n.lblNumUsesJmpNext&&(f=!1):f=!1));if(f&&h){m(h)<=4*this.args.length+4+2+(t.target.isNative?4:30)&&(this.inlineBody=h)}pxt.options.debug&&pxt.debug(this.toString())}},n.iterExpr=function e(t,n){if(n(t),t.args)for(let r of t.args)e(r,n)},n.stmt=g,n.comment=function(e){return g(i.Comment,x(e,e))},n.op=b,n.numlit=function(e){return b(r.NumberLiteral,null,e)},n.shared=function(e){switch(e.exprKind){case r.SharedRef:e=e.args[0];break;case r.NumberLiteral:return e}return b(r.SharedRef,[e])},n.ptrlit=x,n.rtcall=y,n.rtcallMask=function(e,t,n,r){s.startsWith(e,"@nomask@")&&(e=e.slice(8),t=0);let i=y(e,r,t);return i.callingConvention=n,i},n.flattenArgs=k}(t.ir||(t.ir={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){class n{constructor(e,t){this.wave=e,this.id=t,this.flags=0,this.resetAll()}refresh(){this.flags&=-9,!this.proc||this.usedActions||_(this.proc.action)?this.proc&&!this.proc.cachedJS?this.resetEmit():this.usedNodes&&(this.flags|=32):this.resetEmit(),this.classInfo&&this.classInfo.reset()}resetEmit(){this.flags&=-41,this.proc&&this.proc.classInfo&&this.proc.classInfo.ctor==this.proc&&(this.proc.classInfo.ctor=null),this.functionInfo=null,this.variableInfo=null,this.classInfo=null,this.callInfo=null,this.proc=null,this.cell=null,this.exprInfo=null,this.usedNodes=null,this.usedActions=null}resetTSC(){this.flags&=16,this.typeCache=null,this.symbolCache=null,this.commentAttrs=null,this.valueOverride=null,this.declCache=void 0,this.fullName=null,this.constantFolded=void 0}resetAll(){this.resetTSC(),this.resetEmit()}}let r;function s(e){return e<<2|2}t.PxtNode=n,function(e){e[e.Enum=0]="Enum",e[e.Number=1]="Number",e[e.String=2]="String",e[e.Boolean=3]="Boolean",e[e.Unsupported=4]="Unsupported"}(r||(r={})),t.taggedUndefined=0,t.taggedNull=s(1),t.taggedFalse=s(2),t.taggedNaN=s(3),t.taggedTrue=s(16),t.thumbArithmeticInstr={adds:!0,subs:!0,muls:!0,ands:!0,orrs:!0,eors:!0,lsls:!0,asrs:!0,lsrs:!0},t.numberArithmeticInstr={div:!0,mod:!0,le:!0,lt:!0,ge:!0,gt:!0,eq:!0,neq:!0};const i={"Array_::getAt":{name:"_pxt_array_get",argsFmt:["T","T","T"],value:0},"Array_::setAt":{name:"_pxt_array_set",argsFmt:["T","T","T","T"],value:0},"BufferMethods::getByte":{name:"_pxt_buffer_get",argsFmt:["T","T","T"],value:0},"BufferMethods::setByte":{name:"_pxt_buffer_set",argsFmt:["T","T","T","I"],value:0},"pxtrt::mapGetGeneric":{name:"_pxt_map_get",argsFmt:["T","T","S"],value:0},"pxtrt::mapSetGeneric":{name:"_pxt_map_set",argsFmt:["T","T","S","T"],value:0}};let a=t.ir.EK;t.SK=e.SyntaxKind,t.numReservedGlobals=1;let o=0,l=1;function c(n){if(n.pxt)return!!(16&n.pxt.flags);const r=e.getSourceFileOfNode(n);return!!r&&t.isPxtModulesFilename(r.fileName)}function u(e){if(e.pxt){const n=e.pxt;return n.wave!=l&&(n.wave=l,t.compileOptions&&t.compileOptions.skipPxtModulesTSC&&16&n.flags?t.compileOptions.skipPxtModulesEmit?n.refresh():n.resetEmit():n.resetAll()),n}{const t=new n(l,++o);return c(e)&&(t.flags|=16),e.pxt=t,t}}function p(e){return u(e).id}function d(t){return t?e.SyntaxKind[t.kind]:"<null>"}function f(e,t,n=!1){let r=new Error(t);if(r.ksEmitterUserError=!0,r.ksErrorCode=e,n&&B)return M||(M=t,D=e),r;throw r}function m(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_VM}function h(){return t.target.isNative&&t.target.nativeType!=t.NATIVE_TYPE_VM}function g(){return t.target.isNative&&t.target.nativeType==t.NATIVE_TYPE_THUMB}function b(e){return h()?t.ir.rtcall("pxt::fromInt",[e]):e}function x(e){return h()?t.ir.rtcall("pxt::fromBool",[e]):e}function y(e){switch(e){case 0:return t.target.shortPointers?2:4;case 1:return 1;case 3:return 2;case 5:return 4;case 2:return 1;case 4:return 2;case 6:return 4;default:throw t.oops()}}function k(e){switch(e){case 1:case 3:case 5:return!0;case 2:case 4:case 6:return!1;default:throw t.oops()}}function S(e){switch(e.kind){case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return!0;default:return!1}}function T(e){return e&&e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.StaticKeyword))}function I(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}function w(e,t){return e.explicitDefaults?e.explicitDefaults.indexOf(t)<0?null:e.paramDefl[t]:null}function E(e){if(!e)return null;switch(e.kind){case t.SK.MethodDeclaration:return"";case t.SK.Constructor:return"new/";case t.SK.GetAccessor:return"get/";case t.SK.SetAccessor:return"set/";default:return null}}function $(e){return E(e)+V(e)}function v(e){return null!=E(e)}function N(e){return e?v(e)?e:N(e.parent):null}function _(e){let n=e,r=!1;for(;;)switch(n=n.parent,n||f(9229,O("cannot determine parent of {0}",d(e))),n.kind){case t.SK.MethodDeclaration:case t.SK.Constructor:case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.FunctionDeclaration:case t.SK.ArrowFunction:case t.SK.FunctionExpression:return n;case t.SK.WhileStatement:case t.SK.DoStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:r=!0;break;case t.SK.SourceFile:return r?F:null}}function A(e){return"objectFlags"in e}function K(e){return!!e&&(e.kind==t.SK.VariableDeclaration||e.kind==t.SK.BindingElement&&K(e.parent.parent))}function C(e){return!!e&&(K(e)&&!_(e)||e.kind==t.SK.PropertyDeclaration&&T(e))}function U(e){return!!e&&(e.kind==t.SK.Parameter||e.kind==t.SK.BindingElement&&U(e.parent.parent))}t.isInPxtModules=c,t.pxtInfo=u,t.getNodeId=p,t.stringKind=d,t.isStackMachine=m,t.needsNumberConversions=h,t.isThumb=g,t.sizeOfBitSize=y,t.isBitSizeSigned=k,t.setCellProps=function(n){var r;if(n._isLocal=K(r=n.def)&&!C(r)||U(n.def),n._isGlobal=C(n.def),!n.def.isThisParameter){let r=ee(n.def);r.flags&e.TypeFlags.Void&&t.oops("void-typed variable, "+n.toString()),n.bitSize=function(e){if(!e||!e.type)return 0;if(!pe(ee(e)))return 0;if(e.type.kind!=t.SK.TypeReference)return 0;switch(e.type.typeName.getText()){case"int8":return 1;case"int16":return 3;case"int32":return 5;case"uint8":return 2;case"uint16":return 4;case"uint32":return 6;default:return 0}}(n.def),0!=n.bitSize?n._debugType=(k(n.bitSize)?"int":"uint")+8*y(n.bitSize):ue(r)?n._debugType="string":r.flags&e.TypeFlags.NumberLike&&(n._debugType="number")}n.isLocal()&&0!=n.bitSize&&(n.bitSize=0,f(9256,O("bit sizes are not supported for locals and parameters")))},t.isStatic=T,t.isReadOnly=I,t.getExplicitDefault=w,t.isObjectType=A;class P{constructor(e,t){this.id=e,this.decl=t,this.baseClassInfo=null,this.allfields=[],this.methods={},this.attrs=z(t),this.reset()}reset(){this.vtable=null,this.itable=null}get isUsed(){return!!(8&u(this.decl).flags)}allMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t])e.push(n);return e}usedMethods(){const e=[];for(let t of Object.keys(this.methods))for(let n of this.methods[t]){8&u(n).flags&&e.push(n)}return e}}t.ClassInfo=P;let L,F,M,O=t.assembler.lf,D=0,B=0;function R(e,n){const r=u(n);return null==r.fullName&&(r.fullName=t.getFullName(e,n.symbol)),r.fullName}function q(n){n.kind==t.SK.VariableDeclaration&&(n=n.parent.parent);let r=t=>{const n=e.getSourceFileOfNode(t);if(!n)return"";const r=e.getLeadingCommentRangesOfNode(t,n);if(!r)return"";return r.map((e=>n.text.slice(e.pos,e.end))).join("\n")};return n.symbol&&n.symbol.declarations&&n.symbol.declarations.length>1?n.symbol.declarations.map(r).join("\n"):r(n)}function j(e){let n="";for(let t of e.declarations)n+=q(t);return t.parseCommentString(n)}function z(e){const n=e?u(e):null;if(!n||2&n.flags)return t.parseCommentString("");if(n.commentAttrs)return n.commentAttrs;let r=t.parseCommentString(q(e));return r._name=V(e),n.commentAttrs=r,r}function V(e){return e.name&&e.name.kind==t.SK.Identifier?e.name.text:"???"}function G(t){if(A(t)&&t.objectFlags&e.ObjectFlags.Reference){let e=t;if(e.typeArguments&&e.typeArguments.length)return e.target}return null}function H(t){return!!A(t)&&(t.objectFlags&e.ObjectFlags.Reference&&t.symbol&&"Array"==t.symbol.name)}function J(t){return!!A(t)&&(!!(t.objectFlags&e.ObjectFlags.Interface)||!!(t.objectFlags&e.ObjectFlags.Anonymous))}function Q(t){return!!t.isThisType||!!A(t)&&!!(t.objectFlags&e.ObjectFlags.Class||t.symbol&&t.symbol.flags&e.SymbolFlags.Class)}function W(e){let t=G(e);return Q(t||e)}function Y(t,n=-1){return H(t)?t.typeArguments[0]:L.getIndexTypeOfType(t,e.IndexKind.Number)}function Z(e){return e}function X(e){return null===e?t.taggedNull:void 0===e?t.taggedUndefined:!1===e?t.taggedFalse:!0===e?t.taggedTrue:isNaN(e)?t.taggedNaN:null}function ee(t){let n;const r=u(t);if(r.typeCache)return r.typeCache;if(e.isExpression(t)&&(n=L.getContextualType(t)),!n)try{n=L.getTypeAtLocation(t)}catch(e){f(9203,O("Unknown type for expression"))}return n?(r.typeCache=n,n):n}function te(t){if(!(t.flags&e.TypeFlags.Union))return r.Unsupported;let n,s=!0;return t.types.forEach((t=>{if(void 0===n)t.flags&e.TypeFlags.NumberLike?n=r.Number:t.flags&e.TypeFlags.BooleanLike?n=r.Boolean:t.flags&e.TypeFlags.StringLike?n=r.String:t.flags&e.TypeFlags.EnumLike&&(n=r.Enum);else switch(n){case r.Number:s=s&&!!(t.flags&e.TypeFlags.NumberLike);break;case r.Boolean:s=s&&!!(t.flags&e.TypeFlags.BooleanLike);break;case r.String:s=s&&!!(t.flags&e.TypeFlags.StringLike);break;case r.Enum:s=s&&!!(t.flags&e.TypeFlags.EnumLike)}})),s?n:r.Unsupported}function ne(t){let n=L.getSignatureFromDeclaration(t);return!(L.getReturnTypeOfSignature(n).flags&e.TypeFlags.Void)}function re(e){return!(!e||!e.name)}function se(e){if(!e)return"";switch(e.kind){case t.SK.ModuleBlock:return se(e.parent);case t.SK.ClassDeclaration:case t.SK.ModuleDeclaration:return se(e.parent)+e.name.text+".";default:return""}}function ie(e){let n=re(e)?e.name.text:null;if(!n){if(e.kind!=t.SK.Constructor){for(let t=e.parent;t;t=t.parent)if(re(t))return ie(t)+".inline";return"inline"}n="constructor"}return se(e.parent)+n}function ae(e){return ie(e).replace(/[^\w]+/g,"_")}function oe(e){return ae(e)+"__P"+p(e)}t.getNodeFullName=R,t.getComments=q,t.parseCommentsOnSymbol=j,t.parseComments=z,t.getName=V,t.checkType=Z,t.taggedSpecial=X,t.getDeclName=ie,t.getFunctionLabel=oe;class le{constructor(e){this.decl=e,this.capturedVars=[]}get isUsed(){return!!(8&u(this.decl).flags)}}function ce(e,t,n){return!!(e.flags&t)||te(e)===n}function ue(t){return ce(t,e.TypeFlags.String|e.TypeFlags.StringLiteral,r.String)}function pe(t){return ce(t,e.TypeFlags.Number|e.TypeFlags.NumberLiteral,r.Number)}t.FunctionAddInfo=le,t.compileBinary=function(n,r,s,o){t.compilerHooks.preBinary&&t.compilerHooks.preBinary(n,r,s),t.target=r.target,t.compileOptions=r,t.target.debugMode=!!r.breakpoints;const k=e.createDiagnosticCollection();L=n.getTypeChecker();let E=t.U.cpuUs(),A=[],q=[],G={},Z={},te=null,re=null,se=!1,ce=[];if(l++,r.target.isNative){if(!r.extinfo||!r.extinfo.hexinfo)return{diagnostics:[{file:n.getSourceFiles()[0],start:0,length:0,category:t.DiagnosticCategory.Error,code:9043,messageText:O("The hex file is not available, please connect to internet and try again.")}],emittedFiles:[],emitSkipped:!0};let e=r.extinfo,s=r.target;if(e&&e.disabledDeps){const t=(r.otherMultiVariants||[]).find((e=>e.extinfo&&!e.extinfo.disabledDeps));t&&(pxt.debug(`using alternative extinfo (due to ${e.disabledDeps})`),e=t.extinfo,s=t.target)}t.hexfile.setupFor(s,e||t.emptyExtInfo()),t.hexfile.setupInlineAssembly(r)}let ge,be=new de;function xe(){be.reset(),ge=null,s.breakpoints=[{id:0,isDebuggerStmt:!1,fileName:"bogus",start:0,length:0,line:0,column:0}],s.procCallLocations=[]}be.trace=r.trace,be.breakpoints=r.breakpoints,be.name=r.name,be.target=r.target,r.computeUsedSymbols&&(s.usedSymbols={},s.usedArguments={}),r.computeUsedParts&&(s.usedParts=[]);let ye=[];if(!r.forceEmit||0==s.diagnostics.length){let e=n.getSourceFiles().slice();const t=e.find((e=>e.fileName===pxt.MAIN_TS));t&&(e=e.filter((e=>e.fileName!==pxt.MAIN_TS)),e.push(t));const r=e.find((e=>e.fileName===pxt.TUTORIAL_CODE_STOP));r&&(e=e.filter((e=>e.fileName!==pxt.TUTORIAL_CODE_STOP)),e.push(r)),e.forEach((e=>{e.statements.forEach((e=>{ye.push(e)}))}))}let ke=n.getSourceFiles().filter((e=>t.Util.endsWith(e.fileName,o)))[0],Se={kind:t.SK.FunctionDeclaration,parameters:[],name:{text:"<main>",pos:0,end:0},body:{kind:t.SK.Block,statements:ye},parent:ke,pos:0,end:0};F=Se;const Te=u(Se);for(Te.flags|=3,rt(Se),A=[],xe(),se=!0,Sn(Se);Tt(),!Oe(););!function(){let e=be.globals.slice(0);e.forEach(((e,t)=>e.index=t));const n=e=>0==e?10:y(e);e.sort(((e,t)=>n(e.bitSize)-n(t.bitSize)||e.index-t.index));let r=4*t.numReservedGlobals,s=0;for(let t of e){const e=m()?0:t.bitSize;let n=y(e);for(;r&n-1;)r++;s||0!=e||(s=r),t.index=r,r+=n}be.globalsWords=r+3>>2,be.nonPtrGlobals=s?s>>2:be.globalsWords}(),se=!1,function(){for(let e of be.usedClassInfos)De(e);let e=Object.keys(be.ifaceMemberMap);e.sort(t.U.strcmp),e.unshift(""),be.emitString(""),be.ifaceMembers=e,be.ifaceMemberMap={};let n=0;for(let t of e)be.ifaceMemberMap[t]=n++;for(let e of be.usedClassInfos)for(let t of e.itable)t.idx=Ue(t.name);for(let e of be.usedClassInfos)e.lastSubtypeNo=void 0,e.classNo=void 0;let r=pxt.BuiltInType.User0;const s=e=>{t.U.assert(!e.classNo),e.classNo=r++;for(let t of e.derivedClasses)t.isUsed&&s(t);e.lastSubtypeNo=r-1};for(let e of be.usedClassInfos){let t=e;for(;t.baseClassInfo;)t=t.baseClassInfo;t.classNo||s(t)}}();let Ie=t.U.cpuUs();s.times.pass0=Ie-E;let we=k.getDiagnostics();xe(),se=!1,be.finalPass=!0,Tn(Se),t.U.assert(0==A.length),s.configData=[];for(let e of Object.keys(Z))Z["!"+e]||s.configData.push({name:e.replace(/^\!/,""),key:Z[e].key,value:Z[e].value});s.configData.sort(((e,t)=>e.key-t.key));let Ee=t.U.cpuUs();if(s.times.pass1=Ee-Ie,xn(Se,(function(){if(r.noEmit)return;be.writeFile=(e,t)=>{s.outfiles[e]=t};for(let e of be.procs)e.cachedJS&&!e.inlineBody||e.resolve();t.target.isNative&&(be.procs=be.procs.filter((e=>!(e.inlineBody&&!e.info.usedAsIface&&!e.info.usedAsValue))));r.target.isNative?([...r.otherMultiVariants||[],r].forEach((({extinfo:e})=>{e.yotta&&be.writeFile("yotta.json",JSON.stringify(e.yotta,null,2)),e.codal&&be.writeFile("codal.json",JSON.stringify(e.codal,null,2)),e.platformio&&be.writeFile("platformio.json",JSON.stringify(e.platformio,null,2))})),r.target.nativeType==t.NATIVE_TYPE_VM?t.vmEmit(be,r,s):t.processorEmit(be,r,s)):t.jsEmit(be,s);be.writeFile=void 0})),s.times.passFinal=t.U.cpuUs()-Ee,r.ast){let e=t.U.cpuUs();t.annotate(n,o,t.target),s.times.passAnnotate=t.U.cpuUs()-e}return t.compileOptions=null,0==we.length&&(we=k.getDiagnostics()),t.compilerHooks.postBinary&&t.compilerHooks.postBinary(n,r,s),{diagnostics:we,emittedFiles:void 0,emitSkipped:!!r.noEmit};function $e(t,n,r,s,i,a,o){k.add(e.createDiagnosticForNode(n,{code:r,message:s,key:s.replace(/^[a-zA-Z]+/g,"_"),category:t},i,a,o))}function ve(e,n,r,s,i,a){$e(t.DiagnosticCategory.Error,e,n,r,s,i,a)}function Ne(t,n,r=9202){if(n)return f(r,n);t||f(r,O("Sorry, this language feature is not supported"));let s=d(t),i=!1,a=null;switch(t.kind){case e.SyntaxKind.ForInStatement:s=O("for in loops");break;case e.SyntaxKind.ForOfStatement:s=O("for of loops"),i=!0;break;case e.SyntaxKind.PropertyAccessExpression:s=O("property access");break;case e.SyntaxKind.DeleteExpression:s=O("delete");break;case e.SyntaxKind.GetAccessor:s=O("get accessor method"),i=!0;break;case e.SyntaxKind.SetAccessor:s=O("set accessor method"),i=!0;break;case e.SyntaxKind.TaggedTemplateExpression:s=O("tagged templates");break;case e.SyntaxKind.SpreadElement:s=O("spread");break;case e.SyntaxKind.TryStatement:case e.SyntaxKind.CatchClause:case e.SyntaxKind.FinallyKeyword:case e.SyntaxKind.ThrowStatement:s=O("throwing and catching exceptions");break;case e.SyntaxKind.ClassExpression:s=O("class expressions"),a=O("declare a class as class C {} not let C = class {}")}let o="";return o=i?O("{0} not currently supported",s):O("{0} not supported",e.SyntaxKind[t.kind]),a&&(o+=" - "+a),f(r,o)}function _e(e){return p(e)+""}function Ae(e){const t=u(e);return t.functionInfo||(t.functionInfo=new le(e)),t.functionInfo}function Ke(e){const t=u(e);return t.variableInfo||(t.variableInfo={}),t.variableInfo}function Ce(e,t=!1){let n=Ke(e);t&&(n.written=!0);let r=_(e);if(null==r||r==ge.action);else{let t=ge.action;for(;t&&t!=r;){let n=Ae(t);n.capturedVars.indexOf(e)<0&&n.capturedVars.push(e),t=_(t)}n.captured=!0}}function Ue(e,n=!1){return function(e,n,r,s,i){return he(e,s,i,(e=>{r&&(t.U.lookup(e.explicitlyUsedIfaceMembers,n)||(t.U.assert(!e.finalPass),e.explicitlyUsedIfaceMembers[n]=!0));let s=t.U.lookup(e.ifaceMemberMap,n);return null!=s||(t.U.assert(!e.finalPass),s=e.ifaceMemberMap[n]=-1,e.emitString(n)),s}))}(be,e,n,se,re)}function Pe(t){t.flags&e.TypeFlags.Void&&f(9203,O("void-typed variables not supported"))}function Le(e){const n=u(e);Pe(ee(e)),n.cell||(n.cell=new t.ir.Cell(null,e,Ke(e))),be.globals.indexOf(n.cell)<0&&be.globals.push(n.cell)}function Fe(e){if(C(e)){rt(e);const t=u(e);return t.cell||Le(e),t.cell}{let t=ge.localIndex(e);return t||(be.finalPass?f(9204,O("cannot locate identifer")):t=ge.mkLocal(e,Ke(e))),t}}function Me(e){return e.kind==t.SK.MethodDeclaration&&0==e.parameters.length&&"toString"==V(e)}function Oe(){se=!1;const e=be.usedClassInfos.length;for(let e of be.usedClassInfos){for(let r of e.allMethods()){const e=u(r),s=Ae(r);8&e.flags?s.virtualParent&&st(s.virtualParent.decl):(s.virtualParent&&s.virtualParent.isUsed||Me(r)||(n=V(r),null!=t.U.lookup(be.explicitlyUsedIfaceMembers,n)))&&st(r)}const r=bt(e.decl);r&&st(r)}var n;return se=!0,0==A.length&&e==be.usedClassInfos.length}function De(e){if(t.assert(e.isUsed,"inf.isUsed"),e.vtable)return e.vtable;let n=e.baseClassInfo?De(e.baseClassInfo).slice(0):[];e.derivedClasses=[],e.baseClassInfo&&e.baseClassInfo.derivedClasses.push(e);for(let r of e.usedMethods()){be.numMethods++;let s=Ae(r);const i=z(r);if(Me(r)&&!i.shim&&(e.toStringMethod=ht(r),e.toStringMethod.info.usedAsIface=!0),s.virtualParent){be.numVirtMethods++;let e=$(r),i=!1,a=ht(r);t.U.assert(!!a);for(let t=0;t<n.length;++t)$(n[t].action)==e&&(n[t]=a,s.virtualIndex=t,i=!0);i||(s.virtualIndex=n.length,n.push(a))}}e.vtable=n,e.itable=[];const r={};for(let t of e.allfields){let n=V(t),s=Lt(e,t,!1);r[n]=!0,e.itable.push({name:n,info:(s.idx+1)*(m()?1:4),idx:Ue(n),proc:null})}for(let n=e;n;n=n.baseClassInfo)for(let r of n.usedMethods()){const n=V(r);if(z(r).shim)continue;const s=ht(r),i=e.itable.find((e=>e.name==n)),a=r.kind==t.SK.SetAccessor,o=r.kind==t.SK.GetAccessor;i?(a&&!i.setProc?i.setProc=s:o&&!i.proc&&(i.proc=s),i.info=0):e.itable.push({name:n,info:0,idx:Ue(n),proc:a?null:s,setProc:a?s:null}),s.info.usedAsIface=!0}return e.vtable}function Be(e){if(32&e.flags||16&e.flags&&t.compileOptions.skipPxtModulesEmit)throw s.needsFullRecompile=!0,f(9200,O("full recompile required"))}function Re(e,n=null){n||(n=e.symbol.valueDeclaration);const r=u(n);if(!r.classInfo){const e=ae(n)+"__C"+p(n),s=new P(e,n);r.classInfo=s,s.attrs.autoCreate&&(G[s.attrs.autoCreate]=!0),s.baseClassInfo=function(e){if(e.heritageClauses)for(let n of e.heritageClauses)switch(n.token){case t.SK.ExtendsKeyword:if(!n.types||1!=n.types.length)throw f(9228,O("invalid extends clause"));let r=ee(n.types[0]);if(r&&Q(r))return L.getTypeAtLocation(e),Re(r);throw f(9228,O("cannot inherit from this type"));case t.SK.ImplementsKeyword:break;default:throw f(9228,O("invalid heritage clause"))}return null}(n);const i=s.baseClassInfo?t.U.toDictionary(s.baseClassInfo.allfields,(e=>V(e))):{},a=(e,t=s.baseClassInfo)=>t?t.methods[e]||a(e,t.baseClassInfo):null;for(let e of n.members)if(e.kind==t.SK.PropertyDeclaration){let n=e;T(n)||s.allfields.push(n);const r=V(n);(a(r)||t.U.lookup(i,r))&&ve(n,9279,O("redefinition of '{0}' as field",r))}else if(e.kind==t.SK.Constructor)for(let t of e.parameters)fe(t)&&s.allfields.push(t);else if(v(e)){let n=Ae(e);n.parentClassInfo=s,n.isUsed&&xt(s);const r=V(e);s.methods.hasOwnProperty(r)||(s.methods[r]=[]),s.methods[r].push(e);const a=t.U.lookup(i,r);if(a){const e=u(a);64&e.flags||(e.flags|=64,8&e.flags&&Ue(r,!0),Be(e))}}s.baseClassInfo&&(s.allfields=s.baseClassInfo.allfields.concat(s.allfields),function(e){for(let n of e.allMethods()){let r=null;const s=$(n),i=V(n);for(let t=e.baseClassInfo;t;t=t.baseClassInfo)if(t.methods.hasOwnProperty(i))for(let e of t.methods[i])$(e)==s&&(r=e);if(r){let e=Ae(n),s=Ae(r);r.parameters.length!=n.parameters.length&&ve(n,9255,O("the overriding method is currently required to have the same number of arguments as the base one")),e.virtualParent=s,s.virtualParent||(Be(u(r)),s.virtualParent=s),t.assert(s.virtualParent==s,"pinf.virtualParent == pinf")}}}(s))}return r.classInfo}function qe(e){if(!e)return!1;if(S(e))return!1;switch(e.kind){case t.SK.ArrayLiteralExpression:return e.elements.some(qe);default:return null==jt(e)}}function je(e){const t=qt(e);if(t)return Qt(t.val);if(C(e)){if(z(e).shim)return ut(e,e,[])}let n=Fe(e);return Ce(e),n.load()}function ze(e){z(e).shim&&f(9207,O("built-in functions cannot be yet used as values; did you forget ()?"));let n=Ae(e);return Ve(n),n.location?n.location.load():(t.assert(!be.finalPass||0==n.capturedVars.length,"!bin.finalPass || info.capturedVars.length == 0"),n.usedAsValue=!0,st(e),St(e))}function Ve(e){void 0===e.usedBeforeDecl?e.usedBeforeDecl=!0:be.finalPass&&e.usedBeforeDecl&&e.capturedVars.length&&_(e.decl)&&!e.alreadyEmitted&&f(9278,O("function referenced before all variables it uses are defined"))}function Ge(e){const n=ot(e),r=qt(n);if(r)return Qt(r.val);if(n&&(K(n)||U(n)))return je(n);if(n&&n.kind==t.SK.FunctionDeclaration)return ze(n);if("undefined"==e.text)return Qt(void 0);throw Ne(e,O("Unknown or undeclared identifier"),9235)}function He(e){let n=N(e);n||f(9208,O("'this' used outside of a method"));let r=Ae(n);return r.thisParameter||t.oops("no this"),je(r.thisParameter)}function Je(e){let n;if(""==e)n=t.ir.rtcall("String_::mkEmpty",[]);else{let r=function(e){return function(e,t,n,r){return he(e,n,r,(e=>e.emitString(t)))}(be,e,se,re)}(e);n=t.ir.ptrlit(r,JSON.stringify(e))}return n.isStringLiteral=!0,n}function Qe(e){let n=lt(e),r=yn(e);return t.target.isNative||S(e)?Ut(r,n):(r=t.ir.rtcallMask("String_::stringConv",1,1,[r]),Ut(r,!0))}function We(e){let n=0,r=(e,t)=>{return S(r=t)&&""==r.text?e:(n++,Zt("String_::concat",[Ut(e,!0),Qe(t)],null));var r},s=u(Qe(e.head)).valueOverride;for(let t of e.templateSpans)s=r(s,t.expression),s=r(s,t.literal);return 0==n?Zt("String_::concat",[Ut(s,!0),Ut(t.ir.rtcall("String_::mkEmpty",[]),!1)],null):s}function Ye(e){let n=ot(e);const r=qt(n);if(r)return Qt(r.val);if(n.kind==t.SK.SetAccessor&&(n=Ze(n)),n.kind==t.SK.GetAccessor)return dt(e,e,[],null,n);if(n.kind==t.SK.EnumMember)throw f(9210,O("Cannot compute enum value"));if(n.kind==t.SK.PropertySignature||n.kind==t.SK.PropertyAssignment)return dt(e,e,[],null,n,e.expression);if(n.kind==t.SK.PropertyDeclaration||n.kind==t.SK.Parameter){if(T(n))return je(n);if(Xe(n))return dt(e,e,[],null,n,e.expression);{let n=function(e){const n=ee(e.expression);if(W(n)){const r=Re(n);let s=e.expression.kind==t.SK.ThisKeyword;return t.target.switches.noThisCheckOpt&&(s=!1),Lt(r,Ft(r,e.name.text),!s)}throw Ne(e,O("bad field access"),9247)}(e);return t.ir.op(a.FieldAccess,[yn(e.expression)],n)}}if(v(n)||n.kind==t.SK.MethodSignature)throw f(9211,O("cannot use method as lambda; did you forget '()' ?"));if(n.kind==t.SK.FunctionDeclaration)return ze(n);if(K(n))return je(n);throw Ne(e,O("Unknown property access for {0}",d(n)),9237)}function Ze(n){const r=e.getDeclarationOfKind(n.symbol,t.SK.GetAccessor);if(null==r)throw f(9281,O("setter currently requires a corresponding getter"));return r}function Xe(e){if(e.kind==t.SK.Parameter||e.kind==t.SK.PropertyDeclaration){const n=u(e);return!!t.target.switches.slowFields||!!(64&n.flags)}return!1}function et(t,n=null){let r=ee(t.expression),s={callingConvention:0,paramDefl:{}},i=null,a=!1;if(!n&&ue(r)?i="String_::charAt":H(r)?i=n?"Array_::setAt":"Array_::getAt":J(r)&&(s=j(r.symbol),i=n?s.indexerSet:s.indexerGet),!i&&r.flags&(e.TypeFlags.Any|e.TypeFlags.StructuredOrTypeVariable)&&(i=n?"pxtrt::mapSetGeneric":"pxtrt::mapGetGeneric",a=!0),i){if(a||Wt(t.argumentExpression)){return Zt(i,[t.expression,t.argumentExpression],s,n?[n]:[])}throw Ne(t,O("non-numeric indexer on {0}",i),9238)}throw Ne(t,O("unsupported indexer"),9239)}function tt(n){let s=function(e){return!!C(e)&&(!qe(e.initializer)||!!z(e).whenUsed)}(n)||function(e){return e.kind==t.SK.FunctionDeclaration&&!_(e)||v(e)}(n)||e.isClassDeclaration(n);return!t.target.switches.noTreeShake&&(!(r.testMode&&s&&!c(n))&&s)}function nt(e){if(!tt(e))return!0;const t=u(e);return be.finalPass?!!(8&t.flags):t==re}function rt(e){var t;if(!e)return;const n=u(e);if(n.classInfo)xt(n.classInfo);else{if(r.computeUsedSymbols&&e.symbol&&(s.usedSymbols[R(L,e)]=null),r.computeUsedParts&&(null===(t=n.commentAttrs)||void 0===t?void 0:t.parts)){const e=n.commentAttrs.parts.split(/[ ,]+/g);for(const t of e)-1===s.usedParts.indexOf(t)&&s.usedParts.push(t)}m()&&v(e)&&Ue(V(e),!0),it(e),8&n.flags||(n.flags|=8,tt(e)&&A.push(e))}}function st(e){rt(e)}function it(e){se&&(re?re.usedNodes[_e(e)]=e:t.U.oops("no using ctx for: "+V(e)))}function at(t){if(!t)return null;const n=u(t);if(void 0!==n.declCache)return n.declCache;let r,s=L.getSymbolAtLocation(t);if(s&&(r=s.valueDeclaration,!r&&s.declarations)){let t=s.declarations[0];t&&t.kind==e.SyntaxKind.ImportEqualsDeclaration&&(s=L.getSymbolAtLocation(t.moduleReference),s&&(r=s.valueDeclaration))}return r}function ot(e){let n=at(e);if(rt(n),!n&&e&&e.kind==t.SK.PropertyAccessExpression){const r=e;n={kind:t.SK.PropertySignature,symbol:{isBogusSymbol:!0,name:r.name.getText()},name:r.name},u(n).flags|=2}return Te.declCache=n||null,n}function lt(e){return e.kind==t.SK.NullKeyword||e.kind==t.SK.NumericLiteral?!!e.isRefOverride:!S(e)}function ct(e){t.assert(e.length<=8,"args.length <= 8");let n=0;return e.forEach(((e,t)=>{lt(e)&&(n|=1<<t)})),n}function ut(n,s,i){let a=z(n),o=!(ee(s).flags&e.TypeFlags.Void),l=a.shim;if(l.indexOf("(")>=0){let e=/(.*)\((.*)\)$/.exec(l);if(e){i.length&&t.U.userError("no arguments expected");let o=[];if(e[2].replace(/\s/g,"")){for(let n of e[2].split(/,/)){let e=parseInt(n);isNaN(e)&&(e=Ht(s,n),null==e&&(e=Vt(s,n)),null==e&&t.U.userError("invalid argument: "+n+" in "+l)),o.push(t.ir.numlit(e))}o.length>4&&t.U.userError("too many args")}return l=e[1],r.target.isNative&&t.hexfile.validateShim(ie(n),l,a,!0,o.map((e=>!0))),t.ir.rtcallMask(l,0,a.callingConvention,o)}}return"TD_NOOP"==l?(t.assert(!o,"!hasRet"),t.target.switches.profile&&"perfCounter"==a.shimArgument&&(i[0]&&i[0].kind==t.SK.StringLiteral&&(ge.perfCounterName=i[0].text),ge.perfCounterName||(ge.perfCounterName=ge.getFullName())),Qt(void 0)):"TD_ID"==l||"ENUM_GET"===l?(t.assert(1==i.length,"args.length == 1"),yn(i[0])):(r.target.shimRenames&&t.U.lookup(r.target.shimRenames,l)&&(l=r.target.shimRenames[l]),r.target.isNative&&t.hexfile.validateShim(ie(n),l,a,o,i.map(Wt)),Zt(l,i,a))}function pt(e,n,r){if(!e)return;let s=e.getParameters(),i=n.length;s.length>n.length&&s.slice(n.length).forEach((e=>{if(e.valueDeclaration&&e.valueDeclaration.kind==t.SK.Parameter){let s=e.valueDeclaration;if(s.initializer)(function(e){switch(e.kind){case t.SK.UndefinedKeyword:case t.SK.NullKeyword:case t.SK.TrueKeyword:case t.SK.FalseKeyword:case t.SK.NumericLiteral:return!0;case t.SK.PropertyAccessExpression:return yn(e).exprKind==a.NumberLiteral;default:return!1}})(s.initializer)||f(9212,O("only numbers, null, true and false supported as default arguments")),n.push(s.initializer);else{let e=w(r,V(s)),t=e?Qt(parseInt(e)):null;null==t&&(t=Qt(void 0)),n.push(Ut(t))}}else f(9213,O("unsupported default argument (shouldn't happen)"))}));for(let e=0;e<i;e++){let r=s[e];r&&r.valueDeclaration&&r.valueDeclaration.kind==t.SK.Parameter&&(n[e],r.valueDeclaration)}r.imageLiteral&&(S(n[0])||f(9214,O("Only image literals (string literals) supported here; {0}",d(n[0]))),n[0]=function(e){e||(e="0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n");let n=0,r=0,s=0,i="",a=0;e+="\n";for(let t=0;t<e.length;++t)switch(e[t]){case".":case"_":case"0":i+="0,",n++,a++;break;case"#":case"*":case"1":i+="255,",n++,a++;break;case"\t":case"\r":case" ":break;case"\n":n&&(0==r?r=n:n!=r&&f(9205,O("lines in image literal have to have the same width (got {0} and then {1} pixels)",r,n)),n=0,s++);break;default:f(9206,O("Only 0 . _ (off) and 1 # * (on) are allowed in image literals"))}let o="_img"+be.lblNo++;a%2!=0&&(i+="0"),be.otherLiterals.push(`\n.balign 4\n${o}: .short 0xffff\n .short ${r}, ${s}\n .byte ${i}\n`);let l="new pxsim.Image("+r+", ["+i+"])";return{kind:t.SK.NumericLiteral,imageLiteral:o,jsLit:l}}(n[0].text))}function dt(n,r,i,a,o=null,l=null){var c;o||(o=ot(r));let u=!1,p=!1,d=!1;const h=n===r;if(o)switch(o.kind){case t.SK.PropertySignature:case t.SK.PropertyAssignment:case t.SK.PropertyDeclaration:case t.SK.MethodSignature:u=!0;break;case t.SK.Parameter:fe(o)&&(u=!0);break;case t.SK.GetAccessor:case t.SK.SetAccessor:case t.SK.MethodDeclaration:u=!0,p=!0,d=T(o);break;case t.SK.FunctionDeclaration:d=!0;break;case t.SK.ModuleDeclaration:break;default:o=null}else r.kind==t.SK.PropertyAccessExpression&&(u=!0);t.target.switches.slowMethods&&(p=!1);const g=z(o);let b=i.slice(0);if(u&&T(o)&&(u=!1),u&&!l&&r.kind==t.SK.PropertyAccessExpression&&(l=r.expression),s.usedArguments&&g.trackArgs){let e=l?[l].concat(b):b,n=g.trackArgs.map((t=>e[t])).map((e=>{let n=ot(e);return!n||n.kind!=t.SK.EnumMember&&n.kind!=t.SK.VariableDeclaration?e&&e.kind==t.SK.StringLiteral?e.text:"*":R(L,n)})).join(","),r=R(L,o),i=s.usedArguments[r];i||(i=s.usedArguments[r]=[]),i.indexOf(n)<0&&i.push(n)}function x(){let e=gt(o,n,b.map((e=>yn(e)))),r=e.data;return b[0]&&r.proc&&r.proc.classInfo&&(r.isThis=b[0].kind==t.SK.ThisKeyword),e}if(pt(a,b,g),d){if(!Ae(o).location)return g.shim&&!Nt(o)?ut(o,n,b):(st(o),x())}if(r.kind==t.SK.SuperKeyword){let e=ge.classInfo.baseClassInfo.ctor;for(let t=ge.classInfo.baseClassInfo;t&&!e;t=t.baseClassInfo)e=t.ctor;if(!e&&be.finalPass)throw f(9280,O("super() call requires an explicit constructor in base class"));let t=b.map((e=>yn(e)));return t.unshift(He(r)),ft(e,n,t)}if(u){if(t.U.assert(!T(o)),l?b.unshift(l):Ne(n,O("strange method call"),9241),!o){t.U.assert(r.kind==t.SK.PropertyAccessExpression);const e=r.name.text;return mt(b.map((e=>yn(e))),{ifaceIndex:Ue(e,!0),callLocationIndex:wn(n),noArgs:h})}let s=Ae(o);if(s.parentClassInfo&&xt(s.parentClassInfo),st(o),l.kind==t.SK.SuperKeyword)return x();const i=!!s.virtualParent,a=!!m()||!!t.target.switches.slowMethods;if(i&&!a)return o.kind==t.SK.MethodDeclaration?t.U.assert(!h):o.kind==t.SK.GetAccessor||o.kind==t.SK.SetAccessor?t.U.assert(h):t.U.assert(!1),t.U.assert(!be.finalPass||null!=s.virtualIndex,"!bin.finalPass || info.virtualIndex != null"),mt(b.map((e=>yn(e))),{classInfo:s.parentClassInfo,virtualIndex:s.virtualIndex,noArgs:h,isThis:b[0].kind==t.SK.ThisKeyword});if(g.shim&&!Nt(o))return ut(o,n,b);if(g.helper){let r,s=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of s)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(c=e.symbol)||void 0===c?void 0:c.name)==g.helper&&(r=e);return r||f(9215,O("helpers.{0} not found",g.helper)),r.kind!=t.SK.FunctionDeclaration&&f(9216,O("helpers.{0} isn't a function",g.helper)),st(o=r),x()}return i||t.target.switches.slowMethods||!p?mt(b.map((e=>yn(e))),{ifaceIndex:Ue(V(o),!0),isSet:h&&2==b.length,callLocationIndex:wn(n),noArgs:h}):(t.U.assert(o.kind!=t.SK.MethodSignature),x())}return o&&o.kind==t.SK.ModuleDeclaration&&("String"==V(o)?f(9219,O('to convert X to string use: X + ""')):f(9220,O("namespaces cannot be called directly"))),b.unshift(r),t.U.assert(!h),mt(b.map((e=>yn(e))),{virtualIndex:-1,callLocationIndex:wn(n),noArgs:h})}function ft(e,n,r){t.U.assert(!be.finalPass||!!e);let s={proc:e,callLocationIndex:wn(n),virtualIndex:null,ifaceIndex:null};return t.ir.op(a.ProcCall,r,s)}function mt(e,n){return t.ir.op(a.ProcCall,e,n)}function ht(e){return u(e).proc}function gt(e,n,r){const s=ht(e);if(e.kind==t.SK.FunctionDeclaration){Ve(Ae(e))}return t.assert(!!s||!be.finalPass,"!!proc || !bin.finalPass"),ft(s,n,r)}function bt(e){return e.members.filter((e=>e.kind==t.SK.Constructor))[0]}function xt(e){if(it(e.decl),e.isUsed)return;u(e.decl).flags|=8,e.baseClassInfo&&xt(e.baseClassInfo),be.usedClassInfos.push(e)}function yt(n){function s(e){return/^[0-9a-f]$/i.test(e)}let i=ot(n.tag);if(!i)throw Ne(n,O("invalid tagged template"),9265);let a,o=z(i),l={decl:i,qName:i?R(L,i):"?",args:[n.template],isExpression:!0};function c(i){a=function(n,i){let a=te;if("_"==i[0]&&"_"==i[1]&&r.jres[i]&&(a=r.jres[i],i=""),""==i&&a){let n=/font\/x-mkcd-b(\d+)/.exec(a.mimeType);if(n)if(be.finalPass){let e=parseInt(n[1]),r=atob(a.data),s=be.usedChars,o="",l="";for(let t=0;t<r.length;t+=e){let n=r.charCodeAt(t)+(r.charCodeAt(t+1)<<8);(n<128||s[n>>5]&1<<(31&n))&&(o+=r.slice(t,t+e),l+=n+", ")}i=t.U.toHex(t.U.stringToUint8Array(o))}else i="aabbccdd";else a.dataEncoding&&"base64"!=a.dataEncoding?"hex"==a.dataEncoding?i=a.data:f(9271,O("invalid jres encoding '{0}' on '{1}'",a.dataEncoding,a.id)):i=t.U.toHex(t.U.stringToUint8Array(e.pxtc.decodeBase64(a.data)))}if(/^e[14]/i.test(i)&&n.parent&&n.parent.kind==t.SK.CallExpression&&"image.ofBuffer"==n.parent.expression.getText()){const e=/^e([14])(..)(..)..(.*)/i.exec(i);i=`870${e[1]}${e[2]}00${e[3]}000000${e[4]}`}let o="";for(let e=0;e<i.length;++e){let t=i[e];if(!s(t)){if(/^[\s\.]$/.test(t))continue;throw Ne(n,O("invalid character in hex literal '{0}'",t),9265)}s(i[e+1])&&(o+=t+i[e+1],e++)}if(t.target.isNative){const e=be.emitHexLiteral(o.toLowerCase());return t.ir.ptrlit(e,e)}{const e="_hex"+_e(n);return t.ir.ptrlit(e,{hexlit:o.toLowerCase()})}}(n,i(n.template.text))}if(u(n).callInfo=l,n.template.kind!=t.SK.NoSubstitutionTemplateLiteral)throw Ne(n,O("substitution not supported in hex literal",o.shim),9265);switch(o.shim){case"@hex":c((e=>e));break;case"@f4":c((function(e){if(!Array.isArray(o.groups))throw Ne(n,O("missing groups in @f4 literal"),9272);let r=[],s=[],i={},a=0;o.groups.forEach(((e,t)=>{for(let n of e)i[n]=t})),e+="\n";for(let l=0;l<e.length;++l){let c=e[l];switch(c){case" ":case"\t":break;case"\n":s.length>0&&(r.push(s),a=Math.max(s.length,a),s=[]);break;default:let e=t.U.lookup(i,c);if(null==e){if(2!=o.groups.length)throw Ne(n,O("invalid character in image literal: '{0}'",e),9273);e=1}s.push(e)}}let l=8;return o.groups.length<=2?l=1:o.groups.length<=16&&(l=4),t.f4EncodeImg(a,r.length,l,((e,t)=>r[t][e]||0))}));break;default:if(void 0===o.shim&&o.helper)return function(n,r){var s;let i,a=L.getSymbolsInScope(n,e.SymbolFlags.Module);for(let e of a)if("helpers"==e.name)for(let n of e.declarations||[e.valueDeclaration])if(n.kind==t.SK.ModuleDeclaration)for(let e of n.body.statements)(null===(s=e.symbol)||void 0===s?void 0:s.name)==r.helper&&(i=e);i||f(9215,O("helpers.{0} not found",r.helper));i.kind!=t.SK.FunctionDeclaration&&f(9216,O("helpers.{0} isn't a function",r.helper));const o=i;return st(o),gt(o,n,[Je(n.text)])}(n.template,o);throw Ne(n,O("invalid shim '{0}' on tagged template",o.shim),9265)}return o.helper&&(a=t.ir.rtcall(o.helper,[a])),a}function kt(e){let n=e.parameters.slice(0);if(!T(e)&&v(e)){let r=Ae(e);r.thisParameter||(r.thisParameter={kind:t.SK.Parameter,name:{text:"this"},isThisParameter:!0,parent:e}),n.unshift(r.thisParameter)}return n}function St(e,n=!1){let r=oe(e);return t.ir.ptrlit(r+"_Lit",r)}function Tt(){for(ge=ht(Se);A.length>0;){Sn(A.pop())}}function It(){const e=ce;if(e.length>0){ce=[];for(let t of e){const e=ge;try{Et(t)}finally{ge=e}}}}function wt(e){be.finalPass&&e.functionsToDefine&&t.U.pushRange(ce,e.functionsToDefine)}function Et(e){const n=Ae(e);let r=null;if(be.finalPass){if(n.alreadyEmitted)return t.U.assert(n.usedBeforeDecl),null;n.alreadyEmitted=!0}let s=e.kind==t.SK.ArrowFunction||e.kind==t.SK.FunctionExpression,i=n.capturedVars.slice(0),o=i.map(((e,n)=>{let r=new t.ir.Cell(n,e,Ke(e));return r.iscap=!0,r}));void 0===n.usedBeforeDecl&&(n.usedBeforeDecl=!1),i.length>0?(t.assert(null!=_(e),"getEnclosingFunction(node) != null)"),r=t.ir.shared(t.ir.rtcall("pxt::mkAction",[t.ir.numlit(i.length),St(e,!0)])),n.usedAsValue=!0,i.forEach(((e,n)=>{let s=ge.localIndex(e);s||f(9223,O("cannot find captured value: {0}",L.symbolToString(e.symbol)));let i=s.loadCore();ge.emitExpr(t.ir.rtcall("pxtrt::stclo",[r,t.ir.numlit(n),i]))})),e.kind==t.SK.FunctionDeclaration&&(n.location=ge.mkLocal(e,Ke(e)),ge.emitExpr(n.location.storeDirect(r)),r=null)):s&&(r=St(e),n.usedAsValue=!0),t.assert(!!r==s,"!!lit == isExpression");let l=ht(e);if(l)ge=l,ge.reset();else{t.assert(!be.finalPass,"!bin.finalPass");const r=u(e),s=new t.ir.Procedure;s.isRoot=!!(1&r.flags),s.action=e,s.info=n,r.proc=s,s.usingCtx=re,ge=s,function(e,t,n,r){he(e,n,r,(e=>e.addProc(t)))}(be,s,se,re)}ge.captured=o;const c=[];if(e.parent.kind==t.SK.ClassDeclaration){let n=Re(null,e.parent);if(ge.classInfo?t.assert(ge.classInfo==n,"proc.classInfo == classInfo"):ge.classInfo=n,e.kind==t.SK.Constructor){if(n.baseClassInfo)for(let e of n.baseClassInfo.decl.members)e.kind==t.SK.Constructor&&st(e);n.ctor?t.assert(n.ctor==ge,"classInfo.ctor == proc"):n.ctor=ge;for(let e of n.allfields)if(e.kind==t.SK.PropertyDeclaration&&!T(e)){let t=e;t.initializer&&c.push(t)}}}const p=[],d=[];ge.args=kt(e).map(((n,r)=>{n.name.kind===t.SK.ObjectBindingPattern&&p.push(n),e.kind==t.SK.Constructor&&fe(n)&&d.push(n);let s=new t.ir.Cell(r,n,Ke(n));return wt(s.info),s.isarg=!0,s})),ge.args.forEach((e=>{if(e.isByRefLocal()){let n=t.ir.shared(t.ir.rtcall("pxtrt::mklocRef",[]));ge.emitExpr(t.ir.rtcall("pxtrt::stlocRef",[n,e.loadCore()],1)),ge.emitExpr(e.storeDirect(n))}})),p.forEach((e=>hn(e)));for(let e of d){let r=Lt(ge.classInfo,Ft(ge.classInfo,V(e)),!1),s=t.ir.op(a.FieldAccess,[je(n.thisParameter)],r);ge.emitExpr(t.ir.op(a.Store,[s,je(e)]))}for(let e of c){let r=Lt(ge.classInfo,Ft(ge.classInfo,V(e)),!1),s=t.ir.op(a.FieldAccess,[je(n.thisParameter)],r);ge.emitExpr(t.ir.op(a.Store,[s,yn(e.initializer)]))}if(It(),e.body.kind==t.SK.Block){if(Tn(e.body),ne(ge.action)){const n=ge.body[ge.body.length-1];n&&n.stmtKind==t.ir.SK.Jmp&&n.jmpMode==t.ir.JmpMode.Always||ge.emitJmp(an(e).ret,Qt(void 0),t.ir.JmpMode.Always)}}else{let n=yn(e.body);ge.emitJmp(an(e).ret,n,t.ir.JmpMode.Always)}ge.emitLblDirect(an(e).ret),ge.stackEmpty();let m=ge.mkLabel("final");if(ne(ge.action)?ge.emitJmp(m):ge.emitJmp(m,Qt(void 0)),ge.emitLbl(m),n.capturedVars.length&&n.usedBeforeDecl&&e.kind==t.SK.FunctionDeclaration&&!be.finalPass){n.capturedVars.sort(((e,t)=>t.pos-e.pos));const t=Ke(n.capturedVars[0]);t.functionsToDefine||(t.functionsToDefine=[]),t.functionsToDefine.push(e)}return t.assert(!be.finalPass||0==A.length,"!bin.finalPass || usedWorkList.length == 0"),r}function $t(e){let n=t.ir.shared(e);return ge.emitExpr(n),n}function vt(){return $t(t.ir.op(a.JmpValue,[]))}function Nt(e){if(r.target.isNative)return!1;let n=e;return n.body&&(n.body.kind!=t.SK.Block||n.body.statements.length>0)}function _t(n){if(!nt(n))return;if(32&u(n).flags)return;let s=z(n);if(null!=s.shim){if("@"==s.shim[0])return;if(r.target.isNative&&t.hexfile.validateShim(ie(n),s.shim,s,ne(n),kt(n).map((e=>me(ee(e))))),!Nt(n))return}if(e.isInAmbientContext(n))return;if(!n.body)return;let i=null,a=ge;try{i=Et(n)}finally{ge=a}return i}function At(){}function Kt(e){let t=e;t.needsIRCache=!0,q.push(t)}function Ct(e,n=null){let r=q.length;return e.kind!=t.SK.PropertyAccessExpression&&e.kind!=t.SK.ElementAccessExpression||Kt(e.expression),n&&Kt(n),q.length==r?At:()=>{for(let e=r;e<q.length;++e)q[e].cachedIR=null,q[e].needsIRCache=!1;q.splice(r,q.length-r)}}function Ut(e,n=!1){let r={kind:t.SK.NullKeyword,isRefOverride:n};return u(r).valueOverride=e,r}function Pt(e,n,r,s=null){let i=Ct(e),a=s?yn(s):Qt(1),o=t.ir.shared(yn(e)),l=t.ir.shared(Dt(n,o,a));return Mt(e,Ut(l,!0)),i(),r?o:l}function Lt(e,n,r=!0){T(n)&&t.U.oops("fieldIndex on static field: "+V(n));let s=z(n),i=e.allfields.indexOf(n);return i<0&&be.finalPass&&t.U.oops("missing field"),{idx:i,name:V(n),isRef:!0,shimName:s.shim,classInfo:e,needsCheck:r}}function Ft(e,t){const n=e.allfields.filter((e=>e.name.text==t))[0];return n||f(9224,O("field {0} not found",t)),n}function Mt(n,r,s=!1){let i=ot(n),o=C(i);if(n.kind==t.SK.Identifier||o)if(i&&(o||K(i)||U(i))){let e=Fe(i);Ce(i,!0),ge.emitExpr(e.storeByRef(yn(r)))}else Ne(n,O("bad target identifier"),9248);else if(n.kind==t.SK.PropertyAccessExpression){let s=ot(n);if(!s||s.kind!=t.SK.GetAccessor&&s.kind!=t.SK.SetAccessor)if(s&&(s.kind==t.SK.PropertySignature||s.kind==t.SK.PropertyAssignment||Xe(s)))ge.emitExpr(dt(n,n,[r],null,s));else{let e=yn(n);ge.emitExpr(t.ir.op(a.Store,[e,yn(r)]))}else Ze(s),s=e.getDeclarationOfKind(s.symbol,t.SK.SetAccessor),s||Ne(n,O("setter not available"),9253),ge.emitExpr(dt(n,n,[r],null,s))}else if(n.kind==t.SK.ElementAccessExpression)ge.emitExpr(et(n,r));else if(n.kind==t.SK.ArrayLiteralExpression)if(r.kind==t.SK.ArrayLiteralExpression){const e=r.elements.map((e=>{const n=t.ir.shared(yn(e));return ge.emitExpr(n),n}));n.elements.forEach(((t,n)=>{Mt(t,Ut(e[n]))}))}else{const e=t.ir.shared(yn(r));n.elements.forEach(((n,r)=>{Mt(n,Ut(Yt("Array_::getAt",[e,t.ir.numlit(r)])))}))}else Ne(n,O("bad assignment target"),9249)}function Ot(e){if(g())switch(e){case"numops::adds":case"numops::subs":case"numops::eors":case"numops::ands":case"numops::orrs":return"@nomask@"+e}if(m())switch(e){case"pxt::switch_eq":return"numops::eq"}return e}function Dt(e,t,n){return Yt(Ot(e),[t,n])}function Bt(e){if(e.kind==t.SK.Identifier)return e.text;if(e.kind==t.SK.PropertyAccessExpression){const t=e,n=Bt(t.expression);if(n)return n+"."+t.name.text}return null}function Rt(e,t){if(!t)return null;const n=t.val;switch(Bt(e)){case"Math.floor":return{val:Math.floor(n)};case"Math.ceil":return{val:Math.ceil(n)};case"Math.round":return{val:Math.round(n)}}return null}function qt(n){if(!n)return null;const r=u(n);if(void 0!==r.constantFolded)return r.constantFolded;if(K(n)&&n.parent.flags&e.NodeFlags.Const){const e=n;e.initializer&&(r.constantFolded=jt(e.initializer))}else if(n.kind==t.SK.EnumMember){const e=n,s=function(e){let n=z(e).enumval;if(!n){let t=L.getConstantValue(e);if(null==t)return null;n=t+""}return/^[+-]?\d+$/.test(n)||/^0x[A-Fa-f\d]{2,8}$/.test(n)?n:(t.U.userError("enumval only support number literals"),"0")}(e);if(null==s)r.constantFolded=jt(e.initializer);else{const e=parseInt(s);isNaN(e)||(r.constantFolded={val:e})}}else if(n.kind==t.SK.PropertyDeclaration&&T(n)&&I(n)){const e=n;r.constantFolded=jt(e.initializer)}return r.constantFolded}function jt(e){if(!e)return null;const n=u(e);if(void 0===n.constantFolded){n.constantFolded=null;const r=function(e){if(!e)return null;switch(e.kind){case t.SK.PrefixUnaryExpression:{const n=e,r=jt(n.operand);return function(e,n){if(!n)return null;const r=n.val;switch(e){case t.SK.PlusToken:return{val:+r};case t.SK.MinusToken:return{val:-r};case t.SK.TildeToken:return{val:~r};case t.SK.ExclamationToken:return{val:!r};default:return null}}(n.operator,r)}case t.SK.BinaryExpression:{const n=e,r=jt(n.left);if(!r)return null;const s=jt(n.right);return s?function(e,n,r){if(!n||!r)return null;const s=n.val,i=r.val;switch(e){case t.SK.PlusToken:return{val:s+i};case t.SK.MinusToken:return{val:s-i};case t.SK.SlashToken:return{val:s/i};case t.SK.PercentToken:return{val:s%i};case t.SK.AsteriskToken:return{val:s*i};case t.SK.AsteriskAsteriskToken:return{val:s**i};case t.SK.AmpersandToken:return{val:s&i};case t.SK.BarToken:return{val:s|i};case t.SK.CaretToken:return{val:s^i};case t.SK.LessThanLessThanToken:return{val:s<<i};case t.SK.GreaterThanGreaterThanToken:return{val:s>>i};case t.SK.GreaterThanGreaterThanGreaterThanToken:return{val:s>>>i};case t.SK.LessThanEqualsToken:return{val:s<=i};case t.SK.LessThanToken:return{val:s<i};case t.SK.GreaterThanEqualsToken:return{val:s>=i};case t.SK.GreaterThanToken:return{val:s>i};case t.SK.EqualsEqualsToken:return{val:s==i};case t.SK.EqualsEqualsEqualsToken:return{val:s===i};case t.SK.ExclamationEqualsEqualsToken:return{val:s!==i};case t.SK.ExclamationEqualsToken:return{val:s!=i};case t.SK.BarBarToken:return{val:s||i};case t.SK.AmpersandAmpersandToken:return{val:s&&i};default:return null}}(n.operatorToken.kind,r,s):null}case t.SK.NumericLiteral:{const t=parseFloat(e.text);return isNaN(t)?null:{val:t}}case t.SK.NullKeyword:return{val:null};case t.SK.TrueKeyword:return{val:!0};case t.SK.FalseKeyword:return{val:!1};case t.SK.UndefinedKeyword:return{val:void 0};case t.SK.CallExpression:{const t=e;return 1==t.arguments.length?Rt(t.expression,jt(t.arguments[0])):null}case t.SK.PropertyAccessExpression:case t.SK.Identifier:return qt(at(e));case t.SK.AsExpression:return jt(e.expression);default:return null}}(e);n.constantFolded=r}return n.constantFolded}function zt(e){let n=t.target.switches.boxDebug,r=null;if(n)try{t.target.switches.boxDebug=!1,r=yn(e)}finally{t.target.switches.boxDebug=n}else r=yn(e);let s=Jt(r);if(void 0===s)throw f(9267,O("a constant number-like expression is required here"));return s}function Vt(e,t){let n=Gt(e,t,"userconfig");return null==n&&(n=Gt(e,t,"config")),n}function Gt(n,r,s){let i=L.getSymbolsInScope(n,e.SymbolFlags.Module).filter((e=>e.name==s&&!!e.valueDeclaration))[0];if(!i)return null;for(let e of i.valueDeclaration.body.statements)if(e.kind==t.SK.VariableStatement){let t=e;for(let e of t.declarationList.declarations)if(e.symbol.name==r)return zt(e.initializer)}return null}function Ht(t,n){let r=L.getSymbolsInScope(t,e.SymbolFlags.Enum).filter((e=>"DAL"==e.name&&!!e.valueDeclaration))[0];if(!r)return null;let s=r.valueDeclaration.members.filter((e=>e.symbol.name==n))[0];return s?L.getConstantValue(s):null}function Jt(e){if(e.exprKind==t.ir.EK.NumberLiteral){let n=e.data;if(r.target.isNative&&!m()){if(n==t.taggedNull||n==t.taggedUndefined||n==t.taggedFalse)return 0;if(n==t.taggedTrue)return 1;if("number"==typeof n)return n>>1}else if("number"==typeof n)return n}else if(e.exprKind==t.ir.EK.RuntimeCall&&2==e.args.length){let t=Jt(e.args[0]),n=Jt(e.args[1]);if(void 0===t||void 0===n)return;switch(e.data){case"numops::orrs":return t|n;case"numops::adds":return t+n;default:return void console.log(e)}}}function Qt(e){if(r.target.isNative&&!m()){const r=X(e);if(null!=r)return t.ir.numlit(r);if("number"==typeof e){if(n=e,!t.target.switches.boxDebug&&(0|n)==n&&-1073741824<=n&&n<=1073741823)return t.ir.numlit(e<<1|1);{let n=be.emitDouble(e);return t.ir.ptrlit(n,JSON.stringify(e))}}throw t.U.oops("bad literal: "+e)}return t.ir.numlit(e);var n}function Wt(e){if(e.kind==t.SK.NullKeyword){let t=u(e).valueOverride;if(null!=t)return t.exprKind==a.NumberLiteral?!r.target.isNative||!!(1&t.data):t.exprKind==a.RuntimeCall&&"pxt::ptrOfLiteral"==t.data?t.args[0].exprKind==a.PointerLiteral&&!isNaN(parseFloat(t.args[0].jsInfo)):t.exprKind==a.PointerLiteral&&!isNaN(parseFloat(t.jsInfo))}return e.kind==t.SK.NumericLiteral||me(ee(e))}function Yt(e,n){return t.ir.rtcallMask(e,(1<<n.length)-1,0,n)}function Zt(e,n,s,o=null){let l=[],c=t.hexfile.lookupFunc(e);if(g()){let n=t.U.lookup(i,e);n&&(c=n,e=n.name)}c&&(l=c.argsFmt),o&&(n=n.concat(o));let u=ct(n),p=[],d=n.map(((n,r)=>{let i=yn(n);if(!h())return i;let o=l[r+1],c=Wt(n);if(!o&&e.indexOf("::")<0&&(o=c?"I":"_"),o){if("_"==o[0]||"T"==o||"N"==o){let e=function(e){switch(e){case"_Buffer":return pxt.BuiltInType.BoxedBuffer;case"_Image":return t.target.imageRefTag||pxt.BuiltInType.RefImage;case"_Action":return pxt.BuiltInType.RefAction;case"_RefCollection":return pxt.BuiltInType.RefCollection;default:return null}}(o);return e&&p.push({argIdx:r,method:"_validate",refTag:e,refTagNullable:!!s.argsNullable}),i}if("I"==o)return i.exprKind==a.NumberLiteral&&"number"==typeof i.data?t.ir.numlit(i.data>>1):(p.push({argIdx:r,method:"pxt::toInt"}),i);if("B"==o)return u&=~(1<<r),sn(n,i);if("S"==o)return i.isStringLiteral||(p.push({argIdx:r,method:"_pxt_stringConv",returnsRef:!0}),u|=1<<r),i;if("F"==o||"D"==o)return"D"==o&&t.U.oops("double arguments not yet supported"),c||t.U.userError("argsFmt=...F/D... but argument not a number in "+e),p.push({argIdx:r,method:"D"==o?"pxt::toDouble":"pxt::toFloat"}),i;throw t.U.oops("invalid format specifier: "+o)}throw t.U.userError("not enough args for "+e)})),f=t.ir.rtcallMask(e,u,s?s.callingConvention:0,d);if(f.mask||(f.mask={refMask:0}),f.mask.conversions=p,r.target.isNative){let e=l[0];"I"==e?f=b(f):"B"==e?f=x(f):"F"==e?(m=f,f=h()?t.ir.rtcall("pxt::fromFloat",[m]):m):"D"==e&&(t.U.oops("double returns not yet supported"),f=function(e){return h()?t.ir.rtcall("pxt::fromDouble",[e]):e}(f))}var m;return f}function Xt(n){be.numStmts++;const i=t.assembler.debug||t.target.switches.size||t.target.sourceMap;let a=!!r.breakpoints;if(!i&&!a)return;const o=e.getSourceFileOfNode(n);if(r.justMyCode&&c(o)&&(a=!1),!i&&!a)return;let l=n.pos;for(;/^\s$/.exec(o.text[l]);)l++;for(;"/"==o.text[l]&&"/"==o.text[l+1];){for(;o.text[l]&&"\n"!=o.text[l];)l++;l++}const u=e.getLineAndCharacterOfPosition(o,l);if(i){let e=n.end;e-l>80&&(e=l+80);const r=o.text.slice(l,e).trim().replace(/\n[^]*/,"...");ge.emit(t.ir.comment(`${o.fileName.replace(/pxt_modules\//,"")}(${u.line+1},${u.character+1}): ${r}`))}if(!a)return;const p=e.getLineAndCharacterOfPosition(o,n.end),d={id:s.breakpoints.length,isDebuggerStmt:n.kind==t.SK.DebuggerStatement,fileName:o.fileName,start:l,length:n.end-l,line:u.line,endLine:p.line,column:u.character,endColumn:p.character};s.breakpoints.push(d);const f=t.ir.stmt(t.ir.SK.Breakpoint,null);f.breakpointInfo=d,ge.emit(f)}function en(e,n){switch(n){case t.SK.PlusToken:return"numops::adds";case t.SK.MinusToken:return"numops::subs";case t.SK.SlashToken:return"numops::div";case t.SK.PercentToken:return"numops::mod";case t.SK.AsteriskToken:return"numops::muls";case t.SK.AsteriskAsteriskToken:return"Math_::pow";case t.SK.AmpersandToken:return"numops::ands";case t.SK.BarToken:return"numops::orrs";case t.SK.CaretToken:return"numops::eors";case t.SK.LessThanLessThanToken:return"numops::lsls";case t.SK.GreaterThanGreaterThanToken:return"numops::asrs";case t.SK.GreaterThanGreaterThanGreaterThanToken:return"numops::lsrs";case t.SK.LessThanEqualsToken:return"numops::le";case t.SK.LessThanToken:return"numops::lt";case t.SK.GreaterThanEqualsToken:return"numops::ge";case t.SK.GreaterThanToken:return"numops::gt";case t.SK.EqualsEqualsToken:return"numops::eq";case t.SK.EqualsEqualsEqualsToken:return"numops::eqq";case t.SK.ExclamationEqualsEqualsToken:return"numops::neqq";case t.SK.ExclamationEqualsToken:return"numops::neq";default:return null}}function tn(e){if(e.operatorToken.kind==t.SK.EqualsToken)return function(e){let n=e.right;e.parent.kind==t.SK.ExpressionStatement&&(n=null);let r=Ct(e.left,n);Mt(e.left,e.right,!0);let s=n?yn(n):Qt(void 0);return r(),s}(e);const n=jt(e);if(n)return Qt(n.val);let r=null,s=null;e.operatorToken.kind!=t.SK.PlusToken&&e.operatorToken.kind!=t.SK.PlusEqualsToken||(r=ee(e.left),s=ee(e.right),(ue(r)||ue(s)&&e.operatorToken.kind==t.SK.PlusToken)&&(u(e).exprInfo={leftType:L.typeToString(r),rightType:L.typeToString(s)}));if(e.operatorToken.kind==t.SK.CommaToken){if(on(e.left))return yn(e.right);{let n=ln(e.left);return t.ir.op(a.Sequence,[n,yn(e.right)])}}switch(e.operatorToken.kind){case t.SK.BarBarToken:case t.SK.AmpersandAmpersandToken:return function(e){let n=yn(e.left),r=(ue(ee(e.left)),ge.mkLabel("lazy"));n=t.ir.shared(n);let s=t.ir.rtcall("numops::toBool",[n]),i=ge.mkLabel("lazySkip"),a=e.operatorToken.kind==t.SK.BarBarToken?t.ir.JmpMode.IfZero:e.operatorToken.kind==t.SK.AmpersandAmpersandToken?t.ir.JmpMode.IfNotZero:t.U.oops();return ge.emitJmp(i,s,a),ge.emitJmp(r,n,t.ir.JmpMode.Always,n),ge.emitLbl(i),ge.emitExpr(Yt("langsupp::ignore",[n])),ge.emitJmp(r,yn(e.right),t.ir.JmpMode.Always),ge.emitLbl(r),vt()}(e);case t.SK.InstanceOfKeyword:return function(e){let n=ee(e.right),r=W(n)?ot(e.right):null;r&&r.kind==t.SK.ClassDeclaration||f(9275,O("unsupported instanceof expression"));let s=Re(n,r);xt(s);let i=t.ir.op(t.ir.EK.InstanceOf,[yn(e.left)],s);return i.jsInfo="bool",i}(e)}if(e.operatorToken.kind==t.SK.PlusToken&&(ue(r)||ue(s)))return Zt("String_::concat",[Qe(e.left),Qe(e.right)],null);if(e.operatorToken.kind==t.SK.PlusEqualsToken&&ue(r)){let n=Ct(e.left),r=t.ir.shared(Zt("String_::concat",[Qe(e.left),Qe(e.right)],null));return Mt(e.left,Ut(r)),n(),r}let i=function(e){switch(e){case t.SK.PlusEqualsToken:return t.SK.PlusToken;case t.SK.MinusEqualsToken:return t.SK.MinusToken;case t.SK.AsteriskEqualsToken:return t.SK.AsteriskToken;case t.SK.AsteriskAsteriskEqualsToken:return t.SK.AsteriskAsteriskToken;case t.SK.SlashEqualsToken:return t.SK.SlashToken;case t.SK.PercentEqualsToken:return t.SK.PercentToken;case t.SK.LessThanLessThanEqualsToken:return t.SK.LessThanLessThanToken;case t.SK.GreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanToken;case t.SK.GreaterThanGreaterThanGreaterThanEqualsToken:return t.SK.GreaterThanGreaterThanGreaterThanToken;case t.SK.AmpersandEqualsToken:return t.SK.AmpersandToken;case t.SK.BarEqualsToken:return t.SK.BarToken;case t.SK.CaretEqualsToken:return t.SK.CaretToken;default:return t.SK.Unknown}}(e.operatorToken.kind),o=en(0,i||e.operatorToken.kind);return o||Ne(e.operatorToken,O("unsupported operator"),9250),i?Pt(e.left,o,!1,e.right):(n=>{n=Ot(n);let r=[e.left,e.right];return t.ir.rtcallMask(n,ct(r),0,r.map((e=>yn(e))))})(o)}function nn(e){e.statements.forEach(Tn)}function rn(t){if(t.flags&e.NodeFlags.Let||t.flags&e.NodeFlags.Const)return!0;throw f(9260,O("variable needs to be defined using 'let' instead of 'var'"))}function sn(e,n=null){if(!n&&g()&&e.kind==t.SK.BinaryExpression){let n=e,r=t.U.lookup(t.thumbCmpMap,en(0,n.operatorToken.kind));if(r)return t.ir.rtcall(r,[yn(n.left),yn(n.right)])}return n||(n=yn(e)),m()?n:t.ir.rtcall("numops::toBoolDecr",[n])}function an(e){let t=p(e);return{fortop:".fortop."+t,cont:".cont."+t,brk:".brk."+t,ret:".ret."+t}}function on(e){if(!e)return!0;switch(e.kind){case t.SK.Identifier:case t.SK.StringLiteral:case t.SK.NumericLiteral:case t.SK.NullKeyword:return!0}return!1}function ln(e){return yn(e)}function cn(e){if(on(e))return;Xt(e);let t=ln(e);ge.emitExpr(t),ge.stackEmpty()}function un(e=1){for(;e--;)ge.emitExpr(Yt("pxt::endTry",[]))}function pn(){f(9282,O("jumps (return, break, continue) through finally blocks not supported yet"))}function dn(t){let n=0;if(t.kind==e.SyntaxKind.Block&&t.parent)if(t.parent.kind==e.SyntaxKind.CatchClause){t.parent.parent.finallyBlock&&(n++,pn())}else if(t.parent.kind==e.SyntaxKind.TryStatement){const e=t.parent;e.tryBlock==t&&(e.catchClause&&n++,e.finallyBlock&&(n++,pn()))}return n}function fn(e){switch(e.kind){case t.SK.WhileStatement:case t.SK.ForInStatement:case t.SK.ForOfStatement:case t.SK.ForStatement:case t.SK.DoStatement:return!0;default:return!1}}function mn(e,n,s){if(e.name.kind===t.SK.ObjectBindingPattern||e.name.kind==t.SK.ArrayBindingPattern)return n||(n=e.initializer?t.ir.shared(yn(e.initializer)):je(e),s=e.initializer?ee(e.initializer):ee(e)),e.name.elements.forEach((e=>mn(e,n,s))),ge.stackEmpty(),null;if(!nt(e))return null;if(qt(e))return null;let i;if(C(e)?(Le(e),i=Fe(e)):i=ge.mkLocal(e,Ke(e)),wt(i.info),i.isByRefLocal()&&ge.emitExpr(i.storeDirect(t.ir.rtcall("pxtrt::mklocRef",[]))),Pe(ee(e)),e.kind===t.SK.BindingElement){Xt(e);let[t,r]=gn(e,n,s);ge.emitExpr(i.storeByRef(t))}else if(e.initializer){if(Xt(e),C(e)){let n=z(e).jres;if(n){"true"==n&&(n=R(L,e));let s=t.U.lookup(r.jres||{},n);s?te=s:f(9270,O("resource '{0}' not found in any .jres file",n))}}e.initializer,ge.emitExpr(i.storeByRef(yn(e.initializer))),te=null,ge.stackEmpty()}else(function(e){for(;e;){if(fn(e))return!0;e=e.parent}return!1})(e)&&(Xt(e),ge.emitExpr(i.storeByRef(Qt(void 0))),ge.stackEmpty());return i}function hn(e){return mn(e,null,null)}function gn(e,n,r){const s=e.parent.parent;if(s.kind===t.SK.BindingElement){const e=gn(s,n,r);n=e[0],r=e[1]}if(e.parent.kind==t.SK.ArrayBindingPattern){const s=e.parent.elements.indexOf(e);e.dotDotDotToken&&f(9203,O("spread operator not supported yet"));const i=Y(r,s);return[Yt("Array_::getAt",[n,t.ir.numlit(s)]),i]}return function(e,n,r,s){const i=L.getPropertyOfType(r,s);t.U.assert(!!i,"field sym");const o=L.getTypeOfSymbolAtLocation(i,e);let l;if(W(r)){const e=Re(r);l=t.ir.op(a.FieldAccess,[n],Lt(e,Ft(e,s)))}else l=mt([n],{ifaceIndex:Ue(s,!0),callLocationIndex:wn(e),noArgs:!0});return[l,o]}(e,n,r,(e.propertyName||e.name).text)}function bn(e){!function(e,n){const r=e=>{e&&e.kind==t.SK.ClassDeclaration&&f(9261,O("Interface with same name as a class not supported"))};if(r(n.symbol.valueDeclaration),n.symbol.declarations&&n.symbol.declarations.forEach(r),n.heritageClauses)for(let e of n.heritageClauses)switch(e.token){case t.SK.ExtendsKeyword:Q(ee(e.types[0]))&&f(9262,O("Extending a class by an interface not supported."))}}(0,e);let n=z(e);n.autoCreate&&(G[n.autoCreate]=!0)}function xn(e,t){let n=M;B++;try{M=null;let r=t(e);return M&&f(D,M),M=n,B--,r}catch(t){return B--,M=null,ve(e,t.ksErrorCode||9200,t.message),pxt.debug(t.stack),null}}function yn(e,n=!0){let r=e;if(n&&r.cachedIR)return r.cachedIR;let s=xn(r,kn)||Qt(void 0);return n&&r.needsIRCache?(r.cachedIR=t.ir.shared(s),r.cachedIR):s}function kn(n){let r=function(n){switch(n.kind){case t.SK.NullKeyword:let r=u(n).valueOverride;return r||Qt(null);case t.SK.TrueKeyword:return Qt(!0);case t.SK.FalseKeyword:return Qt(!1);case t.SK.TemplateHead:case t.SK.TemplateMiddle:case t.SK.TemplateTail:case t.SK.NumericLiteral:case t.SK.StringLiteral:case t.SK.NoSubstitutionTemplateLiteral:return function(e){if(e.kind==t.SK.NumericLiteral)return e.imageLiteral?t.ir.ptrlit(e.imageLiteral,e.jsLit):Qt(parseFloat(e.text));if(S(e))return Je(e.text);throw t.oops()}(n);case t.SK.TaggedTemplateExpression:return yt(n);case t.SK.PropertyAccessExpression:return Ye(n);case t.SK.BinaryExpression:return tn(n);case t.SK.PrefixUnaryExpression:return function(e){const n=jt(e);if(n)return Qt(n.val);switch(e.operator){case t.SK.ExclamationToken:return x(t.ir.rtcall("Boolean_::bang",[sn(e.operand)]));case t.SK.PlusPlusToken:return Pt(e.operand,"numops::adds",!1);case t.SK.MinusMinusToken:return Pt(e.operand,"numops::subs",!1);case t.SK.PlusToken:case t.SK.MinusToken:{let n=yn(e.operand),r=Jt(n);return null!=r?Qt(-r):e.operator==t.SK.MinusToken?Dt("numops::subs",Qt(0),n):Dt("numops::subs",n,Qt(0))}case t.SK.TildeToken:{let t=yn(e.operand),n=Jt(t);return null!=n?Qt(~n):Yt(Ot("numops::bnot"),[t])}default:throw Ne(e,O("unsupported prefix unary operation"),9245)}}(n);case t.SK.PostfixUnaryExpression:return function(e){if(pe(ee(e.operand)))switch(e.operator){case t.SK.PlusPlusToken:return Pt(e.operand,"numops::adds",!0);case t.SK.MinusMinusToken:return Pt(e.operand,"numops::subs",!0)}throw Ne(e,O("unsupported postfix unary operation"),9246)}(n);case t.SK.ElementAccessExpression:return et(n);case t.SK.ParenthesizedExpression:return function(e){return yn(e.expression)}(n);case t.SK.TypeAssertionExpression:return function(e){return e.expression,yn(e.expression)}(n);case t.SK.ArrayLiteralExpression:return function(e){Y(ee(e));let n=t.ir.shared(t.ir.rtcall("Array_::mk",[]));for(let r of e.elements){let e=lt(r)?2:0;ge.emitExpr(t.ir.rtcall("Array_::push",[n,yn(r)],e))}return n}(n);case t.SK.NewExpression:return function(e){let n=L.getTypeAtLocation(e);if(n&&H(n))throw t.oops();if(n&&W(n)){let n,r=ot(e.expression);r.kind!=t.SK.ClassDeclaration&&f(9221,O("new expression only supported on class types"));let s=Re(ee(e),r);for(let e=s;e&&(n=bt(e.decl),!n);e=e.baseClassInfo);xt(s);let i=s.id+"_VT",a=t.ir.rtcall("pxt::mkClassInstance",[t.ir.ptrlit(i,i)]);if(n){a=$t(a),rt(n);let r=(e.arguments||[]).slice(0),s=z(n);pt(L.getResolvedSignature(e),r,s);let i=r.map((e=>yn(e)));return s.shim?t.ir.rtcall(s.shim,i):(i.unshift(a),ge.emitExpr(gt(n,e,i)),a)}return e.arguments&&e.arguments.length&&f(9222,O("constructor with arguments not found")),a}throw Ne(e,O("unknown type for new"),9243)}(n);case t.SK.SuperKeyword:case t.SK.ThisKeyword:return He(n);case t.SK.CallExpression:return function(e){const t=L.getResolvedSignature(e);return dt(e,e.expression,e.arguments,t)}(n);case t.SK.FunctionExpression:case t.SK.ArrowFunction:return _t(n);case t.SK.Identifier:return Ge(n);case t.SK.ConditionalExpression:return function(e){let n=ge.mkLabel("condexprz"),r=ge.mkLabel("condexprfin");return ge.emitJmp(n,sn(e.condition),t.ir.JmpMode.IfZero),ge.emitJmp(r,yn(e.whenTrue),t.ir.JmpMode.Always),ge.emitLbl(n),ge.emitJmp(r,yn(e.whenFalse),t.ir.JmpMode.Always),ge.emitLbl(r),vt()}(n);case t.SK.AsExpression:return function(e){return e.expression,yn(e.expression)}(n);case t.SK.TemplateExpression:return We(n);case t.SK.ObjectLiteralExpression:return function(e){let n=t.ir.shared(t.ir.rtcall("pxtrt::mkMap",[]));return e.properties.forEach((e=>{let r,s;if(t.assert(!e.questionToken),e.kind==t.SK.ShorthandPropertyAssignment){const n=e;t.assert(!n.equalsToken&&!n.objectAssignmentInitializer),r=e.name.text;const i=L.getShorthandAssignmentValueSymbol(e),a=i&&i.valueDeclaration&&i.valueDeclaration.name;if(!a||a.kind!=t.SK.Identifier)throw Ne(e);s=Ge(a)}else{if(e.name.kind==t.SK.ComputedPropertyName){const t=e.name.expression;return void ge.emitExpr(Zt("pxtrt::mapSetByString",[Ut(n,!0),t,e.initializer],null))}r=e.name.kind==t.SK.StringLiteral?e.name.text:e.name.getText(),s=yn(e.initializer)}const i=t.target.isNative?t.ir.numlit(Ue(r)):t.ir.ptrlit(null,JSON.stringify(r)),a=[n,i,s];ge.emitExpr(t.ir.rtcall(t.target.isNative?"pxtrt::mapSet":"pxtrt::mapSetByString",a))})),n}(n);case t.SK.TypeOfExpression:return function(e){return Zt("pxt::typeOf",[e.expression],null)}(n);case e.SyntaxKind.DeleteExpression:return function(e){let n,r;if(e.expression.kind==t.SK.PropertyAccessExpression){const t=e.expression;n=t.expression,r=Ut(Je(t.name.text))}else{if(e.expression.kind!=t.SK.ElementAccessExpression)throw f(9276,O("expression not supported as argument to 'delete'"));{const t=e.expression;n=t.expression,r=t.argumentExpression}}const s=ee(n);if(Q(s))throw f(9277,O("'delete' not supported on class types"));if(H(s))throw f(9277,O("'delete' not supported on array"));return Zt("pxtrt::mapDeleteByString",[n,r],null)}(n);default:return Ne(n),null}}(n);if(r.isExpr())return r;throw new Error("expecting expression")}function Sn(n){const r=u(n);if(r.usedNodes){se=!1;for(let e of t.U.values(r.usedNodes))rt(e);for(let e of r.usedActions)e(be);se=!0}else C(n)||e.isClassDeclaration(n)?(se=!1,re=r,re.usedNodes=null,re.usedActions=null,C(n)&&!qt(n)&&Le(n),Tn(n),se=!0):(re=r,re.usedNodes={},re.usedActions=[],Tn(n),re=null)}function Tn(e){xn(e,In)}function In(n){switch(n.kind){case t.SK.SourceFile:return function(e){e.statements.forEach(Tn)}(n);case t.SK.InterfaceDeclaration:return bn(n);case t.SK.VariableStatement:return function(n){function r(e){let n=t.U.lookup(Z,e.name);if(n||(n=e,Z[e.name]=n),n.value!=e.value)throw f(9269,O("conflicting values for config.{0}",e.name))}if(n.declarationList.flags&e.NodeFlags.Const){let e=n.parent&&n.parent.kind==t.SK.ModuleBlock?V(n.parent.parent):"?";if("config"==e||"userconfig"==e)for(let t of n.declarationList.declarations){let s=ie(t);if(!t.initializer)continue;let i=zt(t.initializer),a=Ht(n,"CFG_"+s);if(null==a||0==a)throw f(9268,O("can't find DAL.CFG_{0}",s));"userconfig"==e&&(s="!"+s),r({name:s,key:a,value:i})}}e.isInAmbientContext(n)||(rn(n.declarationList),n.declarationList.declarations.forEach(Tn))}(n);case t.SK.ModuleDeclaration:return function(e){Tn(e.body)}(n);case t.SK.EnumDeclaration:return;case t.SK.FunctionDeclaration:case t.SK.Constructor:case t.SK.MethodDeclaration:return void _t(n);case t.SK.ExpressionStatement:return function(e){cn(e.expression)}(n);case t.SK.Block:case t.SK.ModuleBlock:return nn(n);case t.SK.VariableDeclaration:return hn(n),void It();case t.SK.IfStatement:return function(e){Xt(e);let t=ge.mkLabel("else");ge.emitJmpZ(t,sn(e.expression)),Tn(e.thenStatement);let n=ge.mkLabel("afterif");ge.emitJmp(n),ge.emitLbl(t),e.elseStatement&&Tn(e.elseStatement),ge.emitLbl(n)}(n);case t.SK.WhileStatement:return function(e){Xt(e);let t=an(e);ge.emitLblDirect(t.cont),Xt(e.expression),ge.emitJmpZ(t.brk,sn(e.expression)),Tn(e.statement),ge.emitJmp(t.cont),ge.emitLblDirect(t.brk)}(n);case t.SK.DoStatement:return function(e){Xt(e);let t=an(e);ge.emitLblDirect(t.cont),Tn(e.statement),Xt(e.expression),ge.emitJmpZ(t.brk,sn(e.expression)),ge.emitJmp(t.cont),ge.emitLblDirect(t.brk)}(n);case t.SK.ForStatement:return function(e){e.initializer&&e.initializer.kind==t.SK.VariableDeclarationList?(rn(e.initializer),e.initializer.declarations.forEach(Tn)):cn(e.initializer),Xt(e);let n=an(e);ge.emitLblDirect(n.fortop),e.condition&&(Xt(e.condition),ge.emitJmpZ(n.brk,sn(e.condition))),Tn(e.statement),ge.emitLblDirect(n.cont),cn(e.incrementor),ge.emitJmp(n.fortop),ge.emitLblDirect(n.brk)}(n);case t.SK.ForOfStatement:return function(e){if(!e.initializer||e.initializer.kind!=t.SK.VariableDeclarationList)return void Ne(e,"only a single variable may be used to iterate a collection");let n=e.initializer;if(1!=n.declarations.length)return void Ne(e,"only a single variable may be used to iterate a collection");rn(n);let r=ee(e.expression),s="",i="";if(ue(r))s="String_::charAt",i="String_::length";else{if(!H(r))return void Ne(e.expression,"cannot use for...of with this expression");s="Array_::getAt",i="Array_::length"}rt(n.declarations[0]);const a=hn(n.declarations[0]);t.U.assert(!!a||!be.finalPass),ge.stackEmpty();let o=ge.mkLocalUnnamed();ge.emitExpr(o.storeByRef(yn(e.expression)));let l=ge.mkLocalUnnamed();ge.emitExpr(l.storeByRef(Qt(0))),ge.stackEmpty(),Xt(e);let c=an(e);ge.emitLblDirect(c.fortop);let u=t.ir.rtcall(i,[o.loadCore()]),p=Dt("numops::lt_bool",l.load(),b(u));var d;ge.emitJmpZ(c.brk,p),a&&(ge.emitExpr(a.storeByRef(t.ir.rtcall(s,[o.loadCore(),(d=l.loadCore(),h()?t.ir.rtcall("pxt::toInt",[d]):d)]))),Xt(e.initializer)),It(),Tn(e.statement),ge.emitLblDirect(c.cont),ge.emitExpr(l.storeByRef(Dt("numops::adds",l.load(),Qt(1)))),ge.emitJmp(c.fortop),ge.emitLblDirect(c.brk),ge.emitExpr(o.storeByRef(Qt(void 0)))}(n);case t.SK.ContinueStatement:case t.SK.BreakStatement:return function(n){Xt(n);let r=n.label?n.label.text:null,s=n.kind==t.SK.BreakStatement,i=0,a=function n(a){return a?r&&a.kind==t.SK.LabeledStatement&&a.label.text==r?a.statement:a.kind==t.SK.SwitchStatement&&!r&&s||!r&&e.isIterationStatement(a,!1)?a:(i+=dn(a),n(a.parent)):null}(n);if(a){let r=an(a);un(i),n.kind==t.SK.ContinueStatement?e.isIterationStatement(a,!1)?ge.emitJmp(r.cont):ve(n,9231,O("continue on non-loop")):n.kind==t.SK.BreakStatement?ge.emitJmp(r.brk):t.oops()}else ve(n,9230,O("cannot find outer loop"))}(n);case t.SK.LabeledStatement:return function(e){let t=an(e.statement);Tn(e.statement),ge.emitLblDirect(t.brk)}(n);case t.SK.ReturnStatement:return function(e){Xt(e);let n=null;e.expression?n=yn(e.expression):ne(ge.action)&&(n=Qt(void 0));let r=0;for(let t=e;t&&t!=ge.action;t=t.parent)r+=dn(t);un(r),ge.emitJmp(an(ge.action).ret,n,t.ir.JmpMode.Always)}(n);case t.SK.ClassDeclaration:return function(e){const t=Re(null,e);t.isUsed&&be.usedClassInfos.indexOf(t)<0&&be.usedClassInfos.push(t),e.members.forEach(Tn)}(n);case t.SK.PropertyDeclaration:case t.SK.PropertyAssignment:return function(e){if(T(e))hn(e);else if(e.initializer){let t=Re(ee(e.parent));be.finalPass&&t.isUsed&&!t.ctor&&f(9209,O("class field initializers currently require an explicit constructor"))}}(n);case t.SK.SwitchStatement:return function(e){Xt(e);let n,r=an(e),s=t.ir.shared(yn(e.expression)),i=e.caseBlock.clauses.map((e=>{let r=ge.mkLabel("switch");if(e.kind==t.SK.CaseClause){let n=e,i=yn(n.expression),a=lt(n.expression)?1:0,o=t.ir.rtcallMask(Ot("pxt::switch_eq"),a,0,[i,s]);ge.emitJmp(r,o,t.ir.JmpMode.IfNotZero,s)}else e.kind==t.SK.DefaultClause?(t.assert(!n,"!defaultLabel"),n=r):t.oops();return r}));n?ge.emitJmp(n,s):ge.emitJmp(r.brk,s),e.caseBlock.clauses.forEach(((e,t)=>{ge.emitLbl(i[t]),e.statements.forEach(Tn)})),ge.emitLblDirect(r.brk)}(n);case t.SK.TypeAliasDeclaration:return;case e.SyntaxKind.TryStatement:return function(e){const n=e=>Yt("pxt::beginTry",[t.ir.ptrlit(e.lblName,e)]);Xt(e);const r=ge.mkLabel("catch");r.lblName="_catch_"+p(e);const s=ge.mkLabel("finally");if(s.lblName="_finally_"+p(e),e.finallyBlock&&ge.emitExpr(n(s)),e.catchClause&&ge.emitExpr(n(r)),ge.stackEmpty(),nn(e.tryBlock),ge.stackEmpty(),e.catchClause){const t=ge.mkLabel("catchend");un(),ge.emitJmp(t),ge.emitLbl(r);const n=e.catchClause.variableDeclaration;if(n){hn(n);const e=Fe(n);ge.emitExpr(e.storeByRef(Yt("pxt::getThrownValue",[])))}It(),nn(e.catchClause.block),ge.emitLbl(t)}e.finallyBlock&&(un(),ge.emitLbl(s),nn(e.finallyBlock),ge.emitExpr(Yt("pxt::endFinally",[])))}(n);case e.SyntaxKind.ThrowStatement:return function(e){Xt(e),ge.emitExpr(Yt("pxt::throwValue",[yn(e.expression)]))}(n);case t.SK.DebuggerStatement:return function(e){Xt(e)}(n);case t.SK.GetAccessor:case t.SK.SetAccessor:return function(e){_t(e)}(n);case t.SK.ImportEqualsDeclaration:case t.SK.EmptyStatement:case t.SK.SemicolonClassElement:return;default:Ne(n)}}function wn(e){return s.procCallLocations.push(t.nodeLocationInfo(e))-1}},t.isStringType=ue;class de{constructor(){this.procs=[],this.globals=[],this.finalPass=!1,this.writeFile=(e,t)=>{},this.usedClassInfos=[],this.numStmts=1,this.commSize=0,this.itEntries=0,this.itFullEntries=0,this.numMethods=0,this.numVirtMethods=0,this.usedChars=new Uint32Array(2048),this.explicitlyUsedIfaceMembers={},this.ifaceMemberMap={},this.strings={},this.hexlits={},this.doubles={},this.otherLiterals=[],this.codeHelpers={},this.lblNo=0}reset(){this.lblNo=0,this.otherLiterals=[],this.strings={},this.hexlits={},this.doubles={},this.numStmts=0}getTitle(){const e=this.name||t.U.lf("Untitled");return e.length>=90?e.slice(0,87)+"...":e}addProc(e){t.assert(!this.finalPass,"!this.finalPass"),this.procs.push(e),e.seqNo=this.procs.length}recordHelper(e,t,n){const r=e=>{e.codeHelpers[t]||(e.codeHelpers[t]=n(e))};r(this),this.recordAction(e,r)}recordAction(e,n){e?e.usedActions&&e.usedActions.push(n):t.U.oops("no using ctx!")}emitLabelled(e,n,r){let s=t.U.lookup(n,e);if(null!=s)return s;let i=r+this.lblNo++;return n[e]=i,i}emitDouble(e){return this.emitLabelled(t.target.switches.numFloat?function(e){let n=new Float32Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e):function(e){let n=new Float64Array(1);return n[0]=e,t.U.toHex(new Uint8Array(n.buffer))}(e),this.doubles,"_dbl")}emitString(e){if(!this.finalPass)for(let t=0;t<e.length;++t){const n=e.charCodeAt(t);n>=128&&(this.usedChars[n>>5]|=1<<(31&n))}return this.emitLabelled(e,this.strings,"_str")}emitHexLiteral(e){return this.emitLabelled(e,this.hexlits,"_hexlit")}setPerfCounters(e){if(!t.target.switches.profile)return[];const n=e.slice();return this.procs.forEach((e=>{e.perfCounterName&&(t.U.assert(t.target.switches.profile),e.perfCounterNo=n.length,n.push(e.perfCounterName))})),n}}function fe(e){if(!e.modifiers)return!1;if(e.parent.kind!=t.SK.Constructor)return!1;for(let n of e.modifiers)if(n.kind==t.SK.PrivateKeyword||n.kind==t.SK.PublicKeyword||n.kind==t.SK.ProtectedKeyword)return!0;return!1}function me(t){return t.flags&e.TypeFlags.Union?t.types.every((e=>me(e))):!!(t.flags&(e.TypeFlags.NumberLike|e.TypeFlags.EnumLike|e.TypeFlags.BooleanLike))}function he(e,t,n,r){const s=r(e);return t&&e.recordAction(n,r),s}t.Binary=de,t.isCtorField=fe}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(ts){var pxtc;(function(pxtc){function getTsCompilerOptions(e){let t=ts.getDefaultCompilerOptions();return t.target=ts.ScriptTarget.ES5,t.module=ts.ModuleKind.None,t.noImplicitAny=!0,t.noImplicitReturns=!0,t.allowUnreachableCode=!0,t}function nodeLocationInfo(e){let t=ts.getSourceFileOfNode(e);const n=e.getStart?e.getStart():e.pos,{line:r,character:s}=ts.getLineAndCharacterOfPosition(t,n),{line:i,character:a}=ts.getLineAndCharacterOfPosition(t,e.end);return{start:n,length:e.end-n,line:r,column:s,endLine:i,endColumn:a,fileName:t.fileName}}function patchUpDiagnostics(e,t=!1){t&&(e=e.filter((e=>5012!==e.code)));let n=e.filter((e=>1148==e.code));return n.length>0&&(e=n),e.map((e=>{if(!e.file){return{code:e.code,start:e.start,length:e.length,line:0,column:0,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:"?"}}const t=ts.getLineAndCharacterOfPosition(e.file,e.start);let n={code:e.code,start:e.start,length:e.length,line:t.line,column:t.character,messageText:ts.flattenDiagnosticMessageText(e.messageText,"\n"),category:e.category,fileName:e.file.fileName};return 1148==n.code&&(n.messageText=pxtc.Util.lf("all symbols in top-level scope are always exported; please use a namespace if you want to export only some")),n}))}function py2tsIfNecessary(e){if(e.target.preferredEditor==pxt.PYTHON_PROJECT_NAME){return pxtc.transpile.pyToTs(e)}}function mkCompileResult(){return{outfiles:{},diagnostics:[],success:!1,times:{}}}function storeGeneratedFiles(e,t){for(let n of e.generatedFiles||[])t.outfiles[n]=e.fileSystem[n]}function runConversionsAndStoreResults(e,t){const n=pxtc.U.cpuUs();t||(t=mkCompileResult());const r=py2tsIfNecessary(e);r&&(t=Object.assign(Object.assign({},t),{diagnostics:r.diagnostics,sourceMap:r.sourceMap,globalNames:r.globalNames})),storeGeneratedFiles(e,t),e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));const s=e.sourceFiles.indexOf(pxt.MAIN_TS);s>=0&&(e.sourceFiles.splice(s,1),e.sourceFiles.push(pxt.MAIN_TS));const i=e.sourceFiles.indexOf(pxt.TUTORIAL_CODE_STOP);return i>=0&&(e.sourceFiles.splice(i,1),e.sourceFiles.push(pxt.TUTORIAL_CODE_STOP)),t.times.conversions=pxtc.U.cpuUs()-n,t}function timesToMs(e){for(let t of Object.keys(e.times))e.times[t]=Math.round(e.times[t])/1e3}function buildProgram(e,t){let n={};for(let t in e.fileSystem)n[normalizePath(t)]=e.fileSystem[t];let r=getTsCompilerOptions(e),s={getSourceFile:(e,t,r)=>{e=normalizePath(e);let s="";return n.hasOwnProperty(e)?s=n[e]:r&&r("File not found: "+e),null==s&&(r("File not found: "+e),s=""),ts.createSourceFile(e,s,t,true)},fileExists:e=>(e=normalizePath(e),n.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,n,r,s)=>{t.outfiles[e]=n},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),n[e]||""),directoryExists:e=>!0,getDirectories:()=>[]},i=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts")));return ts.createProgram(i,r,s)}function isPxtModulesFilename(e){return pxtc.U.startsWith(e,"pxt_modules/")}function compile(opts,service){pxtc.compilerHooks||(pxtc.compilerHooks={},opts.target.compilerExtension&&eval(opts.target.compilerExtension)),pxtc.compilerHooks.init&&pxtc.compilerHooks.init(opts,service);let startTime=pxtc.U.cpuUs(),res=mkCompileResult(),program;if(service)storeGeneratedFiles(opts,res),program=service.getProgram();else{if(runConversionsAndStoreResults(opts,res),res.diagnostics.length>0)return res;program=buildProgram(opts,res)}const entryPoint=opts.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))).pop().replace(/.*\//,"");if(res.diagnostics=patchUpDiagnostics(program.getSyntacticDiagnostics(),opts.ignoreFileResolutionErrors),res.diagnostics.length>0)return opts.forceEmit&&(pxt.debug("syntactic errors, forcing emit"),pxtc.compileBinary(program,opts,res,entryPoint)),res;res.diagnostics=patchUpDiagnostics(program.getOptionsDiagnostics().concat(pxtc.Util.toArray(program.getGlobalDiagnostics())),opts.ignoreFileResolutionErrors);const semStart=pxtc.U.cpuUs();0==res.diagnostics.length&&(res.diagnostics=patchUpDiagnostics(program.getSemanticDiagnostics(),opts.ignoreFileResolutionErrors));const emitStart=pxtc.U.cpuUs();if(res.times["typescript-syn"]=semStart-startTime,res.times["typescript-sem"]=emitStart-semStart,res.times.typescript=emitStart-startTime,opts.ast&&(res.ast=program),opts.ast||opts.forceEmit||0==res.diagnostics.length){const e=pxtc.compileBinary(program,opts,res,entryPoint);res.times.compilebinary=pxtc.U.cpuUs()-emitStart,res.diagnostics=res.diagnostics.concat(patchUpDiagnostics(e.diagnostics))}0==res.diagnostics.length&&(res.success=!0);for(let e of opts.sourceFiles)pxtc.Util.startsWith(e,"built/")&&(res.outfiles[e.slice(6)]=opts.fileSystem[e]);return res.times.all=pxtc.U.cpuUs()-startTime,pxt.tickEvent("compile",res.times),res}function decompile(e,t,n,r=!1){let s=e.getSourceFile(n);pxtc.annotate(e,n,pxtc.target||pxt.appTarget&&pxt.appTarget.compile);const i=pxtc.getApiInfo(e,t.jres),a=pxtc.getBlocksInfo(i,t.bannedCategories),o={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:r,generateSourceMap:void 0!==t.generateSourceMap?t.generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks},[l,c]=pxtc.decompiler.buildRenameMap(e,s,{declarations:"variables",takenNames:{}});return pxtc.decompiler.decompileToBlocks(a,s,o,l)}function decompileSnippets(e,t,n=!1){const r=pxtc.getApiInfo(e,t.jres),s=pxtc.getBlocksInfo(r,t.bannedCategories),i=new pxtc.decompiler.RenameMap([]),a={snippetMode:t.snippetMode||!1,alwaysEmitOnStart:t.alwaysDecompileOnStart,includeGreyBlockMessages:n,generateSourceMap:void 0!==t.generateSourceMap?t.generateSourceMap:!!t.ast,allowedArgumentTypes:t.allowedArgumentTypes||["number","boolean","string"],errorOnGreyBlocks:!!t.errorOnGreyBlocks};let o;const l=[];if(t.sourceTexts)for(let e=0;e<t.sourceTexts.length;e++){t.fileSystem[pxt.MAIN_TS]=t.sourceTexts[e],t.fileSystem[pxt.MAIN_BLOCKS]="";let n=getTSProgram(t,o);const r=n.getSourceFile(pxt.MAIN_TS),c=pxtc.decompiler.decompileToBlocks(s,r,a,i);l.push(c.outfiles[pxt.MAIN_BLOCKS]),o=n}return l}function getTSProgram(e,t){let n={},r={};for(let t in e.fileSystem)r[normalizePath(t)]=e.fileSystem[t];let s=getTsCompilerOptions(e),i={getSourceFile:(e,t,n)=>{e=normalizePath(e);let s="";return r.hasOwnProperty(e)?s=r[e]:n&&n("File not found: "+e),null==s&&(n("File not found: "+e),s=""),ts.createSourceFile(e,s,t,true)},fileExists:e=>(e=normalizePath(e),r.hasOwnProperty(e)),getCanonicalFileName:e=>e,getDefaultLibFileName:()=>"no-default-lib.d.ts",writeFile:(e,t,r,s)=>{n[e]=t},getCurrentDirectory:()=>".",useCaseSensitiveFileNames:()=>!0,getNewLine:()=>"\n",readFile:e=>(e=normalizePath(e),r[e]||""),directoryExists:e=>!0,getDirectories:()=>[]};e.sourceFiles||(e.sourceFiles=Object.keys(e.fileSystem));let a=e.sourceFiles.filter((e=>pxtc.U.endsWith(e,".ts"))),o=a.filter((e=>e!=pxt.MAIN_TS)),l=!1;a.length>o.length&&(a=o,a.push(pxt.MAIN_TS),l=!0);const c=a.indexOf(pxt.TUTORIAL_CODE_STOP);c>=0&&(a.splice(c,1),a.push(pxt.TUTORIAL_CODE_STOP));const u=ts.createProgram(a,s,i,t);return pxtc.annotate(u,pxt.MAIN_TS,pxtc.target||pxt.appTarget&&pxt.appTarget.compile),u}function normalizePath(e){e=e.replace(/\\/g,"/");const t=[];return e.split("/").forEach((e=>{".."===e&&t.length?t.pop():"."!==e&&t.push(e)})),t.join("/")}pxtc.getTsCompilerOptions=getTsCompilerOptions,pxtc.nodeLocationInfo=nodeLocationInfo,pxtc.patchUpDiagnostics=patchUpDiagnostics,pxtc.py2tsIfNecessary=py2tsIfNecessary,pxtc.storeGeneratedFiles=storeGeneratedFiles,pxtc.runConversionsAndStoreResults=runConversionsAndStoreResults,pxtc.timesToMs=timesToMs,pxtc.isPxtModulesFilename=isPxtModulesFilename,pxtc.compile=compile,pxtc.decompile=decompile,pxtc.decompileSnippets=decompileSnippets,pxtc.getTSProgram=getTSProgram})(pxtc=ts.pxtc||(ts.pxtc={}))}(ts||(ts={})),function(e){!function(t){const n=["type","offset","vaddr","paddr","filesz","memsz","flags","align"],r=e.HF2.read32,s=e.HF2.read16,i=4096;t.parse=function(t){1179403647!=r(t,0)&&e.U.userError("no magic"),1!=t[4]&&e.U.userError("not 32 bit"),1!=t[5]&&e.U.userError("not little endian"),1!=t[6]&&e.U.userError("bad version"),2!=s(t,16)&&e.U.userError("wrong object type"),40!=s(t,18)&&e.U.userError("not ARM");let a=r(t,28);r(t,32),0==a&&e.U.userError("expecting program headers");let o=s(t,42),l=s(t,44),c=e.U.range(l).map((e=>function(e){let s={},i=e;for(let i of n)s[i]=r(t,e),e+=4;let a=s;return a._filepos=i,a}(a+e*o))),u=t.length+1;for(;15&u;)u++;let p=0;for(let e of c)1==e.type&&(p=Math.max(p,e.vaddr+e.memsz));let d=(p+i-1&-4096)+(4095&u),f=-1;for(let e of c)4==e.type&&(f=e._filepos);return{imageMemStart:d,imageFileStart:u,phOffset:f,template:t}},t.patch=function(t,r){let s=new Uint8Array(t.imageFileStart+r.length);return s.fill(0),e.U.memcpy(s,0,t.template),e.U.memcpy(s,t.imageFileStart,r),function(t,r){let s=r._filepos;for(let i of n)e.HF2.write32(t,s,r[i]||0),s+=4}(s,{_filepos:t.phOffset,type:1,offset:t.imageFileStart,vaddr:t.imageMemStart,paddr:t.imageMemStart,filesz:r.length,memsz:r.length,flags:5,align:i}),s}}(e.elf||(e.elf={}))}(pxt||(pxt={})),function(e){!function(t){const n=e.HF2.read32,r=e.HF2.read16,s=[{name:"esp32",chipId:0,memmap:[{from:0,to:65536,id:"PADDING"},{from:1061158912,to:1065353216,id:"DROM"},{from:1065353216,to:1069547520,id:"EXTRAM_DATA"},{from:1073217536,to:1073225728,id:"RTC_DRAM"},{from:1073283072,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073405952,to:1073741824,id:"DRAM"},{from:1073610752,to:1073741820,id:"DIRAM_DRAM"},{from:1073741824,to:1074200576,id:"IROM"},{from:1074200576,to:1074233344,id:"CACHE_PRO"},{from:1074233344,to:1074266112,id:"CACHE_APP"},{from:1074266112,to:1074397184,id:"IRAM"},{from:1074397184,to:1074528252,id:"DIRAM_IRAM"},{from:1074528256,to:1074536448,id:"RTC_IRAM"},{from:1074593792,to:1077936128,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s2",chipId:2,memmap:[{from:0,to:65536,id:"PADDING"},{from:1056964608,to:1073217536,id:"DROM"},{from:1062207488,to:1073217536,id:"EXTRAM_DATA"},{from:1073340416,to:1073348608,id:"RTC_DRAM"},{from:1073340416,to:1073741824,id:"BYTE_ACCESSIBLE"},{from:1073340416,to:1074208768,id:"MEM_INTERNAL"},{from:1073414144,to:1073741824,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1073872896,to:1074200576,id:"IRAM"},{from:1074200576,to:1074208768,id:"RTC_IRAM"},{from:1074266112,to:1082130432,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-s3",chipId:4,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1023410176,id:"DROM"},{from:1023410176,to:1040187392,id:"EXTRAM_DATA"},{from:1611653120,to:1611661312,id:"RTC_DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1070104576,to:1077813248,id:"MEM_INTERNAL"},{from:1070104576,to:1070596096,id:"DRAM"},{from:1073741824,to:1073848576,id:"IROM_MASK"},{from:1077346304,to:1077805056,id:"IRAM"},{from:1611653120,to:1611661312,id:"RTC_IRAM"},{from:1107296256,to:1115684864,id:"IROM"},{from:1342177280,to:1342185472,id:"RTC_DATA"}]},{name:"esp32-c3",chipId:5,memmap:[{from:0,to:65536,id:"PADDING"},{from:1006632960,to:1015021568,id:"DROM"},{from:1070071808,to:1070465024,id:"DRAM"},{from:1070104576,to:1070596096,id:"BYTE_ACCESSIBLE"},{from:1072693248,to:1072824320,id:"DROM_MASK"},{from:1073741824,to:1074135040,id:"IROM_MASK"},{from:1107296256,to:1115684864,id:"IROM"},{from:1077395456,to:1077805056,id:"IRAM"},{from:1342177280,to:1342185472,id:"RTC_IRAM"},{from:1342177280,to:1342185472,id:"RTC_DRAM"},{from:1611653120,to:1611661312,id:"MEM_INTERNAL2"}]}];function i(t){return`0x${t.addr.toString(16)} 0x${t.data.length.toString(16)} bytes; ${t.isDROM?"drom ":""}${t.isMapped?"mapped ":""}${e.U.toHex(t.data.slice(0,20))}...`}function a(t){if(233!=t[0])throw new Error("ESP: invalid magic: "+t[0]);let i=24;const a=r(t,12),o=s.find((e=>e.chipId==a));if(!o)throw new Error("ESP: unknown chipid: "+a);const l={header:t.slice(0,i),chipName:o.name,segments:[]},c=t[1];for(let r=0;r<c;++r){const r=n(t,i),s=n(t,i+4);i+=8;const a=t.slice(i,i+s);if(a.length!=s)throw new Error("too short file");if(i+=s,u(r,"PADDING"))continue;const o=l.segments.filter((e=>e.addr+e.data.length==r))[0];o?o.data=e.U.uint8ArrayConcat([o.data,a]):l.segments.push({addr:r,isMapped:u(r,"DROM")||u(r,"IROM"),isDROM:u(r,"DROM"),data:a})}return l;function u(e,t){return o.memmap.some((n=>n.id==t&&n.from<=e&&e<=n.to))}}function o(t){const n=e.U.flatClone(t);return n.segments=n.segments.map(e.U.flatClone),n}t.toBuffer=function(t,n=!0){let r=(t=function(t){const n=65535;(t=o(t)).segments.sort(((e,t)=>e.addr-t.addr)),e.debug("esp padding:\n"+t.segments.map(i).join("\n")+"\n");const r=t.segments.filter((e=>e.isMapped)),s=t.segments.filter((e=>!e.isMapped));t.segments=[];let a=t.header.length;for(const t of r){const r=t.addr+t.data.length&n;if(r<36){const n=new Uint8Array(36-r);t.data=e.U.uint8ArrayConcat([t.data,n])}}for(;r.length>0;){let e=r[0];const s=l(e);if(s>0)e=c(s);else{if((a+8&n)!=(e.addr&n))throw new Error(`pad oops 0 ${a}+8 != ${e.addr} (mod mask)`);r.shift()}if(t.segments.push(e),a+=8+e.data.length,3&a)throw new Error("pad oops 1")}return t.segments=t.segments.concat(s),e.debug("esp padded:\n"+t.segments.map(i).join("\n")+"\n"),t;function l(e){let t=(e.addr-8&n)-a&n;return 0==t?0:(t-=8,t<0&&(t+=65536),t)}function c(e){if(!s.length||e<=8)return{addr:0,isMapped:!1,isDROM:!1,data:new Uint8Array(e)};const t=s[0],n={addr:t.addr,isMapped:t.isMapped,isDROM:t.isDROM,data:t.data.slice(0,e)};return t.data=t.data.slice(e),t.addr+=n.data.length,0==t.data.length&&s.shift(),n}}(t)).header.length;for(const e of t.segments)r+=8+e.data.length;r=r+16&-16;let s=new Uint8Array(r);s.set(t.header),s[1]=t.segments.length;let a=t.header.length,l=239;for(const n of t.segments){e.HF2.write32(s,a,n.addr),e.HF2.write32(s,a+4,n.data.length),s.set(n.data,a+8),a+=8+n.data.length;for(let e=0;e<n.data.length;++e)l^=n.data[e]}if(s[s.length-1]=l,n){s[23]=1;const t=ts.pxtc.BrowserImpl.sha256buffer(s);s=e.U.uint8ArrayConcat([s,e.U.fromHex(t)])}else s[23]=0;return s},t.parseBuffer=a,t.parseB64=function(t){return a(e.U.stringToUint8Array(atob(t.join(""))))},t.cloneStruct=o}(e.esp||(e.esp={}))}(pxt||(pxt={})),function(e){!function(t){let n;!function(e){e[e.None=0]="None",e[e.Whitespace=1]="Whitespace",e[e.Identifier=2]="Identifier",e[e.Keyword=3]="Keyword",e[e.Operator=4]="Operator",e[e.CommentLine=5]="CommentLine",e[e.CommentBlock=6]="CommentBlock",e[e.NewLine=7]="NewLine",e[e.Literal=8]="Literal",e[e.Tree=9]="Tree",e[e.Block=10]="Block",e[e.EOF=11]="EOF"}(n||(n={}));let r="";let s=e.SyntaxKind;function i(e){switch(e){case s.CommaToken:return 2;case s.EqualsToken:case s.PlusEqualsToken:case s.MinusEqualsToken:case s.AsteriskEqualsToken:case s.AsteriskAsteriskEqualsToken:case s.SlashEqualsToken:case s.PercentEqualsToken:case s.LessThanLessThanEqualsToken:case s.GreaterThanGreaterThanEqualsToken:case s.GreaterThanGreaterThanGreaterThanEqualsToken:case s.AmpersandEqualsToken:case s.BarEqualsToken:case s.CaretEqualsToken:return 5;case s.QuestionToken:case s.ColonToken:return 7;case s.BarBarToken:return 10;case s.AmpersandAmpersandToken:return 20;case s.BarToken:return 30;case s.CaretToken:return 40;case s.AmpersandToken:return 50;case s.EqualsEqualsToken:case s.ExclamationEqualsToken:case s.EqualsEqualsEqualsToken:case s.ExclamationEqualsEqualsToken:return 60;case s.LessThanToken:case s.GreaterThanToken:case s.LessThanEqualsToken:case s.GreaterThanEqualsToken:case s.InstanceOfKeyword:case s.InKeyword:case s.AsKeyword:return 70;case s.LessThanLessThanToken:case s.GreaterThanGreaterThanToken:case s.GreaterThanGreaterThanGreaterThanToken:return 80;case s.PlusToken:case s.MinusToken:return 90;case s.AsteriskToken:case s.SlashToken:case s.PercentToken:return 100;case s.AsteriskAsteriskToken:return 101;case s.DotToken:return 120;default:return 0}}function a(e){switch(e){case s.EndOfFileToken:return n.EOF;case s.SingleLineCommentTrivia:return n.CommentLine;case s.MultiLineCommentTrivia:return n.CommentBlock;case s.NewLineTrivia:return n.NewLine;case s.WhitespaceTrivia:return n.Whitespace;case s.ShebangTrivia:case s.ConflictMarkerTrivia:return n.CommentBlock;case s.NumericLiteral:case s.StringLiteral:case s.RegularExpressionLiteral:case s.NoSubstitutionTemplateLiteral:case s.TemplateHead:case s.TemplateMiddle:case s.TemplateTail:return n.Literal;case s.Identifier:return n.Identifier;default:return e<s.Identifier?n.Operator:n.Keyword}}function o(e,t){for(;e[t]&&e[t].kind==n.Whitespace;)t++;return t}function l(){return{kind:n.EOF,synKind:s.EndOfFileToken,pos:0,lineNo:0,text:""}}function c(e,t){return{kind:n.Whitespace,synKind:s.WhitespaceTrivia,pos:e.pos-t.length,lineNo:e.lineNo,text:t}}function u(e){return{kind:n.Block,synKind:s.OpenBraceToken,pos:e[0].pos,lineNo:e[0].lineNo,stmts:[{tokens:e}],text:"{",endToken:null}}function p(e){if(!e)return!1;switch(e.synKind){case s.IfKeyword:case s.ElseKeyword:case s.LetKeyword:case s.ConstKeyword:case s.VarKeyword:case s.DoKeyword:case s.WhileKeyword:case s.SwitchKeyword:case s.CaseKeyword:case s.DefaultKeyword:case s.ForKeyword:case s.ReturnKeyword:case s.BreakKeyword:case s.ContinueKeyword:case s.TryKeyword:case s.CatchKeyword:case s.FinallyKeyword:case s.DeleteKeyword:case s.FunctionKeyword:case s.ClassKeyword:case s.YieldKeyword:case s.DebuggerKeyword:return!0;default:return!1}}function d(e,r,a=null){let o,f=[],m=0,g=!1;for(e=e.concat([l()]);e[m].kind!=n.EOF;){let n=m;E(),t.Util.assert(m>n,`Error at ${e[m].text}`),b(e.slice(n,m))}return f;function b(e){if(r&&(e=h(e)),0==e.length)return;e.forEach(y),e=x(e);if(r&&f.length>0){let n=f[f.length-1].tokens[0].synKind,r=e[0].synKind;if(n==s.IfKeyword&&r==s.ElseKeyword||n==s.TryKeyword&&r==s.CatchKeyword||n==s.TryKeyword&&r==s.FinallyKeyword||n==s.CatchKeyword&&r==s.FinallyKeyword)return e.unshift(c(e[0]," ")),void t.Util.pushRange(f[f.length-1].tokens,e)}f.push({tokens:e})}function x(e){let t=[],r=0;for(;r<e.length;)if(e[r].blockSpanLength){let a=e.slice(r,r+e[r].blockSpanLength),o=!!a[0].blockSpanIsVirtual;delete a[0].blockSpanLength,delete a[0].blockSpanIsVirtual,r+=a.length,a=x(a),o?t.push((i=a,{kind:n.Tree,synKind:s.WhitespaceTrivia,pos:i[0].pos,lineNo:i[0].lineNo,children:i,endToken:null,text:""})):(t.push(c(a[0]," ")),t.push(u(h(a))))}else t.push(e[r++]);var i;return t}function y(e){if(e.kind==n.Tree){let n=e;n.children=t.Util.concat(d(n.children,!1,n).map((e=>e.tokens)))}}function k(t=!1){for(;;)switch(m++,e[m].kind){case n.Whitespace:case n.CommentBlock:case n.CommentLine:break;case n.NewLine:if(t)break;break;default:return}}function S(){for(;e[m].kind==n.Whitespace;)m++;e[m].kind==n.NewLine&&m++}function T(){for(;;)switch(m++,e[m].kind){case n.EOF:return;case n.Tree:if(e[m].synKind==s.OpenBraceToken)return m--,void w()}}function I(){t.Util.assert(e[m].synKind==s.OpenBraceToken);let r=e[m];t.Util.assert(r.kind==n.Tree);let i=e[m];i.stmts=d(r.children,!0,o),delete r.children,i.kind=n.Block,m++,g=!0}function w(){let t=m+1;k(),e[m].synKind==s.OpenBraceToken?(I(),S()):(E(),e[t].blockSpanLength=m-t)}function E(){for(;;){let l=e[m],c=m;if(o=l,g=!1,l.kind==n.EOF)return;if(r&&l.synKind==s.SemicolonToken)return m++,void S();if(l.synKind==s.EqualsGreaterThanToken){if(k(),e[m].synKind==s.OpenBraceToken){I();continue}{let t=m;E();let r=m;for(;e[r].kind==n.NewLine;)r--;return e[t].blockSpanLength=r-t,void(e[t].blockSpanIsVirtual=!0)}}if(r&&i(l.synKind)){let t=m;if(k(),!p(e[m]))continue;m=t}if(r&&l.kind==n.NewLine){if(k(),l=e[m],i(l.synKind)&&l.synKind!=s.PlusToken&&l.synKind!=s.MinusToken)continue;return void(m=c+1)}if(l.synKind==s.OpenBraceToken&&a&&a.synKind==s.ClassKeyword){let t=m-1;for(;t>=0&&e[t].kind==n.Whitespace;)t--;if(t<0||e[t].synKind!=s.EqualsToken)return m--,void w()}switch(t.Util.assert(c==m),l.synKind){case s.ForKeyword:case s.WhileKeyword:case s.IfKeyword:case s.CatchKeyword:if(k(),e[m].synKind!=s.OpenParenToken)continue;return void w();case s.DoKeyword:if(w(),m--,k(),e[m].synKind==s.WhileKeyword){m++;continue}return;case s.ElseKeyword:if(k(),e[m].synKind==s.IfKeyword)continue;return m=c,void w();case s.TryKeyword:case s.FinallyKeyword:return void w();case s.ClassKeyword:case s.NamespaceKeyword:case s.ModuleKeyword:case s.InterfaceKeyword:case s.FunctionKeyword:return void T()}t.Util.assert(!g,"forgot continue/return after expectBlock"),m++}}}function f(e){return e&&(e.kind==n.Whitespace||e.kind==n.NewLine)}function m(e){let t=[],r=!1;for(let s=0;s<e.length;++s)r&&(s=o(e,s)),e[s]&&(t.push(e[s]),r=e[s].kind==n.NewLine);return t}function h(e){for(e=e.slice(0);f(e[0]);)e.shift();for(;f(e[e.length-1]);)e.pop();return e}function g(e,t){if(t.synKind==s.NoSubstitutionTemplateLiteral&&/^`[\s\.#01]*`$/.test(t.text)){let n=t.text.slice(1,t.text.length-1).split("\n").map((e=>e.replace(/\s/g,""))).filter((e=>!!e));if(n.length<4||n.length>5)return;let r=Math.floor((Math.max(...n.map((e=>e.length)))+2)/5);r<=0&&(r=1);let s="`\n";for(let t=0;t<5;++t){let i=n[t]||"";for(;i.length<5*r;)i+=".";i=i.replace(/0/g,"."),i=i.replace(/1/g,"#"),i=i.replace(/...../g,(e=>"/"+e)),s+=e+i.replace(/./g,(e=>" "+e)).replace(/\//g," ").slice(3)+"\n"}s+=e+"`",t.text=s}}t.toStr=function e(t){return Array.isArray(t)?"[[ "+t.map(e).join(" ")+" ]]":"string"==typeof t.text?JSON.stringify(t.text):t+""},t.format=function(t,u){let p=function(t){r=t;let i=e.createScanner(e.ScriptTarget.Latest,!1,e.LanguageVariant.Standard,t,(e=>{let t=i.getTextPos();console.log("scanner error",t,e.message)})),o=[],l=0,c=-1;for(;;){let e=i.scan();if(e==s.CloseBraceToken&&l==c&&(c=-1,e=i.reScanTemplateToken()),e==s.SlashEqualsToken){let t=i.reScanSlashToken();t==s.RegularExpressionLiteral&&(e=t)}e==s.GreaterThanToken&&(e=i.reScanGreaterToken());let t={kind:a(e),synKind:e,lineNo:0,pos:i.getTokenPos(),text:i.getTokenText()};if(e==s.OpenBraceToken&&l++,e==s.CloseBraceToken&&--l<0&&(l=-1e7),o.push(t),e!=s.TemplateHead&&e!=s.TemplateMiddle||(c=l),t.kind==n.EOF)break}return{tokens:o,braceBalance:l}}(t).tokens;p=function(e,t){let r=[],i=!0,a=1;for(let l=0;l<e.length;++l){if(i){let i=l;if(l=o(e,l),e[l].kind==n.NewLine){let i=!1;t>=0&&e[l].pos>=t&&(t=-1,i=!0),r.push({text:"",kind:n.CommentLine,pos:e[l].pos,lineNo:a,synKind:s.SingleLineCommentTrivia,isCursor:i})}else l=i}r.push(e[l]),e[l].lineNo=a,e[l].kind==n.NewLine?(i=!0,a++):i=!1,t>=0&&e[l].pos>=t&&(t=-1)}return r}(p,u),p=function(e){let t=[];t.push({synKind:s.EndOfFileToken,token:{children:[]}});let r=(e,r)=>{let s=e;s.children=[],s.kind=n.Tree,t.push({synKind:r,token:s})};for(let i=0;i<e.length;++i){let a=e[i],o=t[t.length-1];switch(o.token.children.push(a),a.kind){case n.Operator:switch(a.synKind){case s.OpenBraceToken:case s.OpenParenToken:case s.OpenBracketToken:r(a,a.synKind+1);break;case s.CloseBraceToken:case s.CloseParenToken:case s.CloseBracketToken:for(o.token.children.pop();;){if(o=t.pop(),o.synKind==a.synKind){o.token.endToken=a;break}if(0==t.length||o.synKind==s.CloseBraceToken){t.push(o);break}}}}}return t[0].token.children}(p);let f=d(p,!0),h="",b="",x=-1,y=0;return f.forEach(T),f.forEach((e=>e.tokens.forEach(k))),-1==x&&(x=b.length),{formatted:b,pos:x};function k(e){if(e.kind==n.Tree){let t=e;e.synKind,s.OpenBraceToken,t.children.forEach(k)}else e.kind==n.Block&&e.stmts.forEach((e=>e.tokens.forEach(k)))}function S(e,t){if(y==e.lineNo)t();else{y=e.lineNo;let n=h;h+=" ",t(),h=n}}function T(e){let t=m(e.tokens);1!=t.length||t[0].isCursor||""!=t[0].text?(b+=h,S(t[0],(()=>{w(t)})),"\n"!=b[b.length-1]&&(b+="\n")):b+="\n"}function I(e){-1==x&&e.pos+e.text.length>=u&&(x=b.length+(u-e.pos)),b+=e.text}function w(e){e=function(e){let t=[],r=0,a=l();for(e=e.concat([l()]);r<e.length;){r=o(e,r);let l=e[r];if(l.kind==n.EOF)break;let p=o(e,r+1);if(l.kind==n.NewLine&&e[p].synKind==s.OpenBraceToken){r=p;continue}let d=!0,f=0==t.length?(u=l,{kind:n.NewLine,synKind:s.NewLineTrivia,pos:u.pos,lineNo:u.lineNo,text:"\n"}):t[t.length-1];switch(f.synKind){case s.ExclamationToken:case s.TildeToken:case s.DotToken:d=!1;break;case s.PlusToken:case s.MinusToken:case s.PlusPlusToken:case s.MinusMinusToken:f.isPrefix&&(d=!1)}switch(l.synKind){case s.DotToken:case s.CommaToken:case s.NewLineTrivia:case s.ColonToken:case s.SemicolonToken:case s.OpenBracketToken:d=!1;break;case s.PlusPlusToken:case s.MinusMinusToken:f.kind!=n.Tree&&f.kind!=n.Identifier&&f.kind!=n.Keyword||(d=!1);case s.PlusToken:case s.MinusToken:(a.kind==n.EOF||i(a.synKind)||a.synKind==s.SemicolonToken)&&(l.isPrefix=!0);break;case s.OpenParenToken:if(f.kind==n.Identifier&&(d=!1),f.kind==n.Keyword)switch(f.synKind){case s.IfKeyword:case s.ForKeyword:case s.WhileKeyword:case s.SwitchKeyword:case s.ReturnKeyword:case s.ThrowKeyword:case s.CatchKeyword:break;default:d=!1}}f.kind==n.NewLine&&(d=!1),d&&t.push(c(l," ")),t.push(l),l.kind!=n.NewLine&&(a=l),r++}var u;return t}(e);for(let t=0;t<e.length;++t){let r=e[t];switch(g(h,r),I(r),r.kind){case n.Tree:let s=r;S(r,(()=>{w(m(s.children))})),s.endToken&&I(s.endToken);break;case n.Block:let i=r;0==i.stmts.length?b+=" ":(b+="\n",i.stmts.forEach(T),b+=h.slice(4)),i.endToken?I(i.endToken):b+="}";break;case n.NewLine:if(e[t+1]&&e[t+1].kind==n.CommentLine&&""==e[t+1].text&&!e[t+1].isCursor)break;t==e.length-1?b+=h.slice(4):b+=h;break;case n.Whitespace:}}}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,n){if(!n.packedSource)return;let r=e.currPtr+4096&-256,s=new Uint8Array(256);for(let i=0;i<n.packedSource.length;i+=256){for(let e=0;e<256;++e)s[e]=n.packedSource.charCodeAt(i+e);t.UF2.writeBytes(e,r,s,t.UF2.UF2_FLAG_NOFLASH),r+=256}}!function(e){e.asmTotalSource="";let n={},s=[];let i={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0};function a(e){let n="",r=0;for(;r<e.length;r+=2)n=e[r]+e[r+1]+n;return t.assert(r==e.length),n}function o(e){if(!(e=e.replace(/^[\s:]/,"")))return[];let n=[];if(e.replace(/([a-f0-9][a-f0-9])/gi,(e=>(n.push(parseInt(e,16)),""))))throw t.oops("bad bytes "+e);return n}function l(e){return e.flashCodeAlign||1024}e.getCommBase=function(){return i.commBase},e.getStartAddress=function(){return i.codeStartAddrPadded},e.setupInlineAssembly=function(r){n={};let s=r.sourceFiles.filter((e=>t.U.endsWith(e,".asm")));e.asmTotalSource="";let i=0;for(let t of s){let s=r.fileSystem[t];s.replace(/^\s*(\w+):/gm,((e,t)=>(n[t]=!0,"")));let a=".object inlineasm\n.section code\n@stackmark func\n@scope user"+i+++"\n"+s+"\n@stackempty func\n@scope\n";e.asmTotalSource+=a}},e.parseHexBytes=o,e.parseHexRecord=function(e){let t=o(e);return{len:t[0],addr:t[1]<<8|t[2],type:t[3],data:t.slice(4,t.length-1),checksum:t[t.length-1]}},e.flashCodeAlign=l;const c="0108010842424242010801083ed8e98d";function u(e){return i.funcInfo[e]}function p(){let e=i.sha?i.sha.slice(0,16):"";for(;e.length<16;)e+="0";return e.toUpperCase()}function d(e){let t=0,n=":";return e.forEach((e=>t+=e)),e.push(255&-t),e.forEach((e=>n+=("0"+e.toString(16)).slice(-2))),n.toUpperCase()}e.setupFor=function(e,n){if(i=s.find((e=>e.sha==n.sha)),i)return;i={commBase:0,funcInfo:{},codeStartIdx:-1,codePaddingSize:0,sha:null,codeStartAddrPadded:void 0,hexlines:void 0,jmpStartAddr:void 0,jmpStartIdx:void 0,codeStartAddr:void 0,elfInfo:void 0,espInfo:void 0},s.length>10&&(s=[]),s.push(i);let r=n.functions;i.commBase=n.commBase||0,i.sha=n.sha;const u=n.hexinfo.hex;if(i.hexlines=u,t.target.nativeType==t.NATIVE_TYPE_VM){i.codeStartAddr=0,i.codeStartAddrPadded=0,i.jmpStartAddr=-1,i.jmpStartIdx=-1;for(let e of r)i.funcInfo[e.name]=e,e.value=16777215;if(t.target.useESP){const e=pxt.esp.parseB64(u),r=t.U.fromHex(c),s=(e,t)=>{for(let n=0;n<r.length;++n)if(e[t+n]!=r[n])return!1;return!0},a=e.segments.filter((e=>e.isDROM));t.U.assert(1==a.length);let o=!1;const l=a[0];i.codeStartAddr=l.addr+l.data.length,i.codeStartAddrPadded=i.codeStartAddr+255&-256,i.codePaddingSize=i.codeStartAddrPadded-i.codeStartAddr,pxt.debug(`user code start: 0x${i.codeStartAddrPadded.toString(16)}; dromlen=${l.data.length} pad=${i.codePaddingSize}`);for(let e=0;e<l.data.length;e+=32)if(s(l.data,e)){o=!0,e+=r.length;const t=e;for(let t of n.vmPointers||[])"0"!=t&&(t=t.replace(/^&/,""),i.funcInfo[t]={name:t,argsFmt:[],value:pxt.HF2.read32(l.data,e)},e+=4);pxt.HF2.write32(l.data,t,i.codeStartAddrPadded);break}t.U.assert(o||0==(n.vmPointers||[]).length),i.espInfo=e,i.codeStartAddrPadded=0}return}if(u.length<=2){const e=t.U.fromHex(u[0]);if(e[2]<=2&&96==e[3]){const t=1610612736,n=4096,r=e.length+n-1&~(n-1);i.elfInfo={template:e,imageMemStart:t+r,imageFileStart:r,phOffset:-1e3}}else i.elfInfo=pxt.elf.parse(e);i.codeStartAddr=i.elfInfo.imageMemStart,i.codeStartAddrPadded=i.elfInfo.imageMemStart;let n=u[0].indexOf(c);return n<0&&t.oops("no jmp table in elf"),i.jmpStartAddr=n/2,i.jmpStartIdx=-1,b(u[0].slice(n+32,n+32+8*r.length+16)),void x()}!function(e){for(let n=0;n<e.length;++n)if("2"==e[n][8]){let r=/^:02....02(....)..$/.exec(e[n]);t.U.assert(!!r);let s=16*parseInt(r[1],16);t.U.assert(0==(65535&s)),e[n]=d([2,0,0,4,0,s>>16])}}(u);let p=0,f="0000",m=0,h=0;i.codeStartAddr=0;let g=()=>{if(!i.codeStartAddr){let n=o(u[h]),r=16-(m+n[0]&15)&15;if(r)if(15&n[2]){let e=m+n[0],t=[r,e>>8,255&e,0];for(let e=0;e<r;++e)t.push(0);h++,u.splice(h,0,d(t)),i.codeStartAddr=e+r}else{if(16!=n[0]){for(n.pop(),n[0]=16;n.length<20;)n.push(0);u[h]=d(n)}i.codeStartAddr=m+16}else i.codeStartAddr=m+n[0];i.codeStartIdx=h+1;const s=l(e);i.codeStartAddrPadded=(i.codeStartAddr&~(s-1))+s;const a=i.codeStartAddrPadded-i.codeStartAddr;t.assert(0==(15&a)),i.codePaddingSize=a}};for(;p<u.length;++p){let t=/:02000004(....)/.exec(u[p]);if(t&&(f=t[1]),t=/^:..(....)00/.exec(u[p]),t){let n=parseInt(f+t[1],16);!e.flashUsableEnd&&m&&n-m>65536&&g(),e.flashUsableEnd&&n>=e.flashUsableEnd&&g(),h=p,m=n}/^:00000001/.test(u[p])&&g(),t=/^:10....000108010842424242010801083ED8E98D/.exec(u[p]),t&&(i.jmpStartAddr=m,i.jmpStartIdx=p)}pxt.debug(`code start: ${i.codeStartAddrPadded}, jmptbl: ${i.jmpStartAddr}`),i.jmpStartAddr||t.oops("No hex start"),i.codeStartAddr||t.oops("No hex end"),i.funcInfo={};for(let e=i.jmpStartIdx+1;e<u.length;++e){let t=/^:..(....)00(.{4,})/.exec(u[e]);if(t&&(b(t[2]),0==r.length))break}return void x();function b(n){let s=e.shortPointers?4:8;for(;n.length>=s;){let o=n.slice(0,s),l=parseInt(a(o),16);n=n.slice(s);let c=r.shift();if(!c)break;i.funcInfo[c.name]=c,l||t.U.oops("No value for "+c.name+" / "+o),0==c.argsFmt.length?l^=1:e.runtimeIsARM||e.nativeType!=t.NATIVE_TYPE_THUMB||1&l||t.U.oops("Non-thumb addr for "+c.name+" / "+o),c.value=l}}function x(){r.length&&t.oops("premature EOF in hex file; missing: "+r.map((e=>e.name)).join(", "))}},e.validateShim=function(e,r,s,i,a){if("TD_ID"==r||"TD_NOOP"==r||"ENUM_GET"==r)return;if(t.U.lookup(n,r))return;let o=`${e}(...) (shim=${r})`,l=u(r);if(l){i?"V"==l.argsFmt[0]&&t.U.userError("expecting function for "+o):"V"!=l.argsFmt[0]&&t.U.userError("expecting procedure for "+o);for(let e=0;e<a.length;++e){l.argsFmt[e+1]||t.U.userError("excessive parameters passed to "+o)}a.length!=l.argsFmt.length-1&&t.U.userError(`not enough arguments for ${o} (got ${a.length}; fmt=${l.argsFmt.join(",")})`)}else t.U.userError("function not found: "+o)},e.lookupFunc=u,e.lookupFunctionAddr=function(e){if("_pxt_comm_base"==e)return i.commBase;let t=u(e);return t?t.value:null},e.hexTemplateHash=p,e.hexPrelude=function(){return` .startaddr 0x${i.codeStartAddrPadded.toString(16)}\n`},e.hexBytes=d,e.patchHex=function(e,n,s,o){let l=i.hexlines.slice(0,i.codeStartIdx);if(!e.target.useESP){let r=2*n.length+7>>3;t.assert(r<64e3,"program too large, bytes: "+2*n.length),n[17]=r,n[20]=e.commSize}let c=[];for(let e=0;e<i.codePaddingSize>>1;++e)c.push(0);n=c.concat(n);let u=0;function f(e,t){let n=[16,t>>8&255,255&t,0];for(let t=0;t<8;++t)n.push(255&(e[u]||0)),n.push((e[u]||0)>>>8),u++;return n}let m=[16912,0,65535&i.codeStartAddrPadded,i.codeStartAddrPadded>>>16],h=p();for(let e=0;e<4;++e)m.push(parseInt(a(h.slice(4*e,4*e+4)),16));let g=o?t.UF2.newBlockFile(t.target.uf2Family):null;if(i.elfInfo){let r=new Uint8Array(2*n.length);for(let e=0;e<n.length;++e)pxt.HF2.write16(r,2*e,n[e]);let s=pxt.elf.patch(i.elfInfo,r);for(let e=0;e<m.length;++e)pxt.HF2.write16(s,2*e+i.jmpStartAddr,m[e]);if(g&&!e.target.switches.rawELF){let n=e.name||"pxt";return n=n.replace(/[^a-zA-Z0-9\-\.]+/g,"_"),g.filename="Projects/"+n+".elf",t.UF2.writeBytes(g,0,s),[t.UF2.serializeFile(g)]}return[t.U.uint8ArrayToString(s)]}if(i.espInfo){const s=pxt.esp.cloneStruct(i.espInfo),a=s.segments.find((e=>e.isDROM));let o=a.data.length;const l=new Uint8Array(o+2*n.length+255&-256);l.set(a.data);for(let e=0;e<n.length;++e)pxt.HF2.write16(l,o,n[e]),o+=2;a.data=l;const c=pxt.esp.toBuffer(s);return g?(t.UF2.writeBytes(g,0,c),r(g,e),[t.UF2.serializeFile(g)]):[t.U.uint8ArrayToString(c)]}if(g){if(t.UF2.writeHex(g,l),t.UF2.writeBytes(g,i.jmpStartAddr,f(m,i.jmpStartIdx).slice(4)),e.checksumBlock){let n=[];for(let t of e.checksumBlock)n.push(255&t,t>>8);t.UF2.writeBytes(g,e.target.flashChecksumAddr,n)}}else l[i.jmpStartIdx]=d(f(m,i.jmpStartAddr)),e.checksumBlock&&t.U.oops("checksum block in HEX not implemented yet");u=0,s&&(l=[]);let b=i.codeStartAddr,x=b-16>>16;for(;u<n.length;)g?t.UF2.writeBytes(g,b,f(n,b).slice(4)):(b>>16!=x&&(x=b>>16,l.push(d([2,0,0,4,x>>8,255&x]))),l.push(d(f(n,b)))),b+=16;if(!s){let e=i.hexlines.slice(i.codeStartIdx);g?t.UF2.writeHex(g,e):t.Util.pushRange(l,e)}if(!g&&e.target.moveHexEof){for(;!l[l.length-1];)l.pop();":00000001FF"==l[l.length-1]&&l.pop()}if(e.packedSource)if(g)r(g,e);else{let t=0;for(let n=0;n<e.packedSource.length;n+=16){let r=[16,t>>8&255,255&t,14];for(let t=0;t<16;++t)r.push(255&(e.packedSource.charCodeAt(n+t)||0));l.push(d(r)),t+=16}}return!g&&e.target.moveHexEof&&l.push(":00000001FF"),g?[t.UF2.serializeFile(g)]:l}}(n=t.hexfile||(t.hexfile={})),t.hexDump=function(e,t=0){function n(e,t=8){let n=e.toString(16);for(;n.length<t;)n="0"+n;return n}let r="";for(let s=0;s<e.length;s+=16){r+=n(t+s)+": ";let i="";for(let t=0;t<16;t++){0==(3&t)&&(r+=" ");let a=e[s+t];null!=a?(r+=n(a,2)+" ",i+=32<=a&&a<127?String.fromCharCode(a):"."):r+=" "}r+=" "+i+"\n"}return r},t.asmline=function(e){return e.indexOf("\n")>=0?(e=e.replace(/^\s*/gm,"").replace(/^(.*)$/gm,((e,t)=>";"==t[0]&&" "==t[1]||/:\*$/.test(t)?t:" "+t)))+"\n":(/(^[\s;])|(:$)/.test(e)||(e=" "+e),e+"\n")},t.firstMethodOffset=function(){return 9};const s=[21078089,22513679,15655169,18636881,19658081,21486649,21919277,20041213,20548751,16180187,18361627,19338023,19772677,16506547,23530697,22998697,21225203,19815283,23679599,19822889,21136133,19540043,21837031,18095489,23924267,23434627,22582379,21584111,22615171,23403001,19640683,19998031,18460439,20105387,17595791,16482043,23199959,18881641,21578371,22765747,20170273,16547639,16434589,21435019,20226751,19506731,21454393,23224541,23431973,23745511];function i(e){let n=32;t.U.assert(t.U.unique(e,(e=>""+e)).length==e.length,"non unique");for(let r=2;;r<<=1){if(n--,r<e.length)continue;let i,a=-1,o=-1;for(let l of s){let s=l<<8|n,c=new Uint16Array(r+t.vtLookups+1);t.U.assert(0==(1&c.length));let u=0,p=[];for(let r of e){t.U.assert(r>0);let e=Math.imul(r,s)>>>n;p.push(e);let i=!1;for(let n=0;n<t.vtLookups;n++){if(!c[e+n]){i=!0,c[e+n]=r;break}u++}if(!i){u=-1;break}}(-1==a||a>u)&&(a=u,o=s,i=c)}if(a>=0)return{mult:o,mapping:i,size:r}}}function a(e,n,r,s){const a=i(e.itable.map((e=>e.idx)));let o=t.target.shortPointers?".short":".word",l=`\n .object ${e.id}_VT\n .balign 4\n${e.id}_VT:\n .short ${4*e.allfields.length+4} ; size in bytes\n .byte ${pxt.ValTypeObject}, ${pxt.VTABLE_MAGIC} ; magic\n ${o} ${e.id}_IfaceVT\n .short ${e.classNo} ; class-id\n .short 0 ; reserved\n .word ${a.mult} ; hash-mult\n`,c=e=>{"0"!=e&&(e+="@fn"),l+=` ${o} ${e}\n`};c("pxt::RefRecord_destroy"),c("pxt::RefRecord_print"),c("pxt::RefRecord_scan"),c("pxt::RefRecord_gcsize");let u=e.toStringMethod;c(u?u.vtLabel():"0");for(let t of e.vtable)c(t.label()+"_nochk");l+=`\n .balign ${t.target.shortPointers?2:4}\n${e.id}_IfaceVT:\n`;const p=2*a.mapping.length;let d="",f=p,m={};for(let t of e.itable){m[t.idx+""]=f;const e=t.proc?t.proc.isGetter()?1:2:0;d+=` .short ${t.idx}, ${e} ; ${t.name}\n`,d+=` .word ${t.proc?t.proc.vtLabel()+"@fn":t.info}\n`,f+=8,t.setProc&&(d+=` .short ${t.idx}, 0 ; set ${t.name}\n`,d+=` .word ${t.setProc.vtLabel()}@fn\n`,f+=8)}d+=" .word 0, 0 ; the end\n",f+=8;let h=a.mapping;for(let e=0;e<h.length;++e)r.itEntries++,h[e]&&r.itFullEntries++;return l+=" .short "+t.U.toArray(h).map(((e,t)=>(m[e+""]||p)-2*t)).join(", ")+"\n",l+=d,l+="\n",l}t.vtLookups=3,t.computeHashMultiplier=i,t.vtableToAsm=a;const o=["GC"];function l(e,r,s){let i=`\n .short ${e.globalsWords} ; num. globals\n .short 0 ; patched with number of 64 bit words resulting from assembly\n .word _pxt_config_data\n .short 0 ; patched with comm section size\n .short ${e.nonPtrGlobals} ; number of globals that are not pointers (they come first)\n .word _pxt_iface_member_names\n .word _pxt_lambda_trampoline@fn\n .word _pxt_perf_counters\n .word _pxt_restore_exception_state@fn\n .word ${e.emitString(e.getTitle())} ; name\n`,l=null;l=new t.ThumbSnippets;const c=e.setPerfCounters(o);e.procs.forEach((n=>{let r=new t.ProctoAssembler(l,e,n);i+="\n"+r.getAssembly()+"\n"}));let u=new t.ProctoAssembler(l,e,null);u.emitHelpers(),i+="\n"+u.getAssembly()+"\n",i+=n.asmTotalSource,i+="_code_end:\n\n",t.U.iterMap(e.codeHelpers,((e,t)=>{i+=` .section code\n .object _code_helper_${t}\n${t}:\n${e}\n`})),i+=l.arithmetic(),i+="_helpers_end:\n\n",e.usedClassInfos.forEach((t=>{i+=a(t,0,e)})),i+="\n.balign 4\n.object _pxt_iface_member_names\n_pxt_iface_member_names:\n",i+=` .word ${e.ifaceMembers.length}\n`;let p=0;for(let t of e.ifaceMembers){let n=e.emitString(t);i+=` .word ${n} ; ${p++} .${t}\n`}i+=" .word 0\n",i+="_vtables_end:\n\n",i+="\n.balign 4\n.object _pxt_config_data\n_pxt_config_data:\n";const d=s.configData||[];for(let e of d)i+=` .word ${e.key}, ${e.value} ; ${e.name}=${e.value}\n`;i+=" .word 0\n\n",function(e,n){const r=t.U.unique(n.ifaceMembers.concat(Object.keys(n.strings)),(e=>e));for(let t of r)n.otherLiterals.push(e.string_literal(n.strings[t],t));for(let t of Object.keys(n.doubles)){let r=n.doubles[t];n.otherLiterals.push(`\n.object ${r}\n.balign 4\n${r}: ${e.obj_header("pxt::number_vt")}\n .hex ${t}\n`)}for(let t of Object.keys(n.hexlits))n.otherLiterals.push(e.hex_literal(n.hexlits[t],t)),n.otherLiterals.push()}(l,e),i+=e.otherLiterals.join(""),i+="\n.balign 4\n.section code\n.object _perf_counters\n_pxt_perf_counters:\n",i+=` .word ${c.length}\n`;let f="";for(let e=0;e<c.length;++e){let t=".perf"+e;i+=` .word ${t}\n`,f+=`${t}: .string ${JSON.stringify(c[e])}\n`}return i+=f,i+="_literals_end:\n",i}function c(e){let r;return r=e.nativeType==t.NATIVE_TYPE_VM?new t.assembler.VMFile(new t.vm.VmProcessor(e)):new t.assembler.File(new t.thumb.ThumbProcessor),r.ei.testAssembler(),e.switches.noPeepHole&&(r.disablePeepHole=!0),e.switches.size&&(r.codeSizeStats=!0),r.lookupExternalLabel=n.lookupFunctionAddr,r.normalizeExternalLabel=e=>{let t=n.lookupFunc(e);return t?t.name:e},r}function u(e){if(e.errors.length>0){let n="";throw e.errors.forEach((e=>{let r=/^user(\d+)/.exec(e.scope);if(r){parseInt(r[1]);n+=t.U.lf("At inline assembly:\n"),n+=e.message}})),n?(console.log(t.U.lf("errors in inline assembly")),console.log(n),new Error(e.errors[0].message)):new Error(e.errors[0].message)}}t.processorInlineAssemble=function(e,t){let n=c(e);n.disablePeepHole=!0,n.emit(t),u(n);let r=[];for(let e=0;e<n.buf.length;e+=2)r.push(((n.buf[e+1]||0)<<16|n.buf[e])>>>0);return r};function p(e,t,n){let r=c(e);return r.emit(n),n=`; Interface tables: ${t.itFullEntries}/${t.itEntries} (${Math.round(100*t.itFullEntries/t.itEntries)}%)\n; Virtual methods: ${t.numVirtMethods} / ${t.numMethods}\n`+r.getSource(!0,t.numStmts,e.flashEnd),u(r),{src:n,buf:r.buf,thumbFile:r}}function d(r,s,i,a){const o=i.extinfo.disabledDeps;r=o?`${n.hexPrelude()}\n; compilation disabled on this variant due to ${i.extinfo.disabledDeps}\n.hex 718E3B92C615A841C49866C975EE5197\n.string "${i.extinfo.disabledDeps}"`:`; start\n${n.hexPrelude()}\n .hex 708E3B92C615A841C49866C975EE5197 ; magic number\n .hex ${n.hexTemplateHash()} ; hex template hash\n .hex 873266330af9dbdb ; replaced in binary by program hash\n`+r,i.embedBlob&&(s.packedSource=function(e,n){let r=t.Util.toUTF8(e),s=(r.length,n.length,"A/¸/¢»");return s+=t.U.uint8ArrayToString([255&r.length,r.length>>8,255&n.length,n.length>>8,0,0,0,0]),s+=r,s+=n,s.length%2&&(s+="\0"),s}(i.embedMeta,e.pxtc.decodeBase64(i.embedBlob)),!s.target.noSourceInFlash&&s.packedSource.length<4e4&&(r+=function(e){let t="";for(let n=0;n<e.length;++n){let r=255&e.charCodeAt(n);t+=r<=15?"0"+r.toString(16):r.toString(16)}return`\n .balign 16\n .object _stored_program\n_stored_program: .hex ${t}\n`}(s.packedSource),s.packedSource=null));const l=n.flashCodeAlign(i.target);if(!o&&i.target.flashChecksumAddr){let e=0;for(;l>1<<e;)e++;let t=parseInt(n.hexTemplateHash().slice(8,16),16);const s=n.getStartAddress()/l;t=4294967040&t|e;let a=0,o=s;i.target.flashChecksumAddr<n.getStartAddress()&&(a=Math.ceil((i.target.flashChecksumAddr+32)/l),o-=a),r+=`\n .balign 4\n__end_marker:\n .word ${t}\n\n; ------- this will get removed from the final binary ------\n__flash_checksums:\n .word 0x87eeb07c ; magic\n .word __end_marker ; end marker position\n .word ${t} ; end marker\n ; template region\n .short ${a}, ${o}\n .word 0x${n.hexTemplateHash().slice(0,8)}\n ; user region\n .short ${s}, 0xffff\n .hex 87326633 ; replaced later\n .word 0x0 ; terminator\n`}const c=i.extinfo.outputPrefix||"";s.writeFile(c+t.BINARY_ASM,r);const u=p(i.target,s,r);if(u.thumbFile.commPtr&&(s.commSize=u.thumbFile.commPtr-n.getCommBase()),u.src&&s.writeFile(c+t.BINARY_ASM,u.src),o)return void f();const d=a.configData||[];if(d.some((e=>"BOOTLOADER_BOARD_ID"==e.name))){let e="const uint32_t configData[] = {\n";e+=" 0x1e9e10f1, 0x20227a79, // magic\n",e+=` ${d.length}, 0, // num. entries; reserved\n`;for(let t of d)e+=` ${t.key}, 0x${t.value.toString(16)}, // ${t.name}\n`;e+=" 0, 0\n};\n",s.writeFile(c+"config.c",e)}if(u.buf){const e=u.buf;let n="";for(let t=0;t<e.length;++t)n+=String.fromCharCode(255&e[t],e[t]>>8);const r=t.U.sha256(n).slice(0,16),a=t.U.range(4).map((e=>parseInt(r.slice(2*e,2*e+2),16)));t.U.assert(12935==e[12]);for(let t=0;t<a.length;++t)e[12+t]=a[t];if(i.target.flashChecksumAddr){let n=u.thumbFile.lookupLabel("__flash_checksums")/2;t.U.assert(n==e.length-16);let r=e.slice(e.length-16);e.splice(e.length-16,16);let i=Math.ceil(2*e.length/l);t.U.assert(12935==r[r.length-4]),r[r.length-4]=a[0],r[r.length-3]=a[1],r[r.length-5]=i,s.checksumBlock=r}f()}if(!a.procDebugInfo){for(let e of a.breakpoints){let n=t.U.lookup(u.thumbFile.getLabels(),"__brkp_"+e.id);null!=n&&(e.binAddr=n)}for(let e of s.procs)e.fillDebugInfo(u.thumbFile);if(a.procDebugInfo=s.procs.map((e=>e.debugInfo)),s.target.switches.size){const n=[];for(const r of s.procs){const s=e.pxtc.nodeLocationInfo(r.action),i=[s.fileName.replace("pxt_modules/",""),t.getDeclName(r.action),r.debugInfo.size,"function",s.line+1];n.push(i.map((e=>`"${e}"`)).join(","))}n.sort(),n.unshift("filename,name,size,type,line"),s.writeFile(c+"size.csv",n.join("\n"))}}function f(){if(pxt.isOutputText(t.target)){const e=n.patchHex(s,u.buf,!1,!1).join("\r\n")+"\r\n";s.writeFile(c+pxt.outputName(t.target),e)}else{const r=e.pxtc.encodeBase64(n.patchHex(s,u.buf,!1,!!t.target.useUF2)[0]);s.writeFile(c+pxt.outputName(t.target),r)}}}t.assemble=p,t.processorEmit=function(e,r,s){var i,a;const o=l(e,0,s),c=t.U.flatClone(r);n.setupFor(r.target,r.extinfo||t.emptyExtInfo()),d(o,e,r,s),s.builtVariants||(s.builtVariants=[]),s.builtVariants.push(null===(i=r.extinfo)||void 0===i?void 0:i.appVariant);const u=c.otherMultiVariants||[];if(u.length)try{for(let r of u){const i=t.U.flatClone(c);i.extinfo=r.extinfo,r.target.isNative=!0,i.target=r.target,n.setupFor(i.target,i.extinfo),d(o,e,i,s),s.builtVariants.push(null===(a=r.extinfo)||void 0===a?void 0:a.appVariant)}}finally{n.setupFor(c.target,c.extinfo)}},t.validateShim=n.validateShim}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.getHelpForKeyword=function(e,t){const n={abstract:null,any:null,as:null,break:null,case:null,catch:null,class:null,continue:null,const:null,constructor:null,debugger:null,declare:null,delete:null,do:null,else:null,enum:null,export:null,extends:null,false:lf("Represents the negative outcome of a logical expression"),finally:null,for:null,from:null,function:null,get:null,if:null,implements:null,in:null,instanceof:null,interface:null,is:null,let:null,namespace:null,new:null,null:null,private:null,protected:null,public:null,return:null,set:null,static:null,super:null,switch:null,this:null,throw:null,true:lf("Represents the positive outcome of a logical expression"),try:null,type:null,typeof:null,undefined:null,void:null,while:null,with:null,of:null};if(t){return{True:n.true,False:n.false,None:null,abs:null,all:null,any:null,ascii:null,bin:null,bool:null,bytearray:null,bytes:null,callable:null,chr:null,classmethod:null,compile:null,complex:null,copyright:null,credits:null,delattr:null,dict:null,dir:null,divmod:null,enumerate:null,eval:null,exec:null,exit:null,filter:null,float:null,format:null,frozenset:null,getattr:null,globals:null,hasattr:null,hash:null,help:null,hex:null,id:null,input:null,int:null,isinstance:null,issubclass:null,iter:null,len:null,license:null,list:null,locals:null,map:null,max:null,memoryview:null,min:null,next:null,object:null,oct:null,open:null,ord:null,pow:null,print:null,property:null,quit:null,range:null,repr:null,reversed:null,round:null,set:null,setattr:null,slice:null,sorted:null,staticmethod:null,str:null,sum:null,super:null,tuple:null,type:null,vars:null}[e]}return n[e]}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){e.LSHost=class{constructor(e){this.p=e}getCompilationSettings(){const e=this.p.getCompilerOptions();return e.noLib=!0,e}getNewLine(){return"\n"}getScriptFileNames(){return this.p.getSourceFiles().map((e=>e.fileName))}getScriptVersion(e){return"0"}getScriptSnapshot(e){const t=this.p.getSourceFile(e);return{getLength:()=>t.getFullText().length,getText:()=>t.getFullText(),getChangeRange:()=>{}}}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return""}useCaseSensitiveFileNames(){return!0}}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){var t,r;const s=null===(r=null===(t=null==e?void 0:e.pxt)||void 0===t?void 0:t.callInfo)||void 0===r?void 0:r.qName;return n.lastApiInfo.apis.byQName[s]}function s(e,t,r){if(!e||t<0)return;let s=e.parameters[t];if(e.attributes._def){const i=e.attributes._def.parameters[t].shadowBlockId;if(i){const e=r.blocksById[i],t=n.lastApiInfo.apis.byQName[e.qName];"TD_ID"===t.attributes.shim&&1===t.parameters.length&&(s=t.parameters[0])}}return s}function i(r,s,i,a,o=!1){const l={};a.forEach((e=>{var t,n;let r=e.symbol.retType;if(o)if(7==e.symbol.kind)r=e.symbol.namespace;else if(4==e.symbol.kind){const s=null===(n=null===(t=e.symbol.attributes)||void 0===t?void 0:t.enumIdentity)||void 0===n?void 0:n.split(".");(null==s?void 0:s.length)>1&&(r=s[0])}l[r]=[...l[r]||[],e]}));const c=l[r]||[];let u=[];for(let r of c){const a=h(r.symbol,s,e.SymbolFlags.Enum);if(a){const e=i.getTypeOfSymbolAtLocation(a,s),r=t.getEnumMembers(i,e).map((e=>t.enumMemberToQName(i,e))).map((e=>n.lastApiInfo.apis.byQName[e]));u=[...u,...r]}}return[...c,...d(u,1)]}function a(t){return t.flags&e.SymbolFlags.Variable?4:t.flags&e.SymbolFlags.Class?8:t.flags&e.SymbolFlags.Enum?6:t.flags&e.SymbolFlags.EnumMember?7:t.flags&e.SymbolFlags.Method?1:t.flags&e.SymbolFlags.Module?5:t.flags&e.SymbolFlags.Property?2:0}function o(e){return{kind:0,name:e,pyName:e,qName:e,pyQName:e,namespace:"",attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:"any"}}function l(e,t){var n,r;let s=e.getName(),i=/(.*)\.(.*)/.exec(s),o=i?i[2]:s,l=i?i[1]:"",c=null!==(r=null===(n=t.getSymbol())||void 0===n?void 0:n.getName())&&void 0!==r?r:"any";return{kind:a(e),name:o,pyName:o,qName:s,pyQName:s,namespace:l,attributes:{callingConvention:0,paramDefl:{}},fileName:pxt.MAIN_TS,parameters:[],retType:c}}function c(e,t,n){if(e)return t.byQName[n.getFullyQualifiedName(e)]}function u(e,n){return e.weight!==n.weight?n.weight-e.weight:t.compareSymbols(e.symbol,n.symbol)}function p(e,t){return{symbol:e,weight:t}}function d(e,t){return e.map((e=>p(e,t)))}function f(t,n){var r;if(t.flags&e.TypeFlags.NumberLiteral)return"Number";if(t.flags&e.TypeFlags.StringLiteral)return"String";if(t.flags&e.TypeFlags.BooleanLiteral)return"Boolean";const s=n.typeToString(t);return null!==(r={number:"Number",string:"String",boolean:"Boolean"}[s])&&void 0!==r?r:s}function m(e,t){return"."===t.charAt(0)&&(t=t.substr(1)),e.substr(0,e.lastIndexOf(".")+1)+t}function h(e,t,r){const s=n.service&&n.service.getProgram().getTypeChecker();if(!s)return null;const i=s.getSymbolsInScope(t,r);for(let t of i)if(t.escapedName.toString()===e.qName)return t;return null}function g({symbol:e}){return!(/^__/.test(e.name)||/^__/.test(e.namespace)||e.attributes.hidden||e.attributes.deprecated||"TD_ID"==e.attributes.shim||e.attributes.blockAliasFor)}n.getCallSymbol=r,n.getParameter=s,n.getApisForTsType=i,n.getBasicKindDefault=function(e,n){switch(e){case t.SK.StringKeyword:return'""';case t.SK.NumberKeyword:return"0";case t.SK.BooleanKeyword:return n?"False":"false";case t.SK.ArrayType:return"[]";case t.SK.NullKeyword:return n?"None":"null";default:return}},n.tsSymbolToPxtSymbolKind=a,n.makePxtSymbolFromKeyword=o,n.makePxtSymbolFromTsSymbol=l,n.getPxtSymbolFromTsSymbol=c,n.compareCompletionSymbols=u,n.completionSymbol=p,n.completionSymbols=d,n.getNodeAndSymbolAtLocation=function(e,n,r,s){const i=e.getSourceFile(n),a=e.getTypeChecker(),o=t.findInnerMostNodeAtPosition(i,r);if(o){const e=a.getSymbolAtLocation(o);if(e){return[o,c(e,s,a)]}}return null},n.tsTypeToPxtTypeString=f,n.filenameWithExtension=m,n.getWordAtPosition=function(e,t){let n=t,r=t;for(;n>0&&s(n);)--n;for(;r<e.length-1&&s(r);)++r;return n!=r?{text:e.substring(n+1,r),start:n+1,end:r}:null;function s(t){const n=e.charCodeAt(t);return n>=65&&n<=90||n>=97&&n<=122}},n.getTsSymbolFromPxtSymbol=h,n.getDefaultEnumValue=function(e,r){const s=n.service&&n.service.getProgram().getTypeChecker(),i=t.getEnumMembers(s,e);for(const e of i)if(e.name.kind===t.SK.Identifier){const i=t.enumMemberToQName(s,e),a=n.lastApiInfo.apis.byQName[i];return a?a.attributes.alias?r&&a.attributes.pyAlias||a.attributes.alias:r?a.pyQName:a.qName:i}return"0"},n.getCompletions=function(a){var h,b;const{fileName:x,fileContent:y,position:k,wordStartPos:S,wordEndPos:T,runtime:I}=a;let w=y;y&&n.host.setFile(x,y);const E=m(x,"ts"),$={startPos:S,endPos:T},v=/\.py$/.test(x),N={entries:[],isMemberCompletion:!1,isNewIdentifierLocation:!0,isTypeLocation:!1,namespace:[]};let _=w.lastIndexOf("\n",k-1);_=Math.max(0,_);const A=w.substring(_+1,k),K=v?"#":"//";if(A.trim().startsWith(K))return N;let C=-1,U=-1;for(let e=k-1;e>=0;--e){if("."==w[e]){C=e;break}if(!/\w/.test(w[e]))break;-1==U&&(U=e)}C==k-1?w=w.slice(0,k)+"_"+w.slice(k):-1==U&&(w=w.slice(0,k)+"_"+w.slice(k),U=k);const P=-1!==C;N.isMemberCompletion=P;const L=P?w.slice(C+1,T):w.slice(S,T);P&&(U=C);const F={};let M=n.cloneCompileOpts(n.host.opts);M.fileSystem[x]=w,n.addApiInfo(M),M.syntaxInfo={position:U,type:N.isMemberCompletion?"memberCompletion":"identifierCompletion"};let O,D=[];if(v){const e=t.transpile.pyToTs(M);if(e.syntaxInfo&&e.syntaxInfo.symbols&&(D=d(e.syntaxInfo.symbols,1)),e.globalNames&&(n.lastGlobalNames=e.globalNames),!D.length&&e.globalNames&&(D=d(pxt.U.values(e.globalNames),1)),Object.keys(e.outfiles).forEach((t=>{t===E&&n.host.setFile(t,e.outfiles[t])})),e.sourceMap){const n=w,r=e.outfiles[E]||"",s=t.BuildSourceMapHelpers(e.sourceMap,r,n).py.smallestOverlap($);s&&(O=s.ts.startPos)}!P&&D.length>50&&(D=D.filter((e=>(v?e.symbol.pyQName:e.symbol.qName).toLowerCase().indexOf(L.toLowerCase())>=0))),M.ast=!0;t.compile(M,n.service)}else{O=k,M.ast=!0,n.host.setOpts(M);n.runConversionsAndCompileUsingService()}const B=n.service.getProgram(),R=B.getSourceFile(E),q=B.getTypeChecker();let j=t.findInnerMostNodeAtPosition(R,O);if(t.decompiler.buildCommentMap(R).some((e=>e.start<=k&&k<=e.end)))return N;if(j){if([t.SK.StringLiteral,t.SK.FirstTemplateToken,t.SK.NoSubstitutionTemplateLiteral].some((e=>j.kind===e)))return N}N.namespace=t.getCurrentNamespaces(j);let z=!1;if(P){const e=t.findInnerMostNodeAtPosition(R,v?O:C-1);if(e){let t;const r=q.getSymbolAtLocation(e);if(t=(null===(h=null==r?void 0:r.members)||void 0===h?void 0:h.size)>0?q.getDeclaredTypeOfSymbol(r):r?q.getTypeOfSymbolAtLocation(r,e):q.getTypeAtLocation(e),t){const e=t.symbol?q.getFullyQualifiedName(t.symbol):f(t,q);if(e){D=t.getApparentProperties().map((t=>e+"."+t.getName())).map((e=>n.lastApiInfo.apis.byQName[e])).filter((e=>!!e)).map((e=>p(e,1))),z=!0}}}}const V=pxt.U.values(n.lastApiInfo.apis.byQName);if(0===D.length){D=d(V.filter((e=>(v?e.pyQName:e.qName).toLowerCase().indexOf(L.toLowerCase())>=0)),1)}if(!v&&!z){j=t.findInnerMostNodeAtPosition(R,S),j||(j=R.getSourceFile());let r=e.SymbolFlags.Variable,s=q.getSymbolsInScope(j,r),i=j.getText();"_"!==i&&(s=s.filter((e=>e.name.indexOf(i)>=0)));let a=s.map((e=>{let t=c(e,n.lastApiInfo.apis,q);if(!t){t=l(e,q.getTypeOfSymbolAtLocation(e,j))}return t})).filter((e=>!!e)).map((e=>p(e,1)));a.forEach((e=>e.weight+=5)),D=[...D,...a]}const G=t.getParentCallExpression(j);if(G){let e=t.findCurrentCallArgIdx(G,j,O);if(e>=0){const t=n.blocksInfoOp(n.lastApiInfo.apis,I.bannedCategories),a=r(G);if(a){e>=a.parameters.length&&(e=a.parameters.length-1);const n=s(a,e,t);if(n){i(n.type,G,q,D,n.isEnum).forEach((e=>e.weight=10))}}}}if(!P){let e;if(v){let t=pxt.py.keywords;e=Object.keys(t)}else e=[...ts.pxtc.reservedWords,...ts.pxtc.keywordTypes];let t=e.filter((e=>e.indexOf(L)>=0)).map(o).map((e=>p(e,0)));D=[...D,...t]}let H={};H=v&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName,D.map((e=>!e.symbol.attributes.alias||P&&7===e.symbol.kind?e:p(n.lastApiInfo.apis.byQName[e.symbol.attributes.alias],e.weight))).filter(g).forEach((e=>{F[e.symbol.qName]=e})),D=pxt.Util.values(F).filter((e=>!!e&&!!e.symbol)),D.sort(u),a.light&&D.length>100&&(D=D.splice(0,100));const{bannedCategories:J,screenSize:Q}=a.runtime,W={takenNames:H,blocksInfo:n.blocksInfoOp(n.lastApiInfo.apis,J),screenSize:Q,apis:n.lastApiInfo.apis,checker:null===(b=null===n.service||void 0===n.service?void 0:n.service.getProgram())||void 0===b?void 0:b.getTypeChecker()};return D.forEach((t=>function(t,r,s){const i=n.lastApiInfo.decls[t.qName];if(e.isFunctionLike(i)&&(t.snippetAddsDefinitions||r&&!t.pySnippet||!r&&!t.snippet)){const e=n.getSnippet(s,t,i,r),a=n.snippetStringify(e),o=n.snippetStringify(e,!0),l=n.snippetAddsDefinitions(e);r?(t.pySnippet=a,t.pySnippetWithMarkers=o):(t.snippet=a,t.snippetWithMarkers=o),t.snippetAddsDefinitions=l}}(t.symbol,v,W))),N.entries=D.map((e=>e.symbol)),N}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n=function(t){let n=s(t);e.sys.write(n)};function r(e){for(const t of e)n(t)}function s(n){let r;if(void 0!==n.file){let t=n;const{line:s,character:i}=e.getLineAndCharacterOfPosition(t.file,t.start),a=t.file.fileName;r=Object.assign({fileName:a,line:s,column:i},t)}else r=Object.assign({fileName:void 0,line:void 0,column:void 0},n);return function(n){let r="";n.fileName&&(r+=`${n.fileName}(${n.line+1},${n.column+1}): `);let s=e.sys?e.sys.newLine:"\n";const i=t.DiagnosticCategory[n.category].toLowerCase();return r+=`${i} TS${n.code}: ${t.flattenDiagnosticMessageText(n.messageText,s)}${s}`,r}(r)}function i(t,n){const r=e.createCompilerHost(n);return r.getDefaultLibFileName=()=>"node_modules/pxt-core/pxtcompiler/ext-typescript/lib/lib.d.ts",e.createProgram(t,n,r)}function a(e){let n=e.getSyntacticDiagnostics();return 0===n.length&&(n=e.getOptionsDiagnostics().concat(t.Util.toArray(e.getGlobalDiagnostics())),0===n.length&&(n=e.getSemanticDiagnostics())),n.slice(0)}t.getDiagnosticString=s,t.plainTscCompileDir=function(t){const s=e.parseCommandLine([]);let o=e.findConfigFile(t,e.sys.fileExists);const l=function(){let n=e.sys.readFile(o);const i=e.parseConfigFileTextToJson(o,n),a=i.config;if(!a)return r([i.error]),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);const l=e.parseJsonConfigFileContent(a,e.sys,t,s.options,o);if(l.errors.length>0)return r(l.errors),void e.sys.exit(e.ExitStatus.DiagnosticsPresent_OutputsSkipped);return l}();let c=i(l.fileNames,l.options);return a(c).forEach(n),c},t.plainTscCompileFiles=i,t.getProgramDiagnostics=a}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){function n(t){if(!t||!t.kind)return null;switch(t.kind){case e.SyntaxKind.StringKeyword:return"str";case e.SyntaxKind.NumberKeyword:return"number";case e.SyntaxKind.BooleanKeyword:return"bool";case e.SyntaxKind.VoidKeyword:return"None";case e.SyntaxKind.FunctionType:return function(e){let t=n(e.type);return`(${e.parameters.map((e=>e.type)).map(n).join(", ")}) -> ${t}`}(t);case e.SyntaxKind.ArrayType:return`List[${n(t.elementType)}]`;case e.SyntaxKind.TypeReference:{let e=t;return e.typeName&&e.typeName.getText?e.typeName.getText():""}case e.SyntaxKind.AnyKeyword:return"any";default:return pxt.tickEvent("depython.todo.tstypenodetopytype",{kind:t.kind}),""}}function r(t){if(!t||!t.flags)return null;switch(t.flags){case e.TypeFlags.String:return"str";case e.TypeFlags.Number:return"number";case e.TypeFlags.Boolean:return"bool";case e.TypeFlags.Void:return"None";case e.TypeFlags.Any:return"any";default:return pxt.tickEvent("depython.todo.tstypetopytype",{kind:t.flags}),""}}function s(s,i,a){function o(t,n,r=!1){let i=s.getTypeAtLocation(n);if(!i)return"None";r&&(i=i.getCallSignatures()[0].getReturnType());const a=s.typeToString(i,void 0,e.TypeFormatFlags.UseFullyQualifiedType);return/^\d/.test(a)?"number":"this"==a?c(s,i.symbol):a}let l=function(e){switch(e.kind){case t.SK.MethodDeclaration:case t.SK.MethodSignature:return 1;case t.SK.PropertyDeclaration:case t.SK.PropertySignature:case t.SK.GetAccessor:case t.SK.SetAccessor:return 2;case t.SK.Constructor:case t.SK.FunctionDeclaration:return 3;case t.SK.VariableDeclaration:return 4;case t.SK.ModuleDeclaration:return 5;case t.SK.EnumDeclaration:return 6;case t.SK.EnumMember:return 7;case t.SK.ClassDeclaration:return 8;case t.SK.InterfaceDeclaration:return 9;default:return 0}}(a);if(0!=l){let c=a,u=t.parseComments(c);if(u.weight<0)return null;let p,d=/^(.*)\.(.*)/.exec(i),f=3==l||1==l,m=null,h=null,g=e.getSourceFileOfNode(a);if(g){let e=/^pxt_modules\/([^\/]+)/.exec(g.fileName);e&&(m=e[1])}if(8==l||9==l){let e=a;if(p=[],e.heritageClauses)for(let t of e.heritageClauses)if(t.types)for(let e of t.types)p.push(o(0,e))}6!=l&&7!==l||(p||(p=[])).push("Number");let b={kind:l,qName:i,namespace:d?d[1]:"",name:d?d[2]:i,fileName:a.getSourceFile().fileName,attributes:u,pkg:m,pkgs:h,extendsTypes:p,retType:a.kind==e.SyntaxKind.Constructor?"void":5==l?"":o(c.type,c,f),parameters:f?t.Util.toArray(c.parameters).map(((i,a)=>{let l,c,p=t.getName(i),d=u.paramHelp[p]||"",f=u.paramMin&&u.paramMin[p],m=u.paramMax&&u.paramMax[p];/\beg\.?:\s*(.+)/.exec(d);if(i.type&&i.type.kind===t.SK.FunctionType){const n=s.getSignatureFromDeclaration(i.type).getParameters();"objectdestructuring"===u.mutate?(t.assert(n.length>0),l=s.getTypeAtLocation(n[0].valueDeclaration).getProperties().map((e=>({name:e.getName(),type:s.typeToString(s.getTypeOfSymbolAtLocation(e,n[0].valueDeclaration))})))):c=n.map(((t,n)=>({name:t.getName(),type:s.typeToString(s.getTypeOfSymbolAtLocation(t,i),void 0,e.TypeFormatFlags.UseFullyQualifiedType)})))}let h={};const g=s.getTypeAtLocation(i);let b=g&&!!(g.flags&(e.TypeFlags.Enum|e.TypeFlags.EnumLiteral));if(u.block&&u.paramShadowOptions){const e=[];u.block.replace(/%(\w+)/g,((t,n)=>(e.push(n),""))),u.paramShadowOptions[e[a]]&&(h.fieldEditorOptions={value:u.paramShadowOptions[e[a]]})}f&&(h.min={value:f}),m&&(h.max={value:m});const x=i.type&&n(i.type)||g&&r(g)||"unknown",y=i.initializer?i.initializer.getText():t.getExplicitDefault(u,p)||(i.questionToken?"undefined":void 0);return{name:p,description:d,type:o(i.type,i),pyTypeString:x,initializer:y,default:u.paramDefl[p],properties:l,handlerParameters:c,options:h,isEnum:b}})):null,snippet:e.isFunctionLike(a)?null:void 0};switch(b.kind){case 7:b.pyName=t.U.snakify(b.name).toUpperCase();break;case 4:case 1:case 2:case 3:b.pyName=t.U.snakify(b.name);break;case 6:case 8:case 9:case 5:default:b.pyName=b.name}return(a.kind===t.SK.GetAccessor||(a.kind===t.SK.PropertyDeclaration||a.kind===t.SK.PropertySignature)&&t.isReadonly(a))&&(b.isReadOnly=!0),b}return null}function i(e){return!!e.attributes.block&&!!e.attributes.blockId}let a;function o(e,n){function r(t){return-t(e)+t(n)}let s=r((e=>i(e)?1:-1));return s||(s=r((e=>e.namespace?-1:1)),s||(a||(a={},a[4]=100,a[5]=101,a[3]=99,a[2]=98,a[1]=97,a[8]=89,a[6]=81,a[7]=80),s=r((e=>a[e.kind]||0)),s||(s=r((e=>e.attributes.weight||50)),s||t.U.strcmp(e.name,n.name))))}function l(e,n,r=!1){const i={byQName:{},jres:n},a={},o=e.getTypeChecker(),l=e=>{var n,r;if(e.kind!=t.SK.VariableStatement){if(t.isExported(e)){if(!e.symbol)return void console.warn("no symbol",e);let l=c(o,e.symbol);e.kind==t.SK.SetAccessor&&(l+="@set"),a[l]=e;let u=s(o,l,e);if(u){let s=t.U.lookup(i.byQName,l);if(s)if(9==s.kind&&9!=u.kind)i.byQName[l+"@type"]=s;else if(9!=s.kind&&9==u.kind)i.byQName[l+"@type"]=u,u=s;else{const e=null===(n=s.attributes._source)||void 0===n?void 0:n.trim(),i=null===(r=u.attributes._source)||void 0===r?void 0:r.trim();let a=e+"\n"+i;e&&(null==i?void 0:i.indexOf(e))>=0?a=i:i&&(null==e?void 0:e.indexOf(i))>=0&&(a=e),u.attributes=t.parseCommentString(a),5===s.kind&&(u.pkgs=s.pkgs||[],s.pkg!==u.pkg&&(u.pkgs.find((e=>e===s.pkg))||u.pkgs.push(s.pkg))),s.extendsTypes&&(u.extendsTypes=u.extendsTypes||[],s.extendsTypes.forEach((e=>{-1===u.extendsTypes.indexOf(e)&&u.extendsTypes.push(e)})))}!e.parent||e.parent.kind!=t.SK.ClassDeclaration&&e.parent.kind!=t.SK.InterfaceDeclaration||t.isStatic(e)||(u.isInstance=!0),i.byQName[l]=u}}if(e.kind==t.SK.ModuleDeclaration){let n=e;if(n.body.kind==t.SK.ModuleBlock){n.body.statements.forEach(l)}else n.body.kind==t.SK.ModuleDeclaration&&l(n.body)}else if(e.kind==t.SK.InterfaceDeclaration){e.members.forEach(l)}else if(e.kind==t.SK.ClassDeclaration){e.members.forEach(l)}else if(e.kind==t.SK.EnumDeclaration){e.members.forEach(l)}}else{e.declarationList.declarations.forEach(l)}};for(let t of e.getSourceFiles())t.statements.forEach(l);let u=[];for(let e in i.byQName){let r=i.byQName[e];r.qName=e,r.attributes._source=null,r.extendsTypes&&r.extendsTypes.length&&u.push(r);let s=r.attributes.jres;if(s){"true"==s&&(s=e);let i=t.U.lookup(n||{},s);i&&i.icon&&!r.attributes.iconURL&&(r.attributes.iconURL=i.icon),i&&i.data&&!r.attributes.jresURL&&(r.attributes.jresURL="data:"+i.mimeType+";base64,"+i.data)}if(r.pyName){let e=t.U.lookup(t.ts2PyFunNameMap,r.qName);if(e&&e.n)r.pyQName=e.n,r.pySnippet=e.snippet,r.pySnippetName=e.n,r.pySnippetWithMarkers=void 0;else if(r.namespace){let e=i.byQName[r.namespace];e?r.pyQName=e.pyQName+"."+r.pyName:(pxt.log("namespace missing: "+r.namespace),r.pyQName=r.namespace+"."+r.pyName)}else r.pyQName=r.pyName}}let p={},d=e=>{if(t.U.lookup(p,e.qName))return;p[e.qName]=!0;let n={};n[e.qName]=!0;for(let t of e.extendsTypes||[]){n[t]=!0;let e=i.byQName[t];if(e){d(e);for(let t of e.extendsTypes)n[t]=!0}}e.extendsTypes=Object.keys(n)};return u.forEach(d),r&&delete i.byQName["Array.map"],{apis:i,decls:a}}function c(e,t){return t.isBogusSymbol?t.name:e.getFullyQualifiedName(t)}t.placeholderChar="◊",t.ts2PyFunNameMap={"Math.trunc":{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:"int(0)"},"Math.min":{n:"min",t:e.SyntaxKind.NumberKeyword,snippet:"min(0, 0)"},"Math.max":{n:"max",t:e.SyntaxKind.NumberKeyword,snippet:"max(0, 0)"},"Math.abs":{n:"abs",t:e.SyntaxKind.NumberKeyword,snippet:"abs(0)"},"console.log":{n:"print",t:e.SyntaxKind.VoidKeyword,snippet:'print(":)")'},".length":{n:"len",t:e.SyntaxKind.NumberKeyword},".toLowerCase()":{n:"string.lower",t:e.SyntaxKind.StringKeyword},".toUpperCase()":{n:"string.upper",t:e.SyntaxKind.StringKeyword},".charCodeAt(0)":{n:"ord",t:e.SyntaxKind.NumberKeyword},"pins.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"pins.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"control.createBuffer":{n:"bytearray",t:e.SyntaxKind.Unknown},"control.createBufferFromArray":{n:"bytes",t:e.SyntaxKind.Unknown},"!!":{n:"bool",t:e.SyntaxKind.BooleanKeyword},"Array.indexOf":{n:"Array.index",t:e.SyntaxKind.Unknown},"Array.push":{n:"Array.append",t:e.SyntaxKind.Unknown},parseInt:{n:"int",t:e.SyntaxKind.NumberKeyword,snippet:'int("0")'},"_py.range":{n:"range",t:e.SyntaxKind.Unknown,snippet:"range(4)"}},t.emitPyTypeFromTypeNode=n,t.emitPyTypeFromTsType=r,t.genDocs=function(n,r,s={}){pxt.debug(`generating docs for ${n}`),pxt.debug(JSON.stringify(Object.keys(r.byQName),null,2));const i={},a=t.Util.values(r.byQName),l=a.filter((e=>7==e.kind)).sort(o),c={},u={},p={},d=t=>{if(s.locs&&t.qName&&!/^__/.test(t.name)){if(pxt.debug(`loc: ${t.qName}`),7!=t.kind){const n=e.pxtc.blocksCategory(t);n&&(u[`{id:category}${n}`]=n)}t.attributes.jsDoc&&(p[t.qName]=t.attributes.jsDoc),t.attributes.block&&(u[`${t.qName}|block`]=t.attributes.block),t.attributes.group&&(u[`{id:group}${t.attributes.group}`]=t.attributes.group),t.attributes.subcategory&&(u[`{id:subcategory}${t.attributes.subcategory}`]=t.attributes.subcategory),t.parameters&&t.parameters.filter((e=>!!e.description)).forEach((e=>{p[`${t.qName}|param|${e.name}`]=e.description}))}},f=(e,t)=>{if(!s.locs)return;const r={};Object.keys(e).sort().forEach((t=>r[t]=e[t])),i[n+t+"-strings.json"]=JSON.stringify(r,null,2)};for(const e of a){if(5==e.kind){if(!a.filter((t=>t.namespace==e.name&&!!t.attributes.jsDoc))[0])continue;e.attributes.block||(e.attributes.block=e.name)}d(e)}return s.locs&&l.forEach((e=>{e.attributes.block&&(u[`${e.qName}|block`]=e.attributes.block),e.attributes.jsDoc&&(u[e.qName]=e.attributes.jsDoc)})),f(u,""),f(p,"-jsdoc"),s.pxtsnippet&&(s.pxtsnippet.forEach((e=>function(e,t){const n=["label","title","hint","errorMessage"];t[e.label]=e.label,e.questions.forEach((e=>{n.forEach((n=>{e[n]&&(t[e[n]]=e[n])}))}))}(e,c))),f(c,"-snippet")),i},t.hasBlock=i,t.compareSymbols=o,t.getApiInfo=function(e,t,n=!1){return l(e,t,n).apis},t.internalGetApiInfo=l,t.getFullName=c}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){let r,s,i={fileSystem:{},sourceFiles:[],target:{isNative:!1,hasHex:!1,switches:{}}};class a{constructor(){this.opts=i,this.fileVersions={},this.projectVer=0,this.pxtModulesOK=null}getProjectVersion(){return this.projectVer+""}setFile(e,t){this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1,this.opts.fileSystem[e]=t,this.projectVer++)}reset(){this.setOpts(i),this.pxtModulesOK=null}setOpts(e){t.Util.iterMap(e.fileSystem,((e,t)=>{this.opts.fileSystem[e]!=t&&(this.fileVersions[e]=(this.fileVersions[e]||0)+1)})),this.opts=Object.assign(Object.assign({},e),{fileSystem:Object.assign({},e.fileSystem)}),this.projectVer++}getCompilationSettings(){return t.getTsCompilerOptions(this.opts)}getScriptFileNames(){return this.opts.sourceFiles.filter((e=>t.U.endsWith(e,".ts")))}getScriptVersion(e){return(this.fileVersions[e]||0).toString()}getScriptSnapshot(t){let n=this.opts.fileSystem[t];return null!=n?e.ScriptSnapshot.fromString(n):null}getNewLine(){return"\n"}getCurrentDirectory(){return"."}getDefaultLibFileName(e){return"no-default-lib.d.ts"}log(e){console.log("LOG",e)}trace(e){console.log("TRACE",e)}error(e){console.error("ERROR",e)}useCaseSensitiveFileNames(){return!0}}function o(e,r){return e?(n.lastLocBlocksInfo||(n.lastLocBlocksInfo=t.getBlocksInfo(e,r)),n.lastLocBlocksInfo):(n.lastBlocksInfo||(n.lastBlocksInfo=t.getBlocksInfo(n.lastApiInfo.apis,r)),n.lastBlocksInfo)}function l(e){return n.lastApiInfo||(n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),e.jres)),n.lastApiInfo}function c(e){if(!e.apisInfo){const n=l(e);e.apisInfo=t.U.clone(n.apis)}}function u(e){let t=pxt.U.flatClone(e);return t.fileSystem=pxt.U.flatClone(t.fileSystem),t}n.blocksInfoOp=o,n.getLastApiInfo=l,n.addApiInfo=c,n.cloneCompileOpts=u,n.IsOpErr=function(e){return!!e.errorMessage};const p={reset:()=>{n.service=e.createLanguageService(n.host),n.lastApiInfo=void 0,n.lastGlobalNames=void 0,n.host.reset()},setOptions:e=>{n.host.setOpts(e.options)},syntaxInfo:e=>{var r,s,i;let a=e.fileContent;e.fileContent&&n.host.setFile(e.fileName,e.fileContent);let o=u(n.host.opts);o.fileSystem[e.fileName]=a,c(o),o.syntaxInfo={position:e.position,type:e.infoType};const p=e.fileName.endsWith(".py"),f="symbol"===o.syntaxInfo.type,m="signature"===o.syntaxInfo.type;if(p){let e=t.transpile.pyToTs(o);e.globalNames&&(n.lastGlobalNames=e.globalNames)}else{o.ast=!0,n.host.setOpts(o);d();const s=n.service.getProgram(),i=s.getSourceFile(e.fileName),a=s.getTypeChecker();if(f||m){let s=t.findInnerMostNodeAtPosition(i,e.position);if(s)if(f){const e=a.getSymbolAtLocation(s);if(e){let t=n.getPxtSymbolFromTsSymbol(e,o.apisInfo,a);o.syntaxInfo.symbols=[t],o.syntaxInfo.beginPos=s.getStart(),o.syntaxInfo.endPos=s.getEnd()}}else if(m){const n=null===(r=null==s?void 0:s.pxt)||void 0===r?void 0:r.callInfo;if(n){const r=o.apisInfo.byQName[n.qName];o.syntaxInfo.symbols=[r],o.syntaxInfo.beginPos=s.getStart(),o.syntaxInfo.endPos=s.getEnd();const i=t.getParentCallExpression(s);if(i){const n=t.findCurrentCallArgIdx(i,s,e.position);o.syntaxInfo.auxResult=n}}}}}if(f&&!(null===(s=o.syntaxInfo.symbols)||void 0===s?void 0:s.length)){const r=n.getWordAtPosition(e.fileContent,e.position);if(r)if(p&&"range"===r.text){const e=l(o).apis;e.byQName["_py.range"]&&(o.syntaxInfo.symbols=[e.byQName["_py.range"]],o.syntaxInfo.beginPos=r.start,o.syntaxInfo.endPos=r.end)}else{const e=t.getHelpForKeyword(r.text,p);e&&(o.syntaxInfo.auxResult={documentation:e,displayString:n.displayStringForKeyword(r.text,p)},o.syntaxInfo.beginPos=r.start,o.syntaxInfo.endPos=r.end)}}if(null===(i=o.syntaxInfo.symbols)||void 0===i?void 0:i.length){const e=l(o).apis;p&&(o.syntaxInfo.symbols=o.syntaxInfo.symbols.map((t=>e.byQName[t.qName]||t))),f&&(o.syntaxInfo.auxResult=o.syntaxInfo.symbols.map((t=>n.displayStringForSymbol(t,p,e))))}return o.syntaxInfo},getCompletions:e=>n.getCompletions(e),compile:e=>{n.host.setOpts(e.options);const r=d();return t.timesToMs(r),r},decompile:e=>(n.host.setOpts(e.options),t.decompile(n.service.getProgram(),e.options,e.fileName,!1)),pydecompile:e=>(n.host.setOpts(e.options),t.transpile.tsToPy(n.service.getProgram(),e.fileName)),decompileSnippets:e=>(n.host.setOpts(e.options),t.decompileSnippets(n.service.getProgram(),e.options,!1)),assemble:e=>({words:t.processorInlineAssemble(n.host.opts.target,e.fileContent)}),py2ts:e=>(c(e.options),t.transpile.pyToTs(e.options)),fileDiags:e=>t.patchUpDiagnostics(function(e){if(!/\.ts$/.test(e))return[];let t=n.service.getSyntacticDiagnostics(e);return t&&t.length||(t=n.service.getSemanticDiagnostics(e)),t||(t=[]),t}(e.fileName)),allDiags:()=>{let e=d();return t.timesToMs(e),n.host.opts.target.switches.time&&console.log("DIAG-TIME",e.times),e},format:e=>{const n=e.format;return t.format(n.input,n.pos)},apiInfo:()=>{if(n.lastBlocksInfo=void 0,r=void 0,n.host.opts!==i)return n.lastApiInfo=t.internalGetApiInfo(n.service.getProgram(),n.host.opts.jres),n.lastApiInfo.apis},snippet:t=>{const r=t.snippet;if(!n.lastApiInfo)return;const s=n.lastApiInfo.apis.byQName[r.qName],i=n.lastApiInfo.decls[r.qName];if(!s||!i||!e.isFunctionLike(i))return;const a=!!r.python;let l={};l=a&&n.lastGlobalNames?n.lastGlobalNames:n.lastApiInfo.apis.byQName;const{bannedCategories:c,screenSize:u}=t.runtime,{apis:p}=n.lastApiInfo,d={apis:p,blocksInfo:o(p,c),takenNames:l,bannedCategories:c,screenSize:u,checker:n.service&&n.service.getProgram().getTypeChecker()},f=n.getSnippet(d,s,i,a);return n.snippetStringify(f)},blocksInfo:e=>o(e,e.blocks&&e.blocks.bannedCategories),apiSearch:e=>{const t=e.search,s=o(t.localizedApis,e.blocks&&e.blocks.bannedCategories);t.localizedStrings&&pxt.Util.setLocalizedStrings(t.localizedStrings);const i=(e,t,n)=>{if(e)return"string"==typeof e?e:t?e[t]:Object.keys(e).map((t=>e[t])).join(" ")},a=e=>{var t;if(null===(t=e.attributes)||void 0===t?void 0:t._def){let t=[];const n=e.attributes._def,r=pxt.blocks.compileInfo(e);for(let e of n.parts)switch(e.kind){case"label":t.push(e.text);break;case"param":let n=r.definitionNameToParam[e.name];t.push((null==n?void 0:n.defaultValue)||e.varName||(null==n?void 0:n.actualName)||e.name)}return t.join(" ")}return e.attributes.block},l=e=>{var t;const n=null===(t=e.attributes)||void 0===t?void 0:t.paramHelp;return n&&Object.keys(n).map((e=>n[e])).join(" "),""};if(!n.builtinItems){n.builtinItems=[],n.blockDefinitions=pxt.blocks.blockDefinitions();for(const e in n.blockDefinitions){const t=n.blockDefinitions[e];if(t.operators)for(const r in t.operators){t.operators[r].forEach((s=>n.builtinItems.push({id:e,name:t.name,jsdoc:"string"==typeof t.tooltip?t.tooltip:t.tooltip[s],block:s,field:[r,s],builtinBlock:!0})))}else n.builtinItems.push({id:e,name:t.name,jsdoc:i(t.tooltip,t.tooltipSearch),block:i(t.block,t.blockTextSearch),builtinBlock:!0})}}let c;if(!r||t.subset){const e={};let i=[];t.subset&&(n.tbSubset=t.subset,i=n.builtinItems.filter((e=>!!n.tbSubset[e.id]))),n.tbSubset?c=s.blocks.filter((e=>!!n.tbSubset[e.attributes.blockId])):(c=s.blocks,i=n.builtinItems);let o=c.map((e=>({id:e.attributes.blockId,qName:e.qName,name:e.name,namespace:e.namespace,block:a(e),params:l(e),jsdoc:e.attributes.jsDoc,localizedCategory:n.tbSubset&&"string"==typeof n.tbSubset[e.attributes.blockId]?n.tbSubset[e.attributes.blockId]:void 0}))),u={};i.forEach((e=>u[e.id]=!0)),o=o.filter((e=>!(e.id in u)));let p=0;c.forEach((t=>{const n=e[t.qName]=(e=>{const t=e.attributes.weight||50,n=s.apis.byQName[e.namespace];return(1e3*(n&&n.attributes.weight||50)+t)*(n&&n.attributes.advanced||e.attributes.advanced?1:1e6)})(t);p=Math.max(p,n)})),o=o.concat(i);r=new Fuse(o,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3},{name:"namespace",weight:.1},{name:"localizedCategory",weight:.1},{name:"block",weight:.4375},{name:"params",weight:.0625},{name:"jsdoc",weight:.0625}],sortFn:function(t,n){const r=t.qName?1-e[t.item.qName]/p:1,s=n.qName?1-e[n.item.qName]/p:1;return t.score*(1+r/10)-n.score*(1+s/10)}})}return r.search(t.term).slice(0,7)},projectSearch:e=>{const t=e.projectSearch,n=t.headers;if(!s){s=new Fuse(n,{shouldSort:!0,threshold:.6,location:0,distance:100,maxPatternLength:16,minMatchCharLength:2,findAllMatches:!1,caseSensitive:!1,keys:[{name:"name",weight:.3}]})}return s.search(t.term)},projectSearchClear:()=>{s=void 0}};function d(){c(n.host.opts);const e=t.U.flatClone(n.host.opts.fileSystem);let r=t.runConversionsAndStoreResults(n.host.opts);(null==r?void 0:r.globalNames)&&(n.lastGlobalNames=r.globalNames);const s=n.host.opts.fileSystem;n.host.opts.fileSystem=e;for(let e of Object.keys(s))n.host.setFile(e,s[e]);if(0==r.diagnostics.length){n.host.opts.skipPxtModulesEmit=!1,n.host.opts.skipPxtModulesTSC=!1;const e=n.host.opts.target.isNative?"native":"js";!n.host.opts.target.switches.noIncr&&n.host.pxtModulesOK&&(n.host.opts.skipPxtModulesTSC=!0,n.host.opts.noEmit?n.host.opts.skipPxtModulesEmit=!0:n.host.opts.target.isNative?n.host.opts.skipPxtModulesEmit=!1:"js"!=n.host.pxtModulesOK||n.host.opts.breakpoints&&!n.host.opts.justMyCode||(n.host.opts.skipPxtModulesEmit=!0));let s=t.compile(n.host.opts,n.service);if(r=Object.assign({sourceMap:r.sourceMap},s),(r.needsFullRecompile||(!r.success||r.diagnostics.length)&&n.host.opts.clearIncrBuildAndRetryOnError)&&(pxt.debug("triggering full recompile"),pxt.tickEvent("compile.fullrecompile"),n.host.opts.skipPxtModulesEmit=!1,s=t.compile(n.host.opts,n.service),r=Object.assign({sourceMap:r.sourceMap},s)),r.diagnostics.every((e=>!t.isPxtModulesFilename(e.fileName)))&&(n.host.pxtModulesOK=e),r.ast){let e=t.internalGetApiInfo(r.ast);e&&(n.lastApiInfo=e)}}return r}n.runConversionsAndCompileUsingService=d,n.performOperation=function(t,r){n.service||(n.host=new a,n.service=e.createLanguageService(n.host));let s=null;if(p.hasOwnProperty(t))try{s=(0,p[t])(r)||{}}catch(e){s={errorMessage:e.stack}}else s={errorMessage:"No such operation: "+t};return s}}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){!function(n){function r(e){return"object"==typeof e&&void 0!==e.default}function s(e){return"object"==typeof e&&"number"==typeof e.length}function i(e,t=!1){const n={};let o=1;return function e(l){if(r(l)){if(t){if(a(l.default))return e(l.default);const t=i(l.default,!1);let r=n[t];if(r&&!l.isLiteral||(r=o,o++,n[t]=r),t.indexOf(".")>=0&&t.indexOf(" ")<0){let e=t.split(".");return e[e.length-1]="${"+r+":"+e[e.length-1]+"}",e.join(".")}return"${"+r+":"+t+"}"}return e(l.default)}return s(l)?l.map((t=>e(t))).join(""):l}(e)}function a(e){return!!r(e)||!!s(e)&&e.map(a).reduce(((e,t)=>e||t),!1)}function o(e){return e.attributes.shim&&"@"==e.attributes.shim[0]||e.attributes.pyConvertToTaggedTemplate}n.snippetStringify=i,n.snippetHasReplacementPoints=a,n.snippetAddsDefinitions=function e(t){return r(t)?t.isDefinition||e(t.default):!!s(t)&&t.map(e).reduce(((e,t)=>e||t),!1)},n.getSnippet=function r(s,a,l,c,u=0){var p,d;let{apis:f,takenNames:m,blocksInfo:h,screenSize:g,checker:b}=s;const x=pxt.py.INDENT,y=c?"python":"typescript";let k=a.namespace,S=!1,T="",I=0,w=[];if(o(a))return c?`${a.name}(""" """)`:`${a.name}\`\``;let E="";E=l.kind==t.SK.Constructor?D(l.symbol)||l.parent.name.getText():D(l.symbol)||l.name.getText(),c&&(E=t.U.snakify(E));const $=a.attributes;if("TD_ID"===$.shim&&u&&l.parameters.length)return M(l.parameters[0]);const v=a,N=pxt.blocks.compileInfo(v),_=h.blocksById,A=(null===(p=$._def)||void 0===p?void 0:p.parameters.filter((e=>!!N.definitionNameToParam[e.name])).map((e=>N.definitionNameToParam[e.name].actualName)))||[],K=l.parameters?l.parameters.filter((e=>!e.initializer&&!e.questionToken||A.indexOf(e.name.getText())>=0)):[],C=K.map(M).map((e=>({default:e,isLiteral:!0})));if(v.attributes.block)if(v.attributes.defaultInstance)k=v.attributes.defaultInstance,c&&k&&(k=t.U.snakify(k));else if("variables_get"===(null===(d=N.thisParameter)||void 0===d?void 0:d.shadowBlockId))k=N.thisParameter.defaultValue||N.thisParameter.definitionName,c&&k&&(k=t.U.snakify(k));else if(v.namespace){const e=f.byQName[v.namespace];if(e.attributes.fixedInstances){let n,r=t.Util.values(f.byQName),s=function(e){return r.filter((e=>e.extendsTypes)).filter((t=>t.extendsTypes.reduce(((t,n)=>t||-1!=n.indexOf(e)),!1))).reduce(((e,t)=>e.concat(t.extendsTypes)),[])},i=r.filter((e=>4===e.kind&&e.attributes.fixedInstance));const a=i.filter((t=>t.retType==e.qName)).sort(((e,t)=>e.name.localeCompare(t.name)));if(a.length)n=a[0];else{n=i.filter((t=>-1!==s(e.qName).indexOf(t.retType))).sort(((e,t)=>e.name.localeCompare(t.name)))[0]}n?(k=`${B(n)}`,T=n.namespace):T=e.namespace,T&&(S=!0)}else if(1==v.kind||2==v.kind){if(N.thisParameter){let e;N.thisParameter.definitionName&&(e=N.thisParameter.definitionName,e=e[0].toUpperCase()+e.substring(1),e=`my${e}`),k=N.thisParameter.defaultValue||e,c&&k&&(k=t.U.snakify(k))}}else if(8===e.kind)return}const U=$&&(c?$.pySnippet:$.snippet);let P;if(U)P=[U],k=void 0;else if(P=[E],(null==C?void 0:C.length)||1==v.kind||3==v.kind||8==v.kind){const e=C.reduce(((e,t)=>[...e,e.length?", ":"",t]),[]);P=P.concat(["(",...e,")"])}let L=k?[k,".",...P]:P;if(L=S?[function(e){const t=e.indexOf(".");return t<0?e:e.substring(0,t)}(T),".",...L]:L,$&&$.blockSetVariable)if(c){L=[{default:F(t.U.snakify($.blockSetVariable)),isDefinition:!0}," = ",...L]}else{L=["let ",{default:F($.blockSetVariable),isDefinition:!0}," = ",...L]}return[w,L];function F(t){return m[t]?e.pxtc.decompiler.getNewName(t,m,!1):t}function M(i){var o,l;const p=i.type;if(!p)return c?"None":"null";const d=i.name.kind===t.SK.Identifier?i.name.text:void 0,m=null===(o=$.paramSnippets)||void 0===o?void 0:o[d];if(m)if(c){if(m.python)return m.python}else if(m.ts)return m.ts;const h=null===(l=null==$?void 0:$.paramDefl)||void 0===l?void 0:l[d];if(h){let e;if(p.kind==t.SK.AnyKeyword){const n=h.toUpperCase();e=Number.isNaN(+n)?"FALSE"==n||"TRUE"==n?t.SK.BooleanKeyword:n.includes(".")?t.SK.EnumKeyword:t.SK.StringKeyword:t.SK.NumberKeyword}if(p.kind===t.SK.StringKeyword||e===t.SK.StringKeyword)return 0!=h.indexOf('"')?`"${h}"`:h;const r=null==b?void 0:b.getTypeAtLocation(i),s=n.getPxtSymbolFromTsSymbol(null==r?void 0:r.symbol,f,b);return((null==s?void 0:s.attributes.fixedInstances)||(null==s?void 0:s.attributes.emitAsConstant))&&c?pxt.Util.snakify(h):c?t.tsSnippetToPySnippet(h,s):h}let x=function(e){var t,n;const r=pxt.blocks.compileInfo(a),s=null===(t=r.parameters)||void 0===t?void 0:t.find((t=>t.actualName===e));if(!(null==s?void 0:s.shadowBlockId))return null;let i=_[s.shadowBlockId];if(!i)return null;const o=null===(n=i.attributes)||void 0===n?void 0:n.paramFieldEditor;if(!o)return null;const l=o[e];if(!l)return null;const c=i.attributes.paramFieldEditorOptions||{};switch(l){case"sprite":return function(e){const t={initColor:0,initWidth:16,initHeight:16};if(null==e?void 0:e.sizes){const n=e.sizes.split(";"),r=[];for(let e=0;e<n.length;e++){const t=n[e].split(",");if(2!==t.length)continue;let s=parseInt(t[0]),i=parseInt(t[1]);isNaN(s)||isNaN(i)||(s<0&&g&&(s=g.width),i<0&&g&&(i=g.height),r.push([s,i]))}r.length>0&&(t.initWidth=r[0][0],t.initHeight=r[0][1])}return t.initColor=n(null==e?void 0:e.initColor,t.initColor),t.initWidth=n(null==e?void 0:e.initWidth,t.initWidth),t.initHeight=n(null==e?void 0:e.initHeight,t.initHeight),pxt.sprite.imageLiteralFromDimensions(t.initWidth,t.initHeight,t.initColor,y);function n(e,t){const n=parseInt(e);return isNaN(n)?t:n}}(c[e])}return null}(d);if(x)return x;let k=function(e){let t=($._shadowOverrides||{})[e];if(!t){const n=pxt.blocks.compileInfo(a);for(const r of n.parameters)if(r.actualName===e){t=r.shadowBlockId;break}}if(!t)return null;let n=_[t];if(!n)return null;if("TD_ID"===n.attributes.shim&&n.parameters.length){let e=n.parameters[0].type;n=f.byQName[e]||n}return n}(d);if(k){let o=n.getTsSymbolFromPxtSymbol(k,i,e.SymbolFlags.Enum);if(o){let e=b.getTypeOfSymbolAtLocation(o,i);if(e){let t=O(e);if(t)return t}}const l=k.attributes;if("KIND_GET"===l.shim&&l.blockId){const e=l.kindNamespace||a.namespace,n=t.Util.values(f.byQName).find((t=>t.namespace===e&&t.attributes.isKind));if(n)return c?n.pyQName:n.qName}if(u<3&&n.lastApiInfo.decls[k.qName]){let e=r(s,k,n.lastApiInfo.decls[k.qName],c,u+1);if(e)return e}}if(p.kind===t.SK.StringKeyword&&"leds"===d)return c?'"""\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n"""':"`\n. . . . .\n. . . . .\n. . # . .\n. . . . .\n. . . . .\n`";if(p.kind===t.SK.FunctionType){const e=p;let t=b?b.getSignatureFromDeclaration(e):void 0;return t?R(t,!0):q(d)}const S=n.getBasicKindDefault(p.kind,c);if(void 0!==S)return S;let T=b&&b.getTypeAtLocation(i);if(T){let e=O(T);if(e)return e}return c?"None":"null"}function O(r){if(r.symbol&&r.symbol.flags&e.SymbolFlags.Enum){return n.getDefaultEnumValue(r,c)}const s=n.getPxtSymbolFromTsSymbol(r.symbol,f,b);if(t.isObjectType(r)){const t=s&&s.attributes&&(c?s.attributes.pySnippet:s.attributes.snippet);if(t)return t;if(r.objectFlags&e.ObjectFlags.Anonymous){const t=b.getSignaturesOfType(r,e.SignatureKind.Call);return t&&t.length?R(t[0],!1):q()}}if(r.flags&e.TypeFlags.NumberLike)return"0";if(s&&s.attributes.fixedInstances){const e=function(e){return pxt.Util.values(f.byQName).filter((t=>4===t.kind&&t.attributes.fixedInstance&&function(e,t,n){if(t==n)return!0;let r=e.byQName[t];return!(!r||!r.extendsTypes)&&r.extendsTypes.indexOf(n)>=0}(f,t.retType,e.qName)))}(s);if(e.length){const t=e[0];return c?t.pyQName:t.qName}}}function D(e){if(b){const n=t.getFullName(b,e),r=f.byQName[n];if(r)return B(r)}}function B(e){return c?e.pyName:e.name}function R(n,r){let s="",a=b.getReturnTypeOfSignature(n);if(a.flags&e.TypeFlags.NumberLike?s="return 0":a.flags&e.TypeFlags.StringLike?s='return ""':a.flags&(e.TypeFlags.Boolean|e.TypeFlags.BooleanLiteral)&&(s=c?"return False":"return false"),c){let a;a=$.optionalVariableArgs?"()":`(${n.parameters.map((e=>e.name)).join(", ")})`;let o=E||"fn";I++>0&&(o+=I),r&&!/^on/i.test(o)&&(o="on"+pxt.Util.capitalize(o));const l=K.filter((t=>{const n=b&&b.getTypeAtLocation(t);return!!(n&&n.symbol&&n.symbol.flags&e.SymbolFlags.Enum)})).map((e=>{const t=i(M(e)).toLowerCase(),n=t.lastIndexOf(".");return-1!==n?t.substr(n+1):t})).join("_");return l&&(o+="_"+l),o=t.U.snakify(o),o=F(o),w=[...w,w.length?"\n":"","def ",{default:o,isDefinition:!0},a,`:\n${x}`,{default:s||"pass"},"\n"],{default:o}}{let t="()";if(!$.optionalVariableArgs){let r=e.mapToDisplayParts((t=>{b.getSymbolDisplayBuilder().buildSignatureDisplay(n,t,void 0,e.TypeFormatFlags.UseFullyQualifiedType)})),s=e.displayPartsToString(r);t=s.substr(0,s.lastIndexOf(":"))}return["function",t,` {\n${x}`,{default:s},"\n}"]}}function q(e){return c?(e=e||"fn",e=F(e=t.U.snakify(e)),w=[...w,w.length?"\n":"","def ",{default:e,isDefinition:!0},`():\n${x}`,{default:"pass"},"\n"],{default:e}):"function () {}"}},n.isTaggedTemplate=o}(t.service||(t.service={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(e){const t=e=>`main.${e}`;e.pyToTs=function(e,n=t("py")){return pxt.py.py2ts(e)},e.tsToPy=function(e,n=t("ts")){return pxt.py.decompileToPython(e,n)}}(e.transpile||(e.transpile={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(t){let n;function r(e,t){if(!e)return;const s=t(e);if(s===n.Continue)return r(e.parent,t);if(s===n.Abort)return;if(s===n.Found)return e;return s}function s(t){return r(t,(t=>e.isModuleDeclaration(t)?n.Found:n.Continue))}t.getParentCallExpression=function(t){return r(t,(t=>e.isCallExpression(t)?n.Found:e.isBlock(t)?n.Abort:n.Continue))},t.findCurrentCallArgIdx=function(e,t,n){let r=e.arguments.map((e=>e===t)).indexOf(!0);if(r>=0)return r;if(!(e.arguments.pos<=n&&n<e.end))return-1;if(0===e.arguments.length)return 0;r=0;for(let t of e.arguments){if(!(t.end<=n))break;r++}return e.arguments.hasTrailingComma||(r=Math.max(0,r-1)),r},function(e){e[e.Found=0]="Found",e[e.Continue=1]="Continue",e[e.Abort=2]="Abort"}(n=t.TraverseCheck||(t.TraverseCheck={})),t.traverseUp=r,t.enumMemberToQName=function(e,n){if(n.name.kind===t.SK.Identifier)return e.getFullyQualifiedName(e.getSymbolAtLocation(n.name))},t.findInnerMostNodeAtPosition=function n(r,s){for(let t of r.getChildren()){if(t.kind>=e.SyntaxKind.FirstPunctuation&&t.kind<=e.SyntaxKind.LastPunctuation)continue;let r=t.getStart(),i=t.getEnd();if(r<=s&&s<i)return n(t,s)}return r&&r.kind===t.SK.SourceFile?null:r},t.getParentNamespace=s,t.getCurrentNamespaces=function e(t){if(!t)return[];let n=s(t);if(!n)return[];let r=n.name.getText();return[...e(n.parent),r]},t.getEnumMembers=function(e,n){if(e&&n.symbol&&n.symbol.declarations&&n.symbol.declarations.length)for(let e=0;e<n.symbol.declarations.length;e++){const r=n.symbol.declarations[e];if(r.kind===t.SK.EnumDeclaration){return r.members}}},t.isExported=function(e){if(e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.PrivateKeyword||e.kind==t.SK.ProtectedKeyword)))return!1;let n=e.symbol;if(!n)return!1;for(;;){let e=n.parent;if(!e)break;n=e}let r=n.valueDeclaration||n.declarations[0];return r.kind==t.SK.VariableDeclaration&&(r=r.parent.parent),!(!r.parent||r.parent.kind!=t.SK.SourceFile)},t.isReadonly=function(e){return e.modifiers&&e.modifiers.some((e=>e.kind==t.SK.ReadonlyKeyword))}}(e.pxtc||(e.pxtc={}))}(ts||(ts={})),function(e){!function(e){!function(t){const n=e.assembler.emitErr,r=n("opcode name doesn't match","<name>");class s extends e.assembler.Instruction{constructor(e,t,n){super(e,t,n,n,!1)}emit(t){let s=t.words;if(s[0]!=this.name)return r;let i=this.opcode,a=1,o=[],l=null,c=null;for(let r=0;r<this.args.length;++r){let u=this.args[r],p=s[a++];if("$"==u[0]){let r=this.ei.encoders[u],s=null;if(r.isImmediate||r.isLabel){if(!p)return n("expecting number",p);if(p=p.replace(/^#/,""),s=t.bin.parseOneInt(p),null==s)return n("expecting number",p)}else e.oops();if(null==s)return n("didn't understand it",p);e.U.assert(s>=0),11111!=s&&"$lbl"==u&&(s-=t.bin.location()+2,s>>=1),o.push(s);const a=s;if(s=r.encode(s),null==s)return n(`argument (${a}) out of range or mis-aligned`,p);"$i3"==u?s=c|s<<6:"$i5"==u&&(s=c|s<<8),"$i2"==u||"$i4"==u?c=s:"$rt"==u?(11111!=s&&s>4096&&e.U.oops("label: "+p+" v="+s),i=32768|s,"callrt.p"==this.name&&(i|=8192)):t.isLong||s<0||s>255?(t.isLong=!0,"$lbl"==u&&(s-=1),i=s>>9&65535|49152,l=this.opcode+(s<<7)&65535):i=this.opcode+(s<<7)&65535}else if(u!=p)return n("expecting "+u,p)}return s[a]?n("trailing tokens",s[a]):{stack:0,opcode:i,opcode2:l,numArgs:o,labelName:t.bin.normalizeExternalLabel(null)}}}t.VmInstruction=s,t.withPush={},t.opcodes=["stloc $i1","ldloc $i1","stfld $i4, $i5","ldfld $i4, $i5","newobj $i1","ldcap $i1","bitconv $i1","stglb $i1","ldglb $i1","ldint $i1","ldintneg $i1","ldspecial $i1","ldnumber $i1","ldlit $i1","checkinst $i1","mapget","mapset","ret $i2, $i3","popmany $i1","pushmany $i1","callind $i1","callproc $i1","calliface $i2, $i3","callget $i1","callset $i1","jmp $lbl","jmpnz $lbl","jmpz $lbl","try $lbl","push","pop"];class i extends e.assembler.AbstractProcessor{constructor(e){super(),this.addEnc("$i1","#0-8388607",(e=>this.inrange(8388607,e,e))),this.addEnc("$i2","#0-31",(e=>this.inrange(31,e,e))),this.addEnc("$i3","#0-262143",(e=>this.inrange(262143,e,e))),this.addEnc("$i4","#0-255",(e=>this.inrange(255,e,e))),this.addEnc("$i5","#0-32767",(e=>this.inrange(32767,e,e))),this.addEnc("$lbl","LABEL",(e=>this.inminmax(-4194304,4194303,e,e))).isLabel=!0,this.addEnc("$rt","SHIM",(e=>this.inrange(8388607,e,e))).isLabel=!0;let n=1,r=!0;for(let e of t.opcodes.concat(["callrt $rt"])){let i=new s(this,e,n);this.instructions[i.name]=[i],(r||"callrt"==i.name)&&(t.withPush[i.name]=!0,i=new s(this,e.replace(/\w+/,(e=>e+".p")),64|n),this.instructions[i.name]=[i]),"mapset.p"==i.name&&(r=!1),n++}}testAssembler(){}postProcessRelAddress(e,t){return t}postProcessAbsAddress(e,t){return t}getAddressFromLabel(e,t,n,r=!1){let s=e.lookupLabel(n);return null==s?null:t.is32bit?s:s-(e.pc()+2)}toFnPtr(e,t){return e}wordSize(){return 8}peephole(e,n,r){let s=e.getOp(),i="";if(n){i=n.getOp();let e=s+";"+i,t=this.file.peepCounts;t[e]=(t[e]||0)+1}"stloc"==s&&"ldloc"==i&&e.numArgs[0]==n.numArgs[0]?(/LAST/.test(n.text)&&e.update(""),n.update("")):t.withPush[s]&&"push"==i&&(e.update(e.text.replace(/\w+/,(e=>e+".p"))),n.update(""))}}t.VmProcessor=i}(e.vm||(e.vm={}))}(e.pxtc||(e.pxtc={}))}(ts||(ts={}));