# Mycel Reference for AI Models & Large Language Models

> **Self-contained reference manual for Cloud and Local AI Models (Claude, ChatGPT, Gemini, Copilot, Llama, Qwen, Gemma)**
> Language: **Mycel** (`.myc`, `.olx`) | Manifest: `ply.json` | Compiler: `mycel v0.1.0`
> Copyright (c) 2026 drky. All examples and compiler outputs in this document are verified against the real Mycel compiler.

---

## Table of Contents
1. [Core Non-Negotiable Rules for AI Code Generators](#1-core-non-negotiable-rules-for-ai-code-generators)
2. [Language Overview & Syntax Specification](#2-language-overview--syntax-specification)
   - [Lexical Structure & Keywords](#lexical-structure--keywords)
   - [Type System & Inference](#type-system--inference)
   - [Numbers & Division Semantics](#numbers--division-semantics)
   - [Strings & Interpolation](#strings--interpolation)
   - [Collections (Arrays, Maps, Sets, Tuples)](#collections)
   - [Optionals & Safe Navigation](#optionals--safe-navigation)
   - [Control Flow & Pattern Matching](#control-flow--pattern-matching)
   - [Functions & Closures](#functions--closures)
   - [Classes, Structs, Enums, Interfaces & Extensions](#classes-structs-enums-interfaces--extensions)
   - [Error Handling](#error-handling)
   - [Modules & Imports](#modules--imports)
3. [Habits Comparison: What to Do When Coming from Other Languages](#3-habits-comparison)
4. [Standard Library Reference (Extracted from Real Sources)](#4-standard-library-reference)
5. [47 Verified Executable Examples with Real Outputs](#5-47-verified-executable-examples)
6. [Common Compiler Errors and Real Diagnostics](#6-common-compiler-errors-and-real-diagnostics)

---

## 1. Core Non-Negotiable Rules for AI Code Generators

When generating Mycel code, AI models MUST obey these 10 core rules to avoid syntax and type errors:

1. **Division**: `a / b` ALWAYS performs floating-point division and returns `Float`. For example, `7 / 2` evaluates to `3.5`. For whole-number integer division, use the `.div()` method: `7.div(2)` evaluates to `3` (`Int`). There is **NO `//` operator** in Mycel.
2. **Strings vs Characters**: Strings MUST be wrapped in double quotes (`"hello"`). Single quotes are strictly for single-character `Char` literals (`'c'`). Using single quotes around multiple characters is a syntax error.
3. **Function Declarations**: Declare functions using `fn name(params) -> ReturnType { ... }` or short arrow syntax `fn name(params) => expr`. NEVER use `def`, `function`, or `func`.
4. **Variable Declarations**: Use `let` for immutable bindings and `var` for mutable variables. NEVER use `const` or `val`.
5. **Null Safety**: Absence of a value is `nil` (typed as optional `T?`). NEVER use `None`, `null`, or `NULL`. Safe call is `?.`, coalescing is `??`, and force unwrap is `!`.
6. **Tuples**: Tuples are written `(a, b)` and indexed using dot notation: `pair.0`, `pair.1`. They do NOT support bracket indexing (`pair[0]` will fail).
7. **Maps**: Maps are written `{"key": "value"}`. If values have mixed types, the map must be explicitly typed as `{String: Any}`. Missing map keys return `nil` (so `map[k] ?? default` is idiomatic).
8. **Conditionals**: Write `if condition { ... } else if { ... } else { ... }`. Conditionals do NOT take parentheses and MUST have curly braces. NEVER write `elif` or colons `:`.
9. **Object Oriented Initializers**: Classes use `init(...) { ... }`. In a subclass initializer, call `super.init(...)`, NEVER `super(...)`.
10. **Structs vs Classes**: `struct` creates an immutable value type with structural equality `==` and generated copy method `.with(field: val)`. `class` creates a reference type with inheritance.

---

## 2. Language Overview & Syntax Specification

### Lexical Structure & Keywords
- **Files**: Extension `.myc` (or `.olx`). Top-level statements are valid directly without boilerplate `main()` function.
- **Comments**: `// line`, `/* block */`, `/// doc comment`.
- **Keywords**: `let var fn class struct interface enum type extend import pub private protected static if else while for in match return break continue throw try catch finally true false nil is as async await spawn gen yield init self super override operator extern then`.
- **Contextual Keywords**: `get`, `set`, `test`.

### Type System & Inference
- **Primitives**: `Int` (64-bit signed integer, overflow panics), `Float` (IEEE-754 double), `Bool` (`true` / `false`), `String` (UTF-8 character-aware), `Char` (single Unicode codepoint), `Void` (no value), `Never` (functions that throw or exit), `Any` (dynamic escape hatch).
- **Generics**: Invariant. Declared with `<T>` or bounded `<T: Comparable>`.
- **Type Aliases**: `type Milliseconds = Int`.

### Numbers & Division Semantics
- `7 / 2` evaluates to `3.5` (`Float`).
- `7.div(2)` evaluates to `3` (`Int`).
- `7 % 2` evaluates to `1` (`Int`).
- `2 ** 8` evaluates to `256` (`Int`).
- Integer and Float can be mixed in arithmetic expressions (e.g. `10 * 1.5` yields `15.0`).
- Number methods: `.abs`, `.sign`, `.isEven`, `.isOdd`, `.min(other)`, `.max(other)`, `.clamp(lo, hi)`, `.toFloat()`, `.toInt()`.

### Strings & Interpolation
- Double quotes: `"text"`. Escape sequences: `\n`, `\t`, `\r`, `\\ `, `\"`, `\'`, `\$`, `\u{1F600}`.
- F-Strings: `f"Hello, {name}!"`. Formatting specifiers: `f"Price: ${price:.2f}"`. Debug expression: `f"{x + y = }"`. Escaped braces: `{{` and `}}`.
- Multiline Strings: Triple double quotes `"""..."""`. Leading indentation equal to the closing delimiter is automatically stripped.

### Collections
- **Arrays**: `[1, 2, 3]`. Typed as `[T]`. Zero-indexed. Supports negative indices from end: `arr[-1]`. Methods include `.length`, `.push(x)`, `.pop()`, `.contains(x)`, `.indexOf(x)`, `.map(fn)`, `.filter(fn)`, `.reduce(init, fn)`, `.sorted()`.
- **Maps**: `{"a": 1, "b": 2}`. Empty map is `{}`. Typed as `{K: V}`. Lookup `m[k]` returns `V?` (`nil` if key missing).
- **Sets**: `Set([1, 2, 3])`. Typed as `Set<T>`. Set operations: union `a | b`, intersection `a & b`, difference `a - b`.
- **Tuples**: `(1, "Ada", true)`. Typed as `(Int, String, Bool)`. Fields accessed via `.0`, `.1`, `.2`, or destructuring: `let (id, name, active) = tuple`.

### Optionals & Safe Navigation
- Optional type is annotated with `?`: `String?`.
- `nil` represents absence.
- Safe navigation: `user?.profile?.address?.city`.
- Null coalescing: `name ?? "Anonymous"`.
- Force unwrap: `val!` (panics if `val` is `nil`).
- Optional binding: `if let unwrapped = opt { ... } else { ... }`.

### Control Flow & Pattern Matching
- **If / Else**: Evaluates as an expression if desired: `let v = if cond { a } else { b }`.
- **For Loop**: `for item in items { ... }` or `for i in 0..10 { ... }`.
- **While Loop**: `while condition { ... }`. Supports `break` and `continue`.
- **Match Expression**:
  ```mycel
  match val {
    Pattern1 => expr1
    Pattern2 => {
      statements...
    }
    _ => fallback
  }
  ```

### Functions & Closures
- Explicit: `fn add(a: Int, b: Int) -> Int { return a + b }`.
- Expression body: `fn double(x: Int) => x * 2`.
- Lambdas: `x => x * 2` or `(a: Int, b: Int) => a + b`.
- Default arguments: `fn query(table: String, limit: Int = 50)`.
- Variadic: `fn logAll(...messages: String)`.

### Classes, Structs, Enums, Interfaces & Extensions
- **Class**: Reference type with single inheritance. Must call `super.init(...)`. Overridden methods require `override`.
- **Struct**: Value type with structural equality `==`. Auto-generates `.with(field: newValue)`.
- **Enum**: Algebraic Data Types with payloads: `enum Result<T, E> { Ok(T), Err(E) }`.
- **Interface**: Contract definition: `interface Drawable { fn draw() }`.
- **Extension**: Add methods to existing types: `extend String { fn padBoth() -> String { ... } }`.
- **Operator Overloading**: `operator +(other: Vector) -> Vector`.

### Error Handling
- `Result<T, Error>` with `Ok(val)` and `Err(err)`.
- The `?` postfix operator unwraps `Ok` or returns early with `Err`.
- Exceptions: `throw Error("message")`, `try { ... } catch err { ... } finally { ... }`.

---

## 3. Habits Comparison

Here is how common habits from other programming languages map to Mycel:

### Coming from Python

| You write in Python | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `and / or / not` | ✅ Works | `and`, `or`, `not` work (same as `&&` `\|\|` `!`) |
| `print(a, b)` | ✅ Works | prints the values with a space between |
| `f"hi {name}"` | ✅ Works | the same: f-strings with {x:.2f} and {x=} |
| `for i, x in items` | ✅ Works | the same |
| `len(x)` | ✅ Works | the same |
| `x ** 2` | ✅ Works | the same |
| `no main(): statements at the top` | ✅ Works | the same: a file can just be statements |
| `x if c else y` | ✅ Works | the same |
| `x = 1 (no let)` | ✅ Works | the same: the first assignment creates the variable |
| `a, b = b, a` | ✅ Works | the same |
| `x in items / not in` | ✅ Works | the same |
| `[x * 2 for x in xs if x > 1]` | ✅ Works | the same |
| `xs[-1]` | ✅ Works | the same: negative indexes count from the end |
| `d.get(k, default)` | ✅ Works | the same |
| `a & b, a \| b, a - b on sets` | ✅ Works | the same; sets are written `Set([1, 2])` |
| `def f(x):` | ❌ Compile error | `def` is Python — Mycel writes `fn f(x) { ... }` |
| `elif` | ❌ Compile error | `elif` is Python — Mycel writes `else if` |
| `None` | ❌ Compile error | `None` is Python — Mycel writes `nil` |
| `True / False` | ❌ Compile error | `True`/`False` are Python — Mycel writes `true` / `false` |
| `if x:` | ❌ Compile error | a `:` block is Python — Mycel blocks use `{ ... }` |
| `lambda x: x + 1` | ❌ Compile error | `lambda` is Python — Mycel writes `x => x + 1` |
| `raise` | ❌ Compile error | `raise` is Python — Mycel writes `throw` |
| `except` | ❌ Compile error | `except` is Python — Mycel writes `catch e { ... }` |

### Coming from JavaScript

| You write in JavaScript | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `&&  \|\|  !` | ✅ Works | the same |
| `x => x + 1` | ✅ Works | the same |
| `x?.y and x ?? y` | ✅ Works | the same |
| `// comments and ; at line end` | ✅ Works | the same (semicolons are optional) |
| `async / await` | ✅ Works | the same |
| `=== and !==` | ❌ Compile error | `===` is JavaScript — Mycel's `==` already compares values: write `==` |
| `function f() {}` | ❌ Compile error | `function` is JavaScript — Mycel writes `fn f() { ... }` |
| `const x = 1` | ❌ Compile error | `const` is JavaScript — Mycel writes `let` (`var` for a value that changes) |
| `console.log(x)` | ❌ Compile error | `console.log` is JavaScript — Mycel writes `print(x)` |
| `null / undefined` | ❌ Compile error | `undefined` is JavaScript — Mycel writes `nil` |
| `this.x` | ❌ Compile error | `this` is JavaScript/Java — Mycel writes `self.n` |
| `new Foo()` | ❌ Compile error | `new` is JavaScript/Java — Mycel writes `Foo()` |
| `switch (x) { case 1: }` | ❌ Compile error | `switch` — Mycel writes `match x { 1 => ... }` |
| `x++` | ❌ Compile error | `x++` — Mycel writes `x += 1` |
| ``template ${x}`` | ❌ Compile error | backticks are JavaScript — Mycel writes f"a {x}" |
| `import x from 'y'` | ❌ Compile error | `import ... from` is JavaScript — Mycel writes `import std.fs` |

### Coming from TypeScript

| You write in TypeScript | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `interface / enum / class` | ✅ Works | the same keywords |
| `x!  and  x?.y` | ✅ Works | the same |
| `generics <T>` | ✅ Works | the same |
| `let x: Type = value` | ✅ Works | the same (types are Int, Float, String, Bool) |
| `type Alias = ...` | ✅ Works | the same |
| `async/await, Promise-style code` | ✅ Works | the same without Promise: `async fn` returns the value |
| `number` | ❌ Compile error | `number` is TypeScript — Mycel has `Int` (whole) and `Float` (decimal) |
| `string / boolean` | ❌ Compile error | `string` — Mycel writes `String`; `boolean` is `Bool` |
| `any / unknown` | ❌ Compile error | `any` is TypeScript — Mycel writes `Any` |
| `const / function` | ❌ Compile error | `const` is JavaScript/TypeScript — Mycel writes `let` |
| `number[]` | ❌ Compile error | `number` is TypeScript — Mycel writes `[Int]` for a list of whole numbers |
| `unknown` | ❌ Compile error | `unknown` is TypeScript — Mycel writes `Any` |
| `x as number` | ❌ Compile error | `number` is TypeScript — Mycel has `Int` and `Float` |
| `string[]` | ❌ Compile error | Mycel writes a list type as `[String]` |
| `export function` | ❌ Compile error | `export` is TypeScript — Mycel writes `pub fn f() { ... }` |

### Coming from Java

| You write in Java | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `System.out.println(x)` | ❌ Compile error | `System.out.println` is Java — Mycel writes `print(x)` |
| `public static void main` | ❌ Compile error | no boilerplate: write statements directly, or `fn main() { ... }` |
| `int x = 5;` | ❌ Compile error | types follow the name: `let x: Int = 5` (or just `let x = 5`) |
| `String / double / boolean as types` | ❌ Compile error | `double` is Java — Mycel's decimal type is `Float` |
| `new Foo()` | ❌ Compile error | `new` is JavaScript/Java — Mycel writes `Foo()` |
| `void f()` | ❌ Compile error | `void` is Java — Mycel writes `fn f() { ... }` (no return type needed) |
| `null` | ❌ Compile error | `null` is JavaScript/Java — Mycel writes `nil` |
| `i++` | ❌ Compile error | `x++` — Mycel writes `x += 1` |
| `for (int i = 0; ...; i++)` | ❌ Compile error | Mycel writes `for i in 0..3 { ... }` |
| `extends / implements` | ❌ Compile error | `extends` is Java — Mycel writes `class B: A { ... }` |
| `class Foo { }` | ✅ Works | the same shape |
| `if (x) { } else { }` | ✅ Works | the same (parentheses are optional) |
| `&&  \|\|  !` | ✅ Works | the same |
| `while (x) { }` | ✅ Works | the same |
| `try { } catch (e) { }` | ✅ Works | `catch e { ... }` |

### Coming from Go

| You write in Go | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `if x { } else { }` | ✅ Works | the same |
| `nil` | ✅ Works | the same |
| `// comments` | ✅ Works | the same |
| `struct Foo { }` | ✅ Works | the same shape |
| `for i := range / for ... range` | ✅ Works | `for i in 0..3 { }` (and `for x in items`) |
| `x := 5` | ❌ Compile error | `:=` is Go — Mycel writes `let x = 5` |
| `func f() {}` | ❌ Compile error | `func` is Go/Swift — Mycel writes `fn f() { ... }` |
| `fmt.Println(x)` | ❌ Compile error | `fmt.Println` is Go — Mycel writes `print(x)` |
| `var x int` | ❌ Compile error | types follow a colon: `var x: Int = 1` |
| `switch x { case 1: }` | ❌ Compile error | `switch` — Mycel writes `match x { 1 => ... }` |
| `x++` | ❌ Compile error | `x++` — Mycel writes `x += 1` |
| `go f()` | ❌ Compile error | `go` is Go — Mycel writes `spawn f()` |
| `defer f()` | ❌ Compile error | `defer` is Go/Swift — put cleanup in `try { } finally { }` |
| `package main` | ❌ Compile error | `package` is Go/Java — a Mycel file is a module; no package line |
| `int / string / float64 / bool types` | ❌ Compile error | `float64` is Go — Mycel's decimal type is `Float` |

### Coming from Rust

| You write in Rust | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `fn f(x: Int) -> Int { }` | ✅ Works | the same shape |
| `let x = 5  (immutable by default)` | ✅ Works | the same |
| `match x { A => .. }` | ✅ Works | the same |
| `enum and struct` | ✅ Works | the same |
| `Result and ?` | ✅ Works | the same |
| `for i in 0..n` | ✅ Works | the same |
| `if let Some(x) = y` | ✅ Works | `if let x = y { }` |
| `let mut x = 5` | ❌ Compile error | `let mut` is Rust — Mycel writes `var x = 5` |
| `println!("{}", x)` | ❌ Compile error | `println!` is Rust — Mycel writes `print(x)` |
| `None` | ❌ Compile error | `None` is Python/Rust — Mycel writes `nil` |
| `i32 / u64 / f64 / usize` | ❌ Compile error | `i32` is Rust — Mycel's whole-number type is `Int` |
| `impl Foo { }` | ❌ Compile error | `impl` is Rust — Mycel puts methods inside the class, or `extend Foo { ... }` |
| `vec![1, 2]` | ❌ Compile error | `vec!` is Rust — Mycel writes `[1, 2]` |
| `Type::method` | ❌ Compile error | `::` is Rust — Mycel writes `.` |
| `loop { }` | ❌ Compile error | `loop` is Rust — Mycel writes `while true { ... }` |
| `let x: &str` | ❌ Compile error | no references: Mycel's text type is `String` |

### Coming from Swift

| You write in Swift | What happens in Mycel | Mycel rule / syntax |
|---|---|---|
| `func f() -> Int` | ❌ Compile error | `func` is Go/Swift — Mycel writes `fn f() -> Int { ... }` |
| `"\(x)" interpolation` | ❌ Compile error | `\(x)` is Swift — Mycel writes f"v {x}" |
| `guard let x = y else { return }` | ❌ Compile error | `guard` is Swift — Mycel writes `if x == nil { return }` or `if let v = x { ... }` |
| `switch x { case .a: }` | ❌ Compile error | `switch` — Mycel writes `match x { .a => ... }` |
| `for i in 0..<n` | ❌ Compile error | `..<` is Swift — Mycel's `0..3` already excludes the end (`0..=3` includes it) |
| `extension Foo { }` | ❌ Compile error | `extension` is Swift — Mycel writes `extend Int { ... }` |
| `let / var` | ✅ Works | the same |
| `if let x = y { }` | ✅ Works | the same |
| `x?.y, x ?? y, x!` | ✅ Works | the same |
| `struct / class / enum / protocol→interface` | ✅ Works | the same (`protocol` is `interface`) |
| `closures x in ... → x => ...` | ✅ Works | `x => x * 2` |
| `print(a, b)` | ✅ Works | the same |
| `defer` | ❌ Compile error | `defer` is Go/Swift — put cleanup in `try { } finally { }` |
| `Character` | ❌ Compile error | `Character` is Swift — Mycel writes `Char` |
| `nil` | ✅ Works | the same |
| `Double / String as types` | ❌ Compile error | `Double` is Swift — Mycel's decimal type is `Float` |

---

## 4. Standard Library Reference

Signatures extracted directly from Mycel's standard library definition files (`lang/std/*.olx`):

### std.crypto

Source: `lang/std/crypto.olx`

```mycel
// Hashing and randomness from Node's crypto (OpenSSL).
pub extern fn sha256(text: String) -> String
pub extern fn sha1(text: String) -> String
pub extern fn hmacSha256(key: String, text: String) -> String
/// n random bytes as hex, from the operating system's CSPRNG.
pub extern fn randomHex(n: Int) -> String
pub extern fn uuid() -> String
pub extern fn base64Encode(text: String) -> String
pub extern fn base64Decode(text: String) -> Result<String, Error>
pub extern fn hexEncode(text: String) -> String
```

### std.db

Source: `lang/std/db.olx`

```mycel
import std.sqlite

// Simple databases and key-value stores over SQLite.
// Needs write permission to the database file (run with --allow-write).
//
// Key-Value store:
//   let kv = db.openKV("settings.db").unwrap()
//   kv.set("theme", "dark")
//   print(kv.get("theme", default: "light"))
//
// Tables:
//   let d = db.open("app.db").unwrap()
//   let users = d.table("users", {"id": "integer primary key", "name": "text"}).unwrap()
//   users.insert({"name": "Ada"}).unwrap()
//   for u in users.all().unwrap() { print(u["name"]) }

pub class KV {
  let db: sqlite.Db

  fn set(key: String, value: String) -> Result<Void, Error> {
    return self.db.exec("INSERT OR REPLACE INTO _kv (key, value) VALUES (?, ?)", [key, value])
  }

  fn get(key: String, default: String = "") -> String {
    match self.db.query("SELECT value FROM _kv WHERE key = ?", [key]) {
      .Ok(rows) => {
        if rows.isEmpty { return default }
        return str(rows[0]["value"])
      }
      .Err(_) => return default
    }
  }

  fn getOpt(key: String) -> String? {
    match self.db.query("SELECT value FROM _kv WHERE key = ?", [key]) {
      .Ok(rows) => {
        if rows.isEmpty { return nil }
        return str(rows[0]["value"])
      }
      .Err(_) => return nil
    }
  }

  fn has(key: String) -> Bool {
    match self.db.query("SELECT 1 FROM _kv WHERE key = ?", [key]) {
      .Ok(rows) => return !rows.isEmpty
      .Err(_) => return false
    }
  }

  fn remove(key: String) -> Result<Void, Error> {
    return self.db.exec("DELETE FROM _kv WHERE key = ?", [key])
  }

  fn keys() -> [String] {
    match self.db.query("SELECT key FROM _kv ORDER BY key") {
      .Ok(rows) => return [str(r["key"]) for r in rows]
      .Err(_) => return []
    }
  }

  fn count() -> Int {
    match self.db.query("SELECT COUNT(*) as c FROM _kv") {
      .Ok(rows) => {
        if rows.isEmpty { return 0 }
        let c = rows[0]["c"]
        return Int.parse(str(c)) ?? 0
      }
      .Err(_) => return 0
    }
  }

  fn clear() -> Result<Void, Error> {
    return self.db.exec("DELETE FROM _kv")
  }

  fn close() {
    self.db.close()
  }
}

pub class Table {
  let db: sqlite.Db
  let name: String

  fn insert(row: {String: Any}) -> Result<Void, Error> {
    var cols: [String] = []
    var placeholders: [String] = []
    var params: [Any] = []
    for k, v in row {
      cols.push(k)
      placeholders.push("?")
      params.push(v)
    }
    let colList = cols.join(", ")
    let valList = placeholders.join(", ")
    let sql = f"INSERT INTO {self.name} ({colList}) VALUES ({valList})"
    return self.db.exec(sql, params)
  }

  fn all() -> Result<[{String: Any}], Error> {
    return self.db.query(f"SELECT * FROM {self.name}")
  }

  fn find(where: {String: Any} = {}) -> Result<[{String: Any}], Error> {
    if where.isEmpty { return self.all() }
    var clauses: [String] = []
    var params: [Any] = []
    for k, v in where {
      clauses.push(f"{k} = ?")
      params.push(v)
    }
    let condList = clauses.join(" AND ")
    let sql = f"SELECT * FROM {self.name} WHERE {condList}"
    return self.db.query(sql, params)
  }

  fn findOne(where: {String: Any}) -> Result<{String: Any}?, Error> {
    match self.find(where) {
      .Ok(rows) => {
        if rows.isEmpty { return .Ok(nil) }
        return .Ok(rows[0])
      }
      .Err(e) => return .Err(e)
    }
  }

  fn update(where: {String: Any}, values: {String: Any}) -> Result<Void, Error> {
    var setClauses: [String] = []
    var params: [Any] = []
    for k, v in values {
      setClauses.push(f"{k} = ?")
      params.push(v)
    }
    var whereClauses: [String] = []
    for k, v in where {
      whereClauses.push(f"{k} = ?")
      params.push(v)
    }
    let setList = setClauses.join(", ")
    let condList = whereClauses.join(" AND ")
    let whereSql = if whereClauses.isEmpty { "" } else { f" WHERE {condList}" }
    let sql = f"UPDATE {self.name} SET {setList}{whereSql}"
    return self.db.exec(sql, params)
  }

  fn delete(where: {String: Any} = {}) -> Result<Void, Error> {
    var whereClauses: [String] = []
    var params: [Any] = []
    for k, v in where {
      whereClauses.push(f"{k} = ?")
      params.push(v)
    }
    let condList = whereClauses.join(" AND ")
    let whereSql = if whereClauses.isEmpty { "" } else { f" WHERE {condList}" }
    let sql = f"DELETE FROM {self.name}{whereSql}"
    return self.db.exec(sql, params)
  }

  fn count(where: {String: Any} = {}) -> Result<Int, Error> {
    var whereClauses: [String] = []
    var params: [Any] = []
    for k, v in where {
      whereClauses.push(f"{k} = ?")
      params.push(v)
    }
    let condList = whereClauses.join(" AND ")
    let whereSql = if whereClauses.isEmpty { "" } else { f" WHERE {condList}" }
    let sql = f"SELECT COUNT(*) as c FROM {self.name}{whereSql}"
    match self.db.query(sql, params) {
      .Ok(rows) => {
        if rows.isEmpty { return .Ok(0) }
        let c = rows[0]["c"]
        let countVal = Int.parse(str(c)) ?? 0
        return .Ok(countVal)
      }
      .Err(e) => return .Err(e)
    }
  }
}

pub class Database {
  let db: sqlite.Db

  fn table(name: String, schema: {String: String} = {}) -> Result<Table, Error> {
    if !schema.isEmpty {
      var defs: [String] = []
      for col, ty in schema {
        defs.push(f"{col} {ty}")
      }
      let colDefs = defs.join(", ")
      let sql = f"CREATE TABLE IF NOT EXISTS {name} ({colDefs})"
      match self.db.exec(sql) {
        .Ok(_) => {}
        .Err(e) => return .Err(e)
      }
    }
    return .Ok(Table(db: self.db, name: name))
  }

  fn exec(sql: String, params: [Any] = []) -> Result<Void, Error> {
    return self.db.exec(sql, params)
  }

  fn query(sql: String, params: [Any] = []) -> Result<[{String: Any}], Error> {
    return self.db.query(sql, params)
  }

  fn close() {
    self.db.close()
  }
}

pub fn open(path: String = ":memory:") -> Result<Database, Error> {
  match sqlite.Db.open(path) {
    .Ok(d) => return .Ok(Database(db: d))
    .Err(e) => return .Err(e)
  }
}

pub fn openKV(path: String = ":memory:") -> Result<KV, Error> {
  match sqlite.Db.open(path) {
    .Ok(d) => {
      match d.exec("CREATE TABLE IF NOT EXISTS _kv (key TEXT PRIMARY KEY, value TEXT)") {
        .Ok(_) => return .Ok(KV(db: d))
        .Err(e) => return .Err(e)
      }
    }
    .Err(e) => return .Err(e)
  }
}
```

### std.env

Source: `lang/std/env.olx`

```mycel
/// Command-line arguments given to the program (always available).
pub extern fn args() -> [String]
/// Value of an environment variable; needs a grant (`capabilities.env.read`). Denied or unset gives nil.
pub extern fn get(name: String) -> Result<String?, Error>
pub extern fn platform() -> String
```

### std.files

Source: `lang/std/files.olx`

```mycel
import std.fs

// Python-style file and path operations with capability grants.
// Reading needs --allow-read; writing needs --allow-write.
//
// Examples:
//   import std.files
//   files.write("hello.txt", "world").unwrap()
//   let text = files.read("hello.txt").unwrap()
//   let p = files.path("data").join("items.txt")
//   if p.exists() { print(p.text().unwrap()) }

pub class Path {
  let raw: String

  get name: String {
    return fs.basename(self.raw)
  }

  get extension: String {
    return fs.extension(self.raw)
  }

  get stem: String {
    let n = self.name
    let ext = self.extension
    if ext.isEmpty { return n }
    return n.substring(0, n.length - ext.length)
  }

  get parent: Path {
    let parts = self.raw.split("/")
    if parts.length <= 1 { return Path(raw: ".") }
    let par = parts.slice(0, parts.length - 1).join("/")
    return Path(raw: if par.isEmpty { "/" } else { par })
  }

  fn text() -> Result<String, Error> {
    return fs.readText(self.raw)
  }

  fn write(content: String) -> Result<Void, Error> {
    return fs.writeText(self.raw, content)
  }

  fn append(content: String) -> Result<Void, Error> {
    return fs.appendText(self.raw, content)
  }

  fn exists() -> Bool {
    return match fs.exists(self.raw) { .Ok(b) => b, .Err(_) => false }
  }

  fn isDir() -> Bool {
    return match fs.isDir(self.raw) { .Ok(b) => b, .Err(_) => false }
  }

  fn isFile() -> Bool {
    return self.exists() && !self.isDir()
  }

  fn size() -> Result<Int, Error> {
    return fs.size(self.raw)
  }

  fn list() -> Result<[Path], Error> {
    match fs.list(self.raw) {
      .Ok(names) => return .Ok([self.join(n) for n in names])
      .Err(e) => return .Err(e)
    }
  }

  fn join(part: String) -> Path {
    return Path(raw: fs.join(self.raw, part))
  }

  fn mkdir() -> Result<Void, Error> {
    return fs.mkdirs(self.raw)
  }

  fn remove() -> Result<Void, Error> {
    return fs.remove(self.raw)
  }

  fn toString() -> String {
    return self.raw
  }
}

pub fn path(p: String) -> Path {
  return Path(raw: p)
}

pub fn read(path: String) -> Result<String, Error> {
  return fs.readText(path)
}

pub fn write(path: String, content: String) -> Result<Void, Error> {
  return fs.writeText(path, content)
}

pub fn append(path: String, content: String) -> Result<Void, Error> {
  return fs.appendText(path, content)
}

pub fn exists(path: String) -> Bool {
  return match fs.exists(path) { .Ok(b) => b, .Err(_) => false }
}

pub fn list(path: String = ".") -> Result<[String], Error> {
  return fs.list(path)
}

pub fn remove(path: String) -> Result<Void, Error> {
  return fs.remove(path)
}

pub fn mkdir(path: String) -> Result<Void, Error> {
  return fs.mkdirs(path)
}

pub fn isDir(path: String) -> Bool {
  return match fs.isDir(path) { .Ok(b) => b, .Err(_) => false }
}

pub fn isFile(path: String) -> Bool {
  return exists(path) && !isDir(path)
}

pub fn size(path: String) -> Result<Int, Error> {
  return fs.size(path)
}

pub fn lines(path: String) -> Result<[String], Error> {
  match fs.readText(path) {
    .Ok(t) => return .Ok(t.split("\n"))
    .Err(e) => return .Err(e)
  }
}
```

### std.fs

Source: `lang/std/fs.olx`

```mycel
// File system access. Every function needs a grant (`capabilities.fs.read` / `.write`); a denied call returns Err(CapabilityError).
pub extern fn readText(path: String) -> Result<String, Error>
pub extern fn writeText(path: String, text: String) -> Result<Void, Error>
pub extern fn appendText(path: String, text: String) -> Result<Void, Error>
pub extern fn exists(path: String) -> Result<Bool, Error>
pub extern fn isDir(path: String) -> Result<Bool, Error>
pub extern fn list(path: String) -> Result<[String], Error>
pub extern fn mkdirs(path: String) -> Result<Void, Error>
pub extern fn remove(path: String) -> Result<Void, Error>
pub extern fn size(path: String) -> Result<Int, Error>
pub fn join(a: String, b: String) -> String {
  if a.endsWith("/") { return a + b }
  return a + "/" + b
}
pub fn extension(path: String) -> String {
  let name = path.split("/").last ?? path
  match name.indexOf(".") { nil => return "", i => return name.substring(i!, name.length) }
}
pub fn basename(path: String) -> String { return path.split("/").last ?? path }
```

### std.http

Source: `lang/std/http.olx`

```mycel
import std.json
// HTTP client and server. The client needs `capabilities.net.hosts`; the server needs `capabilities.net.listen` and binds 127.0.0.1.
pub struct Response { let status: Int, body: String, headers: {String: String}
  get ok: Bool { return self.status >= 200 && self.status < 300 }
  fn json() -> Result<json.Json, Error> { return json.parse(self.body) }
}
pub struct Request { let method: String, path: String, query: {String: String}, headers: {String: String}, body: String
  fn json() -> Result<json.Json, Error> { return json.parse(self.body) }
}
pub fn text(body: String, status: Int = 200) -> Response { return Response(status: status, body: body, headers: {"content-type": "text/plain; charset=utf-8"}) }
pub fn jsonResponse(value: json.Json, status: Int = 200) -> Response { return Response(status: status, body: json.stringify(value), headers: {"content-type": "application/json"}) }

pub extern async fn get(url: String, headers: {String: String} = {}) -> Result<Response, Error>
pub extern async fn post(url: String, body: String, headers: {String: String} = {}) -> Result<Response, Error>
pub extern async fn request(method: String, url: String, body: String = "", headers: {String: String} = {}) -> Result<Response, Error>

pub extern class Server {
  get port: Int
  fn stop()
}
/// Start a server on 127.0.0.1:port (0 picks a free port; read it from `server.port`).
pub extern async fn serve(port: Int, handler: (Request) -> Response) -> Result<Server, Error>
pub extern async fn serveAsync(port: Int, handler: (Request) -> Task<Response>) -> Result<Server, Error>
```

### std.io

Source: `lang/std/io.olx`

```mycel
/// Next line from standard input (without the newline), or nil at end of input. Needs the host to provide stdin.
pub extern async fn readLine() -> String?
```

### std.json

Source: `lang/std/json.olx`

```mycel
pub enum Json {
  Null
  Bool(Bool)
  Num(Float)
  Str(String)
  Arr([Json])
  Obj({String: Json})

  /// Items in an array/object, characters in a string, else 0 — so len(data["items"]) works.
  get length: Int => match self { .Arr(a) => a.length, .Obj(o) => o.length, .Str(s) => s.length, _ => 0 }
  get isNull: Bool => match self { .Null => true, _ => false }
  get asString: String? => match self { .Str(s) => s, _ => nil }
  get asFloat: Float? => match self { .Num(n) => n, _ => nil }
  get asInt: Int? => match self { .Num(n) => if n == n.floor().toFloat() { n.toInt() } else { nil }, _ => nil }
  get asBool: Bool? => match self { .Bool(b) => b, _ => nil }
  get asArray: [Json]? => match self { .Arr(a) => a, _ => nil }
  get asObject: {String: Json}? => match self { .Obj(o) => o, _ => nil }
  /// Member of an object, or nil when this is not an object or the key is missing.
  fn get(key: String) -> Json? => match self { .Obj(o) => o[key], _ => nil }
  /// Element of an array, or nil when out of range or not an array.
  fn at(index: Int) -> Json? => match self { .Arr(a) => if index >= 0 && index < a.length { a[index] } else { nil }, _ => nil }
  fn stringify() -> String => stringify(self)
  /// `data["name"]` like a Python dict / JS object: the member, or Null when missing or not an object.
  operator [](key: String) -> Json => match self { .Obj(o) => o[key] ?? .Null, _ => .Null }
  /// `items[0]`: the element, or Null when out of range or not an array.
  operator [](index: Int) -> Json => match self { .Arr(a) => if index >= 0 && index < a.length { a[index] } else { .Null }, _ => .Null }
  /// Text as it is, everything else as JSON (so print(data["name"]) shows Ada, not Str("Ada")).
  fn toString() -> String => match self { .Str(s) => s, _ => stringify(self) }
}

/// Parse JSON text. Numbers are Floats; integers up to 2^53 round-trip exactly.
pub extern fn parse(text: String) -> Result<Json, Error>
/// Compact JSON text for a Json value.
pub extern fn stringify(value: Json) -> String
/// Indented JSON text for a Json value.
pub extern fn pretty(value: Json) -> String
/// JSON text for any plain value: numbers, strings, arrays, maps with String keys, structs and classes (their fields), enums.
pub extern fn encode(value: Any) -> String
```

### std.log

Source: `lang/std/log.olx`

```mycel
pub enum Level { Debug, Info, Warn, Error }
var threshold = 1
pub fn setLevel(level: Level) {
  threshold = match level { .Debug => 0, .Info => 1, .Warn => 2, .Error => 3 }
}
fn emit(rank: Int, tag: String, message: String) {
  if rank >= threshold { print(f"[{tag}] {message}") }
}
pub fn debug(message: String) { emit(0, "debug", message) }
pub fn info(message: String) { emit(1, "info", message) }
pub fn warn(message: String) { emit(2, "warn", message) }
pub fn error(message: String) { emit(3, "error", message) }
```

### std.math

Source: `lang/std/math.olx`

```mycel
pub let PI = 3.141592653589793
pub let E = 2.718281828459045
pub extern fn sin(x: Float) -> Float
pub extern fn cos(x: Float) -> Float
pub extern fn tan(x: Float) -> Float
pub extern fn asin(x: Float) -> Float
pub extern fn acos(x: Float) -> Float
pub extern fn atan(x: Float) -> Float
pub extern fn atan2(y: Float, x: Float) -> Float
pub extern fn exp(x: Float) -> Float
pub extern fn log(x: Float) -> Float
pub extern fn log2(x: Float) -> Float
pub extern fn log10(x: Float) -> Float
pub extern fn sqrt(x: Float) -> Float
pub extern fn pow(x: Float, y: Float) -> Float
/// A uniformly random Float in [0, 1). Not for cryptography (see std.crypto).
pub extern fn random() -> Float
/// A random Int in [lo, hi).
pub extern fn randomInt(lo: Int, hi: Int) -> Int
pub fn hypot(a: Float, b: Float) -> Float { return (a * a + b * b).sqrt() }
pub fn gcd(a: Int, b: Int) -> Int {
  var x = a.abs
  var y = b.abs
  while y != 0 {
    let t = x % y
    x = y
    y = t
  }
  return x
}
pub fn radians(degrees: Float) -> Float { return degrees * PI / 180.0 }
pub fn degrees(radians: Float) -> Float { return radians * 180.0 / PI }
```

### prelude (built-ins)

Source: `lang/std/prelude.olx`

```mycel
// The prelude: always in scope. Types here are `extern`: their bodies live in src/natives.
// Everything user-visible about builtin types is declared in this file, so `ply check` and the
// diagnostics know exactly what exists.

extern fn print(...values: Any)
extern fn write(...values: Any)
/// Python-style input: shows the prompt, waits for one line, returns it without the newline.
extern fn input(prompt: String = "") -> String
extern fn panic(message: String) -> Never
extern fn assert(condition: Bool, message: String = "assertion failed")
extern fn str(value: Any) -> String
extern fn repr(value: Any) -> String
extern fn len(value: Any) -> Int
extern fn typeName(value: Any) -> String

interface Printable { fn toString() -> String }
interface Equatable {}
interface Hashable {}
interface Comparable {}
interface Numeric {}
interface Iterator<T> { fn next() -> T? }
interface Iterable<T> { fn iter() -> Iterator<T> }

extern class Int: Comparable, Equatable, Hashable, Numeric, Printable {
  get abs: Int
  get isEven: Bool
  get isOdd: Bool
  get sign: Int
  fn toFloat() -> Float
  fn toString() -> String
  fn toChar() -> Char
  fn pow(exp: Int) -> Int
  fn min(other: Int) -> Int
  fn max(other: Int) -> Int
  fn clamp(lo: Int, hi: Int) -> Int
  fn toRadix(radix: Int) -> String
  /// Whole-number integer division (like Python's //): 7.div(2) == 3.
  fn div(other: Int) -> Int
  static fn parse(text: String) -> Int?
  static get maxValue: Int
  static get minValue: Int
}
extern class Float: Comparable, Equatable, Hashable, Numeric, Printable {
  get abs: Float
  get isNaN: Bool
  get isFinite: Bool
  fn floor() -> Int
  fn ceil() -> Int
  fn round() -> Int
  fn trunc() -> Int
  fn toInt() -> Int
  fn toString() -> String
  fn sqrt() -> Float
  fn pow(exp: Float) -> Float
  fn min(other: Float) -> Float
  fn max(other: Float) -> Float
  fn clamp(lo: Float, hi: Float) -> Float
  fn fixed(digits: Int) -> String
  static fn parse(text: String) -> Float?
  static get infinity: Float
  static get nan: Float
}
extern class Bool: Equatable, Hashable, Printable { fn toString() -> String }
extern class Char: Comparable, Equatable, Hashable, Printable {
  get isDigit: Bool
  get isLetter: Bool
  get isUpper: Bool
  get isLower: Bool
  get isWhitespace: Bool
  get code: Int
  fn upper() -> Char
  fn lower() -> Char
  fn toString() -> String
  static fn fromCode(code: Int) -> Char
}
extern class String: Comparable, Equatable, Hashable, Printable, Iterable<Char> {
  get length: Int
  get isEmpty: Bool
  fn upper() -> String
  fn lower() -> String
  fn trim() -> String
  fn trimStart() -> String
  fn trimEnd() -> String
  fn split(sep: String) -> [String]
  fn lines() -> [String]
  fn chars() -> [Char]
  fn contains(part: String) -> Bool
  fn contains(part: Char) -> Bool
  fn startsWith(prefix: String) -> Bool
  fn endsWith(suffix: String) -> Bool
  fn replace(find: String, with: String) -> String
  fn indexOf(part: String) -> Int?
  fn repeat(n: Int) -> String
  fn padLeft(width: Int, fill: String = " ") -> String
  fn padRight(width: Int, fill: String = " ") -> String
  fn reversed() -> String
  fn toInt() -> Int?
  fn toFloat() -> Float?
  fn toString() -> String
  fn substring(from: Int, to: Int) -> String
  fn iter() -> Iterator<Char>
  fn bytes() -> [Int]
}
extern class Array<T>: Iterable<T> {
  init()
  get length: Int
  get isEmpty: Bool
  get first: T?
  get last: T?
  /// The element at index, or nil when out of range (indexing with [i] panics instead).
  fn at(index: Int) -> T?
  fn push(item: T)
  fn pop() -> T?
  fn insert(item: T, at: Int)
  fn removeAt(index: Int) -> T
  fn clear()
  fn append(items: [T])
  fn map<U>(f: (T) -> U) -> [U]
  fn flatMap<U>(f: (T) -> [U]) -> [U]
  fn filter(f: (T) -> Bool) -> [T]
  fn reduce<U>(initial: U, f: (U, T) -> U) -> U
  fn forEach(f: (T) -> Void)
  fn any(f: (T) -> Bool) -> Bool
  fn all(f: (T) -> Bool) -> Bool
  fn find(f: (T) -> Bool) -> T?
  fn findIndex(f: (T) -> Bool) -> Int?
  fn count(f: (T) -> Bool) -> Int
  fn contains(item: T) -> Bool
  fn indexOf(item: T) -> Int?
  fn sorted() -> [T]
  fn sortedBy<K>(key: (T) -> K) -> [T]
  fn reversed() -> [T]
  fn join(sep: String = "") -> String
  fn slice(from: Int, to: Int) -> [T]
  fn take(n: Int) -> [T]
  fn drop(n: Int) -> [T]
  fn concat(other: [T]) -> [T]
  fn enumerate() -> [(Int, T)]
  fn zip<U>(other: [U]) -> [(T, U)]
  fn unique() -> [T]
  fn copy() -> [T]
  fn iter() -> Iterator<T>
}
extern class Map<K, V>: Iterable<(K, V)> {
  init()
  get length: Int
  get isEmpty: Bool
  get keys: [K]
  get values: [V]
  get entries: [(K, V)]
  fn has(key: K) -> Bool
  fn contains(key: K) -> Bool
  fn get(key: K) -> V?
  fn get(key: K, default: V) -> V
  fn getOr(key: K, default: V) -> V
  fn set(key: K, value: V)
  fn remove(key: K) -> V?
  fn clear()
  fn copy() -> {K: V}
  fn merge(other: {K: V}) -> {K: V}
  fn iter() -> Iterator<(K, V)>
}
extern class Set<T>: Iterable<T> {
  init()
  init(items: [T])
  get length: Int
  get isEmpty: Bool
  fn add(item: T)
  fn has(item: T) -> Bool
  fn contains(item: T) -> Bool
  fn remove(item: T) -> Bool
  fn clear()
  fn union(other: Set<T>) -> Set<T>
  fn intersect(other: Set<T>) -> Set<T>
  fn subtract(other: Set<T>) -> Set<T>
  fn toArray() -> [T]
  fn sorted() -> [T]
  fn iter() -> Iterator<T>
  operator &(other: Set<T>) -> Set<T>
  operator |(other: Set<T>) -> Set<T>
  operator -(other: Set<T>) -> Set<T>
}
extern class Range: Iterable<Int> {
  get lo: Int
  get hi: Int
  get length: Int
  get isEmpty: Bool
  get first: Int?
  get last: Int?
  fn contains(n: Int) -> Bool
  fn toArray() -> [Int]
  fn iter() -> Iterator<Int>
  fn map<U>(f: (Int) -> U) -> [U]
  fn filter(f: (Int) -> Bool) -> [Int]
  fn reduce<U>(initial: U, f: (U, Int) -> U) -> U
  fn forEach(f: (Int) -> Void)
  fn any(f: (Int) -> Bool) -> Bool
  fn all(f: (Int) -> Bool) -> Bool
  fn count(f: (Int) -> Bool) -> Int
  fn sum() -> Int
  fn step(by: Int) -> [Int]
}
extern class Gen<T>: Iterator<T>, Iterable<T> {
  fn next() -> T?
  fn toArray() -> [T]
  fn iter() -> Iterator<T>
}
extern class Task<T> {}

class Error: Printable {
  let message: String
  init(message: String) { self.message = message }
  fn toString() -> String => f"{typeName(self)}: {self.message}"
}
class IoError: Error {}
class ParseError: Error {}
class CapabilityError: Error {}
class NetError: Error {}
class SqlError: Error {}
class TimeoutError: Error {}

enum Result<T, E> {
  Ok(T)
  Err(E)

  get isOk: Bool => match self { .Ok(_) => true, .Err(_) => false }
  get isErr: Bool => match self { .Ok(_) => false, .Err(_) => true }
  fn unwrap() -> T {
    match self {
        .Ok(v) => return v
        .Err(e) => panic(f"called unwrap() on an Err: {e}")
    }
  }
  fn unwrapOr(fallback: T) -> T => match self { .Ok(v) => v, .Err(_) => fallback }
  fn ok() -> T? => match self { .Ok(v) => v, .Err(_) => nil }
  fn err() -> E? => match self { .Ok(_) => nil, .Err(e) => e }
  fn map<U>(f: (T) -> U) -> Result<U, E> => match self { .Ok(v) => Ok(f(v)), .Err(e) => Err(e) }
  fn mapErr<F>(f: (E) -> F) -> Result<T, F> => match self { .Ok(v) => Ok(v), .Err(e) => Err(f(e)) }
  fn andThen<U>(f: (T) -> Result<U, E>) -> Result<U, E> => match self { .Ok(v) => f(v), .Err(e) => Err(e) }
}

// ----- Python-style helpers for lists: sum(xs), max(xs), min(xs), and max(a, b) / min(a, b) -----
fn sum(values: [Int]) -> Int { var total = 0
  for v in values { total += v }
  return total }
fn sum(values: [Float]) -> Float { var total = 0.0
  for v in values { total += v }
  return total }
fn sum(values: Range) -> Int { return values.sum() }
fn max(values: [Int]) -> Int { if values.isEmpty { panic("max() of an empty list") }
  var best = values[0]
  for v in values { if v > best { best = v } }
  return best }
fn max(values: [Float]) -> Float { if values.isEmpty { panic("max() of an empty list") }
  var best = values[0]
  for v in values { if v > best { best = v } }
  return best }
fn min(values: [Int]) -> Int { if values.isEmpty { panic("min() of an empty list") }
  var best = values[0]
  for v in values { if v < best { best = v } }
  return best }
fn min(values: [Float]) -> Float { if values.isEmpty { panic("min() of an empty list") }
  var best = values[0]
  for v in values { if v < best { best = v } }
  return best }
fn max(a: Int, b: Int) -> Int => if a > b { a } else { b }
fn max(a: Float, b: Float) -> Float => if a > b { a } else { b }
fn min(a: Int, b: Int) -> Int => if a < b { a } else { b }
fn min(a: Float, b: Float) -> Float => if a < b { a } else { b }
```

### std.process

Source: `lang/std/process.olx`

```mycel
pub struct Output { let code: Int, stdout: String, stderr: String
  get ok: Bool { return self.code == 0 }
}
/// Run a program without a shell. Needs `capabilities.process.run` listing the executable (or true).
pub extern fn run(command: String, args: [String] = [], input: String = "", timeoutMs: Int = 30000) -> Result<Output, Error>
pub extern fn pid() -> Int
```

### std.re

Source: `lang/std/re.olx`

```mycel
// Regular expressions (JavaScript syntax). Patterns are limited to 2000 characters and inputs to 1 MB.
pub struct Match { let text: String, start: Int, end: Int, groups: [String?], named: {String: String} }
pub extern class Regex {
  static fn compile(pattern: String, flags: String = "") -> Result<Regex, Error>
  fn isMatch(text: String) -> Bool
  fn find(text: String) -> Match?
  fn findAll(text: String) -> [Match]
  fn replace(text: String, with: String) -> String
  fn split(text: String) -> [String]
}
```

### std.sqlite

Source: `lang/std/sqlite.olx`

```mycel
// SQLite via Node's built-in node:sqlite (experimental in Node). File databases need an fs grant; ":memory:" needs none.
pub extern class Db {
  static fn open(path: String) -> Result<Db, Error>
  /// Run statements that return no rows. Parameters bind to `?` placeholders.
  fn exec(sql: String, params: [Any] = []) -> Result<Void, Error>
  /// Run a query; each row is a map from column name to Int, Float, String or nil.
  fn query(sql: String, params: [Any] = []) -> Result<[{String: Any}], Error>
  fn close()
}
```

### std.task

Source: `lang/std/task.olx`

```mycel
// Concurrency: tasks are cooperative (one thread, interleaved at `await`).
pub extern async fn sleep(ms: Int)
pub extern async fn all<T>(tasks: [Task<T>]) -> [T]
pub extern async fn race<T>(tasks: [Task<T>]) -> T
pub extern async fn timeout<T>(ms: Int, task: Task<T>) -> Result<T, Error>

/// An unbounded multi-producer queue. `recv` waits for a value and gives nil once the channel is closed and drained.
pub extern class Channel<T> {
  init()
  get length: Int
  get isClosed: Bool
  fn send(value: T)
  fn close()
  async fn recv() -> T?
}
```

### std.test

Source: `lang/std/test.olx`

```mycel
// Assertions for `test "name" { ... }` blocks. A failed assertion fails the test with both values shown.
pub extern fn assertEq(actual: Any, expected: Any, message: String = "")
pub extern fn assertNe(actual: Any, unexpected: Any, message: String = "")
pub fn assert(condition: Bool, message: String = "assertion failed") { if !condition { panic(message) } }
pub fn assertTrue(condition: Bool, message: String = "expected true") { if !condition { panic(message) } }
pub fn assertFalse(condition: Bool, message: String = "expected false") { if condition { panic(message) } }
pub fn fail(message: String) -> Never { panic(message) }
```

### std.time

Source: `lang/std/time.olx`

```mycel
import std.task

/// Milliseconds since 1970-01-01 UTC.
pub extern fn nowMs() -> Int
/// Seconds since 1970-01-01 UTC, with fractions.
pub fn now() -> Float { return nowMs().toFloat() / 1000.0 }
/// A monotonic clock in milliseconds, for measuring durations.
pub extern fn monotonicMs() -> Float
/// ISO-8601 UTC text for a timestamp in milliseconds, e.g. 2026-11-01T12:00:00.000Z.
pub extern fn iso(ms: Int) -> String
pub extern fn parseIso(text: String) -> Int?
/// year, month (1-12), day, hour, minute, second, weekday (0 = Sunday) in UTC.
pub struct Parts { let year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, weekday: Int }
pub extern fn parts(ms: Int) -> Parts

/// Current UTC date as "YYYY-MM-DD", like Python's date.today().
pub fn today() -> String {
  let p = parts(nowMs())
  let m = if p.month < 10 { f"0{p.month}" } else { f"{p.month}" }
  let d = if p.day < 10 { f"0{p.day}" } else { f"{p.day}" }
  return f"{p.year}-{m}-{d}"
}

/// Pause execution for the given seconds, like Python's time.sleep().
pub async fn sleep(seconds: Float) {
  let ms = (seconds * 1000.0).floor()
  await task.sleep(ms)
}

pub async fn sleep(seconds: Int) {
  await task.sleep(seconds * 1000)
}

/// A duration of time, like Python's datetime.timedelta.
pub struct Duration {
  let ms: Int
  fn toSeconds() -> Float { return self.ms.toFloat() / 1000.0 }
  fn toMs() -> Int { return self.ms }
  fn toMinutes() -> Float { return self.toSeconds() / 60.0 }
  fn toHours() -> Float { return self.toMinutes() / 60.0 }
  fn toDays() -> Float { return self.toHours() / 24.0 }
}

pub fn milliseconds(n: Int) -> Duration { return Duration(ms: n) }
pub fn seconds(n: Float) -> Duration { return Duration(ms: (n * 1000.0).floor()) }
pub fn seconds(n: Int) -> Duration { return Duration(ms: n * 1000) }
pub fn minutes(n: Float) -> Duration { return Duration(ms: (n * 60000.0).floor()) }
pub fn minutes(n: Int) -> Duration { return Duration(ms: n * 60000) }
pub fn hours(n: Float) -> Duration { return Duration(ms: (n * 3600000.0).floor()) }
pub fn hours(n: Int) -> Duration { return Duration(ms: n * 3600000) }
pub fn days(n: Float) -> Duration { return Duration(ms: (n * 86400000.0).floor()) }
pub fn days(n: Int) -> Duration { return Duration(ms: n * 86400000) }

/// Format a millisecond timestamp using Python-style format tokens: %Y, %m, %d, %H, %M, %S, %F, %T.
pub fn format(ms: Int, formatStr: String) -> String {
  let p = parts(ms)
  let y = f"{p.year}"
  let m = if p.month < 10 { f"0{p.month}" } else { f"{p.month}" }
  let d = if p.day < 10 { f"0{p.day}" } else { f"{p.day}" }
  let h = if p.hour < 10 { f"0{p.hour}" } else { f"{p.hour}" }
  let min = if p.minute < 10 { f"0{p.minute}" } else { f"{p.minute}" }
  let s = if p.second < 10 { f"0{p.second}" } else { f"{p.second}" }
  return formatStr.replace("%Y", y).replace("%m", m).replace("%d", d).replace("%H", h).replace("%M", min).replace("%S", s).replace("%F", f"{y}-{m}-{d}").replace("%T", f"{h}:{min}:{s}")
}

/// Format the current time with the given format string (defaults to "%Y-%m-%d %H:%M:%S").
pub fn format(formatStr: String = "%Y-%m-%d %H:%M:%S") -> String {
  return format(nowMs(), formatStr)
}
```

### std.ui

Source: `lang/std/ui.olx`

```mycel
// A friendly UI kit with one simple model for desktop and browser apps.
// Window, button, text, input, list, image, row, column, and event handlers.
//
// Example:
//   import std.ui
//   var count = 0
//   let label = ui.text("Count: 0")
//   ui.window("Counter", [
//     label,
//     ui.row([
//       ui.button("-", onClick: () => { count -= 1; label.setText(f"Count: {count}") }),
//       ui.button("+", onClick: () => { count += 1; label.setText(f"Count: {count}") }),
//     ])
//   ])

extern fn newId() -> String
extern fn mountWindow(win: Window)
extern fn notifyUpdate(id: String, prop: String, value: String)
extern fn notifyChildren(id: String, children: [Element])
extern fn closeWindow(id: String)
extern fn registerHandler(id: String, event: String, handler: Any)

pub class Element {
  var id: String = ""
  var kind: String = ""
  var text: String = ""
  var placeholder: String = ""
  var src: String = ""
  var alt: String = ""
  var children: [Element] = []

  fn setText(newText: String) {
    self.text = newText
    notifyUpdate(self.id, "text", newText)
  }

  fn value() -> String {
    return self.text
  }

  fn setValue(newValue: String) {
    self.text = newValue
    notifyUpdate(self.id, "value", newValue)
  }

  fn setItems(items: [Element]) {
    self.children = items
    notifyChildren(self.id, items)
  }

  fn append(child: Element) {
    self.children.push(child)
    notifyChildren(self.id, self.children)
  }

  fn removeAt(index: Int) {
    if index >= 0 && index < self.children.length {
      self.children.removeAt(index)
      notifyChildren(self.id, self.children)
    }
  }
}

pub class Window {
  var id: String = ""
  var title: String = ""
  var width: Int = 400
  var height: Int = 500
  var content: Element? = nil

  fn setContent(content: Element) {
    self.content = content
    mountWindow(self)
  }

  fn setTitle(newTitle: String) {
    self.title = newTitle
    notifyUpdate(self.id, "title", newTitle)
  }

  fn show() {
    mountWindow(self)
  }

  fn close() {
    closeWindow(self.id)
  }
}

pub fn text(content: String = "") -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "text"
  el.text = content
  return el
}

pub fn button(label: String, onClick: (() -> Void)? = nil) -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "button"
  el.text = label
  if onClick != nil {
    registerHandler(el.id, "click", onClick!)
  }
  return el
}

pub fn input(value: String = "", placeholder: String = "", onInput: ((String) -> Void)? = nil, onChange: ((String) -> Void)? = nil) -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "input"
  el.text = value
  el.placeholder = placeholder
  let handler = onInput ?? onChange
  if handler != nil {
    registerHandler(el.id, "input", handler!)
  }
  return el
}

pub fn image(src: String, alt: String = "") -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "image"
  el.src = src
  el.alt = alt
  return el
}

pub fn list(children: [Element] = []) -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "list"
  el.children = children
  return el
}

pub fn row(children: [Element] = []) -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "row"
  el.children = children
  return el
}

pub fn column(children: [Element] = []) -> Element {
  let el = Element()
  el.id = newId()
  el.kind = "column"
  el.children = children
  return el
}

pub fn window(title: String, children: [Element]) -> Window {
  let win = Window()
  win.id = newId()
  win.title = title
  let col = column(children)
  win.content = col
  mountWindow(win)
  return win
}

pub fn window(title: String, content: Element) -> Window {
  let win = Window()
  win.id = newId()
  win.title = title
  win.content = content
  mountWindow(win)
  return win
}

pub fn window(title: String) -> Window {
  let win = Window()
  win.id = newId()
  win.title = title
  let col = column([])
  win.content = col
  mountWindow(win)
  return win
}
```

### std.web

Source: `lang/std/web.olx`

```mycel
import std.http
import std.json as js
import std.fs
// Web apps in a few lines, the way Express, Flask and Sinatra do it: routes with :params, JSON, forms, static files.
//   app = web.App()
//   app.get("/", req => web.html("<h1>Hello</h1>"))
//   app.get("/hello/:name", req => web.text(f"Hi {req.params["name"]}"))
//   app.run(8000)          // serves until you stop it (needs --allow-listen)

pub struct Request {
  let method: String, path: String, params: {String: String}, query: {String: String}, form: {String: String}, headers: {String: String}, body: String
  fn json() -> Result<js.Json, Error> { return js.parse(self.body) }
}

pub fn text(body: String, status: Int = 200) -> http.Response { return http.text(body, status: status) }
pub fn html(body: String, status: Int = 200) -> http.Response { return http.Response(status: status, body: body, headers: {"content-type": "text/html; charset=utf-8"}) }
pub fn json(value: Any, status: Int = 200) -> http.Response { return http.Response(status: status, body: js.encode(value), headers: {"content-type": "application/json"}) }
pub fn redirect(to: String) -> http.Response { return http.Response(status: 303, body: "", headers: {"location": to}) }
/// Make text safe to put inside HTML (like Python's html.escape): & < > " ' become entities.
pub fn escape(text: String) -> String { return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;") }
pub fn notFound(message: String = "not found") -> http.Response { return http.text(message, status: 404) }

struct Route { let method: String, parts: [String], handler: (Request) -> http.Response }

fn segments(path: String) -> [String] { return path.split("/").filter(p => !p.isEmpty) }

fn contentType(path: String) -> String {
  let types = {"html": "text/html; charset=utf-8", "css": "text/css", "js": "text/javascript", "json": "application/json", "txt": "text/plain; charset=utf-8", "svg": "image/svg+xml", "md": "text/markdown; charset=utf-8"}
  return types.get(fs.extension(path).lower().replace(".", ""), "text/plain; charset=utf-8")
}

extern fn decodeForm(body: String) -> {String: String}
extern fn runForever(port: Int, handler: (http.Request) -> http.Response)

pub class App {
  var routes: [Route] = []
  var folders: [(String, String)] = []

  fn get(path: String, handler: (Request) -> http.Response) { self.routes.push(Route(method: "GET", parts: segments(path), handler: handler)) }
  fn post(path: String, handler: (Request) -> http.Response) { self.routes.push(Route(method: "POST", parts: segments(path), handler: handler)) }
  fn put(path: String, handler: (Request) -> http.Response) { self.routes.push(Route(method: "PUT", parts: segments(path), handler: handler)) }
  fn delete(path: String, handler: (Request) -> http.Response) { self.routes.push(Route(method: "DELETE", parts: segments(path), handler: handler)) }
  /// Serve the files in `folder` under the URL `prefix` (e.g. files("/static", "public")); needs --allow-read.
  fn files(prefix: String, folder: String) { self.folders.push((prefix, folder)) }

  fn handle(req: http.Request) -> http.Response {
    let got = segments(req.path)
    let form = if req.headers.get("content-type", "").startsWith("application/x-www-form-urlencoded") { decodeForm(req.body) } else { {} }
    var wrongMethod = false
    for r in self.routes {
      if r.parts.length != got.length { continue }
      var params: {String: String} = {}
      var matched = true
      for i, part in r.parts {
        if part.startsWith(":") { params[part.substring(1, part.length)] = got[i] }
        else if part != got[i] { matched = false; break }
      }
      if !matched { continue }
      if r.method != req.method { wrongMethod = true; continue }
      return r.handler(Request(method: req.method, path: req.path, params: params, query: req.query, form: form, headers: req.headers, body: req.body))
    }
    if req.method == "GET" {
      for (prefix, folder) in self.folders {
        let pre = segments(prefix)
        if got.length <= pre.length || got.slice(0, pre.length) != pre { continue }
        let rest = got.slice(pre.length, got.length)
        if ".." in rest { return text("bad path", status: 400) }
        let file = folder + "/" + rest.join("/")
        match fs.readText(file) {
          .Ok(body) => return http.Response(status: 200, body: body, headers: {"content-type": contentType(file)})
          .Err(_) => continue
        }
      }
    }
    if wrongMethod { return text(f"{req.method} is not allowed here", status: 405) }
    return notFound(f"no page at {req.path}")
  }

  /// Start serving and return the server (port 0 picks a free port) — for tests and programs that keep going.
  async fn start(port: Int = 0) -> Result<http.Server, Error> { return await http.serve(port, r => self.handle(r)) }
  /// Serve on 127.0.0.1:port until the program is stopped (Ctrl-C), like Flask's app.run().
  fn run(port: Int = 8000) { runForever(port, r => self.handle(r)) }
}
```

---

## 5. 47 Verified Executable Examples

Every single example below was compiled and executed with `mycel run --allow-all` by `lang/ai/make_ai_learn.mjs`. Outputs are exact real outputs.

### Example 1: Hello World and Top-Level Statements
*Category: Basics*

```mycel
print("Hello, Mycel!")
print("A file can just be top-level statements.")
```

**Verified Output:**
```text
Hello, Mycel!
A file can just be top-level statements.
```

### Example 2: Variables and Immutability (`let` vs `var`)
*Category: Basics*

```mycel
let greeting = "Hello"
var counter = 10
counter += 5
print(f"{greeting}! Counter is now {counter}")
```

**Verified Output:**
```text
Hello! Counter is now 15
```

### Example 3: Division Semantics (`/` yields Float, `.div()` yields Int)
*Category: Basics & Arithmetic*

```mycel
let a = 7
let b = 2
let floatResult = a / b
let intResult = a.div(b)
let remainder = a % b
print(f"Float division: 7 / 2 = {floatResult}")
print(f"Integer division: 7.div(2) = {intResult}")
print(f"Modulo remainder: 7 % 2 = {remainder}")
```

**Verified Output:**
```text
Float division: 7 / 2 = 3.5
Integer division: 7.div(2) = 3
Modulo remainder: 7 % 2 = 1
```

### Example 4: Mixed Arithmetic and Number Methods
*Category: Basics & Arithmetic*

```mycel
let n = 42
let f = 2.5
let mixed = n * f
print("Mixed Int * Float:", mixed)
print("Absolute value of -15:", (-15).abs)
print("Clamped value:", 120.clamp(0, 100))
```

**Verified Output:**
```text
Mixed Int * Float: 105.0
Absolute value of -15: 15
Clamped value: 100
```

### Example 5: F-Strings, Specifiers, and Expression Debugging
*Category: Strings*

```mycel
let item = "Notebook"
let price = 12.4567
print(f"Item: {item}, Price: ${price:.2f}")
let a = 14
let b = 28
print(f"Debug: {a + b = }")
```

**Verified Output:**
```text
Item: Notebook, Price: $12.46
Debug: a + b= 42
```

### Example 6: Multi-line Strings and Indentation Stripping
*Category: Strings*

```mycel
let query = """
  SELECT id, name
  FROM users
  WHERE active = true
  """
print(query)
```

**Verified Output:**
```text
SELECT id, name
FROM users
WHERE active = true
```

### Example 7: Chars (Single Quotes) vs Strings (Double Quotes)
*Category: Strings*

```mycel
let ch: Char = 'A'
let s: String = "Apple"
print("Character:", ch)
print("String first letter:", s[0])
print("Is Char matching:", s[0] == ch)
```

**Verified Output:**
```text
Character: A
String first letter: A
Is Char matching: true
```

### Example 8: If / Else as an Expression
*Category: Control Flow*

```mycel
let score = 88
let grade = if score >= 90 {
  "A"
} else if score >= 80 {
  "B"
} else {
  "C"
}
print(f"Score {score} earned grade {grade}")
```

**Verified Output:**
```text
Score 88 earned grade B
```

### Example 9: Pattern Matching on Values (`match`)
*Category: Control Flow*

```mycel
let httpStatus = 404
let message = match httpStatus {
  200 => "OK"
  301 => "Moved Permanently"
  404 => "Not Found"
  500 => "Internal Server Error"
  _ => "Unknown Status"
}
print(f"HTTP {httpStatus}: {message}")
```

**Verified Output:**
```text
HTTP 404: Not Found
```

### Example 10: For Loops and Numeric Ranges
*Category: Control Flow*

```mycel
var halfOpenSum = 0
for i in 0..5 {
  halfOpenSum += i
}
var closedSum = 0
for i in 1..=5 {
  closedSum += i
}
print("Sum 0..5 (half-open):", halfOpenSum)
print("Sum 1..=5 (closed):", closedSum)
```

**Verified Output:**
```text
Sum 0..5 (half-open): 10
Sum 1..=5 (closed): 15
```

### Example 11: While Loop with Break and Continue
*Category: Control Flow*

```mycel
var n = 0
var evens: [Int] = []
while true {
  n += 1
  if n > 10 { break }
  if n % 2 != 0 { continue }
  evens.push(n)
}
print("First evens:", evens)
```

**Verified Output:**
```text
First evens: [2, 4, 6, 8, 10]
```

### Example 12: Functions with Default and Named Arguments
*Category: Functions*

```mycel
fn greet(name: String, greeting: String = "Hello", punctuation: String = "!") -> String {
  return f"{greeting}, {name}{punctuation}"
}
print(greet("Ada"))
print(greet("Grace", greeting: "Welcome", punctuation: "!!!"))
```

**Verified Output:**
```text
Hello, Ada!
Welcome, Grace!!!
```

### Example 13: Expression-Bodied Functions (`=>`)
*Category: Functions*

```mycel
fn cube(x: Int) => x * x * x
fn isPositive(x: Int) => x > 0
print("cube(3):", cube(3))
print("isPositive(-4):", isPositive(-4))
```

**Verified Output:**
```text
cube(3): 27
isPositive(-4): false
```

### Example 14: Variadic Parameters (`...rest`)
*Category: Functions*

```mycel
fn maxOf(first: Int, ...rest: Int) -> Int {
  var m = first
  for x in rest {
    if x > m { m = x }
  }
  return m
}
print("Max of values:", maxOf(14, 82, 35, 99, 41))
```

**Verified Output:**
```text
Max of values: 99
```

### Example 15: Higher-Order Functions and Lambda Closures
*Category: Functions*

```mycel
fn transform(items: [Int], op: (Int) -> Int) -> [Int] {
  var out: [Int] = []
  for x in items {
    out.push(op(x))
  }
  return out
}
let numbers = [1, 2, 3, 4]
let squared = transform(numbers, x => x * x)
print("Squared:", squared)
```

**Verified Output:**
```text
Squared: [1, 4, 9, 16]
```

### Example 16: Array Operations and Negative Indexing
*Category: Collections*

```mycel
var fruits = ["apple", "banana", "cherry"]
fruits.push("date")
print("Length:", fruits.length)
print("First element:", fruits[0])
print("Last element (negative index):", fruits[-1])
print("Contains banana:", fruits.contains("banana"))
```

**Verified Output:**
```text
Length: 4
First element: apple
Last element (negative index): date
Contains banana: true
```

### Example 17: Array Functional Methods (map, filter, reduce)
*Category: Collections*

```mycel
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evens = nums.filter(x => x % 2 == 0)
let tripled = evens.map(x => x * 3)
let sum = tripled.reduce(0, (acc, x) => acc + x)
print("Sum of tripled evens:", sum)
```

**Verified Output:**
```text
Sum of tripled evens: 90
```

### Example 18: List Comprehensions with Filtering
*Category: Collections*

```mycel
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result = [x * x for x in nums if x > 4]
print("Squares > 4:", result)
```

**Verified Output:**
```text
Squares > 4: [25, 36, 49, 64, 81, 100]
```

### Example 19: Maps and Default Value Retrieval
*Category: Collections*

```mycel
var inventory = {"pens": 20, "notebooks": 15}
inventory["erasers"] = 8
print("Pens:", inventory["pens"] ?? 0)
print("Rulers (missing):", inventory["rulers"] ?? 0)
print("Keys in map:", inventory.length)
```

**Verified Output:**
```text
Pens: 20
Rulers (missing): 0
Keys in map: 3
```

### Example 20: Heterogeneous Maps with `{String: Any}`
*Category: Collections*

```mycel
let record: {String: Any} = {
  "title": "Compiler Guide",
  "version": 1,
  "stable": true
}
print("Title:", record["title"] ?? "")
print("Version:", record["version"] ?? 0)
```

**Verified Output:**
```text
Title: Compiler Guide
Version: 1
```

### Example 21: Sets and Set Arithmetic (| & -)
*Category: Collections*

```mycel
let primes = Set([2, 3, 5, 7, 11])
let odds = Set([1, 3, 5, 7, 9, 11])
let both = primes & odds
let all = primes | odds
print("Intersection:", both.sorted())
print("Total unique in union:", all.length)
```

**Verified Output:**
```text
Intersection: [3, 5, 7, 11]
Total unique in union: 7
```

### Example 22: Tuples, Dot Indexing (.0), and Destructuring
*Category: Collections*

```mycel
let record = ("Alice", 28, true)
print("Name via .0:", record.0)
print("Age via .1:", record.1)
let (name, age, active) = record
print(f"Destructured: {name}, age {age}, active={active}")
```

**Verified Output:**
```text
Name via .0: Alice
Age via .1: 28
Destructured: Alice, age 28, active=true
```

### Example 23: Optionals and `if let` Binding
*Category: Optionals & Safety*

```mycel
fn lookupUser(id: Int) -> String? {
  if id == 42 { return "Arthur Dent" }
  return nil
}
if let user = lookupUser(42) {
  print("User found:", user)
} else {
  print("User not found")
}
```

**Verified Output:**
```text
User found: Arthur Dent
```

### Example 24: Optional Chaining (`?.`) and Coalescing (`??`)
*Category: Optionals & Safety*

```mycel
class Address { let city: String; init(city: String) { self.city = city } }
class Person { let address: Address?; init(address: Address? = nil) { self.address = address } }
let p1 = Person(address: Address(city: "Edinburgh"))
let p2 = Person()
print("P1 city:", p1.address?.city ?? "Unknown")
print("P2 city:", p2.address?.city ?? "Unknown")
```

**Verified Output:**
```text
P1 city: Edinburgh
P2 city: Unknown
```

### Example 25: Structs (Immutable Value Types and `.with(...)`)
*Category: OOP & Types*

```mycel
struct Point {
  let x: Int
  let y: Int
}
let p1 = Point(x: 10, y: 20)
let p2 = Point(x: 10, y: 20)
let p3 = p1.with(y: 99)
print("Structural equality p1 == p2:", p1 == p2)
print("Original p1:", p1.x, p1.y)
print("Copy with change p3:", p3.x, p3.y)
```

**Verified Output:**
```text
Structural equality p1 == p2: true
Original p1: 10 20
Copy with change p3: 10 99
```

### Example 26: Classes, `super.init`, and `override`
*Category: OOP & Types*

```mycel
class Shape {
  let color: String
  init(color: String) { self.color = color }
  fn describe() -> String { return f"{self.color} shape" }
}
class Rectangle: Shape {
  let width: Int
  let height: Int
  init(color: String, width: Int, height: Int) {
    super.init(color: color)
    self.width = width
    self.height = height
  }
  override fn describe() -> String {
    return f"{self.color} rectangle ({self.width}x{self.height})" }
}
let r = Rectangle(color: "blue", width: 10, height: 5)
print(r.describe())
```

**Verified Output:**
```text
blue rectangle (10x5)
```

### Example 27: Computed Properties (`get` and `set`)
*Category: OOP & Types*

```mycel
class Temperature {
  var celsius: Float
  init(celsius: Float) { self.celsius = celsius }
  get fahrenheit: Float { return self.celsius * 1.8 + 32.0 }
  set fahrenheit(f: Float) { self.celsius = (f - 32.0) / 1.8 }
}
let t = Temperature(celsius: 25.0)
print("Celsius 25 is Fahrenheit:", t.fahrenheit)
t.fahrenheit = 212.0
print("Fahrenheit 212 is Celsius:", t.celsius)
```

**Verified Output:**
```text
Celsius 25 is Fahrenheit: 77.0
Fahrenheit 212 is Celsius: 100.0
```

### Example 28: Enums as Algebraic Data Types with Pattern Matching
*Category: OOP & Types*

```mycel
enum WebResponse {
  Success(body: String)
  Redirect(url: String, code: Int)
  Error(message: String)
}
fn formatResponse(res: WebResponse) -> String {
  return match res {
    .Success(body) => f"200 OK: {body}"
    .Redirect(url, code) => f"{code} Redirect to {url}"
    .Error(msg) => f"Error: {msg}"
  }
}
print(formatResponse(WebResponse.Success(body: "Welcome!")))
print(formatResponse(WebResponse.Redirect(url: "https://ol1x.xyz", code: 301)))
```

**Verified Output:**
```text
200 OK: Welcome!
301 Redirect to https://ol1x.xyz
```

### Example 29: Interfaces and Dynamic Polymorphism
*Category: OOP & Types*

```mycel
interface Printable {
  fn format() -> String
}
class Book: Printable {
  let title: String
  init(title: String) { self.title = title }
  fn format() -> String { return f"Book: «{self.title}»" }
}
class Song: Printable {
  let name: String
  init(name: String) { self.name = name }
  fn format() -> String { return f"Song: ♫ {self.name} ♫" }
}
let items: [Printable] = [Book(title: "The Odyssey"), Song(name: "Moonlight")]
for item in items {
  print(item.format())
}
```

**Verified Output:**
```text
Book: «The Odyssey»
Song: ♫ Moonlight ♫
```

### Example 30: Type Extensions (`extend Type { ... }`)
*Category: OOP & Types*

```mycel
extend String {
  fn wrapQuotes() -> String { return f"\"{self}\"" }
}
extend Int {
  fn squared() -> Int { return self * self }
}
print("hello".wrapQuotes())
print(9.squared())
```

**Verified Output:**
```text
"hello"
81
```

### Example 31: Operator Overloading (`operator +`)
*Category: OOP & Types*

```mycel
class Money {
  let cents: Int
  init(cents: Int) { self.cents = cents }
  operator +(other: Money) -> Money {
    return Money(cents: self.cents + other.cents)
  }
  fn toString() -> String {
    let dollars = self.cents.div(100)
    let rem = self.cents % 100
    let remStr = if rem < 10 { f"0{rem}" } else { f"{rem}" }
    return f"${dollars}.{remStr}"
  }
}
let m1 = Money(cents: 1250)
let m2 = Money(cents: 750)
let total = m1 + m2
print("Total money:", total.toString())
```

**Verified Output:**
```text
Total money: $20.00
```

### Example 32: Generics in Functions and Classes
*Category: Generics*

```mycel
class Container<T> {
  let item: T
  init(item: T) { self.item = item }
  fn inspect() -> T { return self.item }
}
fn wrap<T>(val: T) -> Container<T> {
  return Container(item: val)
}
let c1 = wrap(100)
let c2 = wrap("Mycel Generics")
print("c1:", c1.inspect())
print("c2:", c2.inspect())
```

**Verified Output:**
```text
c1: 100
c2: Mycel Generics
```

### Example 33: Pipeline Operator (`|>`) for Readable Transformations
*Category: Functional*

```mycel
fn clean(s: String) => s.trim()
fn uppercase(s: String) => s.upper()
fn badge(s: String) => f"[TAG: {s}]"
let res = "   system alert   " |> clean |> uppercase |> badge
print("Pipelined:", res)
```

**Verified Output:**
```text
Pipelined: [TAG: SYSTEM ALERT]
```

### Example 34: Result Type and `?` Error Propagation
*Category: Error Handling*

```mycel
fn validateAge(input: String) -> Result<Int, Error> {
  let num = Int.parse(input)
  if num == nil {
    return Err(Error("Invalid integer"))
  }
  let n = num!
  if n < 0 || n > 120 {
    return Err(Error("Age out of reasonable bounds"))
  }
  return Ok(n)
}
fn parseUser(ageStr: String) -> Result<String, Error> {
  let age = validateAge(ageStr)?
  return Ok(f"Verified age: {age}")
}
print(parseUser("25").unwrap())
print("Invalid:", parseUser("150").isErr)
```

**Verified Output:**
```text
Verified age: 25
Invalid: true
```

### Example 35: Try / Catch / Finally Exception Handling
*Category: Error Handling*

```mycel
fn risky(succeed: Bool) {
  if !succeed {
    throw Error("Connection timed out")
  }
  print("Operation completed")
}
try {
  risky(false)
} catch err {
  print("Caught expected error:", err.message)
} finally {
  print("Cleanup executed")
}
```

**Verified Output:**
```text
Caught expected error: Connection timed out
Cleanup executed
```

### Example 36: Generators with `gen fn` and `yield`
*Category: Control Flow & Async*

```mycel
gen fn fibonacci(count: Int) -> Gen<Int> {
  var a = 0
  var b = 1
  var i = 0
  while i < count {
    yield a
    let next = a + b
    a = b
    b = next
    i += 1
  }
}
var sequence: [Int] = []
for num in fibonacci(7) {
  sequence.push(num)
}
print("Fibonacci sequence:", sequence)
```

**Verified Output:**
```text
Fibonacci sequence: [0, 1, 1, 2, 3, 5, 8]
```

### Example 37: Standard Library `std.math`
*Category: Standard Library*

```mycel
import std.math
print("PI:", math.PI > 3.14)
print("sqrt(144.0):", math.sqrt(144.0))
print("hypot(5.0, 12.0):", math.hypot(5.0, 12.0))
print("gcd(48, 18):", math.gcd(48, 18))
```

**Verified Output:**
```text
PI: true
sqrt(144.0): 12.0
hypot(5.0, 12.0): 13.0
gcd(48, 18): 6
```

### Example 38: Standard Library `std.json` (Parse and Stringify)
*Category: Standard Library*

```mycel
import std.json
let raw = """{"title":"Dashboard","stars":142,"active":true}"""
let obj = json.parse(raw).unwrap()
print("Title:", obj["title"].asString ?? "")
print("Stars:", obj["stars"].asInt ?? 0)
print("Active:", obj["active"].asBool ?? false)
let serialized = json.stringify(obj)
print("Serialized length > 0:", serialized.length > 0)
```

**Verified Output:**
```text
Title: Dashboard
Stars: 142
Active: true
Serialized length > 0: true
```

### Example 39: Standard Library `std.time`
*Category: Standard Library*

```mycel
import std.time
let now = time.now()
print("Current timestamp is positive:", now > 0.0)
let dur = time.seconds(150.0)
print("Duration in minutes:", dur.toMinutes())
```

**Verified Output:**
```text
Current timestamp is positive: true
Duration in minutes: 2.5
```

### Example 40: Standard Library `std.crypto` (SHA-256 and Hex)
*Category: Standard Library*

```mycel
import std.crypto
let digest = crypto.sha256("mycel-standard-library")
print("SHA-256 length:", digest.length)
print("SHA-256 prefix:", digest.substring(0, 10))
```

**Verified Output:**
```text
SHA-256 length: 64
SHA-256 prefix: ce3ff1d415
```

### Example 41: Standard Library `std.re` (Regex Match and Groups)
*Category: Standard Library*

```mycel
import std.re
let pattern = re.Regex.compile("([a-zA-Z]+)-(\\d+)").unwrap()
let m = pattern.find("Order ID: ITEM-89421 in queue")
if let found = m {
  print("Full match:", found.text)
  print("Prefix:", found.groups[0] ?? "")
  print("Number:", found.groups[1] ?? "")
}
```

**Verified Output:**
```text
Full match: ITEM-89421
Prefix: ITEM
Number: 89421
```

### Example 42: Standard Library `std.env` (Platform and Args)
*Category: Standard Library*

```mycel
import std.env
print("Platform recognized:", env.platform().length > 0)
print("Args available:", env.args().length >= 0)
```

**Verified Output:**
```text
Platform recognized: true
Args available: true
```

### Example 43: Standard Library `std.fs` (Sandboxed File I/O)
*Category: Standard Library*

```mycel
import std.fs
fn main() {
  let file = "/tmp/mycel_demo_fs.txt"
  fs.writeText(file, "Mycel sandbox filesystem verified").unwrap()
  let content = fs.readText(file).unwrap()
  print("Read back:", content)
  fs.remove(file).unwrap()
  print("Cleaned up file:", !fs.exists(file).unwrap())
}
```

**Verified Output:**
```text
Read back: Mycel sandbox filesystem verified
Cleaned up file: true
```

### Example 44: Standard Library `std.test` (Unit Testing)
*Category: Standard Library*

```mycel
import std.test
test "arithmetic checks" {
  test.assertEq(10 * 10, 100)
  test.assertTrue("mycel".startsWith("my"))
}
print("All tests registered clean")
```

**Verified Output:**
```text
All tests registered clean
```

### Example 45: Algorithm: Binary Search
*Category: Algorithms*

```mycel
fn binarySearch(list: [Int], target: Int) -> Int? {
  var low = 0
  var high = list.length - 1
  while low <= high {
    let mid = (low + high).div(2)
    let val = list[mid]
    if val == target {
      return mid
    } else if val < target {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }
  return nil
}
let items = [3, 9, 14, 25, 33, 47, 59, 81, 95]
print("Find 47:", binarySearch(items, 47) ?? -1)
print("Find 50 (missing):", binarySearch(items, 50) ?? -1)
```

**Verified Output:**
```text
Find 47: 5
Find 50 (missing): -1
```

### Example 46: Algorithm: Word Frequency Counter
*Category: Algorithms*

```mycel
let sentence = "to be or not to be that is the question"
var counts: {String: Int} = {}
for word in sentence.split(" ") {
  let cur = counts[word] ?? 0
  counts[word] = cur + 1
}
print("'to' count:", counts["to"] ?? 0)
print("'be' count:", counts["be"] ?? 0)
print("'question' count:", counts["question"] ?? 0)
```

**Verified Output:**
```text
'to' count: 2
'be' count: 2
'question' count: 1
```

### Example 47: Algorithm: Data Aggregation Pipeline
*Category: Algorithms*

```mycel
import std.json
let rawData = """[
  {"sku": "A10", "qty": 4, "price": 12.5},
  {"sku": "B20", "qty": 0, "price": 50.0},
  {"sku": "C30", "qty": 2, "price": 100.0}
]"""
let items = json.parse(rawData).unwrap().asArray ?? []
var totalValue = 0.0
for item in items {
  let qty = item["qty"].asInt ?? 0
  if qty > 0 {
    let price = item["price"].asFloat ?? 0.0
    totalValue += price * qty.toFloat()
  }
}
print(f"Total inventory value: ${totalValue:.2f}")
```

**Verified Output:**
```text
Total inventory value: $250.00
```

---

## 6. Common Compiler Errors and Real Diagnostics

The Mycel compiler includes helpful error diagnostics and did-you-mean hints. Below are real compiler diagnostics generated with `mycel check` for common mistakes:

### Mistake 1: Using `def` (Python habit) instead of `fn`

Mycel uses `fn name(params) { ... }` with curly braces, never Python's `def` or colon `:` blocks.

**Incorrect Code:**
```mycel
def calculate(x, y):
  return x + y
```

**Real Compiler Diagnostic:**
```text
error [E0101]: `def` is Python — Mycel writes `fn name(args) { ... }`
  --> snippet.myc:1:1
  |
1 | def calculate(x, y):
  | ^^^
  why: this word comes from another language
  fix: see `mycel help habits`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
fn calculate(x: Int, y: Int) -> Int {
  return x + y
}
```

### Mistake 2: Using `elif` (Python habit) instead of `else if`

Mycel writes `else if` as two words, exactly like JavaScript, Rust, and Go.

**Incorrect Code:**
```mycel
let x = 10
if x > 20 {
  print("big")
} elif x > 5 {
  print("medium")
}
```

**Real Compiler Diagnostic:**
```text
error [E0100]: unexpected `elif` after the statement
  --> snippet.myc:4:3
  |
4 | } elif x > 5 {
  |   ^^^^
  why: statements are separated by a newline or `;`
  fix: put the next statement on its own line

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let x = 10
if x > 20 {
  print("big")
} else if x > 5 {
  print("medium")
}
```

### Mistake 3: Expecting `//` (Python habit) for integer division

`7 / 2` in Mycel always performs floating-point division (evaluates to `3.5`). Integer division is a method: `7.div(2)` evaluates to `3`.

**Incorrect Code:**
```mycel
let a = 15 // 4
```

**Real Compiler Diagnostic:**
```text
no problems found
```

**Fixed Mycel Code:**
```mycel
let a = 15.div(4)
```

### Mistake 4: Using `None` or `null` instead of `nil`

Mycel uses `nil` (like Swift, Lua, and Ruby) to represent the absence of a value. `None` and `null` are rejected with helpful fix-it diagnostics.

**Incorrect Code:**
```mycel
let name: String? = None
```

**Real Compiler Diagnostic:**
```text
error [E0352]: `None` is Python — Mycel writes `nil`
  --> snippet.myc:1:21
  |
1 | let name: String? = None
  |                     ^^^^
  why: `None` is not defined in Mycel
  fix: see `mycel help habits`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let name: String? = nil
```

### Mistake 5: Single quotes around multi-character text

Single quotes `'c'` are strictly single-character `Char` literals. Strings MUST use double quotes `"..."`.

**Incorrect Code:**
```mycel
let greeting = 'Hello, world!'
```

**Real Compiler Diagnostic:**
```text
error [E0001]: single quotes hold one character in Mycel — text uses double quotes (the JavaScript/Python 'text' habit)
  --> snippet.myc:1:16
  |
1 | let greeting = 'Hello, world!'
  |                ^^
  why: a Char literal holds exactly one character
  fix: use "Hello, world!" for a String

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let greeting = "Hello, world!"
```

### Mistake 6: Using JavaScript's `function` keyword

The `function` keyword is a JavaScript habit. Mycel exclusively uses `fn`.

**Incorrect Code:**
```mycel
function add(a, b) {
  return a + b;
}
```

**Real Compiler Diagnostic:**
```text
error [E0101]: `function` is JavaScript — Mycel writes `fn name(args) { ... }`
  --> snippet.myc:1:1
  |
1 | function add(a, b) {
  | ^^^^^^^^
  why: this word comes from another language
  fix: see `mycel help habits`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
fn add(a: Int, b: Int) -> Int {
  return a + b
}
```

### Mistake 7: Using `const` instead of `let`

Immutable bindings are declared with `let`, not `const` or `val`.

**Incorrect Code:**
```mycel
const maxItems = 100
```

**Real Compiler Diagnostic:**
```text
error [E0101]: `const` is JavaScript — Mycel writes `let` (use `var` for a value that changes)
  --> snippet.myc:1:1
  |
1 | const maxItems = 100
  | ^^^^^
  why: this word comes from another language
  fix: see `mycel help habits`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let maxItems = 100
```

### Mistake 8: Indexing tuples with brackets `[0]` instead of dot `.0`

Tuples in Mycel use dot notation: `tup.0`, `tup.1`, or pattern matching `let (a, b) = tup`.

**Incorrect Code:**
```mycel
let pair = ("Alice", 95)
let first = pair[0]
```

**Real Compiler Diagnostic:**
```text
error [E0383]: (String, Int) cannot be indexed
  --> snippet.myc:2:13
  |
2 | let first = pair[0]
  |             ^^^^^^^
  fix: only arrays, maps and Strings support `[...]`; define `operator [](i: Int) -> T` for your own types

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let pair = ("Alice", 95)
let first = pair.0
```

### Mistake 9: Calling methods on optional `T?` without `?.` or `!`

Optional types `T?` are safe by default. You cannot call methods on `T?` directly without narrowing, optional chaining `?.`, coalescing `??`, or force-unwrapping `!`.

**Incorrect Code:**
```mycel
let name: String? = "Mycel"
let len = name.length
```

**Real Compiler Diagnostic:**
```text
error [E0382]: cannot use `.length` on String? because it might be nil
  --> snippet.myc:2:11
  |
2 | let len = name.length
  |           ^^^^
  why: optional values must be unwrapped before use
  fix: use `?.length` (result becomes optional), `value!.length` (panics on nil), or `if let v = value { v.length }`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
let name: String? = "Mycel"
let len = name?.length ?? 0
```

### Mistake 10: Calling `super()` like Python instead of `super.init(...)`

Subclass initializers must explicitly invoke `super.init(...)`.

**Incorrect Code:**
```mycel
class Animal { init() {} }
class Dog: Animal {
  init() {
    super()
  }
}
```

**Real Compiler Diagnostic:**
```text
error [E0313]: `super` must be followed by a member: `super.method(...)` or `super.init(...)`
  --> snippet.myc:4:5
  |
4 |     super()
  |     ^^^^^

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
class Animal { init() {} }
class Dog: Animal {
  init() {
    super.init()
  }
}
```

### Mistake 11: Attempting to reassign an immutable `let` variable

`let` creates an immutable binding. Use `var` when you intend to reassign a variable.

**Incorrect Code:**
```mycel
let score = 50
score = 100
```

**Real Compiler Diagnostic:**
```text
error [E0371]: cannot assign to `score` because it is declared with `let`
  --> snippet.myc:2:1
  |
2 | score = 100
  | ^^^^^
  fix: declare it with `var`

1 error, 0 warnings
```

**Fixed Mycel Code:**
```mycel
var score = 50
score = 100
```

### Mistake 12: Missing `return` in a typed function

Functions with explicit non-Void return types must return a value on every code path.

**Incorrect Code:**
```mycel
fn calculate() -> Int {
  let a = 10
  let b = 20
}
```

**Real Compiler Diagnostic:**
```text
warning [W0101]: variable `a` is never used
  --> snippet.myc:2:7
  |
2 |   let a = 10
  |       ^
  fix: remove it, or rename it `_a` to silence this warning

warning [W0101]: variable `b` is never used
  --> snippet.myc:3:7
  |
3 |   let b = 20
  |       ^
  fix: remove it, or rename it `_b` to silence this warning

error [E0252]: `calculate` must return Int on every path
  --> snippet.myc:4:1
  |
4 | }
  | ^
  why: execution can reach the end of the function without a return
  fix: add `return <Int>` at the end, or on the branch that falls through

1 error, 2 warnings
```

**Fixed Mycel Code:**
```mycel
fn calculate() -> Int {
  let a = 10
  let b = 20
  return a + b
}
```

