matchExpr
On this page

matchExpr()

Function in Authoring

A typed multi-arm dispatch over a scalar scrutinee, the expression form of switch (scrutinee) { case v0: r0; …; default: dflt }.

import { matchExpr } from 'typeshade'

The signature, the description and the examples come from the compiler's own source at commit 26de7be8.

Syntax

function matchExpr<S extends ScalarKey, R extends string>(
scrutinee: ReadonlyNode<S>,
cases: ReadonlyArray<
readonly [caseValue: number, value: ReadonlyNode<R> | (() => ReadonlyNode<R>)]
>,
default_: ReadonlyNode<R> | (() => ReadonlyNode<R>),
): Node<R>

Parameters

scrutinee ReadonlyNode<S>
cases ReadonlyArray< readonly [caseValue: number, value: ReadonlyNode<R> | (() => ReadonlyNode<R>)] >
default_ ReadonlyNode<R> | (() => ReadonlyNode<R>)

Return value

Node<R>

Exceptions

TypeShadeError

SD0011 when an arm’s type differs from the default’s.

Description

Each arm pairs an integer case value with its result, given either as a node or as a zero-argument function that builds one; the default takes the same two forms. Before emit, every matchExpr in a function body is rewritten into a var slot and a switch statement that writes each arm’s value into it. A match with ten or more arms casts a non-integer scrutinee to i32, since a WGSL switch is integer-only.

Every arm’s type must equal the default’s. The shared R extends string bound rejects most mismatches at tsc; one that reaches the runtime throws.

Examples

Example

import { fn, matchExpr, f32, u32T } from 'typeshade'
const width = fn('width', { kind: u32T }, ({ kind }) =>
matchExpr(kind, [[0, f32(1)], [1, () => f32(2)]], f32(0.5)),
)

In the guide

See also

Source

src/core/ir/node.ts, line 2302, at commit 26de7be8

Edit this page Report a problem