# GCSL

> A statically typed language for configuration and scripting.

---

# GCSL

_GCSL / Getting Started_

> A language for typed configuration values and executable scripts.

GCSL is a statically typed scripting language. A program can describe a
configuration record, compute a value, or run commands. You use the same
expressions for all three, with function types separating pure computation
from operations that can change the outside world.

The `gcsl` command runs programs, checks them without execution, formats
source files, and serves editor requests. Starting it without a command
opens an interactive read-evaluate-print loop (REPL).

## Values first

A file is a block of declarations and expressions. Named fields form its
resulting record. This configuration computes one field from another:

```gcsl
name = "gcsl"
version = "0.1.0"
archive = "{name}-{version}.tar.gz"
```

A file can instead return one expression. Use `let` for private values that
don't become fields of a record. The checker catches incompatible types and
unresolved names before any part of the program runs.

## Execution and trust

Pure functions use `:` before their result type. Impure functions use
`->`; they can run processes, access files, and await deferred work.
Memoized functions use `->>` and reuse results within an execution context.
A `lazy` expression delays work until it is awaited. It doesn't start a
background task.

GCSL's type system is not a sandbox. Running a script gives its process and
file operations the permissions of the process running GCSL. Check an
unfamiliar program with `gcsl check` before deciding whether to run it.
Checking does not establish that executing it is safe.

## Where to go next

Start with [Running a First Program](/gcsl/getting-started/running-a-first-program.md), then
read [Values and Bindings](/gcsl/language/values-and-bindings.md). Use `gcsl(1)` for the
command interface, `gcsl(5)` for language rules, and `gcsl-stdlib(3)` for
standard functions.

Pekit embeds GCSL to provide its own build interface. Its definitions and
commands belong to Pekit. The separate `tree-sitter-gcsl` repository owns
its editor grammar and queries; the compiler parser in this repository is
the authority for whether a GCSL program is accepted.

---

# Running a First Program

_GCSL / Getting Started_

> Create, check, and run a small GCSL file.

You can run a single GCSL file without creating a workspace. This example
checks a small configuration and prints its computed description.

## Before you start

You need the following:

- The `gcsl` executable on your command search path.
- A writable directory for the example file.

## Create and run the file

1. Save the following text as `hello.gcsl`:

   ```gcsl
   let component = {name = "gcsl"; version = "0.1.0"}
   "{component.name} {component.version}"
   ```

2. Check the file without running it:

   ```sh
   gcsl check hello.gcsl
   ```

3. Run the file:

   ```sh
   gcsl run hello.gcsl
   ```

## Check the result

The check reports `no problems in 1 file checked` on standard error. The
run prints the string contents on standard output:

```text
gcsl 0.1.0
```

A file whose result is `{}`, the empty record, prints nothing. Diagnostics
go to standard error. See `gcsl(1)` for exit statuses and output modes.

## Trying expressions interactively

Run `gcsl` without arguments to open the REPL. Enter `let n = 21`, then
`n * 2` on the next line. The second line prints `42 : Int`. Each input is
one line; separate several items on that line with semicolons. Press
**Ctrl+D** to leave the session.

---

# Values and Bindings

_GCSL / The Language_

> Understand block results, records, local names, and value updates.

GCSL programs compute values. A block can return one value or construct a
record of named fields, so you can use configuration data inside ordinary
expressions without a separate data format.

## Blocks and records

Newlines or semicolons separate items inside a file or `{ ... }` block.
A block without fields returns its final expression, or an explicit
`= expression` result. A block with fields returns their record instead;
it cannot also have an explicit result. The empty record `{}` represents
an operation with no useful result.

A field is a public part of the resulting record. A `let` binding is local
to its scope. This block keeps the intermediate name private:

```gcsl
let release = "0.1.0"
name = "gcsl"
archive = "{name}-{release}.tar.gz"
```

Top-level fields and named functions can refer to declarations written
later. Inner blocks evaluate their ordinary fields in order. Private
`let` bindings become available after their declaration.

## Updating a binding

`:=` replaces the value associated with a local name. For an ordinary
`let`, this is restricted to the block that declares it. Use `let mut`
when an inner block of the same function needs to update the variable:

```gcsl
let mut total = 0
for cost in [3, 8, 5] {
    total := total + cost
}
total
```

The variable keeps its declared or inferred type. Values themselves do not
change: replacing a record field or list element constructs an updated
value for the binding. Other bindings and previously created closures
keep the values they already held.

A closure captures values when it is created. It cannot update a mutable
variable belonging to its enclosing function. Pass in a value and return
an updated value when you need that communication.

## Names and arithmetic

Names can contain hyphens. Write spaces around subtraction so that
`left - right` is an operation rather than a name. Integer arithmetic uses
signed 64-bit values with checked overflow. Floating-point values use
64-bit precision. `/` produces a floating-point result; `//` and `%` are
integer floor division and modulo.

Integer literals adapt to an expected numeric type. A bound `Int` does
not silently become a `Float`; use `float(value)` when that conversion is
intended. Conditions require `Bool`, not a nonzero integer or a nonempty
string. See `gcsl(5)` for syntax and operator rules.

## Durations and sizes

`Duration` and `Size` hold amounts with units. Write a duration as a
number followed by units from largest to smallest: `30s`, `500ms`,
`1h30m`, `2d`. The units are `d`, `h`, `m`, `s`, `ms`, `us` and `ns`, and a
day is exactly 24 hours. Write a size with one unit: `512B`, the decimal
`KB` to `PB`, or the binary `KiB` to `PiB`, as in `2GiB`. The last part of
a literal can have a fraction if the result is a whole number of
nanoseconds or bytes, so `1.5s` and `0.5KiB` are allowed but `1.5ns` is
not. Units are case-sensitive.

```gcsl
let timeout = 1m30s
retry_after = timeout // 3
budget = 2 * timeout
memory = 2GiB + 512MiB
long = timeout > 1m
message = "giving up after {timeout}"
```

Add or subtract two values of the same kind, multiply one by an `Int`,
and use `//` to divide by an `Int` or by another value of the same kind.
Dividing by the same kind gives an `Int`. `%` gives the remainder of one
value by another of the same kind. Values of the same kind can be
compared. Durations and sizes never mix with each other, with `Int` or
with `Float`, and an integer is never a duration, so write `0s` rather
than `0`. `/` is not available, because the result would not be a whole
number of the smallest unit.

A value is shown as its simplest literal: `retry_after` above is `30s`,
`budget` is `3m`, and `memory` is `2560MiB`.

---

# Records and Types

_GCSL / The Language_

> Compose structural records and apply annotations and defaults.

A record type describes the fields a value supplies. GCSL uses structural
types: two declarations with the same structure describe the same type,
and a record can be used where fewer of its fields are required.

## Declaring a shape

Use `type` to give a structure a reusable name. An annotation checks a
value against that structure. Defaults supply omitted fields in a record
literal checked against the type:

```gcsl
type Install = {from: String, exclude: List<String> = []}
let item: Install = {from = "src"}
item.exclude
```

Defaults are constant expressions, not arbitrary function calls. They are
applied where a record literal has the expected type; they don't add
fields to an already constructed variable with a smaller type.

An annotation also determines what fields later code can see. Extra
fields in a record literal produce a warning when an expected type hides
them. A structural alias does not introduce a distinct runtime identity.

## Generic types

A type can take type parameters, named in angle brackets after its name.
Each use names the types to put in their place:

```gcsl
type Pair<A, B> = {first: A, second: B}
let entry: Pair<String, Int> = {first = "port"; second = 8080}
entry.second
```

A use must give as many type arguments as the type has parameters, and a
type without parameters takes none. Because types are structural,
`Pair<String, Int>` is the same type as `{first: String, second: Int}`. A
generic type can be built from another, as in
`type Named<T> = Pair<String, T>`. It can't refer to itself, and it can't
spread one of its parameters, because the parameter might not be a record.

## Enums

An extensible enum is a type whose variants any module can add. Declare
the enum, with an optional bound that every variant's payload must fit,
and then its variants, each with a payload type:

```gcsl
enum Shape extensible<{*: Int}>
enum Shape::Square<{side: Int}>
enum Shape::Point
square = Shape::Square({side = 3})
```

A variant is also a value: `Shape::Square` on its own has the type
`Variant<Shape, {side: Int}>`. Calling it makes a value of the enum,
and you can pass it to a function as a key. `kind.matches(value)` tests
whether a value is of that variant, and `kind.payload(value)` takes out
its payload:

```gcsl
enum Tool extensible
enum Tool::C<{cc: String}>
fn find<T>(kind: Variant<Tool, T>, tools: List<Tool>, fallback: T): T {
    for t in tools { if kind.matches(t) { return kind.payload(t) } }
    fallback
}
cc = find(Tool::C, [Tool::C({cc = "gcc"})], {cc = "cc"}).cc
```

Unlike records, enums are nominal: two enums are different types even
if they look alike. `value is Tool` tests whether a value is of the enum.
Values of an enum are compared with `==` only when the enum has a bound,
because an unbounded payload might hold a function. A variant is visible
in its own file, to the other files of its directory and the directories
below it, and to every file that imports its module.

## Partial records

`Partial<T>` holds any of the fields of the record type `T`. Use it to
describe a record by only some of its fields, and `.matches()` to test
a whole record against it:

```gcsl
type Platform = {arch: String, os: String}
let wanted: Partial<Platform> = {arch = "x86_64"}
fits = wanted.matches({arch = "x86_64"; os = "linux"})
```

A field of a partial record can't be read by name, because it might be
absent.

## Records of any fields

A rest-field, `*: T`, gives the type of every field that a record type
doesn't name. Use it when the field names are data, such as paths. A
`{*: String}` holds any fields, each a `String`. Named fields keep their
own types, so `{to: String, *: Int}` holds a `String` field `to`, and any
other fields are `Int`s:

```gcsl
let files: {*: String} = {"bin/*" = "bin/*"; "sbin/*" = "sbin/*"}
files
```

Write the record literal where the type is expected: in an annotation,
an argument or a definition's result. There, each field that the type
doesn't name is checked against the rest-field. A value whose own type
has no rest-field doesn't fit one, because a record keeps fields that its
static type hides, and they could be of any type. `*: *` is the exception,
as [Open records](#open-records) describes.

Read a named field as usual. A field that only the rest-field covers
can't be read by name, and a record whose type has a rest-field can't be
spread. Typed equality compares every field, and `is` and `as` test each
field that the rest-field covers.

When the names themselves are only known as the program runs, such as a
program's environment built from a list, make the record with `record`.
It takes a list of entries, each an `Entry<T>`, a `{key: String, value:
T}`, and gives a `{*: T}` with a field for each:

```gcsl
let vars = [{key = "LANG"; value = "C"}, {key = "TZ"; value = "UTC"}]
let env: {*: String} = record(vars)
env == ({LANG = "C"; TZ = "UTC"}: {*: String})
```

Each field is named as the program names it, so the record equals one
written with the same fields, in any order. A key given twice is an error
when the program runs.

`entries` does the reverse. It lists a record's fields as entries, sorted
by key, so two equal records always give the same list:

```gcsl
let deps: {*: String} = {"org.gnu.glibc" = ">= 2.44"; "org.gnu.bash" = ""}
entries(deps)
```

The record's type must have a rest-field, because a record can hold
fields that its type hides. Without one, the type doesn't say what those
fields are, so read the fields it names by name instead. An entry's value
has a type that covers every field, named or not: the entries of a `{to:
String, *: Int}` have values of type `Int | String`. `record(entries(r))`
equals `r`.

## Open records

A rest-field whose type is `*` holds any data. An open record type names
the fields it knows about and accepts others, so the LSP still completes
the known fields:

```gcsl
type Service = {name: String, *: *}
let web: Service = {name = "web"; limits = {cpu = 2}}
(web as {limits: {cpu: Int}}).limits.cpu
```

Data is a scalar, a `File`, a `Dir`, or a record or list of data, or a
value of an enum whose bound is data. A function, a secret or a `Sandbox`
doesn't fit `*`, and neither does a type parameter. A value that might
still be a future is awaited where it is given, at any depth, so that `is`
and `as` find it present. `*` is written only as a rest-field's type:
`{a: *}` and `List<*>` are errors.

Any record type fits `*: *` if its named fields are data, with or without a
rest-field of its own, so `{version: String, *: *}` accepts a value of type
`{version: String}`.

A field that `*` covers can't be read by name, because nothing says what
type it has. Say what you expect with `as`, which fails when the program
runs, naming the field, if the value isn't that type. `is` asks the same
question as a `Bool`:

```text
fn dependencies(pkg: Package) -> {*: String} {
    if pkg is {ppk: {dependencies: {}}} {
        = (pkg as {ppk: {dependencies: {*: String}}}).ppk.dependencies
    } else {
        = {}
    }
}
```

The `is` here tests only that the field is a record, so that a field of the
wrong shape fails at the `as`, and isn't taken for a missing one. Every
field of the type tested must be present: a field's default doesn't apply
to a test. An `is` that narrows a variable narrows it to the type tested,
so read the fields you know from outside the branch. In the `else` branch,
the variable keeps its type.

`entries` lists an open record too. Each entry is a `{key: String, *: *}`,
so read its value with `as` or `is`, as you would any field that `*`
covers. This lists every field the record holds, including any field its
type hid. A test of a hidden field that isn't data, such as a function,
is false, and `as` fails.

A record type with no rest-field already fits `{*: *}`, so `as {*: *}`
tests nothing and leaves the type as it was. To list a field you only
know is a record, such as `ppk` after `if pkg is {ppk: {}}`, give it the
type instead: `let meta: {*: *} = pkg.ppk`, then `entries(meta)`.

`json.decode` can't decode into `*`, because a document doesn't say what
type each value should be.

## Combining fields

Dotted definitions construct nested records. Compatible dotted paths
merge, including across files in a workspace:

```gcsl
server.host = "localhost"
server.port = 8080
server.tls.enabled = true
```

A whole-field definition such as `server = {...}` closes that field to
further dotted extensions. Define the individual dotted leaves when you
want several files to contribute to a shared structure.

A spread starts from another record's visible fields. Inside an ordinary
record block, put defaults first and explicit overrides afterward:

```gcsl
let defaults = {host = "localhost"; port = 80}
let config = {
    ...defaults
    port = 8080
}
config.port
```

A spread copies only fields visible through its operand's static type.
It cannot replace an earlier explicit field inside an ordinary block.
Top-level declarations are resolved across the whole input and take
precedence over a spread of the same name regardless of textual order.

## Unions and narrowing

A union, such as `Int | String`, allows more than one shape. Use `is` to
test a value and `as` for a checked conversion that fails at runtime if
the value doesn't fit. In `if name is Type`, the branches see narrowed
copies of the named value. This does not perform general flow analysis of
later statements or dotted field paths.

Typed equality `==` compares operands of the same static type. Total
equality `===` compares complete runtime records, including fields hidden by
their shared static type. Both require the same static operand type. The
language's
restrictions on unions, functions, and futures are described in
`gcsl(5)` and [Inference Limits](/gcsl/language/inference-limits.md).

---

# Functions and Effects

_GCSL / The Language_

> Choose pure, impure, or memoized functions and understand captures.

A function's signature says what it accepts, what it returns, and whether
calling it can perform effects. This makes executable configuration
reviewable: a pure calculation cannot silently run a process or read a
file.

## Choosing a function form

Use `fn` for a private function and `def` for a function exposed as a
field. Both forms declare parameter and result types. A function
expression can also be assigned to a variable or passed to another
function.

The marker before the result type selects the effect:

| Marker | Meaning |
|---|---|
| `:` | Pure computation; no effects or awaiting |
| `->` | Impure computation; effects and awaiting are allowed |
| `->>` | Impure computation memoized by its arguments |

This private pure function accepts a named argument and a default:

```gcsl
fn scale(value: Int, factor: Int = 2): Int { value * factor }
scale(value = 21)
```

Positional and named arguments are evaluated in source order. A trailing
block supplies the last parameter, which is useful for functions that
accept a configuration record.

A default can be any expression. It can use the parameters before it and
anything visible where the function is written:

```gcsl
let suffix = ".o"
fn object(source: String, output: String = "{source}{suffix}"): String {
    output
}
main = object("main.c")
lib = object("lib.c", output = "lib.a")
```

A default is evaluated each time a call leaves its parameter out, after
the arguments that are written and before the function's body runs. It
has the function's effect, so a pure function's default cannot call an
impure function. A default cannot use its own parameter or a later one.
Only a call by the function's own name uses its defaults. A call through
a copy, such as `g` after `let g = object`, or through a parameter must
supply every argument.

After a named argument, a name on its own is shorthand for passing the
variable of that name to the parameter of that name. These two calls are
the same:

```gcsl
fn build(source: String, output: String, compiler: String): String {
    "{compiler} {source} -o {output}"
}
let compiler = "cc"
short = build("main.c", output = "main.o", compiler)
long = build("main.c", output = "main.o", compiler = compiler)
```

Before any named argument, a name on its own is an ordinary positional
argument.

## Rest parameters

A rest parameter, written `...name: T`, takes every positional argument
from its place on, and the body sees it as a `List<T>`. Parameters after it
are given by name. A spread argument, `...list`, passes a list's elements
to it, among single arguments:

```gcsl
fn command(program: String, ...words: String, quiet: Bool = false): String {
    let all = join([program, ...words], " ")
    if quiet { "{all} >/dev/null" } else { all }
}
let flags = ["-O2", "-Wall"]
plain = command("cc")
compile = command("cc", "-c", ...flags, "main.c")
silent = command("make", "install", quiet = true)
```

A function has at most one rest parameter, and it has no default: given
nothing, it is the empty list. Its arguments are written together, so that
they run in the order they are written. A function type shows its rest
parameter too, `fn(...words: String): Int`, and only a function with a rest
parameter in the same place fits it.

## Generic functions

A function can work on values of any type. Name its type parameters in
angle brackets after its name, and use them as types in its signature and
body:

```gcsl
fn first<T>(items: List<T>, fallback: T): T {
    if len(items) > 0 { items[0] } else { fallback }
}
port = first([8080, 9090], 80)
name = first([], "none")
```

Each call works out the type parameters from its arguments: here `T` is
`Int` in the first call and `String` in the second. Inside the function, a
value of type `T` can be passed on, returned, or put in a list or record,
but nothing else, because `T` could be anything. A call where nothing binds
a type parameter, such as one that only returns a `List<T>`, is an error.

## Methods

A method is a function you call on a value with a dot. Write its
receiver in parentheses before its name:

```gcsl
fn (n: Int) twice(): Int { n * 2 }
fn (items: List<T>) first_or<T>(fallback: T): T {
    if len(items) > 0 { items[0] } else { fallback }
}
doubled = 21.twice()
port = [8080].first_or(80)
```

The value before the dot is the receiver. GCSL chooses the method by
the receiver's type, so methods with the same name can serve different
types. When more than one fits, the one for the more specific type is
used: a method for `List<Int>` is chosen over one for `List<T>` when
the receiver is a `List<Int>`. A method's other parameters, defaults, and
effects work as a function's do.

A method has no name of its own: `twice` alone is not a variable, and
`x.twice` without parentheses reads a field. A record field and a method
with the same name are an error when both could apply.

Methods are declared at the top level of a file. A `fn` method is
visible only in its own file. A `def` method is also visible to the
other files of its directory and the directories below it, and to every
file that imports its module, whatever the form of the import. In the
REPL, methods are visible to later lines.

### Methods of strings and lists

The standard functions on strings and lists are also methods, so an
editor offers them after a `.`:

```gcsl
words = "a b  c".fields()
padded = " name ".trim()
has_space = "hello world".contains(" ")
csv = ["a", "b"].join(",")
distinct = [3, 1, 3, 2].unique()
count = [1, 2, 3].len()
found = [1, 2, 3].contains(2)
```

Strings have `split`, `starts_with`, `ends_with`, `trim`, `strip_prefix`,
`strip_suffix`, `lines`, `fields`, `contains`, and `compare_version`.
Lists of strings have `join` and `sort_versions`, and every list has
`len`, `unique` and `contains`. `unique` keeps the first of each group of
equal elements, in order, and `contains` tells whether any element equals
the value given. Both compare as `===` does: whole values, with every
field a record has, and secrets by identity. They can't compare functions
or unawaited `lazy` values, so a list whose elements hold either makes
them fail.

A method you declare takes the place of a standard one that would apply
to the same receiver, as your own names take the place of the
prelude's.

## Calling for effects

A call to an impure or memoized function can stand alone as a statement,
outside a pure function, to run it for its effects. Its value is
discarded, whatever it is, and anything it defers is awaited first, so no
effect is lost:

```gcsl
fn build(source: String) -> String {
    sh("make -C {source}")
    sh("make -C {source} install")
    = source
}
```

Any other value standing alone is an error, because discarding it would
do nothing: a pure expression has no effects to keep. Make it the block's
result with `= ...`, bind it with `let`, or remove it.

## Captures and recursion

Closures hold copies of the values they capture. Rebinding a variable
later doesn't change an existing closure. An inner function cannot rebind
an outer function's variable.

Top-level named functions are available regardless of textual order and
can refer to each other within the file. Workspace files still need an
acyclic dependency order: functions in two files cannot make those files
need each other. Put mutually dependent definitions together or extract
their shared dependencies.

## Memoization

A memoized function reuses a successful result for the same arguments in
the same execution context. The cache belongs to the closure, so two
closures created from one function expression have separate entries.
Memoization also accounts for supported ambient inputs such as a caller
path when the function reads it.

This is not a persistent build cache. External changes to files or a
command's environment do not invalidate a stored result. Use `->>` only
when reusing the first result within that run is correct. Cached keys and
results consume memory for the lifetime of their execution context.

Read [Deferred Work](/gcsl/language/deferred-work.md) before using futures in function
signatures; a bare type's present-or-future meaning depends on its
position and the function's effect.

---

# Attributes

_GCSL / The Language_

> Tell the program that runs a function how to run it.

An attribute goes before a function and says how to run it, for example
whether a build step can be cached or how long it can take. GCSL checks
every attribute. Most are read by the tool that runs the program, such as
a build system, and GCSL itself acts on its own three, `retry`, `timeout`
and `track_caller`. The prelude declares two for builds: `hermetic`,
which lets a build tool such as pekit run a function's calls as cached
steps, and `scratch`, which gives such a step a directory kept between its
runs. Plain GCSL runs those calls at once, as any call.

```gcsl
#[hermetic]
fn compile(source: String) -> String { "compiled {source}" }

#[hermetic(false)] #[timeout(10m)]
fn deploy(target: String) -> String { "deployed {target}" }

result = deploy(compile("main.c"))
```

## Declaring an attribute

An attribute's arguments form a record, so you declare an attribute as a
record type marked `#[attribute]`. Each field is an argument, and a field
with a default is an argument you can leave out:

```gcsl
#[attribute] type device = {name: String, count: Int = 1}

#[device(name = "kvm")]
fn boot() -> String { "booted" }

booted = boot()
```

Arguments must be constants: literals, or lists and records of them. A
field can be an `Int`, `Float`, `Bool`, `String`, `Duration` or `Size`, or
a list or record of those. An attribute is declared, imported and named in
the same way as any other type, so a tool usually provides its attributes
in a module that you import.

## Using an attribute

Write `#[NAME]`, or `#[NAME(ARGUMENTS)]`, on the line before a function: a
`fn`, a `def`, or a definition made with a definition type. An attribute
with one field can take its argument by position, as in `#[timeout(10m)]`;
one with more fields takes its arguments by name. A misspelt attribute is
an error, so a mistake isn't silently ignored.

GCSL provides three attributes of its own:

| Attribute | Argument | Meaning |
|---|---|---|
| `#[retry(times)]` | `times: Int` | If the call fails, run it again, up to this many more times. |
| `#[timeout(limit)]` | `limit: Duration` | Fail the call if it runs for longer than this. |
| `#[track_caller]` | none | Report an error raised in the function's body at its call. |

A retried call runs its whole body again with the same arguments, so any
effects it has happen again: use `retry` only where that's safe. Retrying a
pure function can't change its result, so GCSL warns about it. When a call
times out, a program it's running is stopped. A function's own timeout
counts as a failure that its `retry` can retry, and each attempt gets the
full time. A timeout of an enclosing call is never retried by a call inside
it.

```gcsl
#[retry(2)] #[timeout(30s)]
fn fetch(url: String) -> String { exec(["echo", "fetched {url}"]).stdout }

page = fetch("https://example.com")
```

### Reporting errors at the call

A library function that checks its arguments, or wraps a command, fails
inside the library, where the reader of the error can do nothing about it.
Mark it `#[track_caller]`, and an error raised in its body is reported at
the call instead:

```gcsl
#[track_caller]
fn positive(n: Int): Int {
    if n <= 0 { panic("expected a positive number, got {n}") }
    n
}

size = positive(4)
```

A call of `positive(0)` would fail at that call, not at the `panic`. The
standard library marks `exec`, `exec_live`, `sh`, `sh_live`, and the
methods of `File`, `Dir` and `Sandbox` this way.

Only errors raised in the marked function's own body move. When it calls
another marked function, that call's error moves to the call in the body,
and then on to the outer call. An error from a function it calls that
isn't marked, or from a function value it was given, stays where it was
raised. A `fn` written inside the marked body counts as part of it.

You don't need the attribute for an error that leaves a library, or the
standard library, into your own code: that is always reported at your
call into it, with the line where it was raised shown beneath, marked
"failed here, in library code". This holds however deep in libraries the
error was raised, for a library's parameter defaults, and for a build
step a library makes that fails later. A function of your own that a
library calls back, and that fails, is reported where it failed.

## Attributes on a definition type

Attributes on a definition type apply to every definition made with it.
A definition's own attribute of the same name replaces the definition
type's:

```gcsl
#[attribute] type cached = {on: Bool = true}

#[def_type] #[cached]
def check(name: String, f: fn(): Bool): fn(): Bool { f }

def check fast() { true }
#[cached(false)] def check online() { true }

results = [(check fast)()(), (check online)()()]
```

Here `fast` is cached and `online` is not.

A deferring attribute (below) on a definition type works the same way:
it defers each definition, not the definition type itself. The
definition type's body calls the definition, and a host can run that call
as a step, while the body stays outside it. So the body can await the
step's result and recover its failure.

## Attributes that defer calls

A host such as pekit can run some calls as separate steps, possibly in
parallel or from a cache, and give their results later. An attribute that
asks for that is declared with `#[defers]` as well as `#[attribute]`, as
the prelude declares `hermetic`, `#[attribute] #[defers] type hermetic =
{on: Bool = true}`:

```gcsl
#[hermetic]
fn compile(source: String) -> String { "{source}.o" }

fn link(objects: List<String>): String { "app from {len(objects)} objects" }

app = link([compile("main.c"), compile("util.c")])
```

A call of a function with a deferring attribute can give a future instead
of its value. GCSL waits for it wherever the value is used, so nothing
about the code changes: plain GCSL runs each call at once, and under a host
that defers it, only code that uses the result waits. The function's type
shows it: `compile` is a `fn(source: String) -> String | Future<String>`.

Only an impure function can defer, and its result type must be able to be
a future, so `Present<String>` isn't allowed. For a definition type that
defers, its invocations are the deferred calls: a definition keeps the
definition type's function type.

---

# Context

_GCSL / The Language_

> Pass settings such as the target platform through every call without threading them by hand.

Some values matter deep inside a program without every function in
between caring about them: the platform you are building for, for
example, or the toolchains available. A *context* is a named value of
that kind. You declare it once, read it with `^`, and set it for a call
and everything that call does with `with`:

```gcsl
context arch: String = "x86_64"

fn compiler(): String { "gcc-{^arch}" }
fn build(): String { "built with {compiler()}" }

native = build()
cross = build() with { arch = "aarch64" }
```

`build` never mentions `arch`, yet `cross` is built with `gcc-aarch64`:
the `with` reaches every call made inside it.

## Declaring a context

`context NAME: TYPE = DEFAULT` declares a context and its default, at the
top level of a file. Every file of the workspace can read it without an
import, so a name is declared only once. A context can leave out its
default, `context toolchains: List<Toolchain>`; reading it then needs a
`with` that sets it (see [What a function needs](#what-a-function-needs)).

A default is an expression, and it is evaluated where the context is
read, in the context of the read. So one context can default to another,
and follow it:

```gcsl
context exec_cpu: String = "x86_64"
context target_cpu: String = ^exec_cpu

target = ^target_cpu with { exec_cpu = "aarch64" }
```

## The platform contexts

The prelude declares two contexts for building, which every file can read:

- `host_platform` is where build steps run: in plain GCSL, the machine
  you run it on. A build tool such as pekit sets it to where it runs them.
- `platform` is what you're building for. Its default is
  `host_platform`.

Both are a `Platform`, `{arch: String, os: String}`, named as Rust names
them, such as `{arch = "x86_64"; os = "linux"}`:

```gcsl
fn triple(): String { "{^platform.arch}-{^platform.os}" }

native = triple()
arm = triple() with { platform.arch = "aarch64" }
```

A default must be pure: it can't call an impure function. To use a value
that needs one, compute it first and bind it with `with`.

## Setting a context with `with`

`EXPR with { NAME = VALUE }` evaluates `EXPR` with the context `NAME`
set to `VALUE`. It applies to the call or field access immediately before it,
so `a + f() with {...}` sets the context for `f()` alone. It must be on
the line where the expression ends. To set a context for several
statements, use the block form, `with { NAME = VALUE } { ... }`.

A dotted name sets one field of a record context and keeps the others:

```gcsl
type Board = {cpu: String, ram: Int}
context board: Board = {cpu = "x86_64"; ram = 8}

fn describe(): String { "{^board.cpu} with {^board.ram} GiB" }
small = describe() with { board.ram = 1 }
```

`with { arch }` is short for `with { arch = arch }`, setting the context
from a variable of the same name.

## Reading a context in a parameter

A parameter written `^NAME` takes its default from the context of that
name, so a caller can still pass a value explicitly. `fn f(^arch)` is the
same as `fn f(arch: String = ^arch)`, with the type taken from the
context's declaration:

```gcsl
context arch: String = "x86_64"
fn compiler(^arch): String { "gcc-{arch}" }

usual = compiler()
explicit = compiler(arch = "mips")
```

## What a function needs

A function that reads a context with no default, with no `with` of its
own around the read, *needs* that context: whoever calls it must set it.
GCSL works this out for you, through every function in between, and
checks each call before the program runs:

```gcsl
context arch: String

fn compiler(): String { "gcc-{^arch}" }
fn build(): String { "built with {compiler()}" }

cross = build() with { arch = "aarch64" }
```

Here `build` needs `arch` because `compiler` does. Calling `build()`
where no `with` sets `arch` is an error: "context `arch` has no value
here". A `with` inside a function sets the context for what it calls, so
that function needs nothing.

A function's type shows what it needs after its parameters:
`compiler` is a `fn(^arch): String`. A function passed as a value keeps
its needs, so calling it needs them too. A function type you write needs
only the contexts you write in it, in the same form, after its
parameters. So a function that needs a context can be passed where its
type says so, and calling it there needs the context in turn:

```gcsl
context arch: String

fn twice(f: fn(String, ^arch): String): String { "{f("a")} {f("b")}" }
fn tagged(name: String): String { "{name}-{^arch}" }
both = twice(tagged) with { arch = "x86_64" }
```

`twice` needs `arch` because it calls `f`, so the call of `twice` sets
it. Where a function type doesn't name a context, a function that needs
one can't be passed. Set the context inside the function instead:

```gcsl
context arch: String

fn twice(f: fn(): String): String { "{f()} {f()}" }
both = twice(fn(): String { ^arch with { arch = "x86_64" } })
```

Name only contexts with no default: one with a default needs nothing.
A function that reads a context through another's default, `fn(^host |
^target)`, fits a type that names the context with no default,
`fn(^host)`. A declared `type` can't name a need yet, since a declared
type is resolved in each file that uses it: write the function type
where you use it.

A context with a default needs nothing, but its default can read another
context that has none. Then the function needs that one, unless the
caller sets the context with the default, which is then never evaluated.
Its type shows both: `fn(^host | ^target): String`.

What a call needs is what runs where it is called. A `^NAME` parameter's
default is evaluated by the caller, so `fn compiler(^arch)` needs
nothing itself: `compiler()` needs `arch`, and `compiler(arch = "mips")`
doesn't. A `with` around where a function is written doesn't count,
because the function runs in the context of each call. A `lazy` is the
other way round: it needs what its body needs where it is made.

A definition is called by its def-type, which sets no context, so a
definition needs only what its def-type's function parameter names:
with `def script(name: String, f: fn(^session) -> {}) -> {}`, a script
can read `^session` and call other scripts, and anything that calls a
script needs `session` too. A definition of a def-type whose parameter
names nothing, such as `build`, can't need a context, so a build can't
call a script. A function used inside its own recursion
before GCSL knows what it needs, from a function nested in it or as a
value, is an error if it turns out to need a context there. Call it
directly, or set the context around the call.

## Context and deferred work

A `lazy` keeps the context it was made in. Wherever it is later
awaited, it reads the values that were set where it was written. A
top-level field is computed when its file runs, so it reads the default
values.

Memoised functions stay correct: a memoised call's result is reused only
for a call made in a context that gives every context the call read the
same value.

---

# Toolchains

_GCSL / The Language_

> Ask for a compiler or another tool the same way under any host.

A library that compiles code needs a compiler, and which one depends on
where it runs and what it builds for. The `toolchain` module lets a
library ask for a tool without knowing who answers: plain GCSL answers
with the tools on your `PATH`, and a build tool such as pekit with the
toolchains your workspace registers.

```text
import toolchain
import Toolchain from toolchain

def compile(src: File, cchain: toolchain.CToolchain = toolchain.get(Toolchain::C)) -> File {
    cchain.cc.exec("-c", src.path, "-o", "out.o")
    = file("out.o")
}
```

`toolchain.get(Toolchain::C)` gives the first registered C toolchain that
runs on `^host_platform` and builds for `^platform` (see
~gcsl/context). Resolving it in a parameter default means the toolchain
is an ordinary argument, so a build tool can give it to a step like any
other input.

## Kinds of toolchain

Every kind is a variant of the extensible enum `Toolchain`, whose layout
holds only files and directories. `Toolchain::C`'s layout is a
`CToolchain`:

| Field | What it is |
| --- | --- |
| `root` | the whole install, which its tools need beside them |
| `runtime` | the root its tools run on: `/` for the host's own |
| `cc`, `ar`, `ld` | the compiler, the archiver, and the linker |
| `sysroot` | the headers and libraries it builds against |

A new kind is one line, such as
`enum Toolchain::Python<{root: Dir, python: File}>`.

## Registering a toolchain

A toolchain is a definition of the kind it provides, with the platforms
it runs on and builds for. Each platform is partial: a field it leaves
out matches anything.

```text
def Toolchain::C gcc_x86_64() {
    let files = archive.unpack(fetch("https://example.org/gcc.tar.xz", sha256 = "..."))
    host_platform = {arch = "x86_64"}
    platform = {arch = "x86_64"}
    provides = {
        root = files
        runtime = files.dir("sysroot")
        cc = files.file("bin/gcc")
        ar = files.file("bin/ar")
        ld = files.file("bin/ld")
        sysroot = files.dir("sysroot")
    }
}
```

The context `toolchains` lists the registered toolchains in order, and
the first that fits wins. In plain GCSL it holds only `system_c`, the
host's own C compiler found with `which`. It runs on the host and builds
for the host alone, so a build for another platform needs a toolchain
registered for that platform. Set it with `with` to choose others:

```text
let app = build_app() with { toolchains = [Toolchain::C gcc_x86_64] }
```

A registered toolchain's body runs once, when a `get` of its kind first
reaches it. A `get` of another kind passes over it without running it,
so a toolchain built with another can be registered in any order: a
tool compiled with the Rust toolchain doesn't make every `get` of the
Rust toolchain wait on itself. When nothing fits, `get` fails, naming
the kind and both platforms.

`get` runs a toolchain's body with the context `making_tool` set to
`true`. What the body fetches, a compiler's archive or the source of a
tool it builds, is then a tool, which a build tool collecting a package's
corresponding source leaves out (see
[Fetching](/gcsl/working-with-files/file-and-process-effects.md#fetching)).

---

# Failure

_GCSL / The Language_

> Check what must hold with assert, and handle a failure with recover.

A program fails when it hits a runtime error: a `panic`, an index out of
range, a program it runs exiting with an error, or a failed `assert`.
Normally that ends the run. Two constructs work with failure directly:
`assert`, which fails on purpose when something doesn't hold, and
`recover`, which catches a failure and continues.

## Asserting

`assert COND` fails the run if the condition is false. The error shows
the condition as you wrote it, and for a comparison it labels each side
with its value, so a failed check explains itself:

```text
error: assertion failed: `output == "hello"`
 --> app.gcsl:2:8
  |
2 | assert output == "hello"
  |        ------    ------- this is `"hello"`
  |        |
  |        this is `"hullo"`
```

Give your own message after a comma, `assert ok, "the server did not
start"`. Each side of a comparison is evaluated only once, so an
assertion about a program's output doesn't run the program twice.

## Recovering

`recover { BODY } else { FALLBACK }` evaluates the body, and if it fails,
evaluates the fallback instead. Name the failure to read its message:

```gcsl
fn half(n: Int): Int {
    assert n % 2 == 0, "{n} is odd"
    n // 2
}

even = recover { half(10) } else { 0 }
odd = recover { half(7) } else { -1 }
message = recover { "half is {half(7)}" } else (failure) { failure.message }
```

The failure is a record, `{message: String, notes: List<String>}`. The
notes add detail to the message. A program that fails, for example, notes
its standard output and standard error. The two blocks join as an `if`'s
branches do, so they normally have one type.

`recover` catches what `#[retry]` would retry, and nothing else. A bug in
GCSL itself is never caught. Neither is a timeout of a call that encloses
the `recover`: that timeout belongs to the enclosing call, which ends as
if the `recover` weren't there. A `break`, `continue` or `return` inside
the body is not a failure, and leaves through it as usual. Anything the
body did before it failed stays done.

---

# Secrets

_GCSL / The Language_

> Keep a password or token from leaking with Secret<T>.

A secret is a value that never leaks: a password, a token, or a key. Its
type is `Secret<T>`, and wherever it's shown, it's `***`. Make one with
`secret`, giving the value and an identity, a public name for it:

```gcsl
let password = secret("hunter2", "database password")
let user = "admin"

shown = "{password}"
login = "{user}:{password}"
```

Here `shown` and `login` are both secrets too, and are shown as `***`.

## What a secret is computed into

Anything computed from a secret is a secret. That covers `+` and the
other operators, interpolating it into a string, reading a field of a
secret record and indexing a secret list. A comparison is too:
`password == "hunter2"` is a `Secret<Bool>`, not a `Bool`, since its
answer would tell you about the password. The same goes for comparing
any values that hold a secret, such as two records with a secret field.

A secret computed from others is identified by how it was computed: the
operation, the identities of the secrets it used, and the plain values it
used, which aren't secret. `login` above is identified as
`interp("admin", ":", $(database password))`, so equal computations have
equal identities and different ones different.

Give each secret an identity of its own. Where GCSL compares values
without making the result a secret, it compares secrets by identity
alone. That covers `===`, which compares even fields a value's type
doesn't name, and the arguments of a memoised call. Two secrets with one
identity are one secret to them, whatever their values, so neither can
tell anything about a value.

## Secrets from a keychain

A build shouldn't hold its secrets in its source. The `keychain` module
gives them by name instead, and the same build file works wherever the
secret is kept:

```text
import keychain

let token = keychain.string("api-token")
let key = keychain.file("module-signing")
```

`keychain.string` gives a `Secret<String>` and `keychain.file` a
`Secret<File>`. Each looks in the keychain's configuration first: the
context `keychain_keys`, a list of entries naming a secret, the profile
it's for, and the file that holds it. A relative path is relative to the
workspace's root:

```text
let key = keychain.file("module-signing") with {
    keychain_keys = [{profile = "dev"; name = "module-signing"; file = "keys/test.pem"}]
}
```

The profile is the context `keychain_profile`, `dev` unless something
sets it, so a release build can use other keys than a developer's. A
string from a file is the file's contents, without a newline at the end.

With nothing configured, a secret comes from the environment: a file from
the path in `$GCSL_SECRET_FILE_<NAME>`, and a string from that file or
the value of `$GCSL_SECRET_<NAME>`. `<NAME>` is the secret's name in
capitals, with `_` for each character that isn't a letter or a digit, so
`api-token` is `$GCSL_SECRET_API_TOKEN`. A secret found in none of these
fails, naming the variable to set.

A keychain's secret is identified by its profile and name, `dev/api-token`,
unless the program running GCSL identifies it otherwise. A build tool
such as pekit adds a keyed hash of the secret's contents, so that a
changed key never reuses what was made with the old one.

## A secret decides nothing

What a program does never depends on a secret, because whoever can see
what ran would learn something about it. So a secret can't be the
condition of an `if`, the condition of an `assert` or an operand of
`and` and `or`. You can't test it with `is` or `as`, or loop over it with
`for`. A secret isn't its value either: you can't pass a `Secret<String>`
where a `String` is expected.

If an operation on a secret fails, the error says only that "an
operation on a secret failed", and where. Such a failure might depend on
the secret, so `recover` doesn't catch it and `#[retry]` doesn't retry
it. A failure of anything else in the expression is unchanged: in
`password + panic("boom")`, the `panic` fails as it always does.

## Giving a secret to a program

A program that needs a secret gets it with `exec_secret`, as an
environment variable. Reveal the secret with `.reveal()`, which turns a
`Secret<T>` into a `Revealed<T>`, and pass it in `secrets`:

```gcsl
let token = secret("abc123", "api token")

# `test -n` exits 0 if the variable it is given isn't empty.
let run = exec_secret(["sh", "-c", "test -n \"$TOKEN\""], secrets = {TOKEN = token.reveal()})
status = run.status
```

The program receives the value. Everything it reports is a secret,
because the program might tell of what it was given: `run` is a
`Secret<{status: Int, stdout: String, stderr: String}>`, so `run.status`
and `run.stdout` are secrets too. Files the program writes aren't secrets;
a key that signs a file doesn't make the signed file secret.

A secret is never an argument of the command. Any user on the machine
can read a running program's arguments, so `exec` refuses a revealed
secret anywhere in its arguments or its `env`, and points you to
`exec_secret`. Its arguments and the names of its variables are public.

`exec_secret` fails, as `exec` does, when the program exits with a status
other than 0, unless you pass `panic = false`. The error says only that "a
program given a secret failed", without the status or the output. Unlike
other failures involving a secret, `recover` can catch it and `#[retry]`
can retry it: it tells only that the program failed. `exec_secret` doesn't
copy output as it arrives, or give the program the terminal, since either
would show the output.

A revealed secret is contagious too: `"--token={token.reveal()}"` is a
`Revealed<String>`, while mixing in a secret that isn't revealed gives a
plain `Secret`, which `secrets` refuses. Only `exec_secret` takes a
revealed secret, so searching for `.reveal()` finds every program that
ever receives one.

The result of a run is identified by everything the program was given:
its arguments, its options and the identities of its secrets. Two runs of
one command with the same secrets are one secret wherever secrets compare
by identity, even if their outputs differ.

## What secrets protect against

Secrets keep a value from leaking by accident: into a log, an error
message, a cache key, a build record or the output of a command. They
don't protect a secret from the code that uses it. Anyone who can change
a build file can take the value with `.unsafe_value()`, or give it to a
program that writes it somewhere. Review where `.reveal()` and
`.unsafe_value()` are used, as you'd review any code that handles
credentials.

GCSL makes no promise about timing. How long an operation on a secret
takes can depend on its value, but the code that could measure that can
already read the value directly.

## Taking the value

When you really do need the value inside GCSL, take it with
`.unsafe_value()`:

```gcsl
let token = secret("abc123", "api token")

header = "Authorization: Bearer {token.unsafe_value()}"
```

`header` is a plain `String`, and is shown in full. Use it only when
nothing else will do, and nowhere it might be shown. To give a secret to a
program, reveal it instead.

---

# Deferred Work

_GCSL / The Language_

> Delay effects with lazy expressions and resolve them with await.

A future represents a calculation whose result is needed later. `lazy`
creates that calculation without running it. Awaiting it evaluates the
body and remembers the successful result. Futures are deferred work, not
concurrent tasks.

This program creates one future and then reads its result:

```gcsl
let answer = lazy 21 * 2
await answer
```

## Where work happens

A `lazy` body is an impure context, even when a pure function creates it.
That lets a pure function plan effects without performing them. A pure
function cannot await a future. Resolve the value in an impure caller
before passing it into a pure calculation that needs the value itself.

The checker inserts implicit awaits at uses that need a value's contents,
such as arithmetic or a required present argument. A spread is one of
those uses: spreading a list whose elements might be futures into a list
of present values awaits each element. It applies the same purity
restriction to explicit and implicit awaits. A call to a pure
function never secretly starts deferred work inside that function.

An implicit await of a record or a list awaits only the fields and
elements that the expected type needs present. A field typed
`T | Future<T>` keeps its future, so a list of records can collect
deferred results without waiting for any of them.

## Writing contracts

Use explicit wrappers when the distinction is part of an interface:

| Type | Contract |
|---|---|
| `Present<Int>` | A present integer, equivalent to `Int` in an ordinary annotation |
| `Future<Int>` | Deferred work yielding an integer |
| `Int | Future<Int>` | Either a present or a deferred integer |

A present value does not satisfy an explicitly required `Future<T>`.
Nested future layers collapse: awaiting a future resolves it fully.
Awaiting an already present value is a silent no-op.

Bare types in impure parameters accept present or deferred values,
including bare positions inside records and lists. Pure parameters infer
whether their bodies need the value's contents. Impure and memoized
results infer their present-or-future shape from the body. Explicit
wrappers keep the contract you wrote.

## Avoiding surprising inference

A pure function with result `Int` requires a present result, even if it
only returns its argument. It does not preserve a future's shape
polymorphically. Recursive result inference also retains conservative
parts of the declared signature. Use `Present<T>` or an explicit future
contract where an API needs a stable distinction, and consult
[Inference Limits](/gcsl/language/inference-limits.md) when an inferred type is wider
than expected.

---

# Lists and Control Flow

_GCSL / The Language_

> Build lists, repeat expressions, and leave loops or functions.

Lists hold ordered values of one element type. GCSL's loops are
expressions, so a loop can collect results into a list or run only for its
effects. This avoids a separate collection-building language.

## Lists and ranges

`List<Int>` and `Int[]` name the same type. Indexes start at zero; a
negative or out-of-range index is a runtime error. A spread inserts
another list's elements. An empty list needs an expected element type:

```gcsl
let empty: List<Int> = []
let values = [...empty, 3, 8, 5]
values[1]
```

A spread shares the other list's elements instead of copying them, so
building a list from others, such as a package's files from those of its
dependencies, costs time in proportion to what is added, not to everything
spread. Reading a list's length is immediate, and an index or an update of
one element takes time in proportion to the logarithm of its length.

`0..3` produces `[0, 1, 2]`; `0..=3` includes `3`. Bounds are integers and
ranges run upward. A range used directly as a loop's iterable is counted
without first allocating the list of all its integers.

## Collecting and repeating

A loop used as a value collects each iteration's result. A guard skips
iterations that don't match:

```gcsl
let doubled = for n in [1, 2, 3] if n > 1 { n * 2 }
doubled
```

A loop used as a statement discards its results. Use `for condition` for
repetition while a condition holds, `for { ... }` without a condition,
or `do { ... } for condition` to test after the body. A header can contain
initialization and an update:

```gcsl
let values = for let i = 0; i < 3; i := i + 1 { i * 2 }
values
```

A plain header variable can be rebound by the header. Write `let mut` if
the body must also update it.

## Leaving a computation

`break` ends the enclosing loop and `continue` skips to its next
iteration. Either can supply a value to the collecting loop before
leaving that iteration. An unlabeled `return` returns from the enclosing
function or `lazy` body.

Labels identify an outer loop or a block. A labeled `return` leaves that
target with one value; it does not append to a loop's accumulated list.
Control flow cannot jump out through a function boundary. See `gcsl(5)`
for label syntax and the distinction between collected and returned
values.

---

# Inference Limits

_GCSL / The Language_

> Recognize supported inference and use explicit types at its boundaries.

GCSL infers local values and selected present-or-future positions. It does
not infer every relationship between types. Explicit annotations help you
state an intended interface when a program reaches one of these limits.

The following boundaries affect ordinary programs:

| Boundary | What to write |
|---|---|
| An empty list has no independent element type | Give it an annotation or an expected `List<T>` type |
| A pure function does not preserve arbitrary future shapes | Write the present or future contract explicitly |
| Recursive impure results can retain a deferred possibility | Use `Present<T>` when the result must be present |
| General type parameters and intersections are unsupported | Write concrete structural types |
| There is no `None` value or optional-type shorthand | Represent alternatives using supported union members |
| Narrowing recognizes a plain name tested directly by `if` | Bind a field to a name before testing it |
| Narrowing does not establish facts after an early return | Keep uses inside the narrowed branch |
| A narrowed mutable name is a branch-local copy | Don't try to update the original through that copy |
| `len` and `show` use special call rules | Call them directly or through supported aliases, rather than storing them as ordinary function values |

Expected types reach record fields, call arguments, and other supported
literal contexts. An unrelated sibling expression is not a general
constraint-solving mechanism. For example, annotate an empty list before
combining it with independently inferred values.

Warnings do not prevent execution. A union inferred from unlike branch
results can produce a warning while the program remains valid. Use
`gcsl check` to inspect the full set of errors and warnings, and
`gcsl run --dump-types FILE` when the inferred shape is unclear.

These are supported-language boundaries, not promises about a future
inference engine. The checker implementation and its regression tests
are the source for the behavior described here.

---

# Workspaces

_GCSL / Files and Workspaces_

> Understand directory scopes, imports, and checking across files.

A GCSL workspace is a directory tree rooted at `workspace.gcsl`. Files in
one directory share public declarations. Child directories inherit the
public declarations above them, so common types and helpers can live at
the root without repeated imports.

The marker is an ordinary GCSL source file. It can be empty or declare
shared values and functions. The disk loader finds the nearest enclosing
marker when you run a file, reads the workspace, and checks every source
before executing the selected file and its dependencies.

## Public and private names

Fields, `def` functions, and declared types contribute to a directory's
public scope. `let`, `let mut`, and `fn` bindings remain private to their
file. Dotted public paths merge when they define distinct leaves; a
conflicting leaf is an error unless an earlier declaration explicitly
permits shadowing.

Sibling and child directories are not automatically in scope. Imports
name paths from the workspace root, with `/` between directories, as the
file system does. `import lib/helpers` names `lib/helpers.gcsl` or a
directory of that path. Use `as` for a local alias, or import a named
member with `from`.

A directory or file name in a path is written as it is, dots and all, so
`import pkgs/net.busybox.busybox as busybox` names the directory
`pkgs/net.busybox.busybox`. An import without `as` is named after the
path's last part, so that part must be a plain name; give a name such as
`net.busybox.busybox` one with `as`.

## Libraries

A library is a module that lives apart from any workspace, named by a
path in quotes:

```text
import "github.com/gcslib/gcc"
import compile, link from "github.com/gcslib/gcc"
```

The `gcsl` program looks for the library's directory in each directory
of `$GCSL_LIBRARY_PATH`, then in `.gcsl/libraries/` at the workspace's
root, and uses the first it finds. A library is the `.gcsl` files directly
in its directory, which share their public declarations as a workspace
directory's files do.

A library sees only its own files, the standard library, and the other
libraries it imports: never anything of the workspace that uses it. So a
library means the same in every workspace, and a name it uses can't be
picked up from yours by accident.

A library can keep other files beside its `.gcsl` files, sources to build
or tools to run. A relative path in a library is relative to its own
directory, so `file("tools/gen.py")` names the library's tool wherever
it's used.

GCSL doesn't pin the libraries a workspace imports; a host such as pekit
does. `import libraries` gives the context `pinned_libraries`, a
`Pinned` for each library the host pinned: its path, its git repository,
the directory in the repository that holds it, and the commit. A library
that takes what one of those repositories gives another way, such as a
crate from the same repository, can check that both are at one commit.

## Boundaries and evaluation order

Hidden names and nested directories containing their own `workspace.gcsl`
are excluded from an enclosing workspace's source discovery. A nested
workspace is independent, not an importable child module of the outer
workspace. Symbolic-link directory traversal is not a mechanism for
extending the source tree.

A `.gcslignore` file at the root also excludes paths from source discovery.
Use it for GCSL files that are a tool's data, such as test fixtures. Each
line names one file or directory, relative to the root. Blank lines and lines
that start with `#` have no effect, and there are no wildcards. A line that
names nothing is ignored:

```text
# Highlighting fixtures, which aren't build files.
test/highlight
```

Dependencies determine file order; path order breaks ties. A file runs
as a whole before a file that depends on it. Cyclic file dependencies are
errors, including cycles introduced through function bodies or imports.

A standalone file outside any workspace can import standard modules but
cannot import arbitrary neighboring source files. Create a workspace
marker when several files need to cooperate.

## Deliberate overrides

`#[shadowable]` marks a public declaration or import as replaceable by a
later declaration in the workspace's defined order. The implicit prelude
import is shadowable, so your own declarations can use its names.

Use this attribute for intentional defaults. It is not an escape from
all conflicts: an ordinary public leaf still cannot be defined twice.
Whole-value overrides replace the old value, while distinct dotted
leaves can merge. See `gcsl(5)` for ordering and import syntax.

---

# Organizing a Workspace

_GCSL / Files and Workspaces_

> Split shared declarations from an executable entry file.

You can share a type and helper across files by putting them in a
workspace. This example gives the entry file access to root declarations
without an import.

## Before you start

You need `gcsl` on your command search path and an empty writable directory.

## Create the workspace

1. Save these declarations as `workspace.gcsl`:

   ```gcsl
   type Component = {name: String, version: String}
   def describe(item: Component): String {
       "{item.name} {item.version}"
   }
   ```

2. Save the entry program as `main.gcsl` beside it:

   ```gcsl
   describe({name = "gcsl"; version = "0.1.0"})
   ```

3. From that directory, check the workspace and run the entry file:

   ```sh
   gcsl check
   gcsl run main.gcsl
   ```

## Check the result

The check reports `no problems in 2 files checked`. The run prints
`gcsl 0.1.0`. The helper is visible because `def` contributes to the
shared directory scope. Replacing `def` with `fn` makes it private to
`workspace.gcsl`, so the entry file cannot resolve it.

When adding a child library directory, import its public fields or
functions by its root-relative path. Keep independent projects behind
their own workspace markers rather than relying on hidden files to
separate their scopes.

---

# File and Process Effects

_GCSL / Files and Workspaces_

> Understand paths, process execution, and temporary-file lifetime.

GCSL provides standard functions for files and subprocesses. Their effects
use the host process's authority. Absolute paths and explicit command
arguments make those effects easier to inspect, but don't restrict what
a program can access.

## Locating files

Import `fileroot` to locate source directories and `path` to compose paths.
`fileroot.this` is the directory of the file containing the expression;
`fileroot.workspace` is the workspace root. `fileroot.caller` identifies
the source directory of the running function's caller.

`path.join`, `path.normalize`, `path.dirname`, and `path.basename` operate
lexically. They don't resolve symbolic links or prove that a path stays
inside a directory. Use them for path construction, not access control.

File operations under `fs` require absolute paths. The following program
writes and reads a temporary file, then removes its temporary directory
when the run ends:

```gcsl
import fs
import path
let directory = fs.temp_dir()
let file = path.join(directory, "message.txt")
fs.write(file, "GCSL")
fs.read(file)
```

Temporary directories last for the owning run, workspace, or REPL session.
Normal cleanup also runs after an evaluation error. Killing the process
can leave temporary directories behind. Atomic replacement by `fs.write`
protects readers from partial contents; it does not preserve a replaced
file's permissions or provide a durable transaction across several files.

## Running a process

`exec` accepts a list whose first element names the program. Later elements
are passed as arguments without shell interpretation. It returns a record
with the exit status and captured output. A nonzero exit status fails the
call, and the failure notes the program's standard output and standard
error. Pass `panic = false` to get the status back as data instead:

```gcsl
let probe = exec(["sh", "-c", "exit 3"], panic = false)
probe.status
```

`sh` instead executes a string through `/bin/sh` and fails the GCSL run
when the command fails. Don't insert untrusted text into that string.
Prefer `exec` when values need to become arguments rather than shell code.

`exec_live` and `sh_live` also copy child output to GCSL's standard error
as lines arrive. They still capture output in memory. Each gives the child
null standard input. A failure of any of them, such as a program that
can't start, is reported at your call, not inside the standard library.

### The environment

A command inherits GCSL's environment. The `env` option sets variables
over it, replacing any of the same name:

```gcsl
exec(["sh", "-c", "echo $GREETING"], env = {GREETING = "hello"}).stdout
```

The program named first is found through the resulting `PATH`, so setting
`PATH` in `env` also changes where it's looked for. A secret is never
passed this way: `exec_secret` gives a program secrets, and its result is a
secret too (see Secrets).

A build tool that runs commands in isolation, such as pekit, gives them an
environment of its own instead of GCSL's.

### Options

`exec` and `exec_live` take these options by name:

| Option | Default | Effect |
| --- | --- | --- |
| `cwd` | `""` | The working directory. `""` keeps the run's own; a relative path is relative to the directory of the file it's written in. |
| `env` | `{}` | Variables set over the environment, as a record of strings. |
| `panic` | `true` | A nonzero exit status fails the call, noting its standard output and standard error. When false, the status is data. |
| `until` | `""` | When set, the program is stopped at the first line of output containing this text. |
| `interactive` | `false` | When true, the program uses GCSL's terminal, and nothing is captured. |

`until` suits a program that keeps running once it's ready, such as a
server or an emulator. The result holds the output read so far, and its
status is 0 because the condition was met. A line counts as soon as the
text is written, before its newline, so a prompt that waits on the line
it asks is met. The program and anything it started are stopped
together. `until` can't be combined with
`interactive`, because an interactive program's output isn't captured.

```gcsl
let started = exec(["sh", "-c", "echo booting; echo ready; sleep 60"], until = "ready")
started.stdout
```

A source-relative `fileroot` value doesn't change a command's working
directory; pass it as `cwd` instead.

## Files

A `File` is a value that names a file. `file(path)` makes one, and nothing
is read until you ask:

```gcsl
import fs
import path
let directory = fs.temp_dir()
fs.write(path.join(directory, "notes.txt"), "remember")
let notes = file(path.join(directory, "notes.txt"))
notes.read()
```

`f.path` is the file's path, always absolute. A relative path given to
`file` or `dir` is resolved against the directory of the file it's
written in (see [Where relative paths
point](#where-relative-paths-point)). A program runs somewhere else: in
the run's working directory, which `working_dir()` names. So once a
command has written a file, find it there:

```gcsl
let tool = file("/bin/sh")
tool.exec("-c", "echo hello > greeting.txt")
working_dir().file("greeting.txt").read()
```

`f.exec(...words)` runs the file as a program, with `words` as its
arguments and the same options as `exec`. Like `exec`, it fails on a
nonzero exit status unless you pass `panic = false`.

A list of files is a `FileSet`, an alias of `List<File>`. `files.file(name)`
picks the one file whose path is `name`, or ends with `/name`, and fails if
none or several match. `FilePath` is an alias of `String`, for parameters
that take a path.

A `File` is a type of its own: a record with a `path` field isn't one, and
a `String` path is never taken for one. That lets a build tool such as
pekit find every file a step uses and produces, and move it in and out of
the step's sandbox. Under plain GCSL, two files are equal when their paths
are; a build tool can also compare their contents. Under a build tool, the
tool chooses the working directory. Pekit gives each step a directory of
its own, where its programs run and where it writes the files it makes:
`working_dir()` names it.

### Where relative paths point

A relative path is resolved against the directory of the file it's
written in, the way a name means what it means where it's written. That
covers `file`, `dir`, and a relative `cwd`, wherever the code runs and
whoever calls it. So a function in `_lib/c.gcsl` that reads `file("lib.c")`
reads `_lib/lib.c`, and a library reads its own files wherever it's used.
You don't need `fileroot.this` to name the files beside it.

A function that works on its caller's files takes them as a `File` or a
`Dir`. The caller writes the path, so it's resolved against the caller's
directory:

```text
# _lib/c.gcsl
def compile(source: File) -> File { ... }

# app/build.gcsl
def build app() { = c.compile(file("main.c")) }   # app/main.c
```

Take a `File`, not a `String`, for a path a caller gives: a `String`
turned into a file inside the function is resolved against the
function's own directory.

The standard library works for its caller: `exec`'s `cwd = "."` and
`d.exec` are the caller's directory, not the standard library's.

A program that `exec` runs with no `cwd` runs in the run's working
directory, `working_dir()`, which stays the same for the whole run. That
way, a memoised function that starts something once, such as a test
machine, is one call for every definition that uses it. Pass `cwd = "."`
to run a program in the directory of the file the call is written in
instead.

## Fetching

`fetch(url, sha256)` downloads a file and checks it against a SHA-256
digest, so it's the same file wherever and whenever it's fetched:

```text
let zlib = fetch(
    "https://zlib.net/fossils/zlib-1.3.1.tar.gz",
    sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23",
)
```

If the file behind the URL changes, its digest doesn't match the pin, and
`fetch` fails rather than give you different bytes. To find the digest in
the first place, leave it out: `fetch` downloads the file and fails with
the digest it found, ready to paste in.

Plain GCSL runs `curl` to download and `sha256sum` to check, so both must
be installed. A build tool such as pekit keeps fetched files by their
digests, and downloads each one only once.

A file can be a tool the build runs, rather than source of what it
builds: a compiler's release archive, say, or a build environment's
programs. A build tool that collects what a package was built from, its
corresponding source, leaves tools out. It's fetched and kept the same
either way.

Everything fetched while a toolchain is made counts as a tool already:
`toolchain.get` makes each registered toolchain with the context
`making_tool` set, which `fetch` reads. So a toolchain's definition needs
nothing more. Mark a tool fetched anywhere else with `tool = true`:

```text
let wheel = fetch(
    "https://files.pythonhosted.org/packages/.../libclang-18.1.1-py2.py3-none-manylinux2010_x86_64.whl",
    sha256 = "...",
    tool = true,
)
```

Mark only tools. A fetch that isn't marked, outside a toolchain, counts as
source.

A fetched file is data, never executable. To run a downloaded program,
copy it and make the copy executable with `fs.set_executable`:

```text
import fs
let tool = file("busybox")
fs.copy(fetched.path, tool.path)
fs.set_executable(tool.path, true)
```

`fs.set_executable` refuses a file with several hard links, since they
share one mode: changing it through one name would change the file
everywhere else too. That's why the example copies first.

### From a git repository

`fetch_git(url, commit)` gives the files of a git repository as one
commit has them, as a directory:

```text
let authd = fetch_git(
    "https://github.com/peios/authd.git",
    "a014fa4c74f17ce4f67ba964eefce33a1a3dbdfa",
)
```

The pin is the commit's whole name, 40 hexadecimal digits. A commit's
name is a digest of its files, so it pins them as `sha256` pins a file. A
branch or a tag can move, so `fetch_git` refuses one. The directory holds
the repository's files without its `.git` directory, and without its
submodules.

Plain GCSL runs `git` to fetch, so it must be installed. A build tool such
as pekit keeps the repositories it fetches, and fetches each commit only
once.

As with `fetch`, a repository can be a tool the build runs rather than
source of what it builds, such as the git crates of a build tool built
from source. Mark it with `tool = true`, or fetch it while a toolchain is
made, in `making_tool`, and a build tool that collects corresponding source
leaves it out.

## Unpacking archives

The `archive` module's `unpack(archive, strip)` makes a directory of what
a tar archive holds, compressed with gzip, xz, bzip2, or zstd, or not at
all, or what a zip archive holds, such as a Python wheel. It tells which
from the archive's first bytes, whatever the file is called. `strip`
leaves off the first components of each path, as
`tar --strip-components` does, which removes the single top-level
directory most source archives have:

```text
import archive
let zlib = archive.unpack(fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz",
    sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23"), strip = 1)
zlib.file("zlib.h")
```

Plain GCSL runs `tar` to unpack, or `unzip` for a zip archive. A build
tool such as pekit unpacks archives itself and keeps the result, so each
archive is unpacked once.

## Reading JSON

The `json` module's `decode(text)` reads a JSON document as a value of a
type you declare. The type comes from where the call stands, as an empty
list's element type does, so declare it there:

```gcsl
import json

type Dep = {index: Int, name: String}
type Unit = {crate: String, platform: String = "", dependencies: List<Dep>}
type Graph = {units: List<Unit>, roots: List<Int>}

# `{{` and `}}` are a string's literal braces.
let text = "{{\"units\": [{{\"crate\": \"app\", \"platform\": null, \"dependencies\": []}}], \"roots\": [0]}}"
let graph: Graph = json.decode(text)
= graph.units[0].platform == ""
```

A document usually comes from a file, as `json.decode(f.read())`, and
`json.decode(text): Graph` says the same as the `let` above. Each JSON
value becomes a value of the matching kind:

| JSON | GCSL |
|---|---|
| string | `String` |
| number | `Int` if written as an integer that fits, `Float` otherwise |
| `true`, `false` | `Bool` |
| array | a list |
| object | a record |

A record takes each of its fields from the key of the same name. A missing
key, or `null`, gives the field's default, and is an error for a field
without one. Keys the type does not name are ignored, so a type need only
describe the parts of a document you use. A union, such as
`String | List<String>`, takes whichever member matches the value's kind,
so no two of its members can be the same kind of JSON value. `Int` and
`Float` are the exception: an integer goes to the `Int`.

Some types cannot be decoded, and naming one is an error when the file is
checked: `Duration`, `Size`, `File`, `Dir`, enums, secrets, and functions.

A record with a rest-field, such as `{*: Int}`, decodes every key it
doesn't name as a field of that name, so a JSON object whose keys are
data, a map, decodes as a `{*: T}`. A `null` value is left out.

`decode` is pure. Text that is not JSON fails at the call, with the line
and column where parsing stopped. A document that does not match the type
fails with the path to the value that does not fit, such as
`units[3].dependencies[0].index` is a string, not an integer. The parser
follows RFC 8259 strictly, and rejects an object that has the same key
twice.

## Directories

A `Dir` is a tree of files: an unpacked archive, a toolchain, or what a
command leaves in a directory. `dir(path)` makes one, resolved as `file`
resolves a path. Inside it, `d.file(path)` and `d.dir(path)` name a file
and a directory by a path relative to it, and `d.files()` lists every file
in the tree:

```gcsl
import fs
import path
let root = fs.temp_dir()
fs.mkdir(path.join(root, "include"))
fs.write(path.join(root, "include/greet.h"), "void greet(void);")
let tree = dir(root)
header = tree.file("include/greet.h").read()
count = len(tree.files())
```

A path that would leave the directory, such as `d.file("../secret")`, is an
error: a directory's files are its own. `d.exec(...words)` runs a command
with the directory as its working directory.

Use a `Dir` for a tree, and a `FileSet` for loose files such as headers,
sources and objects. A `FileSet` has no root, so it can't say where each of
its files belongs in a tree.

### Composing a directory

`fs.compose_dir` makes a new directory from a record that maps paths to
what goes there:

```gcsl
import fs
import path
let root = fs.temp_dir()
fs.write(path.join(root, "main.c"), "int main(void);")
fs.write(path.join(root, "notes.txt"), "build notes")
let src = dir(root)
let stage = fs.compose_dir({
    "/" = src
    "docs/notes.txt" = src.file("notes.txt")
    "flat" = [src.file("main.c")]
})
listing = stage.exec("ls", "flat").stdout
```

A `Dir`'s tree goes under its key, `/` meaning the new directory itself; a
`File` goes at its key; and each file of a list goes under its key by its
name. Placing two things at one path is an error. Everything is copied, so
a command that writes in the new directory changes none of the originals.
Copying a large tree, such as a toolchain, takes time and space; a build
tool such as pekit mounts the trees instead.

A record's keys are written out, so they can't be computed. When a path
depends on a value, such as a package's name, use `fs.compose`, which
takes a list of entries, each with the path it goes at and what to place
there:

```gcsl
import fs
import path
let root = fs.temp_dir()
fs.write(path.join(root, "zlib.h"), "int deflate(void);")
let name = "zlib"
let stage = fs.compose([
    {at = "include/{name}.h"; place = dir(root).file("zlib.h")},
])
header = stage.file("include/zlib.h").read()
```

Its entries are placed as `fs.compose_dir` places a record's, with the
same errors.

## Sandboxes

An upstream build, such as `./configure && make`, expects its tools at the
usual places: `/bin/sh`, `/usr/bin/make`, a compiler in a fixed directory.
A sandbox runs commands with a directory you compose as their `/`, so those
paths are the ones you put there. `d.sandbox(cwd, env)` makes one from a
directory, with a working directory and an environment for its commands:

```gcsl
import fs
import path
let root = fs.temp_dir()
fs.mkdir(path.join(root, "work/src"))
fs.write(path.join(root, "work/src/config.txt"), "debug = false")
let box = dir(root).sandbox(cwd = "/work/src", env = {MODE = "release"})
config = box.file("config.txt").read()
```

`box.exec(...words)` runs a command in it, as `exec` does: `/` is the
sandbox's directory, the working directory is the sandbox's unless you
pass `cwd`, and the environment is exactly the sandbox's with the call's
`env` set over it, nothing of GCSL's. So a sandbox made with `env = {CC =
"/opt/cc/bin/cc"}` gives every command the compiler that you composed into
`/opt/cc`, never the machine's own. The program is found through that
environment's `PATH`, or `/bin` and `/usr/bin` without one.

A sandbox is live: what one command writes is there for the next, and
`box.file(path)` and `box.dir(path)` read results out, by a path that's
absolute in the sandbox or relative to its working directory. A sandbox is
a copy of its directory, so each sandbox of one directory is its own, and
none changes the directory. Its commands don't reach the network any less
than other commands do; a build tool decides that for the steps it
isolates.

Sandboxes need bubblewrap, `bwrap`. Without it, a sandbox is an error
rather than a command run against your machine's own `/`, which would find
the wrong tools.

Consult `gcsl-stdlib(3)` for exact function contracts and error behavior.

---

# Checking and Formatting Programs

_GCSL / Development Tools_

> Check types and apply the standard GCSL formatter.

You can check a GCSL program without running its effects, then format its
source consistently. The checker and formatter deliberately have different
scopes: checking needs workspace relationships; formatting only needs
source text that parses.

## Before you start

You need `gcsl` and an existing source file or workspace. Commit or save
your changes before rewriting files so you can review the formatting diff.

## Check and format

1. Check a file, including its enclosing workspace if it has one:

   ```sh
   gcsl check main.gcsl
   ```

2. Preview whether formatting would change that file:

   ```sh
   gcsl fmt --check main.gcsl
   ```

3. Apply the formatter and repeat the check:

   ```sh
   gcsl fmt main.gcsl
   gcsl fmt --check main.gcsl
   ```

## Check the result

The checker reports its summary on standard error. Warnings alone do not
make it fail. The final formatting check succeeds without listing the
file when it is already formatted.

A file with lexical or syntax errors is left untouched by the formatter;
fix those diagnostics and retry. Formatting does not require a successful
type check. It uses one language style rather than editor-specific indent
settings.

## Checking a tree

With no paths, both commands use the enclosing workspace and exclude
nested workspaces. An explicit directory makes them discover nested
workspaces too. However, `gcsl check DIRECTORY` checks workspaces, not
unattached `.gcsl` files under that directory. Pass each standalone file
explicitly when it also needs checking.

For automation, `gcsl check --message-format json main.gcsl` writes one
JSON diagnostic per line to standard output and keeps the summary on
standard error. See `gcsl(1)` for the schema and exit statuses.

---

# Configuring an Editor

_GCSL / Development Tools_

> Connect an editor to the bundled GCSL language server.

The GCSL language server supplies diagnostics and navigation from the same
checker that runs programs. You can use it in an editor that supports the
Language Server Protocol (LSP) over standard input and standard output.

## Before you start

You need the following:

- An editor with configurable LSP support.
- The `gcsl` executable on the editor's command search path.
- A GCSL file or workspace to open.

## Connect the server

1. Associate files ending in `.gcsl` with a GCSL language entry in your
   editor.
2. Set the server command to `gcsl` and its argument list to `["lsp"]`.
   Use standard input and standard output for transport.
3. Open a GCSL file. For a multifile project, open the workspace directory
   so the editor can supply file changes and watch notifications.

## Check the result

Hover over a declared name to see its type. Introduce a misspelled name and
confirm that the editor displays a diagnostic. When an unambiguous
spelling suggestion is available, a quick fix offers the replacement.

The server checks source but does not evaluate programs. It supports
completion, signature help, inlay hints, formatting, symbol search, and
references. Rename checks the proposed edits before returning them and
refuses changes that introduce errors or change name resolution. It does
not rename files, directories, or standard-library declarations.

## Incomplete source

The index retains useful information around many syntax errors. For an
unbalanced block, a query can use a repaired copy to answer navigation or
completion while diagnostics still describe the real text. Rename needs
the real source to be valid enough to verify and can be refused instead.

Editor syntax highlighting is a separate integration. The grammar and
queries in `tree-sitter-gcsl` are maintained in their own repository; they
are not required for the `gcsl lsp` process to check your code.

---

# Embedding GCSL

_GCSL / Embedding GCSL_

> Choose a language-library entry point and preserve its execution requirements.

The `gcsl` Rust crate exposes the language pipeline without requiring the
command-line program. You can evaluate one source, retain an interactive
session, or load a workspace supplied by your application.

## Choosing the boundary

The repository separates four responsibilities:

| Crate | Responsibility |
|---|---|
| `gcsl` | Syntax, types, evaluation, formatting, and semantic indexing |
| `gcsl-disk` | Finding workspace roots and reading source trees |
| `gcsl-lsp` | Editor protocol, document state, and request handling |
| `gcsl-cli` | Command arguments, terminal interaction, and output |

`gcsl::run` evaluates a `SourceFile` as a standalone program. A `Session`
retains names and values across inputs. `workspace::Workspace` evaluates
selected files after a workspace check. The lower-level lexer, parser,
checker, and index are available when you only need a particular stage.
Consult the Rust API documentation for exact signatures and ownership.

## Stack and lifetime

Run the language pipeline on a thread with at least `gcsl::STACK_SIZE`
bytes of stack, as the CLI does. Its configured size is 64 MiB. Parsing,
checking, lowering, and evaluation share documented nesting limits; a host
thread's default stack is not a substitute for the required reservation.

Keep the source collection and diagnostic input numbering together.
Standard-library files participate in the source list, so diagnostics can
point into a helper as well as into user text. The library returns
warnings with successful results instead of printing them.

A workspace or session owns memoization state and temporary directories.
Dropping it performs normal temporary-directory cleanup. Do not return a
path to such a directory and then destroy its owner before a consumer has
used it.

## Effects are host effects

The standard library is embedded in the binary. Its process and file
operations go through an effect context, `Effects`, which a host can
replace, and by default they run with the embedding process's
permissions and resources (see [Running steps for a
host](/gcsl/embedding/graph-mode.md)). The library does not impose a wall-clock limit or turn pure
checking into an execution sandbox. A host that accepts untrusted programs
needs an external isolation and resource policy.

Use `gcsl-disk` when you want the CLI's workspace-discovery behavior.
Supply sources yourself when your host has a different storage model;
keep the language's dependency and scope rules intact.

---

# Definition Types and Metadata

_GCSL / Embedding GCSL_

> Build domain-specific declarations without changing the GCSL parser.

A definition type lets a host or library describe a family of named
functions. The language checks each definition against a shared signature,
while the host can discover and invoke definitions by name. This is the
mechanism used by integrations such as Pekit.

## A family of definitions

Mark a public function with `#[def_type]`. Its first parameter receives the
definition's path as a string; its second receives the definition function.
Further parameters become invocation arguments. This example wraps a
pure string-producing definition:

```gcsl
#[def_type]
def describe(name: String, body: fn(): String): String {
    "{name}: {body()}"
}
def describe dev.peios.gcsl() { "language tools" }
result = describe dev.peios.gcsl()
```

Declaring the definition does not execute its body. Calling its reference
does. Definitions live in the definition type's namespace, separate from
ordinary values of the same path. Their public paths merge through
workspace directories and imports like other public declarations.

## Parameters of a definition's own

A definition's parameters are written by name alone: their types come
from the definition type's function parameter. After them, a definition
can declare parameters of its own, each with a type and a default, since
the definition type calls it with none:

```gcsl
#[def_type]
def describe(name: String, body: fn(): String): String {
    "{name}: {body()}"
}
def describe dev.peios.gcsl(version: String = "1.0") { "language tools {version}" }
result = describe dev.peios.gcsl()
```

The defaults are evaluated where the definition type calls the
definition, and the body is then run with what they came to. So a
deferring attribute on the definition, its own or its definition type's,
makes the body the step and gives it those values: a test that is given
its program, `def test runs(prog: File = build app())`, is a step given
the built program, and reruns only when the program changes.

## Importing every definition of a type

A definition is visible in its own directory and the directories below
it. To use many definitions from elsewhere without one import each, import
every definition of one type from a set of directories:

```text
workspace.gcsl          # declares the definition type `package`
pkgs/net.busybox.busybox/build.gcsl   # def package net.busybox.busybox()
pkgs/dev.peios.kernel/build.gcsl      # def package dev.peios.kernel()
image/build.gcsl        # import package * from pkgs/*
```

`import package * from pkgs/*` brings in every `package` definition from
each directory directly inside `pkgs/`, so `image/build.gcsl` can refer to
`package dev.peios.kernel` and `package net.busybox.busybox` by name. The
end of the path says which directories it reads:

| Path | Directories read |
| --- | --- |
| `pkgs` | `pkgs/` itself, as `import * from pkgs` would |
| `pkgs/*` | every directory directly inside `pkgs/` |
| `pkgs/**` | every directory at any depth below `pkgs/` |
| `*` or `**` | the same, below the workspace's root |

Only the definitions of that type are imported, nothing else from the
files. Hidden directories, whose names start with `.`, are skipped, and so
is everything below them. If two of the directories define the same name,
that's an error at the import, naming both definitions, so a new package
can never silently replace another. Finding no definitions at all isn't
an error.

## Definitions made with a variant

A definition type can take a variant of an [enum](/gcsl/language/records-and-types.md)
after the name, and the definition after that. Each definition then
names a variant, and each variant has its own definitions. When the
definition type is generic, the variant's payload type fills in its type
parameter, so each definition's body is checked against its own
variant's payload:

```gcsl
enum Tool extensible<{*: String}>
enum Tool::C<{cc: String}>
enum Tool::Rust<{rustc: String}>
#[def_type]
def Tool<T>(name: String, kind: Variant<Tool, T>, body: fn(): T): Tool {
    kind(body())
}
def Tool::C gcc() { cc = "gcc" }
def Tool::Rust gcc() { rustc = "rustc" }
c = Tool::C gcc()
rust = Tool::Rust gcc()
```

`Tool::C gcc` and `Tool::Rust gcc` are separate definitions. A reference
names the variant in the same way as the definition, and the definition
type receives the variant as its `kind` argument. Hosts don't invoke these
definitions by name: programs reach them through references, for example
in a list of registered toolchains.

To import such definitions, name the variant, or import every variant's:

```text
import Tool::C * from "github.com/example/tools"
import Tool::* from "github.com/example/tools"
```

The first brings in only the `Tool::C` definitions, the second every
`Tool::C`, `Tool::Rust` and any other variant's. A variant the library
declares itself, such as a `Tool::Go` of its own, comes with them, so
you can write `Tool::Go gc` after importing it. Without a variant,
`import Tool * from ...` would find nothing, so it's an error, as is a
variant for a definition type that takes none.

## Importing one definition

Name a definition in place of the `*` to import it and nothing else:

```text
import build greet from app/greet
import Tool::C gcc from "github.com/example/tools"
```

The file then sees `build greet` and `Tool::C gcc`, but no other
definition of those types from there. A path that ends in a glob imports
the definition from whichever directory defines it, and finding it in
none is an error.

## Definitions of any result

A definition type can be generic without a variant. Each definition's
body then fills in the type parameter, so definitions of one type can
give different results:

```gcsl
#[def_type]
def made<T>(name: String, f: fn(): T): {name: String, made: T} {
    name = name
    made = f()
}
def made count() { 3 }
def made label() { "three" }
n: Int = (made count)().made
s: String = (made label)().made
```

The type parameters must appear in the definition parameter's result,
`fn(): T` here, since that's the only thing that binds them.

The prelude's `build` is a definition type of this kind,
`def build<T>(name: String, f: fn() -> T) -> T`, so every file can write
`def build hello() { ... }` with no import, and give whatever it builds.
A workspace that declares its own `build` uses its own.

The prelude's `package` is one too, for packages of any format. Its body
gives a version and files, each at its path under `/usr`, placed as
`fs.compose_dir` places them, and the definition's path is the package's
name:

```text
def package dev.example.greet() {
    version = "1.0-1"
    files = {"bin/greet" = build app()}
}
```

`package dev.example.greet()` is then a `Package` record of the name, the
version, and the files, which a packager library, such as gcslib's `ppk`,
packs.

`PackageDef` and `Package` are [open
records](/gcsl/language/records-and-types.md#open-records), so a body can give any other
data, for the packager of its format:

```text
def package dev.example.greet() {
    version = "1.0-1"
    files = {"bin/greet" = build app()}
    ppk = {dependencies = {"org.gnu.glibc" = ">= 2.44"}}
}
```

`Package` keeps those fields, and a packager reads them with `is` and `as`.
A `name` in the body is replaced by the definition's path. The format's data
is checked when a packager reads it, not when the package is defined. A step
that takes a package is keyed by those fields too, so changing one packs
the package again.

The prelude's `test` is another. A test passes if its body succeeds and
fails if it fails, by an `assert`, a program exiting with an error, or
any other failure:

```gcsl
def test adds() {
    assert 1 + 1 == 2
}
result = test adds()
```

`test adds()` is a `TestResult`, `{name = "adds"; passed = true; message
= ""}`, and never itself a failure. A failing test's message holds the
failure's message, then each of its notes on a line of its own, such as a
failing program's output. `test` is `#[hermetic]`, so a build
tool such as pekit runs each test's body as a step, given what its
parameters' defaults build, and doesn't run a test that passed again for
the same inputs.

The prelude's `script` is for tasks a person runs, such as deploying or
booting what was built, whose effects change the world outside the build:

```text
def script deploy() {
    let ran = exec(["rsync", "-a", (build site()).path, "host:/srv"])
}
```

Its function parameter is `fn(^script_session) -> T`, and
`script_session` has no default, so a script can read `^script_session`
and call other scripts. Only the tool that runs a script binds the
context, for example `pekit run deploy`, so nothing a build, a test or a
package calls can call a script: that fails its check. A script builds
what it calls as any build does. `^script_session.args` holds the words
given after the script's name.

## Metadata

Function types can carry metadata with `META:`, `META->`, or `META->>`.
These distinguish pure reads, impure reads, and memoized reads. A
`defmeta` declaration supplies the metadata of a definition in its
directory. Reading a field through the function reference reads that
metadata according to its effect.

Metadata is not a separate package-format contract. The definition type
chooses its shape, and the host integration owns what those fields mean.
Use the host's documentation for package or build semantics.

## Host invocation

A checked workspace exposes definition types and their definitions. Host
APIs can invoke a selected definition with named textual arguments parsed
against its declared parameter types. When a value the host gets back holds
a reference, such as `build = build busybox`, the host can ask which
definition it names and then invoke it, or read its metadata, by name. The
host can also invoke a definition in a [context](/gcsl/language/context.md) of its
choosing, such as the platform a build step runs on, by giving each
context a value of its declared type, for example one it got back from
an earlier run. Only that invocation sees those values: what each file
computes as it runs uses the declared defaults. The
`gcsl` executable itself exposes
`run`, `check`, `fmt`, and `lsp`; it does not add a general command for each
definition type.

Keep protocol or package policy in the integration repository. Keep
language syntax, type checking, and discovery semantics in GCSL. This
separation lets other hosts use the same language without inheriting
Pekit's packaging model.

---

# Running Steps for a Host

_GCSL / Embedding GCSL_

> Evaluate a workspace as an action graph, so your host can run, cache and parallelise its steps.

A build tool wants to run independent pieces of work at the same time,
reuse results it already has, and isolate each piece. GCSL supports that
through *graph mode*: instead of running every call as it reaches it,
GCSL hands your host the calls it should run as *steps*, and carries on
with the rest of the program until it needs one of their results.

## Marking the calls that are steps

A step is a call of a function whose attribute is declared deferring,
with `#[defers]` as well as `#[attribute]`:

```gcsl
#[attribute] #[defers] type step = {}

#[step]
fn compile(source: String) -> String { "{source}.o" }

#[step]
fn link(objects: List<String>) -> String { "app from {len(objects)}" }

app = link([compile("main.c"), compile("util.c")])
```

Plain GCSL runs every call at once, so the program means the same under
any host. Under a host in graph mode, each call gives a future for its
result instead, and code waits only where it uses one. Here neither
compile waits for the other, and the link is a step whose inputs are the
two compiles' results.

## The loop a host runs

The host keeps a `Graph` for the whole evaluation and drives it:

1. Run a unit, a file with `Workspace::run_graph` or a target with
   `Workspace::prepare_call` and `Workspace::run_prepared`. You get
   `Progress::Paused(nodes)` if the unit needs results it doesn't have
   yet (see [Code that waits](#code-that-waits)),
   `Progress::Waiting(unit)` if it needs a result that another unit is
   computing (see [Units that share work](#units-that-share-work)), or
   `Progress::Done(value)` once it finishes.
2. Find what to run. `graph.holes(&value)` lists the results a finished
   value still waits for, `graph.needed(&demands)` adds every step they
   depend on, and `graph.ready(&needed)` keeps those whose own inputs are
   all known. Steps that nothing needs never run.
3. For each ready step, either give its result from your cache, or run it
   with `Workspace::evaluate`, then pass the outcome to `graph.resolve`.
4. Run the unit again. It carries on from the point where it stopped:
   nothing it did before runs again.

A target's call can set root contexts as it starts, from values you give
or from a top-level field of a file, `Workspace::prepare_call_with`. With
`Workspace::prepare_call_wrapped` it can also give the target's value to
a top-level function of a file, followed by literal arguments of your
own, as if the call were written `FUNCTION(DT PATH(), ARGS...)`. That's
how a host runs code of its own over a target without calling a function
value itself: pekit packs a package as `packaging.pack(package NAME())`.
Several prepared calls are units of their own, and can be driven together
against one graph, sharing the steps they both reach.

## Code that waits

When an iteration of a `for` loop in a function stops to wait, the rest
of the loop doesn't wait with it: the iteration is set aside, and the
next one runs. So a loop that fetches a hundred files stops once, with
all hundred fetches in `Progress::Paused(nodes)`, rather than a hundred
times. The loop's value is the same as if its iterations had run in
order, and if several fail, the earliest iteration's failure is the one
reported.

A loop is only split like this if its iterations are independent: none
assigns a variable declared outside the loop with `:=`, and none leaves
it with `break` or `return`. Any other loop runs its iterations in
order.

The same goes for the elements of a list, the pieces of a string with
`{}` in it, the arguments of a call, the statements of a block and the
fields of a record. In `link(compile(a), compile(b))`, both compiles are
met before the unit stops, and so are both reads in:

```text
let a = fs.read("a.txt")
let b = fs.read("b.txt")
```

A call's body runs, and a parameter's default is evaluated, only once
every argument before it is there. A statement that uses a variable an
earlier statement set aside declares waits for that statement first, and
a block's value waits for all of them. An element, argument or statement
is set aside only if it assigns no variable with `:=` and has no
`break`, `continue` or `return` in it.

If two parts set aside need the same memoised call or `lazy` value, it
runs once. Should a later part have begun it and then had to wait for an
earlier one, the later part gives up its run and the earlier part runs
it, as the program would in order. A run that another unit is waiting
for is never given up, so the earlier part waits for it instead (see
[Units that share work](#units-that-share-work)).

An iteration set aside can still reach effects that must happen in
program order, such as programs that write files the next one reads.
Your `Effects` says which effects it isolates, through
`Effects::isolates`: an effect you don't isolate is only made once
nothing earlier in the program is still waiting, so you still see such
effects one at a time, in program order. The exception is a run that
another unit is waiting for, described below. Once something set aside
has failed, nothing after it that you don't isolate is made at all, as
the program would have stopped at the failure. By default nothing is
isolated. Isolate an effect only if its order can't matter, such as a
fetch pinned by its digest.

## Units that share work

A unit that stops keeps everything it was doing, including the memoised
calls it is in the middle of. If another unit makes the same memoised
call with the same arguments, or awaits the same `lazy` value, it
doesn't compute it again. It stops with `Progress::Waiting(unit)`,
naming the unit that is computing it. Run that unit, or anything else
that can make progress, and then run the waiting unit again. It looks
the call up again, and finds the result once the other unit has
finished it.

A unit that waits on another never makes a node of its own for the
shared work, so the work is done once, by whichever unit reached it
first. That unit's program order doesn't govern it, though. Once another
unit is waiting for a memoised call or `lazy` value, the effects you
don't isolate inside it stop waiting for the earlier work of the unit
running it, and wait only for earlier work inside it. Otherwise that
earlier work could itself be waiting for the other unit, and the two
would wait for each other for ever. Such effects are still made one at
a time per unit. Which unit runs shared work first was already a matter
of chance, so no unit's program order could govern it.

To know whether units that wait for each other are stuck, compare
`Workspace::memo_progress` before and after a round of runs. It changes
when a memoised call or a `lazy` value's run ends, and when a unit
starts waiting for another unit's run, which lets that run go on. A unit
that waits again after its run might still have moved on what another
unit waits for, so wake the waiting units again. Units are stuck only if
a round ran nothing else and `Workspace::memo_progress` didn't change.

If you stop running a unit before it finishes, for example because you
fail its target for a reason of your own while it waits, call
`Workspace::give_up` with its unit. This is for a target's or a step's
unit, not a file's. Otherwise the memoised calls and
`lazy` values it's in the middle of stay its own, and any unit that waits
for them waits for ever. Given up, they're released, and a waiting unit
computes them itself when it runs again, making the effects inside them
again. A unit that fails is released the same way without your help.

If every unit you have is waiting on another, they are waiting on each
other: report that as an error rather than running them again. Call
`Workspace::stuck` first. If the units wait in a circle through memoised
calls or `lazy` values, some call needs its own result, and it returns
the error "this call depends on its own result", with each call in the
circle labeled. A run of the program in order would fail the same way.
It names units through a function you pass, so name them as your users
know them. It returns `None` if the circle goes through a step's result,
which only you can follow.

A step's failure is raised where its result is used, so a `recover`
around that use catches it, as with any failure. A finished value can
also hold a failed step's result that no code used. Once
`graph.holes(&value)` is empty, `graph.failures(&value)` lists those
failures so that you can report them.

Effects that aren't inside a step are steps too: in graph mode, a unit
never runs a program or touches a file itself. Each such effect becomes a
step that the unit needs at once, which keeps it in program order.

Every run in graph mode takes a `GraphHost`: which deferred calls the
host takes as steps, and the `Effects` the unit's own effects use, such
as the working directory that `file("hello.c")` resolves against.

## Running many steps at once

GCSL evaluates on one thread, but the programs steps run can run in
parallel. Run a step's body as a unit of its own with
`Workspace::run_step`: each `exec` in it becomes an effect step of that
unit, and the unit stops at it. `Workspace::effect_job` turns that effect
into an `EffectJob`, plain data you can send to a worker thread, where
`EffectJob::run` runs it under your `Effects`, with a deadline if you want
one. Give the result back with `Workspace::from_plain` and
`graph.resolve`, and run the step again; it carries on to its next
effect. One GCSL thread can drive as many running programs as you have
workers. A step's `exec`s run in the order its code makes them. A
step's own `#[retry]` and `#[timeout]` are left to you, since
you see every attempt: read them from its attributes with
`check::retry_of` and `check::timeout_of`, as GCSL itself does. To run a
failed step again from its start, call `graph.forget_unit` with its unit
first, so that its effects are made again rather than found failed.

## Keys, inputs, and isolation

`Workspace::step_inputs` gives what you need to key and stage a step:

- its arguments, its function's captured values and the context it can
  read, as plain data (`Plain`);
- its function's attributes;
- the files whose sources make up its code, which you hash to identify
  the code.

The context a step can read is every context bound where it was made
that has a default, and each without one that its function needs (see
[What a function needs](/gcsl/language/context.md#what-a-function-needs)). GCSL
works out what a function needs through every call it makes, so a step
can't read a context with no default that its function doesn't need. A
context that only your host binds for some runs, such as pekit's script
session, then doesn't change the key of a step that never reads it.

`Workspace::run_step` also gives what the step's run read of the context
it was made in: each context whose binding is the step's own, with
whether it was bound or its default read. A step keeps what it read while
it is stopped, so the reads a run that ends gives are everything the step
read, and you can key the step by the values of those contexts alone,
rather than by every context it could read. A memoised call found in its
table counts the reads it made, so a cache hit hides none. Each context
is also told to your `Effects::context_read` the first time a run reads
it, before the step does anything with it, so you can give the step that
context's files only then.

A deferred call is one node however many times, and wherever, it is
made: by its function, its arguments and the context it was made in, but
not the definition whose body made it, which a step can't read. So two
targets that make the same call share one step, and a graph records where
each unit met each node, which `Graph::met_at` gives you, for messages
about a unit's own code.

Name a step's outputs by what it is, so that they're at the same path in
every build that makes it, whatever else you build.
`Workspace::step_identity` gives the step's inputs as
`Workspace::step_inputs` does, its function among them, but a result of
another step as `Plain::Step` with that step's node, whether or not it's
been given. Name each step after the steps whose results it's given, and
you can name every step as soon as it's made, before any runs.

`Workspace::step_definition` tells you which definition made a step: the
one whose body was running where it was first made, or else the innermost
`DT PATH()` around it.

`Plain::files` lists the files and directories in a value, which is what
a sandbox needs to contain. Results go back with `Workspace::from_plain`,
and `Workspace::to_plain` refuses a result that holds a function or a
result not given yet.

`Workspace::evaluate` takes an `Effects` value, which decides how the
step's effects reach the system. `Direct` uses the system as it is. Your
own implementation can run each program in a sandbox, through
`Effects::command`, and root file paths there, through
`Effects::host_path`; GCSL's values keep the paths the code wrote.
`Effects::working_dir` is the run's working directory: where a program
given no `cwd` runs, and what `working_dir()` returns. Relative paths
don't resolve against it; they resolve against the directory of the file
they're written in. Give a library's files the directory you found it in
with `SourceFile::with_dir`, so that its relative paths point at its own
files.

If your sandboxes use bubblewrap, also implement
`Effects::sandbox_command`, which runs the commands of a GCSL
`Dir.sandbox` with the sandbox's copy as their root. Without it, GCSL
starts its own bubblewrap inside yours, which some systems, such as
Ubuntu, forbid.

Three more hooks let you avoid copying. `Effects::place_file` places each
file of an `fs.compose_dir`, a copy by default, so you can hard-link a
file nothing can change. `Effects::composed` tells you when a composition
is finished, so you can make it read-only. `Effects::make_sandbox` lets
you make a sandbox yourself, as an overlay over its directory, say; you
then answer `Effects::host_path` for paths in it, upper layer over lower.

`Effects::hides` keeps your own directories out of the code's view. A
directory it names is left out of `d.files()` and of every copy, as if it
were not there, though it can still be read by its path. Pekit uses it to
keep its outputs, `pekit-out/`, out of the workspace.

A host decides, per call, whether to take a deferred call as a step, from
the attribute's arguments. An attribute declared as
`type step = {on: Bool = true}` lets a function written `#[step(false)]`
run inline. The host must decide the same way for the same call
throughout one evaluation.

## Seeing where evaluation spends its time

Call `Workspace::start_profiling` before you run anything, and
`Workspace::profile_report` once you're done. Every run of the
workspace's code is profiled from then on: its files, its prepared calls
and its steps, through every pause. The report has a row for each
function and built-in that ran:

- `calls`, how many calls of it ran, and `found`, how many of those were
  memoised calls that found their entry;
- `own`, the time spent in its body, less the calls made inside it;
- `total`, the time of its calls including the calls inside them,
  counted once for a function that calls itself.

A call's time starts once its arguments are evaluated, so evaluating an
argument counts toward the caller. `outermost` is the time spent in
calls that no other call was running around. If you time your runs, the
difference is the time spent at the top level of the files, outside any
function. A profiled run costs a little more than one that isn't, and
nothing changes for a workspace that never starts profiling.

A target's unit carries on from where it stopped after each pause, so a
profile counts each call it makes once, however often it stops. Time a
unit spends stopped isn't counted.

When the iterations of a loop wait apart (see [Code that
waits](#code-that-waits)), each runs as a task of its own, and every
moment is counted once, to the calls of the task that was running then.
An iteration's calls keep the time they ran before it was set aside, and
the call that runs the loop doesn't count that time as its own. A call
that waits for another task's memoised call isn't charged for the wait.
The evaluator's own work in setting tasks aside and choosing which runs
next counts toward no function: it's part of the difference between
your runs' time and `outermost`.

When the same expensive work, such as
parsing a lock file, shows up thousands of times, it's being done by
that many calls: memoise the function that does it with `->>`, and
later calls find its entry instead of doing the work again.

---

# 100 The Language Pipeline

_GCSL / gcsl-internals_

> Follow source through checking and type-specialized evaluation.

GCSL is a tree-walking interpreter with a typed intermediate
representation. The stages are separate so a formatter or editor can stop
before execution while using the same syntax and type rules as the CLI.

The main pipeline is:

```text
SourceFile
    -> lexer and interned names/strings
    -> parser and arena-based syntax tree
    -> workspace resolution and type-check side tables
    -> type-specialized intermediate representation
    -> evaluation and a value with warnings
```

The lexer and parser can recover enough structure to report multiple
errors. A failed check is never lowered into executable code. Recovery
supports diagnostics and editor queries; it does not make a partially
valid program executable.

The checker resolves names and types expressions, recording captures,
slots, argument destinations, and required awaits in side tables.
Lowering makes those awaits explicit. Evaluation dispatches through
specialized operations whose types have already been checked, rather than
repeating the type system at each operation.

## 100.1 Workspace scheduling

The workspace scanner merges public field paths, resolves imports, and
orders source files by dependencies. Each public leaf has an owner and a
cell. Reading an interior record can require all its contributing owners.
A cycle is a diagnostic, not an order selected at runtime.

Top-level field scheduling differs from ordinary block order. It supports
forward references while ensuring dependencies are initialized before a
read. Shadowed declarations are still checked even when they do not
contribute a runtime value.

## 100.2 Sources

The principal implementation is in `crates/gcsl/src/`: the lexer in
`lexer.rs`, and the parser, workspace, checker, lowering and evaluator
each in a root module (`parser.rs`, `workspace.rs`, `check.rs`,
`lower.rs`, `eval.rs`) with a directory of topic modules beside it, such
as `check/records.rs` or `eval/futures.rs`. Each root documents its
internal invariants and lists its modules, and each module documents its
part. The implementation here is not the separate Tree-sitter grammar
used for highlighting.

---

# 200 Evaluation State

_GCSL / gcsl-internals_

> Understand values, futures, memo tables, and failure cleanup.

GCSL evaluation uses reference-counted values and explicit execution
contexts. A closure captures values; a frame holds the current call's
slots. This supports value semantics without exposing shared mutable
variables to programs.

## 200.1 Futures and memo tables

A future begins pending, becomes running during evaluation, and records a
successful result. Reentering running work is an error rather than an
infinite cycle through the same pending computation. A failed evaluation
does not become a cached success.

Memo tables belong to the execution context and are keyed by closure
identity and argument values, with supported ambient inputs included when
used. Keeping tables outside closures avoids introducing reference cycles
through cached keys and results. Successful entries for live closures
remain until their context ends; they are not an eviction-based cache.

## 200.2 Exits and cleanup

Runtime errors and language control flow share an unwinding path through
the evaluator. A loop handles its own `break` or `continue`; a function,
future, or labeled block handles a matching `return`. Intermediate
operations restore stack and evaluation state before propagating an exit.

A failed REPL input does not commit its new bindings or memo-table changes
to the session. Effects already performed outside the interpreter are not
rolled back. A file written or a subprocess started before an error still
requires the host's ordinary handling.

A workspace remembers the first runtime failure of each file. A later
request that needs that file receives the original diagnostic without
rerunning its effects or starting dependent files. Successful prior files
keep their values, and unrelated files can still run. Create a new
workspace object when you intentionally need to retry evaluation.

## 200.3 Resource limits

The parser's maximum expression depth is `gcsl::MAX_DEPTH`, 10,000 levels.
Runtime expressions, calls, and awaits share a nesting budget; calls cost
additional levels. Iterations reuse their body's depth rather than adding
one level per iteration. Tail calls are not eliminated.

These limits protect the recursive implementation, not total computation.
A program can still loop indefinitely, allocate large values, capture
large process output, or retain many memoized results. The embedding host
owns any execution timeout and memory limit.

The main implementation lives in `eval.rs` and the modules under `eval/`,
`value.rs`, and `session.rs`.

---

# 300 Tooling State

_GCSL / gcsl-internals_

> Understand source discovery, editor snapshots, and formatter boundaries.

GCSL tooling shares language analysis while keeping disk access and editor
protocol handling outside the core. This prevents checking and formatting
from depending on an evaluator run.

## 300.1 Source discovery

`gcsl-disk` finds workspace markers and returns a source collection with
stable path and diagnostic mappings. It excludes hidden names, nested
workspace trees, and paths the root's `.gcslignore` names when reading one
workspace. The CLI and language server
use this shared layer rather than implementing separate import rules.

A check of a directory discovers workspaces. A format of a directory
finds source files, including standalone files. Their traversal results
are therefore intentionally different.

## 300.2 Editor snapshots

`gcsl-lsp` overlays open document text on disk sources and asks a worker to
check the affected workspace. Queries use an up-to-date semantic index;
they can force a pending check before answering. Diagnostics continue to
refer to actual source even when a query temporarily repairs unmatched
braces to find usable names.

Rename computes proposed edits and checks their effect before offering
them. Standard-library, file, and directory identities are not editable
through that operation. Formatting returns edits from the language's
formatter rather than applying the editor's formatting preferences.

Only local `file:` document URIs with an empty or `localhost` authority
and an absolute decoded path map to disk files. Other URI forms are
checked as standalone documents, not treated as local workspace paths.

## 300.3 Formatter

The formatter works from tokens, comments, and parsed structure. It does
not need evaluation or successful type inference. Syntax errors prevent a
rewrite of that file. The CLI uses a temporary file and replacement so
readers don't observe a partially written formatted file.

The principal code is in `crates/gcsl-disk/src/lib.rs`,
`crates/gcsl-lsp/src/`, `crates/gcsl/src/index/`, and
`crates/gcsl/src/fmt.rs`. The CLI adapters live in
`crates/gcsl-cli/src/`.

---

# Tree-sitter Grammar

_GCSL / Tree-sitter Grammar_

> How the GCSL editor grammar provides syntax trees and editor queries.

The GCSL Tree-sitter grammar lets an editor recognize the structure of a
GCSL file as you type. It supplies syntax highlighting and the structural
information an editor can use for folding, indentation, and selections.
The grammar does not run the program or check its types.

## Parser and queries

The parser turns source into a concrete syntax tree. Named nodes identify
constructs such as a function, an import, or a string interpolation. The
tree also records punctuation and source positions so an editor can work
with incomplete text and update a changed region.

Queries attach names to selected nodes. The editor interprets those names:
for example, a function capture can select a highlight group or define a
text object. [Editor Queries](/gcsl/tree-sitter/tree-sitter-queries.md) describes the four
query files shipped with the grammar.

## Native and WebAssembly parsers

The repository builds two forms of the same parser. A native shared object
is loaded by an editor that accepts C Tree-sitter grammars. A WebAssembly
module is loaded by an editor with Tree-sitter's Wasm runtime. Both export
the language entry point `tree_sitter_gcsl` and use language ABI 15.

These artifacts are grammar plugins. They do not embed the GCSL evaluator
or a separate copy of the Tree-sitter runtime. The native parser and Wasm
parser are tested against Tree-sitter 0.27.1.

## Relationship to the language server

The GCSL compiler owns the language rules. Its language server provides
type errors, name resolution, navigation, and formatting. The Tree-sitter
grammar is a separate editor component and can work without the language
server.

The syntax tree is not the compiler's abstract syntax tree. Some node names
are similar, but their structure and meaning are not interchangeable.
The grammar deliberately accepts some text the compiler rejects and has
its own scanner limits. See
[Parser Differences](/gcsl/tree-sitter/tree-sitter-differences.md) before using it to
judge whether a program is valid.

---

# Installing GCSL Parsers

_GCSL / Tree-sitter Grammar_

> Load the native GCSL parser and queries in Neovim.

You can load the native parser directly in Neovim without a parser-manager
plugin. This procedure configures syntax highlighting and folds. It does
not configure the language server or install an indentation plugin.

## Before you start

You need the following:

- Neovim 0.11 with support for Tree-sitter language ABI 15.
- The grammar's `gcsl.so` native build for your host.
- The four files in the grammar repository's `queries/` directory.

The example uses a Linux development build. From the grammar repository,
build the native parser with pekit:

```sh
parser=$(pekit build parser | sed -n 's/^  //p')
```

The command keeps the built parser's path, which pekit prints indented
under the target name, in `parser`.

## Install the parser and queries

1. Create the runtime directories under your Neovim configuration:

   ```sh
   config="${XDG_CONFIG_HOME:-$HOME/.config}/nvim"
   mkdir -p "$config/parser" "$config/queries/gcsl"
   ```

2. Copy the parser and queries into those directories:

   ```sh
   cp "$parser" "$config/parser/gcsl.so"
   cp queries/*.scm "$config/queries/gcsl/"
   ```

3. Add the file type and highlighting setup to `init.lua`:

   ```lua
   vim.filetype.add({ extension = { gcsl = "gcsl" } })
   vim.api.nvim_create_autocmd("FileType", {
       pattern = "gcsl",
       callback = function()
           vim.treesitter.start(0, "gcsl")
           vim.wo.foldmethod = "expr"
           vim.wo.foldexpr = "v:lua.vim.treesitter.foldexpr()"
       end,
   })
   ```

## Check the result

Open a `.gcsl` file containing a function and a string interpolation. Run
`:InspectTree` to view the syntax tree. It should contain `named_function`
and `interpolation` nodes for those constructs.

Run `:Inspect` over a function name to see its highlight capture. Use `za`
on a multiline block to toggle its fold. A parser-load error usually means
the shared object was built for a different host or the editor does not
support its language ABI.

## Indentation and text objects

The indentation and text-object queries require an editor integration that
understands their capture names and predicates. Merely copying the files
does not enable those features. Configure your chosen integration using
its version's instructions; plugin APIs can differ between branches.

---

# Installing the Wasm Grammar

_GCSL / Tree-sitter Grammar_

> Assemble a GCSL language pack for clackatoo from the Wasm parser and queries.

The Wasm parser lets clackatoo recognize GCSL without loading a native
shared object into the editor. A language pack combines the parser, query
files, and a small language declaration.

## Before you start

You need a clackatoo version that supports Wasm language packs and the
grammar repository. To use the language server too, install `gcsl` on the
editor's command search path.

Build the portable parser from the grammar repository with pekit:

```sh
wasm=$(pekit build wasm | sed -n 's/^  //p')
```

The command keeps the built parser's path, which pekit prints indented
under the target name, in `wasm`.

## Create the language pack

1. Create the user language-pack directory:

   ```sh
   pack="${XDG_DATA_HOME:-$HOME/.local/share}/clackatoo/languages/gcsl"
   mkdir -p "$pack"
   ```

2. Copy the parser and supported queries:

   ```sh
   cp "$wasm" "$pack/grammar.wasm"
   cp queries/highlights.scm queries/indents.scm queries/textobjects.scm "$pack/"
   ```

3. Save this declaration as `language.toml` in that directory:

   ```toml
   grammar = "gcsl"
   extensions = ["gcsl"]
   filenames = []
   server = ["gcsl", "lsp"]
   roots = ["workspace.gcsl"]
   word = "-"
   ```

The `word` entry keeps names such as `build-root` together during word
navigation. The `server` entry starts the separate GCSL language server;
omit it if you only want grammar features. The root marker selects the
workspace for language-server requests.

## Check the result

Open a `.gcsl` file in clackatoo and check that strings and function names
are highlighted. Use a function text object to select a function. If the
language server is enabled, hover over a declaration to check that the
server starts separately from the grammar.

The pack does not include `folds.scm`: this clackatoo integration does not
consume the folding query. The same query remains available for editors
that support it.

---

# Editor Queries

_GCSL / Tree-sitter Grammar_

> The GCSL highlight, indentation, folding, and text-object query contracts.

The query files use Tree-sitter node patterns and capture names understood
by editor integrations. Keep the parser and queries from the same grammar
revision: a query referring to a missing node cannot be loaded.

The files have distinct roles:

| File | Purpose | Required editor behavior |
| --- | --- | --- |
| `highlights.scm` | Syntax colors | Map captures to highlight groups and evaluate predicates |
| `indents.scm` | Structural indentation | Interpret `indent.*` captures and `#not-has-parent?` |
| `folds.scm` | Fold ranges | Interpret `@fold` on multiline constructs |
| `textobjects.scm` | Structural selections | Combine captures in one match into an inner or outer range |

## Highlights

Top-level field names use `@variable`; fields inside bodies use
`@variable.member`. A called field uses `@function.call`, because GCSL has
function values rather than a separate method-call syntax. The final name
in a definition path uses `@function`, while preceding segments use
`@module`. Function effect markers use `@keyword.modifier`.

Editors differ in which overlapping highlight pattern wins. The queries
avoid most competing names and repeat specialized field-call patterns on
both sides of the general field pattern. This supports integrations that
choose either the first or last applicable capture.

## Indentation

Blocks, lists, argument lists, and parenthesized constructs open indentation
levels. An `if` opens a level for its branches; the branch blocks do not
open an extra level. A continued binary expression opens a hanging level
only at the outermost binary node.

The editor chooses the width of a level. GCSL's house style is four spaces.
String content and comments use `@indent.auto` so structural indentation
does not rewrite literal text. The predicate `#not-has-parent?` is an editor
extension; a generic query engine alone does not implement its behavior.

## Folds and selections

Folds cover blocks, record types, lists, functions, definitions, metas, and
runs of imports. A one-line node does not need a multiline fold.

Text objects cover functions, classes, parameters, blocks, conditionals,
loops, calls, comments, returns, assignments, and attributes. The `.inner`
capture selects the contents and `.outer` includes the surrounding
construct. Parameter outer ranges include an adjacent separator where one
is present.

The text-object query uses captures for the first and last selected nodes
rather than `#make-range!`. The editor combines those captures. It treats
a block as a record-like class only in the contexts described by the query;
it does not perform the compiler's type analysis.

---

# Parser Differences

_GCSL / Tree-sitter Grammar_

> Deliberate differences between the editor grammar and the GCSL compiler.

Use the compiler or GCSL language server to validate a program. The editor
grammar favors useful syntax trees while a file is incomplete. A successful
Tree-sitter parse does not establish that the compiler accepts the file.

## Accepted forms with additional compiler rules

The grammar accepts these broader forms:

| Area | Editor grammar behavior |
| --- | --- |
| Comparisons and ranges | Chained forms such as `a < b < c` and `a..b..c` associate left |
| Negation | A space can separate `-` from its operand |
| Paths | Shared path rules accept index segments in declarations and fields, quoted first names, and dotted mutable declarations |
| Quoted field names | Interpolation can appear where the compiler expects a plain string |
| Attributes | Attribute names and placement are not checked as strictly as by the compiler |
| Definition references | A def-type can be a field access on a computed expression |
| Definition paths | Some glued numeric and hyphenated segments are accepted more broadly |
| Loop headers | The grammar does not enforce every condition and declaration ordering rule |
| Newlines | A newline can be skipped before a token the compiler expects on the same line |
| Labels | A record-like block can carry a label |
| Escapes | Unknown escapes and a lone closing brace in string content can parse |
| Imports | Dotted members and repeated wildcard imports can parse |

These are editor parsing choices, not alternative GCSL language rules.
The compiler remains responsible for rejecting invalid source.

## Scanner boundaries

The external scanner stores at most 64 simultaneously open string literals.
Nested interpolation can reach this limit. The scanner stops opening more
literals and lets Tree-sitter recover; it does not allocate an unbounded
stack. This editor limit is separate from the compiler's depth limits.

String delimiter lengths are stored as 32-bit counts, including across
incremental edits. Delimiters longer than 255 quotes are supported.
The byte counts in Tree-sitter's input interface bound the document size.
The compatibility tests and known limitations should be reviewed whenever
the language's lexer or parser changes.

The grammar produces a concrete syntax tree with punctuation and recovery
nodes. Its tree shape is not the compiler's AST, even where node names are
shared. `@` is not source syntax; namespace keys created internally by the
compiler do not become valid source identifiers here.
