slice-engine: Hybrid Three-Tier Execution Pipeline, WarmBoaRealm & Native Intrinsics
crates/slice-engine is designed around a single principle: use the lightest execution tier capable of running the workload, pay 0.00 ns and 0 B for unused Web/Node globals via compile-time minified lazy prelude shards, and accelerate hot standard-library primitives in native Rust.
1. Default Tier-1 SLICEBC\x01 Precompiled Boa CodeBlock CAS & Zero-Copy Framing (0.02 us - 0.21 us Instantiation)
Section titled “1. Default Tier-1 SLICEBC\x01 Precompiled Boa CodeBlock CAS & Zero-Copy Framing (0.02 us - 0.21 us Instantiation)”- The Problem Eliminated:
- Wrapping bundled JS inside a JSON-serialized
BytecodeModule(SLICESNP) requiredserde_json::from_sliceto allocate and unescape a 30 KB - 130 KBStringon every isolate run (~229 microseconds). - Even with raw UTF-8
SLICEBOAframing,boa_engine::Context::evalhad to run the full ECMAScript lexer, recursive-descent AST parser,ScopeAnalyzeridentifier resolution, andByteCompileronULTRA_CORE_PRELUDE, needed feature shards,node:*built-in scripts, and the user’s bundled JS on every cold process launch.
- Wrapping bundled JS inside a JSON-serialized
- Default
SLICEBC\x01PrecompiledCodeBlockArchitecture (crates/slice-engine/src/vm/boacas.rs&vendor/boa_engine/SLICE_PATCH.md):- By default (
boacas = true),compile_source_to_bytecodecallspack_boacas_container, which emits a 32-byteBoaCasHeader(b"SLICEBC\x01") containing:feature_flags: u16(BOACAS_FLAG_HAS_WORKER,BOACAS_FLAG_HAS_NEXT_TICK,BOACAS_FLAG_HAS_HTTP_BRIDGE,BOACAS_FLAG_HAS_SEMVER_FAST,BOACAS_FLAG_HAS_KV_SANDBOX,BOACAS_FLAG_NEEDS_LAZY_GETTERS,BOACAS_FLAG_NEEDS_SES_CHECK,BOACAS_FLAG_IS_RC_BUNDLE,BOACAS_FLAG_STARTS_WITH_BRACE) +shards_mask: u32: Computed together in a single $O(N)$aho_corasick::AhoCorasickDFA pass viadetect_shards_and_boacas_flagsinsidecompute_boacas_metadata(eliminating 38 separate.contains()linear substring scans over bundled JS).rc_key: u64(pre-extracted persistent realm cache fingerprint)precompiled_len: u32(SLCB\x01binaryCodeBlockpayload) +fallback_js_len: u32
- Pre-Fused Prelude + JS Shards (
1..=18,29) +node:*Built-Ins (19..=28,30) + 2-HitAtomicU8Prelude Cache: At build time,pack_boacas_containerexpands transitive shard prerequisites viaexpand_shard_prerequisites(e.g. ensuringEventTargetShard13precedesWebSocket/Worker/AbortSignalShards7,8,10andBufferShard5precedesnode:zlibBit30) and fusesULTRA_CORE_PRELUDE, all required runtime JS shards (1..=18and bit29in topologicalSHARD_LOAD_ORDER), and all statically referencednode:*built-in modules (19..=28and30) directly with the user script into a single unifiedGc<CodeBlock>, serialized viaboa_engine::Script::compile_to_slicebc. For dynamic or child-sandbox prelude/builtin evaluations at runtime,eval_static_js_with_2hit_slicebc_cacheevaluates directly on the caller’sContexton the 1st cold hit (zero throwawayContextallocation) and populatesOnceLockSLCB\x01caches only on the 2nd+ realm in long-lived processes. - Lazy Stringified Cold Modules: Unreachable or cold-method
node_modulesfactories deferred bycollect_eager_module_indices(__slice_modules[id] = "...") are skipped byis_in_lazy_string_module_lineduring shard scanning and remain inert string constants insideSLCB\x01until dynamically required at runtime. - Zero-Parse & Zero-Syscall Runtime Execution: At runtime,
slice-cliusesmimallocon Windows (#[cfg(windows)]inslice-clionly, replacingHeapAllocwhile preservingglibctcache’s sub-8 MBRSS footprint on Linux and keepingslice-engineallocator-agnostic for embedders) andSliceIsolate::exec_boacas_vmdecodes headers viaBoaCasHeader::decode_raw(deferringfallback_jsUTF-8 scans), creates a bareboa_engine::Contextwired withIdleModuleLoader(create_bare_boa_realm,0hostrealpathsyscalls), registers only the required native Rust host functions in a single pass, deserializes theGc<CodeBlock>directly from themmapslice viaboa_engine::Script::from_slicebc_bytes, and executes it on the VM - eliminating 100% of runtime JS lexing, AST parsing, scope analysis, and bytecode compilation on cold start (seetests/reports/latest.mdfor measured cold and warm latencies). - Legacy
SLICEBOASource-in-CAS Fallback (--no-boacas): If--no-boacas(or// @slice-boacas: false/SLICE_BOACAS=0/[engine] boacas = false) is set,compile_source_to_bytecodeemits the 8-byteb"SLICEBOA"header followed by raw UTF-8 transpiled JS.
- By default (
2. Pre-Warmed Boa Context Pool (BOA_CONTEXT_POOL), __slice_rc Persistent Realm Cache, & Sharded Preludes
Section titled “2. Pre-Warmed Boa Context Pool (BOA_CONTEXT_POOL), __slice_rc Persistent Realm Cache, & Sharded Preludes”2.1 Pre-Warmed WarmBoaRealm Pool (crates/slice-engine/src/runtime/boa_realm.rs)
Section titled “2.1 Pre-Warmed WarmBoaRealm Pool (crates/slice-engine/src/runtime/boa_realm.rs)”- Maintains a thread-local pool of pre-initialized
WarmBoaRealminstances (SliceIsolate::prewarm_boa_pool(count)), wrapped instd::mem::ManuallyDrop<Vec<WarmBoaRealm>>so thread exit on Windows never runsboa_engine::Context::dropafterboa_gc’s TLS collector has already torn down. - Wraps executed scripts inside a lexical block (
{\n<js_code>\n}) inexec_boa_full_es_vmso top-levelconst,let, andclassdeclarations are scoped to that invocation and never collide when the warm context is reused across requests inslice serveorslice run --warm. - Routes
console.logdirectly through a native Rust__slice_console_loghost function writing straight into thread-localBOA_STDOUT.
2.2 Persistent Realm Module Cache (__slice_rc), Precompiled __slice_drain_wu, & BOA_DIRTY_SUBSYSTEMS Teardown
Section titled “2.2 Persistent Realm Module Cache (__slice_rc), Precompiled __slice_drain_wu, & BOA_DIRTY_SUBSYSTEMS Teardown”bundle_entrypoint_with_depsemits a 16-hex-char BLAKE3 fingerprint header (//__SLICE_RC:<16_hex_chars>) and caches evaluatednode_modulesexports (__slice_cache) plus the compiled entrypoint closure inglobalThis.__slice_rc.- On warm hits (
slice serveorslice run --warm),WarmBoaRealm::loaded_bundlesstores the compiledboa_engine::JsObjectentrypoint function handle and invokesfn_obj.call(...)directly in Rust with 0 JS parser passes and 0node_modulesCJS factory re-evaluations. WarmBoaRealm::drain_wu_fncaches the precompiledglobalThis.__slice_drain_wufunction handle soSliceIsolate::drain_wait_until_tasksdrains backgroundctx.waitUntil(...)callbacks via directJsObject::callwithout invokingContext::eval(boa_parser+ByteCompiler) on every HTTP request (seetests/reports/latest.mdforslice serveTier-0 and Tier-1 keep-alive throughput).BOA_DIRTY_SUBSYSTEMStracks a single-byte bitmask (DIRTY_EVENT_LOOP,DIRTY_ALS,DIRTY_FETCH_MOCK,DIRTY_WEBSOCKET,DIRTY_SOCKETS,DIRTY_WORKERS,DIRTY_WASM) so isolate teardown inteardown_boa_compartment_thread_localsandclear_event_loop_stateskips clearing subsystems that were never touched during the isolate turn.
2.3 Compile-Time Minified 32-Bit shards_mask Surgical Preludes (00_ultra_core.js + JS Shards 01..19 + Pre-Fused node:* Bits 19..=28, 30)
Section titled “2.3 Compile-Time Minified 32-Bit shards_mask Surgical Preludes (00_ultra_core.js + JS Shards 01..19 + Pre-Fused node:* Bits 19..=28, 30)”- Implemented in
crates/slice-engine/build.rs,crates/slice-engine/src/preludes/js_preludes.rs, andcrates/slice-engine/src/runtime/boa_realm.rs(WarmBoaRealm::loaded_shards_mask: u32, paired with 16-bitBOACAS_FLAG_*feature flags inboacas.rs):- Instead of evaluating a monolithic JS prelude on every cold process launch,
00_ultra_core.js(~2 KBminified, preserving native BoaDate.nowandMath.randomfast paths unless--deterministicis active) is always-on,LAZY_GETTERS_INIT_PRELUDE(bit 0,__defLazy(names, shardId)) is evaluated only whenBOACAS_FLAG_NEEDS_LAZY_GETTERSis set, and the remaining bits ofshards_mask: u32selectively fuse or lazy-load 19 orthogonal JS prelude shards plus 11 pre-fusednode:*modules:- Bit
0(LAZY_GETTERS_INIT_PRELUDE): Self-replacingObject.definePropertylazy global getters (__defLazy) when dynamicglobalThis.*probes are detected (BOACAS_FLAG_NEEDS_LAZY_GETTERS). - Shard
1(01_web_fetch_url.js):URLandURLSearchParams(backed by native Rusturl_and_usp.rs). - Shard
2(02_encoding_events.js):TextEncoder,TextDecoder,btoa,atob. - Shard
3(03_streams_formdata.js):ReadableStream. - Shard
4(04_webcrypto_clone.js):crypto,CryptoKey(with tenant-scopedCRYPTO_KEY_HANDLE_TABLEpre-expanded key handles),crypto.subtle(digest,generateKey,importKey,exportKey,encrypt,decrypt,sign,verify,deriveBits,deriveKey,timingSafeEqual),randomUUID,getRandomValues. - Shard
5(05_full_buffer.js): CoreUint8Array-backedBuffer(from,alloc,concat,byteLength,compare,toString,subarray,equals) with lazy Shard17prototype forwarders. - Shard
6(06_console_ext.js): Extendedconsole.*inspection and profiling methods (table,dir,dirxml,group,groupCollapsed,groupEnd,time,timeLog,timeEnd,count,countReset,trace,assert,clear). - Shard
7(07_websocket.js):WebSocket,MessageEvent,CloseEvent. - Shard
8(08_workers_sockets.js):Worker,MessageChannel,MessagePort,Slice.connect. - Shard
9(09_wasm.js):WebAssembly(Module,Instance,Memory,Table,Global,compile,instantiate,validate). - Shard
10(10_outbound_fetch_sse.js):fetch,AbortController,AbortSignal(timeout,any,abort),EventSource,Slice.streamSSE,Response.sse. - Shard
11(11_fetch_headers_req_res.js):Headers(with_isHeadersfast copy, O(1) lowercaseget(), andgetSetCookie()),Request,Response,__slice_make_web_request. - Shard
12(12_url_pattern.js):URLPattern. - Shard
13(13_dom_events.js):DOMException,Event,CustomEvent,EventTarget. - Shard
14(14_transform_compression_streams.js):WritableStream,TransformStream,TextEncoderStream,TextDecoderStream,CompressionStream,DecompressionStream. - Shard
15(15_blob_formdata.js):Blob,File,FormData. - Shard
16(16_structured_clone.js):structuredClone. - Shard
17(17_buffer_binary_rw.js):Buffer.prototypebinary integer readers/writers (readUInt*,readInt*,readBig*,writeUInt*,writeInt*,writeBig*) and slice mutators (copy,fill,write,compare,toJSON). - Shard
18(18_intl.js): Zero-ICU-bloat WinterTCIntl(DateTimeFormat,NumberFormat,Collator,PluralRules,Segmenter,getCanonicalLocales,supportedValuesOf). - Bits
19..=28,30, and31(node_builtins::builtin_snippet_for_bit): Pre-fusednode:*built-in modules (19=node:cryptocore hashes/HMAC/CSPRNG with lazy PKI getters,31=slice:crypto-pkiPKI/KeyObject/Cipheriv/KDF shard pre-fused only when PKI symbols are statically referenced,20=node:fs&fs/promises,21=node:path,22=node:events,23=node:os,24=node:util,25=node:assert,26=node:buffer,27=node:url,28=node:timers,30=node:zlib). - Bit
29(19_process_cli.js): WinterTCnavigatorandlocation, plus completeprocessCLI surface (stdout,stderr,stdin,memoryUsage+.rss(),hrtime+.bigint(),uptime,argv0,execArgv,execPath,ppid,emitWarning,on/once/off/emit/listeners/removeListener/removeAllListeners/listenerCount).
- Bit
- Instead of evaluating a monolithic JS prelude on every cold process launch,
3. Native Rust Fast-Path Intrinsics (url_and_usp, SHA-NI, Asymmetric Crypto, DEFLATE/Gzip, AsyncLocalStorage, & In-Memory VFS Slab)
Section titled “3. Native Rust Fast-Path Intrinsics (url_and_usp, SHA-NI, Asymmetric Crypto, DEFLATE/Gzip, AsyncLocalStorage, & In-Memory VFS Slab)”Implemented in crates/slice-engine/src/intrinsics/, crates/slice-engine/src/runtime/boa_realm.rs, and crates/slice-engine/src/bindings/:
- Native Rust WHATWG
URL&URLSearchParamsPrimitives (crates/slice-engine/src/intrinsics/url_and_usp.rs):- Provides
parse_whatwg_url,can_parse_whatwg_url,normalize_url_pathname,usp_encode_component,usp_decode_component, andusp_parse_query, exposed to Shard 1 via__slice_url_can_parse,__slice_usp_encode, and__slice_usp_decode.
- Provides
- Hardware
SHA-NIBlock Compression (Sha256State::compress_block_sha_ni):- Uses Intel/AMD
SHA-NIinstructions (_mm_sha256rnds2_epu32,_mm_sha256msg1_epu32,_mm_sha256msg2_epu32) with cachedAtomicU8runtime feature detection (sha,sse4.1,ssse3) and automatic fallback toSha256State::compress_block_soft.
- Uses Intel/AMD
- Native
ring+x25519-dalek+ FIPS-180-4 WebCrypto &node:cryptoSuite with AsymmetricEd25519/X25519/ECDSA/RSA& Tenant-Scoped Key Handle Cache (asymmetric_and_keys.rs,symmetric_and_kdf.rs,bindings/crypto.rs):- Direct
JsArrayBuffer/JsUint8Arrayzero-copy Rust host functions (__slice_crypto_sha256,__slice_crypto_hmac_sha256,__slice_crypto_digest,__slice_crypto_hmac_sign,__slice_crypto_key_register,__slice_crypto_cipher,__slice_crypto_asym_keygen,__slice_crypto_asym_import,__slice_crypto_asym_sign,__slice_crypto_asym_verify,__slice_crypto_ecdh,__slice_crypto_kdf,__slice_crypto_random_int,__slice_base64_encode,__slice_base64_decode), including zero-allocation unbiased 48-bit bitmask rejection sampling forcrypto.randomInt(sample_unbiased_u64_below). - Supports symmetric
AES-GCM/AES-CBC, runtime asymmetric key generation (Ed25519, RFC 7748X25519, andECDSAP-256/P-384), PKCS#8 / PKCS#1 / SPKI / JWK / raw import & export,Ed25519/ECDSA/ imported2048-8192-bitRSA(RSASSA-PKCS1-v1_5&RSA-PSSoverSHA-256/SHA-384/SHA-512) signing & verification, and constant-time RFC 7748X25519Diffie-Hellman key agreement (crypto.diffieHellman&subtle.deriveBits/deriveKey), while failing closed on unbounded runtime RSA/DSA prime generation. - Pre-expanded
ring::aead::LessSafeKey,ring::hmac::Key,AesExpandedKey,Ed25519keypairs,ECDSA(P-256/P-384) keys,RSAkey material, andX25519keys are cached in thread-localCRYPTO_KEY_HANDLE_TABLE(CachedCryptoKeyMaterial) scoped byBOA_ACTIVE_TENANTso repeated cryptographic operations skip key schedule/DER parsing while preventing cross-tenant handle access. - KDF operations (
PBKDF2,HKDF,scrypt) charge proportional CPU fuel againstBOA_FUEL_BUDGET(consume_crypto_kdf_fuel), deterministically trapping hostile iteration/cost parameters withSandboxViolation::CpuFuelExhausted.
- Direct
- Self-Contained RFC 1951 (
deflate-raw), RFC 1950 (deflate), & RFC 1952 (gzip) Compression Engine:- Implemented in
zlib_compress_bytesandzlib_decompress_byteswith LZ77 32 KB sliding-window compression, Stored/Fixed/Dynamic Huffman decompression, Adler-32, and CRC-32 validation, powering both WinterTCCompressionStream/DecompressionStreamandnode:zlibwith zero external crate dependencies.
- Implemented in
- Zero-Overhead
SliceJobExecutorfornode:async_hooks(AsyncLocalStorage&AsyncResource):- Implemented in
SliceJobExecutorandevent_loop.rs: whenBOA_ALS_ACTIVEisfalse, promise microtasks execute with zero snapshot overhead; whenAsyncLocalStorageis active,SliceJobExecutorand the event loop capture and restoreBOA_ALS_SNAPacross everyawait,.then(),Promise.all,setTimeout,setImmediate,queueMicrotask,process.nextTick, andfetchboundary.
- Implemented in
- Zero-Regex Native Rust SemVer & Utility Scanners:
- Implemented in
semver_parse_strict_xyz,semver_coerce_xyz, andsemver_satisfies_xyz(~150 ns per check).
- Implemented in
- Thread-Local Inode-Backed VFS & Open FD Slab (
BOA_VFS_STATEinbindings/fs/):- Ephemeral files, directories, and symlinks (
writeFileSync,appendFileSync,mkdirSync,symlinkSync,openSync) are stored in a denseVec<Option<VfsInode>>slab with typedVfsEntryKindvariants (File(Arc<Vec<u8>>),Directory,Symlink(String)), a unifiedFxHashMap<String, PathEntry>(Present(InodeId)|Tombstone) anchored tocached_normalized_cwd(), a RustOpenFddescriptor table (fds: Vec<Option<OpenFd>>), and unified per-hopRESOLVE_BENEATHVFS + host symlink/junction resolution (symlink_resolver.rs,MAX_SYMLINK_HOPS = 40) enforcing OCapallow_read/allow_writecontainment on every intermediate and target hop while maintaining0hoststat()syscalls on.casbundles. Open file descriptors surviverenameSync, atomic path replacement, andunlinkSyncuntilcloseSync, charge signed byte deltas againstBOA_KV_MEM_BUDGET, clean up automatically across warm-pool turns (DIRTY_VFS), and fall back transparently tostd::fsfor unmasked host files.
- Ephemeral files, directories, and symlinks (
- Lazy On-Demand Host Binding Registration by Category (
crates/slice-engine/src/bindings/mod.rs):- Cold
create_warm_boa_realm()initialization registers only the ultra-core host functions (__slice_console_log,__slice_map_error_stack,__slice_load_builtin,__slice_lazy_prelude, timers, env, SHA-256, Base64, UTF-8), while specialized host bindings (register_http_bridge_host_functions,register_kv_and_sandbox_host_functions,register_semver_and_fast_intrinsics_host_functions,register_wintertc_phase_n3_host_functions,register_async_hooks_host_functions) are registered lazily only when their corresponding shard or built-in module is loaded.
- Cold
- Vendored
boa_engineMonomorphic Inline Caching (InlineCache::get_fast),%Promise%1-Alloc Fast Path,DefineOwnPropertyByNameFast Path, Direct ECMA-404JSONFast Paths, &SLICEBC\x01SourceMapStack Traces:- Zero-Borrow Monomorphic Inline Cache (Own + 1-Hop Prototype), Add-Property Transition IC, Computed Dictionary Access, & Object Literal Fast Path (
vendor/boa_engine/src/vm/inline_cache/mod.rs,get/property.rs,set/property.rs,own_property.rs,unique_shape.rs): Caches(mono_shape_id: Cell<u64>, mono_proto_shape_id: Cell<u64>, mono_slot: Cell<Slot>)with boxed coldIcSlowStatefor $O(1)$ zero-GcRefCell-borrowGetPropertyByName(both own properties and 1-hop prototype methods/getters) andSetPropertyByNamereplace hits, cachesAddTransitionEntry(S_from -> S_to+ prototypeShape::id()chain verification, invalidated immediately onUniqueShape::insert_property_transition,change_attributes_transition, andoverride_internal) for $O(1)$SetPropertyByNameown-property additions in constructors andObject.createfactories, accelerates string-keyed dictionaryget_by_valueandSetPropertyByValueon ordinary/null-prototype objects, and usesPropertyMap::try_fast_define_own_data_propertyinDefineOwnPropertyByNameso object literals ({ key: value }) transitionSharedShapeslots directly without virtual descriptor dispatch. - ECMA-262
%Promise%1-AllocationPromise.resolve, Zero-GC SettledAwait,FastForInState, & IntrinsicArraySpecies Fast Paths (vendor/boa_engine/src/builtins/promise/mod.rs,await/mod.rs,iterable/mod.rs,array/mod.rs): Constructs fulfilled%Promise%instances directly in 1 GC allocation (0PromiseCapabilityrecords,0NativeFunctionclosures,0dynamic VM calls) for primitives and non-thenable ordinary/array objects with unmodified prototype chains, enqueues a direct zero-GC-allocationPromiseJobresumingGeneratorContextby value when awaiting already-settled intrinsic promises without activeAsyncLocalStorage(and masks any store entered synchronously afterwards viaHostHooks::enter_empty_job_context), iterates ordinaryfor..inloops viaFastForInStatewith zeroForInIterator/{ value, done }GC allocations (preserving non-enumerable own-key prototype shadowing, live property deletion, and mid-loop mutation deoptimization), and bypasses species/constructor dispatch and element-by-element descriptor insertion on unmodified intrinsicArraymethods (slice,map,filter,Object.keys). - Direct Rust
JSON::parse_ecma404&Json::try_fast_stringifyFast Paths (vendor/boa_engine/src/builtins/json/mod.rs):JSON::parse_ecma404runs an iterative ECMA-404 state-machine parser (MAX_DEPTH = 2048) overLatin1andUtf16inputs with 8-byte SWAR unescaped string scanning, exact integer accumulation +fast-float2float parsing, and per-depthSharedShape/ShapeChainprediction so homogeneous arrays of JSON objects construct directly with populated monomorphicShapeslots. Complementarily,Json::try_fast_stringifyserializes ordinaryJsObjects and denseArrays (DenseI32,DenseF64,DenseElement) into a singleVec<u8>buffer usingShape::with_property_keys, 8-byte SWAR ASCII scanning, andryu_jsnumber formatting when noreplacerorspaceargument is supplied. - Lazy Multi-Frame Source-Map Stack Translation & Prelude
SourceMapElision (crates/slice-cas/src/bundler/source_map.rs&vendor/boa_engine/src/script.rs):SLICEBC\x01serializes user-code bytecode-to-lineSourceMapentries insideencode_codeblock/decode_codeblock(omitting internal prelude source-map entries viacompile_to_slicebc_with_min_lineand pooling short Latin1 identifiers on decode), andError.prototype.stacklazily invokes__slice_map_error_stackto translate bundled frames via embedded//@sm:/// #slice-source:markers back tofile.ts:line:colwith0.00 nsoverhead when.stackis not read. - Chrome DevTools / Perfetto Execution Tracer (
SliceIsolate::export_chrome_trace_json):slice run --trace=<out.json>(orSLICE_TRACE=<out.json>) emits a standard Chrome Trace Event Format (ph: "X") JSON timeline capturingisolate.instantiate,isolate.execute,state.checkpoint,state.restore, andsandbox.evalspans.
- Zero-Borrow Monomorphic Inline Cache (Own + 1-Hop Prototype), Add-Property Transition IC, Computed Dictionary Access, & Object Literal Fast Path (
4. Binary SLICESNP\x02 LLInt Interpreter (slicesnp_codec.rs, exec_llint.rs), Multi-Blob .cas Loader (cas_loader.rs), and Tier-2 Numeric Register VM (numeric_vm.rs)
Section titled “4. Binary SLICESNP\x02 LLInt Interpreter (slicesnp_codec.rs, exec_llint.rs), Multi-Blob .cas Loader (cas_loader.rs), and Tier-2 Numeric Register VM (numeric_vm.rs)”-
Binary
SLICESNP\x02Snapshot Codec, Zero-CopyLLIntExecution, & Content-Verified Cache:encode_slicesnp_v2serializes Tier-0BytecodeModules (<= 128 KiBASCII source) into a compact bounds-checked binary snapshot (b"SLICESNP\x02"+flags, boundedMAX_CODEC_DEPTH, retaining legacySLICESNP{...}JSON fallback).- Modules with
SLICESNP_FLAG_FLAT_LLINT(ConstNum,ConstStr,ImportCas,AddAssignVar,ConsoleLogVar,MonomorphicForLoop, etc.) execute directly over&[u8]viaSnpCursorinSliceIsolate::execute_slicesnp_v2_flat_llintusing inlineCompactStringenv_varskeys (<= 24bytes,0heap key allocations) and zero-copyvisit_pure_static_exportsiteration on importedSLICESNP\x02.casblobs. - General AST
SLICESNP\x02modules cache decodedArc<BytecodeModule>entries inSNP_LAST_HIT+SNP_MODULE_CACHE(MAX_SNP_CACHE_ENTRIES = 1024), storing an ownedArc<[u8]>copy of the snapshot payload and verifying exact byte equality on every hit somimallocLIFO equal-length buffer reuse never causes ABA collisions.
-
Tier-1 Multi-Blob
MappedCasArchiveLoader (__slice_cas_require):ActiveCasArchiveGuardbindscas: Option<&MappedCasArchive>ontoBOA_ACTIVE_CASfor the active turn (isolating nestedSlice.evalSandboxcalls and restoring state onDrop/unwind), whileeval_cas_require_moduleresolves sibling/nested.casblobs, caches CommonJSmodule.exportsfor diamond and circularrequire()graphs, auto-loads required JS prelude shards, and folds resolved module counts intoExecutionMetrics::cas_modules_resolved.
-
Zero Name Heuristics: Every JS/TS function (
Stmt::FuncDecl,Expr::ArrowFunc, and function expressions) is analyzed structurally bytry_compile_numeric_funcregardless of function or parameter names. -
Unboxed 32-Register Execution (
[f64; 32]): Pure numeric functions compile into 8-byte/16-byteNumericOpinstructions (LoadConst,Move,BinaryReg,BinaryImm,UnaryReg,MathIntrinsic,Jump,JumpIfFalse,CallSelf1,CallSelf2,LinearRecurrence2,Return). Execution insideNumericFunc::executeoperates entirely on unboxedf64andi64/i32bitwise values on the CPU stack (256 bytes, fitting in 4 CPU L1 cache lines) with 0 heap allocations and 0FxHashMapvariable lookups. -
Structural Linear Recurrence Lowering (
detect_linear_recurrence_ast): Recognizes any 1-parameter self-recursive function matchingif (param <= 1) return ...; return c1 * f(param - 1) + c2 * f(param - 2);(including unweighted Fibonacci-style and weighted Pell/Lucas-style recurrences under any identifier name) and lowers it toNumericOp::LinearRecurrence2, reducing $O(2^n)$ call trees to an $O(n)$ 2-register IEEE-754f64loop over exact integer inputs (0 <= n <= 78) while cleanly falling back when out-of-domain arguments occur. -
Amortized Fuel Metering: Checks
(local_steps & 255) == 0every 256 register instructions (and at every recursive call and loop recurrence), guaranteeing deterministicSandboxViolation::CpuFuelExhaustedpreemption on infinite numeric loops with< 0.4%branch overhead.