Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
GCSL

The Language

Single-page view · as markdown

Values and Bindings

GCSL / The Language

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:

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:

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.

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

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:

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:

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:

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:

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:

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 Ints:

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 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:

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:

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:

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:

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:

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:

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.

Functions and Effects

GCSL / The Language

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:

MarkerMeaning
: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:

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:

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:

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:

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:

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:

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 .:

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:

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 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

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.

#[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:

#[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:

AttributeArgumentMeaning
#[retry(times)]times: IntIf the call fails, run it again, up to this many more times.
#[timeout(limit)]limit: DurationFail the call if it runs for longer than this.
#[track_caller]noneReport 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.

#[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:

#[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:

#[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}:

#[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

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:

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).

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:

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"}:

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:

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:

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:

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:

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:

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

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.

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:

FieldWhat it is
rootthe whole install, which its tools need beside them
runtimethe root its tools run on: / for the host's own
cc, ar, ldthe compiler, the archiver, and the linker
sysrootthe 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.

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:

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).

Failure

GCSL / The Language

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:

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:

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

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:

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:

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:

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:

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():

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

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:

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:

TypeContract
Present<Int>A present integer, equivalent to Int in an ordinary annotation
Future<Int>Deferred work yielding an integer
`IntFuture`

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 when an inferred type is wider than expected.

Lists and Control Flow

GCSL / The Language

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:

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:

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:

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

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:

BoundaryWhat to write
An empty list has no independent element typeGive it an annotation or an expected List<T> type
A pure function does not preserve arbitrary future shapesWrite the present or future contract explicitly
Recursive impure results can retain a deferred possibilityUse Present<T> when the result must be present
General type parameters and intersections are unsupportedWrite concrete structural types
There is no None value or optional-type shorthandRepresent alternatives using supported union members
Narrowing recognizes a plain name tested directly by ifBind a field to a name before testing it
Narrowing does not establish facts after an early returnKeep uses inside the narrowed branch
A narrowed mutable name is a branch-local copyDon't try to update the original through that copy
len and show use special call rulesCall 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.

Peios Learn — documentation for Peios software.

Built with Trail.