Procedure Specs
A procedure spec is a line at the top of a procedure body that names a predicate for each argument and for the result:
(define (scale n factor)
(: number? number? -> number?)
(* n factor))Read it as "scale takes a number and a number and returns a number". The predicates are ordinary Sigil procedures, so there is no separate type language to learn: anything you can test with a predicate, you can put in a spec. In other words, number? in this example is the standard predicate for checking whether a value is a number.
A spec does two jobs. It is always stored on the procedure, where documentation tools and your own code can read it. And when you turn on the sigil-checks feature, the compiler also inserts code that tests each argument against its predicate on every call. This guide covers how to write specs, exactly when each of those things happens, and how to read specs back.
Writing a Spec
Placement
The spec is the first expression in the body of a define or lambda:
(define (scale n factor)
(: number? number? -> number?)
(* n factor))
(define square
(lambda (x)
(: number? -> number?)
(* x x)))A docstring written as ;;; comments above the define doesn't count as a body expression, so the spec still comes first.
define and lambda remove the spec form before compiling the body. Anywhere else, (: ...) is an ordinary call to a procedure named :, which doesn't exist. If you put the spec after another expression in the body, or inside a case-lambda clause, the procedure compiles but fails when it runs:
Error (unbound): unbound variable ':'
Arguments and Results
Inside (: ...), write one predicate per positional parameter, in order, then ->, then the predicate for the result. The syntax is flat: don't wrap the predicates in another pair of parentheses.
(: string? integer? -> string?) ; correct
(: (string? integer? -> string?)) ; wrongAlways write the result part. Use void? for a procedure that is called only for its side effects, and any? for a result that can be any value.
Optional, Keyword and Rest Arguments
Optional parameters (opts:) take positional predicates like required ones. Keyword parameters (keys:) use a (name: predicate) pair. A rest parameter (rest:) is written as the predicate for each element followed by ...:
(import (sigil string))
(define (pad text (opts: (width 10)) (keys: (fill #\space)))
(: string? integer? (fill: char?) -> string?)
(string-append (make-string (max 0 (- width (string-length text))) fill)
text))
(define (join-all separator (rest: parts))
(: string? string? ... -> string?)
(string-join parts separator))Here string? integer? cover text and width, (fill: char?) covers the fill: keyword, and string? ... describes every element of parts.
Multiple Return Values
A procedure that returns several values lists one predicate per value after ->:
(define (split-at-first text)
(: string? -> string? string?)
(values (substring text 0 1)
(substring text 1 (string-length text))))Combinators
(sigil core) provides predicate combinators that build a new predicate from others. They are also exported from (sigil spec).
| Combinator | Accepts |
|---|---|
(maybe pred) | #f or a value satisfying pred |
(any-of pred ...) | a value satisfying at least one pred |
(none-of pred ...) | a value satisfying none of the preds |
(list-of pred) | a proper list whose every element satisfies pred |
any? | any value |
Write a combinator call directly in the spec:
(define (describe-id id tags)
(: (any-of integer? string?) (list-of symbol?) -> (maybe string?))
(and (pair? tags)
(format "~a:~a" id (car tags))))(maybe pred) is the convention for a result that is #f when nothing was found, such as a lookup that can miss.
Not the Same as Record Patterns
match has a record pattern that also starts with :, such as ((: point x: y:) (+ x y)) in the Functional Programming Style guide. That pattern destructures a struct or record inside a match clause. It has nothing to do with procedure specs. A spec only ever appears as the first expression of a procedure body.
When Specs Are Applied
| Where | What happens with the spec |
|---|---|
| Definition | Always stored on the procedure, as data. |
| Each call | Arguments are checked only when the code was compiled with the sigil-checks feature. |
| Compiler and linters | Not used. Nothing checks specs statically. |
| REPL, MCP server, editor | Shown alongside the procedure's documentation. |
Stored on Every Procedure
When define or lambda sees a spec, it removes it from the body and attaches the spec items to the procedure as metadata. The items are stored as quoted data, not evaluated, so number? is stored as the symbol number?. Storing the spec costs nothing per call, and it happens in every build.
Checked at Runtime with sigil-checks
Runtime checking is a compile-time decision. When define or lambda expands, it wraps the argument checks in a cond-expand on the sigil-checks feature. Code compiled without that feature contains no check code at all. Code compiled with it tests each argument before the body runs.
For scripts, sigil eval and the REPL, set SIGIL_CHECKS=1 in the environment:
SIGIL_CHECKS=1 sigil scale.sgl
SIGIL_CHECKS=1 sigil replFor a project built with sigil run, sigil build or sigil test, add sigil-checks to the features: list of the configs that should check:
configs: (list
(config name: 'dev
output-dir: "build/dev"
bundle?: #t
features: '(debug dev sigil-checks))
(config name: 'release
output-dir: "build/release"
bundle?: #t
features: '(release)))A config checks only if its features: list names sigil-checks. Neither the dev config that sigil init writes nor the built-in configs the CLI falls back to include it, so checking is off until you add it.
How each command decides:
sigil build,sigil runandsigil testuse only the config (devunless you pass--config). They ignoreSIGIL_CHECKSin your environment, soSIGIL_CHECKS=1 sigil run --config releasestill runs without checks.sigil replandsigil evaluse onlySIGIL_CHECKS, even inside a project whose config hassigil-checks.
Checks apply to the code you compile with the feature. The standard library ships precompiled, so its specs are documentation only: (->list 5) reports ->list's own error, not a spec violation, even with SIGIL_CHECKS=1.
What a Check Covers
Checks test arguments only:
- Checked: required and optional positional arguments, and keyword arguments that have a
(name: pred)entry. - Not checked: the result after
->, the elements of a rest argument, every argument of a procedure written with a dotted parameter list such as(define (f a . more) ...), and the constructors and setters generated from struct or record field predicates (see Structs and Records).
The check runs after defaults are filled in, so an optional or keyword argument the caller leaves out has its default checked. A #f default with an integer? predicate fails on every call that omits the argument:
(define (fetch url (keys: (timeout #f)))
(: string? (timeout: integer?) -> any?)
url)
(fetch "https://example.com")
; with checks: fetch: expected timeout to satisfy integer?, got #f (boolean)Write (timeout: (maybe integer?)) for an argument whose default is #f.
Because results aren't checked, a wrong result spec goes unnoticed:
(define (wrong-return x)
(: integer? -> string?)
x)
(wrong-return 5) ; => 5, even with checks onPositional predicates are not compared with the parameters either. Extra positional predicates are ignored, and parameters without a predicate are not checked. Keyword entries are compared: an entry whose keyword names no keyword parameter is an error when the procedure is defined, so (: any? (bogus: string?) -> any?) on (define (f x) ...) raises f: spec entry (bogus: string?) names no keyword parameter.
What a Violation Looks Like
A failed check raises an exception of kind type-error. Running the scale example from a file scale.sgl with (scale "2" 3) at the top level and checks on prints:
Error (type-error): scale: expected n to satisfy number?, got "2" (string) Expected: number? Got: string scale defined at scale.sgl:1:1
The message names the procedure, the parameter, the predicate as written in the spec, the value and its type. The last line is a location. When a procedure in your code called scale, it is that call, such as at scale.sgl:6:12. When there is no such call to point at, it is where scale is defined, labeled defined at. That happens for a call at the top level of a script or sigil eval, and for a call from a library procedure such as map. A call in tail position leaves no frame for its caller, so the location is the nearest call in your code that is still waiting for a result.
Without checks, the same call fails later, inside the body, with whatever error the body produces:
Error (type-error): *: expected number
You can catch a violation like any other exception. The irritants are the predicate, the type name of the bad value and the procedure name, all as strings:
(import (sigil error))
(guard (e ((eq? (exception-kind e) 'type-error)
(println "message: ~a" (exception-message e))
(println "irritants: ~s" (exception-irritants e))))
(scale "2" 3))message: scale: expected n to satisfy number?, got "2" (string)
irritants: ("number?" "string" "scale")The name in the message is the one define binds, including for procedures that use opts:, keys: or rest: and for a lambda written directly as the value of a define. A define-method body reports the multimethod's name. A lambda that is not the value of a define, such as one passed as an argument, reports the name anonymous:
Error (type-error): anonymous: expected fill to satisfy char?, got "0" (string)
If a predicate name is misspelled, nothing complains until a checked call evaluates it:
Error (unbound): unbound variable 'integr?'
Performance
Each check is one predicate call per checked argument, on every call. In a script loop of three million calls to a two-argument procedure, the number? number? spec roughly tripled the time per call compared with checks off. The cost scales with what the predicates do: list-of walks the whole list on every call.
A combinator call written inside the spec, such as (maybe number?), builds a new predicate each time the procedure is called. If a checked procedure is on a hot path, define the combined predicate once and use its name:
(define maybe-port? (maybe port-number?))
(define (listen-on port)
(: maybe-port? -> void?)
...)In the same loop this cut the checked time by 20 to 30 percent. The tradeoff is that procedure-spec and the documentation tools now show maybe-port? instead of (maybe port-number?).
To turn checks off, compile without sigil-checks. A release config that doesn't list the feature produces code with no checks and no cost.
Reading Specs Back
procedure-spec and spec->string
procedure-spec returns a procedure's spec as a list, or #f if it has none. spec->string from (sigil spec) formats that list for display:
(import (sigil spec))
(procedure-spec scale) ; => (number? number? -> number?)
(spec->string (procedure-spec scale)) ; => "number? number? -> number?"Combinator forms and keyword entries come back as written:
(spec->string (procedure-spec pad))
; => "string? integer? (fill: char?) -> string?"
(spec->string (procedure-spec describe-id))
; => "(any-of integer? string?) (list-of symbol?) -> (maybe string?)"Because a spec is plain data, you can use it in your own tooling, for example to generate argument documentation for a command table.
Built-in procedures implemented in C carry the spec their define-native declaration gives, so (procedure-spec car) returns (pair? -> any?). A built-in with no such declaration, such as current-srcloc, has no spec and returns #f.
In the REPL
,doc (or ,d) prints a Spec: line under the signature:
> ,doc ->list (->list ...) -> procedure Spec: any? -> list? Convert a list, vector, or dynamic array to a list in element order.
,doc looks up a symbol through the documentation index, so it works for procedures in loaded modules. For a procedure you just defined at the prompt, call procedure-spec directly.
In Editors and the MCP Server
The sigil mcp server's sigil_lookup and sigil_search tools print a Spec: line for procedures that have one. An agent can then look up each predicate by name to see exactly what it accepts. The language server (sigil lsp) includes the spec in hover text. Both read the spec from the running procedure, so they show it only for modules the server process has loaded, such as the standard library.
Writing Good Specs
Any Predicate Works
A spec predicate is any procedure of one argument that returns true or false. Built-in type predicates (string?, integer?, procedure?, port?), struct predicates, and your own procedures all work the same way:
;;; Return #t if X is a valid TCP port number.
(define (port-number? x)
(: any? -> boolean?)
(and (integer? x) (<= 1 x 65535)))Give a custom predicate a ? name and a docstring that says what it accepts. The name appears in violation messages and in documentation, and someone reading port-number? in a spec can look it up to find the rule.
A predicate can also be an inline expression, such as (lambda (x) (> x 0)). Prefer a named predicate: the inline form shows up verbatim in messages and docs, and it is rebuilt on every checked call.
Conventions
These conventions keep specs consistent across the standard library:
- Write a result after
->on every spec. - Use
void?for side-effect procedures,any?for results that can be anything, and(maybe pred)for "a value or#f". - Give a predicate procedure the spec
(any? -> boolean?), since it must accept any value. - Give a procedure that only makes sense on one type that type's predicate, even when it returns a boolean:
(port? -> boolean?)forport-open?. - Spec procedures you export. A spec on an internal helper is only worth it if you want it checked.
Structs and Records
Field predicates on define-struct generate specs for the procedures the macro creates:
(import (sigil struct))
(define-struct server
(host string?)
(port port-number? default: 8080))
(procedure-spec server) ; => ((host: string?) (port: port-number?) -> server?)
(procedure-spec server-port) ; => (server? -> port-number?)define-record fields take predicates the same way, and they generate specs for the accessors. Neither constructor checks its fields, even with sigil-checks on: (server host: "localhost" port: "eighty") succeeds. Setters for mutable: #t struct fields get a spec such as (server? port-number? -> void?) and don't check it either. If you need field validation, check the values in a procedure that builds the struct, and give that procedure a spec.
The struct predicate itself is a good spec predicate for procedures that take the struct:
(define (server-url srv (keys: (scheme "http")))
(: server? (scheme: string?) -> string?)
(format "~a://~a:~a" scheme (server-host srv) (server-port srv)))Specs and Multimethods
define-method bodies accept a spec, and with checks on each method checks its own arguments:
(import (sigil method))
(define-multi measure)
(define-method measure (s 'string)
(: string? -> integer?)
(string-length s))
(define-method measure (x default:)
(: list? -> integer?)
(length x))
(measure 42)
; with checks: measure: expected x to satisfy list?, got 42 (integer)The spec belongs to the method, not to the multimethod. (procedure-spec measure) returns #f, so the documentation tools show no spec for measure. Dispatch already selects a method by type, so a method spec mostly matters for the default: method, which receives every value no other method handled.
Summary
- Put
(: pred ... -> result ...)first in adefineorlambdabody. - Specs are always stored, and
procedure-spec,,doc, the MCP server and the language server show them. - Arguments are checked at runtime only in code compiled with
sigil-checks:SIGIL_CHECKS=1for scripts,sigil evaland the REPL, the config'sfeatures:for projects. - Defaults of omitted arguments are checked too, so use
(maybe pred)for a#fdefault. - Results, rest elements, dotted parameter lists, and struct constructors and setters are never checked, and nothing checks specs statically.
- A violation raises a
type-errorexception naming the procedure, parameter, predicate and value.
See also: Error Handling for catching type-error exceptions, and Library Design for API conventions.