Morph compiles component logic from TypeScript/JavaScript to C++ at build time. There is no interpreter — code runs as native machine code.
When you write:
const [count, setCount] = morphState(0)Morph's TS→C++ translator (the morpher crate) converts this to equivalent C++ using Oxc. The translated code uses Morph's native runtime types (JsValue, JsString, Signal<T>, etc.) and runs directly in the compiled binary.
In dev mode, the translated logic is compiled to a shared library (logic.<hash>.so) loaded via dlopen. Hot reload re-wires signals and effects in place without restarting the window.
In build mode, the translated logic is compiled directly into the production binary.
Every .mx file starts by importing from morph:
import { CSS, morphState, morphEffect } from 'morph'This module is provided by node_modules/morph/index.d.ts — it ships with every morph new project and gives the editor autocomplete and type checking.
const, let, var with type annotationsvar hoisting: a var binding is function-scoped and starts as
undefined, so console.log(x); var x = 1 prints undefined and then
1; block and for declarations stay visible after their blockvar
declarations run once when the module initializes, dependency-first and
in import order; cycles re-enter a module as a no-oplet/const reads before the declaration line are
rejected by morph check (JS throws a ReferenceError), including
self-referential initializers such as let x = xlet x; and let x = null/undefined read
undefined until the first assignment, then hold any JS value — number,
string, boolean, object, array, or window handle — with real operator
semantics and no type annotation. Late-assigned window handles keep
resolving the current window on every use (see
Window handles)function declarations and expressions() => {})async / await (C++20 coroutines; see Async & Networking)fetch() with method/headers/string body request options and the
full Response API (status, ok(), statusText, headers.get/has,
text(), json(), arrayBuffer(), clone()); see
Async & Networking.on() event handlers
(lowered to one synthetic argument plus local bindings)[a, b] = ..., ({ c } = o)) with defaults,
rest elements, computed keys, nested patterns, and member targetsfor...of declaration and assignment patterns, such as
for (const [key, value] of Object.entries(object))super(), this, inferred or annotated fields, static and #private members, constructor parameter properties, getters/setters, and module-scope class expressions in direct const/let initializersimport type, inline type, export type)| TypeScript | C++ |
|---|---|---|
| int, int32, int64 | int32_t / int64_t (stack, proven range) |
| float, double | float / double (stack) |
| string | std::string (stack) or JsString if dynamic |
| boolean | bool (stack) |
| any | JsValue |
| MouseEvent | MorphEvent* |
| Element, HTMLElement | MorphNode* |
| Promise<T> | morph::Result<T> |
| Promise<void> | morph::Task |
if/else, while, for, do-while, switch/case/default (string, number, and mixed case values with JavaScript ===, fallthrough, and default), try/catch/throw, return, break, continue
Inside a component body, statements written between the declarations (branches, loops, calls) lower into a setup effect that re-runs when the state it reads changes — see Locals Reassigned in the Component Body.
Binary (+, -, *, /, **, ===, !==, ==, !=, <, >, etc.), unary (!, -, ++, --), ternary (? :), template literals, array/object literals (including object spread { ...base } and computed keys { [key]: value }), new, member access, function calls, optional chaining / nullish coalescing, and logical assignments &&=, ||=, ??=. Object literals hold data values only — keep functions as separate consts ({ handler: save } is mx-js-syntax).
0, NaN, "", null, undefined, false are falsy)**, **=) coerces both sides with ToNumber; logical assignments (&&=, ||=, ??=) short-circuit and only test null/undefined for ??=== / != with JS coercion rules, === / !==, relational operators — on native and Js* types alike (see How JavaScript Comparisons Work in Morph)"" + x)let x; … x = ...) keep JS value semantics
through every operator: + concatenates when either side is a string,
- / * / / / % coerce with ToNumber, and ++ / --, compound
assignment, unary + / - / ~, and bitwise/shift operators follow JS
conversions instead of requiring a native numeric slotlet x = 0; x = "hi"), including number | string, any, and
unknown annotations; mixed numeric classes widen to JsNumberthis.field /
ClassName.field writes; conflicting assignments widen the field to
JsLateValue, and static/private members and accessors keep JS access
rulespush/pop/index access, plus map, filter, forEach, reduce, reduceRight, find, findIndex, findLast, findLastIndex, some, every, sort, toSorted, toReversed, toSpliced, with, copyWithin, splice, shift, unshift, fill, flat, flatMap on arrays and JsArray (callbacks receive (item), (item, index), or (item, index, array))has/keys/index accessJsString and native std::string: trim, toUpperCase, toLowerCase, indexOf, substring, slice, replace, charAt, at, codePointAt, concat, plus split, startsWith, endsWith, includes, repeat, padStart, padEnd; String.fromCharCode and String.raw tagged templates are supported on the builtin. Natives lower to morph::str::* helpers, chains nest (see Native C++ Types).toString() on native int/double (lowers to morph::str::to_string)Math constants (PI, E, LN2, LN10, LOG2E, LOG10E, SQRT1_2, SQRT2) and functions (min, max, abs, floor, ceil, round, trunc, sign, pow, sqrt, cbrt, exp, expm1, log, log2, log10, log1p, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, hypot, fround, random); arguments coerce through Number() (see Runtime Types)Date: new Date(...) (epoch milliseconds, ISO text, or local calendar parts), Date.now(), Date.parse(text), getTime/valueOf, toISOString, and local/UTC getters. Invalid dates report NaN and toISOString() throws a catchable RangeError; timezone-aware formatting and setters are rejected (see Runtime Types)RegExp: literals with no flags or i, bound to a local and used directly or through an alias; .test(text) and .exec(text), with array-like exec results (m[0], m.index, m.input, m.length). Patterns match UTF-16 code units, . excludes all JS line terminators, and \s covers JS whitespace. Lookbehind, named groups, backreferences, property escapes, other flags, and generic value positions are rejected (see Runtime Types)Map/Set: new Map()/new Set() with an optional array literal, insertion-ordered get/set/add/has/delete/clear/size, keys/values/entries, for...of, and forEach. Keys use SameValueZero (NaN matches, objects by identity); aliases share storage. Annotations, parameters, returns, exports, class fields, and generic value positions are rejected (see Runtime Types)Object.assign/fromEntries/hasOwn and Array.from/of: assign object, array, and JsValue sources in order; build objects from [key, value] pairs, Maps, and Sets; test own properties on objects, arrays, and JsValues; copy arrays, strings, array-likes, Maps, Sets, and JsValues; and build arrays from values. Mapping callbacks and spread on these statics are rejected (see Runtime Types)String/Number helpers: String.at/codePointAt/concat, String.fromCharCode, String.raw tagged templates, Number.MAX_SAFE_INTEGER/MIN_SAFE_INTEGER/EPSILON/MAX_VALUE/MIN_VALUE/POSITIVE_INFINITY/NEGATIVE_INFINITY/NaN, Number.isSafeInteger, Number.parseInt/parseFloat, and Object.hasOwnProperty (see Runtime Types)URL/URLSearchParams: parse absolute URLs and relative references, read URL fields (href, protocol, host, pathname, search, hash, origin, …), and mutate url.searchParams with append/set/delete/sort. URL field assignment and unsupported members are rejected (see Runtime Types)Array.push on both JsArray (.push) and std::vector (.push_back); multi-argument push, unshift, and splice accept spread elements. .length on vectors, arrays, and strings alike (.size() where native)console.log / console.warn / console.error / console.info print natively (visible in the DevTools Logs tab){ a = 1 }), rest elements ({ ...rest }, [head, ...tail]), and computed keys ({ [key]: value }). Defaults are lazy and apply only when the value is undefined; computed keys evaluate once.for...of binding patterns. The right-hand side is evaluated once, so [a, b] = [b, a] swaps correctly; defaults, rest, computed keys, nested patterns, and member targets ([box.label] = ...) all lower. for...in destructuring is rejected — bind the key with a plain name and destructure inside the loop body.let/const bindings in for, for...of, and for...in. A closure created during the loop keeps that iteration's value (for (let i = 0; i < 3; i++) { fns[i] = () => i } records 0, 1, 2), and closures sharing one iteration's scalar binding see each other's mutations. continue preserves the same per-iteration copy semantics. Class and container values keep their existing carriers.for...in enumerates own index keys as strings (for (const i in [10, 20]) yields "0", "1"); object for...in keeps enumerating object keys.new.target inside a constructor resolves to the most-derived constructor (so a base constructor sees the subclass target), including parameter defaults, initializer lists, and arrows lexically nested in the constructor. Field initializers, methods, function expressions, and plain functions see undefined; class identifiers compare as constructor values....args) and general call/constructor spread
(f(...args), new C(...args)). Spread arguments are supported on
push/unshift/splice/concat and Math.min/Math.max.Promise.reject and Promise statics outside the supported eager shapes:
Promise.resolve(value) (including return Promise.resolve(value) in
async and Promise<T>-annotated functions), plus
Promise.all/allSettled awaited over an array literal of
fetch(...), Promise.resolve(value), or plain values, and
Promise.race/any over already-settled values. Unsupported shapes
are rejected by morph check; await and new Promise(...) lower to C++
coroutines. See Async & Networking..then/.catch forms outside the supported statement-level
fetch(...).then(...).catch(...) chain in an async function (rejected by
morph check)typeof/instanceofDate timezone-aware formatting (toString, toLocaleString), setters,
getTimezoneOffset, non-ISO parsing, and statics other than
Date.now/Date.parse (rejected by morph check)RegExp flags other than i, Unicode case folding, lastIndex/global
matching, lookbehind, named groups, backreferences, property escapes,
new RegExp(...), and : RegExp annotations (rejected by morph check)enum declarationsimport * as ns namespace imports and import.metadocument, window, localStorage, …)const/let initializer
(module-scope initializers lower to a named class; function-local and
every other position are rejected)for...in (bind the key with a plain name and
destructure inside the body)double,
template, delete, …)url.href = ...), direct String.raw(...)
calls, and calling array/string helpers whose receiver is a provably
native type in an unsupported shape (rejected by morph check)The linter (morph check) rejects the constructs listed above with a
precise error and exits non-zero. A clean morph check is the preflight
for morph build; the two commands share the same parser, graph, lint, and
IR pipeline.
Known contract gaps: some constructs still pass
morph checkand fail in generated C++ — JSX spread props, closures stored in JS arrays (Array<() => T>; use a nativestd::functionvector alias), function-local class metadata that escapes its declaring function, and others. The TypeScript App-Logic Coverage plan tracks every case and gates them behind Part 0.Scope: every JavaScript language and standard-library gap in that plan (Parts 1C–5G) is committed to implementation. Browser DOM and browser globals (
document,window,location,history,navigator, event constructors) remain out of scope; use Morph's native equivalents such asuseWindowinstead.
morph check EnforcesBeyond the supported-syntax list, these structural rules are checked before
codegen. Errors block morph build; warnings are reported but do not:
export default function (mx-export).<img> has a non-empty src
(mx-img-src).mx-event-value).key only in lists — key belongs on the root of a .map() item;
outside a list it is dead markup (mx-key-misuse, warning).class and className
(mx-dup-class, warning).'morph' must be actual runtime
exports imported under their canonical names, and module imports must
target .css, .cpp, 'morph', or a source module
(mx-import-morph, mx-import-type).windowConfig keys are known and values are
literals of the documented type (mx-windowconfig-key,
mx-windowconfig-type).morphEffect
argument is a function, never a call result or a receiver-qualified method,
and its callback declares no parameters (mx-effect-cb).morphState inside a
helper, handler, loop, conditional, or nested block is rejected
(mx-state-scope).Each rule links to its full explanation and fix in the error reference.
| Aspect | Command | Behavior |
|---|---|---|
| Default | morph file.ts |
Intent-based: escape analysis → stack/unique_ptr/shared_ptr, native types (int32_t, std::string, std::vector), type widening only when needed |
| Types | morph file.ts --type strict / --type infer |
Respect annotations, or infer from code (default) |
Orthogonal to the mode, --type controls annotations:
| Flag | Behavior |
|---|---|
--type infer (default) |
Ignore annotations, infer the cheapest native type from initializer and usage (trusted number annotations excepted) |
--type strict |
Respect annotations (number stays JsNumber); unannotated variables are still inferred |
morph app.ts --to cpp --type infer # native types + escape analysis
morph app.ts --to cpp --type strict # annotations exactly as writtenSee Intent-Based Codegen for the full memory management strategy, and Native C++ Types for how the two flags interact.