Skip to content
Back to skills

Snail

ASecurity

Write, build and fix programs in Snail, the indentation-based systems language that snailc compiles to C. Use whenever a project has .snail files or a snail.toml, or Snail code is asked for. Gives one program with most of the syntax, the traps that cost compile cycles, and the commands.

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 1, 2026
developmentpythongoexpressspringgitapi

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add CodeAdopter/Snail --skill snail --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Snail?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Snail
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/codeadopter-snail/badge)](https://www.skillsdirectory.com/skills/codeadopter-snail)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: snail
description: Write, build and fix programs in Snail, the indentation-based systems language that snailc compiles to C. Use whenever a project has .snail files or a snail.toml, or Snail code is asked for. Gives one program with most of the syntax, the traps that cost compile cycles, and the commands.
---

# Writing Snail

Snail reads like Python and runs like C: `snailc` turns the whole program into C and builds it
with clang. There is no garbage collector; lists and allocations are freed explicitly or live
until the program ends. This guide matches the `snailc` that printed it (`snailc guide`). For
games run `snailc guide game`, and for changing a running game `snailc guide hot`.

## Build and run

| Command | Does |
|---|---|
| `snailc check` | Errors only, fastest: run it after every edit |
| `snailc check --fix` | Applies the fixes errors carry (`var` for `let`, `ref`, `let _ = `, a misspelled name) until it checks |
| `snailc run` | Debug build, then run. Bounds checks stop with the Snail file and line |
| `snailc run -- a b` | Passes `a b` to the program (`arg(1)`, `arg(2)`) |
| `snailc build -c release` | Optimized executable, in `build/` |
| `snailc test`, `snailc test combo` | Runs the `test` blocks, each in its own process; a word runs only titles with it |
| `snailc api math`, `snailc api base json` | A library's public declarations, signatures and comments: read before guessing a name |
| `snailc fuzz`, `snailc fuzz json --seconds 60` | Runs a `fuzz` block under libFuzzer until a crash, which it saves for `snailc test` |
| `snailc run --check address,undefined` | Stops at a use after free, a read past an `alloc` block or a signed overflow, naming the Snail line. Tests have it on by default |
| `snailc check file.snail`, `snailc run file.snail` | A lone file, with no `snail.toml` |
| `snailc run file.snail --lib base` | A lone file, with the `base` library mounted |
| `snailc init name`, `snailc init --game name` | A new project folder that runs at once |
| `snailc init --web name` (`--api`, `--service`, `--net`) | A web app, JSON API, background service or TCP server, with an `app.toml` of settings |

Commands without a target use the `snail.toml` in the current folder or the nearest one above:

```toml
main = "main.snail"
libs = ["base", "math"]     # libraries that come with snailc, mounted by name
```

No library is mounted on its own. The ones that come with snailc: `base` (text, files, paths,
`Map`, sorting, `base/seq` queries), `math` (vectors, colors, `Rng`, noise), `game` (a window,
input, 2D drawing, sound), `engine` (3D on the GPU, Windows), `sdl3`, `cuda`.

## One program with most of the syntax

```snail
enum Kind: u8
    Coin
    Gem
    Rock

    fn value() -> int
        return match self
            Coin: 1
            Gem: 10
            else: 0

struct Item
    name: str
    kind: Kind
    weight: f32 = 1.0              # a default, used when a literal leaves it out

    fn heavy() -> bool
        return weight > 2.0        # fields need no self.

struct Vec
    x: f32
    y: f32

fn +(a: Vec, b: Vec) -> Vec        # operators are top-level functions
    return Vec(a.x + b.x, a.y + b.y)

fn largest[T](xs: []T) -> T        # generic: one copy per type used
    var best = xs[0]
    for x in xs
        if x > best: best = x
    return best

fn split_score(n: int) -> (int, int)
    return n / 10, n % 10

fn bump(ref total: int, by: int = 1)
    total += by

fn evens(limit: int) -> seq[int]   # a generator, written out in place where it is looped over
    for i in 0..limit step 2
        yield i

fn main()
    var items: [..]Item            # a list: zeroed means empty, no setup
    items.push(Item("coin", Coin))
    items.push(Item(name: "gem", kind: Gem, weight: 0.5))
    items.push(Item("boulder", Rock, 9.0))
    var total = 0
    for ref it in items            # ref: change the stored item, not a copy
        it.weight *= 2.0
        bump(ref total, it.kind.value)
    items.retain(|it| not it.heavy)
    print("kept {items.len}, total {total}, first {items[0].name}")
    let (tens, ones) = split_score(total)
    print("tens {tens} ones {ones} largest {largest([3, 9, 4])}")
    let p = Vec(1.0, 2.0) + Vec(0.5, 0.5)
    print("p = ({p.x:.1}, {p.y:.1})")
    var out: [..]u8                # text that must last is built in a [..]u8
    defer out.free()
    for i, e in evens(7)
        if i > 0: out += ','
        out += "{e}"
    print(str(out))
    for c in "hey" reverse
        write("{c:c}")
    print("")
    let grade = match total
        0..5: "low"
        5..20: "mid"
        else: "high"
    print("grade {grade}, kinds {Kind.count}, {items[0].kind}")
```

```text
kept 2, total 11, first coin
tens 1 ones 1 largest 9
p = (1.5, 2.5)
0,2,4,6
yeh
grade mid, kinds 3, Coin
```

## Traps: where a guess fails

Each of these is a compile error or a wrong value that costs a build cycle.

- **`lo..hi` excludes `hi`.** `0..n` gives the `n` indices of `n` items, and `s[a..b]` holds
  `b - a` bytes. Where the end itself belongs, write `lo..=hi`, never `hi + 1`: `for i in 1..=n`,
  `'a'..='z':` as a match label, `t in 0.0..=1.0`.
- **A kept function parameter takes no capturing lambda.** A function that stores a parameter of
  a function type (`on_click = handler`) makes every caller pass a function's name or a lambda that
  uses only its parameters: `'Box.set' keeps 'g', so it needs a value that reaches no variables`.
- **One namespace, unless `private`.** Every public top-level name of every file and library is
  global, and two declarations of one are an error. Mark a file's helpers `private fn`,
  `private struct`, `private const` and so on: they are seen only in their file and never clash.
  `use path/file` only loads a file, once however many files name it, so each file may `use` what
  it needs. Enum members are not global: two enums may both have `South`, written bare where the
  type is clear and `Heading.South` elsewhere.
- **Built-in names are reserved.** No function of yours may be called `print`, `min`, `max`,
  `abs`, `clamp`, `alloc`, `free`, `copy`, `zero`, `exit`, `format`, `spawn`, `join`, `lock`,
  `unlock`, `sqrt` and the other math names. A method may use one: inside its type a bare call
  is the method when its arguments fit it, so `min(a, b)` beside a `min(o)` method is the
  built-in; `self.min(o)` always reaches the method.
- **`self` in an enum's or distinct type's methods is the value**: `self == North`. In a struct's
  methods, fields and methods need no `self.`: `weight`, `len2()`, and `len2` read like a field.
- **`int` is 32 bits** (`i32`). `len` is an `i64`. Integer variables convert implicitly and
  truncate silently, as in C, so `var n: int = xs.len` keeps the low 32 bits. Use `i64` or `u64`
  for big values and hashes. Signed overflow is undefined behavior: hash in `u64`, or use
  `wrapping_add`.
- **A constant takes its partner's type, and must fit it.** With `b: u8`, `1980 + b` is an error,
  as 1980 would be a `u8`: write `b as int + 1980`. `var n: int = 3000000000` is an error too.
  Hex, binary and `~` constants may use every bit (`let m: i32 = 0xFFFFFFFF`, `x & ~7`), and
  `3000000000 as int` keeps the low bits on purpose. A float constant next to an `f32` stays `f32`.
- **Division follows C.** `7 / 2` is 3 and `-7 % 3` is -1. `7 / 2.0` is 3.5.
- **Floats print exactly.** `{x}` is the shortest text that reads back as the value, as in Python:
  `3.5`, `100.0`, and `0.1 + 0.2` gives `0.30000000000000004`. Round with `{x:.2}` or `{x:8.2}`.
- **`{` starts interpolation in every string.** A literal brace is `\{` or `{{`. A string inside
  the braces is written plainly: `print("{label("x")}")`.
- **Interpolated text is a `str` until the end of its block, or a `[..]u8` of its own.** `"n{n}"`
  passes to any `str` or `cstr` parameter, but as a `str` it cannot be returned, pushed, stored in
  a field or kept in an outer variable. Where a `[..]u8` is wanted it is a new list holding the
  text, which goes anywhere and is freed with `.free()`: `fn label(n: int) -> [..]u8` can
  `return "n{n}"`, and a `[..][..]u8` can `push("item {i}")`. Append with `out += "..."`;
  `str(list)` views a list's bytes until it grows or is freed. A plain literal (`"low"`) lasts
  for the whole program.
- **Strings join, compare and match.** `a + b` is the interpolated text `"{a}{b}"`, with its
  lifetime (above). Strings compare with `<` by their bytes, so `names.sort()` works, and
  `match` takes string labels: `"quit", "q": stop()`.
- **No `if` expression.** Use `cond ? a : b`, or a `match` expression.
- **Operators bind as in Python.** Comparisons chain: `0 <= x < w` is `0 <= x and x < w`, with
  `x` evaluated once. `x & mask == 0` means `(x & mask) == 0`, as bit operators bind tighter than
  comparisons. The words are `and`, `or`, `not`. `as` binds tighter than arithmetic:
  `i as f32 * k` converts `i`, and `a * b as u64` only `b`.
- **`in` searches what is on its right.** `x in [a, b]` (the items take `x`'s type, so enum
  members go bare), `x in 0..n` (`0 <= x < n`), `x in 1..=n` (`1 <= x <= n`), `x in items`
  (an array, slice or list), `c in " \t"` and `"ab" in text`, and `key in m` for any type with a
  `contains` method, such as base's `Map`, `Set` and `Pool`. `not in` negates. With an integer on
  the right it tests a bit: `3 in flags`.
- **A loop's item is a copy, and a `let` never changes.** `for e in es: e.hp -= 1` is an error,
  and so is calling a method that changes fields on the copy (`e.hit()`) or on a `let` (even
  `buf.free_all()`). Use `for ref e in es`, `es[i].hit()`, or `var`. To drop items,
  `es.retain(|e| e.hp > 0)` or `es.swap_remove(i)` walking from the end.
- **No redeclaring in a block.** `let x = 1` then `let x = 2` is an error. `let` cannot be
  assigned; use `var`.
- **A function value kept in a field, list, global or `var` captures nothing.** Store a
  function's name or a lambda that uses only its parameters. A `let` or a parameter may capture.
- **Spaces only.** A tab in indentation is an error.
- **A long statement continues** inside brackets, after a line that ends in an operator (`a +`,
  `x and`, `total =`), and on a next line that starts with `.name` (a chain of calls). Anywhere
  else a line break ends the statement.
- **The command line comes in as `fn main(args: []str)`**, the arguments after the program's
  name, so `args.len == 0` means none was given; plain `fn main()` takes none. `exit(code)` or
  `-> int` on main gives the exit code.

## The rest of the language

- **Values.** `let` is immutable, `var` mutable, `const` folded at compile time. Everything starts
  zeroed; `var buf: [4096]u8 = undefined` skips that. Literals: `0xFF`, `0b1010`, `1_000`, `'a'`
  (a `u8` code), `"text"`.
- **Types.** `i8 i16 int i64 u8 u16 u32 u64 bool f32 f64 str cstr`. `[N]T` arrays copy by value;
  `[E]T` has one item per member of enum `E` (`[Spire: 9.0, else: 1.0]`). `[]T` slices
  (`xs[a..b]`), which write through to what they view even when bound with `let`; `[..]T` lists.
  `*T` pointers dereference on `.`; `&x` and `&xs[i]` give one. `new T` gives a zeroed `*T`,
  `alloc[T](n)` a zeroed block to `free(p)`, `null` is the empty pointer, `p ?? q` picks the first
  that is not null. Tuples: `(int, str)`, `t.0`, `let (a, b) = f()`. `x as T` converts.
- **Optionals.** `fn port_of(s: str) -> int?` returns a value or `null` (none); `[]u8?` is an
  optional slice. Use one with `port_of(s) or 8080`, `?? 8080`, `or return` / `break` /
  `continue`, `or panic("...")`, `== null`, or `let (port, ok) = port_of(s)`. `p or return` works
  on pointers and `ok or return false` on bools too. A call giving a `T?` cannot stand alone
  (`let _ = f()` drops it), `let (v, _) = f()` is an error (write `f() or fallback`), and a `T?`
  prints only through its value: `{port ?? 0}`.
- **Lists.** `push`, `pop`, `add()` (a pointer to a new zeroed item), `remove(i)` (keeps order),
  `swap_remove(i)` (constant time), `retain(keep)`, `resize(n)`, `reserve(n)`, `clear()`,
  `free()`, `sort()`, `sort(|a, b| a.score > b.score)` (true when `a` goes first), `len`. There
  is no `insert`: for a queue, push and keep a head index, or `remove(0)`. A list passes where a
  slice is expected. Copying a list copies its handle, not its items. `[]` is an empty list where
  one is wanted: `list_dir(path) or []`.
- **Structs.** Literals by position or name, `..base` copies the rest: `Style(width: 3, ..base)`.
  `a == b` compares fields when the struct declares no `==` (not through list or array fields).
  `union`, `packed Cell: u16` (bit fields: `x: u8 : 6`), `type Port = u16` and
  `type Meters = f64` (distinct, with methods), `@bits(Dir) type Dirs = u8` (a set of members),
  `extend Type` adds methods from another file. Methods assign fields directly (`stock -= n`); called on `xs[i]`, a `var`, a `ref` item or
  a pointer they change it in place. A method without arguments reads like a field: `v.length`. A static
  method: `static fn origin() -> Vec`, called `Vec.origin`. In `struct Queue[T]`, `T` is a type
  like any other (`items: [..]T`, `fn push(x: T)`), and a zeroed `var q: Queue[Order]` is ready.
- **Enums.** `enum Dir: u8`, members numbered from 0 or given (`East = 4`), written bare where the
  type is clear. `Dir.count`. Printing gives the member's name.
- **Control.** `if`/`elif`/`else`, `while`, `loop` (forever), `break`, `continue`, `return`.
  `for i in 0..n` (to `n - 1`), `for i in 1..=n` (to `n`), `for i, x in xs`, `for (k, v) in pairs`,
  `for d in Dir` (an enum's members), `for bit in mask`, `for c in text` (bytes),
  `for piece in text.split(',')` or `text.split()` (whitespace), each with `reverse`, `step k` or
  `where cond`. `match` on integers, enums and str, with `a, b:`, ranges `'a'..='z':` and
  `else:`. As a statement its arms are statements or indented blocks (`North: y -= 1`) and may
  leave members out; as an expression it must name every member of the enum or have an `else`.
  One statement may follow a colon: `if done: break`.
- **Clean-up.** `defer stmt` runs when the block is left however it is left. `with r = open(x)`
  calls `r.end()` at the end of its block. `init` blocks run once at startup, to fill tables.
- **Tests.** A top-level `test "what it checks"` block, beside the code, fails on a failed `assert`,
  a `panic`, a crash or a memory or overflow bug the default `--check address,undefined` finds. Only
  `snailc test` runs tests; other commands just check them. Passing tests print nothing, a failed
  one shows its title, line, output and how it ended. `assert(a == b)` (or `!=`, `<` and the
  rest) shows both values when it fails, `assertion failed: 4 == 5`, so one comparison per assert
  says the most. A library's tests run with its folder as the target: `snailc test lib/base`.
  `fuzz "what it reads"` is a test given `data: []u8` that must survive any bytes: `snailc fuzz`
  runs it under libFuzzer until it crashes, saving the input in `fuzz/<file>-<title>/`, which
  `snailc test` replays. Give every parser one.
- **Where a call came from.** `caller()` is `"file:line:col"` of where it is written; as a default,
  `fn get(key: str, at: str = caller())`, it is where each call is, so a panic can name the
  caller's line: `panic("no key {key} at {at}")`.
- **Functions.** Defaults (`fn noise(q: f32 = 1.0)`), named arguments (`noise(q: 0.5)`), `ref`
  parameters (`bump(ref total)`), tuples returned (`return q, r`). Lambdas: `|x| x * 2`, one
  expression, capturing surrounding variables by reference. Type parameters: `fn f[T](...)`,
  `struct Stack[T]`, `Stack[int]`. Compile-time values: `fn step[along: Axis](...)` makes a copy
  per value, and a run-time value picks the copy.
- **Fields of a struct.** `for f in fields(T)` writes its body out per field at compile time:
  `f.name`, `f.index`, `x.(f)` (the field, typed), `f.has("skip")` and `f.tag("json")` read tags
  written on fields (`hp: int @json("health")`). `if f.name == "hp": x.(f) += 1` is checked only
  in hp's copy. One generic function then prints, saves or compares any struct. `if T is int:
  return ...` in a generic function picks code per type, and the rest is left to other types;
  `T is struct`, `enum`, `integer`, `float`, `list`, `slice`, `array`, `optional`, `pointer` and
  `tuple` test the kind, and a helper such as `fn items[U](xs: []U)` takes a list's element type.
- **Sequences.** `fn evens() -> seq[int]` with `yield`; a parameter `seq[T]` takes a generator or
  any array, list or `str`. To let a loop change items, yield pointers: `-> seq[*Item]` with
  `yield &items[i]`. Nothing is allocated: the loop is written out in place. `use base/seq`
  adds LINQ-style methods: `where`, `select`, `take`, `count_where`, `any`, `sum`, `min_by`,
  `to_list()` (allocates), `join(", ")`, `refs()`.
- **Strings.** `str` is a pointer and a length: `s.len`, `s[i]` (a `u8`), `s[a..b]`, `==`.
  `parse_int(s)`, `parse_float(s)`, `str(bytes)`. Formats: `{v:.2}`, `{v:8}` (right-aligned in
  8; numbers, text and enums alike), `{name:-12}` (left-aligned in 12), `{n:05}`, `{n:x}`,
  `{code:c}`, and a literal inside: `{"Total":-20}`. `read_line()` gives a `str?`: `let line = read_line() or break`.
  `print(a, b)` prints values with a space between them, and a struct or tuple prints its fields:
  `Vec(x: 1.0, y: 2.0)`.
- **Threads.** `let t = spawn(work, &data)` runs `fn work(d: *T)`; `join(t)`. `atomic_add(&x, 1)`
  and the other atomics; `lock(&flag)`/`unlock(&flag)`.
- **C.** `extern include "x.h"`, `extern fn puts(s: cstr) -> int`, `extern struct`, `extern
  type`. `snailc bind header.h --prefix SDL_` writes the declarations for a whole library.
- **Speed.** `@inline`, `@align(64)` on fields, SIMD types such as `f32x8`
  (`f32x8.load(p)`, `.sum`), `alloc_large`. Release builds use `-O2 -march=native`.

## The base library

Mount it with `libs = ["base"]`, then `use` the files you need. Before guessing a name in any
library, `snailc api base json` (or `snailc api math spring`) prints its public declarations with
their signatures and comments:

| File | Functions |
|---|---|
| `base/text` | `starts_with`, `ends_with`, `contains_text`, `index_of_text`, `replace_text`, `trim`, `split_char` (a `[..]str`), `compare_ordinal`, `equals_ignore_case`, `lower_ascii(c)`, `upper_ascii(c)`, `is_ascii_letter(c)`, `is_digit(c)`, `pad_left`, `thousands`, `own_text(s)` (a copy in memory of its own, from any thread) |
| `base/sys` | `read_file(path)` gives a `[]u8?` (`read_file(path) or []`), `write_text(path, text)`, `write_file`, `file_exists`, `dir_exists`, `make_dir`, `delete_file`, `copy_file`, `env_var(name)` a `str?`, `list_dir(path)` a `[..]DirEntry?`, `file_stat(path)` a `FileStamp?` (`size`, `ticks`), `current_dir()` |
| `base/args` | `let o = parse_args[Options]()`: each field of the struct is a flag (`max_count` is `--max-count`), its default the flag's; tags `@help("...")`, `@short("v")`, `@flag("name")`, `@required`, and `@rest` on a `[..]str` for the other arguments. Prints the usage for `-h`, exits with 2 on a wrong flag; `ArgParser` to parse without exiting |
| `base/log` | `log_info("listening on {port}")`, `log_debug`, `log_warn`, `log_error` (time, level, your file:line); `log_level = Debug`, `log_to_file(path)`, `log_as_json = true`. A line below the level is not formatted at all |
| `base/json` | `to_json(x)` (a `[..]u8` to free; `to_json(x, true)` indents), `write_json(&out, x)`, `from_json[T](text)` a `T?`; for a server `var json = JsonReader(text: body)`, `json.read[T]() or ...` with `json.error`, `json.free()`. Structs through their fields: `@json("name")` renames one, `@skip` leaves it out; enums as names, `T?` as null; `free_json(&x)` frees the lists a read made |
| `base/pack` | `to_pack(x, version)` (a `[..]u8`) and `from_pack[T](str(bytes), version)` a `T?`: compact binary through fields, for saves and messages; a field added later is tagged `@since(2)` and keeps its default when older data is read; `free_pack(&x)` frees the lists a read made |
| `base/config` | `let c = read_config[Config]("app.toml") or exit(2)`: a TOML file into a struct, a key per field, `[table]` a struct field, `[[table]]` a list of structs; an unknown key is an error naming its line, a missing one keeps the field's default |
| `base/toml` | `var r = TomlReader(text: t)`, `let root = r.read()` (null on error, with `r.error` and `r.error_line`), `root.get("server").get("port").integer` |
| `base/time` | `now()` gives a `Time` (UTC, prints as ISO 8601: `2026-12-01T10:15:30.25Z`), `t.date()` (`year`, `month`, `day`, `hour`, `minute`, `second`, `micro`, `weekday`), `Date(...).time()`, `parse_time(text)` a `Time?`, `t.http_date()`, `parse_http_date`; `Duration` from `5 * Minute`, `1.5 * Second` (`Microsecond` .. `Day`), prints as `1m30s`; `later - t` is a `Duration`. `now_ms()` stays the stopwatch |
| `base/crypto` | `random_bytes(buf)`, `random_key()` (32 bytes), `random_token()` (URL-safe text), `hmac_sha256(key, msg)` a `[32]u8` (`str(tag)` reads it), `fixed_time_equals(a, b)`, `hash_password(pw)` / `check_password(pw, stored)` (PBKDF2), `to_hex` / `from_hex`, `to_base64` / `to_base64_url` / `from_base64` (each gives a `[..]u8` to free; `from_` ones a `[..]u8?`) |
| `base/paths` | `combine(a, b)`, `directory_name`, `file_name_of`, `extension_of`, `change_extension`, `full_path` |
| `base/maps` | `Map[K, V]` and `Set[T]`, zeroed and ready: `m.set(k, v)`, `m.get(k)` (panics on a missing key, naming your line), `m.get_or(k, fallback)`, `m.find(k)` (a `*V` or `null`), `let (v, added) = m.put(k)` (a `*V`, zeroed when just added), `m.has(k)` or `k in m`, `m.remove(k)`, `m.len`, `for (k, v) in m.items()` in insertion order; `s.add(x)` (false when already there). Keys: integers, enums, pointers, `str` (kept, not copied: the text must outlive the map; `m.ignore_case = true` for paths) or structs of those |
| `base/pool` | `Pool[T]` of reusable slots: `let h = p.add(v)` gives a `Handle[T]`, `p.get(h)` a `*T` or `null` once removed, `h in p`, `p.remove(h)`, `for e in p.items()` (pointers). For enemies, bullets, particles |
| `base/queue` | `Queue[T]` (`push` at the back, `pop` from the front) and `Heap[T]` (`pop` gives the smallest by `<`; a struct declares `fn <(a: T, b: T) -> bool`) |
| `base/map` | the untyped `Map` from before generics, keyed by text through slots; prefer `base/maps` |
| `base/sort` | `sort_ordinal(&names)` for a `[..]str` |
| `base/seq` | the query methods above |

```snail
use base/sys
use base/paths
use base/maps

fn main()
    let path = combine(temp_dir(), "words.txt")
    defer delete_file(path)
    write_text(path, "the cat saw the dog\nthe end\n")
    let data = read_file(path) or panic("cannot read {path}")
    var counts: Map[str, int]
    for line in str(data).split('\n')
        for word in line.split()
            counts.set(word, counts.get_or(word, 0) + 1)
    print("the: {counts.get("the")}, words: {counts.len}")
```

```text
the: 3, words: 5
```

## Web apps and services

`libs = ["web"]` mounts `lib/web` with `lib/app` and `lib/net` (`snailc init --web` writes it all).
A `WebApp[S]` routes requests to handlers given a `*Ctx[S]`; `S` holds the app's services, which
`setup` fills in once, after the settings are read from flags, `NAME_KEY` environment variables
and `app.toml`. `snailc api web app` lists the rest; `docs/web.md` explains it.

```snail
use web

struct Item
    name: str
    price: f64

struct Shop
    items: [..]Item
    lock: int

fn setup(s: *Shop, cfg: *Config) -> bool
    s.items.push(Item(name: "tea", price: cfg.int("tea-price", 3) as f64))
    return true

fn list_items(c: *Ctx[Shop])
    lock(&c.app.lock)
    defer unlock(&c.app.lock)
    c.json(c.app.items)

fn add_item(c: *Ctx[Shop])
    let item = c.body[Item]() or return         # bad JSON was already answered 400
    lock(&c.app.lock)
    defer unlock(&c.app.lock)
    c.app.items.push(Item(name: own_text(item.name), price: item.price))
    c.status(201)

fn get_item(c: *Ctx[Shop])
    let i = c.param_int("id") or return         # not a number: answered 400
    lock(&c.app.lock)
    defer unlock(&c.app.lock)
    if i < 0 or i >= c.app.items.len
        c.error(404, "no item {i}")             # {"error":"no item 7"}
        return
    c.json(c.app.items[i])

fn main()
    var app = web_app[Shop](setup)
    app.get("/items", list_items)
    app.get("/items/:id", get_item)
    app.post("/items", add_item)
    app.run()                                   # port 8080; --port 9000, Ctrl+C stops it
```

- Route parameters are `:id` (one segment) and `*rest`, never `{id}`, which a string interpolates.
- Handlers run on several threads at once: what they change in `c.app` needs a lock or atomics.
- Text from the request (`c.body` strings, `c.param`, `c.query`) lasts until the handler returns;
  copy what the services keep with `own_text`, not `keep`, whose arena is not thread-safe.
- `c.query("q")` is a `str?`; `c.text(s)`, `c.html(s)`, `c.error(code, msg)`, `c.redirect(url)`.
- `app.files("/", embed_dir("public"))` serves a folder carried inside the program.
- `app.every(ms, task)` and `app.background(task)` run a `fn(*S)` on threads of their own.
- `service_app[S](setup)` is the same host without HTTP; `TcpServer` (`use net`) serves TCP.

## Reading errors

An error names the Snail file, line and column, shows the line, and usually says what to write
instead. Fix the first error and check again: later ones often follow from it. A panic names its
line too: `panic: main.snail:9:14: out of lives` from `panic(...)`, and in a debug build
`panic: index 5 out of range 0..3 at main.snail:12`. A crash (a null pointer, a stack overflow, a
division by zero) under `snailc run` or `snailc test` ends with its stack at Snail lines:
`Crashed  at enemy.snail:5 in hurt`, then `from ...` lines for the callers. `@on_panic` on a free
function taking nothing runs it once at a panic or crash, to save or flush before the program
ends. Notes about padding or zeroing are hints, not errors.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.