Morph's C++ runtime provides JavaScript-compatible types that handle the dynamic nature of JSX expressions.
When you get a wrapper vs a native (std::string, int64_t, std::vector<T>) is the compiler's choice, not yours: under the default --type infer the analyzer picks natives wherever the usage allows and only reaches for these wrappers for genuinely dynamic values; --type strict keeps your annotations verbatim. See Native C++ Types.
The universal value type. Every expression in JSX resolves to a JsValue which can hold:
| Type | C++ | Example |
|---|---|---|
undefined |
JsUndefined |
morphState() with no arg |
null |
JsNull |
null |
boolean |
JsBoolean |
true, false |
number |
JsNumber |
42, 3.14 |
string |
JsString |
"hello" |
array |
JsArray |
[1, 2, 3] |
object |
JsObject |
{ key: "value" } |
typeof works like JavaScript:
typeof(undefined) → "undefined"
typeof(null) → "object"
typeof(42) → "number"
typeof("hello") → "string"
typeof(true) → "boolean"Same rules as JavaScript: false, 0, NaN, "", null, and undefined are falsy; everything else — arrays (empty ones included) and objects — is truthy. See How JavaScript Comparisons Work in Morph for the full truthiness table.
== and != follow JavaScript coercion rules, === and !== check type + value — for Js* wrappers and native types alike. The translator generates morph::js_cmp helpers wherever plain C++ would answer differently. See How JavaScript Comparisons Work in Morph.
A numeric type that handles integers, doubles, and big-number strings:
JsNumber(42) // int
JsNumber(3.14) // double
JsNumber("12345678901234567890") // big stringArithmetic operators (+, -, *, /) work with proper coercion. Number formatting renders cleanly — 8 not 8.0, 2.5 not 2.500000, "Error" not nan/inf.
| Method | Description |
|---|---|
toString() |
Shortest round-tripping decimal — 0.1, 1e+21, NaN, Infinity, -0 → "0" |
toFixed(digits) |
Fixed-point string, 0–100 digits; ties round away from zero ((2.5).toFixed(0) → "3") |
toPrecision(sig) |
1–100 significant digits; switches to exponential when the exponent exceeds sig |
toExponential(frac) |
Exponential notation, 0–100 fraction digits; no argument gives the shortest mantissa |
Out-of-range digits throw a catchable RangeError like V8 (detectable with try/catch).
String type with JS-compatible methods:
| Method | Description |
|---|---|
toUpperCase() |
Convert to uppercase |
toLowerCase() |
Convert to lowercase |
trim() |
Remove whitespace |
charAt(i) |
Get character at index |
at(i) |
Code-point index with negative indexing; out of range → undefined |
codePointAt(i) |
Unicode code point at a code-point index; out of range → undefined |
concat(x, …) |
Concatenate values into a new string |
indexOf(s) |
Find substring position |
substring(start, end) |
Extract substring |
slice(start, end) |
Extract substring |
replace(old, new) |
Replace first occurrence |
split(sep) |
Split into array |
String concatenation with + works: "count: " + 42 produces "count: 42".
String.fromCharCode(...codes) builds a string from UTF-16 code units (each argument is masked to 16 bits, like JS). String.raw is supported only as a tagged template (String.raw\a\n${x}`); calling it directly is rejected. atandcodePointAtindex UTF-8 code points, which matches JS for BMP text; astral characters count as one index instead of two surrogate halves, andcodePointAtreturnsundefined` past the end.
| Form | Description |
|---|---|
Number.MAX_SAFE_INTEGER / MIN_SAFE_INTEGER |
Safe-integer bounds (±9007199254740991) |
Number.EPSILON / MAX_VALUE / MIN_VALUE |
IEEE-754 constants |
Number.POSITIVE_INFINITY / NEGATIVE_INFINITY / NaN |
Numeric sentinels |
Number.isSafeInteger(x) |
No coercion; true only for finite integral values inside the safe range |
Number.parseInt(s, radix?) / Number.parseFloat(s) |
Same lowering as the global parseInt/parseFloat |
Array backed by shared_ptr<vector<JsValue>>:
| Method | Description |
|---|---|
push(value) / pop() |
Append / remove at end |
join(sep?) |
Join elements into a string (default ,); null/undefined elements join empty |
slice(start, end?) |
Copy a subarray; negative indices count from the end |
concat(x, …) |
Concatenate values or arrays into a new array (one level deep) |
includes(v, from?) |
Strict-equality membership |
indexOf(v, from?) / lastIndexOf(v, from?) |
Strict-equality search |
at(i) |
Index access with JS negative indexing; out of range → undefined |
findLast(cb) / findLastIndex(cb) |
Search from the end; callback receives (item, index, array) |
reduceRight(cb, initial?) |
Right-to-left reduction |
toSorted(cmp?) / toReversed() |
Copying variants of sort/reverse |
toSpliced(start?, deleteCount?, …items) |
Copying variant of splice |
with(index, value) |
Copy with one index replaced; negative indices count from the end |
copyWithin(target?, start?, end?) |
Copy a range in place, returns the array; no arguments is a no-op |
reverse() |
Reverse in place, returns the array |
toString() |
Same as join() |
index(i) |
Access by index |
Array.isArray(x) answers true for arrays however they are bound — literal JsArray, JsValue, or a mutated shared_ptr<JsArray> local.
Object backed by shared_ptr<unordered_map<string, JsValue>>:
| Method | Description |
|---|---|
has(key) |
Check if key exists |
keys() / values() / entries() |
Enumerate properties |
index(key) |
Access by key (also obj["key"]) |
hasOwnProperty(key) |
Own-property check; also accepts arrays, strings, and JsValue receivers |
Object enumeration — Object.keys/values/entries and JSON.stringify — walks keys in sorted order, not JavaScript insertion order. This is a deliberate trade-off of the unordered-map runtime (O(1) point lookups, see `docs/future/shipped/kill-runtime-strings.md`); output is deterministic, but don't rely on insertion order.
String(x), Number(x), and Boolean(x) coerce with JavaScript rules:
| Call | Notes |
|---|---|
String(x) |
Arrays join with , — String([1,[2,3]]) → "1,2,3" |
Number(x) |
""/null/[] → 0, [5] → 5, [[5]] → 5, garbage → NaN; parses 0x/0b/0o prefixes |
Boolean(x) |
The falsy set above; arrays and objects are always truthy |
parseInt(s, radix?) |
Optional sign, stops at the first invalid character; parseInt("08") is 8 |
parseFloat(s) |
Like parseInt but accepts decimals/exponents; "Infinity" works |
Number.isFinite(x) / isNaN(x) / isInteger(x) |
No coercion — Number.isFinite("1") is false |
Constants: PI, E, LN2, LN10, LOG2E, LOG10E, SQRT1_2, SQRT2.
Functions: min/max (variadic, and ...spread over arrays), 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, and random. Arguments coerce through Number() (so Math.abs("x") is NaN); round rounds half toward +∞ (Math.round(-2.5) → -2); empty min/max return Infinity/-Infinity; hypot takes fixed arguments (spread is limited to min/max).
JSON.parse(text) and JSON.stringify(value):
parse is strict JSON — no trailing garbage or comments — depth-capped at 100, and throws a catchable SyntaxError on bad input.stringify follows JS: undefined array elements become null, object properties with undefined values are omitted, top-level undefined returns undefined. No reviver or replacer.JsValue; dot access reads the same field as bracket access, including on inline call results: JSON.parse(text).name is JSON.parse(text)["name"].Everything on this page is checker-gated: unsupported globals, members, or methods stay a hard morph check error rather than compiling to something surprising.
new Date(...) lowers to the native morph::Date value type (runtime/cpp/types/js_date.h). Construction:
new Date() — current time.new Date(ms) — milliseconds since the epoch. Values outside ±8.64e15 are an Invalid Date; fractional milliseconds truncate toward zero.new Date(text) — the ISO subset below; anything else is an Invalid Date.new Date(year, month, day?, hours?, minutes?, seconds?, ms?) — local calendar fields. Years 0–99 map to 1900–1999; out-of-range month/day/hour values roll over like JS. At most seven arguments.Date.now() returns the current epoch milliseconds and Date.parse(text) returns the parsed timestamp (NaN when invalid). Both produce a JsNumber.
Accepted Date.parse / new Date(text) inputs:
YYYY-MM-DD — date-only parses as UTC, matching the spec.YYYY-MM-DDTHH:MM[:SS[.sss]][Z|±HH:MM|±HHMM] — a datetime without an offset is local time; offsets accept +HHMM and +HH:MM.24:00 rolls to the next day; fractional seconds accept more than three digits and truncate to milliseconds.Instance methods: getTime, valueOf, toISOString, plus local and UTC getters — getFullYear/getUTCFullYear, getMonth/getUTCMonth, getDate/getUTCDate, getDay/getUTCDay, getHours/getUTCHours, getMinutes/getUTCMinutes, getSeconds/getUTCSeconds, getMilliseconds/getUTCMilliseconds.
Invalid dates return NaN from getTime/valueOf/getters; toISOString() throws a catchable RangeError. Timezone-aware formatting (toString, toLocaleString, toLocaleDateString, …), getTimezoneOffset, and setters are not implemented — morph check rejects them with mx-js-method. Unsupported statics (Date.UTC, Date.prototype, …) are mx-js-member; Date() without new, spreads, and over-arity calls are mx-js-syntax. Runtime tests run with TZ=UTC, so local and UTC getters agree there.
Date values are native value types, not JsValues. They can be constructed, stored in Date-typed locals and fields, passed to functions that take Date, returned, logged with console.log, and used with the methods above. Every boundary must be explicit: a parameter, return type, class field, or variable that holds a Date needs an exact : Date annotation. Unannotated boundaries (generic parameters, untyped fields and locals, unannotated returns, constructor parameters, and callbacks), destructuring a Date, assigning a Date to an untyped target, and exporting a Date or a Date-producing function/class across modules are rejected by morph check. Generic JS value positions have no lowering and are rejected too: String(date), Number(date), Boolean(date), parseInt/parseFloat(date), Math.*/Number.is* with a Date argument, JSON.stringify(date), Date.parse(date), template interpolation, string concatenation/arithmetic/comparisons, conditions, switch, array/object literals, JSX text, for...of/for...in, and unsupported members. Convert explicitly with .getTime() or .toISOString() first.
Regex literals lower to the native morph::RegExp value type (runtime/cpp/types/js_regexp.h), which matches UTF-16 code units through std::wregex — the same units JavaScript uses without the u flag. Only two flag sets are accepted: no flags, or i (ASCII-only case folding; Unicode case pairs are not folded). Every other flag (g, m, s, u, y, d, v) is an mx-js-syntax error.
Bind a literal to a local, then use it directly or through an alias:
const re = /ab+c/i
const alias = re
const ok = alias.test("xABBC") // true
const m = re.exec("xABBC")Supported pattern syntax: literals, ., ^/$, character classes and ranges, \d/\D/\w/\W, JS-aware \s/\S, \b/\B, \n/\r/\t/\f/\v/\0, \xHH, \uXXXX, \cX, identity escapes, capture groups, (?:...), lookaheads (?=...)/(?!...), and greedy/lazy *, +, ?, {m}, {m,}, {m,n}. . excludes \n, \r, U+2028, and U+2029 like JS.
morph check rejects constructs whose JS semantics std::regex cannot reproduce: lookbehind and named groups, backreferences (\1, \k<name>), Unicode property escapes (\p{...}), \u{...}, surrogate escapes, octal escapes, \S inside a character class, ranges with escape classes ([\d-a]), bare {, malformed or out-of-order quantifiers, quantifiers on lookaheads, and repeated quantifiers. new RegExp(...) and bare RegExp are rejected (mx-js-member); : RegExp annotations are rejected (mx-js-syntax).
.test(text) returns a bool. .exec(text) returns null on a miss, or an array-like JsValue on a match with numeric keys (m[0] is the full match, m[1]… are captures), length, index, input, and groups/indices set to undefined. Exec results may be indexed, read through those properties, compared with null, used as truthiness conditions, aliased, and assigned to another exec-result local. Every other sink (call arguments, returns, template interpolation, operators, array/object literals, JSX, exports, and assignment to a non-exec target) is rejected instead of emitting a native value that would not compile. Regex values themselves support only direct .test/.exec calls — no member reads, computed access, operators, conditions, reassignment, or exports. There is no lastIndex state because g/y are not implemented.
new Map() and new Set() lower to the native morph::Map / morph::Set types (runtime/cpp/types/js_collections.h). They keep insertion order and store entries as JsValues. An optional array literal seeds the collection:
const counts = new Map([["a", 1], ["b", 2]])
const seen = new Set([1, 2, 2]) // size 2Map keys use SameValueZero: NaN matches NaN, +0 and -0 are the same key, and object/array keys compare by reference identity (a fresh { id: 1 } is a different key). Copies share storage, so aliases observe each other's mutations, like JS references.
Map methods: get(key), set(key, value), has(key), delete(key), clear(), keys(), values(), entries(), and forEach(callback). Set methods: add(value), has(value), delete(value), clear(), keys(), values(), entries(), and forEach(callback). .size is a property in JS and is emitted as .size(); it is the only member that can be read without calling. delete returns a bool; set, add, clear, and forEach return void in this subset, so they must be standalone statements and cannot be chained.
keys(), values(), and entries() return a JsArray snapshot in insertion order. A Map's entries() items are [key, value] pairs; a Set's entries() items are [value, value]. for...of works directly on the collection: a Map yields [key, value] pairs (destructure with for (const [k, v] of map)), and a Set yields values. forEach callbacks receive (value, key) and may declare zero, one, or two parameters — the third JS argument (the collection itself) is rejected because it cannot be represented as a JsValue. Callbacks must be inline arrow functions or function expressions. Mutating a collection from inside its own for...of body or forEach callback (directly or through an alias) is rejected with mx-js-syntax: the native iterator cannot reproduce JS's mutation-during-iteration behavior, so Morph refuses rather than returning wrong entries. Mutating a different collection is allowed.
Collections must be bound to a local with new Map(...) / new Set(...); module-scope and component-level consts keep one identity for the process. Aliases and reassignment to another same-kind collection are allowed. Every other boundary is rejected by morph check rather than emitting a native type that does not fit: : Map<...>/: Set<...> annotations, parameters, parameter defaults, returns, exports, class fields, call arguments, JSX, template interpolation, spread, array/object literals, operators, conditions, computed access (m["size"]), destructuring, for...in, and calling a collection variable. Bare Map/Set and their static members are mx-js-member; compound assignment (m += 1) is mx-js-op. new Map(existingMap) is rejected because C++ copy semantics would share storage while JS copies the entries. Build a collection from an array literal instead.
Object.assign, Object.fromEntries, Object.hasOwn, Array.from, and Array.of lower to runtime helpers in runtime/cpp/types/js_value.h.
Object.assign(target, ...sources) copies target, applies each source in order, and returns the copy. The original target binding is mutated in place, so const same = Object.assign(obj, extra) satisfies same === obj. Sources may be objects, arrays (index properties), or JsValues (JSON.parse(...)). Targets must be objects.Object.fromEntries(entries) accepts an array of [key, value] pairs, a Map, a Set, or a JsValue. Pair keys convert with JS ToString.Object.hasOwn(object, key) accepts objects, arrays, and JsValue receivers. Array receivers answer true for "length" and in-range index keys. Keys may be strings, numbers, booleans, or JsValues.Array.from(source) accepts arrays, strings (split by code point, so an astral character is one element), array-like objects with a numeric length, Maps (each entry becomes a [key, value] pair), Sets (values), and JsValues. The mapping-callback form is rejected; call .map(...) on the result instead.Array.of(...items) builds a JsArray from its arguments. An array argument stays one nested array value.Module-scope and component-level consts keep their inferred result type at every use site, so moduleMerged.b reads through the object bracket lookup and moduleOf[1] works. Object.assign lowers to a plain runtime function (not a capturing lambda), so it is valid in namespace-scope initializers.
morph check rejects non-object Object.assign targets, primitive sources, spread arguments on these statics, Object.fromEntries arity other than one, Object.hasOwn arity other than two and non-primitive keys, Array.from mapping callbacks and unsupported inputs, and using any static as a value or via computed access (Object["assign"]). Array.of(...items) remains blocked by the general call-spread gate.
new URL(input, base?) and new URLSearchParams(init?) lower to the native morph::URL / morph::URLSearchParams value types (runtime/cpp/types/js_url.h). The URL parser handles absolute URLs and relative resolution against a base string; URLSearchParams accepts a query string, an array of [name, value] pairs, an object, another params object, or no argument.
const url = new URL("../d?q=1", "https://example.com/a/b")
const params = url.searchParams
params.append("page", "2")
console.log(url.href, params.get("q"))URL members are read-only properties: href, protocol, username, password, hostname, host, port, pathname, search, hash, origin, and searchParams. Assigning any of them is rejected (mx-js-syntax); mutate searchParams instead. toString() returns href, and URL values stringify and compare by their serialized href.
URLSearchParams supports size (property), get, getAll, has (name, or name + value), append, set, delete, sort, keys, values, entries, forEach, and toString. Mutating url.searchParams updates the URL's query. append/set require exactly a name and value; get/getAll require a name; zero-argument methods reject extra arguments. The constructor takes zero or one argument, and spread constructor arguments are rejected.
Wrapper around bool with truthiness semantics.
JsValue forwards the common string methods (toUpperCase, toLowerCase, trim, charAt, substring, slice, replace, split, toString, …), so obj["name"].toUpperCase() and arr[0].toString() work without unwrapping. Native std::string values get the same surface through morph::str::* helpers instead — see JS Methods on Natives.
All Js* types support std::format and std::println via formatters in runtime/cpp/types/js_value_format.h. Define MORPH_NO_FORMAT before including js_types.h to opt out of the <format> parse cost (~1.5s per TU) in hot-reload critical paths.