Control Flow
Tyrus supports familiar statement forms for branching, looping, and early exits. The checker validates initialization, ownership, and return paths.
Conditionals
if (enabled) {
print("enabled");
} else if (fallback) {
print("fallback");
} else {
print("disabled");
}The condition is a boolean, or a T? used as a presence test: an optional is truthy when it holds a value. The same applies to while, for, the ternary ? :, &&, ||, and !. In the branch where the optional is known present, an if body, the truthy side of a ternary, or the right side of &&, it narrows to its non-optional type.
Conditions and short-circuit statements
const user: User? = find();
// Ternary and `&&` narrow the optional to its present type in the truthy branch.
const label: string = user ? user.name : "anonymous";
const isAda: boolean = user && user.name === "Ada";
// A logical expression statement runs the right side for its side effect.
const enabled: boolean = ready();
enabled && notify();
invalid() || abort();cond && effect(); and cond || effect(); are also valid statements: they run the right side for its short-circuit side effect, so the right side may return void.
while
let index = 0;
while (index < 3) {
print(index); // 0, 1, 2
index += 1;
}do...while
let attempts = 0;
do {
attempts += 1;
print(attempts); // 1, 2, 3
} while (attempts < 3);do...while runs the body at least once.
loop
let index = 0;
loop {
index += 1;
if (index < 3) {
continue;
}
if (index === 5) {
break;
}
print(index); // 3, 4
}
const found: i32 = loop {
break 42;
};
print(found); // 42loop repeats its body forever until a break. Unlike while, it never evaluates a condition, so it is the natural form for loops that exit mid-body. When every break in the body carries a value, the loop is an expression: it evaluates to the value passed to the break that exits it, so loop { break 42; } has type i32. continue skips to the next repetition. A break with a value is only allowed inside a loop expression (E0571); break without a value always works as in any other loop.
Classic for
for (let index: u32 = 0; index < 3; index += 1) {
print(index); // 0, 1, 2
}
const names = ["Neo", "Trinity"];
for (let i = 0; i < names.length; i++) {
print(names[i]); // Neo, Trinity
}A counter written without an annotation takes its type from the loop bound: i above is the usize that length yields, so it indexes the array directly and needs no annotation of its own. A counter measured against a signed bound stays i32, which keeps arithmetic that dips below zero valid. Annotate the counter when you want to pick the type yourself; the annotation always wins.
for...of
const names: string[] = ["Neo", "Trinity", "Morpheus"];
for (const name of names) {
print(name); // "Neo", "Trinity", "Morpheus"
}Use for...of for arrays and iterable runtime values. The binding may destructure each element with an array/tuple pattern [a, b] or an object pattern { x, y }, which pairs well with a Map's [key, value] entries.
const pairs: [i32, i32][] = [[1, 2], [3, 4]];
for (const [left, right] of pairs) {
print(left + right); // 3, 7
}
const scores = Map<string, i32>();
scores.set("Smith", 1);
for (const [name, score] of scores.entries()) {
print(name, score); // "Smith" 1
}for...of also iterates a Range directly, binding each of its numeric values in turn, a..b excludes b, a..=b includes it.
let sum = 0;
for (const i of 0..5) {
sum += i;
}
print(sum); // 10 (0..5 excludes 5)const main = (): void => {
for (const i of 0..=3) {
print(i); // 0, 1, 2, 3 (0..=3 includes 3)
}
};for...in
interface Config {
host: string;
port: i32;
}
const config: Config = { host: "localhost", port: 8080 };
for (const key in config) {
print(key); // "host", "port"
}for...in iterates over the field names of an object. An array is not an object type, so reach for keys() with for...of when the index is the value you need; array indexes are usize in the native collection API.
const labels: string[] = ["zero", "one"];
for (const index of labels.keys()) {
print(index); // 0, 1
}break and continue
for (let index: u32 = 0; index < 10; index += 1) {
if (index === 2) {
continue;
}
if (index === 5) {
break;
}
print(index); // 0, 1, 3, 4
}break exits the nearest enclosing loop or switch. continue advances the nearest enclosing loop and also works from inside a nested switch or match. A match arm never falls through and rejects a break that could otherwise target an outer control structure (E0269). A break outside every loop and switch, or a continue outside every loop, is an error (E0268).
return
function label(enabled: boolean): string {
if (enabled) {
return "enabled";
}
return "disabled";
}The checker rejects functions with non-void returns that can fall through without returning a value.
defer and errdefer
function process(): void {
defer print("finished");
defer { print("released"); }
print("working");
}
function transfer(ok: boolean): Result<void, i32> {
defer print("always");
errdefer { print("rollback"); }
if (!ok) { return Err(1); }
return Ok();
}defer registers one expression or a block to run when its current lexical scope exits. errdefer has the same two forms but runs only when that scope exits by an explicit error return or by propagating an error with ?. Both are ambient language keywords and need no import. Finalizers run in LIFO order; on an error exit, the scope's errdefer finalizers run first, then its defer finalizers. Nested scopes complete before their parent scope.
The body captures values from its registration point. It cannot use return, break, continue, throw, await, or ?, because cleanup must not replace the exit already in progress. errdefer requires a Result<T, E> or T? return type. Finalizers are currently supported in synchronous functions only. panic() aborts immediately and does not run either finalizer, so recoverable cleanup must use a structured error path.
switch and match
switch is a control-flow statement for comparing one subject against literal cases. Use it for simple dispatch over primitive values or enums.
const role: string = "admin";
switch (role) {
case "admin": {
print("full access");
break;
}
case "operator": {
print("limited access");
break;
}
default: {
print("read-only access");
}
}Use switch for simple dispatch
Use switch when the subject is a primitive value and each branch is a literal equality check.
Fallthrough and Break
Execution falls through from a matched case into each following body. Use break to exit the nearest switch (or loop). Omitting it is useful when multiple cases share behavior:
switch (role) {
case "admin": {
print("privileged");
}
case "operator": {
print("authenticated");
break;
}
default: {
print("anonymous");
}
}With "admin", this prints both privileged and authenticated. continue inside a switch still advances the nearest enclosing loop. Unlike switch, match never falls through.
Duplicate Cases
The linter reports repeated cases because the second branch is unreachable.
error
switch (role) {
case "admin": {
print("first");
}
case "admin": {
print("duplicate");
}
}error
error[E0003]: duplicate match case
--> src/main.tyr:4:10
|
2 | case "admin": {
| ^^^^^^^ first use here
4 | case "admin": { // [!code error]
| ^^^^^^^ duplicate case
|
help: remove the duplicate case or use a different valueSwitch vs Match
Use match when the branch needs destructuring, guarded arms, or narrowing over a tagged union. Use switch to dispatch over an enum or a literal value.
enum PaymentStatus {
Pending,
Paid,
Refused,
}
const status: PaymentStatus = PaymentStatus.Paid;
switch (status) {
case PaymentStatus.Pending: {
print("pending");
break;
}
case PaymentStatus.Paid: {
print("paid");
break;
}
case PaymentStatus.Refused: {
print("refused");
break;
}
}Match patterns are not enum members
A match pattern is a wildcard, a binding, an object pattern, or a literal. An enum member such as PaymentStatus.Paid is not a pattern, so dispatch over an enum with switch and keep match for tagged unions and guarded arms.
throw and try/catch/finally
try {
run();
} catch (error: string) {
printError(error);
} finally {
cleanup();
}A catch without a type binds Error, the interface with message and code that recoverable errors use, so error.message and error.code are available without an annotation. A thrown string or any other type still needs its type written, as in catch (error: string).
function load(): void throws Error {
const failure: Error = { message: "config file is missing", code: "ERR_CONFIG_MISSING" };
throw failure;
}
const main = (): void => {
try {
load();
} catch (error) {
console.error(`${error.code}: ${error.message}`);
}
};The finally block runs before control leaves try or catch, including through return, throw, break, or continue.
Avoid unsafe finally flow
Returning, throwing, breaking, or continuing from finally can override the original control flow and is reported by lint rules.
