1
Language ControlFlow
erick-alcachofa edited this page 2025-12-30 03:08:14 +00:00

Control Flow

This section outlines the control-flow constructs currently supported by the artichoke parser, including variable declarations, loops, pattern unwrapping, and resource management.

Variable Declarations

let x: i32 = 10;
let answer = meaning_of_life();
def PI: f64 = 3.14159265358979;

def ptr: *i32 = &answer;
let mutable_pointer: *$i32 = &x;
let complex_pointer: *$*$i32 = &mutable_pointer;
let null_int: ?i32 = null;
  • let declares mutable bindings; def declares immutable ones.
  • Pointer/mutability/optional qualifiers (*, $, ?) attach immediately to the type on their right.

if / else

if (foo()) |ok_val| {
  /* success path */
} else |err_val| {
  /* error path */
}

if (condition) {
  /* then */
} else if (other_condition) {
  /* else-if */
} else {
  /* final branch */
}
  • Unwrap clauses (|name|) bind Result or optional values for the block.
  • Parentheses around conditions are required.

match

match (foo()) {
  Result::<i32, []u8>::Ok |v| -> {
    std::io::print("Success!");
  }
  _ -> {
    /* default */
  }
}
  • Patterns accept type expressions and optional bindings.
  • _ handles unmatched cases.

switch

switch (value) {
  0 -> { /* ... */ }
  (1 + 2) -> { /* ... */ }
  _ -> { /* ... */ }
}
  • Value-based branching for expressions.

Loops

while (foo()) |ok_val| {
  /* loop while Ok */
} else |err_val| {
  /* handles Err */
}

while (foo.next()) |item| {
  /* iterator-style loop */
}

do {
  /* body */
} while (true);

for (let i = 0; i < 10; i += 1) {
  /* C-style loop */
}

for (let element := returns_range_function()) {
  /* range loop */
}

outer_loop := while (condition) {
  inner_loop := for (let i = 0; i < 10; i += 1) {
    if (i == 5) { break outer_loop; }
  }
}
  • Range loops require := and bind the element name using let or def.
  • Labels (outer_loop :=) allow break/continue to target outer loops.

Defer & errdefer

defer cleanup();
errdefer { log_failure(); }
  • defer runs at scope exit in reverse order.
  • errdefer runs only if the function returns an error variant.

Return and Expressions

  • return expr; or return; (when void-like).
  • Any expression followed by ; forms a statement.

See docs/example.arti for the full program showcasing these constructs.