mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-10 04:58:28 +00:00
17 KiB
17 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 the feature is unavailable, incomplete, or intentionally divergent as described.- A checked item does not promise complete ECMAScript edge-case parity. Known differences are listed next to the supported surface or under Known semantic gaps.
- Intentional exclusions are boundaries, not backlog.
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. - JSON-like host boundaries with
undefinedand non-finite numbers normalized tonull. - Live Date, RegExp, Map, Set, URL, and URLSearchParams values inside the sandbox.
- Tool calls through the host-provided
toolstree only. - Cooperative timeout, tool-call accounting, output bounding, and a maximum of eight concurrent tool calls.
- Full JavaScript or TypeScript compatibility. CodeMode is a bounded orchestration language.
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 object spread.
- Template literals with interpolation.
- Regular-expression literals.
NaNandInfinityglobals.- BigInt literals and values.
- Symbols.
- Tagged template literals.
- Getters and setters 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, object fields, array indexes, and writable URL fields.
- Function declarations are hoisted within their interpreted scope.
- Parameter defaults observe a temporal dead zone for later parameters.
- JavaScript-correct
varfunction scope, hoisting, and redeclaration. Acceptedvarcurrently behaves like a lexical declaration; preferletorconst. - Complete
let/consttemporal-dead-zone and declaration-hoisting semantics. - Computed object destructuring keys such as
const { [field]: value } = record. - Object destructuring from arrays, such as
const { length } = values. - Iterable array destructuring from Map, Set, string, or URLSearchParams values.
- Dynamic property deletion with
delete object[key].
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...ofand async iteration.withanddebuggerstatements.
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, and string-replacement APIs.
Boolean,Number,String,parseInt,parseFloat, and URI helpers as callbacks where applicable.- Async string replacement callbacks; replacements are evaluated sequentially.
this,super, constructor functions, or function prototype methods such ascall,apply, andbind.- Classes and private fields.
- Generator functions and
yield. - Async predicates, reducers, and comparators with automatic awaiting. Async mapping can be joined explicitly with
Promise.all, but a promise is not a meaningful predicate or sort result. - General built-in callable references as callbacks, such as
values.map(Math.abs)orrecords.map(JSON.stringify).
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 sandbox promises; awaiting a plain value is a no-op.newfor Error types, Date, RegExp, Map, Set, URL, and URLSearchParams.- Arithmetic operators:
+,-,*,/,%, and**. - Equality and ordering:
==,!=,===,!==,<,<=,>, and>=. - Bitwise operators:
&,|,^,~,<<,>>, and>>>. - Logical operators:
&&,||,??, and!, with short-circuiting. - Unary
+, unary-,typeof,instanceof, and own-property-onlyin. - Prefix and postfix
++and--. - Plain, arithmetic, bitwise, and logical assignment operators.
- Unary
voidanddelete. - Arbitrary constructors and
new Promise(...).
Promises and tools
- Tool calls start eagerly and return supervised, run-once sandbox promises.
- Direct
await, repeated awaits, and implicit resolution when a promise is returned from a function/program. Promise.resolveandPromise.reject.Promise.all,Promise.allSettled, andPromise.raceover supported collections containing promises and plain values.Promise.allpreserves result order and rejects on the first observed failure.Promise.allSettledreturns plain fulfilled/rejected outcome records.Promise.raceinterrupts losing in-flight tool calls.- Un-awaited calls are drained before execution ends; unhandled failures become diagnostics.
try/catchcan handle awaited tool and promise failures.- Real promise values from
Promise.all,Promise.allSettled, andPromise.race. These calls currently settle before returning, so separately constructed combinator batches do not overlap as normal JavaScript promises do. Promise.any.- Promise chaining with
.then,.catch, and.finally. - Custom promise construction with
new Promise(...). - Async iterables, host streams, and stream consumption.
Objects and properties
- Own-field reads and writes on plain data objects.
- 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-sandbox Object helpers.
- Blocked access to
__proto__,constructor, andprototype. Object.is; runtime and tool-reference identity semantics need to be defined first.Object.groupBy.- Object creation, descriptors, freezing/sealing, prototype APIs, and reflection APIs.
- A final policy for legal data/tool keys named
__proto__,constructor, orprototype.
Arrays
- Static methods:
Array.isArray,Array.of, andArray.from. - 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 mapper and
thisArgforms ofArray.from. Array.prototype.toSpliced.- Canonical index handling: a key such as
"01"must not alias index1. - Complete sparse-array parity.
- Correct
findLastreturn behavior when its predicate mutates the examined element.
Strings
- Case/normalization:
toLowerCase,toUpperCase,normalize. - Trimming:
trim,trimStart,trimEnd,trimLeft, andtrimRight. - Searching/tests:
includes,startsWith,endsWith,indexOf,lastIndexOf, andsearch. - Slicing/access:
slice,substring,substr,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. - Locale/options-aware
localeCompareand locale formatting APIs. - Exact native coercion across every string method; CodeMode often requires explicit strings/numbers.
- Native no-argument parity for
match()andsearch().
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 currently do not produce0and"". - Safe interpreter coercion for
++and--rather than hostNumber(...)coercion. - Reliable feature detection for unknown static members.
Math.sumPrecise.- Global coercing
isFiniteandisNaN.
JSON and console
JSON.parseandJSON.stringify.- Numeric/string indentation for
JSON.stringify. - Captured
console.log,console.info,console.debug,console.warn, andconsole.error. - Captured
console.dirandconsole.table. JSON.parsereviver callbacks.JSON.stringifyfunction/array replacers.- Other console methods, timers, counters, groups, and host console access.
Date
Date.now,Date.parse, andDate.UTC.new Date()from the current time, epoch milliseconds, a date string, another Date, or local components.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. - Date setters.
toUTCString, locale methods, and other Date formatting methods.- Exact native constructor coercion, local-time, and loose-equality semantics.
- Native
RangeErrorbranding for invalidtoISOString()calls. - Temporal and Intl date/time APIs.
Regular expressions
- Literal and
new RegExp(pattern, flags)construction. test,exec, andtoString.- Readable
source,flags,lastIndex,global,ignoreCase,multiline,sticky,unicode, anddotAll. - Captures, named groups, match indexes, and stateful global matching.
- Integration with supported String methods, including async function replacers.
- Writable
lastIndex. - Exposed metadata for the
dandvflags. RegExp.escape.- Protection from pathological host-regex backtracking beyond the cooperative execution timeout.
Map and Set
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 methods such as
union,intersection,difference, and relation predicates. - WeakMap and WeakSet.
- Native iterator objects and custom iterators.
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.- Error
name/message, error inheritance throughinstanceof, and plain-data serialization. instanceoffor Date, RegExp, Map, Set, URL, URLSearchParams, Array, Object, Promise, and Error types.- Catchable interpreter failures and awaited tool failures.
- Source locations on unsupported-syntax diagnostics when available.
- Sanitized model-visible diagnostics and explicit safe
ToolErrormessages. - Distinct public categories for user throws, tool refusal, tool internal failure, invalid returned data, compile failures, and genuine interpreter defects.
- Preservation of detailed recoverable failure categories inside
catchandPromise.allSettled.
Known semantic gaps
These are actionable implementation items. Check them off only when behavior and direct tests land.
- Return real promises from
Promise.all,Promise.allSettled, andPromise.race. - Bound pending tool-call admission/allocation in addition to execution concurrency.
- Guarantee every advertised tool path is executable, including dotted and blocked path segments.
- Define safe outbound handling for non-finite numbers and
undefinedso invalid values cannot silently becomenullin render-only or OpenAPI tool calls. - Make regular-expression execution genuinely timeout-safe, or narrow the timeout guarantee explicitly.
- Complete lexical declaration and destructuring semantics listed above.
- Make callback acceptance and async callback behavior consistent across built-ins.
- Reject every unsupported callback argument explicitly rather than silently ignoring it.
- Resolve the built-in correctness gaps listed in the Array, String, Number, Date, and RegExp sections.
- Make tool search tokenization Unicode-aware.
- Design explicit tagged representations and size limits before adding binary values or streams.
Intentional exclusions
These constraints preserve CodeMode's confinement and host-neutral scope. They are not TODO items.
- Ambient filesystem, process, environment, credential, network, or application access.
fetch, timers, crypto, or other host globals unless a future host explicitly supplies a bounded capability.- Static imports, dynamic imports, modules, npm packages, and module loading.
eval,Function(...), arbitrary host execution, and prototype mutation.- Generic permission prompts, authorization policy, persistence, replay, or exactly-once side effects.
- Arbitrary method dispatch outside the documented allowlists.
- Automatic parsing of text tool results as JSON.
- Full browser, Node.js, Bun, or ECMAScript runtime compatibility.