mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-21 18:26:09 +00:00
24 KiB
24 KiB
CodeMode Interpreter Support
This is the checkable support matrix for CodeMode's confined JavaScript interpreter. It tracks the language and standard-library surface that programs can use today, plus concrete gaps that may be implemented later.
[x]means the feature is implemented at the scope described here.[ ]means a concrete compatibility gap remains.- Checked items do not promise complete ECMAScript edge-case parity; known differences are stated explicitly.
- Intentional boundaries are not listed as compatibility work.
When behavior changes, update this file and the tests in the same change. The implementation and tests remain the ultimate source of truth.
Source and execution model
- JavaScript parsed with the latest syntax accepted by Acorn, then restricted by the interpreter allowlist.
- Erasable TypeScript syntax, including type annotations, type declarations, assertions, and non-null assertions. TypeScript is transpiled first; the emitted JavaScript must still use the supported subset.
- Top-level
awaitandreturnthrough the program's implicit async-function scope. - Explicit
return, final top-level expression as a REPL-style result, andnullwhen no value is produced. - Program results use JSON-like boundaries, with
undefinedand non-finite numbers normalized tonull. Tool arguments follow JSON serialization semantics before their schema applies (see the tools section). - Live Date, RegExp, Map, Set, URL, and URLSearchParams values inside CodeMode.
- Tool calls through the host-provided
toolstree only. - The global
search(...)built-in: synchronous tool discovery that counts as an admitted tool call and is shadowable by program declarations like other globals. - Cooperative timeout, an optional total tool-call limit, output bounding, and unrestricted tool-call concurrency.
Values and literals
null,undefined, booleans, finite and non-finite numbers, and strings.- Array literals, including holes and spread from arrays, strings, Maps, Sets, and URLSearchParams.
- Object literals with shorthand, computed string/number keys, and spread from plain data objects;
nullandundefinedare no-ops, while arrays are rejected. - Template literals with interpolation.
- Regular-expression literals.
NaNandInfinityglobals.- BigInt literals and in-interpreter BigInt arithmetic; BigInt remains invalid at JSON-like host boundaries.
- Arbitrary Symbol primitive values and symbol-keyed properties. The confined
Symbol.iteratorandSymbol.asyncIteratorkeys are available only for custom iterator protocols. - Tagged-template calls.
- Getter and setter definitions in object literals.
Bindings and destructuring
const,let, and acceptedvardeclarations.- Object and array destructuring in declarations, parameters, assignment expressions, and
for...ofbindings. - Nested patterns, defaults, elisions, and rest elements.
- Assignment to identifiers, unblocked plain-object fields, non-negative integer array indexes, and writable URL fields.
- Direct function declarations are hoisted in program and block statement lists.
- Parameter defaults observe a temporal dead zone for later parameters.
- JavaScript-correct function scoping, hoisting, and redeclaration for accepted
vardeclarations. - Predeclare
letandconstbindings in every lexical scope, including program/block bodies, switch bodies, and loop headers, so reads before initialization and self- or cross-referential initializers observe the JavaScript temporal dead zone. - Hoist function declarations accepted directly in switch cases.
- Computed object destructuring keys such as
const { [field]: value } = record. - Object destructuring from arrays, such as
const { length } = values. - Array destructuring from supported non-array iterables: strings, Maps, Sets, and URLSearchParams.
Statements and control flow
- Blocks and empty statements.
if/elseand conditional expressions.switch, including default clauses and fallthrough.for,while, anddo...while.for...ofover arrays, strings, Maps, Sets, and URLSearchParams.for...inover own keys of plain objects, arrays, and tool references.- Unlabeled
breakandcontinue. try,catch, optional catch bindings, andfinally.throwwith arbitrary values.- Labeled statements, labeled
break, and labeledcontinue. for await...ofover the supported synchronous collections and custom iterator objects usingSymbol.asyncIteratoror theSymbol.iteratorfallback. Each iterator step is sequential, yielded promises and plain values from synchronous collections and sync iterators are awaited before binding, and abrupt loop completion invokes the iterator's optionalreturn(). Custom async iterators control their yielded values, as in JavaScript; only theirnext()results are awaited. Async generators remain outside the supported subset.
Functions and callbacks
- Function declarations, function expressions, and arrow functions.
- Synchronous and
asyncfunctions. - Closures, recursion, default parameters, rest parameters, and destructured parameters.
- Expression and block function bodies.
- User callbacks for the supported Array, Map, Set, URLSearchParams, sort, string-replacement, and
Array.frommapper APIs, with one shared acceptance rule everywhere including promise reactions. Boolean,Number,String,parseInt,parseFloat,isFinite,isNaN, and URI helpers as callbacks.- Built-in method references as callbacks, such as
values.map(Math.abs),records.map(JSON.stringify),items.forEach(console.log), andPromise.resolve(-1).then(Math.abs). Extra callback arguments a built-in does not consume are ignored, like JS; consumed arguments stay strictly validated (Math.floorstill rejects a string). Intrinsic references keep their receiver ("abc".includesworks as a predicate), unlike detached JS methods, which losethis. - Constructors work as callbacks with JS call semantics:
Errortypes construct (messages.map(Error)), and new-requiring constructors (Map,Set,URL,URLSearchParams,Promise) throw aTypeError, like JS. - Tool references and detached
Promisestatics are rejected as callbacks with a hint to wrap them in an arrow function. - Promise-returning string replacers are coerced synchronously to
"[object Promise]", like JavaScript; they are not automatically awaited. - The optional
thisArgof iteration methods is accepted and ignored: CodeMode functions have nothis, so ignoring it matches JS arrow-function semantics exactly. thisin non-arrow CodeMode functions and callbacks.- User-defined constructor calls.
Function.prototype.call,apply, andbindfor CodeMode functions.- Classes and private fields.
- Generator functions and
yield.
Expressions and operators
- Property access with dot or computed bracket syntax.
- Optional property access and optional calls.
- Function/tool calls and spread arguments.
- Sequence expressions (the comma operator).
awaitfor CodeMode promises; a plain value passes through unchanged, though everyawaitstill defers its continuation one reaction turn.newfor Array, Object, Error types, Date, RegExp, Map, Set, URL, URLSearchParams, and Promise.- Arithmetic operators:
+,-,*,/,%, and**. - Equality and ordering:
==,!=,===,!==,<,<=,>, and>=. - Bitwise operators:
&,|,^,~,<<,>>, and>>>. - Logical operators:
&&,||,??, and!, with short-circuiting. - Unary
+, unary-,void,typeof,instanceof, and own-property-onlyin. - Prefix and postfix
++and--. - Plain, arithmetic, bitwise, and logical assignment operators.
- Property deletion on plain data objects and arrays, including computed and optional forms; deleting an array index creates a hole without changing its length.
Promises and tools
- Tool calls start eagerly and return supervised, run-once CodeMode promises.
- Direct
await, repeated awaits, and implicit resolution when a promise is returned from a function/program. Promise.resolveandPromise.reject.Promise.all,Promise.allSettled,Promise.race, andPromise.anyover supported collections containing promises and plain values.Promise.allpreserves result order and rejects on the first observed failure without cancelling siblings.Promise.allSettledreturns plain fulfilled/rejected outcome records.Promise.racesettles from the first result without cancelling losers at settlement time.- Real promise values from
Promise.all,Promise.allSettled, andPromise.race; separately constructed combinator batches overlap as in normal JavaScript. - Promise chaining with
.then,.catch, and.finally: handlers run deferred in attach order, returned promises are adopted, handler throws reject the derived promise,.finallypreserves the original settlement unless its cleanup fails, and direct self-resolution rejects with aTypeError. - Every
await(including of plain values and already-settled promises) defers its continuation one reaction turn, so concurrent async functions interleave at await points as in JavaScript. - Combinators settle one reaction turn after their deciding member (V8-observable ordering): reactions already
attached to members run first, and an aggregate cannot beat a plain value settling in the same turn into a
Promise.race. Exact microtask-count parity beyond this observable ordering is not a documented guarantee. - All still-pending work (race losers, fail-fast
Promise.allstragglers, and un-awaited calls alike) is interrupted when the program returns; rejections that settled un-awaited becomeSuccess.warningsdiagnostics. A combinator abandoned inside its final settlement turn counts as pending and is interrupted without a warning. try/catchcan handle awaited tool and promise failures.Promise.any: first fulfillment wins; all-rejected rejects with anAggregateErrorwhoseerrorsarray holds the catch-normalized reasons in input order, and empty input rejects with an emptyAggregateError.new Promise((resolve, reject) => ...): the executor runs synchronously and receives first-class resolve/reject callables that settle the promise exactly once (they may escape the executor and settle later); an executor throw rejects unless the promise already settled, resolving with a promise adopts it, and resolving with the promise itself rejects with aTypeError. Resolver callables work anywhere callbacks are accepted, including.then/.catchhandlers and collection callbacks, but remain opaque references that cannot cross the data boundary.- Thenable assimilation; objects with a callable
thenfield remain plain data. - Dotted tool names are canonicalized into namespace paths; a path can be both callable and a namespace, and the last definition supplied for a canonical path wins.
- Tool path segments may be named
constructor,prototype, or__proto__because paths use inert Map keys. - Outbound tool arguments follow JSON serialization semantics, like
JSON.stringify: object properties withundefinedvalues are dropped,undefinedarray elements and non-finite numbers becomenull, and sparse arrays densify. Tools never receiveundefinedinside their input object, though a baretools.t(undefined)argument still reaches schema decoding asundefined. Program results keep the stricter normalization where everyundefinedbecomesnull. - Tokenize and case-fold non-ASCII tool paths, descriptions, and queries for tool search.
Objects and properties
- Own-field reads and writes on plain data objects.
Object()andnew Object()return{}for nullish arguments and pass objects through unchanged; primitive wrapper objects (Object(1)) are rejected explicitly.- Computed property names and object spread.
Object.keys,Object.values,Object.entries,Object.hasOwn,Object.assign, andObject.fromEntries.Object.keysover arrays and tool references.- Object identity is preserved by in-CodeMode Object helpers.
- Prototype traversal and mutation through
__proto__,constructor, andprototypeare blocked. - Legal own data fields named
__proto__,constructor, orprototypeare rejected at JSON/tool boundaries and cannot be created, read, or written in CodeMode; tool path segments with those names remain supported. Object.isfor supported data values.Object.groupByover supported collection iterables, with string-key coercion and null-prototype results.
Arrays
- The
Arrayconstructor with or withoutnew:Array(a, b)collects arguments andArray(n)creates a sparse array of that length; invalid lengths throwRangeError. Iteration, spread, join, and JSON handle holes like JavaScript, and host results normalize holes tonull. - Static methods:
Array.isArray,Array.of, andArray.from, including theArray.frommapper form with(value, index)arguments. - Iteration/transformation:
map,filter,flatMap, andforEach. - Searching/tests:
find,findIndex,findLast,findLastIndex,some,every,includes,indexOf, andlastIndexOf. - Aggregation:
reduceandreduceRight. - Ordering:
sort,toSorted,reverse, andtoReversed. - Access/copying:
at,slice,concat,flat,with, andjoin. - Mutation:
push,pop,shift,unshift,splice,fill, andcopyWithin. - Materialized iteration helpers:
keys,values, andentriesreturn arrays rather than iterators. length, numeric indexing, index assignment, spread, andfor...of.- The
thisArgargument ofArray.fromis accepted and ignored, like JS arrows. Array.prototype.toSpliced.- Canonical array/string index parsing: keys such as
"01"remain non-index properties rather than aliasing index1; arbitrary array-property assignment remains unsupported. Array.prototype.sortpreserves trailing holes, whiletoSorteddensifies holes intoundefinedelements, like JavaScript.
Strings
- Case/normalization:
toLowerCase,toUpperCase,normalize. - Trimming:
trim,trimStart, andtrimEnd. - Searching/tests:
includes,startsWith,endsWith,indexOf,lastIndexOf, andsearch. - Slicing/access:
slice,substring,at,charAt,charCodeAt, andcodePointAt. - Construction/transformation:
split,concat,repeat,padStart,padEnd,replace, andreplaceAll. - Regular-expression integration:
match, materializedmatchAll,replace,replaceAll,split, andsearch. localeCompare; locale and options arguments are currently ignored.toString,length, numeric indexing, spread, andfor...ofby Unicode code point.- Static
String.fromCharCodeandString.fromCodePoint. - Native argument coercion for supported String methods; for example,
includes(1)andslice("1")coerce like native JS,split(undefined)returns the whole string, andincludes/startsWith/endsWithreject regular expressions with a native-styleTypeError. Opaque runtime references still reject as data errors, andrepeatstill requires a finite non-negative count. - Native no-argument parity for
match(),matchAll(), andsearch(); all behave as an empty pattern. Present arguments must still be a regular expression or string pattern.
Numbers and Math
- Coercion functions:
Number,parseInt, andparseFloat. - Number predicates/parsers:
Number.isInteger,Number.isFinite,Number.isNaN,Number.isSafeInteger,Number.parseInt, andNumber.parseFloat. - Number formatting:
toFixed,toPrecision,toExponential,toString, andvalueOf. - Number constants:
MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,MAX_VALUE,MIN_VALUE,EPSILON,NaN,POSITIVE_INFINITY, andNEGATIVE_INFINITY. - Math constants:
PI,E,LN2,LN10,LOG2E,LOG10E,SQRT2, andSQRT1_2. - Math methods:
random,max,min,abs,acos,acosh,asin,asinh,atan,atan2,atanh,floor,ceil,round,trunc,sign,sqrt,cbrt,pow,hypot,cos,cosh,sin,sinh,tan,tanh,log,log2,log10,log1p,exp,expm1,f16round,fround,clz32, andimul. - Native zero-argument behavior for
Number()andString(): they produce0and"", whileNumber(undefined)staysNaNandString(undefined)stays"undefined". ++and--use CodeMode numeric coercion (numeric strings increment, plain data objects becomeNaN, Dates use their epoch time) and reject opaque runtime references as data errors.- Unknown static members on global namespaces and on
Number/String/the coercion functions read asundefinedfor feature detection. Calling any undefined value reports a native-styleTypeErrornaming the callee, for exampleMath.sum is not a function.Blocked members (constructor,__proto__, ...) still throw, and unknownPromisestatics keep their descriptive error. Math.sumPreciseover supported collection iterables, rejecting non-number elements without coercion.- Global coercing
isFiniteandisNaN; opaque runtime references reject as data errors, likeNumber(...).
JSON and console
JSON.parseandJSON.stringifyfor supported data objects; the blocked data-key gap listed above still applies.- Numeric/string indentation for
JSON.stringify. JSON.parsereviver callbacks, including postorder traversal, deletion throughundefined, and root replacement. Revivers receive(key, value)but nothisholder because CodeMode functions intentionally have nothis.JSON.stringifyfunction and array replacers. Function replacers receive(key, value)in preorder, including the root, but nothisholder. Array replacers preserve requested property order, deduplicate names, coerce number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported.- JSON callbacks retain the blocked-key boundary: parsed or stringified data containing
__proto__,constructor, orprototypeis rejected before callback traversal. - Captured
console.log,console.info,console.debug,console.warn, andconsole.error. - Captured
console.dirandconsole.table.
Date
Date.now,Date.parse, andDate.UTC.new Date()from the current time, epoch milliseconds, a date string, another Date, or local components.Date()withoutnewreturns the current time as a string, like JS, but in deterministic ISO format rather than the host's locale/timezone string.getTime,valueOf,toISOString,toJSON, and deterministic ISOtoString.- Local getters:
getFullYear,getMonth,getDate,getDay,getHours,getMinutes,getSeconds, andgetMilliseconds. - UTC getters:
getUTCFullYear,getUTCMonth,getUTCDate,getUTCDay,getUTCHours,getUTCMinutes,getUTCSeconds, andgetUTCMilliseconds. getTimezoneOffset, arithmetic, relational comparison, andinstanceof Date.- Date values serialize to ISO strings; invalid dates serialize to
null. - Local and UTC Date setters, including native argument coercion, mutation, rollover, invalid-Date recovery, and
TimeClipbehavior. Date.prototype.toUTCStringand itstoGMTStringalias.- Native one-argument Date coercion for supported values, including booleans, null, arrays, and plain objects.
- Native Date loose-equality and default primitive-coercion semantics, using CodeMode's deterministic ISO string representation for the string primitive.
- Native
RangeErrorbranding for invalidtoISOString()calls.
Regular expressions
- Literal and
RegExp(pattern, flags)construction, with or withoutnew. test,exec, andtoString.- Readable
source,flags,lastIndex,hasIndices,global,ignoreCase,multiline,sticky,unicode,unicodeSets, anddotAll. - Captures, safe named groups (blocked member names are omitted), match
.index, and stateful global matching. - Integration with supported String methods, including function replacers.
- Writable
lastIndex. - Match
indicesmetadata for thedflag, including named groups onexec,match, andmatchAllresults. RegExp.escape.
Map and Set
- Static
Map.groupByover supported collection iterables, preserving key identity. new Map()from entry arrays or another Map.- Map
get,set,has,delete,clear,size, andforEach. new Set()from arrays, strings, or another Set.- Set
add,has,delete,clear,size, andforEach. - Materialized
keys,values, andentriesarrays for Map and Set. - Spread,
for...of,Array.from, andObject.fromEntriesintegration. - Map and Set values serialize to
{}at host/JSON boundaries. - Set composition and relation methods:
union,intersection,difference,symmetricDifference,isSubsetOf,isSupersetOf, andisDisjointFrom, including supported Set-like operands.
URL and URI helpers
encodeURI,encodeURIComponent,decodeURI, anddecodeURIComponent.new URL(input, base),URL.canParse, andURL.parse.- URL
toString,toJSON, and linkedsearchParams. - Readable URL fields:
href,origin,protocol,username,password,host,hostname,port,pathname,search, andhash. - Writable URL fields except
origin. new URLSearchParams()from query strings, data objects, pairs, Maps, and URLSearchParams.- URLSearchParams
append,delete,get,getAll,has,set,sort,forEach,keys,values,entries,toString, andsize. - URL values serialize to their href; URLSearchParams serialize to
{}.
Errors and diagnostics
Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError, andURIError, callable with or withoutnew.AggregateErrorwith the(errors, message?)signature and an ownerrorsarray, constructed directly or by an all-rejectedPromise.any.- Error
name/message, error inheritance throughinstanceof, and plain-data serialization. instanceoffor Date, RegExp, Map, Set, URL, URLSearchParams, Array, Object, Promise, and Error types.- Catchable user throws, runtime failures raised during interpreted evaluation, awaited tool failures, and awaited
tool-call-limit failures; parse/compile failures, cooperative timeout, and output bounding remain outside program
catch. - Source locations on unsupported-syntax diagnostics for JavaScript-shaped input; TypeScript transpilation may shift them.
- Sanitized model-visible diagnostics and explicit safe
ToolErrormessages. - Distinguish user-thrown failures from interpreter defects and explicit tool refusals from sanitized internal tool
failures; preserve those categories in caught errors, promise rejection handlers, and
Promise.allSettledreasons.