Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Goblin logo

Goblin is a dynamically typed language with Go-style braces and a compact, Python-like feel. It is useful for experimenting with programs and for learning how interpreters, runtimes, and code generation fit together.

This book assumes that you can use a command line and already know the basic ideas of variables, functions, and control flow. Its aim is not to catalogue every API, but to get you comfortably reading and writing Goblin programs.

Goblin has two ways to run a program:

  • goblin run interprets a source file directly. Use it while developing and experimenting.
  • goblin build-exe transpiles source to Go and compiles a native executable. Use it when you want a standalone program.

Both paths parse the same language and run semantic checks before executing. During development, start with goblin run; use build-exe when you need an executable without the Goblin CLI. The generated executable still uses the Goblin runtime, so the language behavior is intended to be the same.

Here is a complete Goblin program:

func greet(name) {
    print("Hello,", name)
}

for name in ["world", "Goblin"] {
    greet(name)
}

Source files use the .goblin extension. Comments start with #. When you are ready, continue with Installation.

What this book covers

The chapters first cover values and control flow, then functions and collections, followed by custom types, modules, and errors. The examples are complete fragments that can be pasted into a .goblin file. The Book focuses on the language and its standard runtime; see the repository's examples/ directory for larger executable programs.

For the current implementation boundaries and features deliberately absent from the language, see Language model and limits.

Language model and limits

Goblin is a dynamically typed language with a tree-walking interpreter and a Go transpilation backend. Both backends use the same parser, semantic checks, and runtime object model. Use goblin run for iteration and goblin build-exe when a standalone executable is needed.

The language is intentionally small. These boundaries are useful to know before designing a larger program:

AreaCurrent behavior
TypesDynamic; functions and fields have no annotations
Static checksNames and scopes, plus argument counts of calls to known functions and attribute names on values of a known user type; anything dynamic is checked at runtime
FunctionsRequired and defaulted parameters plus *args and **kwargs
StringsUnicode-aware iteration, size, string[index] and string[low:high], all counting characters
PositionsIndexes, slice bounds and method positions count from the end when negative; an out-of-range index or method position is an IndexError, while a slice takes the elements that exist between its bounds
ReflectionThe global functions type_of and attributes; a value's members are only its fields, properties and methods
ProtocolsA closed set of thirteen, implemented in impl blocks for operators and conversions; no user-declared protocols or interfaces
Destructuringvar a, b = value, a, b = value, and for a, b in values split an iterable of exactly that many elements; there are no tuples or nested patterns
ImportsModule scope only; local paths are relative to the importing file
Concurrencyspawn returns a joinable Goblin handle; iterable channels; timeout= on every blocking operation; no select or cancellation
ErrorsExplicit raise and try/catch; a spawned function's error is re-raised by wait(), and reported on stderr at exit if nobody waited
Cleanupdefer call() runs the call when the enclosing function ends; there is no finally and no block-scoped cleanup. os.exit() runs the pending deferred calls of the goblin that called it; Ctrl-C ends the process without running them

Goblin favors direct, explicit code over a large amount of syntax. When a feature is absent, compose the available pieces: use a channel instead of a join operation, or an explicit loop instead of a specialized expression form.

Choosing a backend

Start with goblin run while developing. It gives direct source tracebacks and does not need to invoke Go. Use goblin build-exe only once the program works; it generates Go code and requires a working Go toolchain. A generated executable still uses Goblin's runtime behavior, rather than turning a Goblin value into a native Go primitive everywhere.

Installation

Goblin is installed through the Go toolchain. Install Go 1.20 or later, then verify that it is available:

$ go version

Install with go install

$ go install github.com/aisk/goblin@latest

This downloads, builds, and installs goblin into $GOBIN, normally $HOME/go/bin when GOBIN is unset. Ensure that directory is on your PATH.

For a typical Unix shell, add the following line to your shell profile if goblin is not found after installation:

export PATH="$PATH:$(go env GOPATH)/bin"

Verify the installation

$ goblin --help

If help text is printed, the installation is ready to use. goblin --version prints the version.

The CLI provides three subcommands:

CommandPurpose
goblin run file.goblin [args...]Interpret a source file (trailing args become os.args; put the file before any flags)
goblin build-exe file.goblinBuild a native executable
goblin replStart an interactive session

For goblin run, CLI help is goblin run -h or goblin help run. Script flags such as -v must come after the source file.

Build from source

Alternatively, clone the repository and build it yourself:

$ git clone https://github.com/aisk/goblin.git
$ cd goblin
$ go build .

This produces a goblin executable in the current directory. While working from a clone of the repository, you can also run it directly:

$ go run . run hello.goblin

Run the project's checks before contributing a change:

$ go test ./...

To verify the complete programs mirrored in the Book, run:

$ bash docs/check-examples.sh

Updating

To update an installation made with go install, run the same command again:

$ go install github.com/aisk/goblin@latest

Your first program

Create hello.goblin:

print("Hello, world!")

To write the same kind of line to stderr (for warnings or diagnostics), use eprint instead of print.

Goblin does not require a main function. Statements at the top level run in order. Add a comment with # when you need to explain a line:

# A program may have more than one top-level statement.
var audience = "world"
print("Hello,", audience)

A program can also ask a question. input writes the prompt and returns the line that was typed, or nil when there is nothing more to read:

var name = input("Your name: ")
print("Hello, {name}!")

Run it directly

$ goblin run hello.goblin
Hello, world!

run parses and interprets the file. It is the usual command during development. If parsing, semantic checking, or execution fails, the command reports the source location and exits with an error.

Compile an executable

$ goblin build-exe hello.goblin
$ ./hello
Hello, world!

By default the output name is derived from the source file. Specify a path with -o when needed:

$ goblin build-exe -o bin/hello hello.goblin

build-exe requires a working Go toolchain because it invokes go build after generating Go source. The output path may be absolute or relative to the current directory.

Use the REPL

Goblin also includes an interactive REPL:

$ goblin repl
>>> print("Hello, world!")
Hello, world!

The REPL saves history. Its prompt changes to ... while you enter a multi-line function or block. Press Ctrl-D to exit.

Use the REPL for small experiments. Definitions stay available for the rest of the session:

>>> var answer = 42
>>> answer + 1
43

Using the REPL

Start a persistent interactive Goblin session with:

$ goblin repl
Goblin REPL. Press Ctrl-D to exit.
>>>

Expressions print their value automatically; declarations and statements do not. Names, imports, functions, and types stay available until the session exits.

>>> 1 + 2 * 3
7
>>> var values = [1, 2, 3]
>>> values.push(4)
>>> values
[1, 2, 3, 4]
>>> import "math"
>>> math.sqrt(81)
9.0

Relative imports are resolved from the directory where the REPL starts, so start it from a project directory when testing a local module.

In the REPL os.args is [] and os.program is "". They do not expose the goblin binary's process arguments. Use goblin run when you need real script argv.

Multi-line input

When parentheses, brackets, or braces are unbalanced, the prompt changes to ... and the REPL keeps collecting lines. This is how to enter functions, types, loops, and try/catch blocks.

>>> func square(x) {
...     return x * x
... }
>>> square(12)
144

Enter a blank line to force evaluation of a malformed fragment, or press Ctrl-C to discard the input currently being collected.

The REPL does not run the checks a file gets before it runs, because a line may use names declared on earlier lines. The mistakes those checks catch are reported when the line runs instead, with the same message. Assigning to a name nothing has declared raises NameError (assignment to undefined identifier: total), including from inside a function, so a misspelled name does not silently create a global; declare a new name with var. Assigning to a type name or to a built-in such as print without var raises NameError as well, while var print = ... declares a binding that shadows the built-in.

Entering a type declaration again rebinds its name. Values made before keep the old type. The REPL checks each type's impls when the type is defined, so impl Shape {} reports that Shape is not a protocol right away.

Completion and history

Press Tab to complete visible names, keywords, and member paths. For example, after import "json", type json. and press Tab to see members. Completion only reads attributes; it does not call Goblin functions.

History is stored in ~/.goblin_history; use Up/Down to revisit entries and Ctrl-D to exit. os.exit() leaves the REPL with that status after running the deferred calls of the current input. Use the REPL for small experiments and API discovery, then move repeatable work into a .goblin file.

Syntax and call rules

Goblin uses braces for blocks and does not use semicolons. A newline ends a statement, so each statement sits on its own line. Comments begin with # and continue to the end of the line.

Literals and collection syntax

Integer literals are decimal (42), hexadecimal (0x1F), octal (0o644) or binary (0b1010); the prefix is lowercase, hexadecimal digits may be either case. A decimal integer cannot start with 0: 0644 is an error, so it can never be mistaken for an octal number. Float literals have a decimal point (3.14), an exponent (1e9), or both (1.5e-3). An _ may separate two digits in any number literal (1_000_000, 0xFF_FF); anywhere else it is an error. An integer literal outside the 64-bit range is an error too. The smallest Int is written -9223372036854775808: its digits alone exceed the largest Int, so they are accepted only directly after a unary minus. Strings use double quotes, and {expression} inside one inserts the expression's value; backtick strings are raw, with no escapes and no interpolation, and may span lines. Double-quoted strings support \n, \t, \r, \", \\, \{, \}, \0, \xHH and \u{H...}; any other escape sequence is a syntax error. See Strings for the details.

var names = ["Ada", "Linus"]
var user = {"name": "Ada", "active": true}

List, dictionary, call, parameter, and field lists accept a trailing comma after the last item, so every line of a multi-line list can end the same way. A comma with no item before it, as in [,] or f(,), is a syntax error. Dictionary keys and values are expressions, but keys should be stable values such as strings, integers, or booleans.

Statements and line breaks

Any expression can stand alone as a statement, but only a call, index, or member access may do so in a program: user.save(), "a,b".split(","), and func() { ... }() are valid statements, while a + b or a lone - 2 is rejected with expression value is not used, since a value that is computed and dropped is almost always a mistake. The REPL is the exception: there a bare expression such as 1 + 2 is evaluated and displayed.

A slice is not among them: like a + b, values[1:3] on its own only computes a value.

Because a newline ends a statement, a line can only continue the previous one in places where the expression is visibly unfinished: after a binary operator, a comma, a dictionary colon, or inside an open (, [, or { of a literal. Ending a line with a complete expression and starting the next with an operator does not continue it. var a = 10 followed by a line - 2 is two statements, and the second is the unused-value error above rather than a silent 10 - 2.

var total = price * quantity +
    shipping
var discounted = (
    total - coupon
)
var files = {
    "a.txt": "first",
    "b.txt": "second",
}
print(files["a.txt"],
      files["b.txt"])

Inside the brackets of a slice, a newline may follow [ or precede ], but not follow the colon.

The same rule means else must follow the closing brace of its if on the same line, each catch the closing brace before it, and two statements cannot share a line.

A try takes one or more catch clauses. catch name: Kind { ... } handles an error for which name.is(Kind) holds, where Kind is any expression; catch name { ... } handles any error and must come last. See Errors.

try {
    risky()
} catch e: KeyError {
    print("missing key")
} catch e {
    raise e.wrap("risky failed")
}

Names

Identifiers may not be Go keywords: names such as map, range, select, struct, go, or switch are reserved and rejected at check time, because compiled programs emit them as Go identifiers. A handful of names the generated code itself relies on — object, extension, builtin, fmt, _registry, Execute, and main — are reserved for the same reason, as is the whole family of identifiers shaped like _name_N (a leading underscore with a trailing _<digits> suffix, e.g. _err_0), which the transpiler uses for its own temporaries. Built-in function names like print or max are not reserved — see Scope and declarations for how user declarations shadow them.

Functions and calls

Function parameters are required unless they declare a default value with = or are captured by *args or **kwargs.

func report(name, limit = 10, *values, **options) {
    print(name, limit, values, options)
}

report("scores", 1, 2, visible=true)

Calls can use positional arguments, named arguments, * list expansion, and ** dictionary expansion. Positional arguments must come before named ones. Whether a particular built-in or method accepts names is API-specific: many small methods are positional-only. Use the documented parameter names or attributes(value) in the REPL to discover a value's available methods.

Values, variables, and expressions

Goblin is dynamically typed: variables do not declare a type, and values carry their types at runtime. Use var to bind a name to a value.

var project = "Goblin Book"
var published = false

Assign to the name to update it later.

var score = 10
score = score + 5
print(score) # 15

Destructuring

A var or an assignment can take several targets at once. The value on the right is iterated, and each element goes to the target in the same position:

var width, height = [640, 480]
print(width, height) # 640 480

width, height = [height, width]
print(width, height) # 480 640

The right side is evaluated in full before anything is stored, which is why the swap above needs no temporary. An assignment target may be anything a plain assignment accepts, so point.x, items[0] = pair works too. Any iterable can be destructured, though a list is the usual choice. The number of elements must equal the number of targets; otherwise the statement raises ValueError and stores nothing.

A function returns several results the same way, as one list the caller takes apart:

func divmod(a, b) {
    return [a / b, a % b]
}

var quotient, remainder = divmod(17, 5)

A for loop destructures each element with the same syntax; see Control flow.

Printing and comments

print separates multiple arguments with spaces and ends the line; it writes to stdout. Use eprint for the same formatting on stderr. A comment starts with # and runs to the end of its line.

Operators

The ordinary arithmetic operators are +, -, *, /, and %. The % operator returns the remainder and has the same precedence as multiplication and division. Use parentheses to make grouping explicit.

print(1 + 2 * 3)       # 7
print((1 + 2) * 3)     # 9
print("go" + "blin")  # goblin
print("ha" * 3)        # hahaha
print(10 % 3)          # 1

Comparison operators are ==, !=, <, <=, >, and >=; each produces a boolean. Equality is total across types: values of unrelated types are simply unequal, and lists and dictionaries compare element by element. x == nil is always a safe test: it is true only for nil itself, and it never calls a user type's eq (see Eq and Ord). Ordering comparisons (<, <=, >, >=) order numbers (an Int against a Float too), Strings, Bytes, Bools (false < true), Lists (element by element, the first unequal pair deciding), nil against nil (equal), and user types with an Ord impl. Any other pair, such as an Int and a String, a Dict, or a Function, raises TypeError. A NaN Float is unordered, as IEEE 754 defines it: all four ordering operators are false when either operand is NaN, and nan == nan is false too (see Numbers). Comparisons do not chain: a < b < c is a syntax error rather than the surprising (a < b) < c, so write a < b && b < c, or parenthesize explicitly when you really mean to compare a boolean result. Logical operators are !, &&, and ||. && and || short-circuit, so their right-hand side is evaluated only when needed, and they produce the operand that decided the result rather than a boolean: a || b is a when a is truthy and b otherwise, a && b is a when a is falsy and b otherwise. That makes || the way to write "use this, or a default". Wrap the expression in Bool() when you need a plain true/false. ! always produces a boolean.

var allowed = age >= 18 && !banned
var nickname = supplied || "anonymous"

&& binds tighter than ||, as in most languages: ready || retry && connected evaluates as ready || (retry && connected), and true || false && false produces true.

Operands are evaluated left to right, in both backends: in x + f(), [x, f()] and g(x, f()) the value of x is read before f runs, even when f assigns to x. A call's callee or receiver comes before its arguments, and an assignment xs[i] = value evaluates xs, then i, then value.

Conditions use truthiness. false, nil, numeric zero, and empty strings or collections are false. Continue with Built-in types for the values that Goblin provides.

Scope and declarations

var creates a name in the current lexical scope. A name declared in a block is visible inside nested blocks, but not after the block ends. Assignment updates the nearest existing name; use var when a new local binding is intended.

var message = "outside"
if true {
    var detail = "inside"
    message = "changed"
    print(detail)
}
print(message) # changed
# detail is not visible here

Functions capture the surrounding lexical scope. Each for iteration has its own loop binding, so functions created in a loop retain that iteration's value.

var readers = []
for value in [1, 2, 3] {
    readers.push(func() { return value })
}
print(readers[0](), readers[1](), readers[2]()) # 1 2 3

Declarations at module scope

import, type, and export are allowed only at module scope. Module-level import, func, and type names are hoisted: they are visible throughout the module regardless of where the definition appears, so functions may call functions defined later, including mutually recursive pairs. Type names cannot be reassigned.

func is_even(n) {
    if n == 0 { return true }
    return is_odd(n - 1)
}

func is_odd(n) {
    if n == 0 { return false }
    return is_even(n - 1)
}

print(is_even(10))

Other names must be declared before use: local var declarations (and nested function definitions) are not available before their declaration. Keep declarations near the beginning of the block when that makes a function easier to read.

Shadowing built-in functions

A user declaration may reuse a built-in function's name. The innermost binding wins, and the built-in becomes visible again once the shadowing scope ends:

func min(a, b) {
    return "user min"
}
print(min(1, 2)) # user min

if true {
    var max = 100
    print(max)   # 100
}
print(max(1, 2)) # 2 — the built-in is back in scope

Go keywords such as map or range cannot be used as names at all; see Syntax and call rules.

Built-in functions

These names are available without an import.

FunctionPurpose
print(values...)Write values to stdout, separated by spaces, ending with a newline
eprint(values...)Same as print, but write to stderr
range(end) / range(start, end)Create integer values from start (zero when omitted) through end-exclusive
min(values..., key=nil) / max(values..., key=nil)Choose the smallest or largest of several values, or of one iterable's elements
sum(values)Add up an iterable's elements with +, starting from 0
compare(a, b)Order two values as < does: -1, 0 or 1
hash(value)The hash a dictionary files a key under
Int(value=0, base=10) / Float(value=0.0) / String(value="") / Bool(value=false)Convert a value; base reads text in another base. Called with no argument, each returns its zero value
Bytes(value) / List(iterable) / Dict(key=value, ...)Construct a collection value; value and iterable are optional, and without them the result is empty
Chan(capacity=0)Create a channel; capacity 0 means unbuffered
Function(value)Validate and return a callable value (a function, a constructor, a bound method or an error kind) unchanged; the one constructor whose argument is required
spawn(function, args...)Run a function concurrently, returning a Goblin handle to join it
wait_any(goblins, timeout=nil)Wait until one of several goblins finishes and return it
Error(message="Error", **data)The base error kind; calling it creates an error of that kind, optionally carrying named data
input(prompt="")Write a prompt to stdout and read one line from stdin, or nil at the end of input
format(value, spec)Format a value under a format specifier, as "{value:spec}" does
type_of(value)The constructor of a value's type
attributes(value)List the names of a value's properties and methods

print and eprint return nil. range(n) is short for range(0, n); with keywords, start is optional and end is required.

min and max order their candidates the way < does, so they work on strings and on user types that implement Ord. Several positional arguments are the candidates; a single one must be iterable, and its elements are (max([3, 8, 5]) is 8). So pass a list itself, not max(*values): expanded, a list with one element becomes one argument that is not iterable. With no argument they raise TypeError, and with an empty iterable ValueError. key= takes a function and orders the candidates by what it returns for each, as sort(key=) does. On a tie max answers the later candidate and min the earlier one, the last and first elements a stable sort would give. sum(values) adds an iterable's elements with + starting from 0, so an empty one sums to 0. compare(a, b) is -1, 0 or 1 as a sorts before, with or after b, and raises the TypeError < raises for values without an order. A NaN has no place in an order, so compare, min and max raise ValueError cannot order NaN when they meet one, where < answers false. hash(value) is the hash a dictionary files the value under, so equal values hash equal; it is stable within one run of a program but not between runs, and a value that cannot be a key raises TypeError (cannot hash List). Constructors that use an argument parser, including range, numeric conversions, and Dict, accept their documented keyword names; print and eprint are positional-only, and spawn takes its function positionally and forwards every other argument, keyword arguments included, to it.

Every argument that takes a function (key= of min, max and sort, the fn of map and filter, spawn's first argument) accepts any value that can be called: a function, a constructor such as Int or a user type, a bound method, or an error kind. Anything else raises TypeError (map() argument 'fn' must be callable, got Int).

format(value, spec) returns the String "{value:spec}" would give, for a specifier built at run time (format(name, "<{width}")) or formatting outside a literal (prices.map(func(p) { return format(p, ".2f") })). The specifier language is described under Formatting; spec must be a String, an empty one gives the text print shows, and a malformed one raises ValueError (format() invalid format specifier ".2": precision needs 'f' or 'e').

input(prompt="") writes the prompt (a String, with no newline added) to stdout and reads one line from stdin. It returns the line without its \n or \r\n; a last line with no terminator counts. At the end of input it returns nil. An empty line is "", which is false in a condition, so test == nil to detect the end. A line that is not valid UTF-8 raises ValueError. input() and os.stdin read through one shared buffer, so they can be mixed without losing lines.

var total = 0
while true {
    var line = input()
    if line == nil { break }
    total = total + Int(line)
}
print(total)

Use eprint for diagnostics and warnings so they stay off the program's normal stdout stream (the same role as Python's print(..., file=sys.stderr), Rust's eprintln!, or Go's fmt.Fprintln(os.Stderr, ...)).

var limits = [3, 8, 5]
print(min(limits), max(limits), sum(limits))
print(max(["kiwi", "fig", "banana"], key=func(s) { return s.size }))
print(range(start=2, end=5))
print(Dict(host="127.0.0.1", port=8080))
eprint("ready on port", 8080)

See Built-in types for value-specific methods, and Concurrency for channels and spawn.

Constructors and type identity

type_of(value) returns the constructor of the value's type: the same callable that is used to create or convert that type. A function's name property says which one it is:

var values = [1, "text", Bytes("raw"), [1], {"x": 1}, Chan(1)]
for value in values {
    print(type_of(value), type_of(value).name)
}

func identity(value) {
    return value
}
print(Function(identity) == identity)   # true
print(type_of(identity) == Function)    # true
print(identity.name)                    # identity

Goblin-defined instances and native standard-library values follow the same rule: type_of(instance) is identical to the type callable that created them. Every value has a type, including those that cannot be constructed: for nil, a module or a Goblin handle, type_of returns a stand-in function named after the type (type_of(nil).name is "Nil") that compares equal for values of the same type and raises TypeError when called. The type of an error is Error, the base error kind: type_of(e) == Error holds for every error, and calling Error makes a new one. It is an error rather than a function, but it has a name like every other type, so type_of(value).name works for any value (type_of(e).name is "Error"). Only Error itself has it: on any other error name is free for data, as in NotFound("no such user", name="ann").

attributes(value) returns a new list of the names a value answers to: its properties or fields first, then its methods, in declaration order (a module's members are sorted by name). These are functions rather than members, so a type is free to have a field or method called constructor or attributes.

Built-in types

Goblin values have runtime types; variables do not need type annotations. An operation succeeds only when its value types are compatible.

TypeExamplesNotes
Int0, -42Signed 64-bit whole number
Float3.14, -0.564-bit floating-point number
Booltrue, falseLogical value
NilnilAbsence of a value; it prints as nil
String"hello"Immutable Unicode text
BytesBytes("data")Immutable raw byte sequence
List[1, "two"]Ordered, mutable collection
Dict{"name": "Ada"}Mutable key/value collection, in insertion order
ChanChan()Channel for concurrent functions
Goblinspawn(func() {})Handle to a function running concurrently
Functionfunc() {}Callable value

Custom types are covered in Types and methods.

Numbers

Integer literals have no decimal point and can be written in decimal, hexadecimal, octal or binary (255, 0xFF, 0o377, 0b1111_1111); float literals have a decimal point or an exponent (2.5, 1e9). See Syntax for the exact rules. Arithmetic preserves an integer result when both operands are integers. If either operand is a float, the result is a float. Integer division truncates its fractional part. The % operator returns the remainder after truncating division; the result has the dividend's sign and is a float if either operand is a float. An Int has one method, to_char(), the character with that code point (see Characters and code points).

print(7 / 2)     # 3
print(7 / 2.0)   # 3.5
print(2 + 0.5)   # 2.5
print(-3 * 4)    # -12
print(-7 % 3)    # -1
print(7.5 % 2)   # 1.5
print(4 / 2.0)   # 2.0

A Float always prints as a float: a whole value keeps a .0, and very large or very small magnitudes use an exponent (1e+16, 1e-05). To choose the number of decimals, format it: "{2 / 3.0:.2f}" is 0.67 (see Formatting).

Integers are 64-bit and Goblin has no big integers. Arithmetic whose result does not fit raises OverflowError instead of wrapping around, and so does converting a float or string that is out of range with Int(). Float() raises OverflowError too for text that is a valid number too large for a Float, such as Float("1e400"); text that is not a number raises ValueError.

Numbers can be compared across integer and float values. Division or modulo by zero raises ZeroDivisionError.

A NaN (Float("nan"), or math.NAN) has no place in an order. The ordering operators follow IEEE 754 and answer false when either operand is NaN, and nan == nan is false while nan != nan is true. Everything that needs an actual order raises ValueError cannot order NaN when it meets a NaN, because any answer it gave would be wrong: compare, sort() (also through a key that returns NaN, and the list stays as it was), max, min, and a list or structural comparison that reaches a NaN element. Test for NaN with math.is_nan(x) or x != x. Int() and Float() convert numbers, booleans, and numeric strings; converting a float to Int removes its fractional portion.

print(Int("42"))   # 42
print(Int(3.9))     # 3
print(Float(true))  # 1.0
print(max(3, 5, 4))

When to convert and when to calculate

Use Int() or Float() at the edge of a program, where a value arrives as text or where an integer operation must become floating-point. Keep calculations in their natural numeric form after that. For example, parse a configuration value once, then use min() and max() to keep it within a permitted range.

var requested_workers = Int("12")
var workers = min(max(requested_workers, 1), 8)
print(workers) # 8

Int() rejects non-numeric text with ValueError. This makes it suitable for validating numeric input inside a try/catch block.

Int(text, base=16) reads text written in another base, from 2 to 36. The text is the digits of that base, letters in either case, with an optional leading + or - and nothing else: a prefix such as 0x, an underscore or a space raises ValueError, so strip a prefix first. base needs a String value; Int(255, base=16) raises TypeError.

print(Int("ff", base=16))   # 255
print(Int("755", base=8))   # 493, a permission mode for fs.chmod
var color = "#ff8800"
print(Int(color[1:3], base=16), Int(color[3:5], base=16)) # 255 136

Hex text becomes Bytes by reading it two digits at a time: Bytes(range(hex.size / 2).map(func(i) { return Int(hex[i * 2:i * 2 + 2], base=16) })).

Booleans and nil

Use Bool(value) to convert any value by truthiness. False, nil, numeric zero, and empty strings, lists, dictionaries, or bytes are false.

print(Bool(""))       # false
print(Bool([1]))      # true
print(!nil)           # true
print(true && false)  # false

A function with no explicit result returns nil. Comparing any value against nil with == is safe: it is true only for nil itself, and a user type's eq is not called for it. Arithmetic and indexing on nil are errors.

Using truthiness for optional values

Truthiness is convenient for choosing a fallback or guarding an optional collection. Use an explicit comparison with nil when zero, false, or an empty collection must still be treated as a present value.

var nickname = ""
print(nickname || "anonymous") # anonymous

var limit = 0
if limit == nil {
    print("no limit supplied")
}

Strings and bytes

Strings are immutable Unicode text. They can be iterated by character, indexed with text[i] (giving a one-character string), combined with +, repeated with *, and sliced with text[low:high]. Use index() to find a character position. The property code_point is the code point of the first character as an Int (nil for ""), and an Int's to_char() method turns a code point back into a one-character string. See Strings for conversions and typical methods.

Bytes are immutable raw byte sequences. Bytes("ABC") has size 3 and its first element is the integer 65. Like list indexes, a negative byte index counts from the end, bytes[low:high] slices them, and * repeats them. Bytes share the subsequence methods of strings, with positions counted in bytes: contains(), count(), index(), has_prefix(), has_suffix(), trim_prefix(), trim_suffix(), replace(), split() and cut(), each taking a String or Bytes argument. Text operations (upper(), trim(), splitting at whitespace, lines()) belong to strings: decode() first, which raises ValueError for invalid UTF-8. to_hex() shows Bytes as text of two lower-case hexadecimal digits per byte (empty Bytes give ""), the usual way to print a digest or a random token. There is no reverse conversion from hexadecimal text to Bytes. Bytes are hashable, so they can be dictionary keys. Use Bytes for raw data and strings for text.

Working with bytes

Use Bytes when reading or sending binary-oriented data, or when indexing must produce numeric byte values. Use decode() when that data should become text.

var header = Bytes("GET")
print(header[0])          # 71
print(header.contains("E"))
print(header.decode())    # GET
print(header.to_hex())    # 474554

Lists and dictionaries

Lists and dictionaries are mutable collections. A list is ordered and uses integer indexes; a dictionary maps keys to values. Empty collections are false in conditions. See Collections for creation, indexing, and method guides.

Channels

Chan(capacity=0) creates a channel. Send with send(), receive with receive(), and close with close(), which does nothing on a channel already closed; send() and receive() take an optional timeout= in seconds. Capacity 0 creates an unbuffered channel. Use spawn() to start a concurrent function.

var done = Chan()
spawn(func() {
    done.send("finished")
})
print(done.receive())
done.close()

Coordinating concurrent work

An unbuffered channel makes send() wait until another function calls receive(). A buffered channel can accept up to its capacity before a receiver is ready. A for loop over a channel receives values until it is closed and drained.

var results = Chan(capacity = 2)
spawn(func() {
    defer results.close()
    results.send(2 * 2)
    results.send(3 * 3)
})
var total = 0
for value in results {
    total = total + value
}
print(total) # 13

Close a channel only when no more values will be sent. Calling receive() on a closed, drained channel raises ValueError, rather than producing a special nil value.

Goblin handles

spawn(function, args...) starts the function in a new goroutine and returns a Goblin handle; there is no Goblin constructor. wait() joins it: the function's result is returned, an error it raised is re-raised, and the outcome is cached across repeated calls. The done property reports completion without blocking, and wait(timeout = seconds) raises TimeoutError when the function outlives the timeout. An error no wait() ever saw is reported on stderr when the program ends.

func square(value) {
    return value * value
}

var worker = spawn(square, 6)
print(worker.wait()) # 36

See Concurrency for how handles, channels, and spawn fit together.

Common operations

TypeCommon constructors and operations
Int / FloatInt(value), Float(value), max(...), min(...)
Bool / NilBool(value), !value, value && other, value || other
StringString(value), size, contains(), split(), replace()
BytesBytes(value), size, decode(), to_hex(), contains(), split()
ListList(value), size, first, last, push(), pop(), sort(), copy()
DictDict(), get(), get_or_set(), remove(), keys(), items(), update()
ChanChan(capacity), send(value), receive(), close(), for value in channel
Goblinspawn(function, args...), wait(), done, wait_any(goblins)
FunctionFunction(value), value(...), name

Use attributes(value) in the REPL to inspect all operations provided by a runtime value, and type_of(value) for its type; see Built-in functions.

Control flow

Goblin uses braces for blocks and does not need semicolons.

An indented style makes nested blocks easy to scan, but indentation is not part of the grammar: braces determine the block.

Conditions

Use if, else if, and else to select a branch:

if score >= 90 {
    print("excellent")
} else if score >= 60 {
    print("passed")
} else {
    print("try again")
}

Every condition is evaluated with the truthiness rules described in Built-in types. This lets you test optional values and collections directly:

var users = []
if users {
    print("have users")
} else {
    print("no users")
}

while loops

A while loop repeats while its condition is true. break leaves the nearest loop and continue skips to its next iteration.

var n = 0
while n < 10 {
    n = n + 1
    if n == 3 {
        continue
    }
    if n == 6 {
        break
    }
    print(n)
}

Be sure that a while condition eventually changes or that the loop reaches a break; Goblin does not impose a loop limit. In nested loops, break and continue apply only to the innermost loop.

for ... in loops

for iterates over lists, strings, dictionaries, and other iterable values. Iterating over a dictionary produces its keys, in insertion order.

for name in ["Ada", "Linus"] {
    print(name)
}

for i in range(3) {
    print(i) # 0, 1, 2
}

for i in range(1, 4) {
    print(i) # 1, 2, 3
}

range(end) creates the integers from zero up to, but excluding, end, and range(start, end) those from start. It also accepts named arguments, such as range(start=0, end=3). Called directly in a loop header, range counts instead of building its list, so for i in range(1000000000000) with an early break costs only the iterations that run.

A loop takes one element at a time from the value it walks. For a file that means one line at a time (see fs): the loop reads only as far as it gets, and an error such as an invalid line is raised when the loop reaches it, after the earlier elements have run through the body. A list is walked in place, by position, over at most as many elements as it held when the loop started: assigning an element the loop has not reached yet is seen, elements pushed during the loop are not visited, and when pop, remove or clear has made the list shorter than the position the loop reached, the loop ends there. The list is not copied, so a loop costs nothing up front. Every other walk over a list follows the same rule, such as the function given to map, filter, find or max(key=). A dictionary loop visits the keys it held when the loop started.

However a loop ends (it runs out of elements, break, a return in its body, or an error leaving it) the value being walked is told once that the loop is done, before anything after the loop runs, the function's deferred calls included; a return evaluates its value first. A value that acquired something for the loop, such as a sequence that opened a file to read it, releases it then. A file you opened yourself and loop over stays open: it belongs to you, not to the loop.

Strings iterate by character, lists by element, and dictionaries by key:

var scores = {"Ada": 10, "Linus": 9}
for name in scores {
    print(name, scores[name])
}

for character in "go" {
    print(character)
}

A dictionary is iterated in insertion order: the order its keys were first written in.

When every element is itself a small sequence, name its parts in the loop header. Each element is destructured as var a, b = element would be, so an element with a different number of parts raises ValueError:

for name, score in scores.items() {
    print(name, score)
}

for x, y in [[0, 1], [2, 3]] {
    print(x + y)
}

Functions

Define a function with func. Parameters do not have declared types, and return sends a result back to the caller. A function without a value returns nil.

func add(a, b) {
    return a + b
}

print(add(2, 3))

Use a bare return to exit early. It returns nil.

func describe(value) {
    if value == nil {
        return
    }
    print(value)
}

Functions are values: assign them, pass them to another function, or return them. An anonymous function omits the name.

var square = func(x) { return x * x }

func apply(f, value) {
    return f(value)
}

print(apply(square, 5))

An anonymous function captures variables in its surrounding scope, so it can form a closure:

func multiplier(n) {
    return func(x) { return x * n }
}

var double = multiplier(2)
print(double(21))

The captured value belongs to the closure's surrounding scope. Each call to multiplier above creates a separate function value, so multiplier(3) would produce a different closure.

Parameters

Calls may use positional arguments or parameter names:

print(add(a=2, b=3))

Positional arguments must precede named arguments. A parameter can receive a value only once; passing the same parameter positionally and by name is an error.

A parameter can declare a default value with =, making it optional at the call site:

func greet(name, msg = "hi") {
    print(msg, name)
}

greet("bob")                # hi bob
greet("bob", msg = "yo")    # yo bob

A required parameter cannot follow one with a default. The default expression is evaluated in the function's defining scope — it cannot reference other parameters — and it is evaluated on each call that omits the argument, so a mutable default like [] produces a fresh value every time.

A * parameter collects extra positional arguments, while a ** parameter collects extra named arguments. They receive a list and a dictionary, respectively. The dictionary holds the named arguments in the order the call gives them, left to right, with a **-expanded dictionary contributing its entries in its own order.

func show(first, *rest, **options) {
    print(first)
    print(rest)
    print(options)
}

show("a", "b", "c", color="green")

The *rest parameter must be last, unless a final **options follows it. **options must always be last. Expand a list or dictionary at a call site with f(*items) or f(**options):

func add3(a, b, c) {
    return a + b + c
}

var values = [1, 2, 3]
print(add3(*values))

A call may use both, f(*items, **options). The expanded list supplies the last positional arguments, so after *items only keyword arguments and **options may follow; a positional argument or a second * there is reported before the program runs.

A **-expanded value must be a dictionary with string keys, and each keyword name may only be supplied once per call: naming an argument twice — whether by two explicit keywords, two ** dictionaries that share a key, or one of each — raises a TypeError.

Calls checked before the program runs

When a call names a function directly, its arguments are matched against the parameter list before the program starts, by goblin run and goblin build-exe alike:

func area(width, height = 1) {
    return width * height
}

area()             # error: area() missing required argument: 'width'
area(1, 2, 3)      # error: area() takes 2 positional arguments, got 3
area(1, depth=2)   # error: area() got an unexpected keyword argument 'depth'
area(1, width=2)   # error: area() got multiple values for argument 'width'

This covers names bound by func, by type (the constructor), and by a var initialized with a function literal, as long as the name is never assigned anywhere in the module. A * or ** argument supplies an unknown number of values, so only mistakes that no expansion could repair are reported. Every other call — through a parameter, a reassigned name, a list element, a function from another module — is matched when it runs and raises the same message as a TypeError. The REPL does no checking ahead of time.

Deferred calls

defer schedules a call for the moment the enclosing function ends, however it ends: a return, running off the end of the body, or an error. Put it right after acquiring something that has to be released.

import "fs"

func first_line(path) {
    var file = fs.open(path)
    defer file.close()
    return file.read().decode().split("\n")[0]
}

defer must be followed by a call. The function being called and its arguments are evaluated when the defer statement runs; only the call itself waits. Defer a function literal when the work should see the variables as they are at the end instead:

func demo() {
    var label = "before"
    defer print("argument:", label)                 # argument: before
    defer func() { print("closure:", label) }()     # closure: after
    label = "after"
}

Deferred calls run in reverse order, the last one deferred first, so things are released in the opposite order to how they were acquired. In the example above the closure line prints first.

A few rules follow from "when the function ends":

  • A defer inside an if, a loop, or a try block still belongs to the function, not the block. One in a loop adds a call on every iteration, and all of them wait until the function returns.
  • The result of a deferred call is discarded, and it cannot change the value the function has already decided to return.
  • If a deferred call raises, that error replaces whatever the function was returning or raising. The remaining deferred calls still run.
  • At the top level of a file, deferred calls run when the file's own statements finish, also when they stop with an unhandled error. In the REPL that is the end of each input.
  • os.exit() runs the pending deferred calls of the goblin that called it before the process ends, innermost function first; see os. Deferred calls do not run when the process is ended from outside: an interrupt (Ctrl-C) or any other signal that terminates it, or os.exit() called by another goblin.

Recursion and callbacks

A named function can call itself. Functions also work naturally as callbacks because they are ordinary values.

func factorial(n) {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

func map_values(values, transform) {
    var result = []
    for value in values {
        result.push(transform(value))
    }
    return result
}

print(factorial(5))
print(map_values([1, 2, 3], func(x) { return x * x }))

Recursion depth is limited by the stack a goroutine may use (256 MB), which allows hundreds of thousands of nested calls. A recursion that runs past it, usually one missing its base case, raises RecursionError instead of crashing the process, and can be caught like any other error. Comparing or printing values nested that deeply, such as two distinct lists that each contain themselves, raises the same error. The traceback folds the repeated frames into a single "previous frame repeated N more times" line.

func forever(n) {
    return forever(n + 1)
}

try {
    forever(0)
} catch err {
    print(err.is(RecursionError)) # true
}

Strings

Strings are immutable Unicode text values written with double quotes. Escape a double quote or a backslash with a backslash.

var message = "say: \"hello\""
print(message)        # say: "hello"
print(message.size) # 12

Interpolation

Inside a double-quoted string, {expression} is replaced by the value of the expression, as the same text print shows for it: a String as it is, a number or list as it prints, a custom type through its Show impl.

var user = "Ada"
var inbox = ["hi", "re: hi"]
print("{user} has {inbox.size} messages")  # Ada has 2 messages
print("first: {inbox[0]}, all: {inbox}")   # first: hi, all: ["hi", "re: hi"]
print("{user.upper()} {inbox.size * 10}%") # ADA 20%

The parts are evaluated left to right when the string is. An error raised while evaluating or showing one is reported at the string literal.

  • Write \{ for a literal {. A } outside an interpolation is an ordinary character, and \} also works.
  • The expression ends at the } matching its {, counting (), [] and {}, so "{xs[1:2]}" and "{f(g(x))}" work.
  • It cannot contain a ", a backslash or a line break: the string would end, or the escape would belong to the string. Assign such a value to a variable first, or use a raw string inside: "{names.join(`, `)}".
  • {} with nothing inside is an error (write \{} for the text {}).
  • A : outside any bracket ends the expression and starts a format specifier: see Formatting.

A string without any {expression} is a plain constant.

Formatting

{expression:spec} formats the value under a specifier: it pads text to a width and controls how numbers are written.

var price = 3.1
var name = "tea"
print("{name:<8}|{price:>8.2f}|")      # tea     |    3.10|
print("{255:x} {255:08b} {7:03}")      # ff 11111111 007
print("{1234567:,} {0.5:+.1f}")        # 1,234,567 +0.5
print("{name:*^9}")                    # ***tea***

A specifier is, in this order and each part optional:

[[fill] align] [+] [0] [width] [,] [.precision] [type]
PartMeaning
widthMinimum number of characters; longer text is never cut
align< left, > right, ^ centre (an odd space goes right). Numbers align right by default, everything else left
fillThe padding character, default a space. Only before an explicit align: *^9, >5
+Show + on numbers that are not negative
0Pad a number with zeros between its sign and its digits ({-42:08} is -0000042); not together with an align
,Group the integer digits in threes: an Int with no type or d, or a number with f
.precisionDigits after the decimal point; needs f or e ({x:.2} is an error, write {x:.2f})
dDecimal Int, the default
x X b oInt in hexadecimal (lower or upper case), binary or octal, with no prefix: write "0x{n:04x}"
fFixed point, 6 decimals unless a precision is given; an Int is converted
eScientific (1.50e+03), 6 decimals unless a precision is given; an Int is converted

An Int takes every part. A Float takes all but the Int types; with no type it shows the text print shows (2.0, 1e+16), and , on it needs f ({x:,.2f}). NaN and the infinities show as print shows them, padded with spaces. Any other value (a String, Bool, nil, a list, a custom type through its Show impl) takes only fill, align and width, applied to its print text.

  • The specifier is literal text: it is not interpolated and takes no escapes, so it cannot contain {, }, ", a backslash or a line break. Spaces in it count ({x: >5} pads with spaces); spaces before the : belong to the expression.
  • A malformed specifier ({x:}, {x:5q}, {x:<05}) is a syntax error, reported where it stands when the program is parsed.
  • A value whose type does not take the specifier is a TypeError when the string is evaluated: format specifier ".2f" needs an Int or Float, got String.
  • Rounding is to the nearest value of the exact binary number, so {2.675:.2f} is 2.67, as it is in Go and Python.

When the specifier is only known at run time, such as a column width computed from the data, use the built-in format(value, spec), which is exactly what "{value:spec}" runs:

var names = ["tea", "coffee", "hot chocolate"]
var width = max(names.map(func(n) { return n.size }))
for name in names {
    print(format(name, "<{width}") + "|")
}

Escapes

EscapeMeaning
\n \t \rNewline, tab, carriage return
\" \\Double quote, backslash
\{ \}Literal braces
\0The NUL character
\xHHThe character U+00HH, exactly two hex digits ("\x1b[31m" starts red terminal text)
\u{H...}The character with that code point, one to six hex digits ("\u{1F600}")

\xHH is a character, not a raw byte: "\xe9" is "é", two bytes in UTF-8. Use Bytes for byte values. Any other escape is a syntax error, and so is a \u{...} that is not a valid Unicode code point.

Raw strings

A string between backticks is raw: backslashes and braces are ordinary characters, and it may span lines. It cannot contain a backtick. Raw strings suit regular expressions, Windows paths and embedded JSON.

print(`C:\temp\{name}`)       # C:\temp\{name}
var digits = `\d+(\.\d+)?`
var config = `{"port": 8080}`
var text = `first line
second line`
print(text.size)               # 22

Line breaks in a raw string are always \n, even in a file saved with CRLF line endings.

size counts Unicode characters, not bytes; it is a property, not a method. Strings iterate by character, and text[i] is the character at position i as a one-character string. A negative position counts from the end, and one outside the string raises IndexError. Strings are immutable, so text[i] = c is a TypeError.

var language = "Goblin"

for character in language {
    print(character)
}
print(language[0], language[-1]) # G n

Slicing

text[low:high] returns the characters from position low up to, but excluding, high. Positions count characters, as size does, and either bound may be omitted.

var text = "héllo, wörld"
print(text[:5])  # héllo
print(text[7:])  # wörld
print(text[1:2]) # é

Bounds are positions between characters, a negative one counting from the end (text[:-1] drops the last character). As for a list slice, a bound outside the text stops at its edge, so line[:80] is at most 80 characters and never raises.

Characters and code points

c.code_point is the Unicode code point of a string's first character, as an Int, and nil for the empty string. Indexing or iterating a string gives one-character strings, which is where it is used. In the other direction, n.to_char() is the one-character string for the code point n; it raises ValueError for a number outside 0 to 0x10FFFF or a surrogate (0xD800–0xDFFF).

print("A".code_point)      # 65
print("é".code_point)      # 233
print("".code_point)       # nil
print((97).to_char())      # a
print(0x1F600.to_char())   # 😀

func rot13(c) {
    if c >= "a" && c <= "z" {
        return ((c.code_point - 97 + 13) % 26 + 97).to_char()
    }
    return c
}
print(List("hello").map(rot13).join(""))   # uryyb

A decimal integer literal needs parentheses before a method, (97).to_char(): written 97.to_char() it reads as the start of a float. A variable or a hexadecimal literal needs none.

Combining and converting text

Use + to concatenate two strings. Both operands must be strings: "item-" + 3 raises TypeError, because text that only looks like a number, such as a port read from the environment, would otherwise turn port + 1 into "80801" without an error. Put the value in an interpolation or convert it with String(x) first. * repeats a string by an integer count, in either operand order; a negative count raises ValueError.

print("go" + "blin")      # goblin
print("item-{3}")         # item-3
print("item-" + String(3)) # item-3
print("ha" * 3)           # hahaha
print(3 * "ha")           # hahaha

String(value) converts any value to its display text, the same text print shows and interpolation inserts. Interpolation is usually the clearer way to build a string from other values.

var port = 8080
print("port=" + String(port)) # port=8080
print("port={port}")       # port=8080

Bytes become text in two ways: data.decode() reads them as UTF-8 text, and data.to_hex() spells each byte as two lower-case hexadecimal digits, which is how a digest or a random token is usually printed.

print(Bytes([104, 105]).decode()) # hi
print(Bytes([0, 255]).to_hex())   # 00ff

Common string methods

MethodPurpose
sizeCharacter count (property)
upper() / lower()Change letter case
contains(value)Test for a substring
has_prefix(prefix) / has_suffix(suffix)Test the beginning or end
index(value, start=0)Character position of a substring, or nil
count(value)Count non-overlapping occurrences
replace(old, new, count=nil)Replace occurrences, at most count of them
split(sep=nil, count=nil)Split into a list, at most count times
lines()The lines of the text, without their line endings
cut(sep)Split once: [before, after], or [text, nil]
trim(chars=nil) / trim_start(chars=nil) / trim_end(chars=nil)Trim both ends, the start, or the end
trim_prefix(prefix) / trim_suffix(suffix)Remove one matching edge

Methods accept named arguments as well as positional ones.

var title = "  Goblin book  "
print(title.trim().upper())
print("a,b,c".split(sep=",", count=1))   # ["a", "b,c"]
print("one one one".replace(old="one", new="two", count=2))
print("config.toml".trim_suffix(".toml"))

index() counts characters, like text[i], and returns nil when the substring is absent; start is a position from -size to size. Position 0 is false in a condition, so test the result with != nil, or use contains().

count on replace() and split() is how many times the operation runs; leaving it out (or passing nil) means no limit, and a negative count raises ValueError. So split(",", count=1) gives at most two pieces. split() without a separator splits at runs of Unicode whitespace and drops empty pieces: " a b ".split() is ["a", "b"]; with a count, the rest of the text after the last split, leading whitespace removed, is the final piece. An empty separator raises ValueError, and so does an empty old in replace(), which would otherwise match between every two characters.

lines() is how text becomes its lines: a line ends at \n or \r\n (a lone \r does not end one), the endings are removed, text that ends with a line ending has no empty last line, and "" has no lines at all. That makes it the right call for the output of a command or the body of a file read whole, where split("\n") would leave a last "":

print("a\nb\n".lines())        # ["a", "b"]
print("a\r\n\nb".lines())      # ["a", "", "b"]
print("".lines())               # []
print("a\nb\n".split("\n"))    # ["a", "b", ""]

cut() returns two values, so it destructures:

var key, value = "port=80".cut("=")
print(key, value)               # port 80
print("port".cut("="))          # ["port", nil]

trim() with no argument removes Unicode whitespace. Supplying chars trims any of its characters, not an exact substring; trim_start() and trim_end() do the same at one end. Use trim_prefix() or trim_suffix() to remove an exact substring.

To repeat text use *; to find the last occurrence of a separator, split and take .last, or use the regex module; to split at whitespace use split() without a separator.

Common text-processing patterns

Use trim() before validating user-supplied text, split() to turn a delimited setting into a list, and replace() when normalizing a known spelling or format.

var raw_tags = " go, language,tools "
var tags = []
for tag in raw_tags.split(",") {
    tags.push(tag.trim())
}
print(tags)

var filename = "report.TXT"
if filename.lower().has_suffix(".txt") {
    print("text file")
}

Use contains() when a yes/no answer is enough, and index() when you need the position.

Collections

Lists and dictionaries are mutable collections. Their elements can have mixed runtime types. Empty collections are false in conditions.

Lists

Create a list with square brackets. Indexes begin at zero, and a negative index counts from the end: -1 is the last element and -size the first.

var tasks = ["write", "test"]
print(tasks[0])
tasks[-1] = "review"
tasks.push("ship")
print(tasks.pop())

An index outside -size <= i < size raises IndexError. The + operator makes a new concatenated list; push(), reverse(), sort(), and clear() change the current list.

var first = [1, 2]
var combined = first + [3, 4]
print(combined) # [1, 2, 3, 4]

Printing a collection shows each String element quoted, so ["a, b"] and ["a", "b"] print differently. A value whose own display is bare text shows its type around that text inside a collection, for the same reason: a Path as Path("a b"), an error as ValueError("bad input") (see Errors).

Slicing

list[low:high] makes a new list of the elements from index low up to, but excluding, high. Either bound may be left out: low defaults to the start and high to the end.

var numbers = [10, 20, 30, 40, 50]
print(numbers[1:3]) # [20, 30]
print(numbers[:2])  # [10, 20]
print(numbers[3:])  # [40, 50]
print(numbers[:])   # a copy of the whole list

A slice is a copy, so changing it never changes the list it came from. A bound names a position between elements, so it may also equal the size; like an index, a negative bound counts from the end, so numbers[:-1] drops the last element and numbers[-2:] keeps the last two. A slice takes the elements that exist between its bounds: a bound past either end of the list stops at that end, and a low that ends up past high gives an empty list. That makes "the first three" and "the last ten" one slice whatever the size:

var scores = [95, 70]
print(scores[:3])   # [95, 70]
print(scores[-10:]) # [95, 70]
print(scores[5:])   # []

Indexing is stricter: scores[2] names an element that is not there and raises IndexError. Strings and Bytes are sliced the same way. A slice cannot be assigned to.

The same two kinds of position appear in methods: pop() takes an element index, while insert() and the start of index() take a bound, so list.insert(list.size, value) appends.

List method guide

MethodPurpose
sizeNumber of elements (property)
first / lastThe first or last element, or nil for an empty list (properties)
push(value, ...)Append one or more values
pop(index=-1)Remove and return an element; defaults to the last
insert(index, value)Insert before a position; size appends
remove(value)Remove the first matching value, if there is one
clear()Remove every element
reverse()Reverse the order in place
sort(key=nil, descending=false)Sort in place, stably
copy()A new list with the same elements
contains(value) / count(value)Test for or count a value
index(value, start=0)Position of the first matching value, or nil
find(fn)The first element fn is true for, or nil
join(sep="")Join the elements' text, or Bytes with a Bytes separator
map(fn) / filter(fn) / reduce(fn, initial)Transform, select or combine elements
any(fn=nil) / all(fn=nil)Whether some or every element (or fn of it) is true

Every method that changes the list (push, insert, remove, clear, reverse and sort) returns the list itself, so calls chain: names.push("Cy").sort().reverse(). pop() is the exception: it returns the element it removed, and raises IndexError for an empty list. pop() accepts a negative index, so its default -1 removes the last element. first and last are nil for an empty list, and remove() of a value that is not there does nothing.

index() returns nil when a value is absent. Position 0 is false in a condition, so test the result with != nil, or use contains() when the position does not matter.

sort() is always stable: elements that compare equal (or whose keys do) keep their order, with descending=true as well. descending must be a Bool. key is called once per element, before any comparison, and the list is changed only when the whole sort succeeds: a key or a comparison that raises leaves the list as it was. That includes a NaN among the elements or the keys, which raises ValueError cannot order NaN (see Numbers). Arguments that are functions (fn, key) accept any callable value: a function, a constructor such as Int, a bound method, or an error kind (messages.map(ValueError) makes one error per message). They are checked when the method is called, so xs.map(1) raises TypeError: map() argument 'fn' must be callable, got Int before doing anything.

Common list patterns

Use push() while building a result, pop() when processing a work stack, and copy() before an operation that should not change the original list.

var names = ["Ada", "Linus", "Grace"]
var greetings = []
for name in names {
    greetings.push("Hello, " + name)
}
print(greetings.join(" | "))

var original = [3, 1, 2]
var ordered = original.copy().sort()
print(original) # [3, 1, 2]
print(ordered)  # [1, 2, 3]

Use contains() for membership tests. Use index() when the position matters; check for a missing value before using its result as an index.

Lists compare lexicographically with <, <=, > and >=: the first unequal pair of elements decides, and a list that is a prefix of another sorts first. This makes a list a convenient sort key over several fields:

var people = [["Bo", 30], ["Al", 30], ["Cy", 25]]
people.sort(key=func(p) { return [p[1], p[0]] })
print(people) # [["Cy", 25], ["Al", 30], ["Bo", 30]]

Transforming lists with callbacks

Lists also provide callback-based helpers. map() returns transformed values, filter() keeps values whose callback is truthy, and reduce() combines values from left to right. find() returns the first matching value or nil. To run a callback for its side effect, write a for loop.

var values = [1, 2, 3, 4]
var squares = values.map(func(value) { return value * value })
var large = values.filter(func(value) { return value > 2 })
var total = values.reduce(func(acc, value) { return acc + value }, 0)

print(squares) # [1, 4, 9, 16]
print(large)   # [3, 4]
print(total)   # 10

Callbacks receive one list element, except reduce(), whose callback receives the accumulator followed by the element. Without an initial value, reduce() uses the first list element and raises ValueError for an empty list. any() and all() accept an optional callback; with none, they test each element's truthiness. To add up the elements, use the global sum(values); max and min likewise take a list (see Built-in functions).

Dictionaries

Create a dictionary with key: value pairs. Read and write through a key.

var user = {"name": "Ada", "age": 36}
print(user["name"])
user["active"] = true
print(user.get("role", default="reader"))

Keys may be strings, Bytes, integers, floats, booleans, nil, or any other value that implements Hashable. Key identity follows ==: keys of different types stay distinct (d[1] and d["1"] are separate entries), while equal numbers name the same entry (d[1] and d[1.0] are one key). Values whose equality is identity, such as functions, error kinds and channels, hash by identity. Standard library values like Time, Path and URL hash by the value they compare equal on. Using a list, dictionary, or a user type without an impl Hashable as a key raises TypeError.

NaN is the one exception to "key identity follows ==": nan == nan is false, yet every NaN names the same entry, so d[Float("nan")] finds what d[math.NAN] stored and d.contains(nan) is true. Following == would make a NaN key impossible to look up again and let each write add another entry. [nan].contains(nan) stays false, since a list tests with ==.

Looking up a missing key with dictionary[key] raises KeyError. Use get() when a missing value is expected. Dictionary iteration yields keys; items() yields two-element [key, value] lists, which a loop can destructure.

A dictionary remembers insertion order: iteration, keys(), values(), items(), copy(), update() and printing all list the keys in the order they were first written. Writing to a key that is already present keeps its place; removing a key and writing it again moves it to the end. Equality ignores order, so {"a": 1, "b": 2} == {"b": 2, "a": 1}.

var settings = {}
settings.get_or_set("theme", "dark")
for key, value in settings.items() {
    print(key, value)
}

Dictionary method guide

MethodPurpose
sizeNumber of entries (property)
contains(key)Test whether a key exists
get(key, default=nil)Read a key without raising for a missing key
get_or_set(key, default)Get an existing value, or store default and return it
keys() / values() / items()Return lists of keys, values, or key/value pairs
pop(key, default)Remove and return a value; KeyError without a default
remove(key)Remove a key if it is present
update(other)Copy entries from another dictionary
copy() / clear()Duplicate or empty the dictionary

remove(), update() and clear() return the dictionary itself, so they chain.

List() and Dict() construct the corresponding collections. See Control flow for iteration.

Common dictionary patterns

Use get() to read optional configuration, get_or_set() to initialize a value once, and update() to merge a set of overrides into a base dictionary.

var defaults = {"host": "127.0.0.1", "port": 8080}
var overrides = {"port": 3000}
defaults.update(overrides)
print(defaults["port"]) # 3000

var counts = {}
for word in ["go", "goblin", "go"] {
    var current = counts.get(word, default=0)
    counts[word] = current + 1
}
print(counts["go"]) # 2

Use keys(), values(), or items() only when a list snapshot is useful. For a simple dictionary traversal, iterate the dictionary itself and look up each value by its key.

Types and methods

type defines a custom type with fields and methods. The parentheses list fields supplied at construction; a field may have a default value. Every method must declare self as its first parameter. Type definitions belong at module scope, not inside a function or a control-flow block.

type Point(x, y=0) {
    func move(self, dx, dy) {
        self.x = self.x + dx
        self.y = self.y + dy
    }

    func text(self) {
        return "(" + String(self.x) + ", " + String(self.y) + ")"
    }
}

var p = Point(1)
p.move(2, 3)
print(p.text())

Instance fields can be read and updated directly. Construction accepts both positional and named arguments:

var origin = Point(x=0, y=0)
origin.x = 10

Required fields must come before fields with defaults. Calling a type requires all required fields exactly once; named arguments make construction clearer when a type has several fields.

Methods and state

Methods are ordinary functions attached to a type. They can read or replace fields through self, and methods may call other methods on the same instance.

type Counter(value=0) {
    func increment(self) {
        self.value = self.value + 1
        return self.value
    }
}

var counter = Counter()
print(counter.increment()) # 1
print(counter.increment()) # 2

An instance has exactly the fields and methods its type declares; it cannot grow new ones. Where the type of a value is certain, a misspelled name is reported before the program runs instead of raising AttributeError when the line is reached:

type Counter(value=0) {
    func reset(self) {
        self.valeu = 0      # error: Counter has no attribute 'valeu'
    }
}

var counter = Counter()
print(counter.total)        # error: Counter has no attribute 'total'
counter.reset(1)            # error: Counter.reset() takes 0 positional arguments, got 1

The type is certain for self inside the type's own methods and impl blocks, for a construction such as Counter().value, and for a variable declared with a construction and never assigned again. A value that arrives any other way, such as a parameter or a list element, is checked when the access runs.

Operators and conversions

A type takes part in operators, comparison, printing, conditions, loops and indexing by implementing protocols in impl blocks inside its body. An empty impl of Eq, Ord, Hashable or Show derives the behavior from the fields:

type Vector(x, y) {
    impl Eq {}
    impl Show {}
    impl Add {
        func add(self, other) {
            return Vector(self.x + other.x, self.y + other.y)
        }
    }
}

print(Vector(1, 2) + Vector(3, 4))      # Vector(x=4, y=6)
print(Vector(1, 2) == Vector(1, 2))     # true

Without any impl, an instance is equal only to itself, prints as <Vector@0x...>, is always truthy, and raises TypeError for arithmetic, ordering, iteration and indexing. Protocols lists the protocols and what each one enables.

Checking a value's type

A type name such as Point is the constructor function for that type; it is not a separate type object, and there is no isinstance built-in. type_of(value) returns the function that builds values of the value's type, so comparing it answers "is this a Point":

type Point(x, y) {}

func describe(value) {
    if value == nil {
        return "nothing"
    }
    if type_of(value) == Point {
        return "a point"
    }
    if type_of(value) == Int || type_of(value) == Float {
        return "a number"
    }
    return "something else"
}

print(describe(Point(1, 2)))  # a point
print(describe(2.5))          # a number
print(describe(nil))          # nothing

Built-in values answer with the conversion functions: Int, Float, String, Bool, Bytes, List, Dict, Function and Chan, and an error answers Error, the base error kind. A value whose type has no constructor (nil, a module, a Goblin handle) answers a stand-in that still compares equal across values of that type and has its name, such as type_of(nil).name == "Nil". There is no question for behaviour, such as whether a value implements a protocol: use the operation itself, or compare type_of(value) with the type you expect.

Protocols

impl connects a type to the language's syntax; everything else is an ordinary method.

type Money(amount) {
    impl Eq {}                                  # structural
    impl Ord {
        func compare(self, other) { return self.amount - other.amount }
    }
    impl Show {
        func show(self) { return "${self.amount}" }
    }
    func to_json(self) { return self.amount }   # a method the library asks for
}

var prices = [Money(5), Money(2), Money(9)]
print(prices.sort())                    # [$2, $5, $9]
print(Money(2) < Money(5), max(prices)) # true $9

A protocol is one of thirteen fixed names. Each connects a type to a piece of syntax or a built-in conversion: implement Ord and <, sort, max and compare work on the type; implement Add and + does. The set is closed: a program cannot declare a protocol, and neither can a library.

Implementing a protocol

An impl block sits inside a type body, among the ordinary methods, in any order: impl Name { ... }. A type has at most one impl per protocol. The block defines the protocol's methods, each with self first and a fixed parameter list: no defaults, *args or **kwargs.

The name after impl is never looked up as a variable. The thirteen names are not globals and have no value (print(Eq) is undefined identifier: Eq), so a program may use them for its own things, and impl Show still means the protocol in a module that declares type Show(...). Any other name is an error when the type is defined:

impl Shape for Rect: Shape is not a protocol (protocols: Eq, Ord, Hashable,
Show, Truth, Add, Sub, Mul, Div, Mod, Neg, Iter, Index); other methods go
directly in the type body

Protocol methods never become attributes of the instance: an ordinary method or field may reuse a protocol method's name, so a type can have a get method of its own beside impl Index { func get(self, i) { ... } }, and p.add(x) calls the ordinary add, not +. A protocol method is reached through its syntax. compare(a, b) and hash(x) are the global functions for the two that have none.

ProtocolRequiredOptionalEnablesEmpty impl
Eqeq(self, other)==, !=structural
Ord (needs Eq)compare(self, other)<, <=, >, >=, sort, max, min, comparestructural
Hashable (needs Eq)hash(self)dict keys, hashstructural
Showshow(self)print, String, interpolationstructural
Truthtruth(self)if, while, &&, ||, !, Boolnot allowed
Add Sub Mul Div Modadd sub mul div mod (self, other)radd rsub rmul rdiv rmod (self, other)+ - * / %not allowed
Negneg(self)unary -not allowed
Iteriter(self)for x in value, List(value)not allowed
Indexget(self, index)set(self, index, value)value[i], value[i] = xnot allowed

One required method gives a whole family that cannot disagree: compare is the only ordering method, so <, sort and max always agree, and != is always the negation of ==. A method the protocol does not list is an error (impl Ord for Point: Ord has no method 'lt'), as are a missing required method (impl Truth for Flag is missing method 'truth'), a wrong parameter count, and a missing dependency (impl Ord for Point requires impl Eq). All of them are reported when the type is defined, before any value exists.

compare and hash must return an Int, show a String, and eq and truth a Bool; anything else raises TypeError: Point.show must return String, got Int when the method runs.

Without an impl, the defaults are: == is identity, printing shows <Point@0x...>, a value is truthy, and ordering, arithmetic, iteration, indexing and use as a dict key raise TypeError, which says what to add: cannot hash Point (add 'impl Hashable' to type Point).

Structural implementations

An empty impl of Eq, Ord, Hashable or Show gets the structural implementation, which works on the fields in declaration order:

  • Eq: equal when the other value has the same type and every field pair is equal.
  • Ord: lexicographic, the first unequal field pair decides.
  • Hashable: combines the type and the hash of every field. A field that is not hashable, such as a List, raises TypeError when the value is hashed.
  • Show: Point(x=1, y="a"), with fields rendered the way collections render their elements.

A structural Ord or Hashable must sit on a structural Eq: a structural hash cannot know which fields a custom eq ignores. The checker reports structural Hashable requires structural Eq on Point otherwise.

Eq and Ord

Ord depends on Eq, and like every dependency the type implements it explicitly. A structural Ord pairs with impl Eq {}; a custom compare usually pairs with an eq that asks it, as Money does below, so that == agrees with the ordering.

a == b with a user type is answered in this order:

  1. When either operand is nil, the answer is true only if both are, and no eq is called. So x == nil is a safe test whatever an eq does with other, and so are contains(nil), index(nil), count(nil) and remove(nil).
  2. When a and b are the same object, the answer is true without calling eq: a value is always equal to itself.
  3. Otherwise the left operand's eq is asked, and the Bool it returns is the answer, false included.
  4. The right operand's eq is asked only when the left one has no eq for the pair: it is a built-in value or a type without impl Eq, or its eq raised TypeError. This is how 5 == money reaches Money's eq. Without an eq on either side the two are unequal.

A TypeError raised inside an eq therefore means "I cannot compare with that", never a failure of ==; any other error propagates. An eq that reads fields of other should still check other's type when values of other types can reach it (type_of(other) == Money), or raise TypeError for them, since only nil is filtered out before eq runs. != is always the negation of ==.

The ordering operators, sort, and the built-in compare, max and min all order through compare. When the left operand cannot order the pair, the right operand's compare answers with the result negated, which is how 10 > money reaches Money's impl:

type Money(amount) {
    impl Eq {
        func eq(self, other) {
            return compare(self, other) == 0
        }
    }
    impl Ord {
        func compare(self, other) {
            return self.amount - other
        }
    }
}

var m = Money(5)
print(m < 10)                           # true
print(10 > m)                           # true, answered by Money's compare
print(m == 5)                           # true, answered by Money's eq

Goblin cannot check the laws these protocols rely on, so keep them yourself: a custom hash must agree with eq (equal values hash alike), and compare must be antisymmetric and transitive.

Arithmetic

Each arithmetic operator has a protocol of its own, so a type implements exactly the operators it supports; a missing one raises the usual cannot add Point TypeError. No operator is derived from another: Add and Neg do not give a type -.

A binary protocol requires the method for the value on the left. Its reflected method (radd, rsub, ...) is optional and runs when the value is on the right of an operand that does not know it, with that left operand as the argument. Only a left operand reporting a type mismatch hands over to it, and without the reflected method the left operand's error stands:

type Vector(x, y) {
    impl Sub {
        func sub(self, other) {
            return Vector(self.x - other.x, self.y - other.y)
        }
    }
    impl Neg {
        func neg(self) {
            return Vector(-self.x, -self.y)
        }
    }
    impl Mul {
        func mul(self, k) {
            return Vector(self.x * k, self.y * k)
        }
        func rmul(self, k) {
            return Vector(k * self.x, k * self.y)
        }
    }
    impl Show {}
}

var v = Vector(1, 2)
print(v - Vector(1, 1))                 # Vector(x=0, y=1)
print(2 * v)                            # Vector(x=2, y=4)
print(-v)                               # Vector(x=-1, y=-2)

Built-in sequences follow the same rule, so 3 * "ab" works like "ab" * 3.

Truth, Iter and Index

A truth method decides every condition and Bool(value); !value is always its negation. An iter method returns any iterable value — a List, a String, a file, another value with an Iter impl — and for visits what iterating that value visits. A lazy value stays lazy: a type whose iter returns an open file reads it line by line. An Index impl's get backs value[i]; an impl without set is read-only, and assigning raises TypeError: Grid does not support index assignment.

Methods the library asks for

Library functions that need something from a value ask for an ordinary method by name, not for a protocol: read(size) for something readable, write(data) for something writable, and to_json() for a value json should encode. Define them directly in the type body; there is nothing to import or implement.

Errors

Errors are values. Use raise to stop normal execution with an error and try / catch to recover at a boundary that can make a useful decision.

func divide(a, b) {
    if b == 0 {
        raise ZeroDivisionError("cannot divide {a} by zero")
    }
    return a / b
}

try {
    print(divide(10, 0))
} catch err: ZeroDivisionError {
    print(err.message)   # cannot divide 10 by zero
}

The name after catch is local to its catch block. When no error is raised, the catch block is skipped. An unhandled error stops the program and prints a traceback.

Creating and matching errors

There are two ways to derive an error, and they have different jobs:

  • Call a kind to report a new failure of that kind. ValueError("invalid port: {s}") is an error whose message is exactly that and whose cause is ValueError, so it matches ValueError (and its parent kinds).
  • Wrap an error that already happened to add context. err.wrap("loading profile") is an error whose message is "loading profile: " followed by the original message, and whose cause is the original error.

Error is the base kind, the one every other kind descends from, so Error("message") creates an error of the base kind and nothing more specific: its cause is Error. Any error can serve as a kind: a kind is simply an error you call or test for. Use one when callers need to tell a particular failure apart from unrelated errors.

var ConfigError = ValueError("ConfigError")   # a kind of your own, a ValueError
var not_found = Error("not found")            # a sentinel, raised as it is

func load_user(id) {
    if id == 0 {
        raise not_found
    }
    return {"id": id}
}

try {
    load_user(0)
} catch err: not_found {
    print("choose another user")
}

var err = ConfigError("missing field 'name'")
print(err.message)           # missing field 'name'
print(err.is(ConfigError))   # true
print(err.is(ValueError))    # true

Calling a kind with no message keeps the kind's own: ValueError().message is ValueError, and Error().message is Error.

A kind is callable like any constructor, so it can be passed wherever a function is expected: ["bad port", "bad host"].map(ConfigError) makes one ConfigError per message, and Function(ValueError) returns the kind itself.

The cause property is the next error down the chain, and is() tests the complete chain, the error itself included.

var base = Error("connection failed")
var err = base.wrap("loading profile")
print(err.message)       # loading profile: connection failed
print(err.cause.message) # connection failed
print(err.cause == base) # true
print(err.is(base))      # true
print(base.cause)        # Error
print(Error.cause)       # nil

The chain continues through error kinds: a kind's cause is its parent kind, so IndexError.cause == LookupError. Every chain ends at the base kind Error, the only error whose cause is nil. A failure reported by a library module carries its kind one level down: when fs.read fails, e.message describes what failed, e.cause is the operating system's own error (open nope.txt: no such file or directory), and e.cause.is(NotExistError) is true, as is e.is(NotExistError).

The error a catch binds is the error that was raised, however many calls it passed through on the way: e == not_found and e.cause give the same answer for a raise at module level and one three functions deep. Errors compare and hash by identity, so a sentinel can key a dictionary and a caught error finds its entry.

Catching by kind

catch e: Kind { ... } handles an error only when e.is(Kind) is true; catch e { ... } handles any error. e.is(Error) is true for every error, including the runtime's own failures and wrapped errors, so catch e: Error and catch e handle the same errors. A try can have several clauses. They are tested from top to bottom, and the first that matches runs; the others are skipped.

try {
    var text = fs.read(path)
} catch e: NotExistError {
    print("no file yet")
} catch e: PermissionError {
    raise e.wrap("fix the permissions of {path}")
} catch e {
    eprint("unexpected: {e}")
    raise e
}
  • When no clause matches, the error continues outward unchanged: the same error value with the same traceback, exactly as if there were no try.
  • The kind can be any expression (NotExistError, not_found, kinds[i]). It is evaluated only when an error reaches its clause, in the scope around the try; the clause's own variable is not visible in it. A kind that is not an Error raises TypeError: catch expects an Error to match, got Int in place of the error being handled, and so does any error raised while evaluating the kind.
  • A clause without a kind catches everything, so it must be the last one: catch after a catch-all clause can never run is reported when the program is parsed.
  • os.exit() is not an error: no catch clause receives it, with or without a kind, catch e: Error included.
  • Each clause has its own variable and scope; clauses may use different names.
  • An error raised inside a clause body is not offered to the later clauses of the same try.

Errors with data

Keyword arguments given when an error is made are data, read back as attributes:

var ConfigError = ValueError("ConfigError")

try {
    raise ConfigError("missing field 'name'", field="name", line=3)
} catch e: ConfigError {
    print("{e.message} (line {e.line})")   # missing field 'name' (line 3)
    print(e.field)                          # name
}
  • e.name looks in the error's own data and then down its cause chain, the first hit winning. So a wrap between the raise and the catch does not hide the data, and data given to a kind (var Retryable = Error("retryable", retry=true)) is seen on every error made from it.
  • A name that is not there is the usual AttributeError: Error has no attribute 'code'. To probe an error of unknown kind, use attributes(e).contains("code"); it lists the built-in members and then the data names, nearest first.
  • Data cannot be changed once the error is made, and the built-in members traceback, cause, wrap and is cannot be data names (ValueError: Error() cannot use 'cause' as a data name).
  • Data is for code: print(e), e.message and the traceback show only the message.

How an error displays

print(e), String(e), interpolation and an uncaught error show the message alone. Inside a list, a dictionary or a structural impl Show {}, a bare message could not be told apart from a String, from a name, or (when empty) from nothing, so there an error shows as Kind("message"): Kind is the nearest built-in or library kind in its cause chain (ValueError, exec.ExitError, and Error when there is no other), and the message is quoted as a String element is. Such a kind itself shows as its bare name.

var ConfigError = ValueError("ConfigError")
var not_found = Error("not found")

print([ValueError("bad input"), "bad input", ValueError("")])
# [ValueError("bad input"), "bad input", ValueError("")]
print([ValueError, ConfigError, ConfigError("missing name")])
# [ValueError, ValueError("ConfigError"), ValueError("missing name")]
print([not_found, ValueError("bad").wrap("parsing")])
# [Error("not found"), ValueError("parsing: bad")]

An error a program uses as a kind of its own, such as ConfigError, and a sentinel such as not_found are errors like any other here: each shows with the built-in kind it was made from, and so do the errors made by calling them. The display does not guess from a message whether an error is meant as a kind. A wrapped error shows its full message with the kind of the error it wraps.

Error kinds

The runtime uses named error kinds. Raise one as it is, or call it to make an error of that kind with a message of your own. Every kind descends from the base kind Error; the table lists all of them with the kind each one directly descends from.

KindParentTypical cause
TypeErrorErrorAn operation receives an incompatible value
ValueErrorErrorA valid type has an invalid value
ParseErrorValueErrorInvalid JSON or other parsed input
LookupErrorErrorNot raised by the runtime directly; it groups the five kinds below it
IndexErrorLookupErrorA list index out of range
KeyErrorLookupErrorA missing dictionary key
AttributeErrorLookupErrorA missing member, such as a misspelled field
NameErrorLookupErrorA missing identifier
ImportErrorLookupErrorAn unavailable module
ArithmeticErrorErrorNot raised by the runtime directly; it groups the two kinds below it
ZeroDivisionErrorArithmeticErrorDivision or modulo by zero
OverflowErrorArithmeticErrorAn integer result that does not fit in 64 bits, or a number too large for its type
IOErrorErrorGeneric file, network, or operating-system failure
NotExistErrorIOErrorA missing filesystem path
ExistErrorIOErrorA filesystem path that already exists
PermissionErrorIOErrorAn inaccessible filesystem path
TimeoutErrorIOErrorA timeout= that ran out, with or without I/O: a channel's send or receive, a goblin's wait, wait_any, or a network request
NetworkErrorIOErrorA failed network operation (a connection refused, reset or unreachable, a broken pipe). A local file failure such as "is a directory" is a plain IOError
NotImplementedErrorErrorAn operation the runtime does not implement
RecursionErrorErrorRecursion, or comparing or printing nested values, too deep for the stack
InternalErrorErrorA failure inside the runtime itself, such as a Go panic in a goblin

A catch clause handles its kind and every kind below it. So catch e: LookupError also handles AttributeError, NameError and ImportError, which can come from a misspelled name rather than a missing entry; catch IndexError or KeyError when only a missing index or key is expected. Likewise catch e: IOError handles a TimeoutError from a channel or a goblin, not only one from the file system or the network.

An uncaught error prints its message, not its kind name, so give the errors you make a message that says what went wrong.

Cleaning up

There is no finally. To release something whether or not an error occurs, defer the release right after acquiring it: a deferred call runs when the function ends, including when an error is on its way out of it.

func load(path) {
    var file = fs.open(path)
    defer file.close()
    return parse(file.read())   # file.close() runs even if parse raises
}

See Deferred calls for the details.

Wrap errors where you can add useful context. Do not catch an error merely to discard it: name the kind you can handle, and let everything else pass through.

Concurrency

spawn(function, args...) starts a function in a new goroutine and returns a Goblin handle; wait() on the handle joins the function and delivers its result. Channels (Chan) carry streams of values between goroutines, and every blocking operation takes the same timeout= keyword. Those three are all there is: a Goblin handle stands for one running function, a Chan carries values from one goblin to another, and timeout= limits how long any blocking call waits.

func square(value) {
    return value * value
}

var worker = spawn(square, 6)
print(worker.wait()) # 36

Goblin handles

spawn starts the function right away; there is no separate start step. Arguments after the function, positional and keyword alike, are forwarded to it. A handle is only ever obtained from spawn: Goblin is the name of its type, not a function you can call.

OperationBehavior
spawn(function, args...)Start the function in a new goroutine and return a handle
handle.wait()Block until the function finishes, then return its result
handle.wait(timeout = seconds)Same, but raise TimeoutError if the function is still running when the timeout expires
handle.doneWhether the function has finished; reading it never blocks
wait_any(goblins, timeout = nil)Block until one of the goblins finishes and return its handle

The outcome is computed once and cached, so wait() can be called any number of times — and from several places at once — with the same answer. An error raised inside the function is stored and re-raised by every wait() call, where the normal try/catch machinery applies:

func fail() {
    raise ValueError("bad input")
}

var failing = spawn(fail)
try {
    failing.wait()
} catch err {
    print(err.is(ValueError)) # true
}

A handle you do not need can simply be dropped; spawn(log_visit, user) on a line of its own is fine. An error is still never lost: when the program ends normally, every goblin that failed without any wait() seeing its error is reported on stderr as uncaught error in goblin: <error>, in the order they failed. The report does not change the exit status. Goblins still running when the program ends are stopped mid-flight and not reported. The same holds when a goblin calls os.exit(): that goblin runs its deferred calls, every other goblin is stopped mid-flight, and failed goblins nobody waited for are not reported. The REPL makes the same report after each line it evaluates.

Waiting for the first of several

wait_any(goblins) takes any iterable of handles and returns the first one to finish. It does not take the result or raise the error; call wait() on the handle it returns for that. When several have already finished, it returns the one earliest in the list, so the answer is reproducible; which of several goblins finishing at the same moment it picks while it waits is not defined. An empty iterable raises ValueError, an element that is not a Goblin handle raises TypeError.

import "time"

func fetch(name, delay) {
    time.sleep(delay)
    return name
}

var jobs = [spawn(fetch, "slow", 1), spawn(fetch, "fast", 0.01)]
var first = wait_any(jobs, timeout = 5)
print(first.wait()) # fast

There is no cancellation: the goblins that did not finish first keep running until they return or the program ends.

Time limits

wait, send, receive and wait_any all take an optional timeout in seconds, an Int or a Float. When it expires the operation raises TimeoutError (receive() timed out after 2 seconds). nil, the default, waits forever; a negative timeout raises ValueError and any other type TypeError. An operation that can complete immediately always does, even with timeout = 0, so channel.receive(timeout = 0) means "take a value if one is ready".

Sharing data with a goblin

Pass data into a goblin through its arguments, and out through its return value or a channel. Two goblins — or a goblin and the top-level program — reading and writing the same variable concurrently is a data race: no ordering is defined, and the compiled backend inherits Go's undefined behavior for races. Reading surrounding names that nothing writes concurrently (module imports, top-level functions, builtins) is safe.

The same rule covers the inside of a shared mutable value: lists and dictionaries are not synchronized, and Goblin never locks them for you. The consequence of a race is not limited to stale or torn data — two goblins writing to the same dictionary can terminate the whole process at once, and try/catch cannot intercept that crash. When several goblins must work on the same data, keep one owner that mutates it and let the others send requests or results over a channel, as in the examples below.

goblin build-exe --race compiles the executable with Go's race detector: when a race actually occurs at run time, the program reports both racing operations with stack traces and exits with a failure status. The interpreter has no equivalent switch — race instrumentation happens when Go code is compiled — so a program that only ever ran under goblin run may hide a race that the compiled backend hits. Build the racy suspect with --race and exercise it when in doubt.

Channels

Chan() creates an unbuffered channel: a send waits until some goroutine receives it, and a receive waits until a value is sent. Chan(capacity = n) creates a buffer that can hold up to n values before sends block.

OperationBehavior
channel.send(value, timeout = nil)Blocks until a receiver is ready or buffer space exists
channel.receive(timeout = nil)Blocks until a value is available
channel.close()Prevents future sends; buffered values can still be received. Returns nil; closing a closed channel does nothing
for value in channelReceives values until the channel is closed and drained
Chan(capacity = 0)Requires an integer from 0 to 1000000; Go allocates the whole buffer when the channel is made

Sending on a closed channel, or calling receive() after a channel is closed and drained, raises ValueError. Closing a channel twice is allowed, as for a File, so defer ch.close() can stay in place beside an earlier explicit close.

A channel is iterable, and closing it is how a sender says the stream is over: a for loop receives one value per iteration and ends when the channel is closed and every buffered value has been received. Several loops iterating the same channel at once each receive different values.

var words = Chan(capacity = 16)
spawn(func() {
    defer words.close()
    for word in ["alpha", "beta", "gamma"] {
        words.send(word)
    }
})
for word in words {
    print(word)
}

Values from several channels are combined by forwarding them into one channel (a goblin per source, each looping over its own channel); there is no select.

Buffering a known number of results

Use a buffered channel when several workers can finish before the caller starts receiving. The buffer capacity here matches the number of results.

func square(value, result) {
    result.send(value * value)
}

var results = Chan(capacity = 3)
for value in [2, 3, 4] {
    spawn(square, value, results)
}

var total = 0
for ignored in range(3) {
    total = total + results.receive()
}
results.close()
print(total) # 29

An unbuffered results channel also works in this example because the caller begins receiving after it starts the workers. Buffering changes when sends block; it does not guarantee a result order. Do not rely on spawned work finishing in the order it was started. When each job has a single result, returning it and calling wait() on every handle is simpler still.

Returning errors explicitly

wait() re-raises a goblin's error at the call site, which covers the common case of one job whose failure the caller handles. When workers stream results through a channel instead, the caller receives values, not errors. Catch the error in the worker and send a result record when the caller needs to handle failures.

func load_number(text, result) {
    try {
        result.send({"value": Int(text), "error": nil})
    } catch err {
        result.send({"value": nil, "error": err})
    }
}

var result = Chan()
spawn(load_number, "not-a-number", result)
var outcome = result.receive()
if outcome["error"] {
    print(outcome["error"].message)
}
result.close()

Use a dictionary only as a small result record like this. For a repeated or larger protocol, define a custom type so the fields and methods are explicit.

Ownership and deadlocks

The code that knows no more values will be sent should close the channel. Do not close a channel while a spawned sender may still use it. A common deadlock is sending to an unbuffered channel in the same goroutine before starting a receiver:

var messages = Chan()
# messages.send("hello") would block here: no receiver can run yet.
spawn(func() { messages.send("hello") })
print(messages.receive())
messages.close()

Goblin has no select operation and no cancellation primitive. Design each concurrent operation so every blocking send has a receiver, every expected result is received, and the owner can decide when it is safe to close its channel; where waiting forever would be a bug, give the operation a timeout.

Troubleshooting

When a program fails, first identify which stage reported the problem. The message and traceback include the source location.

SymptomLikely causeWhat to check
Parse errorSyntax the grammar does not acceptBraces, commas, string escapes, and function parameter syntax
Semantic errorA name, declaration, or statement is invalid in its scope, or a call or attribute can never succeedDeclare names before use; keep import/type/export at module scope; compare the call with the function's parameters and the attribute with the type's fields
NameError / AttributeErrorA runtime name or member is unavailableSpelling, module import, and attributes(value) in the REPL
TypeErrorAn operation received an unsupported value typeConstructor inputs, callback return values, and operator operands
IndexError / KeyErrorA list index or dictionary key is absentBounds checks, dict.get(), and list.index() returning nil
A found value is treated as missingindex() returned position 0, which is false in a conditionCompare the result with != nil, or use contains()
ValueError from split() or replace()An empty separator or a negative countLeave count out for no limit; use List(text) for characters
IOError / NetworkErrorA filesystem or HTTP operation failedPaths, permissions, connectivity, and a try/catch recovery boundary
invalid format specifier ".2": precision needs 'f' or 'e'A precision without a type letter in "{x:.2}"Write {x:.2f} for decimals or {x:.2e} for scientific notation

A reliable debugging loop

Reduce the failing code to a small .goblin file, then run it through the interpreter:

goblin run failing.goblin

Use goblin repl for inspecting values. attributes(value) lists the operations an object exposes, which is particularly useful for module values, responses, files, and custom types.

If build-exe fails after a program works with run, verify that the Go toolchain is installed and run the command again with the generated-build message visible. Report the Goblin source, command, full error text, and whether the interpreter path succeeds when filing an issue.

build-exe compiles against the same published Goblin runtime version as the installed CLI unless it finds a local source checkout (from the working directory or the executable's location). Development builds without embedded module-version information use a pinned runtime fallback. When developing Goblin itself, set GOBLIN_ROOT to the checkout path so compiled programs use your local runtime.

Standard library

Goblin's standard library provides modules for common program boundaries: files and paths, environment variables, external commands, time, data formats, digests, compression and archives, networking, random values, and mathematics. Import a module at module scope, then access its members with dot notation.

import "json"
import "fs"

var cwd = fs.cwd()
var text = json.encode({"cwd": String(cwd)})
print(text)

The standard library is separate from Goblin's built-in functions and types. For example, print(), eprint(), range(), Int(), List(), Dict(), and Chan() are available without an import. Import a module only when its capabilities are needed.

Modules

ModuleMain purposeStart with
jsonJSON text to values and backencode(), decode()
fsFiles, directories and path namesread(), write(), Path()
osArguments, environment, standard streams, exitargs, env, stdin, exit()
cliCommand-line arguments, options, help and usage errorsparse(), Option(), Flag(), Command()
execRun other programsrun(), capture(), start()
timeInstants, the clock, time zones, sleepingnow(), parse(), Time(), sleep()
randRandom choices, secure bytes and ids, reproducible on requestchoice(), int(), bytes(), uuid(), Rand()
mathFloat functions, constants and basic statisticsPI, sqrt(), round(), mean()
httpHTTP client: messages, requests, sessions, uploads, streamed bodiesget(), request(), send(), Request(), Client()
regexSearch and rewrite text by patternfind(), find_all(), replace(), split()
urlTake a URL apart, escape its parts, change its queryparse(), encode_query(), decode_query(), query_values()
csvCSV text to rows and backdecode(), decode_dicts(), encode(), read_rows()
hashDigests of data: checksums and HMAC signaturessha256(), hmac()
base64Bytes as Base64 text and backencode(), decode()
gzipGzip data, in memory and as files of any sizecompress(), decompress(), open(), read_lines()
zipZip archives: list, read one member, unpack safely, packextract(), open(), create()
tarTar archives, plain or gzip-compressed, from files or streamsextract(), open(), create(), Reader()

Imports and errors

Standard-library module names are single words ("json", "fs") and never start with "./" or "../". Local source modules use a relative import such as "./modules/greeter"; those are documented in Modules and imports because they use the same import syntax.

Most standard-library operations that touch the outside world can fail. JSON parsing may raise ParseError, a missing file may raise an I/O-related error, and HTTP requests may fail. Use try/catch around work that your program can recover from; see Errors.

Choosing a module

Use json whenever a program boundary expects JSON rather than trying to build JSON text manually. Prefer fs for simple whole-file reads and writes, and use its open() function when a file object is needed. Use fs.cwd() or fs.home() instead of assuming a current directory. Use time.sleep() only for intentional delays, and use Chan plus spawn() for communication between concurrent Goblin functions.

Each module has its own chapter in this section, with a focused API reference and example.

Reading API signatures

Examples and tables use name(required, optional=value) to show argument order and defaults. Square brackets mean an argument may be omitted, as in Chan([size]). They do not promise that named arguments are accepted: a function's chapter calls out positional-only APIs where that matters.

Unless a chapter says otherwise, a function that touches files, the operating system, or the network can raise an error value. Wrap the smallest useful boundary in try/catch, then add context or recover deliberately.

Modules and imports

A module groups related values. Import statements belong at module scope. An imported name is the final component of its path.

import "json"
import "./modules/greeter"

print(json.encode({"ok": true}))
greeter.greet("world")

Local modules

Local paths must start with ./ or ../ and are resolved relative to the file that imports them; any other path names a standard-library module (like "json"). Omit the .goblin suffix. A local module chooses its public names with export.

# modules/greeter.goblin
var greeting = "Hello"

func greet(name) {
    print(greeting, name)
}

export greet

Names without export remain private. Define a module-level name before code that uses it; this also applies to names referenced from an exported function. Named functions may call themselves recursively.

An exported name is a live binding, not a copy: reading counter.count gives the module's variable count as it is at that moment, including assignments the module makes after its export statement or later from its own functions. Only the module itself can assign its variables; counter.count = 10 from outside raises TypeError (Module does not support attribute assignment).

# counter.goblin
var count = 0

func bump() {
    count = count + 1
    return count
}

export count
export bump
# main.goblin
import "./counter"

print(counter.bump(), counter.count, counter.bump(), counter.count)   # 1 1 2 2

A complete local module

For a small project, keep the entry point and local module in separate files:

project/
├── main.goblin
└── modules/
    └── greeter.goblin
# modules/greeter.goblin
var greeting = "Hello"

func greet(name) {
    return greeting + ", " + name
}

export greet
# main.goblin
import "./modules/greeter"

print(greeter.greet("world"))

Run the entry point from project/ with goblin run main.goblin. Local import paths are resolved from the importing file, not from the shell's current directory. A local import's final path component becomes its module name, so ./modules/greeter is available as greeter.

A module is loaded once and cached; later imports of the same file reuse the loaded module, so every module that imports it sees the same variables. Two modules importing each other is a cycle, reported as circular import detected.

The remaining chapters document each built-in module separately.

json

The json module turns JSON text into Goblin values and back: loading a configuration file, calling an API, writing a report. It has two functions, encode and decode, and works on one whole document at a time.

Common tasks

import "fs"
import "http"
import "json"
import "os"

# Load configuration
var config = json.decode(fs.read("config.json"))
var port = config.get("port", default=8080)

# Save a report, readable by people
fs.write("report.json", json.encode(report, indent=2))

# One JSON document per line
for line in fs.read_lines("events.jsonl") {
    var event = json.decode(line)
    print(event["type"])
}

# Write one JSON document per line
var log = fs.open("events.jsonl", append=true)
defer log.close()
for event in events {
    log.write(json.encode(event) + "\n")
}

# Values JSON has no form for: choose the form where you encode
var entry = {"file": String(path), "at": started.format("%Y-%m-%d"), "size": size}
fs.write("entry.json", json.encode(entry))

# Straight from a stream
var user = json.decode(http.get("https://api.example.com/me").body)

# Your own types
type Point(x, y) {
    func to_json(self) {
        return {"x": self.x, "y": self.y}
    }
}
print(json.encode([Point(1, 2)]))      # [{"x":1,"y":2}]

# Bad input: say where
try {
    config = json.decode(fs.read("config.json"))
} catch e: ParseError {
    eprint("config.json:{e.line}:{e.column}: {e.message}")
    os.exit(1)
}

examples/json.goblin runs each of these tasks except the request, which examples/httpserver/testdata/http_tasks.goblin runs against a local server. A response's body is a File, so json.decode reads it to its end as it arrives.

JSON text written inside a Goblin string needs a raw string (`{"a": 1}`) or escaped braces ("\{\"a\": 1}"), because { starts an interpolation.

Module members

MemberReturnsBehaviour
encode(value, indent=nil)StringThe JSON text of value. indent=nil is compact ({"a":1,"b":[1,2]}); an Int is the number of spaces per level, with ": " after keys. Dict entries are written in the Dict's order. In strings only ", \ and the control characters below U+0020 are escaped, so <, >, & and every other character are written as they are
decode(data)valueThe value of one JSON document. data is a String, Bytes, or a readable read to its end. Objects become Dicts in document order

Values

GoblinJSONBack
nilnullnil
Booltrue / falseBool
IntnumberInt when the number has no fraction or exponent and fits 64 bits
Floatnumber (the shortest form that reads back the same; a whole Float keeps .0)Float otherwise
StringstringString
ListarrayList
Dict with String keysobjectDict
any value with a to_json() methodwhatever to_json() returns, encoded in turn—
anything else (Bytes, Path, Time, an instance without to_json(), …)TypeError—

to_json() is an ordinary method, one of the methods the library asks for by name: nothing to import or declare. It takes no arguments, must return something encodable, and must not return the value itself. Library value types do not have it; convert them where you encode (String(path), t.format(layout), base64.encode(bytes)), so the file says which form it holds.

A key that appears twice in a JSON object keeps its last value, at the place of its first occurrence.

A byte-order mark is not JSON, so text that starts with one raises ParseError unexpected "\ufeff". Remove it first: json.decode(text.trim_prefix((0xFEFF).to_char())).

Errors

FailureRaisesData on the error
decode: text that is not one JSON document, including empty text and anything but whitespace after the documentParseError decode() invalid JSON at line 2, column 9: unexpected "}"line, column: Ints counted from 1, where the text stops being JSON. column counts characters, not bytes. Empty input is line 1, column 1
decode: bytes that are not valid UTF-8ParseError decode() invalid JSON at line 1, column 2: invalid UTF-8line, column of the first invalid byte
decode: a number too large for a FloatParseError decode() invalid JSON at line 1, column 2: number 1e999 is out of rangeline, column
decode: data has the wrong typeTypeError decode() argument 'data' must be String, Bytes or have a read(size) method, got Int—
decode: reading a readable data failsthe error the readable raised, such as IOError—
encode: an instance with no to_json() methodTypeError encode() cannot encode Point (give its type a to_json() method)—
encode: a built-in or library value with no JSON form (Bytes, Path, Time, Chan, …)TypeError encode() cannot encode Path (convert it first, such as String(value))—
encode: a Dict key that is not a StringTypeError encode() Dict keys must be String, got Int—
encode: NaN or infinityValueError encode() cannot encode +Inf (JSON has no NaN or infinity)—
encode: a negative indentValueError encode() argument 'indent' must be non-negative, got -1—
encode: to_json() returns the value itselfValueError encode() Point.to_json() returned the value itself—
encode: a value that contains itselfRecursionError—

The message already says where; line and column are for a program that reports the place its own way, as config.json:2:9.

Left out

Sorted keys (keys keep the Dict's order; build the Dict from d.keys().sort() when a diff needs it), streaming a document too large for memory (use one document per line, as above), comments and trailing commas (that is not JSON), and automatic encoding of a type's fields (write to_json()).

fs

The fs module works with files, directories and path names. Its functions read and change the disk; the members of a Path work on the name alone and never touch the disk.

Every parameter called path, src or dst accepts a String or a Path, and every function that produces a file name returns a Path. Text is UTF-8.

Common tasks

import "fs"
import "time"

# Read and write whole files
var text = fs.read("notes.txt")
fs.write("copy.txt", text)
fs.write("events.log", "started\n", append=true)

# A big file, one line at a time; the file is closed when the loop ends
var errors = 0
for line in fs.read_lines("server.log") {
    if line.contains("ERROR") {
        errors = errors + 1
    }
}

# Build and take apart names (no disk access)
var source = fs.Path("docs/guide.md")
print(source.name, source.stem, source.suffix)   # guide.md guide .md
var target = fs.Path("build").join(source.with_suffix(".html").name)
print(target)                                    # build/guide.html

# Make sure the output directory is there, then write into it
fs.mkdir(target.parent)
fs.write(target, render(fs.read(source)))

# List, match, walk
for entry in fs.read_dir(".") {
    print(entry.name, fs.stat(entry).size)
}
for page in fs.glob("docs/**/*.md") {
    print(page)
}
func hidden(entry) {
    return entry.name.has_prefix(".")
}
for file in fs.walk(".", skip=hidden) {
    print(file.relative_to(fs.cwd()))
}

# A scratch directory for this run
var scratch = fs.mkdir_temp(prefix="report-")
defer fs.remove(scratch, recursive=true)
fs.write(scratch.join("data.json"), "[]")

# Write a file piece by piece
var out = fs.open("big.csv", write=true)
defer out.close()
for row in rows {
    out.write("{row}\n")
}

# Copy, move, delete, permissions
fs.copy("config.toml", "config.toml.bak")
fs.move("draft.md", "posts/final.md")
fs.remove("old.log")
fs.chmod("deploy.sh", 0o755)

# Is it there, how old is it
if fs.exists("cache.json") {
    var age = time.now() - fs.stat("cache.json").modified_at
}

examples/fs.goblin in the repository runs each of these tasks against a scratch directory.

Module functions

FunctionReturnsBehaviour
Path(text)PathA Path from a String or Path; see Path
read(path)StringThe whole file as text; an empty file is "". ValueError if it is not valid UTF-8
read_bytes(path)BytesThe whole file as bytes
read_lines(path)iterable of StringLazy; see Lines
write(path, data, append=false)nilCreates the file (mode 0o644) or replaces its content; append=true adds to the end. data is a String, Bytes or a readable, which is streamed. Parent directories are not created. The file is emptied before a readable is read, so when reading it fails partway the file holds what was written up to then
open(path, write=false, append=false)FileRead-only by default, and the file must exist. write=true: write-only, created or truncated. append=true: write-only, created, writes go to the end, also when write=true is given too
exists(path)BoolWhether the path names anything. Follows symlinks, so a broken link is false. A directory on the way that cannot be searched raises PermissionError rather than answering
is_file(path) / is_dir(path)BoolA regular file / a directory, after following symlinks. Missing is false; PermissionError as for exists
stat(path)FileInfoA snapshot of the entry; follows symlinks, and describes a broken link itself
read_dir(path)List of PathThe entries, each joined onto path, sorted by name. An empty directory is []
walk(path, skip=nil)iterable of PathLazy. Every file below path, depth first, names sorted within each directory
glob(pattern)List of PathPaths matching pattern (a String or a Path, such as dir.join("*.txt")), sorted; no match is []
mkdir(path)nilCreates the directory and any missing parents (mode 0o755). An existing directory is fine
mkdir_temp(prefix="")PathA new, uniquely named directory under temp_dir(); the caller removes it
remove(path, recursive=false)nilRemoves a file, a symlink (not its target) or an empty directory; a non-empty directory needs recursive=true. Removing what is already absent succeeds
copy(src, dst)nildst is the new path itself. A file is copied with its permission bits, replacing an existing file; a directory is copied as a tree, dst must not exist and must not be inside src. A symbolic link given as src is followed, so its target's content is copied (a broken one raises NotExistError); links inside a copied tree are copied as links
move(src, dst)nilRenames; dst is the new path itself and an existing file there is replaced. Across file systems it copies, then removes; a symbolic link is moved as a link there too
chmod(path, mode)nilSets permission bits, an Int from 0 to 0o777 such as 0o755
resolve(path)PathThe absolute form: joined onto cwd(), cleaned, symlinks resolved. A path that does not exist is still made absolute
cwd() / home() / temp_dir()PathThe working directory, the user's home directory, the directory for temporary files

Every function that takes a path accepts a String or a Path. An empty String names no file, so it raises ValueError read() argument 'path' must not be empty rather than standing for the current directory, which is written ".". The same holds for every path argument in the other modules (gzip, zip, tar, and cwd= in exec).

The module also exports the type names File, FileInfo, Lines and Walk so type_of(v) == fs.File works. They cannot be called: fs.File() raises TypeError: File cannot be constructed; use fs.open(path).

Walking and matching

walk yields files only: directories are descended, not yielded, and symbolic links are yielded but never followed. skip is a function called with the Path of every entry, file or directory; when it returns true the entry is not yielded and, for a directory, not entered. Pruning has to be a predicate because a loop body cannot tell the walk what not to enter.

In a glob pattern, * and ? match within one name, [a-z] is a character class, and ** as a whole component matches zero or more directories. A pattern matches files and directories, and names starting with a dot like any other. A relative pattern is relative to the working directory. A malformed pattern raises ValueError.

A directory that cannot be read stops walk and glob with PermissionError for the whole call, not only for that directory. walk can avoid one by name with skip: fs.walk(root, skip=func(p) { return p.name == "private" }).

Errors

Failures keep their kind: NotExistError, ExistError, PermissionError, or IOError for the rest. The message names the function and the path, and the operating system's error is the cause:

try {
    fs.read("nope.txt")
} catch e: NotExistError {
    print(e.path)                # nope.txt
    print(e.message)             # read() cannot open "nope.txt": no such file or directory
}

An error about a path carries it as e.path, a Path; a line that is not valid UTF-8 also carries e.line.

ErrorData
NotExistError, ExistError, PermissionError, IOError from any fs functionpath: the Path the message quotes, as given. For copy and move it is whichever of src and dst the failure is about
ValueError read() "x" is not valid UTF-8path
ValueError line 3 of "x" is not valid UTF-8 (read_lines, a File opened from a path)path, and line, an Int counted from 1
IOError from a File's read, write or closepath when the File has one; none for standard streams and pipes
TypeError, and ValueError about an argument (mode, prefix, a malformed glob pattern, a closed File)none: they are mistakes in the call, not facts about the disk

A handler further up can use the data without parsing the message:

func load_all(paths) {
    return paths.map(func(p) { return fs.read(p) })
}

try {
    var texts = load_all(os.args)
} catch e: NotExistError {
    eprint("missing: {e.path}")
} catch e: PermissionError {
    eprint("cannot read {e.path.name}; check its permissions")
}

fs.remove(dir) on a non-empty directory raises IOError remove() directory "dir" is not empty (pass recursive=true); mkdir raises ExistError when a file that is not a directory is in the way; copy and move raise ExistError when dst is a directory (or, when copying a directory, when dst exists at all). Copying a directory to a path inside itself, such as fs.copy(".", "dist/pkg"), raises IOError copy() cannot copy "." into itself ("dist/pkg") with e.path set to dst, before anything is written.

Path

An immutable name. It performs no I/O.

  • fs.Path(text) takes exactly one String or Path. The text is cleaned: repeated separators and . are dropped, and .. is applied lexically. fs.Path("") raises ValueError Path() argument 'text' must not be empty, as an empty path does everywhere; the current directory is fs.Path("."). A Path the library computes is never empty: the parent of "a" and Path("a").relative_to("a") are both ..
  • Paths compare (==, <), hash and print by their text, with the platform's separator. A Path never equals a String: compare String(p) == "a/b" or p == fs.Path("a/b").
  • Inside a List, a Dict or a structural Show, a Path shows as Path("a b"), its text quoted like a String element, so it is not mistaken for a String: print([fs.Path("a b"), "a b"]) prints [Path("a b"), "a b"]. print(p), String(p) and "{p}" give the plain text.
  • There is no / operator; joining is join.
MemberKindValue
namepropertyThe last component ("report.tar.gz"); "" for a root and for .
stempropertyname without its suffix ("report.tar")
suffixpropertyFrom the last dot of name (".gz"); "" when there is none, and for a name whose only dot is the first character (.bashrc)
parentpropertyThe path without its last component. A root is its own parent; the parent of "a" is .
is_absolutepropertyBool
join(*segments)methodThe path with each segment (String or Path) appended, then cleaned. Path("a").join("/b") is a/b. An empty segment raises ValueError, as an empty path does everywhere
with_name(name)methodThe last component replaced. ValueError for an empty name, one containing a separator, or a path with no name
with_suffix(suffix)methodThe suffix replaced; "" removes it. ValueError unless suffix is "" or starts with .
relative_to(base)methodThe path leading from base to this one, worked out from the names alone; may start with ... ValueError when one is absolute and the other is not

File

A stream over an open file, from fs.open. It is also the type of os.stdin, os.stdout and os.stderr, of the pipes of a command started with exec.start, and of a .gz file opened with gzip.open. It shows as <File notes.txt>.

MemberKindValue
pathpropertyThe Path it was opened with; nil for standard streams and pipes
closedpropertyBool
read(size=nil)methodBytes: up to size bytes, or everything left when nil. Empty Bytes at end of file
read_line()methodThe next line as a String without its terminator, or nil at end of file
write(data)methodWrites a String or Bytes and returns the number of bytes written
close()methodReleases the file; calling it again does nothing
for line in fileiterationThe remaining lines, as with read_line()

Calling a method on a closed file, read on a file open for writing or write on one open for reading raises ValueError. A line that is not valid UTF-8 raises ValueError when it is reached.

The loop for line in file does not close the file: read and read_line afterwards continue where the loop stopped. Whoever opened a file closes it, normally with defer file.close(). Because a File has read(size) and write(data), it can be passed wherever a readable or a writable is accepted, such as the data of fs.write.

Reading lines

fs.read_lines(path) is the one-call way to go through a file line by line. Each for over the value it returns opens the file, yields one line per step (the \n or \r\n terminator removed, a last line without one included) and closes the file when the loop ends by any route: at the end, on break or return, or when an error is raised. It can be iterated again, which opens the file again. A missing file raises NotExistError when the loop starts; a line that is not valid UTF-8 raises ValueError line 3 of "x" is not valid UTF-8.

FileInfo

An immutable snapshot from fs.stat. All members are properties.

PropertyValue
sizeInt, bytes
modified_attime.Time
is_fileBool, a regular file
is_dirBool
is_symlinkBool: the path itself is a symbolic link (the other properties describe its target)
modeInt, permission bits (info.mode == 0o644)

A FileInfo shows the kind of entry its properties describe: <FileInfo file size=12> for a regular file, <FileInfo dir> for a directory, <FileInfo other> for anything else (a device, a named pipe, a socket). A symbolic link shows its target's kind, since the properties describe the target; a broken link, which stat describes itself, shows as <FileInfo symlink>.

info.is_dir reads a snapshot already taken, while fs.is_dir(path) asks the disk again.

Left out

Symlink creation, ownership, file locking, seek/tell, and changing the working directory (it is process-global and unsafe with goblins; pass cwd= to exec instead) are not part of the module. walk never yields directories.

os

The os module is the running process: its arguments, environment, standard streams and exit status. Files are in fs and other programs in exec.

Common tasks

import "os"

# Positional arguments
if os.args.size != 2 {
    eprint("usage: {os.program} <source> <target>")
    os.exit(2)
}
var source, target = os.args

# Settings from the environment
var port = Int(os.env.get("PORT", default="8080"))
var token = os.env["API_TOKEN"]          # KeyError if it is not set
os.env["NO_COLOR"] = "1"                 # seen by programs started later

# A filter: stdin to stdout
for line in os.stdin {
    if line.contains("ERROR") {
        print(line)
    }
}

# Ask a question: the built-in input() writes the prompt and reads a line
var answer = input("Delete everything? [y/N] ")
if answer == nil || answer.trim().lower() != "y" {
    os.exit(1)
}

# Platform differences
var opener = "xdg-open"
if os.platform == "darwin" {
    opener = "open"
}

docs/examples/os-tasks.goblin runs these tasks with arguments and piped input; examples/os.goblin covers the rest of the module.

Module members

MemberKindValue
argsList of StringThe program's arguments, without the program name. goblin run app.goblin a b and ./app a b both give ["a", "b"]; [] in the REPL. It is built once: every read gives the same List
programStringWhat the program was started as: the source path under goblin run, the executable path when compiled, "" in the REPL
envEnvThe process environment, live; see Env
stdinfs.FileReadable: for line in os.stdin, read_line(), read()
stdoutfs.FileWritable; write(data) adds no newline
stderrfs.FileWritable
pidIntThe process id
platformString"linux", "darwin", "windows", … (Go's runtime.GOOS)
exit(code=0)functionEnds the process with that status, from 0 to 255 (ValueError otherwise), after running pending deferred calls

A fact fixed for the life of the process is a value (os.args, os.pid), the environment is an object, and ending the process is a function.

os.exit() ends the program: nothing after the call runs, and no catch clause sees it. Before the process ends, the deferred calls that are still pending run as they would for an error nobody catches: those of the calling function, of each of its callers, then of the file's top level. A temporary directory removed by a defer is removed.

If one of those deferred calls raises, the error is written to stderr as uncaught error in deferred call: <error>, the remaining ones still run, and a status of 0 becomes 1. A deferred call that itself calls os.exit() replaces the status. A deferred call that blocks delays the exit.

Only the goblin that called os.exit() runs its deferred calls; every other goblin is stopped where it is, including the main one when a spawned goblin exits. An interrupt (Ctrl-C) ends the process without running deferred calls. Avoid os.exit() in library code; raise an error instead and let the program decide.

The standard streams are ordinary File values whose path is nil; their methods raise IOError when the stream fails. print writes to the same stdout and neither is buffered, so their output interleaves in call order. close() on a standard stream is allowed and closes the process's stream.

Env

os.env is one object instead of four functions. It is not a Dict, but it uses Dict's vocabulary and nothing else. Names and values are Strings; anything else is a TypeError. Changes affect this process and the programs it starts afterwards.

MemberValueWhen the variable is missing
env[name]The variable's valueKeyError environment variable 'X' is not set
env[name] = valueSets it; ValueError for an empty name or one containing = or NUL—
get(name, default=nil)The value, or defaultdefault
contains(name)Bool; a variable set to "" is containedfalse
remove(name)Unsets it and returns the Envfine
to_dict()A new Dict snapshot of every variable, sorted by name—

Env is not iterable and has no size, keys() or items(): use to_dict() when the whole environment is wanted. The module exports the type name Env for type_of(os.env) == os.Env; it cannot be called.

Left out

  • Prompting is the built-in input(prompt), not a member of this module. It reads through the same buffer as os.stdin, so the two can be mixed.
  • Options, help and usage errors are the cli module's; os.args is the raw list.
  • The host name and user and group ids are not in the module: exec.capture(["hostname"]).stdout.trim() or exec.capture(["id", "-u"]).
  • The working directory and temporary directories are in fs: fs.cwd(), fs.mkdir_temp().

cli

The cli module reads a program's command line. A script describes its arguments the way a call is written, positional names first and then name=default, and gets back an Args value with one attribute per name. Help, usage errors and their exit statuses come with it.

Common tasks

import "cli"

# Two arguments and a flag: tool in.txt out.txt --verbose
var args = cli.parse("source", "target", verbose=false)
if args.verbose { print("copying {args.source} to {args.target}") }

# Options with values: the default says what the option holds
var args = cli.parse(
    "url",
    count   = 3,             # --count 5, --count=5         Int
    timeout = 2.5,           # --timeout 10                 Float
    output  = "out.txt",     # --output a.txt               String
    token   = nil,           # --token abc                  String, nil when absent
    include = [],            # --include a --include b      List of String
    dry_run = false,         # --dry-run                    Bool; args.dry_run
)

# Saying more: help text, a short letter, required, choices, a converter
var args = cli.parse(
    cli.Arg("files", "images to resize", many=true),
    width   = cli.Option("target width in pixels", short="w", default=800),
    format  = cli.Option(choices=["png", "jpg"], default="png"),
    output  = cli.Option("directory to write to", short="o", required=true),
    since   = cli.Option("only files newer than this date", convert=time.parse),
    verbose = cli.Flag("say what is being done", short="v", many=true),   # -vv gives 2
    help    = "Resize images into a directory.",
)
for file in args.files { ... }

# An optional argument, and any number of them
var args = cli.parse("pattern", cli.Arg("paths", default=["."], many=true))

# A default from the environment: ordinary code, the default is just a value
var args = cli.parse(port = Int(os.env.get("PORT", default="8080")))

# Subcommands: tool build --release, tool test parser -v
var args = cli.parse(
    build   = cli.Command(release=false, help="Compile the project"),
    test    = cli.Command(cli.Arg("name", default=nil), help="Run the tests"),
    verbose = cli.Flag(short="v"),
    help    = "Project tool.",
)
if args.command == "build" {
    build(release=args.release)
} else {
    test(args.name)
}

# Your own check after parsing: same look, same status
if args.width <= 0 {
    eprint("error: --width must be positive")
    os.exit(2)
}

# Testing: give a List and nothing is printed and nothing exits
func parse(argv=nil) {
    return cli.parse("source", "target", verbose=false, argv=argv)
}
var args = parse()                              # the real command line
print(parse(["a", "b", "--verbose"]).verbose)   # true
try {
    parse(["a"])
} catch e: cli.UsageError {
    print(e.message)                            # missing argument <target>
}

docs/examples/cli-tasks.goblin runs these tasks; examples/cli.goblin covers the rest of the module.

Members

MemberKindValue
parse(*params, help=nil, argv=nil, **options)functionParses a command line against the declaration and returns an Args
Arg(name, help=nil, convert=nil, choices=nil, default=…, many=false)typeA positional argument
Option(help=nil, short=nil, convert=nil, choices=nil, default=nil, required=false, many=false)typeAn option that takes a value
Flag(help=nil, short=nil, many=false)typeAn option that takes no value
Command(*params, help=nil, **options)typeA subcommand with its own declaration
ArgstypeWhat parse returns; it cannot be constructed
UsageErrorerror kind (parent Error)The command line does not fit the declaration
HelpRequestederror kind (parent Error)--help was given, when parsing a List

Arg, Option, Flag and Command values are immutable descriptions with no members; one can be stored in a variable and used under several names. They print as <Option> and so on and compare by identity.

The declaration

*params, in order, are the positional arguments. Each is a String (short for cli.Arg(name)) or a cli.Arg.

Each keyword in **options declares the option --name, with _ written as - on the command line: dry_run is --dry-run and only that, and the result attribute is args.dry_run. The value is:

WrittenMeansResult attribute
falsecli.Flag()Bool
nilcli.Option()String, or nil when absent
a String, Int or Floatcli.Option(default=value)same type as the default
a Listcli.Option(many=true, default=list)List of String
cli.Flag(...), cli.Option(...)itselfbelow
cli.Command(...)a subcommand—

help= is the program's description, shown by --help, and argv= chooses the mode (below); neither can be an option name. Names, keywords and Arg names alike, are lower-case letters and digits in words joined by single _s, starting with a letter.

The keywords shared by Arg, Option and Flag mean the same everywhere:

  • help: one line for --help. It is the first parameter after the name, so it is usually written positionally: cli.Option("where to write").
  • convert: a function from the text to the value: Int, Float, fs.Path, time.parse, or your own. A ValueError it raises (ParseError included) becomes a usage error naming the parameter; any other error passes through as the bug it is. Without convert, an Int or Float default converts with Int or Float; otherwise the text is kept as a String.
  • choices: a non-empty List; the converted value must == one of them.
  • default: the value when the parameter is not given, used as it is: not converted and not checked against choices.
  • many: the parameter may be given many times. Its value is a List for Arg and Option (a new List on every parse; given values replace the default rather than add to it) and the Int count for Flag.
  • short: one ASCII letter, giving -x. No option has a short letter unless it is given one.

An Arg is required unless default= is given (default=nil counts). With many=true it takes all remaining positionals: one or more, or zero or more when it has a default, which must then be a List. Optional Args come after required ones, and a many Arg is last.

An Option is optional unless required=true. Absent, it is its default (nil; [] with many=true). Given twice without many, the last one wins. A Flag is false until given and true after, however often; with many=true it counts from 0.

Args

An immutable value with exactly one attribute per declared parameter (plus command when subcommands are declared) and no methods, so no option name is ever taken. attributes(args) lists them in declaration order. A wrong name raises AttributeError: Args has no attribute 'verbsoe', and assigning raises TypeError: Args does not support attribute assignment, as on every other library value. It prints as Args(source="a", target="b", verbose=false).

Two modes

argv=nil (default)argv= a List of String
Parsesos.argsthe List
Bad inputwrites the error to stderr, exits 2raises cli.UsageError
--helpwrites the help to stdout, exits 0raises cli.HelpRequested
Program name in textsbase name of os.program (program when empty, as in the REPL)same

The process's command line gets the process's behaviour; a List gets a function's. Exiting works like os.exit: pending deferred calls run first.

  • UsageError: message is the one-line reason, standing alone; the data usage is the usage line.
  • HelpRequested: message is the complete help text without a trailing newline.

A program that reads command lines from somewhere else, a prompt loop for instance, parses a List and prints e.message itself.

Subcommands

A keyword whose value is a cli.Command declares a subcommand, named like an option is (dry_run= is typed dry-run). Command takes the same declaration as parse, without argv.

  • With any Command declared, the first positional on the command line names the command, and one is required. Top-level positionals cannot be combined with commands, and commands do not nest.
  • Top-level options are global: accepted before or after the command name. A command's own options are accepted only after it.
  • The result is flat: args.command is the name as typed ("build"), followed by the global options and the chosen command's parameters. The other commands' parameters are not attributes. A command's parameter therefore may not reuse a global option's name or be called command; two commands may use the same name.
  • tool --help lists the commands; tool build --help describes build.

The command line accepted

Tokens are read left to right, and options and positionals may be mixed in any order.

TokenMeaning
--nameA Flag; or an Option whose value is the next token
--name=valueAn Option with that value, which may be empty. On a Flag: an error
-xA short flag; or a short option whose value is the next token
-abcA cluster: -a -b -c. The first letter that is an Option takes the rest of the token as its value, or the next token if nothing is left: -n5, -vn 5, -vvo out.txt. A leading = in the attached value is dropped (-o=x is x)
--Ends the options: every later token is positional
-A positional (conventionally "standard input")
-5, -1.5, -.5A positional or a value: a - followed by a digit, or by . and a digit, never starts an option
anything elseA positional

The next token is taken as an option's value unless it looks like an option itself; then the error is option --output needs a value. Write a value that starts with a dash as --pattern=-x. Long options are never abbreviated and names are case-sensitive: --verb and --dry_run are unknown.

--help always asks for help, and -h does unless a parameter declared short="h". It takes effect where the scan reaches it, so an error earlier on the line is reported instead, while missing parameters are only checked after the scan: tool --help alone always gives help. After -- it is a positional. Conversion and choices apply as each value is read.

Problems are reported in this order: a wrong declaration, then the first problem on the line, then a missing command, then missing arguments (all of them in one message), then the first missing required option.

SituationMessage
Unknown optionunknown option --widht (did you mean --width?) / unknown option -x
Option without a valueoption --output needs a value
Flag given a valueoption --verbose takes no value
Int conversion fails, a number too large for an Int includedinvalid value "abc" for --count: expected an integer
Float conversion failsinvalid value "abc" for --timeout: expected a number
Another convert raises ValueErrorinvalid value "abc" for --since: and the error's message
Not among choicesinvalid value "gif" for --format: expected one of png, jpg
Same, for an argumentinvalid value "abc" for <count>: expected an integer
Too many positionalsunexpected argument "extra"
Missing positionalsmissing argument <target> / missing arguments <source> <target>
Missing required optionmissing required option --output
No commandmissing command (one of build, test)
Unknown commandunknown command "biuld" (did you mean build?)

Options are always named by their long form, whatever was typed. A suggestion is made when the nearest declared long option (or command) is within two edits; a tie goes to the earlier declaration.

Help and errors

The "saying more" declaration above, with the since line replaced by dry_run = false, run as goblin run resize.goblin --help, writes this to stdout and exits with status 0:

usage: resize.goblin [options] <files>...

Resize images into a directory.

arguments:
  <files>...              images to resize

options:
  -w, --width <width>     target width in pixels (default: 800)
      --format <png|jpg>  (default: png)
  -o, --output <output>   directory to write to (required)
      --dry-run
  -v, --verbose           say what is being done
  -h, --help              show this help and exit

The layout is fixed: no terminal width, no wrapping, no colour.

  • The usage line is usage: , the program, [options], then the positionals: <name> required, [<name>] optional, <name>... many, [<name>...] optional many. With commands it is usage: tool.goblin [options] <command> ..., and for one command usage: tool.goblin build [options] <name>.
  • The help= description follows between blank lines, when there is one.
  • arguments: has a line for each Arg with help, choices or a default; an Arg's choices show as (one of fast, safe).
  • commands: lists each command with its help.
  • options: lists the options in declaration order, then --help; a command's page lists its own options, then the global ones. The left column is -x, --name (four spaces without a short letter), then <name> for an Option, <a|b> when it has choices, and ... when it takes many values.
  • The help text follows two spaces after the longest left column, then (default: X) unless the default is nil, false, a counting flag's 0 or [] (a String without quotes, a List as its elements joined by , ), and (required) for a required Option.

A usage error in process mode writes three lines to stderr, nothing to stdout, and exits with status 2:

error: unknown option --widht (did you mean --width?)
usage: resize.goblin [options] <files>...
Run 'resize.goblin --help' for details.

Wrong declarations

A wrong declaration is the programmer's bug, not the user's: cli.parse raises an ordinary TypeError or ValueError in both modes, before looking at the command line, so it shows on the first run whatever the arguments.

DeclarationMessage
An option value of another type (x={})TypeError parse() option 'x' must be false, nil, String, Int, Float, List, Flag, Option or Command, got Dict
x=trueparse() option 'x' cannot default to true; declare the opposite flag (no_x=false)
A positional that is not a String or an ArgTypeError parse() argument 1 must be String or Arg, got Int
A bad nameparse() invalid name 'Dry-Run' (use lower case letters, digits and '_')
A name used twiceparse() duplicate name 'output'
short not one ASCII letterOption() argument 'short' must be one letter, got "ab"
A short letter used twiceparse() short option -o is used by 'output' and 'only'
A required Arg after an optional oneparse() required argument 'target' follows optional argument 'source'
A many Arg that is not lastparse() argument 'files' takes all remaining arguments and must be last
required=true with a defaultOption() cannot be both required and have a default
many=true with a default that is not a ListOption() argument 'default' must be a List when many is true, got String
A Bool default on an OptionOption() argument 'default' cannot be a Bool; use cli.Flag()
Empty or non-List choicesOption() argument 'choices' must be a non-empty List
Args together with Commandsparse() cannot combine arguments with commands
A Command inside a CommandCommand() commands cannot be nested
A command parameter named like a global option, or commandparse() command 'build' reuses the name 'verbose'
argv not a List of StringTypeError parse() argument 'argv' must be a List of String, got String

Left out

  • Defaults from environment variables: one line of ordinary code, as in the tasks above. Help does not mention the variable.
  • --version, abbreviated long options, --no-x negation, +x, single-dash words (-verbose) and Windows /x.
  • A placeholder different from the option's name (--output FILE): it is <output>.
  • Args as a Dict (to_dict(), main(**args)): Args has no methods, so no option name is ever taken.
  • A many Arg before others (cp <src>... <dst>): take the last one with args.paths.pop().
  • Nested subcommands, a default subcommand and command aliases.
  • Mutually exclusive or dependent options and value ranges: check after parsing, with eprint and os.exit(2) as above.
  • Reading a declaration back, shell completion, wrapping to the terminal width, colour and response files (@args.txt).

exec

The exec module runs other programs. Three functions cover three tasks: run for a command's effect, capture for its output, start for a process you keep control of.

A command is always a List: the program followed by its arguments. No shell is involved, so there is no quoting and no injection; for a pipeline, run ["sh", "-c", "a | b"] on purpose.

Common tasks

import "exec"
import "fs"
import "http"
import "os"
import "time"

# Run a step; the program stops with an error if it fails
exec.run(["go", "build", "./..."])
exec.run(["npm", "install"], cwd="web", env={"CI": "1"})

# Get a command's output
var head = exec.capture(["git", "rev-parse", "HEAD"]).stdout.trim()
var tags = exec.capture(["git", "tag"]).stdout.lines()

# Feed it input
var sorted_text = exec.capture(["sort", "-u"], stdin="b\na\nb\n").stdout

# A failure you expect: look at the result instead of catching
var diff = exec.run(["git", "diff", "--quiet"], check=false)
if !diff.success {
    print("working tree is dirty (status {diff.code})")
}

# A failure you want to report your own way
try {
    exec.capture(["git", "push"])
} catch e: exec.ExitError {
    eprint("push failed with status {e.code}")
    eprint(e.stderr)
    os.exit(1)
}

# Is the tool there at all
if exec.find("docker") == nil {
    raise Error("docker is not installed")
}

# Send output to a file
var log = fs.open("build.log", write=true)
defer log.close()
exec.run(["make"], stdout=log, stderr=log)

# Give up after a minute
exec.run(["npm", "test"], timeout=60)

# Start a server, use it, stop it
var server = exec.start(["python3", "-m", "http.server", "8000"])
defer server.kill()
time.sleep(1)
print(http.get("http://localhost:8000/").status)

# Follow a long-running command line by line
var tail = exec.start(["tail", "-f", "app.log"], stdout=exec.PIPE)
for line in tail.stdout {
    if line.contains("READY") {
        break
    }
}
tail.kill()

# Show a build's output as it comes, and stop if it fails
var build = exec.start(["make"], stdout=exec.PIPE)
for line in build.stdout {
    print("make: {line}")
}
build.wait()                 # raises exec.ExitError for a non-zero exit

# Read binary output as Bytes
var archive = exec.start(["tar", "-cz", "src"], stdout=exec.PIPE)
var data = archive.stdout.read()
archive.wait()

examples/exec.goblin runs each of these tasks with small shell commands.

Module members

MemberReturnsBehaviour
run(args, cwd=nil, env=nil, stdin=nil, stdout=nil, stderr=nil, timeout=nil, check=true)ResultRuns the command to completion; its output goes where this program's goes, or to stdout=/stderr=. result.stdout and stderr are nil
capture(args, cwd=nil, env=nil, stdin=nil, timeout=nil, check=true)ResultRuns the command to completion, collecting stdout and stderr as text in the Result. Nothing reaches the terminal. Output that is not valid UTF-8 raises ValueError: read binary output through start with stdout=exec.PIPE
start(args, cwd=nil, env=nil, stdin=nil, stdout=nil, stderr=nil)CommandStarts the command and returns at once. stdin, stdout and stderr also accept exec.PIPE
find(name)Path or nilWhere name would be found on PATH; nil when it is not installed
ExitErrorerror kindRaised by run, capture and Command.wait for a non-zero exit under check=true
PIPEconstantFor start only: connect that stream to this program (command.stdin, command.stdout, command.stderr). Passing it to run is a TypeError

The parameters they share:

ParameterAcceptsMeaning
argsnon-empty List of String or PathProgram and arguments. A bare name is looked up on PATH
cwd=nilString, PathWorking directory for the command; nil is this program's. An empty String raises ValueError run() argument 'cwd' must not be empty, as an empty path does in fs
env=nilDict of String to String or nilAdded to the inherited environment; a nil value removes that variable. Names and values are checked as os.env checks them: ValueError run() invalid environment variable name "A=B" for an empty name or one with =, and for a value with a NUL character
stdin=nilnil, String, Bytes or a readablenil: the command reads this program's stdin. Data is fed to the command, then its stdin is closed
stdout=nil, stderr=nilnil or a writablenil: the command writes to this program's stream. A writable (a File, anything with write(data)) receives the output and is not closed
timeout=nilsecondsWhen it expires the process is killed and TimeoutError is raised
check=trueBoolA non-zero exit raises. false returns the Result for you to inspect

The type names Command and Result are exported for type_of; calling them raises TypeError pointing at exec.start / exec.run. PIPE is compared as itself (stream == exec.PIPE), so its type has no exported name.

Errors

FailureRaisesData
The program is not foundNotExistError run() program "gti" not found—
The program name is ""ValueError run() argument 'args' has an empty program name—
cwd does not existNotExistError run() working directory "build": no such file or directorypath: the cwd given, a Path
cwd is not a directoryIOError run() working directory "notes.txt" is not a directory, as fs reports a file where a directory belongspath
It cannot be runPermissionError, IOError—
timeout expired, timeout=0 includedTimeoutError run() "sleep" timed out after 2 secondsstdout, stderr: what capture had collected when the process was killed; nil from run
Non-zero exit with check=trueexec.ExitError run() "git" exited with status 128; capture adds the last non-empty stderr line: capture() "git" exited with status 128: fatal: not a git repository; Command.wait says wait() "make" exited with status 2code, stdout, stderr
capture collected output that is not valid UTF-8ValueError capture() "cat" wrote stdout that is not valid UTF-8 (use exec.start with stdout=exec.PIPE for bytes), after the timeout and exit checks—

The data of an exec.ExitError is what the Result would have shown under check=false: code is the exit status (-1 when the process was killed by a signal, never 0), stdout and stderr are the captured text from capture and nil from run and Command.wait. It is not an IOError: the command ran, and its answer was "failed". The output an ExitError or a TimeoutError carries is for diagnosis, so invalid UTF-8 in it is replaced by U+FFFD rather than raising a second error.

Pass check=false when a non-zero status is an answer rather than a failure; catch exec.ExitError when it is a failure you want to handle.

Result

Immutable; all properties.

PropertyValue
codeInt exit status; -1 when the process was killed by a signal
successBool, code == 0
stdoutString from capture, always valid UTF-8; nil from run and Command.wait
stderrlikewise

Command

A started process, from exec.start. It shows as <Command ["git", "status"]>.

MemberKindValue
pidpropertyInt
runningpropertyBool: started and not yet exited
stdinpropertyA writable File when started with stdin=exec.PIPE, else nil. close() it to signal the end of input
stdout, stderrpropertyA readable File when started with exec.PIPE, else nil
wait(timeout=nil, check=true)methodBlocks until the process exits and returns its Result (stdout/stderr are nil). A non-zero exit raises exec.ExitError as run does; check=false returns the Result instead. Calling it again gives the same outcome. On timeout it raises TimeoutError and the process keeps running
kill()methodStops the process; nil. Fine if it already exited. A killed process has status -1, so collect it with wait(check=false)

A piped stdout or stderr must be read to its end before wait(): a process blocked on a full pipe never exits. Close the pipes you asked for once you are done with them.

When stdout= or stderr= is a writable, its write is called while the command runs, also while your program goes on after start; do not use the same object from Goblin code until wait() returns.

Left out

Shell command strings, signals other than kill, a clean (not inherited) environment, and capturing output as Bytes in one call are not part of the module. Binary output is read from exec.start(args, stdout=exec.PIPE) with command.stdout.read(), or sent to a File with stdout=.

time

The time module reads the clock, sleeps, and works with instants and time zones. There are two kinds of value and no more: an instant is a Time, and a duration is a number of seconds (an Int or a Float), as it is everywhere else in Goblin (timeout=, Chan.receive). time.MINUTE, time.HOUR and time.DAY are the readable multipliers.

Common tasks

import "fs"
import "math"
import "time"

# Timestamps
print(time.now())                                   # 2026-07-19T09:30:00+08:00
print(time.now().format("%Y-%m-%d %H:%M"))          # 2026-07-19 09:30
var stamp = time.now().format("%Y%m%d")
var name = "backup-{stamp}.tar"
print("[{time.now().format(`%H:%M:%S`)}] started")  # inside an interpolation the layout is a raw string
print(time.now().to_utc())                          # 2026-07-19T01:30:00Z

# How long did it take
var started = time.now()
build()
print("built in {time.now() - started:.1f} seconds")

# Dates from data
var due = time.parse("2026-08-01")
var posted = time.parse("19/07/2026 14:05", layout="%d/%m/%Y %H:%M")
if time.now() > due {
    print("overdue by {(time.now() - due) / time.DAY:.0f} days")
}

# A column of dates, some of them wrong
func read_date(text) {
    try {
        return time.parse(text, layout="%d/%m/%Y")
    } catch e: ParseError {
        eprint("not a date: {e.text}")
        return nil
    }
}

# Relative times
var last_week = time.now() - 7 * time.DAY
var stale = fs.stat("cache.json").modified_at < last_week

# What time is that for someone else
var meeting = time.Time(2026, 7, 19, hour=9, minute=30, zone="America/New_York")
print(meeting.to_zone("Asia/Shanghai"))                    # 2026-07-19T21:30:00+08:00
print(meeting.to_zone("Europe/Paris").format("%H:%M %Z"))  # 15:30 CEST
print(meeting.zone, meeting.offset / time.HOUR)            # America/New_York -4
var record_at = meeting.to_utc().format("%Y-%m-%dT%H:%M:%SZ")   # 2026-07-19T13:30:00Z, for a log or an API

# A time an API gave in UTC, shown to the person at this computer
print(time.parse("2026-07-19T13:30:00Z").to_zone("local").format("%H:%M"))

# Times in data that do not say their zone
var opened = time.parse("2026-07-19 09:00", zone="Europe/Paris")
var logged = time.parse(record["created"], zone="UTC")
var changed = time.parse(last_modified, layout="%a, %d %b %Y %H:%M:%S GMT", zone="UTC")

# A zone from settings, which may be misspelt
func show(t, zone) {
    try {
        return t.to_zone(zone).format("%Y-%m-%d %H:%M")
    } catch e: ValueError {
        eprint(e.message)                  # to_zone() unknown time zone "Asia/Shangai"
        return t.format("%Y-%m-%d %H:%M")
    }
}

# Today, and what happened on which day
var today = time.now().start_of_day()
var fresh = fs.stat("report.html").modified_at >= today
var per_day = {}
for event in events {
    var day = time.unix(event["at"]).start_of_day()
    per_day[day] = per_day.get(day, default=0) + 1
}

# Whole days between two dates, whatever the hours
var nights = math.round((checkout.start_of_day() - checkin.start_of_day()) / time.DAY)

# Calendar values and calendar steps: the constructor rolls over
var launch = time.Time(2026, 7, 19, hour=9, minute=30)
if launch.weekday >= 6 {
    print("that is a weekend")
}
var next_month = time.Time(launch.year, launch.month + 1, 1)
var month_end = time.Time(launch.year, launch.month + 1, 0)
var same_time_next_week = time.Time(launch.year, launch.month, launch.day + 7, hour=launch.hour, minute=launch.minute, zone=launch.zone)

# Which week is it
print(time.now().format("%G-W%V"))                  # 2026-W29

# Unix timestamps from and for an API
var created = time.unix(payload["created"])
var expires = (time.now() + time.HOUR).unix

# Retry with a pause
func fetch_with_retry() {
    for attempt in range(3) {
        try {
            return fetch()
        } catch e: IOError {
            time.sleep(2)
        }
    }
    raise Error("gave up after 3 attempts")
}

docs/examples/time-tasks.goblin runs these tasks against fixed instants; examples/time.goblin covers the rest of the module.

Module members

MemberReturnsBehaviour
now()TimeThe current instant, in the local zone
sleep(seconds)nilPauses this goblin for an Int or Float number of seconds; 0 returns at once. ValueError for a negative number
Time(year, month, day, hour=0, minute=0, second=0, zone=nil)TimeThat wall-clock time in zone; nil is the local zone. Out-of-range parts roll over: month=13 is January of the next year, day=0 the last day of the previous month. ValueError Time() result is out of range (years 1 to 9999) when the result, as an instant in UTC, is outside the years 1 to 9999, or a part is too large to roll over. TypeError for a part that is not an Int
parse(text, layout=nil, zone=nil)TimeWithout a layout, ISO 8601 / RFC 3339 (below). With one, the layout's form exactly. Text that carries an offset keeps it; text that carries none is wall-clock time in zone, nil being the local zone
unix(seconds)TimeThe instant that many seconds (Int or Float) after 1970-01-01 UTC, in the local zone. ValueError outside the years 1 to 9999
MINUTE, HOUR, DAYInt60, 3600, 86400: time.sleep(5 * time.MINUTE)

The forms parse(text) accepts with no layout are 2026-07-19, 2026-07-19T09:30, 2026-07-19T09:30:15 and 2026-07-19T09:30:15.250, each time form optionally followed by Z or an offset such as +08:00; a space is accepted in place of T.

Zones

A zone is a String, written the same four ways wherever one is accepted (Time(zone=), parse(zone=), to_zone) and wherever one is reported (Time.zone):

SpellingZone
"local"The computer's zone (the TZ environment variable, else the system setting)
"UTC"UTC
"Asia/Shanghai", "America/New_York", …A zone of the IANA time zone database, by its name exactly as listed there, in the same case on every system ("asia/shanghai" is an unknown zone). Its offset follows that place's rules, daylight saving included
"+08:00", "-03:30"A fixed offset from UTC, always ±HH:MM
  • A zone= keyword also accepts nil, meaning "local".
  • Anything else is ValueError: to_zone() unknown time zone "Asia/Shangai", with the function's own name in front. It carries no data: the caller holds the name.
  • The zone database is built into every program that imports time, so a name works the same on Windows, in a minimal container and on a machine whose system database is old or missing. The system's database is used when it is there and the built-in copy is the fallback. It costs about 450 KB in a compiled executable that imports time; programs that do not import it pay nothing.
  • A wall-clock time that does not exist (the hour skipped when clocks go forward) or exists twice (the hour repeated when they go back) gives one of the two possible instants. Scripts that schedule inside those hours should use UTC.

Time

Immutable: an instant together with the zone it is shown in.

== and the ordering operators compare instants, whatever the zones (09:00+08:00 equals 01:00Z), and a Time can be a Dict key on the same terms. A Time prints as RFC 3339 (2026-07-19T09:30:00+08:00), with fractional seconds only when they are not zero; its zone's name is not shown, its offset is. Inside a List, a Dict or a structural Show it shows as Time("2026-07-19T09:30:00+08:00"), so it is not mistaken for a String. Like every library value it is always truthy.

MemberKindValue
year, month, daypropertyInt; month is 1–12
hour, minute, secondpropertyInt
nanosecondpropertyInt 0–999999999, the fraction of the second
weekdaypropertyInt, 1 (Monday) to 7 (Sunday), as ISO 8601. The name is t.format("%A")
unixpropertyInt, whole seconds since 1970-01-01 UTC, rounded down
zonepropertyString: the zone this Time is shown in, in a spelling of the table above ("local", "UTC", "Europe/Paris", "+08:00"). Passing it to zone= gives the same zone
offsetpropertyInt: seconds east of UTC at this instant in this zone (28800 for +08:00, negative west)
format(layout=nil)methodString. nil gives the printed form; otherwise per the layout. ValueError for an unknown directive
to_utc()methodThe same instant shown in UTC: exactly t.to_zone("UTC")
to_zone(zone)methodThe same instant shown in zone. t.to_zone("local") shows it in the computer's zone. ValueError for an unknown zone
start_of_day()method00:00:00 of the same calendar day, in the same zone. Where the clocks jump over midnight on that day (America/Santiago in September), 00:00 does not exist and the day starts at the jump (01:00)

All the wall-clock properties are read in the Time's zone. Time.zone reports "local" for the local zone rather than guessing its IANA name, which the operating system does not reliably tell a program.

ExpressionResult
t + seconds, seconds + t, t - secondsA Time shifted by exactly that many elapsed seconds, in the same zone. ValueError Time arithmetic result is out of range (years 1 to 9999) outside the years 1 to 9999, the range of Time(...) and unix
t - uFloat, the seconds from u to t. Between two now() values of one process it is measured on the monotonic clock
t < u, t == u, …By instant

t + time.DAY is 24 hours later, which is not always "the same time tomorrow" in a zone with daylight saving. A calendar step is the constructor, which rolls over: time.Time(t.year, t.month, t.day + 1, hour=t.hour, minute=t.minute, zone=t.zone).

Layouts

Layouts are strftime directives, the form shared by C, Python, Ruby and date(1). Anything else in a layout is literal text, so "2006 Jan" is just those characters.

DirectiveMeaningExample
%Y / %yyear, 4 / 2 digits2026 / 26
%mmonth 01–1207
%d / %eday 01–31 / space padded09 / 9
%H / %Ihour 00–23 / 01–1215 / 03
%M, %Sminute, second04, 05
%fmicroseconds, 6 digits250000
%pAM / PMPM
%A / %aweekday name, full / 3 letters (English)Sunday / Sun
%B / %bmonth name, full / 3 letters (English)July / Jul
%jday of the year 001–366200
%zoffset+0800
%Zthe zone's abbreviation at that instant; the offset where the zone has none. format onlyCST, EDT, UTC
%G, %VISO 8601 week-numbering year and week 01–53. format only2026, 29
%%a literal %%

parse accepts the same directives, except the three marked format only, which are a ValueError in a parse layout: an abbreviation does not name a zone (CST is three of them) and a week does not name a day. When parsing:

  • names (%A, %a, %B, %b, %p) are read case-insensitively; %j, %a and %A are read and then ignored;
  • two-digit fields accept one digit as well (9/7/2026 with %d/%m/%Y); %Y needs four digits; %y reads 69–99 as 1969–1999 and 00–68 as 2000–2068;
  • %z reads +0800, +08:00 or Z; a layout without it reads the text in zone;
  • a part the layout does not mention is taken from 1900-01-01 00:00:00, as in C and Python: time.parse("09:30", layout="%H:%M") is on 1900-01-01;
  • text naming a day that does not exist (31/06/2026) does not match: unlike the constructor, parsing does not roll over.

A layout is not a format specifier: "{t:%Y}" is rejected when the program is parsed, because every value other than a number takes only fill, alignment and width after :. Call format and pad its result instead:

print("{t:%H:%M}")                        # not valid
print("{t.format(`%H:%M`):>8}")           # valid: a method call, then padding

Errors

FailureRaisesData
parse(text, layout=…) of text that does not fitParseError parse() "19/07" does not match layout "%d/%m/%Y"text, layout
parse(text) of text that is not ISO 8601ParseError parse() "19/07" is not an ISO 8601 timetext, and layout as nil
An unknown directiveValueError format() unknown layout directive %Q—
%Z, %G or %V in a parse layoutValueError parse() layout directive %Z can only be used to format—
An unknown zoneValueError to_zone() unknown time zone "Asia/Shangai"—
A negative sleep; a constructor result, a unix or arithmetic outside the years 1 to 9999ValueError—

A bad layout or zone is a mistake in the program rather than in the data, so it is a ValueError and is reported whatever the text.

Left out

A Duration type (a duration is a number of seconds, and a format specifier shows it: "{elapsed:.1f} s"); calendar arithmetic as a method ("add one month": rebuild with Time(...), which rolls over); to_local() (it is to_zone("local")); listing the known zone names; parsing zone abbreviations; choosing between the two readings of an ambiguous wall-clock time; localised month and weekday names; a layout as a format specifier; a to_json() on Time (write t.format() or t.unix where you encode).

rand

The rand module makes everyday random choices, secure random bytes and ids. Its functions draw from one shared generator seeded differently on every run; rand.Rand(seed) gives a generator of its own when the same sequence is needed on every run, as in a test.

Common tasks

import "rand"

# Pick one, pick a few
var winner = rand.choice(entrants)
var panel = rand.sample(entrants, 3)

# Pick one where some are likelier than others
var drop = rand.choice(["common", "rare", "epic"], weights=[90, 9, 1])

# Numbers
var die = rand.int(1, 7)
var index = rand.int(items.size)
if rand.float() < 0.1 {
    print("one time in ten")
}

# Shuffle a deck
var deck = rand.shuffle(List(range(52)))

# A token that is safe to use as a secret
var token = rand.bytes(16).to_hex()

# A shorter secret that is safe in a URL or a file name (import "base64"): 24 characters
var invite = base64.encode(rand.bytes(18), url_safe=true)

# An id for a record, a file, a request
var id = rand.uuid()
fs.write("jobs/{id}.json", json.encode({"id": id, "state": "queued"}))

# Ids that sort in the order they were made
var first = rand.uuid(version=7)
var second = rand.uuid(version=7)
print(first < second)                       # true

# Is this text a UUID (import "regex")
func is_uuid(text) {
    return regex.find(`[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}`, text.lower(), full=true) != nil
}

# The same "random" data in every test run
var fixed = rand.Rand(42)
var sample_users = fixed.sample(users, 5)
print(fixed.int(100))

docs/examples/rand-tasks.goblin runs these tasks; examples/rand.goblin covers the rest of the module.

Module functions

MemberReturnsBehaviour
int(end) / int(start, end)IntA whole number from start (0 when omitted) up to but not including end: the numbers range with the same arguments would produce. rand.int(6) is 0–5, rand.int(1, 7) a die. ValueError int() range is empty when end <= start
float()FloatFrom 0.0 up to but not including 1.0
choice(items, weights=nil)elementOne element of items (any iterable), each equally likely. With weights, a List of non-negative Ints or Floats, one per item, an item is picked in proportion to its weight ([90, 9, 1]: nine times in ten the first)
sample(items, count)Listcount different elements of items, in random order. Different means by position, so equal values may repeat if items has them. count=0 is []
shuffle(list)the same ListPuts list in random order in place and returns it
bytes(size)Bytessize bytes from the operating system's secure source: fit for tokens, keys and passwords. size is at most 1073741824 (1 GiB), because the bytes are made in memory at once
uuid(version=4)StringA new UUID in its usual text form, 36 lower-case characters: 0190f3c2-7b1a-7d3e-9c4f-2a6b8e1d5f00. Version 4 is random. Version 7 starts with the time in milliseconds, so ids made later sort later as plain Strings. The random bits come from the secure source
Rand(seed)RandA generator of its own whose sequence is fixed by the Int seed

Apart from bytes and uuid, the functions use the shared generator, which is not suitable for secrets. Every function is safe to call from several goblins at once.

FailureRaises
int with end <= startValueError int() range is empty
choice of an empty iterableValueError choice() argument 'items' is empty
weights of a different length, with a negative number, or all zeroValueError
sample with a negative count or more than there are itemsValueError
shuffle of anything but a ListTypeError
A negative bytes size or one above 1 GiB; a uuid version other than 4 or 7ValueError (bytes() argument 'size' must be at most 1073741824, got 2147483648, uuid() argument 'version' must be 4 or 7, got 1)
The secure source failingIOError

Two version-7 ids made in the same millisecond are not ordered: the random part follows the timestamp directly, with no counter. That is enough for records and file names; a strict sequence is a counter, not a UUID.

Rand

A seeded generator. Two Rand values with the same seed produce the same results for the same calls, on every run and on every machine.

MemberBehaviour
int(end) / int(start, end), float(), choice(items, weights=nil), sample(items, count), shuffle(list)As the module functions, drawing from this generator

There is no Rand.bytes and no Rand.uuid: both promise unpredictability, which a seed removes. A Rand prints as <Rand seed=42> and equals only itself.

Left out

A UUID value type and parsing UUIDs (an id is a String; normalise one from input with text.lower() and check it with the pattern above); normally distributed numbers; a random Float in a range (low + rand.float() * (high - low)); several picks with repeats (List(range(n)).map(func(i) { return rand.choice(items) })).

math

The math module holds Float functions, constants and basic statistics. Its members are plain functions: x is an Int or a Float everywhere, and results are Floats unless a row says otherwise.

Common tasks

import "math"

# Geometry
var area = math.PI * math.pow(radius, 2)
var distance = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))
var heading = math.atan2(dy, dx) * 180 / math.PI
print("heading {heading:.1f} degrees, {distance:,.0f} m away")

# Whole numbers from measurements
var pages = math.ceil(items.size / 20.0)
var percent = math.round(100.0 * done / total)

# Two decimal places: in the value, or only in the text
var price = math.round(total * 100) / 100.0
print("total: {total:.2f}")

# Statistics of a set of measurements
var timings = [0.82, 0.79, 1.31, 0.80, 0.85]
print("mean {math.mean(timings):.2f} s, median {math.median(timings):.2f} s")
print("spread {math.stdev(timings):.2f} s, 95th percentile {math.percentile(timings, 95):.2f} s")
print("total {sum(timings):.1f} s, slowest {max(timings):.2f} s")
var ages = people.map(func(p) { return p["age"] })
var typical_age = math.round(math.median(ages))

# Orders of magnitude
var digits = math.floor(math.log(n, base=10)) + 1

docs/examples/math-tasks.goblin runs these tasks; examples/math.goblin covers the rest of the module.

Members

MemberReturnsBehaviour
PI, EFloatConstants
INFFloatPositive infinity; -math.INF is the negative one
NANFloatNot-a-number. It equals nothing, itself included: test with is_nan
sqrt(x)FloatSquare root; NAN for a negative x
pow(x, y)Floatx to the power y, also for two Ints (the language has no power operator; an exact Int power is repeated multiplication)
exp(x)FloatE to the power x
log(x, base=nil)FloatLogarithm; base=nil is the natural logarithm. log(8, base=2) and log(1000, base=10) are exact. -INF for 0, NAN for a negative x. ValueError unless base is positive and not 1
sin(x), cos(x), tan(x)Floatx in radians
asin(x), acos(x), atan(x)FloatRadians; NAN outside the domain
atan2(y, x)FloatThe angle of the point (x, y), −π to π
abs(x)Int for an Int, Float for a FloatMagnitude. OverflowError for the smallest Int
floor(x)IntLargest whole number ≤ x
ceil(x)IntSmallest whole number ≥ x
round(x)IntNearest whole number, halves away from zero (round(2.5) is 3, round(-2.5) is −3)
is_nan(x)BoolWhether x is NAN

floor, ceil and round return an Int because that is what the result is used as: an index, a count. An Int argument is returned as it is. NAN or an infinity is a ValueError (floor() cannot convert NaN), and a result that does not fit 64 bits an OverflowError. Truncation toward zero is Int(x).

Every function raises TypeError for a non-number: sqrt() argument 'x' must be Int or Float, got String. Domain errors follow IEEE 754: they produce NAN or an infinity and do not raise.

Statistics

Four functions over a set of measurements. values is any iterable of Ints and Floats (a List, a range, the values of a Dict); it is read once and not changed.

MemberReturnsBehaviour
mean(values)FloatThe arithmetic mean
median(values)FloatThe middle value in sorted order; for an even count, the mean of the two middle values
stdev(values)FloatThe sample standard deviation (divides by n − 1): how far a measurement typically lies from the mean
percentile(values, p)FloatThe value below which p percent of the values fall, p being an Int or Float from 0 to 100. Between two values it interpolates linearly, as spreadsheet PERCENTILE and NumPy do by default. p=0 is the smallest value, p=100 the largest, p=50 the median
  • The result is always a Float, also for Ints and also when it is whole (math.mean([1, 2, 3]) is 2.0). math.round(…) makes an Int.
  • Empty input raises ValueError (mean() argument 'values' is empty; stdev() needs at least two values, got 1). There is no mean of nothing, and 0.0 or NAN would travel silently into a report: test values.size first when empty is expected.
  • An element that is not an Int or Float is a TypeError (mean() argument 'values' must contain only Int or Float, got String); a Bool is not a number. A NAN among the values gives NAN from mean and stdev, whose arithmetic carries it through, and is a ValueError from median and percentile (median() cannot order NaN): they sort the values, and a NaN has no place in an order, as with sort().
  • A p outside 0–100 is a ValueError.
  • The population deviation is math.stdev(xs) * math.sqrt((n - 1.0) / n), and the variance math.pow(math.stdev(xs), 2).

Sums and extremes are the globals sum, max and min, which work on any values that add or compare, not only numbers.

Formatting and powers

Printing a number a certain way is not this module's job: format specifiers do it ("{x:.2f}", "{n:,}", format(x, spec); see Strings). Rounding a value to decimals is math.round(x * 100) / 100.0; showing two decimals is {x:.2f}. They are different operations, and the first is rare.

Left out

round(x, digits) (format specifiers); a power operator (deferred in the language, so pow stays); trunc (Int(x)); log2/log10 (log(x, base=2)); cbrt (math.pow(x, 1.0 / 3)); hypot (math.sqrt(x * x + y * y)); is_inf (x == math.INF); the hyperbolic functions; max/min (the globals); variance, the population deviation, mode and correlation.

http

The http module is an HTTP client built on two messages. A Request is what a client sends and a Response is what it receives; both have headers (a Headers) and a body (always a File). Four functions send a request:

FunctionDoes
exchange(request)One request, one response. Adds nothing, follows nothing, checks nothing
send(request)What a user agent does: default headers, User-Agent, gzip, cookies, redirects, then the status check, as stated steps over exchange
request(method, url, …)send of the Request built from the arguments
get(url, …)request("GET", url, …)

Anything that is a policy (which base a path is relative to, when to try again, how a value becomes a body) is written by you, with the pieces below.

Common tasks

import "base64"
import "fs"
import "hash"
import "http"
import "json"
import "time"
import "url"

# Fetch JSON. A 404 or 500 raises, so the next line can trust what it got
var repo = json.decode(http.get("https://api.github.com/repos/aisk/goblin").body)
print(repo["stargazers_count"])

# A page as text
var page = http.get("https://example.com/").text()

# Query parameters: the url module writes the query
var query = url.encode_query({"q": "goblin lang", "page": 2})
var found = json.decode(http.get("https://api.example.com/search?{query}").body)
for item in found["items"] {
    print(item["name"])
}

# Send JSON: encode it, and say what it is
var created = http.request("POST", "https://api.example.com/users",
    headers={"Content-Type": "application/json"},
    body=json.encode({"name": "Ada"}))
print(created.status, created.headers.get("location"))

# Send a form
http.request("POST", "https://example.com/contact",
    headers={"Content-Type": "application/x-www-form-urlencoded"},
    body=url.encode_query({"email": "ada@example.com", "message": "hello"}))

# Upload a file with two form fields
var photo = fs.open("photo.png")
defer photo.close()
var form, form_type = http.multipart(
    fields={"title": "Me", "album": "2026"},
    files={"avatar": photo},
)
http.request("POST", "https://example.com/profile", headers={"Content-Type": form_type}, body=form)

# Send a big file as the body, without holding it in memory
var backup = fs.open("backup.tar.gz")
defer backup.close()
http.request("PUT", "https://storage.example.com/backup.tar.gz", body=backup, timeout=nil)

# Download to a file without holding it in memory; an error page is never saved
fs.write("goblin.tar.gz", http.get(release_url).body)

# Where did a redirect end
var landed = http.get("https://example.com/latest")
print(landed.url, landed.url.path)

# Does it exist, and how big is it, without fetching it
var head = http.request("HEAD", "https://example.com/big.iso", check=false)
print(head.status, head.headers.get("content-length"))

# Fetch only when it changed (a 304 is an answer and does not raise)
var feed = http.get(feed_url, headers={"If-None-Match": etag})
if feed.status != 304 {
    fs.write("feed.xml", feed.body)
    fs.write("feed.etag", feed.headers.get("etag", default=""))
}

# Handle a status you expect
try {
    http.request("DELETE", "https://api.example.com/users/7")
} catch e: http.StatusError {
    if e.status != 404 {
        eprint(e.response.text())
        raise e
    }
}

# A status that is an answer: wait until a job is there
var job = http.get(job_url, check=false)
while job.status == 404 {
    time.sleep(2)
    job = http.get(job_url, check=false)
}
print(json.decode(job.body)["state"])

# An API you call many times: shared headers in a Client, the address in a variable
var api = "https://api.example.com/v1"
var client = http.Client(headers={"Authorization": "Bearer {token}"}, timeout=10)
var id = json.decode(client.get("{api}/me").body)["id"]
client.request("DELETE", "{api}/sessions/current")

# A helper of your own, when a script sends JSON many times
func call(method, path, value) {
    var reply = client.request(method, "{api}{path}",
        headers={"Content-Type": "application/json"}, body=json.encode(value))
    return json.decode(reply.body)
}
call("PATCH", "/users/{id}", {"active": false})

# User name and password (Basic authentication)
var credentials = base64.encode("{user}:{password}")
var inbox = http.get("https://example.com/inbox", headers={"Authorization": "Basic {credentials}"})

# Log in, then fetch pages as that user: the Client keeps the session cookie
var shop = "https://example.com"
var site = http.Client()
var form_headers = {"Content-Type": "application/x-www-form-urlencoded"}
site.request("POST", "{shop}/login", headers=form_headers,
    body=url.encode_query({"user": "ada", "password": secret}))
var orders = site.get("{shop}/account/orders").text()

# A cookie the site wants echoed in a header
var csrf = site.cookies(shop)["csrftoken"]
site.request("POST", "{shop}/account/email",
    headers={"Content-Type": "application/x-www-form-urlencoded", "X-CSRFToken": csrf},
    body=url.encode_query({"email": "ada@example.com"}))

# Keep the session for the next run
fs.write("session.json", json.encode(site.cookies(shop)))
var saved = json.decode(fs.read("session.json"))
var resumed = http.Client(cookies={shop: saved})

# An internal service with a self-signed certificate. This gives up knowing who answers
var lab = http.Client(insecure=true)
print(json.decode(lab.get("https://build.lab.internal/status").body)["state"])

# A stream of events (one JSON document per "data:" line): each line as it arrives
var events = http.get("https://api.example.com/events", timeout=nil)
defer events.body.close()
for line in events.body {
    if line.has_prefix("data: ") {
        var event = json.decode(line.trim_prefix("data: "))
        print(event["type"])
    }
}

# A request is a value: build it, change it, send it
var ping = http.Request("POST", "https://api.example.com/ping", body="hello")
ping.headers["X-Signature"] = hash.hmac(secret, "POST /ping hello").to_hex()
http.send(ping, timeout=5)

# Try again when the network or the server has a bad moment: one function for any request
func send_patiently(request, attempts=4) {
    var pause = 1
    for attempt in range(attempts - 1) {
        try {
            return http.send(request, timeout=10)
        } catch e: http.StatusError {
            if ![429, 502, 503, 504].contains(e.status) {
                raise e
            }
            var advice = e.response.headers.get("retry-after")
            if advice != nil {
                pause = Int(advice)     # seconds; a server that sends a date needs time.parse
            }
        } catch e: NetworkError {
        } catch e: TimeoutError {
        }
        time.sleep(pause)
        pause = pause * 2
    }
    return http.send(request, timeout=10)     # the last attempt raises whatever it meets
}
var prices = json.decode(send_patiently(http.Request("GET", "https://api.example.com/prices")).body)

# Every cookie a server set, as it was sent
for cookie in landed.headers.get_all("set-cookie") {
    print(cookie.split(";")[0])
}

# Where a short link points, without following it: one exchange
var hop = http.exchange(http.Request("GET", short_url))
print(hop.status, hop.headers.get("location"))

# Follow redirects yourself, printing each step
var step = http.Request("GET", short_url)
var reply = http.exchange(step)
while [301, 302, 303, 307, 308].contains(reply.status) {
    var target = step.url.join(reply.headers["location"])
    print(reply.status, target)
    step = http.Request("GET", target)
    reply = http.exchange(step)
}

# The bytes exactly as the server sent them, compressed or not
var raw = http.get(export_url, headers={"Accept-Encoding": "identity"})
fs.write("export.bin", raw.body)

examples/httpserver/testdata/http_tasks.goblin runs each of these tasks against a local server that the example tests start, through the interpreter and as a compiled program; examples/http.goblin covers what needs no server.

Posting JSON or a form names a Content-Type and calls an encoder. That is deliberate: the body is always the bytes you give, the header says what they are, and JSON and query strings have one home each (json.encode, url.encode_query). A script that does it often writes the four-line helper above.

Module members

MemberReturnsBehaviour
Headers(fields=nil)HeadersHeaders
Request(method, url, headers=nil, body=nil)RequestRequest. Sends nothing
Response(status, headers=nil, body=nil)ResponseResponse. Sends nothing
Client(headers=nil, timeout=30, cookies=nil, insecure=false, redirects=10)ClientClient
exchange(request, timeout=30)Responseexchange, on a new Client()
send(request, timeout=30, check=true)Responsesend, on a new Client()
request(method, url, headers=nil, body=nil, timeout=30, check=true)Responsehttp.send(http.Request(method, url, headers=headers, body=body), timeout=timeout, check=check)
get(url, headers=nil, timeout=30, check=true)Responsehttp.request("GET", url, headers=headers, timeout=timeout, check=check)
multipart(fields=nil, files=nil)List [body, content_type]Multipart bodies. Sends nothing
StatusErrorerror kindErrors
  • request and get are exactly the expressions in the table: they have no behaviour of their own. There is no post, put, patch or delete: the method is a setting, so it is the first argument of request.
  • Headers, Request, Response and Client are constructors and are what type_of(x) returns.
  • Each module function runs on a new Client(). A module call therefore keeps the cookies it is given for the length of its own redirect chain (a login that answers "303, here is your cookie" works) and forgets them when it returns; two module calls never share cookies. Connections are shared by every call in the process.
  • Error messages name the function you called: get() …, request() …, send() …, exchange() …, Request() ….

Headers

The header fields of one message. Names are case-insensitive and are stored in lower case. A name may have several values. A Headers is mutable, like a Dict.

Headers(fields=nil) takes nil (empty), a Dict of String to String or to a List of String (one name per entry, in the Dict's order; a List gives the name several values; two keys that differ only in case are one name, their values joined in order), or a Headers (a copy). Every headers= parameter of the module accepts the same three and makes its own copy, so changing the Dict or the Headers afterwards does not change the message.

MemberKindValue
h[name]indexString: the value, or all values joined with ", ". KeyError when the name is absent
h[name] = valueindex assignmentReplaces every value of name. value is a String or a List of String; an empty List removes name, as remove does, because a field without a value is not sent. A Dict given to Headers (or any headers=) treats an empty List the same way
get(name, default=nil)methodAs h[name], or default when the name is absent
get_all(name)methodA new List of String: each value as it was sent or added, in order. [] when absent. This is the reading for set-cookie, whose values contain commas
add(name, value)methodAdds one more value (a String) to name and keeps the ones it has. Returns the Headers
remove(name)methodRemoves the name with all its values; an absent name is accepted. Returns the Headers
contains(name)methodBool
keys()methodA new List of String: the names, lower case, in order
items()methodA new List of [name, value], one pair per value, so a name with two values appears twice
sizepropertyInt: the number of names
for name in hiterationThe names, as keys()
==, !=EqEqual when both have the same names and each name the same values in the same order. The order of different names is ignored, as HTTP gives it no meaning. A Headers never equals a Dict
conditionsTruthFalse when empty, as a Dict
print(h)ShowHeaders({"content-type": "text/html", "set-cookie": ["a=1", "b=2"]}): one value shows as a String, several as a List
  • name is a String in any case in every member.
  • Names keep the order in which they were first added. The names of a received message are in alphabetical order, because Go's parser keeps them in a map; the values of one name are in the order they were sent.
  • A Headers is not hashable and has no order. There is no values() (it would be confused with get_all(name)), no copy() (the constructor copies) and no pop, update or clear.
FailureRaises
fields of another type; a name that is not a String; a value that is not a String (or List of String where a List is allowed)TypeError Headers() argument 'fields' values must be String or List of String, got Int
A name that is empty or has a character outside the RFC 9110 token set (a space, a colon, a control or non-ASCII character)ValueError Headers() invalid header name "a b"
A value with a control character other than tab, or DELValueError Headers() invalid value for header "x-id"
h[name] on an absent nameKeyError key not found: "x-id", as a Dict

The function named is the one used (add() invalid header name "a b"), or the one whose headers= received the value (request() argument 'headers' values must be …, request() invalid header name "a b"). Index assignment is syntax, so its message names no function (invalid header name "a b").

Request

http.Request(method, url, headers=nil, body=nil) builds a request message. It sends nothing: something a retry function, a signer or a logger can take.

ArgumentAcceptsMeaning
methodStringAny HTTP method name, sent as written. Method names are case-sensitive: "GET" is the method, "get" a different token that servers refuse
urlString or url.URLAbsolute, scheme http or https, without a user name or password. There is no base to resolve against: a URL built from parts is an interpolation, "{api}/users/{id}". When the request is sent, a byte the request line cannot hold (a space, a non-ASCII character, a % that starts no escape) is percent-encoded, in the path and in the query, and so is a followed redirect's Location; an existing %XX escape and the query's delimiters (&, =, +, …) are sent as written, so ?q=new york arrives as ?q=new%20york and ?tag=a+b as ?tag=a+b. The url of the Request and of the Response show the query as written: it is encoded only on the wire
headersnil, Dict, HeadersHeaders
bodynil, String, Bytes, readableThe content, as it is. No Content-Type is added. See How a body is sent
MemberKindValue
methodpropertyString
urlpropertyurl.URL
headerspropertyHeaders. The same object on every read, so request.headers["X-Signature"] = … changes what is sent
bodypropertyFile, read-only. The same object on every read. Never nil: a message without content has an empty stream
text()methodbody.read().decode(): the rest of the body as a String. ValueError text() body is not valid UTF-8 when it is not UTF-8; "" when the body is empty or was already read

It shows as <Request POST https://example.com/users>. Its properties are read-only; to change the method, URL or body, build a new one: http.Request(r.method, other, headers=r.headers, body=r.body).

Response

http.Response(status, headers=nil, body=nil) builds a response message (status is an Int from 100 to 999); exchange, send, request and get return the one they received.

MemberKindValue
statuspropertyInt
headerspropertyHeaders. The same object on every read
bodypropertyFile, read-only. The same object on every read
text()methodAs on Request
urlpropertyurl.URL: the URL of the request this response answers. For exchange it is the request's URL; for send it differs when a redirect was followed. nil on a Response that was built
versionpropertyString: the HTTP version of the exchange, "1.1", "2", "1.0". nil on a Response that was built

It shows as <Response 200>. There is no reason phrase (HTTP/2 does not send one) and no success: compare status. Messages compare by identity and are not hashable.

A handler is a function from a Request to a Response, and it can be tested without a network:

func orders(request) {
    if request.method != "POST" {
        return http.Response(405, headers={"Allow": "POST"})
    }
    var order = json.decode(request.body)
    return http.Response(201, headers={"Content-Type": "application/json"},
        body=json.encode({"id": 7, "item": order["item"]}))
}
print(orders(http.Request("POST", "http://test/orders", body=json.encode({"item": "tea"}))).status)

The body of a message

body is always a File, the stream type of os.stdin and of pipes. Its members are those of the fs chapter: read(size=nil), read_line(), for line in, close(), closed; path is nil; write raises the File's ValueError.

The messagebody isShows as
Built with body=nilAn empty stream<File body>
Built with a String or BytesA stream over a copy of those bytes. The message keeps the bytes: reading body does not change what a later send sends<File body>
Built with a File (this includes the body from http.multipart and the body of another message)That File itselfas that File
Built with another readable (a value with read(size))A File that reads from it. Closing this File does not call the readable's close()<File body>
ReceivedThe content as it arrives from the network<File body>

Being a File, a body goes to anything that takes data: json.decode(response.body), fs.write(path, response.body), csv.decode(response.body), hash.sha256(response.body), gzip.decompress(response.body), and body= of another message. A message is not a readable itself: fs.write(path, response) is the TypeError that asks for a read(size) method.

A received body and its connection.

  • The connection is released when the body has been read to its end or body.close() is called. A response whose body is read needs no defer.
  • A loop over response.body that may stop early gets defer response.body.close(). After break, read continues where the loop stopped.
  • A response dropped unread releases its connection when it is collected. A program that makes many requests and ignores the bodies should close them.
  • closed is true only after close() was called.

Reading a received body can fail: NetworkError cannot read the response body from example.com when the connection breaks, and TimeoutError timed out after 30 seconds waiting for the response body from example.com when no data arrives for the timeout of the call that returned the Response (Timeouts). A line that is not valid UTF-8 raises the File's ValueError. These messages name no function, because the read happens inside read, a for loop or a function such as json.decode that was given the body.

exchange: one request, one response

client.exchange(request, timeout=<the client's>) returns a Response; http.exchange(request, timeout=30) is the same on a new Client().

It sends the request to the host of its URL and returns when the status and headers of the response have arrived. The body is not read: it is response.body. The request object is not changed.

  • The request's headers are sent as they are. No User-Agent, no Accept-Encoding, no cookie and no default header of the Client is added.
  • The response is returned whatever its status: a 3xx is returned, and so is a 404.
  • The body is the bytes the server sent. No content coding is decoded.
  • Of the Client, only the connection setting (insecure) and the default timeout apply.

What the library still decides in an exchange is the wire format: the Connection table and How a body is sent. A CONNECT request is a ValueError exchange() cannot send a CONNECT request.

send: a user agent's request

client.send(request, timeout=<the client's>, check=true) returns a Response; http.send(request, timeout=30, check=true) is the same on a new Client(). timeout is one limit for all the steps (Timeouts); check=false returns the Response whatever its status.

send does the following, in this order. This is the complete list.

  1. Copies the request's headers and adds: each default header of the Client whose name the request does not have; User-Agent: goblin/<version> when there is none; Accept-Encoding: gzip when there is none, the request has no Range header and the method is not HEAD; and the Client's cookies for the URL.
  2. Performs one exchange.
  3. Stores the cookies the response sets.
  4. When the response is a 301, 302, 303, 307 or 308 with a Location, fewer than redirects redirects have been followed, and the next request can be built: releases this response and repeats from step 1 with the next request (Redirects).
  5. When step 1 asked for gzip and the response has Content-Encoding: gzip: the body is decoded as it is read, and content-encoding and content-length are removed from the response's headers.
  6. With check=true, raises http.StatusError when the status is 400 or above, or when the response is a redirect that step 4 would have followed and did not (the limit was reached, or a 307 or 308 asked for a stream body to be sent again).

The Response send returns is the last one. A caller who needs the steps separately calls exchange and writes the ones it wants, as the redirect loop in the common tasks does.

Client

http.Client(headers=nil, timeout=30, cookies=nil, insecure=false, redirects=10)

A Client holds the settings of its connections, default headers, a cookie store and a redirect limit. It shows as <Client>, has no properties and nothing to close, and several goblins may use one Client. It does not hold a base URL: every request names its full URL.

MemberBehaviour
exchange(request, timeout=<client's>)exchange
send(request, timeout=<client's>, check=true)send
request(method, url, headers=nil, body=nil, timeout=<client's>, check=true)client.send(http.Request(method, url, headers=headers, body=body), timeout=timeout, check=check)
get(url, headers=nil, timeout=<client's>, check=true)client.request("GET", url, headers=headers, timeout=timeout, check=check)
cookies(url)A new Dict of name to value: the cookies the client would send to url (String or URL) now. {} when there are none. ParseError for an invalid URL, ValueError for one that is not an absolute http or https URL (cookies() needs an absolute URL, got "shop")

check is per call; it is not a Client setting. A per-call timeout, nil included, replaces the Client's.

What the library does without being asked

The complete list. The first table applies to exchange and therefore to everything; the second applies to send, request and get only.

Connection (every exchange).

BehaviourDetailTo change it
FramingContent-Length or chunked encoding is computed from the body. Content-Length, Transfer-Encoding, Connection, Keep-Alive, Proxy-Connection, TE and Upgrade in the request's headers are not sent: they describe one connection or one wire format—
HostThe request names the host of its URL. A Host header replaces that name; the connection still goes to the host of the URLA Host header
Protocol versionHTTP/2 for https URLs when the server offers it, HTTP/1.1 otherwise—
ConnectionsKept and reused, shared by all Clients with the same insecure setting—
A dead reused connectionWhen a request fails on a reused connection before any response arrived, it is sent once more on a new connection, if nothing of it had been written, or if its method is GET, HEAD, OPTIONS or TRACE (or it has an Idempotency-Key header) and its body can be sent again. This is the only case in which the library repeats a request on its own—
Interim responses1xx responses are skipped. A request with Expect: 100-continue waits up to one second for the 100 before sending its body—
ProxyThe one named by HTTP_PROXY, HTTPS_PROXY, NO_PROXY (never for localhost and loopback addresses)The environment
TLS verificationCertificates are verified against the system's store (SSL_CERT_FILE/SSL_CERT_DIR on Linux)Client(insecure=true)

User agent (send, request, get).

BehaviourDetailTo turn it off or change it
Default headersEach header of Client(headers=…) whose name the request does not have is addedheaders=nil
User-Agent: goblin/<version>Added when neither the request nor the Client's headers name one. The version is what goblin --version printsName one
gzipAccept-Encoding: gzip is added when the request names no Accept-Encoding, has no Range header and is not a HEAD. A response with Content-Encoding: gzip is then decoded as it is read, and content-encoding and content-length are absent from its headersName an Accept-Encoding (for example "identity"), on the request or in the Client's headers. The body then arrives as the server sent it
CookiesThe Client keeps the cookies servers set (Set-Cookie, on redirects too) and sends each back to the site that set it, by the browser rules for domain, path, Secure and expiry. A Cookie header on the request is sent beside themA new Client has none. exchange neither stores nor sends any
RedirectsBelowClient(redirects=0)
Status checkStep 6 of sendcheck=false

Nothing else is added, repeated or decided. In particular the library adds no Referer, no Accept, no Content-Type and no Authorization, and never retries on a status.

Redirects

A 301, 302, 303, 307 or 308 with a Location is followed, up to redirects times.

  • The next URL is the Location resolved against the URL of the request that was answered.
  • 301, 302, 303: the next request is a GET without a body (a HEAD stays a HEAD), and the original request's Content-Type, Content-Encoding, Content-Language and Content-Location headers are not sent with it.
  • 307, 308: the same method and body, when the body can be sent again. When it cannot (a stream), the redirect is not followed.
  • The other headers of the original request are sent again, except that Authorization, Cookie, Proxy-Authorization, WWW-Authenticate and Proxy-Authenticate are not sent once a redirect has led to a host that is neither the original host nor a subdomain of it.
  • Response.url says where the chain ended.
  • redirects is an Int, 0 or more. With redirects=0 every 3xx is returned as it is, and check does not raise for it: you asked to see it.
  • When a redirect is not followed because redirects were already followed, or because a 307 or 308 needs a stream body again, check=true raises http.StatusError and check=false returns that 3xx response. An upload answered by a 307 has uploaded nothing, so it is not allowed to pass as a success.

Cookies

Client(cookies=nil) starts with no cookies. cookies={url: {name: value}} starts with cookies: the keys are URLs (String or URL) and the values are what cookies(url) returns, so a saved session is restored in one call.

  • Each given cookie belongs to the host of its URL, every path, only over TLS when the URL is https, and is kept until the Client is dropped. Original expiry dates are not restored.
  • A bare {name: value} has no site to belong to and is a TypeError (Client() argument 'cookies' values must be Dict, got String).
  • A key is checked as Request() checks its URL: "example.com", without a scheme, is a ValueError (Client() needs an absolute URL, got "example.com") rather than a site no request would match.
  • A name must be a token and a value made of cookie characters (printable ASCII other than space, ", ,, ; and \), or the cookie could not be sent as given: ValueError Client() invalid cookie name "a b", Client() invalid value for cookie "sid".
  • As in browsers, localhost and loopback addresses count as secure, so a Secure cookie for them is also sent over plain http.
  • Cookies cannot be edited or cleared: a session that should forget is a new Client. A cookie for one request only is headers={"Cookie": "name=value"}.

insecure

insecure=true turns off TLS certificate verification for every connection this Client makes, redirects included. Any certificate is accepted, for any host name, expired or not. The connection is still encrypted, but to whoever answered, so everything sent (tokens, cookies, bodies) can be read and changed by anyone on the path. It is for an internal or development service with a self-signed certificate that cannot be added to the system's store, and never for a public host. It is a Client setting only, so a script's trusted and untrusted traffic are different values. The safer fix where it is possible: name the certificate authority to the system (SSL_CERT_FILE on Linux, the keychain or certificate store elsewhere).

FailureRaises
redirects negativeValueError Client() argument 'redirects' must be non-negative, got -1
redirects a Bool or another typeTypeError Client() argument 'redirects' must be Int, got Bool
cookies keys or values of the wrong typeTypeError
cookies key not an absolute http or https URL; a cookie name or value that cannot be sentValueError Client() needs an absolute URL, got "example.com", Client() invalid cookie name "a b", Client() invalid value for cookie "sid"
headersAs for Headers

Timeouts

timeout is a number of seconds, or nil for no limit.

  • It limits the call it is given to. For exchange: connecting, sending the request with its body, and waiting for the status and headers. For send, request and get: all of that for every exchange of the redirect chain together, and reading an error body before StatusError is raised. When the limit passes, the call raises TimeoutError get() timed out after 30 seconds.
  • After the call has returned, the same number limits each wait for more of the response body. A body that keeps arriving is never cut off, however long the whole transfer takes. A body that stops arriving for longer than timeout raises TimeoutError from the read.

So a download of any size needs no timeout=nil. An upload that takes longer than the limit needs a larger one or nil, and so does a stream of events that can be silent for longer than the limit.

timeout= cannot cancel work in progress in another goblin: a timed-out request is abandoned.

How a body is sent

No header is derived from the body except the framing. In particular no Content-Type is set.

The request's body was built fromLengthCan be sent again (a 307 or 308, or a second send of the same Request)
nilNoneYes
String, BytesContent-LengthYes. The Request keeps the bytes
A File open on a regular fileContent-Length: from its position to its end, measured when the request startsNo
The body from http.multipartContent-Length when every part is a String, Bytes or such a File; otherwise unknownNo
The body of a received messageContent-Length when that message declared one and was not decoded from gzip; otherwise unknownNo
Any other readable (a pipe, os.stdin, a type with read(size))Unknown: chunked on HTTP/1.1No
  • A stream is read as it is sent and is never held whole. It is read to its end and not closed.
  • A Request whose body is a stream is good for one send or exchange. A second one is a ValueError before anything is sent: send() the body of this request is a stream that was already sent; build the request again.
  • A File that changes size while it is sent fails the request with a NetworkError.
  • Once the call has returned or raised, the request body is not read any further.
  • The headers of a received message can be passed to a new message unchanged, because the framing fields are dropped when it is sent. The headers of a received message never contain host (the host is in url) or transfer-encoding; they contain content-length when the server sent one. So a proxy is http.exchange(http.Request(r.method, target, headers=r.headers, body=r.body)).

Multipart bodies

http.multipart(fields=nil, files=nil) encodes a form with files as multipart/form-data and returns two things to pass on visibly. It sends nothing and reads nothing.

var body, content_type = http.multipart(fields={"title": "Me"}, files={"avatar": photo})
http.request("POST", target, headers={"Content-Type": content_type}, body=body)
ReturnedValue
bodyA read-only File (path is nil, shows as <File multipart>): the encoded form, produced as it is read. Parts are read when the body is, so nothing is held in memory and every stream given as a part must still be open when the request is sent
content_typeString multipart/form-data; boundary=…. The boundary is random and belongs to this body; the header must be this value
ArgumentAcceptsBecomes
fieldsDict of name to value; the values url.encode_query acceptsOne text part per field, in the Dict's order, before the files. A List value repeats the field
filesDict of field name to a partOne file part per entry, in the Dict's order. A List of parts repeats the field

A part in files is data, never a path:

PartFile nameContent type
A File that has a path (from fs.open)file.path.nameapplication/octet-stream
Dict {"data": data, "name": String, "content_type": String}name. Required, except when data is a File with a path, whose name is then the defaultcontent_type; application/octet-stream when absent
  • data is a String, Bytes or readable. Only data is required; a key other than these three is a ValueError.
  • A bare String, Bytes or other readable is not a part: multipart() file "avatar" needs a name: pass an open fs.File, or {"name": …, "data": …}. This is also what catches files={"avatar": "photo.png"}: a String here would be content, not a path.
  • Nothing is guessed: the content type is not derived from the file name.
  • In field names and file names, a carriage return, a line feed and " are written as %0D, %0A and %22, which is how browsers encode a form. Written as they are, a line break would end the part's header line and a quote would end the name.
  • The library closes nothing. Whoever opened a file closes it, with defer.
  • The body is good for one request. Sending it again is a ValueError (send() this multipart body was already sent; build it again); call multipart again, with the files opened again.
  • Empty fields and files give a valid empty form.

Errors

FailureRaisesData
send, request, get with check=true: the final status is 400 or abovehttp.StatusError get() https://api.example.com/users/9 returned 404 Not Foundstatus Int; response the Response
The same, when the redirect limit was reachedhttp.StatusError get() https://example.com/a was redirected more than 10 timesstatus, response (the last 3xx)
The same, when a 307 or 308 asked for a stream body againhttp.StatusError request() https://example.com/up answered 307 and the body is a stream that cannot be sent againstatus, response
No response arrived (DNS, connection, TLS)NetworkError get() cannot reach example.com; the Go error is the cause—
timeout passed in the callTimeoutError get() timed out after 30 seconds—
Reading a received body: the connection broke, or the gzip data send is decoding is damagedNetworkError cannot read the response body from example.com—
Reading a received body: no data for timeoutTimeoutError timed out after 30 seconds waiting for the response body from example.com—
A readable given as body=, or a part of a multipart body, raises while it is sentThat error, unchanged. The request is abandonedwhatever it carries
A readable's length changed while it was sentNetworkError send() the body changed size while it was sent to example.com—
A Request with a stream body sent a second time; a multipart body that was already read fromValueError, before anything is sent—
The argument of send or exchange is not a RequestTypeError send() argument 'request' must be Request, got Dict—
A CONNECT requestValueError send() cannot send a CONNECT request—
url is not a URLParseError Request() invalid URL "ht!tp://x": …, as url.parsetext
url has no scheme and host, a scheme other than http or https, or a user name or passwordValueError Request() needs an absolute URL, got "users/7"; … URL scheme must be http or https, got "ftp"; … URL must not contain a user name or password; send an Authorization header—
method empty or not a tokenValueError Request() invalid method "GET /"—
status outside 100–999ValueError Response() argument 'status' must be between 100 and 999, got 20—
body of another typeTypeError Request() argument 'body' must be String, Bytes, Nil or have a read(size) method, got Int—

About StatusError:

  • The URL in the message is the one of the request passed to the call. The phrase after the number is the standard one for that status; an unknown status has none.
  • Before it is raised the rest of the body is read into memory, within the call's timeout, and the connection is released. e.response holds no resource; its body, text(), headers, status and url work as on any Response. That is everything a retry function reads: e.status, and e.response.headers.get("retry-after").
  • Its parent is Error. It is not an IOError, because the exchange worked and the server said no. catch e: IOError is "could not talk to the server" (NetworkError and TimeoutError are both IOErrors, and siblings: catching one does not catch the other). A failure of a local file is an IOError but neither of the two, so a retry loop that catches NetworkError and TimeoutError does not retry a file that cannot be read.
  • exchange never raises it.

Left out

Left outWhat to do instead, or where it would go
A serverNot designed yet. It would be a function that calls a handler with a Request and sends the Response the handler returns; both types exist
post, put, patch, delete, headrequest(method, url, …)
json=, form=, params=, Response.json()json.encode, url.encode_query, json.decode(response.body)
Content codings other than gzipName the Accept-Encoding and decode the body yourself
status_text, successresponse.status; compare it
A base URL, relative request URLsAn interpolation, "{api}/users/{id}"; url.parse(base).join(ref) for a link found in a page
Retrying on a status or an errorA function over a Request, as above
auth=, a user name and password in the URLAn Authorization header, as above
Changing a message's method, url or body in placeBuild a new one
Declaring the length of a stream bodyA stream of unknown length is sent chunked
Trailers; seeing 1xx responses; an upgrade (WebSocket); CONNECTNot available
A custom CA file, client certificates, a proxy URL, HTTP/2 without TLS, HTTP/3, pool sizesThe system store and the environment
Certificate checks off for one request or module-widehttp.Client(insecure=true); deliberately not shorter
Editing or clearing a Client's cookies; cookie attributesA new Client; headers.get_all("set-cookie") shows what was sent
Decoding a multipart bodyIt would come with a server
Header names in their original case; the order of different names on the wireNot kept; HTTP/2 requires lower case and HTTP gives the order no meaning
Response charsets other than UTF-8response.body.read() gives the Bytes
Upload and download progressRead response.body with read(size) in a loop; wrap a file in a type with read(size)

regex

The regex module searches and rewrites text by pattern. A pattern is a String, written best as a raw string (`\d+`), and every function takes it first. There is no compiled-pattern object: a pattern is compiled the first time it is used and remembered (the most recent 256), so a pattern used in a loop costs one lookup per call.

The syntax is RE2, the syntax of Go's regexp package: matching takes time linear in the size of the text, and there are no backreferences or lookaround. Flags are written in the pattern: (?i) ignores case, (?m) makes ^ and $ match at line boundaries, (?s) lets . match a newline; they combine ((?im)) and can be put in front of a pattern held in a variable ("(?i)" + pattern). Named groups are (?P<name>…) or (?<name>…).

Common tasks

Patterns are written as raw strings: backslashes and braces in them are ordinary characters ("\d{4}" would be an escape error and an interpolation).

import "fs"
import "json"
import "os"
import "regex"

# Does it look right
if !regex.find(`^[a-z0-9_]+$`, username) {
    raise ValueError("bad user name: {username}")
}
var is_date = regex.find(`\d{4}-\d{2}-\d{2}`, text, full=true) != nil

# Pull fields out
var m = regex.find(`(\w+)@(\w+)\.com`, "mail ada@example.com today")
if m {
    var user, domain = m.groups
    print(user, domain, m.start)              # ada example 5
}

# Parse a log line: name the fields in the pattern, then look them up
var access = `(?P<ip>\S+) \S+ \S+ \[(?P<when>[^\]]+)\] "(?P<verb>[A-Z]+) (?P<path>\S+)[^"]*" (?P<status>\d{3}) (?P<bytes>\d+|-)`
var hits = {}
var records = []
for line in fs.read_lines("access.log") {
    var entry = regex.find(access, line)
    if entry == nil {
        continue                                # not an access line
    }
    if entry["status"] == "404" {
        hits[entry["path"]] = hits.get(entry["path"], default=0) + 1
    }
    records.push(entry.to_dict())                   # {"ip": "203.0.113.9", "when": "19/Jul/2026:09:30:00 +0800", "verb": "GET", …}
}
fs.write("access.json", json.encode(records))

# Point at the part that is wrong
var setting = regex.find(`port=(?P<port>\S+)`, config_line)
var start, end = setting.span("port")
print(config_line)
print(" " * start + "^" * (end - start))

# Every occurrence
for hit in regex.find_all(`#(\w+)`, post) {
    print(hit[1])
}

# Rewrite
print(regex.replace(`\s+`, "a   b \t c", " "))                    # a b c
print(regex.replace(`(\d+)-(\d+)`, "10-20", "$2-$1"))              # 20-10
print(regex.replace(`\d+`, "a1b22", func(m) { return "<{m.text}>" }))   # a<1>b<22>

# Split on a pattern
print(regex.split(`,\s*`, "a, b,c"))                               # ["a", "b", "c"]

# Search for text that is not a pattern, ignoring case
var needle = "(?i)" + regex.escape("a.c")
print(regex.find(needle, "abc"))                                   # nil
print(regex.find(needle, "xA.Cx").text)                            # A.C

# A pattern from the command line: check it once, then use it on every line
var pattern = os.args[0]
try {
    regex.find(pattern, "")
} catch e: ParseError {
    eprint(e.message)
    os.exit(2)
}
for line in os.stdin {
    if regex.find(pattern, line) {
        print(line)
    }
}

docs/examples/regex-tasks.goblin runs these tasks; examples/regex.goblin covers the rest of the module.

Module functions

MemberReturnsBehaviour
find(pattern, text, full=false)Match or nilThe leftmost match in text; nil when there is none. With full=true the pattern must match the whole of text
find_all(pattern, text, count=nil)List of MatchEvery non-overlapping match, left to right; at most count. No match is []
replace(pattern, text, replacement, count=nil)Stringtext with its matches replaced, at most count of them. replacement is a template String or a function
split(pattern, text, count=nil)List of StringThe pieces of text between matches; at most count splits. No match is [text]
escape(text)Stringtext with every pattern metacharacter quoted, for building a pattern around data

count means what it means on String.split and String.replace: the most times the operation runs; nil is no limit, and a negative count is a ValueError. All arguments are Strings; Bytes is a TypeError (decode first).

Empty matches follow Go: find_all keeps them, except one immediately after the previous match (regex.find_all("^|$", "ab") finds two).

Replacement

A template String refers to groups with $1 or ${1} by number and $name or ${name} by name; $$ is a dollar sign. Write templates as raw strings too, since { in a double-quoted string starts an interpolation. A reference to a group the pattern does not have is a ValueError (replace() template refers to unknown group 'x') rather than silently becoming empty text. $1x refers to a group named 1x; write ${1}x for group 1 followed by an x. A $ that starts no reference is kept as it is.

A function is called with each Match, in order, and returns the String to put there: func(m) { return m.text.upper() }. A result that is not a String is a TypeError, and an error the function raises ends replace and propagates.

Match

The type name Match is exported for type_of(m) == regex.Match; calling it raises TypeError. A Match is an immutable snapshot of one match, and always truthy, so if regex.find(...) is the test for "does it match". It shows as <Match "ada@example.com">, with the matched text.

MemberKindValue
textpropertyString, what the whole pattern matched
start, endpropertyInt positions in the searched text, counted in characters like every String position, so searched[m.start:m.end] == m.text
groupspropertyList of the capture groups 1…n, each a String, or nil for a group that took no part. A new List on every read, so changing it does not change the Match; made for destructuring
match[key]indexAn Int selects a group by number (0 is the whole match), a String by name. nil for a group that took no part
to_dict()methodA new Dict of every named group, name to String (or nil for one that took no part), in the order the names appear in the pattern. {} when the pattern names none
span(key)method[start, end]: where that group matched, in characters, so searched[start:end] == match[key]. key as for match[key]. nil for a group that took no part

start and end are the whole match's position, the common case; span is for a group and is made for destructuring: var start, end = m.span("port").

A group that took no part is nil, which keeps it apart from a group that matched empty text (""). A key the pattern does not have is an IndexError (no such capture group: 3); a key that is neither Int nor String is a TypeError. When a pattern uses one name for several groups, match[name], span(name) and to_dict() all report the last of them that took part.

Errors

FailureRaisesData
An invalid pattern, in any functionParseError find() invalid pattern: missing closing ): `(` pattern, the String as given
A template naming a missing groupValueError replace() template refers to unknown group 'x'—
A replacement function returning something other than a StringTypeError—
A negative countValueError split() argument 'count' must be non-negative, got -1—
A group the pattern does not have, in match[key] or span(key)IndexError no such capture group: 3—

An invalid pattern raises the same ParseError on every call that uses it: a failed compilation is not remembered. Go's parser reports no position, so there is none. To check a pattern that comes from a user before using it, call regex.find(pattern, "") inside try and catch e: ParseError.

Left out

A compiled Pattern object (the cache removes the reason for one, and a String is easier to pass around and store); a flags= keyword (flags are written in the pattern); a Bool-returning match (find returns nil on a miss and a Match is truthy); listing a pattern's group names without matching; backreferences and lookaround (RE2 has neither).

url

The url module takes a URL apart, escapes its parts and changes its query. A URL is a value, like fs.Path: it never touches the network. Functions that act on what a URL names, such as the http requests, accept a String or a URL.

Common tasks

import "fs"
import "url"

# Take one apart
var link = url.parse("https://example.com:8443/docs/intro?lang=en&page=2#install")
print(link.host, link.port, link.path)        # example.com 8443 /docs/intro
var params = url.decode_query(link.query)
print(params.get("page", default="1"))        # 2

# Every value of a name that repeats
print(url.query_values("tag=a&tag=b&x=1", "tag")) # ["a", "b"]

# The credentials in a connection URL, decoded
var db = url.parse("postgres://ada:p%40ss@db.example.com:5432/shop")
print(db.user, db.password, db.host)          # ada p@ss db.example.com

# Resolve the links found on a page
var page = url.parse("https://example.com/docs/intro")
print(page.join("../img/logo.png"))           # https://example.com/img/logo.png

# Build one
var search = "https://example.com/search?" + url.encode_query({"q": "goblin lang", "tag": ["a", "b"]})
var file_url = "https://example.com/files/{url.path_escape(name)}"

# The same URL with a query parameter changed: the next page
var listing = url.parse("https://example.com/items?sort=price&page=2")
var query = url.decode_query(listing.query)
query["page"] = Int(query["page"]) + 1
print(listing.with_query(query))              # https://example.com/items?sort=price&page=3

# A link without its tracking parameters
func clean(link) {
    var kept = {}
    for name, value in url.decode_query(link.query).items() {
        if !name.has_prefix("utm_") {
            kept[name] = value
        }
    }
    return link.with_query(kept)
}

# The file name a URL ends in
var download = url.parse("https://example.com/files/report%202026.pdf?dl=1")
print(fs.Path(download.path).name)            # report 2026.pdf

# Is it a link we follow
func is_web(text) {
    try {
        var scheme = url.parse(text).scheme
        return scheme == "http" || scheme == "https"
    } catch e: ParseError {
        return false
    }
}

# Report the bad ones
for line in fs.read_lines("links.txt") {
    try {
        print(url.parse(line).host)
    } catch e: ParseError {
        eprint("not a URL: {e.text}")
    }
}

docs/examples/url-tasks.goblin runs these tasks; examples/url.goblin covers the rest of the module.

Module members

MemberReturnsBehaviour
parse(text)URLThe URL text spells. Relative references ("../a?x=1", "/path") are valid and have an empty scheme and host
encode_query(params)StringA query string without the leading ?, from a Dict in its order: {"q": "a b", "page": 2} gives q=a+b&page=2. Values are String, Int, Float or Bool; a List value repeats the name once per element; a nil value leaves the name out. {} gives ""
decode_query(text)Dict of String to StringThe names and values of a query string, in order; a leading ? is ignored. A name that repeats keeps its last value. "" gives {}
query_values(text, name)List of StringEvery value name has in the query string text, in order; [] when it has none. A leading ? is ignored. It is a module function, not a URL method, because a query string also arrives on its own, as a form body
query_escape(text)Stringtext made safe as one query name or value (a space becomes +)
path_escape(text)Stringtext made safe as one path segment (a space becomes %20, / becomes %2F)

The type name URL is exported for type_of(u) == url.URL; calling it raises TypeError: URL cannot be constructed; use url.parse(text).

URL

Immutable. Two URLs are equal when their text is (a URL never equals a String), a URL can be a Dict key, and it prints as the full URL. Inside a List, a Dict or a structural Show it shows as URL("https://example.com/"), the text quoted like a String element, so it is not mistaken for a String. URLs have no order.

MemberKindValueWhen absent
schemepropertyString, lower case ("https")""
userpropertyString, the user name, decoded ("ada" in postgres://ada:p%40ss@db/shop)""
passwordpropertyString, the password, decoded ("p@ss")""
hostpropertyString, the host name or address without the port and without IPv6 brackets""
portpropertyInt, 0 to 65535 (parse refuses a larger one)nil; it is not filled in from the scheme
pathpropertyString, decoded ("/a b/c")""
querypropertyString, as written, without ? ("q=a+b&page=2"); read it with url.decode_query""
fragmentpropertyString, decoded, without #""
join(reference)methodThe URL that reference (a String or URL) means when found on this page, by the rules of RFC 3986. An absolute reference is returned as it is
with_query(params)methodThe same URL with its query replaced by url.encode_query(params); {} removes the query. Everything else, the fragment included, is kept

Repeated names

Writing and reading are deliberately not mirror images, here and for HTTP headers:

WritingReading
Query (url)encode_query, with_query: a List value repeats the namedecode_query: one String per name; a repeated name keeps its last value. query_values(text, name) for each
Headers (http)headers=: a List value repeats the headerAn http.Headers: headers[name] and get(name) give one String per name, repeats joined with ", "; get_all(name) for each

Reading returns one shape whatever the data: a value is never "a String, or a List when the name repeats". The two differ in what they do with repeats because the formats do: HTTP defines a repeated header as a comma-joined list, a query string defines nothing.

Errors

FailureRaisesData
parse(text) of text that is not a URLParseError parse() invalid URL "ht!tp://x": first path segment in URL cannot contain colontext
parse(text) with a port above 65535ParseError parse() invalid URL "http://h:99999/": port out of rangetext
join(reference) with a String that is not a URLParseError join() invalid URL "…": …text, the reference
decode_query or query_values with a bad % escape anywhere in the queryParseError decode_query() invalid escape "%zz"text, the whole query
A Dict key that is not a String, a value that is not String, Int, Float, Bool, List or nilTypeError—

e.text is the String that could not be parsed, whole, so a handler can report it without keeping the input around.

Left out

Changing parts of a URL other than the query: build the text with interpolation, escaping the decoded path again segment by segment, since u.path is decoded text:

var p = u.path.split("/").map(url.path_escape).join("/")
var moved = "{u.scheme}://{mirror}{p}"
if u.query != "" {
    moved = "{moved}?{u.query}"
}

Also left out: unescaping functions (URL.path, URL.fragment, user, password and decode_query already return decoded text). A URL has one text form, String(u), so there is no format.

csv

The csv module turns CSV text into rows and back: reading a spreadsheet export, writing a report a spreadsheet can open. A row is a List of Strings, or a Dict from column name to field; a table is a List of rows. decode and encode work on whole documents; read_rows reads a stream one row at a time.

Common tasks

import "csv"
import "fs"

# Read a spreadsheet export by column name
for person in csv.decode_dicts(fs.read("people.csv")) {
    print(person["name"], Int(person["age"]) + 1)
}

# Read plain rows, tab separated
var rows = csv.decode(fs.read("data.tsv"), sep="\t")
var header = rows[0]
var body = rows[1:]

# An export whose rows are not all the same length: read it raw, pad it yourself
for row in csv.decode(fs.read("legacy.csv"))[1:] {
    var note = ""
    if row.size > 3 {
        note = row[3]
    }
    print(row[0], note)
}

# Write rows; numbers are written as print shows them, so format the ones that need it
var table = [["name", "score"], ["Ada", 97], ["Linus", format(88.5, ".2f")]]
fs.write("scores.csv", csv.encode(table))

# Write records, choosing the column order
var people = [{"name": "Ada", "age": 36}, {"name": "Linus", "age": 28}]
fs.write("people.csv", csv.encode(people, columns=["age", "name"]))

# A file that may be broken: say where
try {
    rows = csv.decode(fs.read("upload.csv"))
} catch e: ParseError {
    eprint("upload.csv, line {e.line}: {e.message}")
}

# A file of any size, one row at a time: take the header, then loop over the rest
var big = fs.open("big.csv")
defer big.close()
var reader = csv.read_rows(big)
var columns = nil
for row in reader {
    columns = row
    break
}
for row in reader {
    var record = {}
    for i in range(columns.size) {
        record[columns[i]] = row[i]
    }
    print(record)
}

examples/csv.goblin runs each of these tasks.

A program writing for a spreadsheet that wants something else has the pieces: sep=";", a byte-order mark with (0xFEFF).to_char() + text, Windows line ends with .replace("\n", "\r\n"). One more row goes on the end of a file with fs.write(path, csv.encode([row]), append=true).

Module members

MemberReturnsBehaviour
decode(data, sep=",")List of List of StringEvery record as a row, as long as the record is. data is a String, Bytes, or a readable read to its end. Quoted fields, line breaks inside them and "" escapes follow RFC 4180. A leading byte-order mark is dropped and blank lines are skipped. Empty input is []
decode_dicts(data, sep=",")List of DictThe first record is the header; every later record becomes a Dict from column name to field, in header order. Every record must have exactly as many fields as the header. Empty input, or a header alone, is []
read_rows(readable, sep=",")csv.RowsA lazy iterable over the rows decode would return for what readable (anything with a read(size) method, such as a File from fs.open or gzip.open) holds. Each step reads only as far as the next row, so the data never has to fit in memory. Reading starts where the readable is when the first loop begins, dropping a byte-order mark there. The Rows reads ahead in chunks and keeps what it read ahead, so a second loop over the same Rows continues with the row after the last one given (take the header with break, then loop over the rest); the readable's own position may be past that row, which matters only to code that reads the readable directly. After an error every later loop raises the same error. read_rows never closes the readable: whoever opened it does, with defer. It takes no path and no String or Bytes; for those use decode
encode(rows, sep=",", columns=nil)StringCSV text, one \n-terminated line per row, quoting only where needed. A row whose only field is empty is written as "", because decode skips a blank line; an empty row [] is written as a blank line, so it is not read back. rows is any iterable of Lists or of Dicts. For Dicts a header line comes first: columns (a List of Strings) when given, otherwise the keys of the first Dict; a Dict without one of the columns writes an empty field there. With List rows, columns is written as the header line. No rows and no columns is ""

sep is one character, other than a quote or a line break.

Fields are Strings when decoding; converting a column is the program's job (Int(row["age"])). When encoding, a String is written as it is, nil as an empty field, and any other value as String() shows it (42, 1.5, true); an instance needs impl Show for that. A List or a Dict cannot be a field.

decode checks nothing about row lengths, so an export whose rows differ can be read and the short rows seen (row.size). decode_dicts does check: by name, a row with a separator missing would put values under the wrong columns without a word.

Errors

FailureRaisesData on the error
A quote where none may beParseError decode() invalid CSV at line 3, column 9: stray quoteline, column: Ints counted from 1, where the reader stopped; column counts characters
A quoted field that never endsParseError decode() invalid CSV at line 2, column 3: quoted field never endsline, column
Bytes that are not valid UTF-8, such as a Windows-1252 exportParseError decode() invalid CSV at line 2, column 4: invalid UTF-8line, column of the first invalid byte. decode and decode_dicts check the whole input before reading it; read_rows checks each row as it reads it, so the rows before the bad one have been yielded
decode_dicts: a record with a different number of fields than the headerParseError decode_dicts() invalid CSV at line 3, column 1: expected 4 fields, got 3line: the line the record starts on; column: 1
decode_dicts: the header names a column twiceParseError decode_dicts() invalid CSV at line 1, column 8: duplicate column "id"line, column of the second occurrence
sep is not one usable characterValueError decode() argument 'sep' must be one character other than a quote or a line break, got ";;"—
Reading a readable data (or the readable of read_rows) failsthe error the readable raised, such as IOError—
read_rows: readable has no read(size) methodTypeError read_rows() argument 'readable' must have a read(size) method, got String—
encode: a row that is not a List or DictTypeError encode() row 2 must be List or Dict, got Int—
encode: a List or Dict as a field, or an instance without impl ShowTypeError encode() row 1 cannot hold a List as a field—
encode: a Dict key that is not a columnValueError encode() row 2 has unknown column "x"—
encode: a Dict row after List rows, with no columnsValueError encode() row 2 is a Dict but the rows before it are Lists; give the columns with columns=—

The errors of read_rows name read_rows() and are otherwise those of decode. Rows in encode messages are counted from 1. line counts lines in the text, so a quoted field with line breaks in it moves it on; the names mean what they mean for json.

Left out

Reading rows by column name lazily (pair the header row with the rows of read_rows, as above), comments, lenient quoting and trimming of spaces (clean the text first), and encodings other than UTF-8.

hash

The hash module computes digests of data: a checksum of a download, the signature of an API request, a content-addressed cache key. Every function returns the digest as Bytes; digest.to_hex() is its usual text form.

import "hash" binds the name hash, which hides the built-in hash(x) in that file. The two are unrelated: the built-in is the Dict hash of a value and changes between runs, while a digest is the same everywhere and forever.

Common tasks

import "hash"
import "fs"

# Checksum of a string
print(hash.sha256("hello").to_hex())

# Verify a download without loading it into memory
var file = fs.open("goblin.tar.gz")
defer file.close()
var actual = hash.sha256(file).to_hex()
if actual != expected {
    raise Error("checksum mismatch: {actual}")
}

# Sign a request
var signature = hash.hmac(secret, body).to_hex()
var headers = {"X-Signature": signature}

# An older scheme that still uses SHA-1
var legacy = hash.hmac(secret, body, algorithm=hash.sha1)

Pass the headers with the request as the http chapter shows. examples/hash.goblin runs each of these tasks.

Module members

data is a String (its UTF-8 bytes), Bytes, or a readable (anything with a read(size) method, such as an open File), which is read to its end in chunks and not closed, so a file of any size can be hashed. Empty data is valid and has a digest.

MemberReturnsBehaviour
sha256(data)Bytes (32)SHA-256 digest. The default choice
sha512(data)Bytes (64)SHA-512 digest
sha1(data)Bytes (20)SHA-1 digest. For compatibility with existing checksums only
md5(data)Bytes (16)MD5 digest. For compatibility with existing checksums only
hmac(key, data, algorithm=hash.sha256)BytesKeyed digest (HMAC). key is a String or Bytes. algorithm is one of the four functions above, passed as a value

Errors

FailureRaises
data is not String, Bytes or a readableTypeError sha256() argument 'data' must be String, Bytes or have a read(size) method, got Int
key is not String or BytesTypeError hmac() argument 'key' must be String or Bytes, got Int
algorithm is anything else, a name string includedValueError hmac() argument 'algorithm' must be hash.md5, hash.sha1, hash.sha256 or hash.sha512
Reading the readable failsthe error the readable raised, such as IOError

Left out

Incremental hashers (a readable covers the large-input case), SHA-224, SHA-384 and the truncated SHA-512 variants, CRC32, CRC64, Adler-32 and FNV checksums, constant-time comparison (Goblin has no server side to receive signatures: compare with ==), and password hashing.

base64

The base64 module turns bytes into Base64 text and back: Basic authentication headers, data URLs, binary data inside JSON, the parts of a JWT.

Common tasks

import "base64"
import "fs"
import "json"

# Basic authentication
var credentials = base64.encode("{user}:{password}")
var headers = {"Authorization": "Basic {credentials}"}

# Binary data inside JSON
var payload = json.encode({"name": "logo.png", "data": base64.encode(fs.read_bytes("logo.png"))})

# And back
var image = base64.decode(json.decode(payload)["data"])
fs.write("logo-copy.png", image)

# The middle part of a JWT: URL alphabet, no padding
var claims = json.decode(base64.decode(token.split(".")[1], url_safe=true).decode())

examples/base64.goblin runs each of these tasks.

Module members

MemberReturnsBehaviour
encode(data, url_safe=false, padding=true)StringBase64 text of data (a String's UTF-8 bytes, Bytes, or a readable read to its end). url_safe=true uses - and _ instead of + and /. padding=false leaves off the trailing =
decode(data, url_safe=false)BytesThe bytes data encodes: Base64 text as a String, Bytes, or a readable read to its end. Trailing = padding may be present or absent, but when present it must be complete. Line breaks inside data are ignored. "" decodes to empty Bytes

decode returns Bytes because Base64 carries binary data; call .decode() on the result when it is known to be text.

Errors

FailureRaises
data is not valid Base64 in the chosen alphabetParseError decode() invalid Base64 at position 5, the position being the character index in data; the error carries it as e.position, an Int
data has the wrong typeTypeError
Reading a readable data failsthe error the readable raised, such as IOError

Left out

Base32, Ascii85 and quoted-printable encodings.

gzip

The gzip module reads and writes gzip data: the .gz files that exports and log rotation produce, and compressed request bodies. compress and decompress work on a whole value in memory; open and read_lines work on a .gz file of any size, a piece at a time.

Common tasks

import "exec"
import "fs"
import "gzip"
import "http"
import "json"

# A compressed export of any size, one line at a time
var errors = 0
for line in gzip.read_lines("events.jsonl.gz") {
    if json.decode(line)["level"] == "error" {
        errors = errors + 1
    }
}

# A small one, whole
var config = json.decode(gzip.decompress(fs.read_bytes("config.json.gz")))

# Write a compressed file piece by piece
var out = gzip.open("report.csv.gz", write=true)
defer out.close()
for row in rows {
    out.write("{row}\n")
}

# Compress a big log without holding it
var packed = gzip.open("app.log.gz", write=true, level=9)
defer packed.close()
for line in fs.read_lines("app.log") {
    packed.write("{line}\n")
}

# Compress a small file in one line
fs.write("notes.txt.gz", gzip.compress(fs.read_bytes("notes.txt")))

# Unpack to disk without holding it
var source = gzip.open("dump.sql.gz")
defer source.close()
fs.write("dump.sql", source)

# Compress a command's output as it is produced
var dump = gzip.open("shop.sql.gz", write=true)
defer dump.close()
exec.run(["pg_dump", "shop"], stdout=dump)

# Download a big compressed export, then go through it
fs.write("export.jsonl.gz", http.get(export_url).body)
for line in gzip.read_lines("export.jsonl.gz") {
    print(json.decode(line)["id"])
}

# Compress before uploading
var body = gzip.compress(json.encode(records))
http.request("POST", upload_url, headers={"Content-Encoding": "gzip", "Content-Type": "application/json"}, body=body)

examples/gzip.goblin runs the tasks that need no network or database.

Module members

MemberReturnsBehaviour
compress(data, level=nil)Bytesdata (a String's UTF-8 bytes, Bytes, or a readable read to its end) in gzip format. level is 1 (fastest) to 9 (smallest); nil is the usual balance
decompress(data)BytesThe original bytes. data is Bytes or a readable such as an open File; a String is a TypeError, since gzip data is binary. Several gzip members one after another are decompressed as one
read_lines(path)fs.LinesThe twin of fs.read_lines: each for over it opens the file, yields the decompressed text one line per step (terminator removed) and closes the file when the loop ends by any route. It never holds more than one line
open(path, write=false, level=nil)fs.FileThe twin of fs.open. Read-only by default: the file must exist and be gzip, and the File reads its decompressed content. write=true: the file is created or truncated, and everything written is compressed into it at level

decompress returns Bytes; .decode() it when the content is text.

Streams

gzip.open returns an ordinary File: no new type, nothing new to learn. type_of(f) == fs.File, it shows as <File events.json.gz> and f.path is the path given. Code written for a plain file works on a .gz by changing fs. to gzip..

File memberOpened for readingOpened with write=true
read(size=nil)Decompressed Bytes; empty at the endValueError, as any File open for writing
read_line(), for line in fDecompressed lines as StringsValueError
write(data)ValueError, as any File open for readingCompresses the String or Bytes into the file; returns the number of bytes given, not the compressed size
close()Releases the fileFinishes the gzip data, then releases the file
closed, pathas on any Fileas on any File

Until a writing File is closed the file on disk is incomplete, so a writer always gets defer f.close(). As with any File, for line in f does not close f: whoever opened it closes it.

A reading File is a readable, so it can be passed as the data of csv.decode_dicts(f), json.decode(f), hash.sha256(f) or fs.write(path, f). A writing File is a writable, so it can be the stdout= of exec.run.

A response sent with Content-Encoding: gzip is already decompressed by http's get, request and send; a downloaded .gz file goes to disk first with fs.write(path, http.get(url).body), then through gzip.read_lines(path).

Errors

FailureRaises
level outside 1 to 9ValueError compress() argument 'level' must be between 1 and 9, got 0
level given to open without write=trueValueError
data does not start like gzip (empty data included)ParseError decompress() not gzip data
The data is truncated or damagedParseError decompress() corrupt gzip data
data has the wrong typeTypeError
Reading a readable data failsthe error the readable raised, such as IOError
open or a read_lines loop on a missing or unreadable fileNotExistError, PermissionError, IOError, as fs
The file is not gzipParseError open() "x.gz" is not gzip data, read_lines() "x.gz" is not gzip data (when the loop starts)
The file is damaged further inParseError from the call that reaches the damage: read() corrupt gzip data in "x.gz", read_lines() corrupt gzip data in "x.gz"
A line is not valid UTF-8ValueError line 3 of "x.gz" is not valid UTF-8

Every error of open and read_lines, and of the File they give, that is about the file carries e.path, a Path; the invalid-UTF-8 ValueError also carries e.line, as in fs.

Left out

Wrapping a readable or writable that is not a file (open takes a path, like every open: decompress a response body or a pipe in memory with gzip.decompress(readable), or through a file); appending to an existing .gz; gzip header fields such as the stored file name; and every other format: zlib, raw DEFLATE, bzip2 and LZW. Archives are other modules: tar reads a .tar.gz by itself and writes one with tar.create(path, gzip=true), and zip handles .zip.

zip

The zip module reads and writes zip archives. zip.extract(path, dst) unpacks a whole archive in one call, and nothing it writes lands outside dst. To look inside first, zip.open(path) gives a Reader: iterate it for the members, open(member) reads one without unpacking the rest, and extract(member, dst) unpacks one. zip.create(path) gives a Writer that packs files, directories and content the program made.

For .tar and .tar.gz use tar. The two modules share their vocabulary: the same function and method names, the same Member type and the same UnsafeError kind. They differ where the formats differ: a zip has an index at its end, so its members can be read in any order and the file must be on disk; a tar is a sequence that can come from a pipe.

Common tasks

import "fs"
import "hash"
import "http"
import "json"
import "zip"

# Unpack a downloaded release into a directory
fs.write("goblin-1.4.2.zip", http.get(url).body)
zip.extract("goblin-1.4.2.zip", "tools/goblin")

# Check the download first, then unpack over an earlier version
var download = fs.open("goblin-1.4.2.zip")
defer download.close()
if hash.sha256(download).to_hex() != expected {
    raise ValueError("goblin-1.4.2.zip does not match its checksum")
}
zip.extract("goblin-1.4.2.zip", "tools/goblin", overwrite=true)

# An archive you do not trust: bound what it may write, and say why it was refused
try {
    zip.extract("upload.zip", "incoming", max_size=200 * 1024 * 1024)
} catch e: zip.UnsafeError {
    eprint("upload.zip refused: {e.message}")
    if e.member != nil {
        eprint("offending member: {e.member.name}")
    }
}

# List what a zip contains
var bundle = zip.open("bundle.zip")
defer bundle.close()
for member in bundle {
    var when = member.modified_at.format("%Y-%m-%d %H:%M")
    print("{member.size:>10}  {when}  {member.name}")
}
print(sum(List(bundle).map(func(m) { return m.size })), "bytes when unpacked")

# Read one member without unpacking the rest
var manifest = json.decode(bundle.open("manifest.json"))
var readme = bundle.open("README.md").read().decode()
var notes = bundle.find("NOTES.txt")
if notes != nil {
    for line in bundle.open(notes) {
        print(line)
    }
}

# Unpack only some members
for member in bundle {
    if member.name.has_prefix("docs/") {
        bundle.extract(member, "site")
    }
}

# Pack a directory
var out = zip.create("site.zip")
defer out.close()
out.add("site")                       # stored as site/index.html, site/css/main.css, ...

# The contents of a directory at the top of the archive
var deploy = zip.create("function.zip")
defer deploy.close()
for entry in fs.read_dir("build") {
    deploy.add(entry)                 # stored as handler.js, lib/util.js, ...
}

# Chosen files, under names of your choosing
func unwanted(entry) {
    return entry.name.has_prefix(".") || entry.name == "node_modules"
}
var sources = zip.create("sources.zip")
defer sources.close()
for file in fs.walk("project", skip=unwanted) {
    var inside = file.relative_to("project")
    sources.add(file, name="project-1.4.2/{inside}")
}

# Add content the program made
var results = zip.create("results.zip")
defer results.close()
results.add_data("results.json", json.encode(records))
results.add_data("run.sh", "#!/bin/sh\nexec ./tool --all\n", mode=0o755)
results.add("report.pdf")

examples/zip.goblin runs these tasks on a tree it builds in a temporary directory.

Module members

MemberReturnsBehaviour
open(path)ReaderOpens an existing zip for reading. Reads its index, but no member content
create(path)WriterCreates the file (mode 0o644), or replaces its content, and returns a Writer for it. The file is not a valid archive until the Writer's close()
extract(path, dst, overwrite=false, max_size=nil)nilUnpacks every member under the directory dst, which is created with its parents when missing. Opens and closes the archive itself. Every member's name, kind and declared size is checked before anything is written (What extract does). max_size is the most bytes the whole extraction may write; nil is no limit
UnsafeErrorerror kindRaised by extract, the function and the method, for a member it refuses. Its parent is Error. It is the same kind as tar.UnsafeError
Reader, Writer, Membertype namesFor type_of. Calling Reader raises TypeError: Reader cannot be constructed; use zip.open(path), and Writer names zip.create(path)

path and dst are a String or an fs.Path.

Reader

An open zip, from zip.open. It holds the file open until close(). It shows as <zip.Reader bundle.zip>. A Reader is not meant to be shared between goblins.

MemberKindValue
pathpropertyThe Path it was opened with
closedpropertyBool
for member in readeriterationEvery Member, in the order the archive lists them. Each loop starts from the first, so List(reader) is the whole listing. Reads nothing from disk
find(name)methodThe Member stored under exactly name (a String), or nil. When a name is stored twice, the last one, which is the one unpacking tools keep
open(member)methodAn fs.File open for reading the member's content, decompressed as it is read. member is a Member of this Reader or a name
extract(member, dst, name=nil, overwrite=false)methodWrites that one member under the directory dst and returns the Path written. It lands at its own name, or at name (a String or Path, relative to dst) when given. The checks are those of the module function, applied to the name it lands at. Creates dst and missing parent directories
close()methodReleases the file and returns nil. Calling it again does nothing. Member Files from this Reader stop working

There is no read method on the archive: a method of that name would make the Reader look like a readable to fs.write and json.decode. reader.open(member).read() is a member's whole content.

Member Files

The File from open(member):

  • reads the member's content; its path is nil and it shows as <File bundle.zip:manifest.json>;
  • is a readable, so json.decode, csv.decode_dicts, hash.sha256 and fs.write(path, file) take it; read() gives Bytes and for line in file gives lines;
  • holds no resource of its own: close() on it is allowed and never needed, and the Reader's close() is what releases the file on disk;
  • stops working when its Reader is closed: ValueError: read() member "a.log" is no longer open, and from then on its closed is true;
  • raises ParseError read() corrupt data in member "x" of "bundle.zip" from the call that reaches damage, including a failed checksum at the end of the member.

Writer

A zip being written, from zip.create. It shows as <zip.Writer site.zip>. A Writer is not meant to be shared between goblins.

MemberKindValue
pathpropertyThe Path it was created with
closedpropertyBool
add(path, name=nil)methodStores what path names on disk and returns nil. A file: its content (compressed and streamed, never held whole), permission bits and modification time. A directory: an entry for it and everything below it, names sorted within each directory. A symbolic link: stored as a link, never followed. It is stored under name (a String or Path), which defaults to the last component of path; entries below a directory get name in front of their relative path. The archive's own file is passed over when it lies inside an added directory
add_data(name, data, mode=0o644)methodStores data (a String, Bytes, or a readable, which is streamed) as a file member called name, with permission bits mode and the current time; returns nil
close()methodFinishes the archive by writing its index, then releases the file; returns nil. Calling it again does nothing

Until close() the file is not a zip, so a Writer always gets defer archive.close().

The name of the last component is the default because the alternative, the path as given, would put build/ in front of every name for add("build/site") and would store an absolute path as home/me/…. The default stores site/…, as cp -r build/site dst/ would.

Names given to a Writer. A name is written the way a relative path is written on this platform and is stored with /. It must be usable when unpacked: not empty, not absolute, with no .. component and no NUL or \. Anything else raises ValueError: add() name "../x" would be unpacked outside its directory; an empty String raises ValueError: add() argument 'name' must not be empty, as an empty path does everywhere. A Writer therefore cannot produce an archive that extract refuses for its names.

Every file is compressed with DEFLATE at the usual level. Names that are not ASCII are stored as UTF-8 and flagged as such.

Member

One type shared with tar: zip.Member == tar.Member. A Member is an immutable description of one entry, with no I/O; its content comes from the archive through open(member). It shows as <Member docs/guide.md>. It cannot be constructed (TypeError: Member cannot be constructed; iterate an archive from zip.open(path) or tar.open(path)), and two Members are equal only when they are the same value.

PropertyValue
nameString: the name as stored, components separated by /, without the trailing / of a directory entry. It is not cleaned: ../x and /etc/passwd are reported as they are. Bytes that are not valid UTF-8 are shown as U+FFFD
sizeInt: bytes of content when unpacked; 0 for a directory or a link
modified_attime.Time, in the local zone (as fs.stat gives it)
modeInt: permission bits as stored (member.mode == 0o755). A zip written on a system without them reports 0o644 for a file and 0o755 for a directory
is_fileBool: a regular file
is_dirBool
is_symlinkBool: a symbolic link
link_targetString: what a link points to, as stored; nil unless the member is a link

The names and meanings are those of fs.FileInfo, plus name and link_target. A member that is none of file, directory or link (a device, a FIFO) has all three is_ properties false.

A zip stores wall-clock time without a zone unless the program that made it added the UTC timestamp field. Without that field the stored time is read as UTC.

What extract does, and what it refuses

The same rules hold for zip.extract, tar.extract and the extract method of both Readers. "The name" is the member's name, or the name= argument when the method was given one.

What is created

MemberResult under dst
FileA file with the member's content, its permission bits and its modification time. Missing parent directories are created (0o755), since many archives have no entries for them
DirectoryThe directory. An existing one is used as it is
Symbolic linkThe link, when its target is relative and, followed from where the link lands, stays inside dst. Otherwise it is refused
Hard link (tar)A hard link to the file already unpacked under the target name. The target is checked as a member name is
Anything else (device, FIFO, socket)Refused

Permission bits are the stored ones, limited to 0o777 and then by the process's umask, as for any file a program creates. Set-user-id, set-group-id and sticky bits are never applied. A directory always gets read, write and search permission for its owner, so that unpacking can continue inside it. Ownership is never applied: everything belongs to the user running the script. Directory modification times are not restored.

What is refused

HazardDefaultReported asTo do it anyway
A name that is absolute (/etc/passwd, C:\x), has a .. component, contains \ or NUL, is empty, or is a reserved device name on WindowsRefusedUnsafeError: extract() member "../../etc/passwd" of "upload.zip" would be written outside "incoming"The method, with a name= the script computed
A symbolic link whose target is absolute or leads outside dstRefusedUnsafeError: extract() link "current" of "x.tar" points outside "app": "/etc"Not possible with this module; skip the member in a loop
A name that passes through a symbolic link leading outside dst, whether the link was in dst before or came from this archiveRefused by the operating system interface used, whatever the name looked likeUnsafeError: extract() member "lib/x" of "x.tar" would be written outside "app"—
A device, FIFO or socketRefusedUnsafeError: extract() member "dev/null" of "rootfs.tar" is a deviceSkip the member in a loop
More content than the member declares (a header that understates its size)Stops at the declared size; nothing is left at the nameUnsafeError: extract() member "a.bin" of "x.zip" is larger than the 1024 bytes it declares—
The members' declared sizes add up to more than max_size (module function only)No limit unless max_size is givenUnsafeError: extract() "upload.zip" unpacks to 6442450944 bytes, over max_size 209715200A larger max_size, or nil
A file already at the nameRefusedExistError: extract() "app/bin/tool" already exists (pass overwrite=true), with data pathoverwrite=true replaces files and links. The existing entry is removed and a new one created, so nothing is ever written through an existing link
A directory where a file must go, or a file where a directory must goRefused, with or without overwriteExistError: extract() "app/bin" is a directory (or is not a directory), with data pathfs.remove it first
The same name twice in one archiveThe second is "a file already at the name"ExistError as aboveoverwrite=true, which keeps the last, as tar and unzip do

When the method was given a name= that is refused, the message adds where the member would have landed: extract() member "a.txt" of "x.zip" would be written outside "dst" as "../a.txt".

These rules follow from the table:

  • Nothing is skipped and no name is changed. An archive either unpacks as it says or raises. tar(1) strips a leading / and carries on, which unpacks something other than what the archive says without telling the caller.
  • zip.extract checks every member's name, kind and declared size before it writes anything, because a zip's index is available up front. A zip refused for those reasons leaves dst untouched. Link targets are stored as content and are checked when they are reached.
  • tar.extract stops at the member it refuses. The members before it stay unpacked: a tar cannot be checked ahead without reading all of it. A script that must not leave a partial tree unpacks into fs.mkdir_temp() and moves the result.
  • The default does not protect against an archive that is honestly huge, or one made to be (a "zip bomb" declares its true, enormous sizes). Content is streamed, so memory is never at risk; disk space is. For input from a source the script does not trust, pass max_size. With zip the refusal comes before anything is written; with tar it comes at the member whose declared size crosses the limit, before that member is written.
  • The method takes no max_size. In a loop the script has member.size, and no member can write more than that.
  • Reading (for member in, open(member)) never refuses a name. A listing shows ../../etc/passwd as it is stored. Only extract writes to disk under a member's name.

There is no default size limit because any number would be a policy that refuses some ordinary large archives, and changing it later would break scripts either way. What the default does guarantee is where files land and that no member exceeds its declared size.

Errors

FromKinds (besides TypeError and ValueError for arguments)Data
open, create, extract: the archive fileNotExistError, PermissionError, IOError (a directory: open() cannot read "d": is a directory, as gzip and tar report it)path: the archive
open, a member File, extract: not a zip, damaged, encrypted, unsupported compressionParseError: open() "x.zip" is not a zip archive, open() member "x" of "bundle.zip" is encrypted, open() member "x" of "bundle.zip" uses a compression method zip does not read, read() corrupt data in member "x" of "bundle.zip"path: the archive
Reader.open(name), Reader.extract(name, …): no such memberKeyError open() no member "x" in "bundle.zip"—
extract: a refused memberUnsafeErrormember: the Member refused, nil when the refusal is about the whole archive (max_size). path: the archive
extract: something in the way under dst, or dst cannot be writtenExistError, PermissionError, IOErrorpath: the path under dst
add: the file being addedNotExistError, PermissionError, IOErrorpath: that file
A closed Reader or Writer; a Member of another archive; open of a directory or link; a bad name given to a Writer; a name already in the archive; add(".") without name=; a socket or device given to add; mode outside 0–0o777ValueError—

UnsafeError is not an IOError, because the disk and the archive both worked: a handler that receives archives from elsewhere catches exactly it, and can tell it from a full disk (IOError) and from a damaged archive (ParseError).

Left out

Left outInstead
Encrypted zips, reading or writingexec.run(["unzip", "-P", password, file]). Go's library has no zip encryption; the legacy scheme is broken and AES is an extension. open(path, password=) can be added later
Changing an existing archive: appending, deleting or replacing a memberWrite a new archive
Copying a member into another archive without unpacking itextract and add, or for small members add_data(member.name, source.open(member).read())
A one-call "pack this directory"Three lines: create, defer close(), add. They show what the names inside will be
A one-call listingopen, defer close(), a loop
A Reader over Bytes or a stream; a Writer over a writablefs.write(file, data) first: reading needs a seekable file because the index is at the end. The names zip.Reader(source) and zip.Writer(target) stay free for this
A compression level, or storing without compressionNone; level= on create can be added later
Setting a member's modification time; an empty directory or a link from add_dataadd takes times and kinds from disk
exclude= or skip= on add and extractA loop over fs.walk(path, skip=…) with add; a loop with extract(member, dst)
strip= on extractA loop with name=, as the tar chapter shows for a source tarball
Progress reportingA loop with the method; member.size gives the total up front
Names in a legacy encoding (CP437, Shift-JIS)They are shown with U+FFFD; unpack such a member with name=
Restoring ownership, set-id bits and directory times; links that point outsideNot offered: these are the unsafe parts

tar

The tar module reads and writes tar archives, plain or gzip-compressed: .tar and .tar.gz files, and tar data arriving from a download or another program. tar.extract(path, dst) unpacks a whole archive in one call, and nothing it writes lands outside dst. A tar is a sequence of members, so a Reader visits them in order, once, and reads only the member it is at: an archive larger than memory is fine. tar.create(path) gives a Writer that packs files, directories and content the program made.

For .zip use zip. The two modules share their vocabulary: the same function and method names, the same Member type and the same UnsafeError kind. They differ where the formats differ: a zip has an index at its end, so its members can be read in any order and the file must be on disk; a tar can come from a pipe, but only in order.

Common tasks

import "exec"
import "fs"
import "gzip"
import "hash"
import "http"
import "tar"

# Unpack a downloaded release into a directory
fs.write("goblin-1.4.2.tar.gz", http.get(url).body)
tar.extract("goblin-1.4.2.tar.gz", "tools/goblin")

# Check the download first, then unpack over an earlier version
var download = fs.open("goblin-1.4.2.tar.gz")
defer download.close()
if hash.sha256(download).to_hex() != expected {
    raise ValueError("goblin-1.4.2.tar.gz does not match its checksum")
}
tar.extract("goblin-1.4.2.tar.gz", "tools/goblin", overwrite=true)

# An archive you do not trust: bound what it may write, and say why it was refused
try {
    tar.extract("upload.tar.gz", "incoming", max_size=200 * 1024 * 1024)
} catch e: tar.UnsafeError {
    eprint("upload.tar.gz refused: {e.message}")
    eprint("offending member: {e.member.name}")
}

# All or nothing: unpack beside the target, then move into place
var staging = fs.mkdir_temp(prefix="unpack-")
defer fs.remove(staging, recursive=true)
tar.extract("release.tar.gz", staging.join("app"))
fs.move(staging.join("app"), "app")

# Go through a tar of any size, one member at a time
var logs = tar.open("logs-2026-11.tar.gz")
defer logs.close()
var errors = 0
for member in logs {
    if member.is_file && member.name.has_suffix(".log") {
        for line in logs.open(member) {
            if line.contains("ERROR") {
                errors = errors + 1
            }
        }
    }
}

# Read one member: stop when it has been found
var source = tar.open("project.tar.gz")
defer source.close()
var version = nil
for member in source {
    if member.name == "project/VERSION" {
        version = source.open(member).read().decode().trim()
        break
    }
}

# Unpack a source tarball without its top-level directory
var release = tar.open("project-1.4.2.tar.gz")
defer release.close()
for member in release {
    var top, rest = member.name.cut("/")
    if rest != nil && rest != "" {
        release.extract(member, "project", name=rest)
    }
}

# Unpack a download as it arrives, without saving the archive
var response = http.get(url, timeout=nil)
defer response.body.close()
var stream = tar.Reader(response.body)
for member in stream {
    stream.extract(member, "data")
}

# Pack a directory into a .tar.gz
var backup = tar.create("site.tar.gz", gzip=true)
defer backup.close()
backup.add("site")                    # stored as site/index.html, site/css/main.css, ...

# Chosen files, under names of your choosing
func unwanted(entry) {
    return entry.name.has_prefix(".") || entry.name == "node_modules"
}
var sources = tar.create("sources.tar.gz", gzip=true)
defer sources.close()
for file in fs.walk("project", skip=unwanted) {
    var inside = file.relative_to("project")
    sources.add(file, name="project-1.4.2/{inside}")
}

# The smallest .tar.gz: tar inside the File that gzip.open gives
var packed = gzip.open("corpus.tar.gz", write=true, level=9)
defer packed.close()
var corpus = tar.Writer(packed)
defer corpus.close()                  # runs first: ends the tar data, then packed.close() ends the gzip data
corpus.add("corpus")

# A compression tar does not read: let the program do it
var xz = exec.start(["xz", "-dc", "rootfs.tar.xz"], stdout=exec.PIPE)
var rootfs = tar.Reader(xz.stdout)
for member in rootfs {
    print(member.name)
}
xz.wait()

examples/tar.goblin runs these tasks on a tree it builds in a temporary directory.

Module members

MemberReturnsBehaviour
open(path)ReaderOpens an existing tar for reading, gzip-compressed or not. Gzip is recognised by the first bytes of the file, not by its name. Members are read only when the Reader is iterated
create(path, gzip=false)WriterCreates the file (mode 0o644), or replaces its content. gzip=true compresses the archive as it is written. The file's name decides nothing
extract(path, dst, overwrite=false, max_size=nil)nilUnpacks every member, gzip-compressed or not, under the directory dst, which is created with its parents when missing. Opens and closes the archive itself. It stops at the first member it refuses (What extract does). max_size is the most bytes the whole extraction may write; nil is no limit
Reader(source)ReaderA Reader over a readable the caller owns: a File, a response body, a process's stdout. Gzip is recognised the same way. close() on this Reader does not close source
Writer(target)WriterA Writer over a writable the caller owns: a File from fs.open(path, write=true) or gzip.open(path, write=true), a process's stdin. It writes plain tar. close() finishes the tar data and does not close target
UnsafeErrorerror kindRaised by extract, the function and the method, for a member it refuses. Its parent is Error. It is the same kind as zip.UnsafeError
Membertype nameMember

path and dst are a String or an fs.Path.

Reading recognises gzip by content because a script does not choose what it is given, and nearly every tar a script meets is compressed; it needs no rule about file names. Writing is the script's choice, so it says so with gzip=true, or with tar.Writer over gzip.open(path, write=true, level=9) when it wants a compression level. Another compression goes through an exec pipe, as the last task above shows.

Reader

A tar being read, from tar.open or tar.Reader. It is a stream of members in the way a File is a stream of lines. It shows as <tar.Reader logs.tar.gz>, or <tar.Reader> over a stream. A Reader is not meant to be shared between goblins.

MemberKindValue
pathpropertyThe Path it was opened with; nil over a stream
closedpropertyBool
for member in readeriterationThe remaining Members, one per step. Each step moves to the next member and passes over whatever content of the previous one was not read. The loop does not close the Reader, and a loop left with break leaves it at that member: a later loop continues after it. It never holds more than one member's header
open(member)methodAn fs.File open for reading the content of the current member: the one the loop most recently gave. Each call gives a File over the same content, continuing where the last one stopped
extract(member, dst, name=nil, overwrite=false)methodWrites the current member under the directory dst and returns the Path written. It lands at its own name, or at name (a String or Path, relative to dst) when given. The checks are those of the module function, applied to the name it lands at. Creates dst and missing parent directories
close()methodReleases the file when the Reader came from tar.open and returns nil. Calling it again does nothing

There is no find, and open takes no name: finding a member means reading past the ones before it, and that belongs in a loop the reader of the script can see.

A File from open(member) reads ahead when it is read line by line, so a second File over the same member continues after what the first one buffered. extract of a member whose content was already read, in part or in full, through open or by an earlier extract, raises ValueError: extract() member "a.log" was already read; a tar archive is read in order, because what is left is not the member.

Member Files

The File from open(member):

  • reads the member's content; its path is nil and it shows as <File logs.tar.gz:a.log> (<File a.log> over a stream);
  • is a readable, so json.decode, csv.decode_dicts, hash.sha256 and fs.write(path, file) take it; read() gives Bytes and for line in file gives lines;
  • holds no resource of its own: close() on it is allowed and never needed;
  • stops working when the loop moves to the next member, and when its Reader is closed: ValueError: read() member "a.log" is no longer open, and from then on its closed is true;
  • raises ParseError read() corrupt data in member "a.log" of "logs.tar.gz" from the call that reaches damage.

Writer

A tar being written, from tar.create or tar.Writer. It shows as <tar.Writer site.tar.gz>, or <tar.Writer> over a stream. A Writer is not meant to be shared between goblins.

MemberKindValue
pathpropertyThe Path it was created with; nil over a stream
closedpropertyBool
add(path, name=nil)methodStores what path names on disk and returns nil. A file: its content, permission bits and modification time. A directory: an entry for it and everything below it, names sorted within each directory. A symbolic link: stored as a link, never followed. It is stored under name (a String or Path), which defaults to the last component of path; entries below a directory get name in front of their relative path. The archive's own file is passed over when it lies inside an added directory. The owner's and group's ids and names are not stored (ids are written as 0, names empty), so an archive does not record who made it and is the same on every machine
add_data(name, data, mode=0o644)methodStores data, a String or Bytes, as a file member called name, with permission bits mode and the current time; returns nil. A tar member's size is written before its content, so a stream of unknown length cannot be stored without holding it: content too big for memory goes to a file first and is added with add
close()methodWrites the end-of-archive marker, finishes the gzip data when the Writer came from create(path, gzip=true), and releases the file when it came from create; returns nil. Over a stream it does not close target. Calling it again does nothing

Until close() the archive is incomplete, so a Writer always gets defer archive.close(). With gzip.open underneath, the tar Writer is closed first and the File second; two defers in the order of creation do exactly that.

The name of the last component is the default because the alternative, the path as given, would put build/ in front of every name for add("build/site") and would store an absolute path as home/me/…. The default stores site/…, as cp -r build/site dst/ would.

Names given to a Writer. A name is written the way a relative path is written on this platform and is stored with /. It must be usable when unpacked: not empty, not absolute, with no .. component and no NUL or \. Anything else raises ValueError: add() name "../x" would be unpacked outside its directory; an empty String raises ValueError: add() argument 'name' must not be empty, as an empty path does everywhere. A Writer therefore cannot produce an archive that extract refuses for its names.

The format written is the common one (ustar), with the extended (pax) header only for a member that needs it, such as a name over 100 bytes or a size over 8 GiB. There is no setting.

Member

One type shared with zip: tar.Member == zip.Member. A Member is an immutable description of one entry, with no I/O; its content comes from the archive through open(member). It shows as <Member docs/guide.md>. It cannot be constructed (TypeError: Member cannot be constructed; iterate an archive from zip.open(path) or tar.open(path)), and two Members are equal only when they are the same value.

PropertyValue
nameString: the name as stored, components separated by /, without the trailing / of a directory entry. It is not cleaned: ../x and /etc/passwd are reported as they are. Bytes that are not valid UTF-8 are shown as U+FFFD
sizeInt: bytes of content when unpacked; 0 for a directory or a link
modified_attime.Time, in the local zone (as fs.stat gives it)
modeInt: permission bits as stored (member.mode == 0o755).
is_fileBool: a regular file
is_dirBool
is_symlinkBool: a symbolic link
link_targetString: what a link points to, as stored; nil unless the member is a link

The names and meanings are those of fs.FileInfo, plus name and link_target. A member that is none of file, directory or link (a device, a FIFO) has all three is_ properties false.

A tar hard link has link_target set and is_file, is_dir and is_symlink all false; no other member has that combination.

What extract does, and what it refuses

The same rules hold for zip.extract, tar.extract and the extract method of both Readers. "The name" is the member's name, or the name= argument when the method was given one.

What is created

MemberResult under dst
FileA file with the member's content, its permission bits and its modification time. Missing parent directories are created (0o755), since many archives have no entries for them
DirectoryThe directory. An existing one is used as it is
Symbolic linkThe link, when its target is relative and, followed from where the link lands, stays inside dst. Otherwise it is refused
Hard link (tar)A hard link to the file already unpacked under the target name. The target is checked as a member name is
Anything else (device, FIFO, socket)Refused

Permission bits are the stored ones, limited to 0o777 and then by the process's umask, as for any file a program creates. Set-user-id, set-group-id and sticky bits are never applied. A directory always gets read, write and search permission for its owner, so that unpacking can continue inside it. Ownership is never applied: everything belongs to the user running the script. Directory modification times are not restored.

What is refused

HazardDefaultReported asTo do it anyway
A name that is absolute (/etc/passwd, C:\x), has a .. component, contains \ or NUL, is empty, or is a reserved device name on WindowsRefusedUnsafeError: extract() member "../../etc/passwd" of "upload.zip" would be written outside "incoming"The method, with a name= the script computed
A symbolic link whose target is absolute or leads outside dstRefusedUnsafeError: extract() link "current" of "x.tar" points outside "app": "/etc"Not possible with this module; skip the member in a loop
A name that passes through a symbolic link leading outside dst, whether the link was in dst before or came from this archiveRefused by the operating system interface used, whatever the name looked likeUnsafeError: extract() member "lib/x" of "x.tar" would be written outside "app"—
A device, FIFO or socketRefusedUnsafeError: extract() member "dev/null" of "rootfs.tar" is a deviceSkip the member in a loop
More content than the member declares (a header that understates its size)Stops at the declared size; nothing is left at the nameUnsafeError: extract() member "a.bin" of "x.zip" is larger than the 1024 bytes it declares—
The members' declared sizes add up to more than max_size (module function only)No limit unless max_size is givenUnsafeError: extract() "upload.zip" unpacks to 6442450944 bytes, over max_size 209715200A larger max_size, or nil
A file already at the nameRefusedExistError: extract() "app/bin/tool" already exists (pass overwrite=true), with data pathoverwrite=true replaces files and links. The existing entry is removed and a new one created, so nothing is ever written through an existing link
A directory where a file must go, or a file where a directory must goRefused, with or without overwriteExistError: extract() "app/bin" is a directory (or is not a directory), with data pathfs.remove it first
The same name twice in one archiveThe second is "a file already at the name"ExistError as aboveoverwrite=true, which keeps the last, as tar and unzip do

When the method was given a name= that is refused, the message adds where the member would have landed: extract() member "a.txt" of "x.zip" would be written outside "dst" as "../a.txt".

These rules follow from the table:

  • Nothing is skipped and no name is changed. An archive either unpacks as it says or raises. tar(1) strips a leading / and carries on, which unpacks something other than what the archive says without telling the caller.
  • zip.extract checks every member's name, kind and declared size before it writes anything, because a zip's index is available up front. A zip refused for those reasons leaves dst untouched. Link targets are stored as content and are checked when they are reached.
  • tar.extract stops at the member it refuses. The members before it stay unpacked: a tar cannot be checked ahead without reading all of it. A script that must not leave a partial tree unpacks into fs.mkdir_temp() and moves the result.
  • The default does not protect against an archive that is honestly huge, or one made to be (a "zip bomb" declares its true, enormous sizes). Content is streamed, so memory is never at risk; disk space is. For input from a source the script does not trust, pass max_size. With zip the refusal comes before anything is written; with tar it comes at the member whose declared size crosses the limit, before that member is written.
  • The method takes no max_size. In a loop the script has member.size, and no member can write more than that.
  • Reading (for member in, open(member)) never refuses a name. A listing shows ../../etc/passwd as it is stored. Only extract writes to disk under a member's name.

There is no default size limit because any number would be a policy that refuses some ordinary large archives, and changing it later would break scripts either way. What the default does guarantee is where files land and that no member exceeds its declared size.

Errors

FromKinds (besides TypeError and ValueError for arguments)Data
open, create, extract: the archive fileNotExistError, PermissionError, IOErrorpath: the archive
open, Reader: a compression tar does not readParseError open() "x.tar.xz" is xz-compressed; tar reads plain and gzip-compressed archives (also bzip2 and zstd)path: the archive, nil over a stream
Iteration, a member File, extract: not a tar, damagedParseError: "x.tar" is not a tar archive at the first step, corrupt tar data in "x.tar" later, read() corrupt data in member "a.log" of "x.tar"; extract() "x.tar" is not a tar archive and extract() corrupt tar data in "x.tar" from the module functionpath: the archive, nil over a stream
extract: a refused memberUnsafeErrormember: the Member refused. path: the archive, nil over a stream
extract: something in the way under dst, or dst cannot be writtenExistError, PermissionError, IOErrorpath: the path under dst
add: the file being addedNotExistError, PermissionError, IOErrorpath: that file
Reader(source) without read(size), Writer(target) without write(data)TypeError Reader() argument 'source' must have a read(size) method, got String—
open or extract of a Member that is not the current oneValueError open() "a.log" is not the current member; a tar archive is read in order—
open(name) with a StringTypeError open() argument 'member' must be Member, got String—
add_data with a readableTypeError add_data() argument 'data' must be String or Bytes, got File (a tar header holds the size before the content; write a stream to a file and add() it)—
A closed Reader or Writer; open of a directory or link; a bad name given to a Writer; a name already in the archive; add(".") without name=; a socket or device given to add; mode outside 0–0o777ValueError—

UnsafeError is not an IOError, because the disk and the archive both worked: a handler that receives archives from elsewhere catches exactly it, and can tell it from a full disk (IOError) and from a damaged archive (ParseError).

Over a stream there is no archive to name, so messages leave out of "x.tar": extract() member "../x" would be written outside "data".

Left out

Left outInstead
Reading .tar.xz, .tar.zst or .tar.bz2 in the moduletar.Reader over an exec pipe, as in the tasks above. The error names the compression it found, and recognition by content can grow a format without an API change
Changing an existing archive: appending, deleting or replacing a memberWrite a new archive
Copying a member into another archive without unpacking itextract and add, or for small members add_data(member.name, source.open(member).read())
A one-call "pack this directory"Three lines: create, defer close(), add. They show what the names inside will be
A compression level on tar.createtar.Writer(gzip.open(path, write=true, level=9))
Setting a member's modification time; an empty directory or a link from add_dataadd takes times and kinds from disk
Owner and group, extended attributes, sparse files, device nodesexec.run(["tar", …]) for system backups; this module is for releases and data
exclude= or skip= on add and extractA loop over fs.walk(path, skip=…) with add; a loop with extract(member, dst)
strip= on extractThe loop with name= in the tasks above, which also shows what happens to a member with no such component
Progress reportingA loop with the method
Restoring ownership, set-id bits and directory times; links that point outsideNot offered: these are the unsafe parts

Extending Goblin with Go

Goblin is implemented in Go, and its runtime values are Go values. This makes the standard library extension model straightforward: write Go code that implements the runtime contracts, expose it as a module or built-in function, then make both Goblin execution backends aware of it.

This chapter is for contributors extending the Goblin repository, not for ordinary Goblin programs. The extension code imports the repository packages:

import (
    "github.com/aisk/goblin/object"
)

The runtime boundary

Every Goblin value implements object.Object. Integer, Float, String, List, Dict, module values, functions, and user-defined Goblin types all appear to the Go runtime through this interface. It supplies conversion, comparison, operators, iteration, indexing, and attribute access.

This single interface is why a Go extension can participate naturally in Goblin expressions. A custom value can decide how it prints, whether it is truthy, what an attribute lookup returns, and which operators are valid. Custom object types explains the contract in detail.

Adding a function or module

A Go-callable Goblin function has this shape:

func(args object.CallArgs) (object.Object, error)

Place related functions in an extension package and return them from an object.Module. object.NewModule takes the module name, a map of plain values such as constants, and an object.Funcs map whose entries become functions named after their keys:

func Execute() (object.Object, error) {
    return object.NewModule("greeting", map[string]object.Object{
        "default_name": object.String("world"),
    }, object.Funcs{
        "greet": greet,
    }), nil
}

A new built-in module lives in its own Go package, extension/, and exposes that function as Execute. Register it once, in the table in extension/stdlib/stdlib.go. goblin run loads modules from that table, and goblin build-exe uses it to validate the import before emitting a direct import of the module's package, so a compiled program links only the modules it imports. A test in extension/stdlib checks that every registered executor really is extension/.Execute.

Add a focused Go test for the extension and a Goblin example when its user visible behavior needs end-to-end coverage.

Choosing an extension shape

Use a plain object.Function for a stateless operation such as a conversion or utility. Use object.Module for a named collection of functions and constants. Use a custom object.Object type when the feature has its own state, methods, or protocol behavior, such as a Path, HTTP response, file, or time value.

The next chapters show custom values and safe argument parsing.

Custom object types

Every runtime value in Goblin is a Go implementation of object.Object. The interface is the contract between a value and the interpreter or transpiler. It includes these groups of methods:

GroupObject methods
Display and conversionToString(), ToBool() (which ! negates)
Comparison and operatorsEquals(), Compare(), Add(), Minus(), Multiply(), Divide(), Modulo()
Reflected operatorsRAdd(), RMinus(), RMultiply(), RDivide(), RModulo()
Collection protocolsIter(), Index()
MembersGetAttr(), Attributes(), SetIndex(), SetAttr()
IdentityTypeName()

The reflected operators are required, but most types have nothing to say through them: embed object.NoReflectedOps and they all answer "not handled".

Types should also implement String() string, satisfying fmt.Stringer. It is not part of the interface, but diagnostics and formatting use fmt.Stringer and fall back to TypeName() when String is not available. ToString is the failing counterpart, which for a Goblin-defined type runs its Show impl.

Assignment is part of the interface too: SetIndex and SetAttr return a bool saying whether the value accepts that form of assignment at all. A value that accepts neither embeds object.NoAssignment and says nothing.

Start with a Go struct

This excerpt shows the state, conversion, and member portion of a Counter value. A complete implementation must also provide every remaining object.Object method listed above. Unsupported operators should return the standard TypeError rather than silently accepting an operation.

type Counter struct {
    object.NoReflectedOps // nothing completes an operation from Counter's right
    object.NoAssignment   // counter[i] = x and counter.f = x are not accepted
    Value int64
}

func (c *Counter) TypeName() string { return "Counter" }
func (c *Counter) String() string { return fmt.Sprintf("Counter(%d)", c.Value) }
func (c *Counter) ToString() (string, error) { return c.String(), nil }
func (c *Counter) ToBool() (bool, error) { return c.Value != 0, nil }

func (c *Counter) GetAttr(name string) (object.Object, error) {
    switch name {
    case "value":
        return object.Integer(c.Value), nil
    case "increment":
        return &object.Function{Name: "increment", Fn: c.increment}, nil
    default:
        return nil, object.NewAttributeError("Counter has no attribute '%s'", name)
    }
}

// Attributes lists what attributes(counter) shows: properties first, then
// methods.
func (c *Counter) Attributes() []string {
    return []string{"value", "increment"}
}

func (c *Counter) increment(args object.CallArgs) (object.Object, error) {
    if err := object.RequireNoKeyword("increment", args); err != nil {
        return nil, err
    }
    if len(args.Positional) != 0 {
        return nil, object.NewTypeError("increment() takes no arguments")
    }
    c.Value++
    return object.Integer(c.Value), nil
}

The receiver-bound object.Function is the key pattern: Goblin evaluates counter.increment() by looking up increment and then calling the returned function. It can safely mutate the Go receiver.

For example, a Counter that has no addition at all should implement Add by returning object.Unsupported with the matching object.ErrFmt format, which reads "cannot add Counter". Apply the same principle to the other unsupported protocol methods. A handle type with no operators at all can embed object.OpaqueBase instead of writing them out.

func (c *Counter) Add(other object.Object) (object.Object, error) {
    return nil, object.Unsupported("Counter", object.ErrFmtCannotAdd)
}

Define protocol behavior deliberately

Return a useful result for supported operations and a TypeError for unsupported ones. For example, a Vector can implement Add and Compare while a Counter may only need display, truthiness, and members. When the operation exists but the right operand does not fit, object.NewOperandError words the error the way the built-in types do: "cannot add Vector and String".

func (v Vector) Add(other object.Object) (object.Object, error) {
    right, ok := other.(Vector)
    if !ok {
        return nil, object.NewOperandError(object.OpAdd, "Vector", other)
    }
    return Vector{X: v.X + right.X, Y: v.Y + right.Y}, nil
}

Compare returns a negative value, zero, or a positive value. Iter returns a slice of object.Object values. Index must verify that its index is an object.Integer and return IndexError for an invalid position.

A type whose elements are produced one at a time (lines of a stream, a large or unbounded sequence) also implements object.Iterable, whose Iterator method starts a pass and returns an object.Iterator. Its Next returns the next value and true, false at the end, or an error that the loop raises at the for statement. Every consumer — for, destructuring, * arguments, List(x) — goes through object.Iterate, which prefers Iterable over Iter, so Iter can then simply return object.Collect(v). Go code that walks an arbitrary value calls object.Iterate (or object.Collect for the whole slice) rather than Iter.

A loop may stop pulling before the end (break, return, an error), so a pass is ended explicitly: whoever starts one with object.Iterate calls the Iteration's Close exactly once however the pass ends, and never calls Next after it. An iterator that holds something for the duration of one pass (a file it opened in Iterator, say) also implements object.Closer and releases it in Close, and only there; object.IteratorWithClose(next, close) builds one from two functions. Close cannot fail, so a source whose release can fail reports that from its last Next. A pass owns only what it acquired when it started: iterating a file leaves the file open, because the file is the iterable's, not the pass's.

func (c Countdown) Iter() ([]object.Object, error) { return object.Collect(c) }

func (c Countdown) Iterator() (object.Iterator, error) {
    n := c.From
    return object.IteratorFunc(func() (object.Object, bool, error) {
        if n <= 0 {
            return nil, false, nil
        }
        n--
        return object.Integer(n + 1), true, nil
    }), nil
}

Name types in messages with TypeName

Use value.TypeName(), not %T, when an error mentions the type of a value. A Go type name is an implementation detail that differs between the two backends — a user-defined Point is *interpreter.instance under goblin run and *main.Point in a compiled program — so %T makes the same program report different messages depending on how it was executed. TypeName returns the Goblin-level name, which is why every type declares it:

func (v Vector) TypeName() string { return "Vector" }

Embedding is not enough here: a type that embeds another for its defaults inherits that type's name too, which is exactly the wrong answer.

Operators dispatch through package-level helpers

The operators do not call Equals, Compare, Add and friends on the left operand directly: both backends go through object.Equals and object.NotEquals, the ordering helpers object.Less, object.LessEqual, object.Greater and object.GreaterEqual, and object.Add, object.Minus, object.Multiply, object.Divide and object.Modulo, which also give the right operand a chance to answer. A custom type therefore only has to recognize the types it knows, and its Compare is reached even when it appears on the right of 1 < value. Report an unfit pair with object.NewTypeError so the reflected attempt is made; any other error propagates as-is. Equals follows the same rule with its own error return: a TypeError from it means "not this type" and leaves == total, while any other error fails the comparison.

Arithmetic reaches the right operand through RAdd, RMinus, RMultiply, RDivide and RModulo, the Go side of Add.radd and friends. Their argument is the LEFT operand — RMinus(left) computes left - receiver — and the bool they return reports whether the receiver handled this operand at all; returning false leaves the left operand's error in place. Embed object.NoReflectedOps and override only the operator a type completes from the right, the way object.String and object.List override RMultiply to make 3 * "ab" work:

type Vector struct {
    object.NoReflectedOps
    X, Y float64
}

// `2 * v` — scaling reads the same in either operand order.
func (v Vector) RMultiply(left object.Object) (object.Object, bool, error) {
    n, ok := left.(object.Integer)
    if !ok {
        return nil, false, nil
    }
    return Vector{X: v.X * float64(n), Y: v.Y * float64(n)}, true, nil
}

A Go type has no impl blocks: it implements the object.Object methods, and by that the protocols. a < b or compare(a, b) on a Go value calls object.Compare, String(x) calls ToString, a + b calls object.Add, and so on, so a Go type that implements Compare works with max and sort without further work.

For a complete reference implementation, read the existing runtime types in object/, especially path.go, list.go, dict.go, bytes.go, and chan.go. They show how to report errors consistently and how to expose methods through GetAttr.

Expose a constructor with stable type identity

Most custom values need a constructor added to a module or to the built-ins map. Use object.NewNativeConstructor so the exported callable and every instance share one stable identity, matching Goblin-defined types:

var CounterType = object.NewNativeConstructor(
	"Counter",
	func(args object.CallArgs) (object.Object, error) {
		p := object.NewArgParser("Counter", args)
		start := p.IntOr("start", 0)
		if err := p.Finish(); err != nil {
			return nil, err
		}
		return &Counter{Value: int64(start)}, nil
	},
)

Place CounterType.Function in the module members map, and have the value return the same function from a Constructor method, which is what type_of asks for (the object.Constructed interface):

func (c *Counter) Constructor() *object.Function { return CounterType.Function }

Goblin can then use the same constructor identity check for native, built-in, and source-defined values:

var counter = module.Counter(start=10)
print(type_of(counter) == module.Counter) # true

A type that a module exports only for type_of comparisons, with no way to build it from arguments, uses object.NewOpaqueConstructor("File", "fs.open(path)"): calling it raises TypeError: File cannot be constructed; use fs.open(path).

A value without a Constructor method still has a type: type_of answers a stand-in function named after its TypeName, which cannot be called.

Create the helper once at package scope. Constructing it during every module load would give the same native type multiple identities. See Functions and arguments for the argument parser used by the constructor.

Functions and arguments

A Go function visible to Goblin is an object.Function. Its Fn callback receives object.CallArgs and returns either a runtime value or an error.

var Greet = &object.Function{
    Name: "greet",
    Fn: greet,
}

func greet(args object.CallArgs) (object.Object, error) {
    p := object.NewArgParser("greet", args)
    name := p.Str("name")
    excited := p.BoolOr("excited", false)
    if err := p.Finish(); err != nil {
        return nil, err
    }
    suffix := "."
    if excited {
        suffix = "!"
    }
    return object.String("Hello, " + string(name) + suffix), nil
}

This accepts both greet("Ada") and greet(name="Ada", excited=true). The order of parser calls defines the positional argument order. Finish is mandatory: it reports unconsumed positional arguments and unexpected keyword arguments.

ArgParser accessors

NewArgParser accumulates the first argument error, letting the function extract all of its inputs before checking once at Finish.

AccessorMeaning
Any(name) / AnyOr(name, default)Required or optional arbitrary Object
Int, Float, String, BoolRequired typed value
IntOr, FloatOr, StrOr, BoolOrOptional typed value with a default
Number / NumberOrInt or Float
Float64Numeric value converted to Go float64
FuncA Goblin function
Path / NullablePathA file name: a String or a value implementing object.PathValue (fs.Path), as Go text
DataA data argument as an io.Reader: a String, Bytes, or anything with a read(size) method (read, never closed)
DataBytesData read to the end as []byte; a failure to read the stream is what Finish reports
TimeoutA timeout= number of seconds as a time.Duration
OptionalAnyValue plus whether it was supplied
RestAll remaining positional values

Use OptionalAny when omitted and explicitly passing nil have different meanings. Use Rest for an open-ended positional tail.

func sum(args object.CallArgs) (object.Object, error) {
    p := object.NewArgParser("sum", args)
    values := p.Rest()
    if err := p.Finish(); err != nil {
        return nil, err
    }
    var total int64
    for _, value := range values {
        n, ok := value.(object.Integer)
        if !ok {
            return nil, object.NewTypeError("sum() values must be Int")
        }
        total += int64(n)
    }
    return object.Integer(total), nil
}

Other binding helpers

For a function that permits positional arguments only, call object.RequireNoKeyword before checking the positional count. This is useful for small no-options methods.

BindArguments is useful when an extension needs a declared parameter list plus varargs or keyword captures. It binds positional and named values, detects duplicates, and returns a map of parameter names to Object values.

bound, err := object.BindArguments(
    "inspect",
    []string{"name"},
    "rest",
    "options",
    args,
)
if err != nil {
    return nil, err
}
name := bound["name"].(object.String)
rest := bound["rest"].(*object.List)
options := bound["options"].(*object.Dict)

Always return object.NewTypeError or another runtime error constructor for user-facing failures. This preserves Goblin error handling and produces useful tracebacks in both the interpreter and compiled executable.