Introduction
Calque is a small, statically typed, expression-oriented Lisp and its
WebAssembly toolchain. It parses and type-checks a program, optimizes the typed
AST, lowers it to WebAssembly, and ships the que CLI, formatter, language
servers, runtime integration, and editor integrations.
Why
que? Calque is the language and toolchain name.queis its compact technical spelling: the command isque, source files end in.que, project configuration isque.toml, and the language server isquelsp.
Calque is designed for a particular trade-off: write direct functional code when it is the clearest model, and drop into explicit vectors, loops, and mutation when a program needs predictable work and memory behavior. The compiler type-checks the whole program before generating Wasm, and can explain many safety and optimization facts it proves.
(let sum-squares
(lambda (xs)
(|> xs
(map (lambda (x) (* x x)))
sum)))
(sum-squares [1 2 3 4 5])
; 55
What Calque provides
- Hindley–Milner type inference, polymorphic functions, and explicit
sigdeclarations where a boundary needs a known type. - Lexical closures, recursion, partial application, macro expansion, and data-last functional APIs.
- Mutable locals and mutable vectors with direct loop constructs.
- Deterministic reference-counted memory for vectors, tuples, and closures; source-level reference cycles are rejected.
- Fixed-size
Intarithmetic, fixed-pointDec, and compact closed enums. - Static warnings for likely out-of-bounds access, empty-vector operations, unsafe arithmetic, and termination facts that could not be proven.
- WebAssembly output that runs through an external WASI runtime, plus an optional wasm2c/native-C repository path for ahead-of-time native binaries.
- The
quecommand, formatter, language servers, and editor integrations.
Status and compatibility
Calque is pre-1.0. It has a substantial regression and differential test suite, but the language and standard-library API may still evolve. Treat the compiler version as part of a project’s build input; pin a release for long-lived work.
The rest of this book describes behavior implemented by the repository. For a live list of library signatures from the compiler you are actually running, use:
que --lib types
que --lib types 'Table/*'
que --lib source Table/get
Installation
Calque uses the que command and .que source files. The compiler is
installed separately from the WASI runtime that executes compiled programs.
wasmtime is the default runtime; wasmer and iwasm/WAMR also work.
Compiler and bundled library
macOS and Linux
The installer downloads the latest release for the current architecture and
installs que in /usr/local/bin and the bundled library in
/usr/local/share/que. It may ask for your sudo password.
curl -fsSL https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/install.sh | bash
Install a compatible WASI runtime separately and ensure it is on PATH. Then
verify the installation:
que --help
wasmtime --version
Windows
Run this in PowerShell. It installs the latest que.exe and que-lib.lisp
under %LOCALAPPDATA%\\Programs\\Que and adds its bin directory to your user
PATH; administrator rights are not needed.
irm https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/install.ps1 | iex
Restart PowerShell after the installer finishes, then install a compatible
WASI runtime separately (normally Wasmtime) and ensure it is on PATH:
que --help
wasmtime --version
For one invocation, choose a runtime other than the default:
que hello.que --runtime wasmer
que hello.que --runtime /path/to/iwasm
Language server and editors
quelsp is a separate executable. It provides diagnostics, type hovers,
completion, signatures, formatting integration, and project-aware navigation.
It does not need a WASI runtime merely to serve an editor.
macOS and Linux
curl -fsSL https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/lsp.sh | bash
quelsp --help
Windows
Run this in PowerShell after the compiler installation:
irm https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/lsp.ps1 | iex
Restart PowerShell if necessary, then check it:
quelsp --help
The VS Code extension uses quelsp from PATH by default. To choose a
specific executable, set que.languageServer.path to its full path. The
included Neovim and Emacs integrations also look for quelsp on PATH.
Emacs
Emacs 29.1+ is supported through the built-in Eglot client. The mode supplies Calque syntax highlighting, indentation, formatting, run commands, and Eglot diagnostics, inferred-type hover, completion, signatures, and definitions.
curl -fsSL https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/install-emacs.sh | bash
Then add the printed load-path and (require 'que-mode) forms to your Emacs
init file. The installer does not rewrite an existing init file. See
miscs/emacs/README.md
for configuration and command bindings.
For the managed Neovim workstation on a fresh Linux machine—Calque, quelsp,
Wasmtime, Neovim, Telescope, Catppuccin, and the Calque setup—use:
curl -fsSL https://raw.githubusercontent.com/AT-290690/que-script/main/scripts/install-all-linux.sh | bash
See Projects, tests, and editors for Neovim commands, VS Code configuration, and project behavior.
Getting started
Install Calque, a WASI runtime, the language server, and optional editor
integration by following Installation. Once que is on
your PATH, continue here.
First program
Create hello.que:
(let greeting "Hello, Calque!")
(println! greeting)
Run while developing:
que hello.que --debug --allow print
Use --opt for release-style execution after checking the program’s
invariants:
que hello.que --opt --allow print
--debug keeps runtime guards for checked integer arithmetic, division by
zero, and vector access where appropriate, and reports static-analysis
findings. --opt enables optimization and removes those optional runtime
guards; it is not a substitute for establishing correctness.
See Debug, optimized, and native execution for
the precise safety and deployment contract.
Learn from the installed compiler
que --help
que --learn
que --examples
que --style
que --pitfalls
Evaluate a small source expression without making a file:
que --eval '(+ 20 22)' --debug
A project
A project uses que.toml to supply optional source dependencies and compiler
environment settings:
entry = "main.que"
deps = ["./lib/math.que"]
[env]
QUE_TCO = "aggressive"
Run the entry file explicitly from the project folder:
que main.que --debug
Calque discovers the nearest que.toml, loads deps as definition bundles, and
applies its [env] settings. See Projects, tests, and
editors for the exact rules.
Language tour
Calque is an expression language. A program is a sequence of forms and its
last value is the result. Function bodies also sequence their forms, so a
separate do is useful for readability but not required merely to sequence.
(let classify
(lambda (x)
(cond (< x 0) "negative"
(= x 0) "zero"
"positive")))
(map classify [3 -1 0 8])
; ["positive" "negative" "zero" "positive"]
block is different from sequencing: it creates a lexical scope. Use it when
two branches or repeated loop bodies need their own local bindings.
(if enabled?
(block (let label "on") label)
(block (let label "off") label))
Data and calls
[1 2 3] ; vector
{ "Ada" 37 } ; tuple
"hello" ; string, typed as [Char]
'x' ; Char
true ; Bool
nil ; unit, type ()
(+ 20 22) ; ordinary prefix call
(map (lambda (x) (* x x)) [1 2 3])
Calls are curried. Supplying fewer arguments produces a function value, which makes partial application useful but also means that accidentally omitting an argument can produce a closure instead of an immediate error.
(let add2 (+ 2))
(add2 40) ; 42
Functional and imperative code together
Collection transforms use data-last arguments so they compose naturally:
(|> [1 2 3 4 5 6]
(select (lambda (x) (= (% x 2) 0)))
(map (lambda (x) (* x x))))
; [4 16 36]
For a hot update loop, use a mutable local and a mutable vector directly:
(let increment-all!
(lambda (xs)
(loop i (< i (length xs))
(set! i (+ (get i xs) 1) xs))
xs))
(increment-all! [10 20 30])
; [11 21 31]
The following chapters spell out the rules behind these examples.
Calque, form by form
This is a guided tour of what happens between a Calque source form and a running WebAssembly program. It is a map of the system, not a replacement for the language reference.
Calque deliberately combines two styles: direct functional transformations when they are clearest, and explicit loops and mutable vectors when work and storage should be visible in the source.
(let sum-even-squares
(lambda (xs)
(|> xs
(select (lambda (x) (= (% x 2) 0)))
(map (lambda (x) (* x x)))
sum)))
(sum-even-squares [1 2 3 4 5 6])
; 56
The exact generated instructions may improve between releases. The language rules and safety model below are the contract.
1. Forms become ordinary expressions
Calque is an expression-oriented Lisp. Calls are prefix forms, vectors use
square brackets, tuples use braces, and the final expression of a program or
function body is its value. In the example, sum-even-squares is bound to a
function and the final call produces an Int.
|> is convenient surface syntax, not a second evaluation model. It is a
macro that rewrites the source into ordinary, data-last calls before type
inference. Conceptually, the function body becomes:
(sum
(map (lambda (x) (* x x))
(select (lambda (x) (= (% x 2) 0)) xs)))
That is why pipelines, comp, and explicit calls have the same type rules and
runtime behaviour. Other bundled conveniences such as loop, when, cond,
+=, and match/string are macros too: they generate normal Calque forms;
they do not bypass type checking or ownership.
Inspect an expansion when it is surprising:
que program.que --emit source
See Pipelines and composition and Macros.
2. Inference gives every form a shape
After macro expansion, Calque infers a type for every expression. The example has the conceptual type:
sum-even-squares : [Int] -> Int
The lambda parameter begins unknown. % constrains its elements to Int;
select preserves the element type; map produces another [Int]; and sum
produces an Int. No annotation was needed, but an inconsistent use is still
rejected before Wasm generation.
This is Hindley–Milner-style inference extended with vectors, tuples, nominal closed enums, and a value restriction for mutable allocations. An empty vector does not become independently polymorphic at every use:
(let values [])
(push! 1 values) ; values is now [Int]
; (push! true values) ; type error
Enum tags compile compactly but are not Int values in the language type
system. That prevents accidentally mixing domains and lets match check that
all cases are covered:
(enum Light Red Amber Green)
(let action
(lambda (light)
(match light
Red "stop"
Amber "wait"
Green "go")))
Read Types, Inference and signatures, and Enums and matching for the full rules.
3. Analysis proves runtime facts
Types establish that a value is an Int, a [T], or a function. They cannot
alone establish that an index is within this vector’s current length, that an
addition cannot overflow, or that a loop makes progress.
Calque therefore runs a flow-sensitive static analysis after inference. A counted loop makes a useful bounds invariant visible:
(let copy
(lambda (xs)
(let out [])
(capacity! (length xs) out)
(loop i (< i (length xs))
(push! (get i xs) out))
out))
Inside the loop, the analyser can derive 0 <= i < length(xs), so the get
is eligible for unchecked optimized lowering. If it cannot prove a property,
that is a warning—not proof that the program is wrong. Make an input-dependent
invariant explicit with a guard:
(if (and (>= index 0) (< index (length xs)))
(get index xs)
fallback)
The same analysis tracks simple arithmetic ranges, recognised safety predicates, loop progress, effects, and selected ownership facts. It is conservative: it removes a check only after a proof, and discards facts that a mutation or unknown call could invalidate.
que explain program.que --opt
que explain program.que --opt --json --out explain.json
que explain reports result type, warnings, proven bounds, termination
evidence, effects, allocation/call shape, and generated-code observations. It
is a static report, not a timing profiler. See Correctness analysis
and Warnings and proof recipes.
4. Values are immediate or managed
The core scalar values are immediate Wasm values:
| Calque value | Runtime representation |
|---|---|
Int | signed i32 |
Dec | scaled signed i32 |
Bool, Char, unit | immediate i32 values |
| enum value | compact i32 tag, still nominally typed |
Vectors, strings, tuples containing managed values, and closures are managed
values. A string is [Char] at the language level; the current runtime does
not store it as a packed UTF-8 byte array. String operations are therefore
ordinary vector operations, with the same predictable trade-off in memory use.
The distinction is practical: scalar computations do not allocate or use reference counting; managed-memory work happens where a program constructs or shares managed values.
5. Managed values have deterministic ownership
Calque has no tracing garbage collector. The compiler inserts reference counts,
retains, releases, and ownership transfers for managed values. Ordinary source
code has no manual free, borrow annotation, lifetime parameter, or retain.
(let xs [10 20 30])
(let alias xs)
(length alias)
xs and alias safely share one vector. It remains live until its last owning
reference is gone. When a fresh value has one known destination, optimized
code can transfer it directly rather than retain then release it again.
Reference counting cannot reclaim an ownership cycle. Calque rejects ordinary source programs that would create one, such as storing a closure in a vector when that closure captures the same vector:
(let callbacks [])
(let count-callbacks (lambda () (length callbacks)))
; Rejected: callbacks would own a closure that captures callbacks.
; (push! count-callbacks callbacks)
Logical graph cycles are still useful. Represent graph edges with IDs, enum
tags, or table keys instead of managed back-references. For reusable work
buffers, empty! releases elements while retaining a vector’s backing storage,
and capacity! reserves space before known growth:
(let work [])
(capacity! 1000 work)
; fill and consume work
(empty! work)
Read Memory management and ownership for the exact model and FFI boundary rules.
6. Functional transformations and explicit updates share one backend
Pipelines make input-to-output transformations easy to read. A hot indexed algorithm can instead make its loop order and updates obvious:
(let increment-all!
(lambda (xs)
(loop i (< i (length xs))
(set! i (+ (get i xs) 1) xs))
xs))
There is no separate functional and imperative runtime. Both forms infer
types, run through the same analysis, and lower through the same backend. The
! convention generally marks mutation or a host action; ? generally marks
a predicate. It improves readability, while types and effects remain the
authority.
Use functional transforms for a direct data story. Use loop, set!, push!,
and capacity! when they make the algorithm’s work or allocation behaviour
clearer. See Mutation and capacity and Performance guide.
7. Effects are explicit at the execution boundary
Pure computations need no permission. File access, terminal output, clocks,
randomness, and custom extern imports are recognised host effects. The
runner requires the capability explicitly:
(let source (read! "input.txt"))
(println! source)
que program.que --debug --allow read print
The program is still typed before it runs. Effects are compiler metadata used for diagnostics, permission reporting, and optimization; function arrows do not encode effects today. See Effects and permissions and FFI and host imports.
8. Checked source lowers to WebAssembly
Once a program has expanded, inferred, and been analysed, Calque optimizes the typed representation and lowers it to WebAssembly. The default runner executes that Wasm through an external WASI runtime, normally Wasmtime.
que program.que --debug
que program.que --opt
que compile program.que --opt --out program.wasm
que wat program.que
--debug keeps runtime guards for unproven vector bounds, integer arithmetic,
and division assumptions. --opt enables source and Wasm optimization and may
omit optional Calque guards. Wasm still bounds linear memory, but an unchecked
vector index is not thereby valid: a bad address that stays within linear
memory can corrupt another Calque runtime value. Validate in debug mode before
choosing optimized execution.
The repository can also pass the same Wasm through wasm2c and a C compiler
for a native executable. That is an alternative execution route, not a second
language or a different ownership model.
source → macro expansion → inferred typed program → analysis + optimization
→ WAT → Wasm → WASI runtime
└→ wasm2c + C compiler (optional native route)
For commands and release policy, see WebAssembly target and Debug, optimized, and native execution.
Keep this page as the map
When a program is surprising, follow this order:
- Forms and macros establish source structure.
- Inference assigns a coherent static shape.
- Analysis proves visible invariants and reports unknown ones.
- Ownership makes managed storage deterministic and rejects managed cycles.
- Optimization and the Wasm backend turn the checked program into executable code.
The deeper chapters define each rule. This page explains why they belong to one toolchain.
Build a file-report program
This short program reads a text file, parses one integer per non-empty line, and reports the count and sum. It demonstrates the normal Calque workflow: write direct code, run it safely, inspect facts, then use optimized execution.
Create numbers.txt:
12
14
1969
100756
Then create report.que:
; use-strict-warnings!
(let parse
(comp
split/lines
(select (lambda (line) (> (length line) 0)))
(map String->Integer)))
(let report
(lambda (text)
(let values (parse text))
{ (length values) (sum values) }))
(let input (read! "numbers.txt"))
(report input)
Run it during development with the smallest permission it needs:
que report.que --debug --allow read
; {4 102751}
If the file is absent, read! reports an ordinary host error such as
read!: numbers.txt: file not found; it is not a Calque safety trap.
Read what the compiler knows
Ask for the optimized report before treating this as a hot path:
que explain report.que --opt
The report shows the final result type, effects (the read! is host I/O), and
any bounds, arithmetic, or termination facts that were or were not proven. It
is static information, not a timing measurement.
Release run
Once representative inputs run cleanly in debug mode and the warnings have been addressed deliberately:
que report.que --opt --allow read
The pipeline is appropriate here because the transformation is a direct
data-last sequence. For a tight indexed algorithm, use a mutable vector and a
loop instead; see the grid-paths example.
Extend it
The next natural changes each introduce one Calque feature rather than a new framework:
- return an enum such as
EmptyorNumberswhen an empty file needs a distinct result; - use a
Tableto report frequencies rather than one aggregate; - add a
sigwhen this becomes a public project boundary; - put parsing helpers in
lib/parse.que, list that file inque.toml, and keepreport.queas the executable entry.
The projects chapter explains that last step.
Types
Calque infers types with Hindley–Milner inference. Most bindings need no type annotation; incompatible uses are errors before Wasm generation.
Core types
| Source type | Meaning |
|---|---|
Int | signed 32-bit integer (i32) |
Dec | fixed-point decimal backed by a scaled i32 |
Bool | true or false |
Char | a Unicode scalar value |
() | unit; nil has this type |
[T] | vector of values of type T |
{A B} | ordered tuple |
A -> B | function from A to B |
Name | a declared non-generic enum or record type |
(Name T K) | an application of a parameterized enum or record type |
Strings are [Char]. This makes string operations ordinary vector-oriented
operations at the language level; it does not mean strings are a packed
UTF-8 byte array in the current runtime representation.
The standard library also provides the generic enum (Option T) with None
and (Some value). Safe lookups use it to represent a present value or a
missing one without a sentinel value:
(match (Vector/get* 1 [10 20])
None 0
(Some value) value)
; 20
For operations that need to report why they failed, use the generic
(Result T E) enum. Result/ok carries a successful T; Result/err
carries an error value E:
(let divide
(lambda (numerator denominator)
(if (= denominator 0)
(Result/err "division by zero")
(Result/ok (/ numerator denominator)))))
(match (divide 12 3)
(Result/ok value) value
(Result/err message) 0)
; 4
(let count 3) ; Int
(let ready? true) ; Bool
(let title "Calque") ; [Char]
(let pair {count title}) ; {Int [Char]}
Records
record declares a named, nominal fixed-field product type. Unlike a tuple,
a record carries its declared identity: a raw {Int Int} tuple cannot be used
where a Point is required, even if its elements have the same types.
(record Point x Int y Int)
(let origin (Point 0 0))
(Point/x origin) ; 0
(Point/y origin) ; 0
Destructure by naming the record and its fields. The compiler expands this to the generated accessors, then checks that the value really is that record:
(let (Point x y) origin)
(+ x y) ; 0
Use _ to skip a field: (let (Point x _) origin).
Use (field local-name) when the field needs a different local binding—for
example, because it would collide with a standard function:
(record Pair first Int second Int)
(let pair (Pair 3 4))
(let (Pair (first left) (second right)) pair)
(+ left right) ; 7
The declaration syntax is flat: (record Name field Type ...). It creates a
constructor named Name and a typed accessor for every field, named
Name/field. Fields may use any concrete Calque type, including strings,
vectors, tuples, other already-declared records, and functions. Records work
in vectors and functions:
(record Message title [Char] tags [[Char]] count Int)
(let message (Message "Calque" ["typed" "lisp"] 2))
(Message/title message) ; "Calque"
Constructors and accessors are ordinary first-class, curried functions. They can be assigned, partially applied, or stored in collections:
(record Point x Int y Int)
(let make Point)
(let make-x (make 4))
(let get-x Point/x)
(get-x (make-x 9)) ; 4
Parameterized records
Records can take named type parameters after their name. These are ordinary Hindley–Milner type variables: the constructor and accessors are polymorphic, while every individual record value has one concrete instantiation.
(record Pair T K first T second K)
(let number-and-name (Pair 7 "Calque"))
(Pair/first number-and-name) ; 7
(Pair/second number-and-name) ; "Calque"
In type annotations, apply the type constructor with parentheses:
(sig swap ((Pair T K) -> (Pair K T)))
(let swap
(lambda (pair)
(Pair (Pair/second pair) (Pair/first pair))))
T and K are just conventional parameter names; different names denote
different roles. A generic declaration is nominal, so (Pair Int [Char]) is
still distinct from a tuple {Int [Char]}.
A record owns its managed fields. The runtime retains vector, tuple, record, and function fields on construction when necessary and releases them when the record’s final reference is gone. Known ownership cycles involving a closure stored through a record are rejected by the same compile-time RC-cycle check used for vectors.
Records are nominal now; their future packed Vector<Record> representation
is a separate storage optimization. Do not rely on the current implementation
layout as an FFI ABI.
An individual record uses one runtime allocation: its fixed fields and the small ownership bitmap for managed fields are stored inline with its header. Boxed payload-enum values use the same compact layout. This is an internal runtime detail, not an FFI ABI guarantee.
Records serialize with their type and field names, and can be deserialized
when a sig supplies the expected record type:
(record Point x Int y Int)
(let saved (serialize (Point 3 4)))
(sig restored Point)
(let restored (deserialize saved))
The same applies to a parameterized record: provide its fully instantiated type at the deserialization boundary.
(record Pair T K first T second K)
(sig restored (Pair Int [Char]))
(let restored (deserialize "Pair{ first 3 second \"Calque\"}"))
Deserialization is strict: missing or malformed numeric fields trap instead of
silently becoming 0.
Numeric types
Int does not silently become Dec. Use the decimal operators (+., -.,
*., /.) and conversions such as Int->Dec / Dec->Int when crossing the
boundary. The suffixed comparison operators follow the same pattern: <. for
Dec, <# for Char, and so on.
Dec source literals are parsed as exact base-10 values. At runtime, a Dec
is a scaled signed i32 (scale 1000 by default and configurable with
QUE_DECIMAL_SCALE at compile time). Decimal multiplication and division use
i64 intermediates before returning to the configured fixed-point scale.
Int overflow is meaningful: in debug mode guards can trap it, and strict
analysis reports arithmetic it cannot prove safe. The /safe?, +/safe?,
*/safe?, and related predicates can establish a guarded operation.
Polymorphism
Library functions and ordinary inferred functions may be generic:
(let first-or
(lambda (fallback xs)
(if (empty? xs) fallback (car xs))))
Its shape is conceptually T -> [T] -> T: the fallback and vector element
must be the same type, but callers choose that type independently.
Use a sig when an external boundary needs a concrete type or when you want
to state the public contract explicitly. See Inference and
signatures.
Hindley–Milner inference in Calque
Calque uses Hindley–Milner-style inference: most source programs do not need annotations, yet a binding is checked consistently at every use. The implementation follows the usual Algorithm W shape—fresh type variables, constraints, unification, and generalization—while collecting constraints and solving them at binding boundaries. This gives better source locations for diagnostics than a presentation of the algorithm that only returns a type.
The small mathematical core
The notation below is useful when reading an inferred type or a compiler diagnostic:
τ ::= Int | Dec | Bool | Char | () | α
| [τ] | {τ τ} | τ -> τ | EnumName | RecordName
σ ::= ∀α₁ … αₙ. τ
Γ ⊢ e : τ
τ is a monotype, α is an unknown type variable, σ is a polymorphic type
scheme, and Γ ⊢ e : τ reads “under type environment Γ, expression e has
type τ.” Calque source prints inferred unknowns as names such as T0; the
Greek letters are only the conventional mathematical notation.
For a lambda, the parameter starts with a fresh unknown type:
Γ, x : α ⊢ body : β
─────────────────────
Γ ⊢ (lambda (x) body) : α -> β
For an application f x, the compiler creates a fresh result type β and
requires the type of f to unify with type(x) -> β. Unification recursively
matches the structure of functions, vectors, and tuples. It includes an
occurs check, so it cannot invent an infinite type such as α = [α].
At a safe let binding, the compiler quantifies the variables that are free
in the value but not free in the surrounding environment:
generalize(Γ, τ) = ∀(ftv(τ) − ftv(Γ)). τ
For example, the identity function is inferred once as ∀α. α -> α; each use
instantiates α with a fresh unknown, so one call may use Int and another
may use [Char].
(let id (lambda (x) x))
{(id 42) (id "Calque")}
; {Int [Char]}
There is no implicit numeric subtyping or promotion in these rules. Int and
Dec unify only with themselves; use an explicit conversion when crossing
that boundary.
Product, vector, and enum types
HM’s core is deliberately small. Calque extends its type grammar with the following structural and nominal types.
Vectors are homogeneous. [T] has exactly one element type. A vector
literal adds a constraint that every element has that same type:
(let scores [10 20 30]) ; [Int]
; [10 true] ; type error: Int and Bool do not unify
The same relationship is carried through vector operations:
get : [T] -> Int -> T
set! : [T] -> Int -> T -> ()
push! : [T] -> T -> ()
Tuples are ordered pairs and may be heterogeneous. {A B} means the
first field has type A and the second has type B; unification checks both
positions independently.
(let entry {"Ada" 37}) ; {[Char] Int}
Enums are nominal, closed types. An enum declaration makes every variant
belong to that one named type. Its compact runtime i32 tag does not make it
an Int at the language level. =~ requires both operands to have the same
enum type, and match checks coverage of that closed variant set. See Enums
and matching.
Records are nominal product types. A record declaration fixes both its field names and field order. The type checker never treats a tuple with the same field types as that record, which prevents accidental field-order bugs.
Mutation and the value restriction
Plain HM generalizes every suitable let. That is unsound in the presence of
mutable containers: if an empty vector were independently polymorphic at each
use, one use could store an Int and another could read it as a Bool.
Calque therefore uses a value restriction. It generalizes non-expansive bindings—such as literals, names, and lambdas—but an allocating expression such as a vector is kept monomorphic for its binding. Its element type is still inferred; it is simply shared by every later mutation.
(let xs [])
(push! 1 xs) ; fixes xs as [Int]
; (push! true xs) ; type error
mut bindings are monomorphic by design and retain one type throughout their
updates:
(mut total 0)
(alter! total (+ total 1))
; (alter! total true) ; type error
The &mut, &get, and &alter! forms are library macros over an ordinary
one-element vector cell, so they inherit the same vector constraints rather
than introducing a hidden second reference type.
Effects are tracked alongside inferred expressions as compiler metadata:
pure, mutation, host I/O, or an unknown call. They help diagnostics,
permission checking, and optimization, but they are not currently an
effect-row type system: an arrow such as Int -> Int does not encode an
effect. See Effects and permissions.
Recursion, macros, and signatures
For letrec, Calque first binds the recursive name to a fresh monomorphic
placeholder, infers its value, and then unifies the placeholder with that
value. This is why a recursive call must agree with the function being
defined. letrec is intended for self-recursive functions; mutually recursive
definitions do not have a separate forward-declaration form.
Macros expand before inference. The expanded ordinary Calque expression is what receives these HM constraints, which keeps macros syntactic rather than an untyped escape hatch.
sig writes a contract in the same type language and verifies the inferred
binding against it. It is useful for public APIs and for boundaries such as
deserialize, where the desired result type cannot be recovered from the
serialized text alone. See Inference and signatures for
the syntax and diagnostics.
Bindings and scope
Immutable and mutable locals
let binds an ordinary lexical name. A let binding cannot be reassigned.
(let greeting "hello")
(let answer (+ 40 2))
mut declares a mutable local. Update it with alter!, +=, ++, and the
other mutation helpers:
(mut total 0)
(alter! total (+ total 10))
(+= total 20)
(++ total)
total ; 31
alter! takes a value, not a callback. It is equivalent in spirit to
assignment after the new expression has been evaluated.
Destructuring
Tuple and vector patterns can bind components directly:
(let {name age} {"Ada" 37})
(let [first second] [10 20])
Vector destructuring has the usual shape constraint: a fixed pattern such as
[a b] requires the vector to contain those elements. The analyser
may warn when it cannot prove that fact. A final . rest binding works in
both let and lambda vector patterns:
(let [a b . rest] [10 20 30 40])
a ; 10
b ; 20
rest ; [30 40]
(let get-head (lambda ([x . xs]) x))
The names before . bind fixed positions. rest is the same tail window as
(cdr fixed-position-count vector): it begins after those positions without
initially copying the remaining values. It materializes independently if you
mutate it. The rest pattern must be final and can bind one name only.
Scope
Names are lexical. A binding introduced by block is not visible after that
block:
(let label
(if true
(block (let value "yes") value)
(block (let value "no") value)))
do sequences values but does not make a lexical scope. This distinction
matters in branches and loops: prefer block for branch-local temporary
bindings.
Reference cells
&mut, &get, and &alter! are macros for an explicit mutable cell. They
are useful when a closure must update state that outlives a single local scope:
(&mut counter 0)
(let next!
(lambda ()
(&alter! counter (+ (&get counter) 1))))
(next!) ; 1
(next!) ; 2
They preserve the compiler’s normal mutation analysis; they are source-level convenience forms, not an untyped escape hatch.
Functions and recursion
Lambdas and calls
Use lambda to build a function. Parameters can be written as one name or a
group:
(let square (lambda (x) (* x x)))
(let add (lambda (left right) (+ left right)))
(square 9)
(add 20 22)
Multiple forms in a lambda body are evaluated in order; its final form is the return value.
(let magnitude
(lambda (x)
(let value (if (< x 0) (- 0 x) x))
value))
Functions are first class and lexical closures capture the bindings they use.
Calls support partial application, so (map square) is a function waiting for
its vector argument.
Recursive bindings
Use letrec when the binding calls itself:
(letrec factorial
(lambda (n)
(if (<= n 1)
1
(* n (factorial (- n 1))))))
Recursion is intentionally explicit. A let binding cannot refer to itself;
this avoids accidental forward references and makes recursive intent obvious.
The current type system does not permit arbitrary mutually recursive
definitions through forward references.
Tail calls and loops
Write direct loops for work that is naturally iterative. Calque recognizes and
optimizes important tail-recursive shapes, but a loop / while makes the
space behavior explicit and maps directly to Wasm control flow.
(let factorial
(lambda (n)
(mut result 1)
(loop i (<= i n)
(alter! result (* result i)))
result))
Use que explain program.que --opt to see whether the analyser proved a
recursive function or loop terminating, and use the generated output when
investigating performance.
Control flow
All control forms are expressions.
if, cond, and when
(if (> score 0) "positive" "not positive")
(cond
(< score 0) "negative"
(= score 0) "zero"
"positive")
(when ready?
(println! "go"))
(unless ready?
(println! "wait"))
cond tests each condition in order. Its last unpaired expression is the
default branch. when, when-not, and unless are bundled macros. when
and when-not are for effects: their implicit false branch is nil, so use
if or cond when both branches must produce a useful value.
while and loop
while runs while its condition is true. The counter-style loop macro
introduces and updates its named counter for you:
(mut i 0)
(while (< i 3)
(println! (Integer->String i))
(++ i))
(loop i (< i 3)
(println! (Integer->String i)))
println! has type [Char] -> (): convert an Int with
Integer->String, or build text with functions such as join.
There are library macros for common forms:
(loop/for i 1 (<= i 10) (++ i) (println! (Integer->String i)))
(loop/in value [10 20 30] (println! (Integer->String value)))
(loop/in/i index value [10 20]
(println! (join ":" [(Integer->String index) (Integer->String value)])))
(times 3 (println! "tick"))
The correctness analyser recognizes many counter loops and can show the
initial value, condition, update, and exit bound in que explain. It is
conservative: “unknown” means it did not establish a proof, not that the loop
is definitely infinite.
block and do
Use block when a control-flow branch needs its own bindings. Use do only
when you need explicit sequencing without a new scope.
Vectors, tuples, strings, and characters
Vectors
Vectors are homogeneous mutable collections written with square brackets:
(let xs [10 20 30])
(get 1 xs) ; 20
(set! 1 99 xs)
(push! 40 xs)
(pop! xs)
The basic operations are:
| Form | Meaning |
|---|---|
(length xs) | number of elements |
(get i xs) | element at index i |
(set! i value xs) | replace an existing element, or append at length |
(push! value xs) | append |
(pop! xs) | remove the final element |
(pop-val! xs) | remove and return the final element |
(empty! xs) | set length to zero while retaining allocated capacity |
(car xs) | first element; equivalent to (get 0 xs) |
(cdr xs), (cdr n xs) | tail window from offset 1 or explicit offset n |
get is guarded in debug mode when the compiler cannot prove the access safe.
Optimized code relies on the established invariant, so write an explicit guard
or structure the loop so that the proof is obvious:
(loop i (< i (length xs))
(println! (get i xs)))
cdr initially shares the source vector’s backing storage and shifts the
logical start index; it does not copy every tail. Mutating that result
materializes an independent vector, so it cannot change the original. See
Functions by example
for a complete example and the retention trade-off.
Tuples
Tuples are fixed-size heterogeneous values:
(let person {"Ada" 37 true})
(fst person) ; "Ada"
(snd person) ; 37
(let {name age active?} person)
Use tuples for a small fixed record-like value. A tuple has positional fields; names in a destructuring pattern are local variable names, not stored field names.
Strings and characters
Strings are sequences of Char values, so their language type is [Char]:
(let title "Calque")
(get 0 title) ; 'Q'
(length title) ; 3
(cons "Hello, " title)
Character literals use single quotes. Use =#, <#, +#, and related
operators for character arithmetic and comparison; use Char->Int and
Int->Char when deliberately converting code points.
The bundled library provides split, split/lines, join, trim, slice,
String->Integer, Integer->String, String/contains?, String/starts?,
and other text functions. Their exact signatures are available through:
que --lib types 'String/*'
que --lib types 'split*'
Enums and matching
An enum declares a closed set of variants. A zero-payload enum is the most
compact form:
(enum Shape Rock Paper Scissors)
Rock, Paper, and Scissors have type Shape; they are not Int values
even though the compiler represents them compactly as i32 tags at runtime.
That separation prevents mixing unrelated domains by accident.
If names would collide, choose qualified ordinary identifiers yourself:
(enum Traffic Traffic/Red Traffic/Amber Traffic/Green)
Compare enum values
Use =~ for enum equality:
(=~ Rock Paper) ; false
(=~ Rock Rock) ; true
Both operands must have the same enum type. =~ Rock 1 and comparison between
values from two distinct enums are type errors. Ordinary = remains the
integer equality operator; this deliberate distinction stops an enum tag from
silently becoming an arbitrary number.
Exhaustive match
match is for enum dispatch. It requires every variant, unless the final
branch is _:
(let score
(lambda (shape)
(match shape
Rock 1
Paper 2
Scissors 3)))
(let describe
(lambda (shape)
(match shape
Rock "rock"
_ "another shape")))
The match expression is checked statically. Adding a variant to a fully matched enum exposes every site that must decide how to handle it.
Enums in functions and Tables
Enum values flow through ordinary variables and functions:
(let winner?
(lambda ({left right})
(or (and (=~ left Rock) (=~ right Scissors))
(and (=~ left Paper) (=~ right Rock))
(and (=~ left Scissors) (=~ right Paper)))))
They are also efficient Table keys. Their compact tags are hashed and
compared directly—there is no conversion to a string:
(sig points [[{ Shape Int }]])
(let points (Table/new))
(Table/set! Rock 1 points)
(Table/set! Paper 2 points)
Payload and recursive variants
A parenthesized variant declares named payload fields. This is how to model trees, linked values, ASTs, and other recursive data:
(enum Tree
Empty
(Node value Int left Tree right Tree))
(let tree (Node 4 (Node 2 Empty Empty) (Node 7 Empty Empty)))
(letrec size
(lambda (tree)
(match tree
Empty 0
(Node value left right)
(+ 1 (+ (size left) (size right))))))
(size tree) ; 3
The payload binding count must match the variant declaration. Payload enums
are boxed and reference-counted; plain zero-payload enums remain immediate
i32 tags. Recursive types are therefore fine, but managed ownership
cycles are not: a tree may own its children, while a cycle such as a → b → a
is rejected by Calque’s RC-cycle checks.
=~ remains useful for zero-payload state enums. It is not structural payload
equality; use match to inspect a payload variant.
Parameterized enums
Payload enums can also take type parameters. This makes the type relationship between a payload and its enclosing variant explicit without giving up exhaustive matching. The standard library defines this common type already:
(let read-or
(lambda (fallback option)
(match option
None fallback
(Some value) value)))
{(read-or 0 (Some 4))
(read-or "none" (Some "Calque"))}
; {4 "Calque"}
Use the applied form in annotations: (Option Int), (Option [Char]), or a
generic relationship such as (Option T). Recursive generic enums work the
same way:
(enum Tree T
Empty
(Node value T left (Tree T) right (Tree T)))
Every use chooses one payload type. (Some 1) and (Some "one") can coexist
in a program, but they have different types: (Option Int) and
(Option [Char]).
Typed choices without overloads
Parameterized enums are also useful when an API needs a choice that must stay connected to the type of another argument. Calque functions are not overloaded by argument type: one function has one type. Put the type-dependent operation in a generic enum instead.
For example, an ordering could use a parameterized enum to choose ascending or descending behaviour:
(enum SortOrder T
(Asc compare (T -> T -> Bool))
(Desc compare (T -> T -> Bool)))
(sig sort-with-direction ((SortOrder T) -> [T] -> [T]))
(let sort-with-direction
(lambda (order values)
(match order
(Asc compare) (sort compare values)
(Desc compare) (sort compare values))))
(sig Asc/Int (SortOrder Int))
(let Asc/Int (Asc <))
(sig Desc/Int (SortOrder Int))
(let Desc/Int (Desc >))
(sig Asc/Dec (SortOrder Dec))
(let Asc/Dec (Asc <.))
(sort-with-direction Asc/Int [3 1 2])
; [1 2 3]
(sort-with-direction Desc/Int [3 1 2])
; [3 2 1]
(sort-with-direction Asc/Dec [3.2 1.1 2.4])
; [1.1 2.4 3.2]
sort-with-direction is one polymorphic function, not separate Int and Dec overloads.
The signature ties the T inside (SortOrder T) to the element type of
[T], so (sort-with-direction Asc/Int [1.2 2.4]) is a type error. The named values
Asc/Int and Asc/Dec are ordinary bindings; an enum variant name does not
need to encode the concrete type.
Payload enums are also valid Table keys. Their tag and fields are hashed and
compared structurally, including nested payload enums, vectors, tuples, and
records:
(let table (Table/new))
(Table/set! (Node 1 Empty Empty) "stored" table)
(Table/get (Node 1 Empty Empty) table)
The same rule applies to a payload such as (Named ["calque" "lisp"]): a
separately allocated value with the same nested text is the same key. Tuples
and records can also be used directly as structural Table keys.
Like existing [Char] keys, do not mutate a managed value after using it as a
key: changing its contents can change its hash and make it unreachable in the
table.
Serialize payload enums
Payload enums use an explicit, readable recursive format. serialize writes
the enum type, variant, and each field; deserialize validates that exact
shape against the concrete type supplied by sig:
(enum Tree T Empty (Node value T left (Tree T) right (Tree T)))
(let saved (serialize (Node 4 Empty Empty)))
; Tree{ Node 4 Tree{ Empty } Tree{ Empty } }
(sig restored (Tree Int))
(let restored (deserialize saved))
Malformed text, an unknown variant, or a missing field is an error. Recursive payloads are decoded recursively, so this format also round-trips ordinary trees and ASTs without a separate schema.
match/string remains available for the older string-dispatch macro use case.
Mutation and capacity
Mutation is explicit in both spelling and type/effect analysis. Use it for local counters, in-place algorithms, and predictable allocation behavior.
Locals and vectors
(mut total 0)
(loop i (< i 10)
(+= total i))
(let xs [])
(push! total xs)
(set! 0 42 xs)
The caller-visible mutable value of a function is normally its final parameter. This keeps mutation APIs pipeline-friendly:
(let fill-zeroes!
(lambda (xs)
(loop i (< i (length xs))
(set! i 0 xs))
xs))
Reserving vector storage
capacity! reserves backing storage without changing a vector’s length:
(let paths [])
(capacity! 1000 paths)
(loop i (< i 1000)
(push! i paths))
It is useful before a known burst of appends. It returns unit, deliberately:
the vector itself remains the same mutable value. empty! similarly resets
the vector’s length while retaining storage for reuse.
(empty! paths)
; paths can be refilled without reallocating until it grows past capacity
capacity! is a reservation, not a maximum length. Appending more than the
requested capacity remains valid and grows the vector as needed.
Safe, fast code
For debug builds, Calque can trap unproven bad indices and checked arithmetic.
For optimized builds, organize loops so que explain can see basic facts such
as 0 <= i < length(xs). This lets the compiler remove checks where safe,
while the source retains its clear invariant.
Memory management and ownership
Calque has no tracing garbage collector. Managed values use runtime reference
counting: the compiler inserts retains, releases, and ownership transfers for
you. There is no free, borrow annotation, lifetime syntax, or manual retain
operation in ordinary Calque source.
This is designed to make memory behavior predictable: when the final live reference to a managed value is released, its storage can be reclaimed immediately by the runtime allocator. The optimizer can also transfer a fresh value directly to its final owner, or release a value after its last use, which avoids needless retain/release traffic.
What is managed
Int, Dec, Bool, Char, unit, and zero-payload enum tags are immediate i32 values. Payload enums are boxed managed values.
They do not allocate and do not participate in reference counting.
Vectors, strings ([Char]), tuples containing managed values, and closures
are managed heap values. The rule is implementation detail, not an operation
you normally need to write around:
(let title "Calque") ; a managed character vector
(let pair {title [1 2 3]}) ; managed tuple containing managed vectors
(let prefix (lambda (x) ; managed closure: it captures title
(cons title x)))
(prefix " is typed")
Aliasing is safe. If two bindings refer to the same vector, it remains alive until neither binding (nor any live container or closure) owns it:
(let xs [1 2 3])
(let also-xs xs)
(length also-xs)
You should write the direct program. Calque determines when a retain is needed, when a value can be moved instead, and when it can be released.
Why cycles are forbidden
Reference counting alone cannot reclaim a cycle. If a vector owns a closure and that closure captures the same vector, both counts can remain nonzero even after the surrounding program has stopped referring to either one.
Calque therefore rejects source-level operations that would form a managed reference cycle. This program is rejected at compile time:
(let callbacks [])
(let report-size
(lambda ()
(length callbacks)))
; Error: report-size captures callbacks, then is stored in callbacks.
(push! report-size callbacks)
The same protection applies to direct set! and recognised container
mutators—such as table, set, heap, and deque operations—and also follows a
simple wrapper function that stores one of its arguments into another. The
diagnostic identifies the storing operation and the captured managed root.
Capturing a collection is fine by itself. It is the back-edge—putting that capturing closure into the collection it captures—that is not allowed:
(let xs [1 2 3])
(let size
(lambda ()
(length xs)))
(size)
; 3 — no cycle: xs does not own size.
This restriction is intentional. Calque does not promise a cycle collector as a fallback, because that would lose deterministic reclamation and introduce a second memory-management model.
Model graphs with IDs, not object back-edges
Cycles in the data you model are perfectly valid. Represent graph edges with integers, strings, enum tags, or table keys rather than managed pointers or closures that refer back to their owner:
; Node id -> ids of outgoing neighbours.
(let edges (Table/new))
(Table/set! 0 [1 2] edges)
(Table/set! 1 [2] edges)
(Table/set! 2 [0] edges)
That graph has a logical cycle (0 → 1 → 2 → 0), but its values do not own one
another. It is ordinary acyclic runtime storage and works with the graph
helpers in the standard library.
For parent links, caches, registries, or callback dispatch, use an ID or a key into an owner table instead of storing a closure back into the structure that closure captures.
Mutation, capacity, and observable memory
empty! removes vector elements. If those elements are managed, their owned
references are released; the vector’s backing allocation is retained for
reuse. capacity! reserves backing storage and compact! rebuilds a vector
with only the storage required by its current length:
(let work [])
(capacity! 1000 work)
; fill and process work
(empty! work) ; elements are released; reserved storage stays reusable
(compact! work) ; discard unused backing capacity
Releasing an object returns it to Calque’s allocator. It does not guarantee that a WebAssembly runtime immediately returns linear-memory pages to the operating system, so RSS may remain high after a temporary peak. The important semantic guarantee is that unreachable managed objects do not remain live; their storage is available for reuse without a tracing-GC pause.
Performance and external hosts
Reference counting has a cost when a managed value is shared. Calque’s
optimizer removes redundant retain/release pairs, transfers ownership of fresh
values, and specializes known vector paths where it can. Use que explain program.que --opt when investigating retained/released work in a hot path.
--debug and --opt use the same ownership semantics. Debug mode adds safety
guards; optimized mode may remove proven-safe checks and redundant ownership
traffic, but it never makes cycles valid.
The rule also matters at FFI boundaries. A custom Wasm host that constructs or retains Calque-managed values must obey the runtime ownership convention. Do not use a host import to manufacture a cyclic Calque object; it bypasses the source-level proof that keeps ordinary programs cycle-free. See FFI and host imports for the ABI boundary.
Performance guide
Calque is designed so ordinary, direct source can compile efficiently. Start
with clear code, establish its invariants in --debug, inspect the optimized
shape with que explain, and measure the complete program. Do not optimize
from source appearance alone.
que program.que --debug
que explain program.que --opt
que program.que --opt
que explain reports static generated-code facts—such as remaining
allocations, direct calls, and checked or unchecked reads. It is not a timing
profiler. Use a repeatable wall-clock benchmark for timing decisions.
Choose the simplest fitting shape
| Situation | Prefer |
|---|---|
| One clear collection transformation | ` |
| Reusable transformation with no meaningful input name | comp |
| Tight numeric or indexed work | loop / while and explicit mutable state |
| A known burst of appends | capacity! before push! |
| Reusing a temporary vector | empty!, retaining its capacity |
| A completed compute-heavy program | the repository wasm2c/native-C path, after measuring |
Functional collection code is not automatically slow. The optimizer can fuse supported chains of collection operations, avoiding intermediate vectors. Keep the natural pipeline first:
(let sum-positive-squares
(lambda (xs)
(|> xs
(select (lambda (n) (> n 0)))
(map (lambda (n) (* n n)))
sum)))
Then use que explain program.que --opt to see whether the generated shape
still contains avoidable allocations. An opaque callback, escaping collection,
or operation with different semantics may correctly prevent fusion.
Allocate deliberately
Vectors grow when necessary, but a vector that repeatedly grows must allocate and copy backing storage. Reserve once when the eventual append count is known:
(let squares [])
(capacity! 1000 squares)
(loop i (< i 1000)
(push! (* i i) squares))
capacity! is only a reservation: it does not set the length or impose a
maximum. If the same scratch vector is refilled many times, empty! resets
its length while keeping that capacity.
For a table with an approximate number of entries, use Table/new/capacity.
This avoids repeated hash-table resizing; it does not change table semantics.
Make proofs visible
The analyser and optimizer work from source-level facts. A counted loop makes both the access invariant and the intended work clear:
(let total 0)
(loop i (< i (length xs))
(alter! total (+ total (get i xs))))
Here the compiler can establish 0 <= i < length(xs). In optimized output it
can use that proof to remove the corresponding bounds check. If an invariant
comes from input validation or another source the analyser cannot see, state it
as a guard rather than assuming --opt will discover it:
(if (and (>= index 0) (< index (length xs)))
(get index xs)
fallback)
Likewise, use arithmetic safety predicates when a calculation reaches the
edge of Int’s signed i32 range:
(if (+/safe? left right)
(+ left right)
fallback)
Keep ownership simple
Vectors, tuples, strings, and closures use deterministic reference counting. The compiler can transfer a fresh value, borrow an immutable value, and remove some final-use retains/releases. It has the most freedom when a value has an obvious owner and does not escape through an unknown callback or mutable alias.
This is a reason to write direct expressions rather than manually simulating memory management. There is no source-level retain/release operation to call. See Memory management and ownership for the model and its no-cycle rule.
Recursion and loops
Use a loop when the algorithm is naturally iterative. Direct self tail calls that meet the current tail-call safety policy are lowered to a Wasm local loop in optimized builds, so they also work through wasm2c. Non-tail recursion, such as naive Fibonacci, still consumes one frame per outstanding call and cannot be converted into a loop without changing the algorithm.
(letrec count-down
(lambda (n total)
(if (= n 0)
total
(count-down (- n 1) (+ total 1)))))
Use que explain program.que --opt and a real benchmark before choosing
between the recursive and loop forms.
Select an execution path after measuring
The ordinary command uses an external WASI runtime, normally Wasmtime:
que program.que --opt
For a completed compute-heavy program, the repository can lower the same Wasm through wasm2c and a C compiler:
./scripts/compile-native-c.sh program.que
The source language and correctness pipeline are the same in both cases. The best path depends on startup cost, workload length, host compiler, and runtime; benchmark the exact deployment shape rather than assuming native C always wins.
Pipelines and composition
Most functional library APIs take their data argument last. That makes a pipeline read from input to result:
(|> [1 2 3 4 5]
(select (lambda (x) (> x 2)))
(map (lambda (x) (* x x)))
sum)
; 50
|> inserts the value on its left as the final argument of each following
form. The reverse pipeline <| inserts it as the first argument instead.
(let parse-ids
(comp
trim
split/lines
(map String->Integer)))
(parse-ids "1\n2\n3")
comp builds a left-to-right data-last pipeline: the first listed function
receives the input first. Pipelines are often more readable for a one-off
transformation because they keep the data visible.
Point-free definitions
When the input is only passed from one transformation to the next, a named
parameter adds no information. comp lets you define that function without
spelling the parameter: this is point-free style.
; Explicit input and pipeline.
(let parse-ids
(lambda (input)
(|> input
trim
split/lines
(map String->Integer))))
; The same function, point-free.
(let parse-ids
(comp
trim
split/lines
(map String->Integer)))
The stages still run left to right. A bare name is a stage such as trim; a
form such as (map String->Integer) supplies its non-data arguments first and
receives the composed input last. Therefore the definition above behaves like:
(lambda (input)
(map String->Integer (split/lines (trim input))))
This is especially useful for parsers and reusable collection transforms:
(let positive-squares
(comp
(select (lambda (n) (> n 0)))
(map (lambda (n) (* n n)))))
(positive-squares [-2 -1 0 1 2])
; [1 4]
Use comp when it makes the flow clearer. When a step needs to name an
intermediate value, branch, or perform several effects, an ordinary lambda
and |> are usually easier to read.
apply is a source-level macro that splices the written argument forms into a
call. It is useful when another macro is constructing a call; it does not
unpack a runtime vector:
(apply + 20 22) ; expands to (+ 20 22), therefore 42
|>, <|, comp, and apply are bundled macros. They expand before
inference and code generation, so they do not add a dynamic dispatch cost.
Extremely long pipeline expansions are intentionally bounded to keep macro
expansion predictable; normal pipelines are unaffected.
Macros
Macros transform syntax before the program is inferred and compiled. They are
written in Calque using letmacro, quasiquote (qq), unquote (uq), and
unquote-splice (uqs).
(letmacro unless
((test body)
(qq (if (uq test) nil (uq body)))))
(unless (= 1 2)
(println! "runs"))
Macros are appropriate when you need new surface syntax or want to generate a repeated structural pattern. They are not ordinary runtime functions: they receive syntax, not evaluated values.
Bundled macros
The bundled library implements many familiar forms as macros, including:
when,when-not,unless,cond,!=,<>|>,<|,comp,applyloop,loop/for,loop/in,loop/in/i, range-loop helpers,timeslet*,+=,-=,*=,/=,++,--- Decimal compound assignment:
+=.,-=.,*=.,/=. &mut,&get,&alter!,variablematch/string
Use que <file> --emit source to inspect expanded source and understand what
a macro call becomes. Formatter, LSP, and diagnostics preserve source
locations where possible, but macro-generated code can still make a complex
error easier to understand after looking at that expansion.
The decimal forms mirror the integer ones while preserving fixed-point Dec
arithmetic. They are intentionally compound assignments rather than a decimal
++. shorthand:
(mut opacity 0.25)
(+=. opacity 0.10)
(*=. opacity 2.0)
opacity
; 0.7
Macro discipline
Prefer a function when values are enough. Prefer a macro when the caller needs new binding structure, control flow, or syntactic rearrangement. Keep macro expansions small, hygienic in spirit, and transparent enough that the expanded form remains ordinary, type-checkable Calque.
Writing a macro
A macro transformer receives the written syntax at its call site and must return replacement syntax. The smallest form uses a lambda transformer and quasiquote:
(letmacro add1
(lambda (x)
(qq (+ (uq x) 1))))
(add1 41)
; expands to: (+ 41 1)
; 42
qq constructs the output program. Inside it, ordinary words and lists are
literal output syntax. (uq x) inserts the single syntax form supplied as
x; it does not evaluate that form. In the example, (add1 (+ 20 21))
becomes (+ (+ 20 21) 1), then normal type checking and evaluation happen.
Macros can also use pattern clauses. This version of unless accepts zero or
more body forms, and uses uqs to splice all of them into the generated
do:
(letmacro unless*
(()
(qq nil))
((test . body)
(qq (if (uq test) nil (do (uqs body))))))
(mut total 0)
(unless* false
(++ total)
(++ total))
total
; 2
Use uq for one expression and uqs only where a surrounding list or body
accepts several forms. The rest pattern . body is syntax-list rest capture;
it is not a runtime vector value.
Generated bindings and gensym
If a macro introduces a local name, create it with gensym. It produces a
fresh identifier, avoiding accidental capture of a caller’s name. This macro
evaluates its input once, then reads its final element:
(letmacro last-item
(lambda (xs)
(do
(let values (gensym))
(qq
(block
(let (uq values) (uq xs))
(get (- (length (uq values)) 1) (uq values)))))))
(last-item [10 20 30])
; 30
The generated values cannot collide with a caller’s values binding. Like
car, this macro requires a non-empty vector; macros preserve the ordinary
runtime and static-safety rules of the forms they expand to.
Syntax-time helpers
For macros that inspect or rebuild an arbitrary syntax list, use the
syntax-only helpers syntax/list?, syntax/empty?, syntax/head,
syntax/tail, syntax/prepend, syntax/append, syntax/word?, and
syntax/word=?. They are available only while a letmacro expands; they are
not runtime data-structure functions. The implementation of |> in the
bundled library is the reference example of this more advanced style.
Debugging an expansion
Define a macro before its use, keep its expansion small, and inspect what the compiler will receive when a type error is unclear:
que program.que --emit source
The result is expanded Calque source. It is particularly useful for checking
uq versus uqs, generated bindings, and a macro that introduces control
flow. The expanded result must still type-check like handwritten Calque.
Inference and signatures
Calque infers types for ordinary bindings and generalizes them where valid. Start without annotations:
(let id (lambda (x) x))
(let pair-with (lambda (left right) {left right}))
The compiler rejects inconsistent uses before code generation.
sig
Use sig immediately before a binding when the program crosses a boundary
whose type cannot be inferred from ordinary use, or when you want to state the
binding’s contract:
(sig parse/int! ([Char] -> Int))
(let parse/int! (lambda (text) (deserialize text)))
deserialize is the important practical example: serialized characters do not
contain enough static information for the compiler to know which decoder to
generate. The signature supplies the expected result type.
(enum Shape Rock Paper Scissors)
(sig restored [[{ Shape Int }]])
(let restored (deserialize saved))
The type above is the physical representation of a Table in the current
library: a vector of buckets, each containing {key value} entries. Programs
normally use Table/new, Table/set!, and Table/get; the representation only
needs to be written at a serialization boundary.
Function type syntax
(sig increment (Int -> Int))
(sig compare (Int -> Int -> Bool))
(sig map-int ((Int -> Int) -> [Int] -> [Int]))
An arrow chain associates to the right. Parenthesize a function when it is an argument type.
Named generic roles are rigid
Inside a sig, a named type variable is a role in the contract, not a
placeholder that the implementation may silently specialize. Repeated names
must remain the same type; different names must remain different roles.
(sig wrap (T -> [T]))
(let wrap (lambda (x) [x])) ; valid
(sig broken (T -> [T]))
(let broken (lambda (x) [3])) ; error: T was forced to Int
Likewise, the order of generic roles matters:
(sig pair (T -> K -> [{ T K }]))
(let pair (lambda (left right) [{right left}])) ; error
Use _ for an intentionally unconstrained slot. Every _ is a new flexible
wildcard, unlike a repeated named role:
(sig keep-left (T -> _ -> T))
(let keep-left (lambda (x ignored) x))
Inspect inferred types
que program.que --emit types
que explain program.que
The LSP also exposes inferred types in hover information. Use a sig to make
an intended public type visible and enforced, not merely to silence inference.
Correctness analysis
The type checker catches incompatible values. Calque’s static analyser adds conservative warnings about runtime properties that types alone cannot prove.
Enable strict warnings in a source file:
; use-strict-warnings!
For a compact message-to-fix table, see Warnings and proof recipes.
Or inspect a full report:
que explain program.que --opt
que explain program.que --opt --json
The report groups warnings before termination, effects and permissions, performance observations, and generated-code details.
Reading que explain
que explain is the programmer-facing view of the typed program, static
proofs, and generated WAT shape. It does not run the program or benchmark it.
Use --opt when you want its generated-code and performance observations to
describe the optimized build you intend to run:
que explain program.que --opt
que explain program.que --opt --json --out explain.json
The text report has these sections:
| Section | What it tells you |
|---|---|
| Result type | The inferred type of the final user expression. |
| Correctness | Static arithmetic/bounds warnings, source locations, suggestions, and successful bounds proofs. |
| Termination | A proven or unknown result for analysed loops and recursive functions, including the inferred measure when available. |
| Effects and permissions | The combined effect (pure, mutation, host I/O, or unknown call) and required host imports. |
| Performance | A static count of allocations, dynamic applies, checked/unchecked reads, direct calls, and WAT bytes. |
| Generated code | Per-function allocation and call details, plus inferred source-form types and effects. |
For a safe counted access, the useful part looks conceptually like this:
Correctness:
Proven bounds:
(get i xs) proven safe
0 <= i <= 9
Termination:
proven terminating: while (< i (length xs))
i increases toward the exit bound
The report’s performance section is deliberately static WAT shape, not a runtime profile. It can identify a remaining allocation or bounds check and point toward a useful rewrite, but timing, CPU effects, and allocator behavior still require a real benchmark.
--json contains the same information in stable fields such as
result_type, warnings, bounds_proofs, termination, effect,
host_imports, metrics, compiled_functions, and optimization_targets.
That form is intended for editor integrations, CI, and custom reporting.
The analysis model
Type inference answers questions such as “is this value an Int or a
[Char]?” It cannot answer “can this Int overflow?” or “is this index below
this particular vector’s length?” Calque runs a second, flow-sensitive static
analysis after type inference for those questions.
It is an abstract interpreter: it executes a finite mathematical summary of the program rather than executing its concrete values. A useful simplified view of the state at a program point is:
S = (R, L, A, P)
R(x) = [lower, upper] possible Int range for x
L(xs) = n or >= n known exact or minimum vector length
A symbolic affine relations, such as i < length(xs)
P path facts, aliases, and recognised guard summaries
For example, on the true path of this condition the analyser refines the
abstract state to include both facts needed by get:
(if (and (>= i 0) (< i (length xs)))
(get i xs)
fallback)
true path: 0 <= i < length(xs)
therefore: (get i xs) is proven safe
It keeps bounded alternatives when useful—for example, a value known to be
negative or positive rather than merely “some Int”—and tracks simple
affine relations such as a + b <= 2147483647. Arithmetic ranges are
calculated in a wider analysis domain, then checked against the signed i32
range used by Int.
Control flow and loops
The analyser refines facts independently along each branch. Where paths meet, it retains only facts that remain valid on every incoming path. Informally:
after (if condition left right) = join(state(left), state(right))
Loops require a fixed point: the body is analysed repeatedly until its summary stops gaining useful facts. Widening deliberately broadens a changing range when necessary so this process always finishes. That is why Calque can prove common counted loops without attempting to solve the halting problem.
(loop i (< i (length xs))
(get i xs))
The loop supplies an initial value, condition, and update. The analysis derives
0 <= i < length(xs) for the body, proves the read safe, and can record the
counter as moving toward its exit bound.
Proof outcomes
Each checked operation has one of three outcomes:
| Result | Meaning |
|---|---|
| proven safe | Every abstract execution reaching the operation satisfies the required fact. |
| definitely invalid | Every possible execution violates it, such as a known negative index. |
| unknown | The analysis cannot establish either conclusion with its conservative model. |
Only a proven-safe fact is eligible for an optimization such as omitting a
runtime bounds check. unknown is intentionally not a claim that the program
fails; write a guard, simplify the shape, or keep the check if the invariant
lives outside the visible source.
The same model supports several analyses:
- bounds and non-empty vectors —
get,set!,car, andpop-val!; - arithmetic —
+,-,*,/, and%, including a non-zero divisor and the specialminimum Int / -1overflow case; - termination evidence — counted loops and recursive calls whose argument is shown to move toward a base-case guard;
- effects — mutation, host I/O, and calls whose effect cannot yet be resolved.
Recognised helper predicates can carry proof information too. A conventional
definition such as in-bounds? can establish a later get when its true
branch is taken, and +/safe? can establish the corresponding guarded
addition. The analyser is conservative about aliases and mutation: once a
fact may have been invalidated, it stops relying on it.
Bounds and empty vectors
The analyser recognizes common loop shapes:
(loop i (< i (length xs))
(get i xs))
Here it can establish 0 <= i < length(xs). If it cannot prove an access, it
reports the source expression and suggests a guard such as:
(and (>= index 0) (< index (length xs)))
It also reports calls such as pop!, pop-val!, and car when the vector may
be empty. A warning is not necessarily a bug: it says a proof was unavailable.
Arithmetic
Int is signed i32. The analyser tracks ranges where it can and warns about
possible overflow, underflow, division by zero, and unsafe squares. Use the
matching predicate in a value-producing if:
(if (+/safe? left right)
(+ left right)
fallback)
when is for effect-only bodies: its false branch is nil, so its body must
also produce nil. It is appropriate when the guarded operation is a mutation:
(when (+/safe? total amount)
(alter! total (+ total amount)))
Debug execution additionally inserts runtime guards for configured checks;
optimized execution assumes the program’s invariants. For this reason, first
use --debug, address real warnings, then benchmark with --opt.
Termination
Counter loops and many recursive calls have an inferred measure. For example,
a counter initialized at zero, tested against a bound, and incremented toward
that bound can be reported as proven terminating. Recursive code may be
reported as unknown when the analyser cannot identify a decreasing measure.
That result is intentionally conservative, not a claim of non-termination.
Avoid writing a “fake” base case that does not actually guard the recursive call; the analyser follows control flow rather than just looking for a test.
Warnings and proof recipes
Warnings are conservative: they mean Calque could not prove a required fact
from the source it can see. They are neither ignored type errors nor proof that
the program fails. Start with --debug and inspect the full explanation when
needed:
que program.que --debug
que explain program.que --opt
Put ; use-strict-warnings! at the top of a source file to surface these
findings in editor diagnostics.
| Finding | Meaning | Usual source-level proof or fix |
|---|---|---|
index not proven safe | An index may be negative or beyond vector length. | Guard with in-bounds?, or use a counted loop whose condition includes (length xs). |
vector may be empty | car, pop-val!, or a similar operation may see no elements. | Check (> (length xs) 0), use a safe library variant, or restructure the branch. |
Int overflow/underflow possible | Signed i32 arithmetic is not proven in range. | Use +/safe?, -/safe?, or */safe? with a value-producing if; constrain the range. |
division by zero possible | A divisor may be zero. | Guard the divisor before / or %. |
termination: unknown | The analyser did not infer a decreasing measure. | Make the base-case guard control the recursive call; use an explicit counter loop when that is clearer. |
unknown-call | A function value is called indirectly and its behavior cannot be resolved. | It is valid code. Prefer a known direct helper only when that genuinely improves clarity or hot-path optimization. |
| RC cycle rejection | A managed collection would own a closure that captures the same collection. | Store IDs/indexes instead of owning back-edges; see memory. |
| permission error | A host operation lacks an allowed WASI capability. | Grant the narrow matching --allow group, for example --allow read. |
Bounds
The canonical dynamic guard is:
(if (and (>= index 0) (< index (length xs)))
(get index xs)
fallback)
For loops, keep the relationship visible rather than calculating an unrelated upper bound elsewhere:
(loop i (< i (length xs))
(get i xs))
Arithmetic
Safety predicates prove the corresponding operation only in their true path.
Use if or cond when the expression must produce a value:
(if (+/safe? left right)
(+ left right)
fallback)
Use when only for a body whose result is nil, such as a mutation:
(when (+/safe? total amount)
(alter! total (+ total amount)))
Termination
Calque understands conventional counted loops and some recursive measures. A base case must dominate the recursive call; merely placing an unrelated test earlier in the function does not establish termination.
(letrec count-down
(lambda (n)
(if (<= n 0)
0
(count-down (- n 1)))))
An unknown termination result is not a rejection. It means the analysis chose
not to make a proof claim. The full correctness-analysis
chapter describes the model and que explain
output.
Effects and permissions
Pure computation is available without runtime permissions. Host operations are explicit functions and must be granted capabilities when running under the external WASI host.
(let input (read! "input.txt"))
(println! input)
que program.que --allow read print
What Calque tracks
Effects are compiler metadata inferred from the implementation of an
expression. They are useful for diagnostics, permission reporting, ownership
reasoning, and optimization. They are not part of a function’s written
type: Int -> Int does not say whether a function mutates or performs I/O.
que explain and editor hovers can report one or more of these labels:
| Label | Meaning |
|---|---|
pure | No known mutation, host I/O, or unresolved call. |
mutate | Performs a mutation which the compiler can identify. |
io | Calls a host operation or extern; it may require a permission. |
unknown-call | Calls a function whose implementation is not statically known at this call site. |
The labels combine. For example, a function may be both mutate and io.
pure is used only when none of the other labels apply.
unknown-call is conservative, not an error
Higher-order code often accepts a callback. The callback may be pure, mutate its argument, or call the host, but that information is not contained in its ordinary function type:
(let apply-twice
(lambda (f x)
(f (f x))))
apply-twice is therefore reported with unknown-call: the parameter f
could refer to any compatible function. This does not mean the program is
invalid, that it necessarily performs I/O, or that permission was denied. It
means the compiler cannot make a stronger claim from the source it sees.
By contrast, a direct call to a locally known implementation can be summarised precisely:
(let plus-one (lambda x (+ x 1)))
(let answer (plus-one 41))
; `plus-one` and this call are pure.
The analyser also resolves many direct letrec calls. A function passed
through a parameter, stored behind an unknown value, or invoked indirectly may
remain unknown-call even when you know it is harmless at runtime.
This conservatism protects correctness and ownership: around an unknown call, the optimizer does not assume that a mutable argument is unchanged, and avoids transformations that would reorder, duplicate, or discard the call. It can also prevent inlining, loop unrolling, and other optimizations that require a known effect. Make the callee direct, or keep the callback boundary explicit, when the distinction matters for performance.
Use que explain to inspect the inferred result for a program:
que explain program.que --opt
The Effects and permissions section gives the combined program effect; the Generated code section lists effects for individual compiled functions. In the editor, hover over a binding to see its inferred effect.
Effects, names, and permissions
! is a useful naming convention for operations which mutate or interact with
the outside world, but it is not a permission grant and does not by itself
determine an effect. An extern declaration is always treated as host I/O,
and the external runner enforces its matching --allow capability. Local
functions infer their effects from their bodies.
Effects are informative rather than an effect-row type system: there is no
syntax for declaring “this function is pure,” and sig checks value types,
not effects. Runtime permissions remain the authority for built-in host
operations.
Permission groups
| Permission | Operations |
|---|---|
read | read!, list-dir!, read/chunks!, read/lines! |
stdin | stdin!, stdin/chunks! |
write | write!, mkdir!, move! |
delete | delete! |
print | print!, println!, clear! |
clock | sleep!, time!, random! |
all | all groups |
--allow accepts the groups separated by spaces on the command line. The
runtime exposes the current working directory to the Wasm program when a file
permission is granted.
Callback input
The callback forms process chunks or lines without building an output vector:
(read/lines! "input.txt"
(lambda (line)
(println! line)
false))
The callback returns a Bool: false continues and true stops early. The
operation returns whether it stopped early. read/chunks! and
stdin/chunks! require a positive chunk size.
The current external WASI adapter reads the source input before splitting it for these callbacks, while a native-C or embedding host can stream directly. The callback API is still useful for early exit and for avoiding a separate vector of every line or chunk. Query the installed library when using these APIs:
que --lib types 'read/*'
que --lib types 'stdin/*'
Serialization and FFI
serialize converts a statically known Calque value to text. deserialize
requires a concrete expected type, usually supplied by sig. Enums serialize
by declared variant name and can be deserialized back into their enum type.
For custom host functions and the Wasm ABI, see FFI and host imports. External functions must have declared types; they are not dynamically typed escape hatches.
WebAssembly target
Calque lowers its typed AST into WebAssembly. Core scalar values fit the Wasm
i32 model: Int, Bool, Char, zero-payload enum tags, Dec, and unit all have compact
scalar lowering. Managed collections and closures use the runtime’s reference
counted representation.
Wasm32 today
The default target is Wasm32: linear-memory addresses and array indexes in the
runtime are i32. An Int index is signed at the language level, while Wasm
memory addressing is unsigned internally; valid program indices are therefore
non-negative and bounded by the allocated vector length.
Wasm32’s address space is bounded by its configured linear memory limits. This
does not make the language architecture obsolete: Wasm continues to support
i32 operations on 64-bit hosts, and memory64 can be introduced later with an
explicit wider language type rather than changing existing Int behavior.
Inspect generated output
que program.que --emit source --out expanded.que
que program.que --opt --emit opt-source --out optimized.que
que program.que --opt --emit wat --out program.wat
que program.que --opt --emit wasm --out program.wasm
Use this when optimizing or reporting a compiler bug. The expanded source shows macro lowering; optimized source shows source-level rewrites; WAT shows the final Wasm structure.
Runtime choices
que program.que compiles then invokes an external WASI runtime. Wasmtime is
the default runtime; Wasmer and iwasm/WAMR can also be selected.
The repository’s native path runs generated Wasm through wasm2c and a C
compiler. It is deliberately separate from the main que command:
./scripts/compile-native-c.sh program.que
This is useful for completed compute-heavy programs and native benchmarking. It is not a different source language: static typing, macro expansion, and Wasm generation occur first in the same compiler.
serialize and deserialize also stay in the generated guest Wasm on this
path. Their record and payload-enum format is therefore the same under
Wasmtime and under wasm2c/native C. The native wrapper uses that codec for a
program’s final result too, including direct record and payload-enum returns.
For the debug/optimized safety boundary and a release checklist, see Debug, optimized, and native execution.
Debug, optimized, and native execution
Calque has one source language and one type checker. The execution mode changes which runtime guards remain in generated code and which runtime executes the result; it does not loosen type checking, make reference cycles valid, or turn warnings into type errors.
Development: --debug
Use debug mode while writing and testing a program:
que program.que --debug --allow read print
It emits static-analysis findings and keeps configured runtime checks for facts the compiler could not prove, including vector bounds, integer arithmetic, and division by zero. A debug trap is evidence that an execution violated a Calque invariant. Fix the input validation or source invariant rather than treating a trap as an expected control-flow mechanism.
Release: --opt
Use optimized mode only after exercising the program in debug mode and reading relevant warnings:
que explain program.que --opt
que program.que --opt --allow read
--opt enables source and Wasm optimizations and omits optional Calque runtime
guards. It uses static proofs when available, but it also assumes that source
invariants you chose not to guard are true. For example, an unguarded dynamic
get can be unchecked in optimized code.
WebAssembly still bounds every access to its linear memory. An access outside
linear memory traps and cannot escape the guest sandbox. That is not the same
as a valid vector access: an incorrect unchecked index that remains inside
linear memory can read or overwrite unrelated Calque runtime data. The result
may be wrong or may later fail due to corrupted Calque-level state. Treat
--opt as release performance mode, not as permission to ignore correctness.
Native C path
The repository’s optional native path first compiles the same typed Calque
program to Wasm, then translates that Wasm through wasm2c and a C compiler:
./scripts/compile-native-c.sh program.que
It is useful for finished compute-heavy programs, low RSS, and native benchmarking. It is not a separate compiler, a different ownership model, or a replacement for debug validation. Compare its output with both debug and optimized WASI runs before relying on it for a workload.
Recommended release checklist
- Run representative inputs with
--debug. - Address warnings, or make the invariant visible with a guard.
- Inspect
que explain program.que --optfor hot-path bounds checks, allocations, and unknown calls. - Compare debug and optimized output on representative inputs.
- Measure complete optimized runs; compare the native path only when it is a realistic deployment option.
- Pin the Calque version used for a long-lived project or reproducible build.
If debug, optimized, or native output differs for the same valid input, reduce the program and report it as a compiler bug. See the debugging cookbook.
CLI
Run que --help for the installed command overview. The important commands
are below.
Run and compile
que program.que --debug
que program.que --opt
que run-wasi program.que --runtime wasmtime --allow read print
que compile program.que --opt --out program.wasm
que wat program.que
run-wasi is the explicit spelling of normal execution; que program.que
uses it implicitly. --runtime accepts wasmtime, wasmer, iwasm/wamr,
or a path to one of those executables.
Inspect and explain
que program.que --emit types
que program.que --emit source
que program.que --opt --emit opt-source
que explain program.que --opt
que explain program.que --opt --json --out report.json
Format and browse the library
que fmt program.que
que fmt program.que --check
que fmt --stdin
que --lib names 'Table/*'
que --lib types 'map*'
que --lib source Table/get
Library patterns are passed as an argument—names containing !, ?, or *
do not need shell escaping when quoted.
Built-in guides and environment
que --learn
que --examples
que --style
que --pitfalls
que --env
--env lists compiler/runtime environment settings, including optimization,
debug, decimal-scale, and runtime selection settings.
Debugging cookbook
Calque separates type errors, static warnings, runtime guards, permissions, and generated-code inspection. Start with the mode that preserves the most information:
que program.que --debug
After the program’s invariants are established, inspect and run the optimized form:
que explain program.que --opt
que program.que --opt
“Undefined variable” or an unexpected binding
Bindings are lexical. let creates an immutable local, mut a mutable local,
and letrec is required only when a binding calls itself. Check for a name
outside its scope or a recursive function written with let:
; Wrong: `factorial` is not in scope while its value is being defined.
(let factorial
(lambda (n) (factorial (- n 1))))
; Right.
(letrec factorial
(lambda (n)
(if (<= n 1) 1 (* n (factorial (- n 1))))))
For macro-heavy code, inspect the expanded source. This distinguishes your source binding from a generated temporary without exposing implementation details in normal diagnostics:
que program.que --emit source --out expanded.que
“Expected … but got …”
The error normally identifies the argument or expression that conflicts. Ask the compiler for the inferred shape of a library operation instead of guessing:
que --lib types 'Table/get*'
que --lib types 'map*'
At a public boundary, add a sig to state the intended type. This both records
the contract and makes an accidental specialization easier to find:
(sig square (Int -> Int))
(let square (lambda (n) (* n n)))
Check destructuring too: [head . tail] needs a non-empty vector, while
{left right} expects a two-field tuple.
The compiler and both language servers collect independent top-level type errors together. During diagnostic recovery only, a failed declaration gets an internal unknown placeholder so later forms can still be checked; it never makes the program valid or compilable. This avoids distracting “undefined variable” cascades while still finding other errors in those later forms.
A bounds, empty-vector, or arithmetic warning
Warnings mean the analyser could not prove the required fact. They are not all runtime failures, but they deserve an explicit decision. Run the full report:
que explain program.que --opt
Make the condition visible at the use site:
(if (and (>= index 0) (< index (length xs)))
(get index xs)
fallback)
For arithmetic, make both outcomes value-producing with if or cond:
(if (+/safe? total amount)
(+ total amount)
total)
when is for an effect-only body and returns nil when its condition is
false. Use it for a guarded mutation, not to produce an Int result.
A debug runtime trap
--debug retains configured runtime guards for operations that static analysis
could not prove safe. A trap such as integer overflow, division by zero, or an
out-of-bounds vector access is evidence that the input reached an invalid
state—not merely a compiler warning.
Fix the source invariant first. The diagnostic points at the original Calque
source span; if a macro is involved, emit expanded source as shown above. Once
the program is correct in debug mode, use --opt for release timing.
An operation is denied at runtime
File, terminal, clock, and stdin functions require explicit permissions under the external WASI runtime. Grant only the needed groups:
que report.que --debug --allow read print
Use --allow all only for trusted local experiments. See Effects and
permissions for the operation-to-permission mapping.
The optimized program differs from debug
That is a compiler bug, not an expected trade-off. Preserve the smallest source that demonstrates it and compare the forms:
que program.que --debug
que program.que --opt
que program.que --opt --emit opt-source --out optimized.que
que program.que --opt --emit wat --out program.wat
If you use the native path, compare that too:
./scripts/compile-native-c.sh program.que
Record the compiler version, command lines, expected output, actual output, and the smallest reproducer. Do not work around a debug/optimized mismatch by shipping the unverified optimized result.
A program is correct but unexpectedly slow
First find out whether the issue is generated shape or measured runtime:
que explain program.que --opt
que program.que --opt
The explain report can reveal remaining allocations, dynamic application, or checked accesses. It cannot tell you elapsed time. Benchmark multiple complete runs, then inspect optimized source and WAT only after the benchmark identifies a real hot path. The Performance guide gives the common source-level choices.
Editor diagnostics look stale
Save the buffer and confirm the command-line compiler sees the same source:
que program.que --debug
Then confirm the editor launched the intended quelsp from PATH. Restarting
the language server is appropriate after installing a new release. If the
command-line and editor diagnostics disagree on saved source, keep the source
and both messages as a language-server bug report.
Projects, composition, tests, and editors
que.toml
When compiling a .que file, Calque searches upward from that file for a
que.toml. The configuration can provide source bundles and environment
settings:
entry = "main.que"
deps = [
"./lib/math.que",
"./lib/text.que",
]
[env]
QUE_WASM_OPT = "speed"
QUE_DEVIRTUALIZE = "aggressive"
QUE_TCO = "aggressive"
deps paths are resolved from the project root. Each dependency must be a
.que definition bundle: its top-level forms may be sig, let, letrec,
mut, or extern, but not arbitrary run-time expressions. Calque merges those
definitions with the standard library and the compiled source file.
At present, invoke the source entry explicitly:
que main.que --debug
The entry field records the intended entrypoint for tooling and project
conventions; compilation is driven by the source file passed to the current
CLI command.
Composition, not modules
Today Calque projects use ordered source composition, not an import/module system or package registry. A dependency bundle contributes its top-level names to the program that is compiled. This has useful consequences:
- dependencies are ordinary
.quesource, versioned with the project; - definitions must appear before uses, so dependency order in
depsmatters; - a dependency cannot perform top-level I/O or other run-time work;
- duplicate top-level names are an error rather than an override mechanism;
- recursive calls use
letrecinside one definition; mutually recursive top-level bundles are not currently a project feature.
A small project can therefore use a simple layout:
report/
que.toml
lib/parse.que
lib/stats.que
main.que
tests/report.test.que
Keep reusable let/letrec definitions in lib/*.que, list them in
dependency order in que.toml, and keep execution and host I/O in main.que.
This is deliberately explicit until Calque grows a real module/package model.
Tests and CI
Calque test files are ordinary source. A useful small test file returns data that a shell runner, CI job, or person can inspect:
; tests/math.test.que
(let square (lambda (n) (* n n)))
[(test "square of zero" (= (square 0) 0))
(test "square of nine" (= (square 9) 81))]
; [{"square of zero" true} {"square of nine" true}]
test is intentionally a tiny macro that creates {name outcome} data. It
does not provide a hidden test runner or magical assertion behavior. Run test
sources in debug mode first:
que tests/math.test.que --debug
For a project, make CI run formatting, debug tests, optimized tests where relevant, and the compiler’s own Rust suite from a checkout:
que fmt main.que --check
que tests/math.test.que --debug
que tests/math.test.que --opt
cargo test
Use a real assertion runner around the printed result if a nonzero process exit
on false is required today. A debug/optimized or WASI/native output mismatch
for the same valid test input is a compiler bug; preserve the smallest
reproducer and the commands used. See the debugging cookbook.
Formatter
que fmt program.que
que fmt program.que --check
que fmt --stdin
The formatter keeps compact short forms where possible, uses two-space-style nesting, preserves comments, and deliberately keeps runs of closing delimiters together rather than spreading them across lines.
Language server and editors
quelsp provides diagnostics, inferred-type hover, completion, signatures,
and project-aware definitions. The repository includes:
- a thin Neovim plugin in
miscs/neovim - an Emacs 29.1+ mode with built-in Eglot support in
miscs/emacs - a VS Code extension in
miscs/extension/que-lang
The Neovim integration provides :QueFormat / <Space>f and :QueLib /
<Space>g. In que nvim, scratch commands include optimized run, debug run,
WAT, inferred types, explain, expanded source, and library browsing.
Use que nvim --file program.que to open and edit an existing Calque file.
The optional permission flags, such as --allow read, are forwarded to its
run and debug mappings. que nvim and que nvim --code "..." instead open
disposable scratch buffers.
In Emacs, que-mode starts Eglot automatically when quelsp is on PATH.
Its buffer-local bindings are C-c C-f (format), C-c C-r (optimized run),
C-c C-d (debug run), C-c C-w (WAT), and C-c C-e (explain).
See the integration READMEs for installation details and configuration examples.
FFI and host imports
Calque’s current FFI is a WebAssembly host-import FFI. A Calque extern
declaration becomes a Wasm import; an embedding host must supply a function
with the same module and import names. It is not a C ABI, plugin system, or
callback framework.
Declare an import
(extern env add_one add-one! (Int -> Int))
(add-one! 41)
; 42 when the host supplies env.add_one
The declaration syntax is:
(extern module import local-name! Type)
Rules:
externis top-level only.- A local external name must end in
!. - External calls are treated as effectful by the compiler.
- The declaration has a concrete type; it is not dynamically typed.
Zero-argument imports use unit as their argument:
(extern env clock_now_ms clock-now-ms! (() -> Int))
Supported declared shapes
Extern signatures use the familiar core type syntax:
Int
Dec
Bool
Char
()
[Char]
[Int]
{Int Int}
(Int -> Int)
([Char] [Char] -> ())
At the Wasm ABI boundary, scalar core values lower to i32. Vectors, tuples,
and strings lower to an i32 pointer into Calque’s linear memory. Dec is a
fixed-point i32, not an f64. Calque’s managed representation is internal to
the runtime: a host returning a managed value must construct a valid Calque heap
object, while managed values received from Calque are borrowed unless the host
explicitly retains them using the runtime convention.
Built-in effect operations
The normal que runner supplies these operations through its WASI adapter.
They have ordinary, statically checked Calque types; ! marks the operations
that perform an external effect. println! is the standard-library convenience
form of print! plus a newline, but has the same source-level type.
Files and directories
| Operation | Type | Permission | Meaning |
|---|---|---|---|
read! | [Char] -> [Char] | read | Read a complete text file. |
list-dir! | [Char] -> [[Char]] | read | List directory-entry names. |
read/chunks! | [Char] -> Int -> ([Char] -> Bool) -> Bool | read | Visit successive text chunks. |
read/lines! | [Char] -> ([Char] -> Bool) -> Bool | read | Visit successive lines, without newline terminators. |
write! | [Char] -> [Char] -> () | write | Write text to a path. |
mkdir! | [Char] -> () | write | Create a directory path. |
move! | [Char] -> [Char] -> () | write | Rename or move a path. |
delete! | [Char] -> () | delete | Delete a file or directory path. |
Paths and text are both [Char], normally written as string literals:
(let config (read! "config.txt"))
(write! "copy.txt" config)
(let names (list-dir! "."))
Standard input and callbacks
| Operation | Type | Permission | Meaning |
|---|---|---|---|
stdin! | () -> [Char] | stdin | Read all standard input as text. |
stdin/chunks! | Int -> ([Char] -> Bool) -> Bool | stdin | Visit standard input in chunks. |
All three callback operations—read/chunks!, read/lines!, and
stdin/chunks!—share one control convention:
- The callback receives a
[Char]chunk or line. - Return
falseto continue. - Return
trueto stop early. - The operation itself returns
truewhen it stopped early andfalsewhen it reached end of input.
Chunk size must be positive. For example, print at most ten lines:
(&mut seen 0)
(let stopped?
(read/lines! "input.txt"
(lambda (line)
(&alter! seen (+ (&get seen) 1))
(println! line)
(>= (&get seen) 10))))
The callback API avoids constructing a vector of all lines or chunks. The current external WASI adapter reads its input text before it partitions it for callbacks; an embedding or native-C host may stream at the host level. Do not assume the callback spelling alone guarantees bounded host-side input memory on every target.
Terminal and clock
| Operation | Type | Permission | Meaning |
|---|---|---|---|
print! | [Char] -> () | print | Print text without adding a newline. |
println! | [Char] -> () | print | Print text followed by a newline. |
clear! | () -> () | print | Request a terminal clear. |
sleep! | Int -> () | clock | Sleep for a non-negative number of milliseconds. |
time! | () -> Int | clock | Current wall-clock time in whole Unix seconds. |
random! | () -> Int | clock | Get one host-provided random Int. |
println! accepts text, not an arbitrary value. Convert an integer explicitly:
(println! (Integer->String (time!)))
(sleep! 250)
random! is effectful host randomness. The library’s random, random/int,
random., and random/dec are separate deterministic seed-to-next-state
functions for reproducible computations.
Serialization
| Operation | Type | Permission | Meaning |
|---|---|---|---|
serialize | T -> [Char] | none | Convert a statically known supported Calque value to text. |
deserialize | [Char] -> T | none | Decode text as the statically expected type. |
deserialize cannot infer a target type from characters alone. State the
expected result with sig before the binding:
(let saved (serialize {42 "Ada"}))
(sig restored {Int [Char]})
(let restored (deserialize saved))
; {42 "Ada"}
Enums serialize by their declared variant name and are checked against the expected enum on decode. See Enum-keyed table round trip for a table example.
Compatibility and persistence
serialize is designed for Calque-to-Calque data within a compatible compiler
release. It is not yet a versioned, stable public storage or network format.
Do not make a database schema, long-lived cache, or external API depend on its
exact textual spelling without pinning the Calque compiler version and testing
the decoder during upgrades.
For persistent application data today, store an explicit version field next to the serialized value and own the migration in source:
(let saved {1 (serialize value)})
; On read, inspect the version before choosing the expected decoder and migration.
Serialization needs a concrete, fully known value type. It cannot serialize an
unresolved generic or a function/closure, and deserialize needs an expected
type through its binding, sig, or surrounding context. Malformed input or a
type mismatch is a decoding failure, not an implicit conversion.
Run a program using an operation only after granting the matching capability:
que program.que --allow read write print
--allow all grants every group. See Effects and permissions
for the short permission overview.
Custom hosts
The normal que runner delegates to an external WASI runtime. It can run the
built-in operations through Calque’s WASI adapter, but it does not load arbitrary
user host modules from command-line configuration. A program containing a
custom extern therefore needs an embedding/application that instantiates the
generated Wasm module and supplies the declared import.
For example, a Rust Wasmtime host conceptually registers:
#![allow(unused)]
fn main() {
linker.func_wrap("env", "add_one", |x: i32| -> i32 { x + 1 })?;
}
before instantiating the compiled module. The exact initialization needed for Calque-managed values belongs to that host integration, not the source program.
Current limits
The current supported model deliberately excludes:
- callbacks from host code into Calque closures
- an async/await runtime or automatic future bridging
- a stable public C ABI for Calque objects
- a generic CLI plugin loader for arbitrary imports
- automatic marshalling of arbitrary managed data
The optional wasm2c/native-C runner still uses this host-import model: wasm2c translates the guest code, while the adapter supplies the imports. It does not turn Calque’s internal memory representation into a general C interface.
Standard library overview
The active library is implemented in the repository’s lisp/ directory and
is bundled into normal compilation. It is deliberately ordinary Calque source
where possible: the compiler recognizes a small set of primitive operations,
while functional helpers, collection APIs, loop conveniences, and algorithms
are written in the language itself.
Do not guess a signature
The installed compiler can query the library it actually bundles:
que --lib names 'Table/*'
que --lib types 'map*'
que --lib source Table/update!
This is the authoritative API reference between releases. Start with Functions by example for copyable everyday use, then use the complete library index and the live query when you need a specialist or implementation-level name.
Naming and argument order
!marks a mutating or effectful operation.?marks a predicate./iis commonly an index-aware collection variant./rawis an implementation-level helper; prefer its public counterpart.- Namespace-like names use
/:Vector/sort!,String/contains?,Table/update!. - Transform-style functions usually take data last so they work with
|>. - Collection operations, including mutating ones, normally take their collection last.
(|> xs
(map normalize)
(select valid?)
sum)
(Table/set! key value table)
Main families
| Family | Purpose |
|---|---|
| Core vectors | get, set!, push!, pop!, length, car, cdr |
| Functional transforms | map, select, filter, reduce, sort, range |
| Text and conversion | split, join, trim, slice, String/*, Integer->String |
| Data structures | Table/*, Set/*, Heap/*, Que/*, Matrix/* |
| Numbers | decimal helpers, bit operations, random, BigInt and SignedBigInt |
| Meta and utility | dates, parsing helpers, test helpers, constants |
The following pages cover the most important usage patterns and the complete public library families.
Functions by example
This is the practical first stop for the bundled library: short examples of the functions you will use in normal programs. The complete library index covers every exported family, including low-level helpers.
Functions that transform a collection take that collection last, so they
compose naturally with |>. Operations ending in ! mutate their final
collection argument and normally return nil.
(|> [1 2 3 4]
(map (lambda (x) (* x x)))
(filter (lambda (x) (> x 4)))
sum)
; 25
Core vectors
Vectors are homogeneous and mutable. Strings are vectors of Char, so the
same basic read operations work on both.
(let xs [10 20 30])
(length xs) ; 3
(get 1 xs) ; 20
(car xs) ; 10 — first element
(cdr xs) ; [20 30] — tail from offset 1
(cdr 2 xs) ; [30] — tail from an explicit offset
(first xs) ; 10
(last xs) ; 30
(at -1 xs) ; 30 — negative indexing helper
(cons [0] xs) ; [0 10 20 30] — concatenate two vectors
car, cdr, and tail windows
car reads the first element: it is the head-oriented spelling of
(get 0 xs). cdr creates a tail window. (cdr xs) starts at offset
1; (cdr n xs) starts at offset n. The window has its own logical index
zero, so it is useful for head-and-tail recursion without copying every tail.
(let xs [10 20 30 40])
(let tail (cdr 2 xs))
(get 0 tail) ; 30
(length tail) ; 2
(set! 0 99 tail)
{xs tail}
; { [10 20 30 40] [99 40] }
Initially, a cdr result shares the source vector’s backing storage. The
first mutation of the tail materializes an independent vector, so changing
tail does not change xs. Conversely, retaining a small tail also retains
the original allocation until the tail is released or materialized. Use
slice when a fresh copied subvector is the clearer or more appropriate
representation.
get, car, first, last, and pop-val! require a valid, non-empty
input. For a dynamic index, use in-bounds?, Vector/get*, or structure the
loop so the analyser can prove the access.
(if (in-bounds? xs index)
(get index xs)
fallback)
(match (Vector/get* index xs)
None fallback
(Some value) value)
Mutation is direct and explicit:
(let xs [10 20])
(set! 0 99 xs) ; [99 20]
(push! 30 xs) ; append, xs is now [99 20 30]
(let last-value (pop-val! xs))
(pop! xs) ; remove the last value and return nil
(empty! xs) ; length becomes zero; allocation remains available
capacity! reserves storage for later appends without changing length. It is
effect-only. capacity is the non-mutating version: it copies first, reserves
the copy, and returns it. compact! discards unused vector capacity.
(let out [])
(capacity! 1000 out)
(loop i (< i 1000) (push! i out))
(let copy-with-room (capacity 1000 out))
(compact! out)
Useful names in this family are Vector/new, Vector/of, Vector/first,
Vector/last, Vector/at!, Vector/get-unsafe, Vector/set!,
Vector/push!, Vector/pop!, Vector/pull!, Vector/reverse!,
Vector/swap!, Vector/sort!, Vector/concat, and Vector/cons. Their
namespace forms are useful when an explicit, regular API is clearer than the
short core spelling.
Build and reshape sequences
range includes both endpoints. Use range/exclusive when the end should be
excluded; range/dec creates decimal values.
(range 3 6) ; [3 4 5 6]
(range/exclusive 3 6) ; [3 4 5]
(range/dec 1 3) ; [1.0 2.0 3.0]
(replicate 3 "go") ; ["go" "go" "go"]
(fill 4 (lambda (i) (* i i)))
; [0 1 4 9]
(Vector/new (lambda (i) i) 5)
; [0 1 2 3 4]
(zeroes 4) ; [0 0 0 0]
(ones 4) ; [1 1 1 1]
fill and Vector/new call their callback once per output index, from 0
through n - 1, and place each result at that same index.
The common shape operations return fresh vectors:
(reverse [1 2 3]) ; [3 2 1]
(flat [[1 2] [3] [4 5]]) ; [1 2 3 4 5]
(flat-map (lambda (x) [x (* x 10)]) [1 2])
; [1 10 2 20]
(zip {[1 2] ["a" "b"]}) ; [{1 "a"} {2 "b"}]
(unzip [{1 "a"} {2 "b"}]) ; {[1 2] ["a" "b"]}
(zip-with + [1 2] [10 20]) ; [11 22]
(interleave [1 2 3] [10 20 30]) ; [1 10 2 20 3 30]
(intersperse 0 [1 2 3]) ; [1 0 2 0 3]
For a contiguous part of a vector, slice uses an exclusive end. The
take/* and drop/* names describe which side is retained or removed.
(slice 1 4 [0 1 2 3 4]) ; [1 2 3]
(take/first 3 [0 1 2 3]) ; [0 1 2]
(take/last 2 [0 1 2 3]) ; [2 3]
(drop/first 2 [0 1 2 3]) ; [2 3]
(drop/last 2 [0 1 2 3]) ; [0 1]
(partition 2 [1 2 3 4 5]) ; [[1 2] [3 4] [5]]
(window 3 [1 2 3 4]) ; [[1 2 3] [2 3 4]]
(pairwise [1 2 3 4]) ; [{1 2} {2 3} {3 4}]
take/while retains the initial matching prefix; drop/while removes that
prefix. cycle, subset, permutation, combination, and combination/n
are combinatoric builders. transpose turns rows into columns; Matrix/new
and Matrix/for/i are the more direct matrix tools.
pairwise returns the overlapping adjacent pairs of a vector as tuples. An
empty or one-element input has no pairs. Use it when the pairs themselves are
useful data; use map/adjacent when you want to transform every neighboring
pair immediately.
(pairwise [10 13 18 20])
; [{10 13} {13 18} {18 20}]
(map/adjacent - [10 13 18 20])
; [-3 -5 -2]
(|> [10 13 18 20]
pairwise
(map (lambda ({left right}) (abs (- right left)))))
; [3 5 2]
Map, filter, visit, and fold
map transforms every element. The /i forms pass (value index). filter
and its alias select retain matching values; exclude removes them.
(map (lambda (x) (* x 2)) [1 2 3])
; [2 4 6]
(map/i (lambda (x i) {i x}) ["a" "b"])
; [{0 "a"} {1 "b"}]
(filter even? [1 2 3 4])
; [2 4]
(exclude even? [1 2 3 4])
; [1 3]
for visits for effects and returns nil. each performs the same visit but
returns the original vector, which is useful in a pipeline. Their /i forms
also receive an index.
(let seen [])
(for (lambda (x) (push! x seen)) [1 2 3])
; seen is [1 2 3]
(|> [1 2 3]
(each (lambda (x) (println! x)))
reverse)
; [3 2 1]
reduce combines a vector from left to right with an explicit initial value.
reduce/i also supplies the index. scan returns all running reductions.
(reduce + 0 [10 20 30]) ; 60
(reduce/i (lambda (total x i) (+ total (* x i))) 0 [2 3 4])
; 11
(scan + [1 2 3 4]) ; [1 3 6 10]
The /until variants stop before the first value whose stop predicate is
true. They exist for map, reduce, and for, with index-aware /i forms.
(map/until (lambda (x) (* x 2)) (lambda (x) (> x 3)) [1 2 3 4])
; [2 4 6]
Search, tests, and aggregates
(find (lambda (x) (> x 10)) [3 7 12 9]) ; 2, or -1 when absent
(match (find* (lambda (x) (> x 10)) [3 7 12 9])
None -1
(Some index) index) ; 2
(count odd? [1 2 3 4]) ; 2
(some? odd? [2 4 5]) ; true
(every? positive? [1 2 3]) ; true
(some/i? (lambda (x i) (= x i)) [0 9]) ; true
(sum [1 2 3]) ; 6
(product [2 3 4]) ; 24
(minimum [8 2 5]) ; 2
(maximum [8 2 5]) ; 8
(mean [2 4 6]) ; 4
(median [9 1 5]) ; 5
(avg 5 8) ; 6 — integer average
Decimal equivalents use /dec, . suffixes, or the matching decimal
operator: sum/dec, product/dec, minimum/dec, maximum/dec,
mean/dec, median/dec, avg/dec, min., and max.. count/int,
count/char, count/dec, and count/bool count a particular value using the
appropriate equality operation.
Ordering and grouping
sort returns a sorted copy. Vector/sort! sorts the supplied vector in
place. A comparator returns true when its first argument belongs before its
second.
(sort (lambda (a b) (< a b)) [5 1 4 2])
; [1 2 4 5]
(let xs [5 1 4 2])
(Vector/sort! (lambda (a b) (< a b)) xs)
; xs is [1 2 4 5]
For a reusable named order, use Ord T and sort/ord:
(sort/ord Ord/Int [5 1 4 2])
; [1 2 4 5]
(sort/ord Ord/Dec [3.2 1.1 2.4])
; [1.1 2.4 3.2]
unique/int and unique/char remove repeated values for their respective
element types. group builds a table keyed by a function result:
(group (lambda (x) (% x 2)) [1 2 3 4])
; table with key 1 -> [1 3], key 0 -> [2 4]
Text and characters
Strings have type [Char]. split takes the separator first and text last;
join takes the separator first and a vector of strings last.
(split "," "red,green,blue") ; ["red" "green" "blue"]
(split/lines "one\n\ntwo") ; ["one" "" "two"]
(split/spaces "one two") ; ["one" "" "two"]
(split/words " one\ttwo\nthree ") ; ["one" "two" "three"]
(join "/" ["usr" "local" "bin"]) ; "usr/local/bin"
(trim " Calque ") ; "Calque"
(slice 1 4 "Calque") ; "alq"
split and split/spaces are raw delimiter splits: repeated, leading, and
trailing delimiters produce empty fields. split/lines follows that rule so
blank lines remain available as structure in an input. split/words is the
tokenizing variant: it splits on spaces, tabs, carriage returns, and newlines,
and drops empty fields.
Use lower, upper, digit?, space?, and the String/* predicates for
text logic:
(lower 'Q') ; 'q'
(upper 'q') ; 'Q'
(digit? '7') ; true
(String/starts? "Cal" "Calque") ; true
(String/contains? "lq" "Calque") ; true
(String/ends? "que" "Calque") ; true
(String/lt? "Ada" "Lin") ; true
Conversions are explicit:
(String->Integer "42") ; 42
(Integer->String 42) ; "42"
(String->Dec "3.5") ; 3.5
(Dec->String 3.5) ; "3.5"
(Char->Int 'A') ; 65
(Int->Char 65) ; 'A'
Other useful text functions are String/find, String/find/last,
String/matches-at?, String/damerau-levenshtein, String/quote,
String/dquote, and String/prepend-zeroes. match? compares two character
vectors exactly.
Regular expressions
String/regex compiles a reusable regular expression. A compiled expression
can be checked with String/regex/valid?, then used for either a whole-text
match or a substring search. Both matching functions take the text last.
(let identifier (String/regex "^[a-zA-Z_][a-zA-Z0-9_]*$"))
(String/regex/valid? identifier) ; true
(String/regex/matches? identifier "calque_2") ; true
(String/regex/matches? identifier "2calque") ; false
(String/regex/contains? (String/regex "cat") "concatenate")
; true
; One-off convenience forms compile the pattern for this call.
(String/matches-regex? "[0-9]+" "2048") ; true
(String/contains-regex? "\\d+" "item-42") ; true
The engine is a predictable Thompson NFA, not a PCRE implementation. It
supports grouping, alternation (|), *, +, ?, ., ^, $, character
classes (including negated ASCII ranges), and \\d, \\D, \\w, \\W, \\s,
\\S, \\n, \\r, \\t, \\f, and \\v. Literal characters may be Unicode
code points, but character classes and shorthand classes are ASCII-oriented.
Counted repetitions ({m,n}), word boundaries, backreferences, look-around,
and hexadecimal escapes are deliberately unsupported. An invalid pattern makes
String/regex/valid? false; matching predicates return false for it.
Numeric helpers
Normal Int arithmetic is signed i32; decimals use Dec and dotted
operators. The predicate variants let a program establish a safety condition
before using arithmetic in an optimized program.
(abs -9) ; 9
(square 12) ; 144
(gcd 18 24) ; 6
(lcm 6 8) ; 24
(clamp 10 14) ; 10
(clamp-range 0 10 -4) ; 0
(even? 8) ; true
(odd? 9) ; true
(divisible? 3 12) ; true
(expt 3 2) ; 8 — exponent first
(sqrt 81) ; 9
Use positive?, negative?, zero?, one?, negative-one?, invert,
delta, min, max, floor, ceil, and Int/euclidean-mod for the
corresponding small operations. Decimal versions include abs., sqrt.,
expt., clamp/dec, delta/dec, and /dec? predicates. Integer->Bits,
Bits->Integer, Integer->Digits, Digits->Integer, and their character
versions convert representations. random/int and random/dec are
deterministic seed-to-value functions.
Tables, sets, heaps, deques, and matrices
Tables are mutable hash maps. Their public operations put the table last, so
they compose naturally with |>.
(let scores (Table/new))
(Table/set! "Ada" 10 scores)
(Table/update-or! "Ada" (lambda () 0) (lambda (n) (+ n 1)) scores)
(Table/has? "Ada" scores) ; true
(Table/get-unsafe "Ada" scores) ; 11
(Table/entries scores) ; [{"Ada" 11}]
(Table/keys scores) ; ["Ada"]
(Table/values scores) ; [11]
Table/get returns the internal matching entry vector; prefer Table/get*
for a (Option V) result or Table/get-unsafe after a Table/has?
check. Table/remove!, Table/drop!, Table/merge!, Table/resize!, and
Table/compact! mutate; Table/keep, Table/omit, and Table/merge return
new tables. Table/count and Table/frequency build counting tables.
(let tags (Set/new))
(Set/add! "fast" tags)
(Set/add! "typed" tags)
(Set/has? "fast" tags) ; true
(Set/remove! "fast" tags)
(Set/values tags) ; ["typed"]
Sets provide intersection, union, difference, and xor, as well as
Set/new/capacity, Set/resize!, and Set/compact! for allocation control.
(let heap [])
(let before? (lambda (a b) (< a b)))
(Heap/push! 4 before? heap)
(Heap/push! 1 before? heap)
(Heap/peek! heap) ; 1
(Heap/pop! before? heap)
Que/new creates a deque with a default value. Use Que/append!/Que/push!
and Que/prepend! to add at either end; Que/pop! and Que/tail! remove;
Que/first, Que/last, Que/peek, Que/get, and Que/at read it.
(let matrix (Matrix/new (lambda (y x) (+ (* y 10) x)) 3 2))
; [[0 1] [10 11] [20 21]]
(Matrix/in-bounds? 1 2 matrix) ; true
Big integers, dates, metadata, and options
BigInt is a nominal record containing an unsigned arbitrary-precision digit
sequence. SignedBigInt is a nominal record around a sign and a BigInt;
StructBigDec adds an explicit decimal precision. Construct values through
their namespaces and keep arithmetic there rather than passing raw digit
vectors:
(let a (BigInt/new "999999999999999999"))
(Digits->Chars (BigInt/digits (BigInt/add a (BigInt/new "1"))))
; "1000000000000000000"
(SignedBigInt->String
(SignedBigInt/add (SignedBigInt/new "-25") (SignedBigInt/new "7")))
; "-18"
(StructBigDec->String
(StructBigDec/new-digits false (BigInt [3]) (BigInt [1 4])))
; "3.14"
Date/iso->Vector, Date/iso-z->Vector, Date/year, Date/month,
Date/day, and Date/hour work with the library’s date-vector representation.
Meta/parse, Meta/table, Meta/get, and Meta/has? support simple
metadata tokens. true/option, false/option, and resolve/option use the
ordinary tuple representation {Bool value} for success-or-default flows.
Discover anything not shown here
The installed compiler is the exact reference for the library bundled with that installation. Search by shell-style glob and inspect a definition when needed:
que --lib names 'Table/*'
que --lib types 'map*'
que --lib source Table/update-or!
The complete library index explains how the remaining specialist and implementation-level names are organized.
Complete library index
Calque ships a large library, including general-purpose functions, specialist algorithms, compatibility aliases, and low-level building blocks used to implement the higher-level APIs. The normal public starting points are shown with runnable code in Functions by example.
This page tells you where every exported name belongs. The compiler installed on your machine is the authoritative source for exact signatures and source:
que --lib names '*'
que --lib types 'Table/*'
que --lib source Table/update-or!
Common functions
Most Calque programs use a fairly small part of the library. Start with these names; the sections below remain the complete family index, and Functions by example shows each of these patterns in runnable code.
| Need | Start with |
|---|---|
| Build integer data | range, range/exclusive, fill, replicate |
| Transform or retain vector values | map, map/i, filter (or select), exclude, flat-map |
| Visit for effects | for, each, for/i, each/i |
| Combine or inspect values | reduce, sum, product, count, find, some?, every?, minimum, maximum |
| Reshape a vector | reverse, flat, zip, unzip, slice, take/first, drop/first, partition, pairwise |
| Order or classify values | sort, group, unique/int, unique/char |
| Parse or assemble text | split, split/lines, split/spaces, split/words, trim, join, String->Integer, Integer->String |
| Use key-value data | Table/new, Table/set!, Table/get, Table/has?, Table/entries, Table/update-or!, Table/count |
| Work directly with a vector | length, get, set!, push!, pop!, pop-val!, empty!, capacity!, in-bounds? |
The usual collection convention is data last, so calls compose through
|>:
(|> [1 2 3 4]
(map (lambda (x) (* x x)))
(filter (lambda (x) (> x 4)))
sum)
; 25
get, pop-val!, first, and last require a valid value. When an index or
input length is dynamic, check it with in-bounds? or use Vector/get*,
which returns (Option T).
Core language operations
The compiler provides vector and tuple primitives: length, get, set!,
push!, pop!, pop-val!, empty!, capacity!, car, cdr, cons,
fst, snd, box, and swap!. It also provides arithmetic,
comparison, bitwise, boolean, character, decimal, I/O, serialization, and
filesystem primitives. These are described in the language chapters rather
than duplicated as library implementations.
Macros include cond, when, when-not, unless, |>, <|, comp,
apply, loop, loop/for, loop/in, loop/in/i, times, mutation sugar
such as ++ and +=, and compile-time helpers such as test.
Functional and vector helpers
The unnamespaced functional collection surface is in lisp/fp.lisp:
- Construction and shape:
range,range/inclusive,range/exclusive,range/dec,fill,replicate,copy,reverse,flat,flat-map,zip,unzip,zip-with,transpose,interleave,intersperse,partition,window,pairwise,slice,take/first,take/last,drop/first,drop/last,take/while,drop/while,cycle,subset,permutation,combination,combination/n, andscan. - Traversal:
map,map/i,filter,filter/i,select,exclude,for,for/i,each,each/i,reduce,reduce/i,map/until,map/until/i,reduce/until,reduce/until/i,for/until, andfor/until/i. - Queries and aggregation:
empty?,not-empty?,in-bounds?,find,count,count/int,count/char,count/dec,count/bool,some?,some/i?,every?,every/i?,sum,sum/dec,product,product/dec,minimum,minimum/dec,maximum,maximum/dec,mean,mean/dec,median,median/dec,avg, andavg/dec. - Ordering and specialized operations:
sort,group,unique/int,unique/char,pairwise,map/adjacent,map/tuple,map/fst,map/snd,resolve/option,autocorrect,match?,cartesian-product, andneighborhood. - Safe lookup:
get*,at*, andfind*. They return(Option T); match onNoneand(Some value)rather than using a sentinel value.
The Vector/* namespace supplies regular versions and lower-level helpers:
Vector/new, Vector/of, Vector/first, Vector/last, Vector/at!,
Vector/get*, Vector/at*, Vector/find*, Vector/get-unsafe,
Vector/in-bounds?, Vector/set!,
Vector/push!, Vector/pop!, Vector/pull!, Vector/append!,
Vector/concat, Vector/cons, Vector/reverse!, Vector/sort!, and
Vector/swap!. Names ending in /raw are implementation-level variants;
prefer the non-raw name unless you are extending the library itself.
Text, numbers, and conversion
- Text:
split,split/lines,split/spaces,split/words,split/commas,join,trim,trim/left,trim/right,lower,upper,digit?,space?,String/starts?,String/ends?,String/contains?,String/equal?,String/lt?,String/lte?,String/gt?,String/gte?,String/find,String/find/last,String/matches-at?,String/damerau-levenshtein,String/quote,String/dquote,String/prepend-zeroes,String/regex,String/regex/valid?,String/regex/matches?,String/regex/contains?,String/matches-regex?, andString/contains-regex?. - Conversions:
String->Integer,Integer->String,String->Dec,Dec->String,String->Bool,String->Vector,Char->Int,Int->Char,Char->Bool,Bool->Char,Bool->Int,Int->Bool,Int->Dec,Dec->Int,Integer->Bits,Bits->Integer,Integer->Digits,Digits->Integer,Digits->Chars,Chars->Digits,Chars->Integer, and their/baseor/decvariants. - Integer math:
abs,square,gcd,lcm,min,max,clamp,clamp-range,sqrt,expt,floor,ceil,delta,divisible?,positive?,negative?,zero?,one?,negative-one?,even?,odd?,invert, andInt/euclidean-mod. - Decimal math mirrors the applicable integer functions with
.or/decspellings. Safety predicates are+/safe?,-/safe?,*/safe?,/safe?,%/safe?, plus decimal equivalents such as+./safe?. - Deterministic pseudo-random helpers are
random,random/int,random., andrandom/dec; mathematical constants live underconst/dec/*.
Structured data
- Tables:
Table/new,Table/new/capacity,Table/set!,Table/get,Table/get*,Table/get-unsafe,Table/has?,Table/remove!,Table/drop!,Table/keep,Table/omit,Table/entries,Table/keys,Table/values,Table/update!,Table/update-or!,Table/push-or!,Table/count,Table/frequency,Table/merge,Table/merge!,Table/resize!,Table/compact!, andTable/count-entries. - Sets:
Set/new,Set/new/capacity,Set/add!,Set/remove!,Set/has?,Set/values,Set/size,Set/count,Set/intersection,Set/union,Set/difference,Set/xor,Set/resize!, andSet/compact!. - Heaps:
Heap/push!,Heap/pop!,Heap/peek!,Heap/replace!,Heap/empty!,Heap/empty?,Heap/not-empty?,Heap/parent,Heap/left,Heap/right,Heap/sift-up!, andHeap/sift-down!. - Deques:
Que/new,Que/length,Que/empty?,Que/not-empty?,Que/get,Que/at,Que/peek,Que/first,Que/last,Que/append!,Que/enque!,Que/push!,Que/prepend!,Que/pop!,Que/tail!,Que/deque!, andQue/empty!. - Matrices:
Matrix/new,Matrix/in-bounds?,Matrix/for/i, andMatrix->String.neighborhood/*constants provide common coordinate kernels.
Specialist representations
BigInt/* implements unsigned arbitrary-precision arithmetic, including
new, add, sub, mul, div, mod, comparisons, pow, square,
sum, product, and range. BigInt is a nominal record around its digit
storage, so it cannot be confused with an ordinary [Int]. SignedBigInt/*
supplies the corresponding nominal signed representation, and
StructBigDec/* supplies arbitrary-precision decimal arithmetic with an
explicit precision. BigInt is unsigned: BigInt/sub requires its first
argument to be at least its second, and div/mod require a nonzero divisor.
Violating either precondition traps rather than wrapping or manufacturing a
value. Signed and decimal division likewise trap on a zero divisor. Date/* extracts pieces of the date-vector format;
Meta/* parses lightweight metadata; Payload/get accesses embedded payload
text.
The following names are intentionally low-level: */raw, */unchecked!,
Table/hash, Set/hash, allocation/bucket helpers, implementation constants,
and aliases maintained for library implementation. They are exported because
the library is Calque source, not because new applications should depend on
their representation. Query their source before using them.
Functional collections
The central functional transforms are data-last.
(|> [1 2 3 4 5]
(map (lambda (x) (* x x)))
(select (lambda (x) (> x 10)))
sum)
Transform and traverse
| Function | Role |
|---|---|
map / map/i | build a new vector; /i receives the index |
pairwise | build overlapping adjacent {left right} tuples |
map/adjacent | transform each neighboring pair directly |
filter, select, filter/i | retain items satisfying a predicate |
each / each/i | visit items and return the original vector |
for / for/i | visit items for effects |
reduce / reduce/i | fold with an explicit initial accumulator |
map/until, reduce/until, for/until | stop according to a predicate |
(reduce (lambda (total x) (+ total x)) 0 [10 20 30])
; 60
(map/i (lambda (x index) {index x}) ["a" "b"])
pairwise is data-last and returns one fewer tuple than its input. It is
empty for inputs shorter than two elements.
(|> [1 4 9 16]
pairwise
(map (lambda ({left right}) (- right left))))
; [3 5 7]
Construct and order
range, range/inclusive, and related helpers construct numeric sequences.
sort returns a sorted copy; Vector/sort! sorts a vector in place. Use a
comparison predicate that expresses the desired ordering.
(sort (lambda (left right) (< left right)) [5 1 4 2])
Ord T packages a reusable comparison for one value type, and sort/ord
uses it. You do not need a sig to define an order in ordinary code: the
constructor and its comparison infer together.
(sort/ord Ord/Int [5 1 4 2])
; [1 2 4 5]
(record Point y Int x Int)
(let Point/row-major
(Ord
(lambda (a b)
(or (< (Point/y a) (Point/y b))
(and (= (Point/y a) (Point/y b))
(< (Point/x a) (Point/x b)))))))
(sort/ord Point/row-major [(Point 1 0) (Point 0 4)])
; [Point{ y 0 x 4 } Point{ y 1 x 0 }]
The ordered collection is simply [Point]; there is no need for a separate
Points wrapper. Ord/Int and Ord/Dec are the standard ascending orders.
For allocation-sensitive code, prefer explicit loops and a reserved output vector when the result length is known. Pipeline fusion may optimize common map/filter/reduce shapes, but clear source invariants remain the first goal.
Numeric aggregates
The library has aggregate and statistical helpers including sum, product,
avg, mean, median, minimum, and maximum, with integer and decimal
variants where relevant. Query the exact expected element type rather than
relying on a name alone:
que --lib types 'sum*'
que --lib types 'avg*'
Tables, sets, heaps, and queues
Tables
Table/new creates a mutable hash table. Its public operations place the
table last, including mutating operations:
(let scores (Table/new))
(Table/set! "Ada" 10 scores)
(Table/set! "Lin" 20 scores)
(Table/has? "Ada" scores)
(Table/get "Ada" scores)
Table/get returns the table’s entry-vector form. Table/get* returns an
(Option V) for a checked lookup; use Table/get-unsafe when presence is
already established:
(match (Table/get* "Ada" scores)
None 0
(Some score) score)
(if (Table/has? "Ada" scores)
(Table/get-unsafe "Ada" scores)
0)
Table/update! and Table/update-or! cover common count/accumulator patterns;
Table/entries, Table/keys, Table/values, and Table/count expose its
contents. Tables support their established key representations, including
strings and closed enum tags. Use Table/new/capacity when an approximate
entry count is known, and Table/compact! to rebuild after substantial
deletion.
Sets
Set/new, Set/add!, Set/remove!, Set/has?, Set/values, and set algebra
are provided for the library’s set representation. As with tables, query the
specific function type for the accepted key kind:
que --lib types 'Set/*'
Set algebra
Set/intersection, Set/union, Set/difference, and Set/xor each create a
new set; neither input set is changed. Let A = {"red", "blue", "green"}
and B = {"green", "gold"}:
| Operation | Mathematical meaning | With A and B |
|---|---|---|
(Set/intersection A B) | values in both sets, A ∩ B | {"green"} |
(Set/union A B) | values in either set, A ∪ B | {"red", "blue", "green", "gold"} |
(Set/difference A B) | values in the first but not the second, A \ B | {"red", "blue"} |
(Set/xor A B) | values in exactly one input, (A \ B) ∪ (B \ A) | {"red", "blue", "gold"} |
(let A (Vector->Set ["red" "blue" "green"]))
(let B (Vector->Set ["green" "gold"]))
(let common (Set/intersection A B))
(let all (Set/union A B))
(let only-A (Set/difference A B))
(let exclusive (Set/xor A B))
{ (Set/has? "green" common) ; true
(Set/has? "red" common) ; false
(Set/has? "gold" all) ; true
(Set/has? "blue" only-A) ; true
(Set/has? "green" exclusive)} ; false
Set/difference is directional: swapping its arguments changes the result.
Set/xor is symmetric, so (Set/xor A B) and (Set/xor B A) contain the
same members. A set’s bucket layout does not promise a presentation order; if
you need a deterministic displayed vector, convert with Set->Vector and sort
the result.
Heap and deque
Heap/* implements a mutable binary heap using a caller-supplied comparison
predicate. Que/* provides a deque-like structure backed by vectors, with
operations such as Que/push!, Que/prepend!, Que/first, Que/last, and
Que/deque!.
These structures favor explicit mutation and predictable representation over hidden GC behavior. Use the public namespace functions rather than relying on their internal vector layout.
Matrices
Matrix/new, Matrix/in-bounds?, Matrix/for/i, and related helpers cover
nested-vector matrix work. Matrix coordinates are explicit Int values; use
the bounds helper before dynamic access when static analysis cannot prove an
index safe.
Text, numbers, and utilities
Text
Strings are [Char], and the library provides both general collection helpers
and string-specific operations:
(let fields (split "," "one,two,three"))
(join " / " fields)
(trim " Calque ")
(String/starts? "Calque" "Calque compiler")
(String/contains? "omp" "Calque compiler")
Useful conversion functions include String->Integer, Integer->String,
String->Dec, Dec->String, Char->Int, and Int->Char. Conversion is
explicit because an Int, a decimal fixed-point value, a character, and text
remain distinct static types.
Numeric helpers
In addition to primitive arithmetic, the library provides range construction, clamping, min/max, absolute value, parity predicates, bit conversion, random helpers, and decimal-specific aliases. Big integers are a library-level digit vector representation:
que --lib types 'BigInt/*'
que --lib types 'SignedBigInt/*'
They are useful when a calculation exceeds Int’s signed i32 range, but are
not a replacement for the fixed-cost behavior of normal Int arithmetic.
Dates and metadata
Date/* helpers parse and project date-like vectors. Meta/* provides simple
metadata/token helpers. These are intentionally ordinary library APIs; use the
live reference for their types and behavior before building a dependency on a
particular representation.
Testing helpers
The library contains test, test-suite/static, assert/static, and related
macros for examples and compile-time-shaped test definitions. Compiler and
runtime behavior is tested from the Rust workspace as well:
cargo test
For program-level checks, favor small .que test programs run under --debug
and, for optimized code, compare the same expected result with --opt.
Recipes
These are compact, complete patterns rather than isolated API calls. Copy one
into a .que file, run it with --debug, and adapt it to your data.
Parse lines and aggregate them
comp makes a reusable parser when the input simply flows through each stage.
The data-last collection API keeps each transformation readable:
(let parse-and-sum
(comp
trim
split/lines
(map String->Integer)
sum))
(parse-and-sum "10\n20\n12")
; 42
For file input, put read! at the front and grant the read permission:
(let sum-file
(comp
read!
trim
split/lines
(map String->Integer)
sum))
(sum-file "numbers.txt")
que sum-file.que --debug --allow read
Count occurrences with a Table
Use Table/update-or! for the common “insert an initial value or update the
existing value” pattern. The guard gives a defined result if a count reaches
the maximum Int value.
(let frequency
(lambda (words)
(let counts (Table/new))
(loop/in word words
(Table/update-or! word
(lambda () 1)
(lambda (n)
(if (+/safe? n 1) (+ n 1) n))
counts))
counts))
(let counts (frequency ["tea" "coffee" "tea" "tea"]))
(Table/get-unsafe "tea" counts)
; 3
If the approximate number of distinct keys is known, create the table with
Table/new/capacity instead. See Tables.
Model a closed state machine with enums
Enums prevent accidental use of arbitrary integers or strings as states.
=~ compares values of the same enum, while match makes rendering a state
exhaustive:
(enum Request Idle Loading Ready Failed)
(enum Event Start Succeed Fail Reset)
(let transition
(lambda (state event)
(cond
(=~ event Reset) Idle
(and (=~ state Idle) (=~ event Start)) Loading
(and (=~ state Loading) (=~ event Succeed)) Ready
(and (=~ state Loading) (=~ event Fail)) Failed
state)))
(let describe
(lambda (state)
(match state
Idle "idle"
Loading "loading"
Ready "ready"
Failed "failed")))
(describe (transition Idle Start))
; "loading"
Adding a new Request variant makes each exhaustive match site a type error
until it has a deliberate branch.
Reuse a scratch vector
Reserve storage once, refill it, then keep the capacity for the next pass. This is useful in repeated simulations and parsers with a predictable maximum batch size:
(let scratch [])
(capacity! 1000 scratch)
(loop pass (< pass 3)
(empty! scratch)
(loop i (< i 1000)
(push! (+ pass i) scratch))
(length scratch))
(length scratch)
; 1000
empty! changes the length, not the reserved backing capacity.
Dynamic programming in one vector
Many dynamic-programming problems only require the prior row or column. Keep
that state in one mutable vector rather than building a full matrix. The grid
paths example counts right/down paths and demonstrates a proof-friendly indexed
loop, capacity!, and a checked arithmetic update.
See Grid paths: mutable dynamic programming for the complete program and an explanation of its invariants.
Grid paths: mutable dynamic programming
This program counts right/down paths through a square grid. It demonstrates a small mutable vector, capacity reservation, an analyzable indexed loop, and an explicit arithmetic safety guard.
; use-strict-warnings!
; How many routes go from the top-left to the bottom-right of a 10 × 10 grid
; when each step goes only right or down?
(let SIZE 10)
(let paths [])
(capacity! (+ SIZE 1) paths)
(loop i (<= i SIZE)
(push! 1 paths))
(loop row (< row SIZE)
(loop/for col 1 (<= col SIZE) (++ col)
(let left (get (- col 1) paths))
(let current (get col paths))
(when (+/safe? current left)
(set! col (+ current left) paths))))
; 184756
(get (- (length paths) 1) paths)
The vector holds one dynamic-programming row. Initially every entry is one; each update adds the number of paths from the cell to the left to the number already stored for the cell above.
capacity! reserves room for the initial SIZE + 1 appends but does not alter
the vector’s length. The analyser can see the loop access bounds, and the
+/safe? guard gives the source-level condition for the arithmetic update.
Run the file during development with:
que grid-paths.que --debug
que explain grid-paths.que --opt
Enum-keyed table round trip
Closed enums remain typed values even though their runtime representation is a
compact i32 tag. That makes them suitable for exhaustive dispatch and fast
table keys.
; A closed enum can be used as a typed hash-table key and survives
; serialize/deserialize when the destination type is declared.
(enum Shape Rock Paper Scissors)
(sig points [[{ Shape Int }]])
(let points (Table/new))
(Table/set! Rock 1 points)
(Table/set! Scissors 2 points)
(let text (serialize points))
; `deserialize` needs a concrete expected type.
(sig restored [[{ Shape Int }]])
(let restored (deserialize text))
(let score (Table/get-unsafe Rock restored))
(match Rock
Rock score
Paper 0
Scissors 0)
The runnable source is
examples/demo/04-enum-table-round-trip.que.
From a checkout, run it with:
que examples/demo/04-enum-table-round-trip.que --debug
The [[{ Shape Int }]] annotation is only needed because deserialize needs
to know which decoder to generate. It is the current library representation of
a table: buckets containing key/value tuples. Normal table code should keep
using Table/new, Table/set!, Table/get*, and Table/get-unsafe rather
than accessing that representation directly.
Enum serialization uses declared names (Rock, Paper, Scissors), and the
decoder validates them against the expected enum. =~ compares values of this
same enum; match checks coverage of its variants.
Regular expressions
Calque’s regular-expression engine is a Thompson NFA: matching time stays predictable even for patterns that cause catastrophic backtracking in engines based on recursive backtracking.
Compile a pattern once if it is reused. String/regex/matches? requires the
whole input to match, while String/regex/contains? searches for a match
anywhere in the input. Both take their text argument last.
; Compile once when a pattern will be reused.
(let identifier (String/regex "^[a-zA-Z_][a-zA-Z0-9_]*$"))
(let candidates ["calque_2" "2calque" "with-dash"])
(let identifiers
(map
(lambda text (String/regex/matches? identifier text))
candidates))
; `contains?` searches anywhere in the text.
(let ticket (String/regex "ticket-[0-9]+"))
(let contains-ticket
(String/regex/contains? ticket "opened ticket-42 for review"))
; Invalid patterns compile to a value that can be checked safely.
(let invalid (String/regex "a{3}"))
{identifiers {contains-ticket (String/regex/valid? invalid)}}
; {[true false false] {true false}}
Run it from a checkout with:
que examples/demo/05-regex.que --debug
Supported syntax is grouping, alternation (|), *, +, ?, ., ^, $,
character classes and ranges, negated classes, and the \\d, \\D, \\w,
\\W, \\s, \\S, \\n, \\r, \\t, \\f, and \\v escapes. It is not a
PCRE implementation: counted repetition, word boundaries, backreferences,
look-around, and hexadecimal escapes are unsupported.
String/regex never throws for invalid pattern syntax. Instead,
String/regex/valid? reports false, and the matching predicates return
false. This permits dynamic patterns without making malformed input a
runtime failure.
Syntax and literals
Calque uses S-expressions. Whitespace separates forms; parentheses make a call or special form; square brackets make a vector; braces make a tuple.
(+ 1 2)
(let xs [1 2 3])
(let point {10 20})
Literals
42 ; Int
-7 ; Int
3.14 ; Dec
true ; Bool
false ; Bool
nil ; unit, type ()
'a' ; Char
'\n' ; newline Char
"hello" ; [Char]
Comments begin with ; and end at the line boundary:
; this is a comment
(let answer 42) ; so is this
Forms and patterns
(lambda (left right) (+ left right))
(let {x y} {10 20})
(let [a b] [10 20])
(let [a . tail] [1 2 3])
The final rest pattern works in let and lambda vector destructuring. It
binds the remaining tail after the fixed positions. When destructuring requires
elements, static analysis may warn unless it can prove the source vector has
sufficient length.
Operators are names
Operators are ordinary callable names in prefix position. Their suffix communicates their type family:
(+ 1 2) ; Int
(+. 1.5 2.0) ; Dec
(+# 'A' 1) ; Char arithmetic
(= 2 2) ; Int equality
(=. 2.0 2.0) ; Dec equality
(=# 'x' 'x') ; Char equality
(=? true true) ; Bool equality
Enum equality is intentionally separate: (=~ A B).
Naming conventions
Names are ordinary identifiers, so these spellings are conventions with useful semantic meaning—not a separate method syntax. Follow them for library and application APIs so callers can understand an operation before opening its implementation.
| Form | Convention | Examples |
|---|---|---|
name? | Returns a Bool; asks a question or establishes a condition. | empty?, Table/has?, +/safe?, in-bounds? |
name! | Performs an observable effect: usually mutation, sometimes host I/O. | push!, set!, capacity!, read!, println! |
name/i | An index-aware collection variant; it receives the element and its index. | map/i, select/i, every/i? |
Namespace/name | A namespace-like library family; it is still one ordinary identifier. | Table/get, String/contains?, Vector/sort! |
From->To | Explicit conversion between representations or numeric families. | String->Integer, Int->Dec, Char->Int |
name/raw | Internal or lower-level helper. Prefer the corresponding public API unless you need its precise representation contract. | Vector/append/raw! |
! does not mean only “changes its first argument.” push! and set!
mutate a collection, while read!, println!, sleep!, and random! are
also bang-named because they interact with the host. The type/effect analysis
tracks the actual mutation and I/O behavior; the suffix makes that behavior
visible at the call site.
Likewise, ? says a function’s result is a boolean predicate, not that it is
necessarily pure. A predicate can be used directly in a condition and some
recognised guards, such as +/safe? or a conventional in-bounds? helper,
can refine facts for the static analyser.
The punctuation suffixes on primitive operators select a value family:
(+ 1 2) ; Int arithmetic
(+. 1.5 2.0) ; Dec arithmetic
(+# 'A' 1) ; Char arithmetic
(= 2 2) ; Int equality
(=. 2.0 2.0) ; Dec equality
(=# 'x' 'x') ; Char equality
(=? true true) ; Bool equality
(=~ Rock Rock) ; enum equality
For the live library surface and exact inferred signatures, query the installed compiler rather than guessing from a name:
que --lib types 'Table/*'
que --lib types '*safe?'
que --lib source Vector/sort!
Quick reference
Bind and define
(let name value)
(mut name value)
(alter! name value)
(letrec name (lambda (args) body))
(sig name Type)
(enum Name [T K ...] Variant... (PayloadVariant field Type ...))
(record Name [T K ...] field Type ...)
Control
(if test yes no)
(cond test value ... default)
(when test body...)
(unless test body...)
(while test body...)
(loop i test body...)
(block body...)
(do body...)
Vectors and tuples
[a b c]
{a b}
(length xs)
(get i xs)
(set! i value xs)
(push! value xs)
(pop! xs)
(empty! xs)
(capacity! n xs)
Functions and composition
(lambda (x) body)
(lambda (x y) body)
(|> value (map f) sum)
(<| value f g)
(comp f g h)
(apply f arg...)
Static inspection
que file.que --debug
que file.que --opt
que file.que --emit types
que explain file.que --opt
que fmt file.que
que --lib types 'pattern*'
For the complete current library surface, que --lib types is the reference.
Pitfalls and style
Develop safely, release deliberately
Use --debug while building and testing. It enables configured runtime guards
and emits static-analysis findings. Use --opt once your program’s bounds and
arithmetic invariants are established, then benchmark the real workload.
Common pitfalls
dosequences but does not introduce lexical scope; useblockfor local branch/loop bindings.get,car,pop!, andpop-val!require a non-empty/in-bounds vector. In optimized code, prove or guard that fact yourself.Intis signedi32; large addition, multiplication, and division deserve an explicit invariant or a*/safe?,+/safe?, or/safe?guard.- A missing function argument is partial application, not necessarily an immediate error.
deserializeneeds a concrete expected result type; putsigimmediately before its binding.- Use
=~rather than=for values from an enum. Table/getexposes an entry-vector form. PreferTable/get*and match onNone/Some, or useTable/get-unsafeafterTable/has?if you want a value.
Style
- Prefer pipelines for a readable data transformation.
- Prefer explicit loops and mutation for a hot, allocation-sensitive kernel.
- Cache repeated lengths or computed values in hot loops.
- Use names ending in
!for mutating/effectful user functions. - Put data last in transform-style helpers and collection first in mutators.
- Start a performance-sensitive file with
; use-strict-warnings!and inspectque explainbefore treating an optimization as established. - Keep a reduced program when you find a compiler bug; debug/opt/native target agreement is part of the compiler’s correctness contract.