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

Embedding GCSL

Single-page view · as markdown

Embedding GCSL

GCSL / Embedding GCSL

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:

CrateResponsibility
gcslSyntax, types, evaluation, formatting, and semantic indexing
gcsl-diskFinding workspace roots and reading source trees
gcsl-lspEditor protocol, document state, and request handling
gcsl-cliCommand 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). 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

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:

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

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

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:

PathDirectories read
pkgspkgs/ 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 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:

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:

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:

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:

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

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, so a body can give any other data, for the packager of its format:

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:

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:

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

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

#[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), Progress::Waiting(unit) if it needs a result that another unit is computing (see 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:

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

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

Peios Learn — documentation for Peios software.

Built with Trail.