ApolloVM
ApolloVM is a portable VM (native, JS/Web, Flutter) that can parse, translate, and execute multiple languages such as Dart, Java, Kotlin, Go, C#, JavaScript, TypeScript, Lua, and Python. It also provides on-the-fly compilation to Wasm.
Use Cases
- 🤖 MCP tool for LLMs — expose ApolloVM over MCP so an LLM can use it as a sandboxed reasoning scratchpad and validate generated code (parse, run, check output).
- 🔄 Cross-language translation / porting — translate and regenerate source between any supported languages to prototype, migrate, or share logic across stacks.
- 📱 Embedded scripting in Dart/Flutter — ship logic, UIs, and behavior that update live at runtime, with no rebuild or app-store redeploy.
- 📐 Business rules & formulas — define pricing, discounts, validation, and eligibility logic as editable rules in a real, familiar language, evaluated safely at runtime — no hardcoding or custom expression engine to build and maintain.
- 🔒 Sandboxed execution — run untrusted, user-supplied snippets isolated from the host, via the interpreter or compiled Wasm.
- ⚙️ On-the-fly WebAssembly — compile loaded source to portable Wasm modules at runtime (browser or native) without any external toolchain.
- 🎓 Playgrounds & education — build multi-language runners/REPLs that show the same program across languages and its translated output.
- 🧪 Reference implementations / test oracles — write an algorithm once, then run or emit it across language targets to cross-check behavior.
- 🌳 Polyglot AST tooling — parse multiple languages into one shared AST for analysis, transformation, and code generation.
- 🪶 Small, multi-platform VM — runs on native, web/JS, and Flutter; the CLI compiles to a self-contained native binary under 10 MB with all features included.
Live Example
Experience ApolloVM in action right from your browser:
- Explore the ApolloVM Web Demo
If you prefer to run the demo on your local machine:
- Follow the step-by-step instructions available in the GitHub Repository.
Supported Features
ApolloVM can parse, execute (interpret), and translate (cross-compile) source code between all supported languages, and compile to WebAssembly on the fly.
Languages
Dart, Java 11, Kotlin, Go, C#, JavaScript, TypeScript, Lua and Python.
Any supported language can be translated to any other (e.g. Java → Dart, C# → Python, Kotlin → JavaScript, Go → Dart), and code can be regenerated back to its original language.
Core capabilities
- Parsing of each language into a shared AST.
- Execution: a tree-walking interpreter runs the AST directly.
- Translation: regenerate the AST as source in any supported language.
- Wasm compilation: compile to WebAssembly, including
async/await(via Asyncify), classes (fields, constructors, instance &staticmethods,toString()dispatch,Object/dynamicboxing), exceptions, closures, lists/maps and GC types. - Null safety: nullable types (
T?),??/??=,?./?[,!and cascades — parsed from Dart, interpreted, compiled to Wasm and translated to every target, plus a flow-aware static analyzer surfaced through the LSP. See Null safety.
Control flow & operators
Legend: ✅ supported · 🧩 supported via the language's idiom · 🚧 not yet supported (exists in the language but not implemented yet) · 🚫 not applicable (the language has no such construct).
The Wasm column shows what the on-the-fly WebAssembly compiler currently supports (any source language is compiled through the same shared AST).
| Feature | Dart | Java | Kotlin | Go | C# | JS | TS | Lua | Python | Wasm |
|---|---|---|---|---|---|---|---|---|---|---|
if / else if / else | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Unbraced single-statement body¹⁴ | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
for (C-style) | ✅ | ✅ | 🚫 | ✅ | ✅ | ✅ | ✅ | 🧩¹ | 🚫 | ✅ |
for-each / for-in | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
while | ✅ | ✅ | ✅ | 🧩⁸ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
do / while | ✅ | ✅ | ✅ | 🧩⁹ | ✅ | ✅ | ✅ | 🧩² | 🚫 | ✅ |
switch / case | ✅ | ✅ | 🧩³ | ✅ | ✅ | ✅ | ✅ | 🚫 | 🧩⁴ | ✅ |
break | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
continue | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
try / catch / finally | ✅ | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
throw / raise | ✅ | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
async / await | ✅ | 🚫 | 🧩⁷ | 🚫 | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
Ternary (? :) | ✅ | ✅ | ✅ | 🧩¹⁰ | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
Arithmetic (+ - * / %) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Comparison / logical | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Bitwise (& | ^ << >> ~) | ✅ | ✅ | 🧩⁵ | 🧩¹¹ | ✅ | ✅ | ✅ | 🧩⁶ | ✅ | ✅ |
++ / --, compound assign¹⁵ | ✅ | ✅ | 🧩¹⁵ | ✅ | ✅ | ✅ | ✅ | 🧩¹⁵ | ✅ | ✅ |
assert¹⁶ | ✅ | ✅ | ✅ | 🧩¹⁶ | ✅ | 🧩¹⁶ | 🧩¹⁶ | ✅ | ✅ | 🚧 |
| Lambdas / closures | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Named / keyword arguments | ✅ | 🚫 | ✅ | 🚫 | ✅ | 🚫 | 🚫 | 🚫 | ✅ | ✅ |
| Parameter default values | ✅ | 🚫 | ✅ | 🚫 | ✅ | 🚫 | 🚫 | 🚫 | ✅ | ✅ |
| String interpolation / concat | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| List & map / dict literals | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Set literals ({1, 2})¹⁷ | ✅ | 🚧 | 🚧 | 🧩¹⁷ | 🚧 | 🚧 | 🚧 | 🧩¹⁷ | 🚧 | 🚧 |
Index access (a[i], nested m[i][j])¹² | ✅ | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | ✅ |
null / None / nil¹³ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🧩¹³ |
¹ Lua numeric-for (for i = a, b do). ² Lua repeat … until.
³ Kotlin when. ⁴ Python match / case.
⁵ Kotlin bitwise are infix functions: and/or/xor/shl/shr and .inv().
⁶ Lua bitwise use &/|/~ (xor)/<</>> and unary ~ (Lua 5.3).
⁷ Kotlin's async idiom is suspend / coroutines: ApolloVM generates suspend fun
(dropping await) when translating to Kotlin, but does not yet parse Kotlin suspend.
await unwraps the awaitable (Future<T> / Promise<T> / Task<T>) to T.
⁸ Go has no while; the condition-only for cond {} is used.
⁹ Go has no do/while; emitted as for { … if !cond { break } }.
¹⁰ Go has no ?:/if-expression; ApolloVM emits an IIFE
func() any { if c { return a } else { return b } }().
¹¹ Go bitwise use &/|/^ (xor)/<</>>, unary ^ for NOT and &^ (AND-NOT).
try/catch/throw (Go uses defer/recover/panic) and async/await
(Go uses goroutines/channels) are not applicable / not implemented yet.
¹² Reading and writing list/map entries by index/key (a[i], m['k']), including
compound assignment (a[i] += 1). Chained/nested access and assignment
(m[0][1], m['a']['b'] = v) run on the shared interpreter and are parsed from
Dart source; the other languages currently parse a single [...] only (🧩),
with nested-index parsing being extended per grammar.
¹³ The null literal and its per-language spelling (null / nil / None).
Wasm has no null value of its own and represents it as a boxed pointer, so it is
🧩 — see Null safety for the operators (??, ?., !, …) and
the Wasm limits.
¹⁴ A control-flow body may be a single statement without braces
(for (var e in l) print(e);), on if/else/else if and on every loop. A
dangling else binds to the nearest if, as in each target language. Python's
equivalent is the inline suite (if x: return 1), including the ;-joined form.
Go is 🚫 by its own spec (Block = "{" StatementList "}") and Lua has no such
form; a single-statement body translated to either is emitted braced /
do…end. The empty statement as a body (while (c) ;) is not supported.
¹⁵ Compound assignment covers = += -= *= /= ~/= %= &= |= ^= <<= >>= ??=.
Kotlin has no compound form for the bitwise/shift operators and Lua has none at
all, so those are lowered to x = x OP y (🧩).
¹⁶ Each target uses its own idiom: Dart assert(c, m);, Java assert c : m;,
Python assert c, m, Kotlin assert(c) { m }, C# Debug.Assert(c, m), Lua's
built-in assert(c, m). JS/TS have no throwing assert and Go has none at all,
so they are lowered to an explicit check (if (!(c)) throw m; /
if !(c) { panic(m) }) — 🧩. A failed assertion throws and is catchable like
any other exception. Wasm refuses to compile assert rather than mis-compile it.
¹⁷ A set literal ({1, 2}, <int>{}, Set<T> as a type) is parsed from
Dart source — a bare {} stays an empty map, as in Dart — and runs with
length, isEmpty/isNotEmpty, first/last, contains, add/addAll,
remove, clear, toList and for-in. Every target can be generated:
Java new HashSet<T>(){{ add(…); }}, Kotlin mutableSetOf<T>(…), C#
new HashSet<T>(){…}, JS/TS new Set([…]), Python {…} (set() when empty),
and — for the two languages with no set type (🧩) — Go
map[T]struct{}{…: {}} and Lua { [e] = true }. The other grammars do not
parse a set literal yet (🚧), and the Wasm backend refuses to compile one
rather than lower it to a list and lose the uniqueness.
Null safety
Dart's null-safety surface — nullable types (T?), the null-coalescing operators
?? / ??=, null-aware access ?. / ?[, the null assertion !, and cascades
.. / ?.. — is parsed from Dart source (the other grammars do not accept
this syntax yet), runs on the interpreter, compiles to Wasm within the limits
below, and is translated to every target.
Comparison against null is the exception: every grammar parses its own spelling,
including Python's is None / is not None, so a null check written in any
supported language round-trips.
Same legend as above, plus ⚠️ lossy: the construct is emitted in a form that compiles but drops its null semantics (the null check is not performed).
The null-aware accesses (?., ?[) are never lossy: a target without the
native operator lowers them to an explicit guard that yields null, so the check
is really performed — see footnote ¹¹. Only the null assertion ! is still
dropped where the target has no equivalent, and that diverges from Dart solely
in the error path (a value that should have thrown is used instead).
| Feature | Dart | Java | Kotlin | Go | C# | JS | TS | Lua | Python | Wasm |
|---|---|---|---|---|---|---|---|---|---|---|
Nullable type T? | ✅ | 🚫 | ✅¹ | 🧩² | 🚫 | 🚫 | 🧩³ | 🚫 | 🚫 | 🧩⁴ |
?? (null-coalescing) | ✅ | 🧩⁵ | ✅⁶ | 🧩⁷ | ✅ | ✅ | ✅ | 🧩⁸ | 🧩⁹ | 🧩⁴ |
??= (null-coalescing assign) | ✅ | 🧩⁵ | 🧩⁶ | 🚧¹⁰ | ✅ | ✅ | ✅ | 🧩⁸ | 🧩⁹ | 🧩⁴ |
?. (null-aware access) | ✅ | 🧩¹¹ | ✅ | 🚧¹² | ✅ | ✅ | ✅ | 🧩¹¹ | 🧩¹¹ | 🧩⁴ |
?[ (null-aware index) | ✅ | 🧩¹¹ | ✅¹³ | 🚧¹² | ✅ | ✅¹⁴ | ✅¹⁴ | 🧩¹¹ | 🧩¹¹ | 🧩⁴ |
! (null assertion) | ✅ | ⚠️ | ✅¹⁵ | 🧩¹⁶ | ✅ | 🚫¹⁷ | ✅ | ⚠️ | ⚠️ | 🧩⁴ |
Cascades .. / ?.. | ✅ | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🧩 | 🚧 |
x == null / x != null | ✅ | ✅ | ✅ | ✅¹⁸ | ✅ | ✅ | ✅ | ✅¹⁹ | ✅²⁰ | ✅ |
| Static null-safety analysis²¹ | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 |
| Enforce analysis at load²² | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 |
¹ Kotlin renders the suffix natively (Int?).
² Go has no nullable value types: a T? is generated as a pointer *T — reads
deref ((*a)), x == null compares the pointer (x == nil), and a non-null
value takes its address through a generated func goPtr[T any](v T) *T helper
(Go cannot write &5). Types already nilable in Go are left alone, so a
List<int>? stays []int, not *[]int.
³ TypeScript renders nullable types without the suffix — T? on a member is
not valid TS — while the null-aware operators are native.
⁴ Wasm has no null value of its own, so null is the boxed-Object pointer 0.
That covers everything that stays boxed: a var / Object? local, a ternary
arm, a List<Object> element, ??, == null, and string interpolation (which
prints null). A slot with a concrete Wasm type has no encoding for it — an
int is an i64 — and is reported as an UnsupportedSyntaxError naming the type
rather than compiled into a module that fails to validate.
⁵ Java has no null-coalescing operator; emitted as the ternary
(a != null ? a : b), and a ??= b as a = (a != null ? a : b).
⁶ Kotlin's null-coalescing is the Elvis operator a ?: b. It has no ??=, so
that becomes a = a ?: b.
⁷ Go has no conditional expression, so a ?? b is an inline function that
nil-checks the pointer: func() int { if a != nil { return *a }; return b }().
⁸ Lua has no null-coalescing operator, and neither a or b nor the common
a ~= nil and a or b idiom is correct — Lua treats false as falsy, so a
non-nil false would wrongly fall through. It is emitted as an
immediately-invoked function with an explicit nil test, which also evaluates
the left operand only once.
⁹ Python uses a conditional expression testing is not None, so 0 / '' /
False are preserved (an or shortcut would not).
¹⁰ Go's ??= lowering (t = t ?? v) needs the target's element type to build
the inline function's return type, which the text-level assignment hook does not
have; it is reported as unsupported. Plain ?? is unaffected.
¹¹ Java, Lua and Python have no null-aware access operator, so the access is
lowered to an explicit guard that yields null — a ternary in Java
((a != null ? a.x : null)), a conditional expression testing is not None in
Python, and an immediately-invoked function with a nil test in Lua. The guard
wraps the whole chain, so a?.m().toInt() becomes
(a != null ? a.m().toInt() : null) rather than leaving the trailing call
outside it. Like the ?? desugaring, the guard repeats the receiver, so it is
only used for receivers that are safe to evaluate twice (variables, fields and
index reads).
¹² In Go, degrading ?. / ?[ to a plain access would both skip the nil check
and yield a value where a *T is expected, so it is reported rather than
mis-emitted.
¹³ Kotlin has no ?[ operator: null-aware element access is the call
a?.get(i).
¹⁴ TypeScript's and JavaScript's null-aware element access is a?.[i], not
a?[i].
¹⁵ Kotlin's null assertion is !!.
¹⁶ Go's a! is the pointer dereference (*a), which panics on nil — the same
shape as the assertion's throw.
¹⁷ JavaScript has no null-assertion operator — a postfix ! there is logical
NOT — so a! is emitted as plain a. Dropping the token is the only
meaning-preserving option; emitting it would negate the value.
¹⁸ Go compares the pointer directly (a != nil), without dereferencing.
¹⁹ Lua's null literal is nil. ²⁰ Python compares against None by
identity (x is None / x is not None), not ==: equality dispatches through
__eq__, which a class can redefine to return True for None.
²¹ A pragmatic, flow-aware analyzer reports assigning null (or a nullable
value) to a non-nullable slot, and unconditional member/method/index access or
operator use on a nullable — with promotion for if (x != null) { … } /
if (x == null) … else { … }, and suppression via ?. / ! / ??. Its
diagnostics are surfaced through the LSP for Dart
documents. It analyzes top-level functions and class methods, constructors
and getters.
²² ApolloVM(nullSafetyChecks: true) makes loadCodeUnit throw
NullSafetyError when the AST has null-safety errors, so a mistake fails at
resolution time instead of partway through a run:
dartvar vm = ApolloVM(nullSafetyChecks: true); // class Foo { static void main(int a, int? b) { print(a); var c = a + b; } } await vm.loadCodeUnit(unit); // NullSafetyError — nothing printed, nothing executed.
Off by default, so loading is unchanged unless you opt in. Only error-severity
findings block; warnings and info stay diagnostic-only. The thrown error carries
the offending findings.
The same check is reachable without writing Dart:
shell# CLI — `run`, `translate` and `compile`; exits non-zero on a finding. apollovm run --null-safety script.dart # MCP — per call, or as the server default via `apollovm mcp --null-safety`. {"name": "apollovm.execute", "arguments": {"language": "dart", "source": "...", "nullSafety": true}}
On the MCP tools that load code (execute, translate, wasm) a finding
rejects the source; on the parse-based tools (parse, ast, symbols,
types) nothing is loaded, so the findings are added to diagnostics instead.
See doc/MCP.md.
The
⚠️cells are targets whose language has no equivalent construct: the access is emitted without its null check (a?.xbecomesa.x,a!becomesa). The generated source compiles, but a null receiver behaves differently than in the source language.??/??=are never lossy — every target either has the operator or gets a faithful desugaring.
Member-access chains
A chain of field/method accesses of any depth, in any mix of ., ?. and !
(a.b.c, a.b?.c, a.b!.c, a.b.m(), a.b?.m(x)), plus chained writes
(a.b.c = v), a field read off a parenthesized receiver ((a).v, (a)?.v) and
a call followed by a field access ((expr).m().field), are parsed from Dart
source. Each segment folds onto the previous one and reuses the same
object-access nodes, so the runtime, null-aware and code-generation behaviour is
shared. The other grammars parse a single access segment only.
Classes, types & OOP
Same legend and Wasm column semantics as the table above.
| Feature | Dart | Java | Kotlin | Go | C# | JS | TS | Lua | Python | Wasm |
|---|---|---|---|---|---|---|---|---|---|---|
| Classes | ✅ | ✅ | ✅ | 🧩⁷ | ✅ | ✅ | ✅ | 🚫 | ✅ | ✅ |
| Fields (with initializers) | ✅ | ✅ | ✅ | 🧩⁸ | ✅ | ✅ | ✅ | 🧩¹ | ✅ | ✅ |
Constructors & instantiation (new Foo(...) / Foo(...)) | ✅ | ✅ | ✅ | 🧩⁹ | ✅ | ✅ | ✅ | 🧩¹ | ✅ | ✅ |
| Methods | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Static / visibility modifiers | ✅ | ✅ | 🧩³ | 🧩¹⁰ | ✅ | 🧩² | ✅ | 🚫 | 🚫 | 🧩⁴ |
Inheritance (extends) / superclass members¹³ | ✅ | ✅ | 🚧 | 🚧 | ✅ | ✅ | ✅ | 🚫 | ✅ | 🚧 |
| Enums (rich: ctor args, fields, methods)⁶ | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚫 | ✅ | 🚫 | ✅ | ✅⁶ |
| Generics (generic classes + instantiation + type erasure) | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚫 | ✅ | 🚫 | 🚫 | 🚧 |
Type inference (var / val / auto) | ✅ | ✅ | ✅ | ✅ | ✅ | 🚫 | ✅ | 🚫 | 🚫 | ✅⁵ |
| Extensions (methods + getters)¹¹ | ✅ | 🚫 | ✅ | 🚫 | 🧩¹² | 🚫 | 🚫 | 🚫 | 🚫 | 🚧 |
| Getters / setters¹⁴ | ✅¹⁴ | 🚧 | 🧩¹⁴ | 🚫 | 🚧 | 🚧 | 🚧 | 🚫 | 🚧 | 🚧 |
Annotations / metadata (@…)¹⁵ | 🧩¹⁵ | 🚧 | 🚧 | 🚫 | 🚧 | 🚫 | 🚧 | 🚫 | 🚧 | 🚫 |
required named parameters | ✅ | 🚫 | 🧩¹⁶ | 🚫 | 🧩¹⁶ | 🚫 | 🚫 | 🚫 | 🧩¹⁶ | ✅ |
| Primary constructors (class header)¹⁷ | ✅ | 🚫 | 🚧 | 🚫 | 🚧 | 🚫 | 🚫 | 🚫 | 🚫 | ✅¹⁷ |
Private named parameters (this._x → x:)¹⁸ | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | ✅¹⁸ |
Super parameters (B(super.x))¹⁹ | ✅ | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | 🚫 | ✅¹⁹ |
¹ Lua is table-based: "fields" are table entries (obj.x), "constructors" are factory/setmetatable
idioms, methods are function Obj:method.
² JavaScript has static but no visibility keywords (privacy is by convention/closures).
³ Kotlin private/public visibility round-trips; internal/protected are parsed but not preserved
yet; no static (uses companion object, not yet supported).
⁴ Wasm compiles static methods (exported as Class.method) and instance methods (called with a
receiver); only static methods are callable as entry points, with no source-level visibility.
⁵ Wasm consumes the already type-resolved AST, so var/val-typed code compiles unchanged.
⁶ Each enum entry is a const instance of the enum's class (Dart enhanced enums): .index,
.name, EnumName.values, identity ==, plus rich-enum constructor args, fields, methods and
accessors (see footnote 14).
Java/Kotlin emit native rich enums; C#/TS/Python use a class + static-const-instances idiom; Wasm
compiles entries to heap instances (a method chained directly on an entry needs a variable first).
Breaking change: an entry is no longer an int — use .index (and .value for = N entries).
Generics are 🚫 for JS/Lua/Python: no static type syntax to parameterize.
⁷ Go has no classes; a class is modeled as a type Name struct { ... } plus receiver
methods func (o *Name) m(...) (the same idiom Lua uses for tables).
⁸ Go struct types can't carry inline field initializers, so initializers are moved into the
generated NewName factory.
⁹ Go constructors/instantiation use a func NewName(...) *Name factory (built around the
zero-valued composite literal &Name{}), and call sites read NewName(...), since Go has
no new. Every struct gets a factory, so instantiation always resolves. Only the empty-brace
composite literal is parsed; field-initializing literals (&Name{x: 1}) are not.
¹⁰ Go has no static/visibility keywords: static methods become package-level funcs and
visibility follows identifier capitalization. Inheritance, rich enums and generics
(Go embedding/iota/[T any]) are 🚧 — not implemented for Go yet.
¹¹ Members added to an existing type (a core type like int/String, or a user class) from
outside its declaration: Dart extension E on T { ... }, Kotlin top-level fun T.m() and
val T.g: R get(), C# static class E { static R M(this T self) }. A class member always wins
over an extension member, and an extension is visible only within its own module (not carried
across import). The languages marked 🚫 have no equivalent construct — prototype patching,
monkey patching and metatables are not the same thing — so generating an extension for them
throws UnsupportedSyntaxError rather than emitting a semantically different shim.
¹² C# has no extension property, so an extension declaring a getter cannot be emitted as C#;
its methods round-trip, with this/self translated both ways.
¹³ A subclass inherits its superclass's methods, fields, getters and static
fields; super.method() / super.getter / super.field reach the parent, and a
subclass override wins. Works for the languages that record their base class:
Dart, Java (extends), C# / TS / JS (: Base / extends), Python. Kotlin's
class B : A() base clause and Go embedding aren't parsed yet (🚧), and the
Wasm backend doesn't compile inheritance yet. Constructor initializer lists with
an explicit : super(v) call are not parsed yet — set an inherited field with a
super parameter (B(super.x), footnote 19) or from the constructor
body.
¹⁴ Getters and setters are parsed and executed on classes, extensions and
enum bodies (an enum member declares them like any other class member):
get name => … / get name { … } (with or without an explicit return type) and
set name(T v) { … } / set name(v) => … (typed or untyped parameter). A
setter runs on obj.x = v, this.x = v, an unqualified x = v inside the
class, and on compound forms (+=, ??=, …), which read through the getter
when there is one; ??= short-circuits, so the setter does not run when the
current value is non-null. Inherited and overridden accessors resolve through
the superclass chain. Only Dart generates them — Kotlin emits getters
(val x: T get() { … }) but not setters, and every other target refuses an
accessor with UnsupportedSyntaxError rather than dropping it. Not yet
supported, for getters and setters alike: static accessors, top-level
accessors, and an unqualified read of a getter (return value; inside a
method — use this.value).
¹⁵ Dart annotations (@override, @Deprecated('x'), @pragma(...),
@a.B(1)) are accepted wherever Dart allows them — top-level declarations,
class and enum members, enum entries, extension members, parameters and local
variable declarations — and are then discarded, so they do not survive a
round-trip. Their arguments are skipped as a balanced parenthesis group, so an
annotation using syntax ApolloVM does not model yet still cannot break the
declaration it precedes.
¹⁶ Only Dart spells a mandatory named parameter with a required modifier. The
other targets that have named parameters express it by the absence of a default
value, so the modifier is dropped when generating for them.
¹⁷ A primary constructor declares the constructor in the class header:
class Point(final int x, var int y) { … }, with ; instead of a body when
there is nothing else to declare. A parameter marked var or final also
declares the field it initializes (mutable for var, final for final); one
without either is an ordinary parameter and declares no field. Named {…} and
optional […] groups, required and default values all work, and the class may
still declare members, extends and implements. It is desugared as it is
parsed into the classic form — the induced fields plus a constructor whose
parameters are this.x formals — so every runner, generator and codec (Wasm
included) sees a shape it already handles, and Dart output comes back in the
classic form. Not supported: a named primary constructor
(class Point.custom(…)), class const Point(…), and the in-body this : …
form, all of which need constructor features ApolloVM does not have yet (named
constructors, compile-time constants, initializer lists). Kotlin and C# have
their own header/primary-constructor syntax but do not parse it yet (🚧).
¹⁸ A private named parameter is an initializing formal whose field is
private: Point({required this._x}) writes _x but is passed as x: at the
call site, with the leading _ stripped (a name with no valid public form —
__x, _ — is left alone). Only a named parameter is renamed, and only Dart
has the rule, so the parameter keeps writing its private field everywhere else,
and the declaration keeps this._x in Dart output.
¹⁹ A super parameter initializes a field the class inherits —
B(super.x), B({required super.x}), B([super.x = 9]), and in a primary
constructor header — reaching through the whole superclass chain. An
initializing formal may only name a field of its own class, so super.x is how
an inherited one is written; ApolloVM assigns that field on the instance being
built. Dart output spells it super. again (and this. for an own field), and
the distinction is re-derived from the class hierarchy when a binary AST is
decoded, so it needs no format change. The targets with no equivalent name the
parameter and drop the qualifier. What is not supported is the rest of the
initializer list: an explicit : super(v) call, and running the superclass
constructor's body — no subclass instantiation does that yet, so a
superclass constructor that computes rather than assigns is not reproduced.
Per-language behavior is normalized to a shared AST, so types and constructs map cleanly when translating between languages (e.g. C#
string⇄ DartString, JavaList<Integer>⇄ DartList<int>).
Command Line Usage
You can use the executable apollovm to run, translate or compile source
files, and to start the MCP and LSP servers.
First you should activate the package globally:
shell$> dart pub global activate apollovm
Now you can use the apollovm Dart executable:
shell$> apollovm help ApolloVM - A compact VM for Dart, Java, Kotlin, Go, C#, JavaScript, TypeScript, Lua and Python. Usage: apollovm <command> [arguments] Global options: -h, --help Print this usage information. -v, --version Show ApolloVM version. Available commands: compile Compile a source file to a binary target (WebAssembly). lsp Start the ApolloVM Language Server (LSP) over stdin/stdout. mcp ApolloVM MCP (Model Context Protocol) server and tools. run Run a source file. translate Translate a source file. Run "apollovm help <command>" for more information about a command.
To run a Java file:
shell$> apollovm run -v test/hello-world.java foo ## [RUN] File: 'test/hello-world.java' ; language: java11 > main( [foo] ) Hello World! - args: [foo] - a0: foo
To translate a Java file to Dart:
shell$> apollovm translate -v --target dart test/hello-world.java ## [TRANSLATE] File: 'test/hello-world.java' ; language: java11 > targetLanguage: dart <<<< [SOURCES_BEGIN] >>>> <<<< NAMESPACE="" >>>> <<<< CODE_UNIT_START="/test/hello-world.java" >>>> class Hello { static void main(List<String> args) { var a0 = args[0]; print('Hello World!'); print('- args: $args'); print('- a0: $a0'); } } <<<< CODE_UNIT_END="/test/hello-world.java" >>>> <<<< [SOURCES_END] >>>>
The same commands work for any supported language — the language is detected
from the file extension (.dart, .java, .kt, .go, .cs, .js, .ts,
.lua, .py), and --target accepts any of them.
Compiling ApolloVM executable.
Dart supports compilation to native self-contained executables.
To have a fast and small executable of ApolloVM, just clone the project and compile it:
shell## Go to a directory to clone the project (usually a workspace): $> cd ./some-workspace/ ## Git clone the project: $> git clone https://github.com/ApolloVM/apollovm_dart.git ## Enter the project: $> cd ./apollovm_dart ## Compile ApolloVM executable: $> dart compile exe bin/apollovm.dart ## Copy the binary to your preferred PATH: $> cp bin/apollovm.exe /usr/bin/apollovm
Now you can use apollovm as a self-executable,
even if you don't have Dart installed.
Package Usage
The examples below load source code into the VM, execute it, and regenerate it
in another language. The first two (Dart and Java) show the full host code; the
host code is identical for every language — only the language id passed to
SourceCodeUnit(...) and vm.createRunner(...) changes.
Language: Dart
Loading Dart source code, executing it, and then converting it to Java 11:
dartimport 'package:apollovm/apollovm.dart'; void main() async { var vm = ApolloVM(); var codeUnit = SourceCodeUnit( 'dart', r''' class Foo { static int main(List<Object> args) { var title = args[0]; var a = args[1]; var b = args[2] ~/ 2; var c = args[3] * 3; if (c > 120) { c = 120 ; } var str = 'variables> a: $a ; b: $b ; c: $c' ; var sumAB = a + b ; var sumABC = a + b + c; print(str); print(title); print(sumAB); print(sumABC); // Map: var map = <String,int>{ 'a': a, 'b': b, 'c': c, 'sumAB': sumAB, "sumABC": sumABC, }; print('Map: $map'); print('Map `b`: ${map['b']}'); return map['sumABC']; } } ''', id: 'test'); var loadOK = await vm.loadCodeUnit(codeUnit); if (!loadOK) { print("Can't load source!"); return; } print('---------------------------------------'); var dartRunner = vm.createRunner('dart')!; // Map the `print` function in the VM: dartRunner.externalPrintFunction = (o) => print("» $o"); var astValue = await dartRunner.executeClassMethod( '', 'Foo', 'main', positionalParameters: [ ['Sums:', 10, 30, 50] ], ); var result = astValue.getValueNoContext(); print('Result: $result'); print('---------------------------------------'); // Regenerate code in Java11: var codeStorageJava = vm.generateAllCodeIn('java11'); var allSourcesJava = await codeStorageJava.writeAllSources(); print(allSourcesJava); }
Note: the parsed function print was mapped as an external function.
Output:
text--------------------------------------- » variables> a: 10 ; b: 15 ; c: 120 » Sums: » 25 » 145 » Map: {a: 10, b: 15, c: 120, sumAB: 25, sumABC: 145} » Map `b`: 15 Result: 145 --------------------------------------- <<<< [SOURCES_BEGIN] >>>> <<<< NAMESPACE="" >>>> <<<< CODE_UNIT_START="/test" >>>> class Foo { static int main(Object[] args) { var title = args[0]; var a = args[1]; var b = args[2] / 2; var c = args[3] * 3; if (c > 120) { c = 120; } var str = "variables> a: " + a + " ; b: " + b + " ; c: " + c; var sumAB = a + b; var sumABC = a + b + c; print(str); print(title); print(sumAB); print(sumABC); var map = new HashMap<String,int>(){{ put("a", a); put("b", b); put("c", c); put("sumAB", sumAB); put("sumABC", sumABC); }}; print("Map: " + map); print("Map `b`: " + String.valueOf( map["b"] )); return map["sumABC"]; } } <<<< CODE_UNIT_END="/test" >>>> <<<< [SOURCES_END] >>>>
Language: Java 11
Loading Java 11 source code, executing it, and then converting it to Dart:
dartimport 'package:apollovm/apollovm.dart'; void main() async { var vm = ApolloVM(); var codeUnit = SourceCodeUnit( 'java11', r''' class Foo { static public void main(Object[] args) { var title = args[0]; var a = args[1]; var b = args[2]; var c = args[3]; var sumAB = a + b ; var sumABC = a + b + c; print(title); print(sumAB); print(sumABC); // Map: var map = new HashMap<String,int>(){{ put("a", a); put("b", b); put("c", c); put("sumAB", sumAB); put("sumABC", sumABC); }}; print("Map: " + map); } } ''', id: 'test'); var loadOK = await vm.loadCodeUnit(codeUnit); if (!loadOK) { throw StateError('Error parsing Java11 code!'); } var javaRunner = vm.createRunner('java11')!; // Map the `print` function in the VM: javaRunner.externalPrintFunction = (o) => print("» $o"); await javaRunner.executeClassMethod('', 'Foo', 'main', positionalParameters: [ ['Sums:', 10, 20, 30] ]); print('---------------------------------------'); // Regenerate code: var codeStorageDart = vm.generateAllCodeIn('dart'); var allSourcesDart = await codeStorageDart.writeAllSources(); print(allSourcesDart.toString()); }
Note: the parsed function print was mapped as an external function.
Output:
text» Sums: » 30 » 60 » Map: {a: 10, b: 20, c: 30, sumAB: 30, sumABC: 60} --------------------------------------- <<<< [SOURCES_BEGIN] >>>> <<<< NAMESPACE="" >>>> <<<< CODE_UNIT_START="/test" >>>> class Foo { static void main(List<Object> args) { var title = args[0]; var a = args[1]; var b = args[2]; var c = args[3]; var sumAB = a + b; var sumABC = a + b + c; print(title); print(sumAB); print(sumABC); var map = <String,int>{'a': a, 'b': b, 'c': c, 'sumAB': sumAB, 'sumABC': sumABC}; print('Map: $map'); } } <<<< CODE_UNIT_END="/test" >>>> <<<< [SOURCES_END] >>>>
The remaining languages follow the same pattern, so only each language's source
snippet is shown. Two notes that apply below: instance (non-static) methods —
Kotlin's greet, Go receiver methods, Lua's Foo:main, Python's self
methods — need a class instance, provided via classInstanceFields: const {};
and each language's native print (println, fmt.Println, …) is normalized to
the VM's print, mapped as an external function.
Language: Kotlin
kotlinclass Foo { fun greet(name: String, count: Int) { val msg = "Hello $name, you have $count messages." println(msg) } }
Kotlin support reaches parity with the Java feature set: top-level and class fun
declarations, val/var with type inference, if/else, for (x in …), while,
listOf/mapOf literals, and "$x" / "${expr}" string templates — all
translatable to Dart, Java or back to Kotlin.
Language: Go
gotype Foo struct { } func (o *Foo) greet(name string, count int) { msg := "Hello " + name + ", you have " + count + " messages." fmt.Println(msg) }
Go is bidirectional: ApolloVM parses .go/go source into the AST, executes it, and
generates idiomatic Go — package main with an import "fmt" when needed, type-after-name
declarations (func f(a int) int, x := …), for-only control flow (for cond {} for
while, for { … if !cond { break } } for do/while, for _, x := range xs {} for
for-each), Go switch (no fall-through), slices/maps ([]int{…}, map[K]V{…}) and closures
(func(x int) int { … }). Classes map to the Go idiom — a type Name struct { … } plus
receiver methods func (o *Name) m(...) — so object-oriented code round-trips to and from
Dart, Java, Kotlin, C#, JavaScript, TypeScript and Python.
Language: JavaScript
javascriptclass Foo { static greet(name, count) { let msg = `Hello ${name}, you have ${count} messages.`; print(msg); } }
JavaScript is fully bidirectional: ApolloVM can parse .js/javascript source into
the AST, execute it, and generate idiomatic modern ES (let/const, template
literals, for...of, top-level functions, ===/!==) from any loaded AST (Dart,
Java, or JavaScript).
Language: TypeScript
TypeScript is supported as a superset of JavaScript: everything JavaScript supports,
plus type annotations (variables, parameters, return types, fields), interfaces,
enums, and access modifiers (public/private/protected/readonly/static/
abstract).
typescriptclass Foo { static greet(name: string, count: number): void { let msg: string = `Hello ${name}, you have ${count} messages.`; print(msg); } }
TypeScript is bidirectional: ApolloVM parses .ts/typescript source (including
interface, enum, and member modifiers) into the AST, executes it, and generates
idiomatic TypeScript with type annotations. The same interface/enum/modifier
constructs are also supported in Dart (abstract class, enum, static/final),
so they cross-translate between Dart, TypeScript and JavaScript.
Language: Lua
luaFoo = {} Foo.__index = Foo function Foo:main(title, a, b, c) local sumAB = a + b local sumABC = a + b + c print(title) print(sumAB) print(sumABC) end
Lua is bidirectional: ApolloVM parses .lua source into the AST, executes it, and
generates idiomatic Lua (keyword-delimited blocks with end, local variables, ..
concatenation, and/or/not/~=, and generic for ... in ipairs(...)) from any
loaded AST. Object-oriented code uses the conventional table + metatable form
(Name = {}, Name.__index = Name, function Name:method(...)), so classes round-trip
to and from Dart, Java, Kotlin, JavaScript and TypeScript.
Language: Python
pythonclass Foo: def greet(self, name, count): msg = f'Hello {name}, you have {count} messages.' print(msg)
Python is bidirectional: ApolloVM parses .py/python source into the AST, executes it,
and generates strict, idiomatic Python 3. Indentation-significant blocks are handled by an
INDENT/DEDENT/NEWLINE pre-tokenizer, and generation emits PEP-484 type hints when the AST
type is statically known (def f(x: int) -> int:, x: str = ..., List[T]/Dict[K, V])
with a dynamic fallback. Supported constructs include functions, self-based methods and
class declarations, if/elif/else, while, for ... in, try/except/finally
with raise, lists & dicts, f-string interpolation, // integer division,
and/or/not, True/False/None, and import/from ... import — all
cross-translatable with Dart, Java, Kotlin, JavaScript, TypeScript and Lua.
Wasm Support
ApolloVM can compile its AST tree to WebAssembly (Wasm). This means that parsed code loaded into the VM can be compiled on the fly, without the need for any third-party tools.
-
Compiling Wasm works everywhere, out of the box, with this package alone.
-
Executing a compiled module needs a Wasm engine. Browsers have one built in. The Dart VM does not, so it needs
apollovm_wasm— a separate package, so that the native/FFI toolchain it depends on is paid for only by those who actually run Wasm on the VM:dartimport 'package:apollovm_wasm/apollovm_wasm.dart'; void main() { registerApolloVMWasmRuntime(); // now `WasmRuntime()` executes on the VM }Without it,
WasmRuntime().isSupportedisfalseon the VM.
- Status: Wasm support is under active development. It already compiles a broad subset of
the AST — functions, full control flow (
if/for/for-each/while/do-while/switch/break/continue/ternary), arithmetic/comparison/logical/bitwise operators,try/catch/throw, classes, closures, lists/maps,async/await(via Asyncify), andnullwithin its boxed-Objectdomain; see the feature table. Constructs not yet compiled to Wasm are limited to a few higher-level features (e.g. non-integerswitch), and anullin a slot with a concrete Wasm type (anintis an i64) is reported as an unsupported construct rather than mis-compiled — see Null safety.
Example compiling Dart code to WebAssembly (Wasm):
dartimport 'dart:typed_data'; import 'package:apollovm/apollovm.dart'; void main() async { var wasmBytes = await compileToWasm('dart', ''' int main( int a , double b ) { var x = (a + b) / 2 ; if (x > 1000) { return -1; } return x ; } '''); // Execute or save the compiled Wasm... } Future<Uint8List> compileToWasm(String codeLanguage, String code) async { var vm = ApolloVM(); var codeUnit = SourceCodeUnit(codeLanguage, code, id: 'test'); Object? loadError; var loadOK = false; try { loadOK = await vm.loadCodeUnit(codeUnit); } catch (e, s) { loadError = e; } if (!loadOK) { throw StateError( "Can't load source! Language: $codeLanguage\n\n$loadError"); } var storageWasm = vm.generateAllIn<BytesOutput>('wasm'); var wasmModules = await storageWasm.allEntries(); var namespace0 = wasmModules.values.first; var wasmModule = namespace0.entries.first; var wasmOutput = wasmModule.value; // BytesOutput print(wasmOutput.toString()); // Show bytes description. var wasmBytes = wasmOutput.output(); return wasmBytes; }
Generated Wasm bytes with description:
text## Wasm Magic: [0 97 115 109] ## Version 1: [1 0 0 0] ## Section: Type: ## Section Type ID: [1] ## Bytes block length: [7] ## Functions signatures: ## Types count: [1] ## Type: function: [96] ## Parameters types: [2 126 124] ## Return value: [1 126] ## Section: Function: ## Section Function ID: [3] ## Bytes block length: [2] ## Functions type indexes: [1 0] ## Section: Export: ## Section Export ID: [7] ## Bytes block length: [8] ## Exported types: ## Exported types count: [1] ## Export function: ## Function name(`main`): [4 109 97 105 110] ## Export type(function): [0] ## Type index(0): [0] ## Section: Code: ## Section Code ID: [10] ## Bytes block length: [35] ## Functions bodies: ## Bodies count: [1] ## Bytes block length: [33] ## Function body: ## Local variables count: [1] ## Declared variable count: [1] ## Declared variable type(f64): [124] ## [OP] local get: 0 $a: [32 0] ## [OP] convert i64 to f64 signed: [185] ## [OP] local get: 1 $b: [32 1] ## [OP] operator: add(f64): [160] ## [OP] push constant(i64): 2: [66 2] ## [OP] convert i64 to f64 signed: [185] ## [OP] operator: divide(f64): [163] ## [OP] local set: 2 $x: [33 2] ## [OP] local get: 2 $x: [32 2] ## [OP] push constant(i64): 1000: [66 232 7] ## [OP] convert i64 to f64 signed: [185] ## [OP] operator: greaterThan(f64): [100] ## [OP] if ( x > (int) 1000 ): [4 64] ## [OP] push constant(i64): -1: [66 127] ## [OP] return value: (int) -1: [15] ## [OP] if end: [11] ## [OP] local get: 2 $x (return): [32 2] ## f64TruncateToI64Signed: [176] ## [OP] return variable: 2 $x: [15] ## Code body end: [11]
- NOTE: When compiling to WebAssembly, ApolloVM keeps track of the stack and performs automatic type casting to facilitate operations between different types or return values.
Binary AST
Parsing dominates the cost of loading code. ApolloVM can save an already-parsed AST as a compact binary image, so an application parses once — at build time, or on first run — and afterwards loads the same code unit by decoding bytes, with no grammar and no backtracking.
Such an image is an .avma file: an Apollo Virtual Machine
Archive. It carries one parsed code unit, or a whole VM's worth of them.
On a ~4 KB program, decoding is around 11× faster than parsing, and the image is about two thirds the size of the source. (For a very small unit the fixed header and pools cost more than the source is worth; the saving appears once there is a program to speak of.)
dartimport 'package:apollovm/apollovm.dart'; import 'package:apollovm/apollovm_serialization.dart'; // Once, wherever the source is available: var vm = ApolloVM(); var codeUnit = SourceCodeUnit('dart', source, id: 'calc.dart'); await vm.loadCodeUnit(codeUnit); var image = vm.saveCodeUnitAST(codeUnit); // Uint8List // Afterwards, with no parser involved: var vm2 = ApolloVM(); await v





