Skip to content

Language Syntax

w4ffl35 edited this page Aug 26, 2026 · 14 revisions

Curlee Syntax (MVP)

This document locks the MVP surface syntax.

Design goals:

  • Unambiguous and tooling-friendly (no indentation parsing).
  • Highly reliable for LLM generation (explicit delimiters).
  • Error recovery-friendly (statement terminators + block delimiters).
  • Contracts/refinements are first-class and always either verified (within scope) or rejected (no silent weakening).

Principles are in wiki/Syntax-Principles.md.


1) Top-level structure

A Curlee source file is a sequence of items.

  • Import declarations: import ...;
  • Struct declarations: struct ... { ... }
  • Enum declarations: enum ... { ... }
  • Function declarations: fn ... { ... }
  • Top-level let declarations (optional in MVP)

Notes:

  • import declarations must appear before any fn declarations.

1.5) Imports

Top-level imports only:

import foo;
import foo.bar;
import foo.bar as baz;

Rules:

  • import must appear at the top level.
  • The module path is a dotted identifier sequence.
  • Optional aliasing is supported via as <alias>.
  • A trailing ; is required.

Module resolution rules are specified in Modules and Imports.

2) Blocks and statements

2.1 Blocks

Blocks use braces:

{
  /* statements */
}

2.2 Statement terminators

Statements must end with ; where applicable.

This is a deliberate choice to:

  • improve parse recovery
  • reduce ambiguity for LLMs

Examples:

let x: Int = 1;
print(x);
return;
return x;

2.3 Assignment statements

x = expr; reassigns an existing binding. It is not a declaration — the target must already be in scope as a local let binding (a new binding is still let):

let i: Int = 0;
i = i + 1;   // reassigns i

Rules:

  • The target is a plain identifier (member/scoped targets are not in the MVP fragment).
  • The target's type is unchanged; the RHS must have the same type.
  • Parameters and ghost let snapshots are read-only and cannot be assigned.
  • Assignments are how loop-carried state is mutated, e.g. a bounded sum:
fn sum_to(n: Int) -> Int {
  let total: Int = 0;
  let i: Int = 0;
  while (i < n)
    [ invariant 0 <= i && i <= n && total >= 0;
      decreases n - i; ]
  {
    i = i + 1;
    total = total + i;
  }
  return total;
}

Verifier semantics: each assignment rebinds the name to a fresh solver symbol (constrained to the RHS value), so loop decreases variants and invariants are checked against the post-mutation state; see Verification Scope §6.


3) Functions

3.1 Function header

fn name(param1: Type, param2: Type) -> ReturnType { ... }

Return type is recommended for MVP.

3.2 Contracts (chosen form: bracketed contract block)

Contracts attach to a function header via a bracketed block.

fn divide(numerator: Int, denominator: Int) -> Int
  [ requires denominator != 0;
    ensures result * denominator == numerator; ]
{
  return numerator / denominator;
}

Rules:

  • Contract block is optional.
  • Inside [...], each clause ends with ;.
  • Supported clauses:
    • requires <pred>;
    • ensures <pred>;
  • result is reserved inside ensures and refers to the returned value.

If a predicate uses constructs outside wiki/Verification-Scope.md, compilation fails with a clear diagnostic.


4) Refinements (where)

where refines types at bindings and parameters.

Variable refinement:

let x: Int where x > 0 = 5;

Parameter refinement:

fn takes_pos(x: Int where x > 0) -> Int {
  return x;
}

5) Expressions (MVP)

Expressions include:

  • literals: integers, strings, booleans
  • identifiers
  • member access: value.field
  • unary: !, -, ~
  • binary arithmetic: +, -, *, /, %
  • bitwise: &, |, ^, <<, >>
  • comparisons: ==, !=, <, <=, >, >=
  • boolean connectives: &&, ||
  • calls: callee(args...)

5.2) Structs and field access (MVP)

Struct declarations and literals:

struct Point {
  x: Int;
  y: Int;
}

let p: Point = Point{ x: 1, y: 2 };

Field access uses .:

let sum: Int = p.x + p.y;

Rules:

  • Struct field declarations end with ;.
  • Struct literals require named field initializers (name: expr).
  • Duplicate field names are rejected with span-precise diagnostics.
  • Unknown fields are rejected with span-precise diagnostics.

Calls are intentionally restricted in MVP:

  • name(args...)
  • module-qualified: alias.name(args...) or foo.bar.name(args...)

Note: verification predicates are parsed from expression syntax but are restricted by wiki/Verification-Scope.md.

5.1) Enum construction and pattern matching (MVP)

Enums support constructor calls via scoped variant names:

enum Maybe {
  Some(Int);
  None;
}

let x: Maybe = Maybe::Some(1);
let y: Maybe = Maybe::None;

MVP deconstruction uses match with variant-only patterns:

match (x) {
  Maybe::Some(n) => {
    return n;
  }
  Maybe::None => {
    return 0;
  }
}

Pattern rules:

  • Arm pattern must be Enum::Variant or Enum::Variant(binding).
  • Payload-bearing variants require a binding.
  • Variants without payload must not bind a payload.
  • Duplicate variant arms are rejected.
  • Matches must be exhaustive over declared enum variants.

The match arm body is always a block.


6) Minimal grammar sketch (informal)

program        = { item } ;
item           = import_decl | fn_decl | let_decl ";" ;

import_decl    = "import" module_path [ "as" IDENT ] ";" ;
module_path    = IDENT { "." IDENT } ;

fn_decl         = "fn" IDENT "(" [ params ] ")" [ "->" type ]
                  [ contract_block ] block ;

contract_block  = "[" { contract_clause ";" } "]" ;
contract_clause = "requires" pred | "ensures" pred ;

params         = param { "," param } ;
param          = IDENT ":" type [ "where" pred ] ;

let_decl       = "let" IDENT ":" type [ "where" pred ] "=" expr ;

block          = "{" { stmt } "}" ;
stmt           = let_decl ";"
              | expr ";"
              | return_stmt ";"
              | if_stmt
              | while_stmt
              | match_stmt
              | block ;

return_stmt    = "return" [ expr ] ;

match_stmt     = "match" "(" expr ")" "{" { match_arm } "}" ;
match_arm      = match_pattern "=>" block ;
match_pattern  = IDENT "::" IDENT [ "(" IDENT ")" ] ;

pred           = expr ;

type           = core_type | cap_type | nominal_type | phys_type | extern_fn ;
core_type      = "Int" | "Bool" | "String" | "Unit" | "U8" | "U16" | "U32" | "U64" ;
cap_type       = "cap" capability_name ;
capability_name = IDENT { "." IDENT } ;
nominal_type   = IDENT ;
phys_type      = "Phys" "<" element_kind ">" ;
element_kind   = "U8" | "U16" | "U32" | "U64" ;
extern_fn      = "extern" "fn" IDENT "(" [ params ] ")" [ "->" type ] ";" ;

7) Bounded vectors (MVP-run)

Curlee supports a deterministic bounded vector baseline in MVP-run via Vec and stdlib wrappers.

Type form:

let v: Vec = vec.new_int(8);

MVP element support is currently integer-only (Vec<Int> semantics behind Vec).

stdlib v1 API (import std.vec as vec;):

fn new_int(max_len: Int) -> Vec
fn len_int(v: Vec) -> Int
fn push_int(v: Vec, value: Int) -> Unit
fn get_int(v: Vec, index: Int) -> Int
fn set_int(v: Vec, index: Int, value: Int) -> Unit

Deterministic runtime failures:

  • vec capacity exceeded
  • vec index out of bounds

Note: capability names must be written without whitespace around . (e.g. cap io.stdout).


7.5) Freestanding surface (Phys, port I/O, extern fn)

The freestanding target (curlee build --target freestanding-c, see Running Programs) extends the surface with physical-memory access, x86 port I/O, and extern functions. All three are freestanding-only: the VM (curlee run) rejects them.

7.5.1 Phys<T> and phys<U>(literal)

Phys<T> is an opaque physical-memory pointer type. Element kinds are limited to the fixed-width unsigned integers U8 | U16 | U32 | U64.

fn main(pm: cap phys.mem) -> U32 {
  unsafe {
    let fb: Phys<U32> = phys<U32>(0xFD00_0000); // framebuffer base
    fb.write(0xFF8800);                          // pixel write
    let v: U32 = fb.read();                      // register/framebuffer read
    return v;
  }
}

Rules (constant-address rule):

  • phys<U>(literal) requires a compile-time literal address (decimal or hex, e.g. 0xFD00_0000). Non-constant addresses are rejected.
  • read() / write(v) are allowed only inside unsafe { ... } blocks.
  • Every read()/write() use requires a cap phys.mem capability value in scope (typically a main parameter).
  • Phys<T> cannot be stored (struct field / enum payload), returned, or held in a let outside unsafe; it is an opaque pointer used only for read()/write().
  • Writes accept Int literals for unsigned element kinds (the compiler range-checks at the freestanding target).

7.5.2 x86 port I/O builtins (port_inb/port_outb/port_inw/port_outw/port_inl/port_outl)

The x86 port I/O instructions (in/out) live in a separate I/O address space from MMIO. Six builtins expose them for freestanding drivers:

Builtin Width Direction
port_inb(port) -> U8 8-bit read
port_outb(port, value) 8-bit write
port_inw(port) -> U16 16-bit read
port_outw(port, value) 16-bit write
port_inl(port) -> U32 32-bit read
port_outl(port, value) 32-bit write
fn main(pm: cap phys.mem) -> Unit {
  unsafe {
    port_outb(0x3FB, 0x03);        // COM1 LCR: 8N1
    let lsr: U8 = port_inb(0x3FD); // COM1 LSR (opaque read)
    port_outb(0x3F8, lsr);         // COM1 THR
  }
  return;
}

Rules (mirror the Phys<T> gate):

  • The port is a general Int expression: a compile-time literal (decimal or hex, e.g. 0x3F8), or a let-bound base plus a constant offset (e.g. io_base + 0x0E, the virtio_net.c legacy-virtio pattern, issue #276). Non-Int port expressions are rejected.
  • Port I/O is allowed only inside unsafe { ... } blocks and requires a cap phys.mem capability value in scope.
  • Verifier semantics are trusted/opaque, exactly like Phys<T> reads: port reads are uninterpreted (a contract cannot see through them), and there is no address-range fault model, so no out-of-bounds obligation is introduced.
  • port_out* values must match the builtin's unsigned width (Int literals are accepted, mirroring Phys writes).
  • Codegen emits inline in/out assembly (asm volatile). Constant ports use an 8-bit immediate where possible; runtime ports (a let-bound base, with or without an offset) use the DX-register form (in (%dx),%ax / out %ax,(%dx)).

7.5.3 extern fn

Extern functions declare a foreign symbol (no body) that the freestanding runtime must provide:

extern fn curlee_putc(c: Int) -> Unit;
extern fn curlee_halt() -> Unit;

Rules:

  • extern fn must appear at the top level and has no body.
  • The contract on an extern is assumed, not verified (see Verification Scope): the extern boundary is a documented exception — the caller trusts the declared signature.
  • The VM rejects calls to extern functions (freestanding-only). Only curlee build (and the linked kernel, which provides the symbols) can call them.

7.5.4 Unsigned construction and widening

Unsigned element kinds (U8 | U16 | U32 | U64) are produced by opaque reads (Phys<T>.read(), port_in*). Since issue #277 a U64 can also be constructed from an Int or a literal; the other unsigned kinds widen implicitly to Int (issue #274).

Rules:

  • U8/U16/U32 widen implicitly to Int in expressions (issue #274): mixed arithmetic/comparisons between an unsigned read and an Int are typed as Int.
  • U64 is constructed from an Int or a literal in binding positions — let initializers, ghost snapshots, and struct-literal fields — when the value is value-preserving: a compile-time-known literal must satisfy 0 <= value < 2^32 (all joeos physical addresses are 32-bit); an out-of-range or negative literal is a hard error, never a silent truncation.
  • U64 == U64 comparisons are legal; U64 arithmetic and mixed U64/Int comparisons remain out of scope.
let base: Int = 1048576;      // 0x100000: a physical address
let addr: U64 = base;         // Int -> U64 widening (issue #277)
let lit: U64 = 1048576;       // U64 literal adaptation
// let bad: U64 = 4294967296; // error: 0 <= value < 2^32 required

Codegen stores a U64 as C uint64_t (see Running Programs).


7.5.5 Fixed-size mutable arrays ([T; N] + indexed access)

Fixed-size mutable arrays are a freestanding-local binding form (issue #278), for ring buffers / driver state (the fb.c tool_queue and virtio_net.c rx_buf_state patterns). A let binding declares the array with a repeat initializer; element reads/writes use arr[i].

let q: [Int; 8] = [0; 8];   // 8-element Int array, zero-initialized
q[0] = 42;                   // indexed element write
let v: Int = q[0];           // indexed element read

Rules:

  • T is a storable core element type: Int | U8 | U16 | U32 | U64.
  • N is a positive compile-time integer literal (decimal; hex is reserved for physical-address literals). The initializer must be the repeat literal [v; N] with the same length N.
  • [0; N] codegens to a zero-filled C array (T q[N] = {0};); a non-zero repeat literal emits an explicit brace list ({7, 7, 7, 7}).
  • The Int-literal -> unsigned element adaptation applies to the repeat value and to element writes, mirroring port_outb: let rx: [U8; 16] = [0; 16]; and rx[i] = 2 are legal.
  • Every element access carries a verifier bounds obligation (0 <= i < N): constant out-of-bounds (including negative) indices are rejected by the type checker; symbolic indices must be provably in 0..N-1 (the loop-invariant machinery discharges this for bounded ring indices).
  • MVP scope: arrays are let bindings only — no struct fields, parameters, return types, ghost snapshots, or multi-dimensional indexing; a bare array name is not a first-class value (it must be indexed); predicates cannot reference array elements; curlee run (the VM) rejects arrays (they are freestanding-only).

7) Keywords (MVP)

Reserved keywords:

  • fn, let, if, else, while, return
  • requires, ensures, where
  • import, as

Planned/reserved for later (do not assign other meanings):

  • unsafe, cap
  • phys (currently usable as the phys<U>(addr) constructor / Phys<T> type name)

Clone this wiki locally