Types
WebAssembly’s value types, spelled like TypeScript.
Basic types
| Type | Wasm | Description |
|---|---|---|
i32 / u32 | i32 | 32-bit integer, signed / unsigned interpretation |
i64 / u64 | i64 | 64-bit integer |
i8 u8 i16 u16 | i32 | small integers for storage; compute in i32 (below) |
isize / usize | i32 | pointer-sized — 32-bit (wasm32) |
f32 / f64 | f32 / f64 | IEEE floats |
bool | i32 | true / false |
v128 | v128 | SIMD vector; see SIMD |
- No implicit narrowing. Convert explicitly with
as:x as u8,f as i32. Float-to-int truncates and traps out of range (upstream AssemblyScript saturates). - Integer literals type contextually: a literal takes the type its
context asks for when it fits, otherwise
i32,u32,i64or, pasti64’s range,u64, so18446744073709551615 > 1holds. A literal that cannot fit a small type, or a negative one pasti64’s range, is an error rather than a wrap. - A literal past
i64’s range stays au64under ani64context too, so0x8000000000000000 % -7is 1, and beside a signed value that may be negative it computes on exact values and the type you declare reads the result; with no declared type, rasc asks for one (E3005). Below is where this follows JavaScript rather than asc. - Orderings (
<,>,<=,>=) compare values across signedness, as TypeScript numbers do:x > -1holds for everyu32x. A signed and an unsigned operand widen to a signed type that holds both,i64for 32 bit ones, and au64against a signed value tests the sign first. A constant expression folds to its value, sox > 0 - 1holds too, a constantifor loop condition takes the branch that value takes, and equality compares values as orderings do, so ani32-1never equals theu324294967295, and a comparison that can never hold warns (W3008). - Integer division and remainder by zero trap.
- No
any, noundefined, no union types; a nullable reference is writtenT?. - A line break ends a type before
[, as in TypeScript, so a[starting the next line begins a new statement rather than an array type:let o = x as Cellfollowed by a line[1, 2].forEach(…)casts and then runs the call.
Integer typing and JavaScript
Where asc and JavaScript give an integer expression different answers,
rasc’s typing rules give the answer that is right for the source as
written. They are on by default; --no-typing-rules turns them
off, and code then types as asc types it. JavaScript is
right about values: arithmetic a literal leads under a float context computes
in the float, a division there is a real division, a comparison compares
values, and &&, || and ternaries compute in
the context they sit in. Other integer arithmetic wraps in its type, as in
asc, which costs nothing. JavaScript is wrong inside bitwise operators, where it reads
every operand as int32 for want of an unsigned type, so there rasc keeps each
operand’s value, as C# does: &, | and
^ sign extend a signed operand and zero extend an unsigned one,
and the result is read in the type you declare, or else in the narrowest type
holding both: u32 & i32 is an i64, so
-1 | u stays -1. A declared 32 bit type computes them in 32 bits
wherever only the low bits matter, so hash and mask code costs nothing.
i32(a) | i32(b) gives JavaScript’s int32 result
and <u32>a | b C’s unsigned one. A u64
beside a signed value that may be negative has no type holding both, so with
no declared type it is E3005. A shift’s left decides the type it
computes in: an 8 or 16 bit left computes in i32, as C does, a
constant left takes the 64 bit type beside it, whatever the count, so
q | (1 << n) sets bit n up to 63 and
q & ~(1 << n) clears it, and a declared 64 bit type widens any left, so
let r: u64 = u << 8 keeps every bit of u,
which stops a 32 bit rotate such as (k << 15) | (k
>>> 17) rotating there
(W3017); write rotl<u32>(k,
15) for one.
>> and >>> keep their left’s
type, so >> on a u32 is logical,
>>> on an i8 shifts its own 8 bits, and
>>> on a mixed sign ^ shifts 64 bits
(W3009). A constant count that would wrap,
at or past the bits the shift computes in or below zero, as in let r =
1 << 40, is error E3008, and so
is one that shifts every bit out of a narrower type reading it. A cast
reaches every other behavior.
- Small operands. An
i8,u8,i16oru16operand of+,-,*,/,%, a<<left,~and unary-computes ini32by its value, as C, C#, Java and JavaScript promote it, solet sum: i32 = a16 + b16 + c16keeps every carry andlet s = a + bwith twou8is ani32. A small target still wraps:let x: u8 = a + b. A value an unannotated declaration holds is thati32, so two spellings that leaned on the small type need a cast:let avg = (r1 + r2) >> 1passed where au8is expected, andlet avg: u8 = s3 / 3wherelet s3 = r + g + bsumsu8parts, arei32values that au8takes only by<u8>, which keeps the low byte. - Declared wider types. A declared
i64oru64computes+,-,*, unary-and<<lefts in 64 bits, each operand extended by its own sign first, solet r: i64 = x + 1is 2147483648 atx = 2147483647andlet end: i64 = base + count * strideneeds no cast. No context reaches the operands of/or%: a small dividend computes ini32by its value and a divisor in its own type, soq + (s / 2)is 7 atq = 10ands = -6, and an unannotated declaration keeps asc’s typing. - Unsigned differences under
u64. A difference of two unsigned 32 bit operands under a declaredu64wraps in 32 bits first and widens after, as C and C# computeuint, so the clock idiom reads across a wrap of the clock:let ms: u64 = (now - last) / 1000is 4294967 atnow = 5andlast = 7,total += now - startadds the wrapped delta, and(u - w + 500) / 1000rounds the wrapped one. The whole+-chain around the difference computes inu32: au32variable, field, load, call, quotient, complement or pick of such arms counts as an operand, a never negativeu8oru16too, while a left shift, a negation, a literal that only 64 bits hold and any 64 bit operand keep their 64 bit value beside it, solet r: u64 = q + (u - w)adds the wrappedu - wtoq. A signed operand keeps the exact difference, which theu64then wraps:let d: u64 = u - xis 2^64 - 1 atu = 0,x = 1. A declaredi64keeps the exact difference, solet r: i64 = u - 1is -1 atu = 0. - Joins under 32 bit readers. Where a shift or a
bitwise operator reads a join of mixed signs, or of a narrow and a
u32, under a declared 32 bit type or an unannotated declaration, it reads the join’sint32wrap, as JavaScript does, solet slot: u32 = (h * 31 + u) >> 8andlet r = (b * 2 + 1 + hash) & 1023give JavaScript’s values;/and%read the exact value there, so(c8 * 2 + 1 + hash) % 1021is the remainder of the exact sum. A negative literal divisor divides au32dividend by its value, solet r: u32 = (n + u) % -257is 1 atn = 2,u = 256, where asc divides by 4294967039. - Shifts into the sign bit. Under a declared 64 bit
type a
<<whose left is never negative keeps every bit, solet r: u64 = (nv << 31) + uis 2147483649 atnv = 1,u = 1, and a left that may be negative shifts asint32, as JavaScript does, so((s << 24) + u) % 1024under au64is 512 ats = -256,u = 3e9. A word assembled from shifted bytes reads unsigned under au64, as C does withuint. The sign extension idiom(x << n) >> ncomputes ini32under every reader, so(b << 24) >> 24is the signed byte. A declared type is the real type:const off: i32 = b << 24; let addr: u64 = q + offadds thei32. - Names keep asc’s type. A name bound once to a
shift, a word or a join is the type asc gives it in every position, as C,
C# and JavaScript read it, whatever reads it later, so
const mk = 1 << b; flags |= mksets bitb & 31of au64flagswhere the inlineflags |= 1 << bsets bitb, andlet dt = tick - lastwith 16 bittickandlastis ani32thatnow - dtsubtracts exactly. A 64 bit reader of such a name warns (W3018); annotate the name (const mk: u64 = 1 << b) or write the shift inline to shift in 64 bits. - Constants take the 64 bit type beside them, keeping
their sign, through signs,
~,+,-,*,&,|,^, picks and a<<left, whatever 32 bit operand sits beside them on the way, soq & ~(1 << 31)clears bit 31 only andq & ~(0x10 | FLC)keeps the high half ofq. Aconstwithout a type whose initializer is only literals stands for that initializer wherever a context types a literal, so withconst B31 = 1 << 31,q & ~B31does the same, while a typed constant keeps its type. A join of narrower operands never retypes a constant, nor does a declared type reach one inside a comparison, and a closure reads a constant it captures as its function does. ~complements in its operand’s own type, as C# does, soq & ~FLAwithFLA: u32clears the high 32 bits ofqtoo, which W3016 points out; write~<u64>FLAto clear only its bits. A literal or untyped constant inside it still takes a 64 bit reader’s type, solet m: u64 = ~(1 << n)clears only bitn, asq & ~(1 << n)does, while a variable keeps its own type, so~(h << n)withh: u16shifts ini32. Unary-does the same beside a 64 bit operand, soq & -FLCnegates inu32, while a declared 64 bit type negates exactly.- Mixed signs. A pick or comparison whose sides have
different signs computes the chain of sums, differences, products and
negations leading each side in a type holding both, so
let last = found ? -1 : count - 1is -1 atcount = 0andx == u - 1is true atx = -1,u = 0. That type is ani64for au32beside a signed value, so a local holding such a pick needs a cast where ani32oru32is expected:let i = c ? count - 1 : -1; arr[i]is an error, whilearr[c ? count - 1 : -1]reads the index directly. A declared type of 32 bits or less changes nothing, as it keeps only the low bits, solet r: u32 = (x * y) || utests the product’s 32 bits. An equality whose sides may read one bit pattern as two numbers warns (W3013). - A bool left of
&&or||yields the number it picks, as JavaScript does:let n = c && xisxor 0, ani32, andc || xis 1 orx. It has the number’s type, so a 64 bit number needs a cast where the bool converted implicitly:let r: f64 = 65535 & (c && q)with au64qis an error, and<f64>(65535 & (c && q))converts it. - Narrow loads. In a condition, or under an
f64context or an explicit cast to a float, including the left of an&&or||there, the left operand of a shift computes ini32, and aload<u8>orload<u16>there widens to it, soif ((load<u8>(p) << 8 | load<u8>(p + 1)) == 0xFFD8)keeps the high byte;&,|and^keep each operand’s value. asc computes these ini64underf64; write<i64>load<u8>(p)for 64 bits. An explicit cast tof32computes them ini32too, since the cast converts it. Thef64a compiler infers for an unannotated declaration, an array element or a generic argument is no float context, and an implicitf32context keeps the operand’s own width, since ani32does not convert tof32implicitly. &&and||give their left operand a declared context, never one an operand’s type gave, so a fallback leaves the arithmetic it guards alone:let ns: i64 = 1000000 * ms || 1000000000multiplies ini64, andlet r: u64 = (1 << k) || 7shifts in 64 bits, sok = 31gives bit 31 rather than a negative value. A right operand the left cannot hold joins with it, son || 0.5is anf64. A literal left whose truth makes the right the result only gates it: a right an operator computes takes a declared integer context through it, solet r: i64 = 2 && (u - 0)subtracts ini64, and a leaf right keeps its values where the literal’s own type cannot hold them, solet r: i64 = 0xFFFF0000 && sissand1 && 0x80000000compared to 24 is 2147483648. Under a float context only arithmetic a literal leads on the left takes the float type.- Compound assignments compute in their target’s
type, which is fixed, so their right operand takes it as a declared
context:
r += (1 << k) || 7withr: u64adds bit 31 atk = 31, andacc += 1 / nwithacc: f64divides in floats. - Ternary arms. When the then arm converts exactly to a
wider declared context, the else arm compiles in that context wherever
this can change its value:
let mask: i32 = b != 0 ? b : 1 << kwithb: u8shifts ini32,c ? b : -1is-1, andlet r: i64 = c ? x : (0xFFFF0000 & u)is the masked unsigned value, 3999989760 foru = 4000000000, where JavaScript and rasc without the rules give int32’s -294977536. Arms whose join would misread one take that context too, solet r: f64 = c ? s : (0xFF000000 & w)keepssnegative. Under an explicit cast every arm converts to the cast’s type, sof32(inv ? 1 / scale : offset)compiles and divides in floats, and an integer cast wraps an integer arm rather than truncating the float a float arm would join it to. - Wrapping literals. A literal a 32 bit context holds
only by wrapping,
0x80000000to0xFFFFFFFFunder a signed type or a negative literal under an unsigned one, computes by its value where its result is used in place, as by an annotated declaration, a parameter, a return, a comparison or a cast:let s: i32 = 0xFFFFFFFF / ndivides 4294967295. A quotient that onlyi64holds divides there and wraps back, as does a dividend such a literal leads, solet r: u32 = (-1 / w) + xis the signed quotient. A bitwise operator applies its typed meaning to the literal’s own value, solet m: i32 = 0xFFFFFFFF >> 27is the mask 31 and(0xFFFFFFFF - argb) >> 24is a byte, where JavaScript gives -1 and a negative number; write<i32>0xFFFFFFFF >> 27for -1. A type the compiler infers, for an unannotated declaration at any scope, an array literal or a generic argument, keeps the typing by context, since another type could stop an array or generic it reaches from compiling, and so does a template literal’s interpolation, a method’s receiver or a switch value, which read what the same declaration would:let m = 0xFFFFFFFF & ustays au32, and W3007 flags it where the wrap shows. - Comparisons compare values: a literal the context
would wrap compares in the type its value picks,
u16(-255 == load<u16>(p))is 0 for a load of 65281, a signed load keeps its sign under an unsigned context, sostore<u16>(q, load<i8>(p) >= load<u16>(p + 2))orders -128 below anyu16, and a quotient a comparison widens stays whole on either side. A negative constant beside au64keeps its sign on either side, soq > -(1 << 31)is true. Equality compares values too. - Narrow operands and wide literals. A literal an
8 or 16 bit operand cannot hold computes in its own type, as asc does,
so
b % 300withb: u8isbandh == -2withh: u16is false, where rasc without the rules stops with a conversion error. - Divisors of the other sign. A literal over a
divisor of the other sign divides by the divisor’s value, so
let r: u32 = 100 / xwithx = -5is the wrapped -20 andlet r: i32 = 100 / uwithu = 0xFFFFFFFFis 0, where asc reinterprets the divisor. Only a divisor whose value is its own, a leaf or a bitwise operator, divides so; another keeps its typing. - Arithmetic under a float context. Under an
f32orf64context,+,-,*and/a literal leads compute in floats wherever floats give another value, as asc and JavaScript do, when each other operand converts exactly, up to 32 bits forf64and 16 forf32or any 32 bit integer an explicit cast converts:let r: f64 = 1 - uis -1,let r: f64 = 100000 * xis 1010 forx = 100000,1 / (a - b)divides in floats, and the constant folder agrees, soconst STEP: f64 = 1 / FPSis 0.016666666666666666. Anf32context rounds once, as JavaScript does: it computes inf64, sof32(1 + w)is 16777218 forw: u32 = 16777217, and leaves a sum or product of signed integers of 32 bits or more in integers, which round once too and differ only where they overflow, and a spine of only floats in its own float arithmetic, sof32(0.1 * f)multiplies inf32. An operand whose own integer arithmetic can wrap keeps+,-and*in integers, where the wrap cancels, and a remainder stays in integers the float holds exactly;<i32>1 / ndivides integers anywhere. Any integer quotient a float context reaches divides for real, as JavaScript does, solet gray: f64 = (r + g + b) / 3is 85.333… foru8channels summing to 256, not 85, a product no 64 bit type holds multiplies for real under anf64, and a small sum, difference or producti32cannot hold computes ini64there, so<f64>((65535 * h) % 7)is 1 forh = 65535. - A literal beside an unsigned or small operand. With
no integer context, a literal takes the other operand’s type, so
let left = 60 - elapsedwithelapsed: u32is au32that never goes below 0, where JavaScript gives-15. rasc keeps that typing, which existing code relies on, for examplelet mask = 1 << bitfor au8field, and warns W3007 where the value can leave the type and a consumer shows it; annotatelet left: i32, or elsewhere cast it or an operand. W3008 flags the comparison such a countdown usually ends in, an unsigned value ordered against 0. - Picks.
&&,||and?:yield the picked operand’s value; between au32and ani32the result is ani64, and between au64and a signed value with no declared type it is E3005. - Division by zero. Integer division and remainder by
zero trap, as in C# and Rust, and a divisor that is always zero, a
literal, a constant or a folded constant, is error
E3006. Under a float context
/gives ±Infinity or NaN and%gives NaN, as JavaScript does.
Small integers
WebAssembly has no 8 or 16 bit values. Locals, parameters, returns and
the operand stack hold only 32 and 64 bit integers and floats, so an
i8, u8, i16 or u16 is a
wasm i32 everywhere except memory. Memory is the one place with
real 8 and 16 bit values: loads and stores of those widths read and write
exactly one or two bytes.
The results still behave like true small integers, as in upstream
AssemblyScript. Arithmetic
runs at 32 bits and may leave extra high bits, and every use that could see
them narrows first: comparisons, division, remainder, right shifts,
**, conversions to other types, conditions, returns,
switch, and the integer builtins abs,
clz, ctz, popcnt, min and
max. rotl and rotr rotate within the
small width, and constant folding follows the same rule. The
narrowing is one extra instruction, a small cost in a tight loop that compares
or divides small integers.
Addition, subtraction, multiplication, &, |,
^ and << never need it.
Store in small types, compute in i32. Declare fields,
arrays and struct members as u8 or i16 to save
bytes, where the store narrows for free. Declare locals, parameters, loop
counters and return values as i32 or u32, which
never narrow. Read a small field into an i32, work on it,
and cast once when you store it back.
declare function print(s: string): void;
class Pixel { r: u8 = 0; g: u8 = 0; }
export function demo(): void {
let x: u8 = 255;
x++;
print(x.toString()); // 0, as in C and asc
let p = new Pixel();
p.r = 200;
p.g = 200;
print(((p.r + p.g) >> 1).toString()); // 200, a u8 sum computes in i32
// Compute in i32: no overflow and nothing to narrow.
let r: i32 = p.r;
let g: i32 = p.g;
p.r = <u8>((r + g) >> 1);
print(p.r.toString()); // 200
}
The u8 sum computes in i32 before the shift, as C
computes it. With --no-typing-rules it wraps in u8
first, as asc computes it, and the second line prints 72.
Nullability
Nullable types are reference-only: string?,
C?, (() => i32)?, with T?[] an
array of nullable elements and T[]? a nullable array. There are
no other unions, so T | null is an error. A nullable basic type
(i32?) is a compile error. Nullability folds correctly per
generic instance, so nullable array elements behave. Value classes exclude
nullability entirely: null refuses a value-class target at compile
time.
After x as T a ? followed by an operand starts a
ternary, as in Dart. At the end of a line it makes T nullable, so
a statement can end there without a semicolon, unless the next line is a
ternary branch followed by its :. In a class body a member on the
next line ends the field instead, so a field's ternary broken after
as T ? needs that ? on the next line or
parentheses. A basic type such as bool can never be nullable,
so after a cast to one the ternary wins unless the next line can only be a
member: one with an initializer or a body, or a field of a basic type or
string.
The checker enforces the flag with a definite non-null analysis. A member
access, call, index, for..of or cascade on a nullable value warns
(W3004) unless the value is proven
non-null on that path, and so does a nullable value, or null itself,
stored into a non-nullable local, parameter, field, element or return. A proof
comes from if (x != null) and if (x) for the then
branch, if (x == null) for the else branch or for the rest of the
block when the then branch returns, breaks, continues or throws, the right side
of x != null && … and x == null || …, an
assignment of a proven value, x ??= y or x ||= y
with y proven, assert(x != null), and
x!, which proves x from then on. A ternary,
a || b or a ?? b whose arms are both proven counts
as proven too.
Four operators work on nullable values, as in Dart:
x!assertsxis not null and traps when it is. The check is skipped when the analysis already provedx, and insideunchecked().a ?? bisaunless it is null, evaluatingbonly then. The result is nullable only whenbis. Beside||or&&it needs parentheses, as in TypeScript.a ??= bstoresbintoawhenais null.a?.b,a?.m(),a?.[i]andf?.()stop at a null link and yield null for the whole chain, skipping everything after it, arguments included. A chain ending in a basic type such asa?.lengthcannot be null, so it needs a fallback,a?.length ?? 0, unless its value is dropped.
Field chains narrow like locals: after if (this.context != null)
the chain this.context stays proven until a store through any
prefix of it (this.context = …) or a method call on a proper
prefix (this.reset()), since a method can store into its
receiver's fields. A call on the chain itself (this.context.grow())
keeps the chain and only drops what sits below it. Inside a loop, every key the
loop stores or calls through is unproven for the whole loop; a closure starts
with no proofs, since captures are copies.
declare function print(s: string): void;
function firstName(names: Array<string?>): string {
let n = names[0];
if (n != null) {
return n; // narrowed to string
}
return "anonymous";
}
class User {
name: string? = null;
manager: User? = null;
}
export function demo(): void {
let empty: Array<string?> = [null, "rasc"];
let named: Array<string?> = ["rasc", null];
print(firstName(empty)); // anonymous
print(firstName(named)); // rasc
let user = new User();
print((user.manager?.name?.length ?? 0).toString()); // 0
user.manager ??= new User();
user.manager.name = "Ada";
print(user.manager?.name ?? "nobody"); // Ada
}
Array<T?> literals need an explicitly annotated
local before they can be assigned somewhere that expects the nullable element
type.
Narrowing never changes a type, only whether the checker warns, so
x != null ? x : y still has the nullable type. A proof about a
local or parameter also lets ! and ?. skip their
runtime null check; one about a global or a field does not, since a call or
another reference to the same object can null it without the checker seeing.
Reference classes
Ordinary classes are managed heap objects: a small header followed by
naturally aligned fields. The header holds the runtime class id, which drives
instanceof, virtual dispatch, and garbage collection.
@unmanaged classes drop all of that — raw structs for
low-level work, so they cannot implement interfaces, override methods, or
extend or be extended by managed classes.
An interface, generic ones included, types a reference to any class that implements it, and calls through it dispatch on the runtime class. The compiler checks each implementation against every member of the interface; see Classes & Generics.
Value classes
struct types are plain-old-data with copy semantics — they live
in wasm locals, flatten into their containers, and never allocate. They get
their own chapter.
Function types
function apply(g: (x: i32) => i32, v: i32): i32 {
return g(v);
}
export function demo(): i32 {
let f: (x: i32) => i32 = (x: i32): i32 => x + 1;
return apply(f, 41); // 42
}
Plain functions and capturing closures mix freely behind the same function
type, and a function-typed field or accessor calls directly:
obj.fn(x). See Closures &
Iteration.
Enums and namespaces
enum Color { Red, Green = 5, Blue } // Blue == 6; values must be constant
namespace Geo {
export function area(w: f64, h: f64): f64 { return w * h; }
}
export function demo(): f64 {
return Geo.area(6, 7) + Color.Blue; // 48
}
Nested namespace paths resolve through scopes and enums
(String.UTF8.ErrorMode). Inside a namespace a member’s own
name is that member, as in TypeScript, even in its own initializer, so
namespace N { export const x = x + 1; } is an error, “'x'
is read in its own initialization cycle”, rather than a read of an outer
x. A member with a declared type reads its own zero there
instead, as a top-level const y: i32 = y + 1 does.
SIMD
v128 works as locals, params, returns, and class fields, with
f32x4 and i32x4 builtin families (splat, lane access,
arithmetic, compares, abs/neg/sqrt, min/max, bitmask) plus the bitwise
v128 operations, loads, stores and lane shuffles. SIMD is on by
default in a Rive project. There is no v128.const, so there are no
v128 globals. See SIMD for the full list and for keeping
a scalar path beside the SIMD one with ASC_FEATURE_SIMD.
Type queries and layout builtins
sizeof<T>(), alignof<T>(),
offsetof<T>("field") const-fold. For value classes they report
payload size and alignment; for reference classes, pointer size.
idof<T>() gives the runtime class id;
isDefined, isBoolean, isArray,
isFunction, and isNullable<T>() fold per
monomorphized instance — pair them with constant if folding for
compile-time specialization.