Quadrate Language Specification
Version 0.5.0
This document describes the Quadrate language as of toolchain release 0.5.0. The version above is the release it describes, not a number the document carries on its own.
SPDX-License-Identifier: CC0-1.0 — This specification is released into the public domain. Anyone may implement the Quadrate language without royalty or restriction.
This document provides a complete specification of the Quadrate programming language, intended for implementers who wish to create their own Quadrate compiler or interpreter.
Table of Contents
- Introduction
- Lexical Structure
- Type System
- Stack Machine Model
- Syntax and Grammar
- Control Flow
- Functions
- Structs
- Module System
- Error Handling
- Memory Management
- Built-in Instructions
- Standard Library Interface
- Runtime Requirements
- Appendix A: Grammar Summary
- Appendix B: Operator Reference
1. Introduction
Quadrate is a stack-based programming language that compiles to native code via LLVM. It combines the simplicity of stack-based execution with modern features like generics, closures, and a module system.
1.1 Design Principles
- Stack-based execution: All operations manipulate an explicit runtime stack
- Postfix notation: Operators follow their operands
- Strong typing: Types are checked at compile time with runtime validation
- Reference counting: Automatic memory management for heap objects
- Module system: Code organization with public/private visibility
1.2 Terminology
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
1.3 Execution Model
A Quadrate program MUST consist of:
1. Module imports (use statements)
2. Constant declarations
3. Struct declarations
4. Function declarations
5. A main function (entry point)
Execution MUST begin at main, which operates on a shared runtime stack.
2. Lexical Structure
2.1 Character Set
Quadrate source files MUST be UTF-8 encoded. Identifiers MUST contain only ASCII letters, digits, and underscores.
2.2 Comments
// Line comment - extends to end of line
/* Block comment
Can span multiple lines
/* Can be nested */
*/
2.3 Tokens
2.3.1 Keywords
fn def pub inline struct packed enum
type use import if else for loop
while until switch break continue return defer
const var test as
2.3.2 Predefined Constants
These identifiers are reserved and MUST evaluate to integer literals:
| Constant | Value | Description |
|---|---|---|
true |
1 |
Boolean true |
false |
0 |
Boolean false |
Ok |
0 |
The status of a fallible call that succeeded (§10.3) |
Err |
1 |
The generic error code (§10.4) |
null |
0 |
Null pointer |
Note: Ok and Err are a status and an error code, not false and true under other
names: no error is 0. null pushes 0 with pointer type for use in struct pointer fields.
2.3.3 Identifiers
identifier := letter (letter | digit | '_')*
letter := 'a'..'z' | 'A'..'Z'
digit := '0'..'9'
Naming conventions (RECOMMENDED):
- Structs: PascalCase (e.g., Point, HttpRequest)
- Constants: PascalCase (e.g., MaxSize, DefaultTimeout)
- Functions: snake_case (e.g., get_value, parse_input)
- Variables: snake_case (e.g., file_path, line_count)
- Type parameters: Single uppercase letters (T, U, V)
2.3.4 Literals
Integer literals:
integer := ['-'] ( digit+
| '0x' hex_digit+
| '0b' bin_digit+ )
Examples: 42, 0, 1000, 0xFF, 0b1010, -1, -0x10
Float literals:
float := ['-'] ( digit+ ('.' digit+)? exponent
| digit+ '.' digit+ exponent? )
exponent := ('e' | 'E') ('+' | '-')? digit+
Examples: 3.14, 0.0, 100.5, 1e3, 1.5e-3, 6.02214076e23, -2.5
A point needs a digit on each side of it: 0.5 and 5.0, not .5 or 5.. A literal
carrying a point or an exponent is an f64, so 1e3 is the float 1000.0 and 1000 is
the integer. _ is not a digit separator and there is no hex float form. A value too large
for an f64 is an error; one too small underflows to a subnormal or to zero, as the same
arithmetic does at runtime.
A leading - belongs to the literal, so 10-1 is the two literals 10 and -1 and not a
subtraction; §2.4 says what that costs.
d128 literals:
d128 := ['-'] digit+ ('.' digit+)? exponent? 'd'
Examples: 0.1d, 42d, -2.50d, 1e-40d, 6.02214076e23d
A decimal integer or float literal written hard against a d is a d128 (§3.1.2). The
digits are read in decimal, so 0.1d is exactly one tenth — which 0.1 converted to
d128 is not — and the exponent the literal is written with is kept: 2.50d prints as
2.50. A literal with more than 34 significant digits rounds to 34, ties to even. One
beyond the largest finite d128, 9.999999999999999999999999999999999e6144d, is an error,
as an out-of-range f64 literal is; one too small underflows toward zero. d is the only
suffix a number takes, and a binary literal cannot take it. A hex literal reads a d as a
digit, so 0x10d is the integer 269 and not a d128.
String literals:
string := '"' character* '"'
Escape sequences: \n, \r, \t, \\, \"
Examples: "hello", "line1\nline2"
String interpolation:
interp_string := '$"' (character | '{' (identifier | scoped_id) '}')* '"'
Interpolated strings are prefixed with $. Each {...} names one value -- a local, a
constant, or a module-qualified name such as math::Pi -- which is converted to a string
whatever its type. It is a name, not an expression: {x + y} is an error naming the
undefined identifier x + y; compute the value into a local first. The compiler desugars
$"..." into sb::new / sb::append / sb::finish calls (the sb module is
auto-imported).
Examples:
$"Hello, {name}!" // A local
$"{first} {last}" // Several names
$"Age: {age}" // An integer, converted to a string
$"pi={math::Pi}" // A module-qualified constant
2.3.5 Operators and Punctuation
Arithmetic operators:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
Comparison operators:
< Less than
> Greater than
== Equal
!= Not equal
<= Less than or equal
>= Greater than or equal
Other operators:
++ Increment
-- Decrement
<< Field access (read): struct <<field
>> Field set (write): struct value >>field (writes the field, pushes the same struct back)
-> Local variable binding
:: Scope resolution
& Function value prefix: `&name` is the named function as a value
! Abort-on-error suffix
Punctuation:
: Type annotation
, Type parameter separator
( ) Function signatures
{ } Blocks
[ ] Array literals
Note: and, or and not are the logical operators and MUST use named forms (no
symbolic equivalents). The bitwise operations of the same names live in the bits module
as bits::and, bits::or, bits::xor and bits::not, and the shifts with them as
bits::shl and bits::shr. The arithmetic and comparison operators MUST be written as
symbols; they have no word forms.
2.4 Whitespace
Whitespace (spaces, tabs, newlines) separates tokens. Indentation MUST NOT be syntactically meaningful, and no construct is delimited by a line break.
Whitespace is not, however, insignificant everywhere. Two rules read it, and both are normative:
- Adjacency after
](§3.2.2). A type name or a[written immediately after a], with no whitespace, makes the brackets a size rather than a list of elements.[3]i64is an array of three zeros;[3] i64is the one-element array[3]followed by the identifieri64. Two array literals in a row MUST therefore be separated by whitespace. - A leading
-on a numeric literal (§2.3.4). The sign belongs to the literal, so10 1 -subtracts and10-1pushes the two literals10and-1. An implementation SHOULD diagnose the second form, which reads as subtraction to anyone arriving from an infix language.
3. Type System
3.1 Primitive Types
Implementations MUST support these five primitive types:
| Type | Description | Size |
|---|---|---|
i64 |
Signed 64-bit integer | 8 bytes |
f64 |
IEEE 754 double-precision float | 8 bytes |
d128 |
IEEE 754 decimal128 float (§3.1.2) | 16 bytes |
str |
Immutable UTF-8 string | pointer |
ptr |
Raw memory address (§3.5.1) | 8 bytes |
Note: Arithmetic, comparison, and all stack operations operate on i64, f64 and d128
only; implementations MUST NOT introduce narrower stack types. Narrower widths exist solely
as memory-layout annotations — see §3.1.1. A stack slot is wide enough to hold a d128 in
place, so a d128 is copied by value and needs no reference counting; a str is held by
reference.
Strings are UTF-8, and their unit is the codepoint. Every index and length a string
operation takes or returns MUST count codepoints, not bytes: "héllo" len is 5, and
strings::char_at 1 is U+00E9, not the byte 0xC3 that happens to begin its encoding. No
string operation may produce invalid UTF-8; an operation that would cut a multi-byte sequence
MUST instead act on whole characters. strings::data exposes the underlying bytes for the
callers that genuinely need them, and is the only place byte extent is visible.
Implementations SHOULD decode malformed input rather than reject it — a string can arrive from
a file, a socket or argv — by treating each byte that is not part of a well-formed sequence
as one character. Whatever they accept, their output MUST be well-formed.
bool is an alias for i64, as if every program began with type bool = i64: it MUST be accepted wherever a type is written, and means i64 there.
3.1.1 Sized Integer Types
Implementations SHOULD support the following sized integer types. They describe the width of a value in memory, not on the stack, and exist so that programs can match byte-exact binary layouts (on-disk formats, network headers, MMIO registers):
| Type | Description | Size |
|---|---|---|
i8 / u8 |
8-bit signed / unsigned integer | 1 byte |
i16 / u16 |
16-bit signed / unsigned integer | 2 bytes |
i32 / u32 |
32-bit signed / unsigned integer | 4 bytes |
u64 |
64-bit unsigned integer | 8 bytes |
They are valid as struct field types (§8) and as the width selector on raw memory accessors
(mem::get_u8, mem::set_i16, and the rest of that family), and an implementation MUST reject
them anywhere else — a parameter, a return value, a module-level var, a cast target. In each
of those the value is a 64-bit stack slot and the annotation has no width to describe; accepting
it there states a constraint the implementation does not keep. To keep the low bits of a value,
mask it (value 255 and).
Load and store semantics. At a memory boundary:
- A store MUST truncate the 64-bit stack value to the field's width, keeping the low N bits.
Storing a negative value into an unsigned field is therefore a bit-pattern reinterpretation,
not an error:
-1into au8stores0xFF. - A load MUST widen back to 64 bits: signed types sign-extend, unsigned types zero-extend.
The same byte read through an
i8field and au8field yields-1and255respectively.
Layout. In an ordinary struct, every field MUST occupy an 8-byte slot regardless of its
declared width. In a packed struct (§8), fields MUST be laid out adjacent at exactly their
declared widths with no padding, in target byte order.
u64 caveat: because a stack element is always i64, a u64 value above 2^63-1 loads as
a negative i64 with the same bit pattern. Bitwise operations behave as expected; comparison
operators treat it as signed.
3.1.2 d128
d128 is the IEEE 754-2008 decimal128 format: 34 significant decimal digits, exponents from
-6143 to +6144 for a normal value and down to -6176 for a subnormal one, signed zeros,
infinities and NaN. It is decimal so that what a program prints is exactly what it holds:
0.1d 0.2d + is 0.3 and equals 0.3d, where 0.1 0.2 + is not 0.3.
Implementations MUST round every d128 result to the format with roundTiesToEven, as IEEE
754 requires of each operation. + - * /, neg and the comparisons take d128 operands;
the remaining IEEE operations and the elementary functions are the decimal module (§13.9).
An i64 widens to a d128 exactly, since it has at most 19 of the 34 digits: an arithmetic
or comparison instruction with one d128 operand and one i64 operand is a d128 operation,
2 1.5d + being 3.5, and an i64 argument to a d128 parameter is widened at the call. An
f64 does not mix. An instruction with one d128 operand and one f64 operand is a
compile-time type error, as is an f64 argument to a d128 parameter: letting the f64 in
would bring back the binary rounding the type exists to keep out. cast<d128> converts
explicitly, and a literal is written with its d.
An implementation MAY offer a setting under which a decimal float literal written without a
d is a d128 literal, as if it had one: 1.5 then means 1.5d, while integer literals
stay i64. It is for a calculator, where every number typed should be decimal. quadc
--default-float d128 applies it to the files named on the command line, not to the modules
they import, and an embedder of the interpreter sets it with qd_interp_set_default_float.
A value keeps the exponent it was written or computed with, as IEEE decimal arithmetic
requires: 1.10d 1.20d + is 2.30, which equals 2.3d but prints with its trailing zero.
decimal::reduce strips trailing zeros and decimal::quantize sets a number of decimal places.
Division by zero and overflow are defined, as for f64: 1d 0d / is inf and 0d 0d / is
NaN. NaN compares unequal to everything including itself, so != of a NaN is 1.
A d128 prints in the IEEE to-scientific-string form: the digits held, with an exponent
once it is positive or the value is smaller than 1e-6 — 1.10, 1.5e+40, 1e-7 —
and infinity and NaN spelled as f64 spells them, inf, -inf and nan.
%, ++ and -- are integer and f64 operations and reject d128; decimal::fmod
and decimal::remainder are its remainders.
3.2 Composite Types
3.2.1 Structs
User-defined composite types with named fields:
struct Point {
x:f64
y:f64
}
struct Person {
name:str
age:i64
}
A struct value on the stack MUST be a counted reference to the struct, not a ptr
(§3.5.1): its slot owns a reference, and copying, binding and dropping it move the struct's
count (§11.2.2). Implementations MUST reject a struct supplied where a ptr is declared, and
MUST accept nothing but a value of that struct type, or null, where a struct type or a *T
is declared — an arbitrary raw ptr is not one, since nothing would say the memory behind it
holds a T with a count to move.
3.2.2 Arrays
Dynamic arrays are created by an array literal. There is no creation instruction.
A literal's brackets hold either elements or a size, and which one MUST be decided by
what follows the ]: a type name immediately after it, with no intervening whitespace, makes
the brackets a size. Anything else makes them elements.
[1 2 3 4 5] // Integer array
[1.0 2.0 3.0] // Float array
["a" "b" "c"] // String array
[[1 2] [3 4]] // Nested array
[x 2 3] // A local as an element
[P { x = 1 }] // Struct literals as elements
[] // No elements; element type adopted on first append
An element MAY be any expression that pushes one value, not only a literal: a local, a nested array literal or a struct literal. All elements MUST have the same type -- an array carries one element type, adopted from the first value stored -- and a literal whose element types disagree is a compile-time error where they are known.
[10]i64 // Ten elements, each the zero value of i64
[]i64 // The size omitted, so zero of them: an empty []i64
[src len]i64 // The size MAY be any expression leaving one i64
The zero value MUST be 0 for the integer types and bool, 0.0 for f64, 0 for d128, an empty string
for str, null for ptr, and for a function type fn(...) a null function value, so
[n]fn(i64 -- i64) is a table of n empty entries to fill with set; calling one that was
never filled MUST stop the program with a fatal "NULL function value". For a struct type, [n]T MUST produce n distinct instances,
each constructed as T {}; it is therefore well-formed exactly where T {} is, which
requires every field of T to declare a default. For an array element type, [n][]T MUST
produce n distinct empty arrays, on the same principle: the zero of an array is an empty
one. For a type parameter of the enclosing generic function, the element type is not known at
run time and the array MUST adopt one from the first value appended.
[n]T is an expression, not a type. Arrays are dynamic and []T is the only array type, so
[10]i64 and []i64 both produce a value of type []i64 and a size MUST be rejected
wherever a type is expected.
The element type MAY itself be an array, so [][]i64 is the type of an array of []i64, and
[n][]i64 builds one. A [ hard against a ] is an element type by the same adjacency rule
a type name is, so two array literals written in a row MUST be separated by whitespace.
[][]i64 // The type: an array whose elements are []i64
[2][]i64 // Two distinct empty []i64
[[1 2] [3 4]] // Two []i64 with elements, an expression of type [][]i64
[1 2] [3 4] // Two array literals, which the space is what makes them
An array value on the stack MUST be a counted reference to the array, not a ptr (§3.5.1),
and its type is written []T (e.g., []i64, []f64, []str, []mod::Point, [][]i64).
An array carries its element type, and for elements that are references, which kind they are
(§11.5).
Implementations MUST reject a []T supplied where a parameter, output or struct field is
declared ptr. The reference addresses the array's header, not its elements, so a function
that takes a raw buffer would read and write the header rather than the data. A raw buffer and
the length beside it remain the way to pass elements:
fn sum(arr:ptr count:i64 -- total:i64) // a raw buffer
fn sum(arr:[]i64 -- total:i64) // an array; `arr len` gives the count
[]ptr is an array of raw memory addresses and holds nothing else: set and append MUST
check that what they store into an array of references is of the kind the array already holds,
and reject a struct, an array or a function value stored into a []ptr, as they reject a raw
ptr stored into an array of structs.
3.3 Generic Types
Functions and structs can be parameterized over types:
fn identity<T>(x:T -- y:T) {
}
struct Box<T> {
value:T
}
struct Pair<A, B> {
first:A
second:B
}
Type parameters SHOULD be single uppercase letters or short uppercase names.
A field whose type is a type parameter MUST hold a whole stack slot, the value with its type and,
for a reference, its kind, and MUST own a reference to it as any field holding a reference does
(§11.2.2): Box<Point> keeps its point alive, and Box<i64> holds a plain number.
3.4 Function Types
A function value is a named function or an anonymous function (§7.5) held as a value. Its
type MUST be written with the typed fn(...) syntax:
fn apply(x:i64 f:fn(i64 -- i64) -- result:i64) {
call
}
// Get a function value
&double -> f
The fn(...) type specifies the full signature of the function value, including parameter types
and return types. A function value is counted, as a struct is: a closure owns its captures
(§11.6), and the slot, local, field or element holding it owns a reference (§11.2.2). &name
gives a static function value, which captures nothing and is never freed, so counting it is a
no-op. A function value MUST NOT be passed, stored or returned as a ptr (§3.5.1), and a raw
ptr MUST NOT be passed where a function value is declared nor called: call on a ptr MUST
be a compile-time error.
A parameter in a function type MAY carry a name, fn(x:i64 -- r:i64). The name documents it and
is not part of the type.
3.4.1 Stack Variables
A function type of fixed arity leaves the rest of the stack as it was, whatever that is, so
fn(T -- U) already works on any stack. A stack variable names that rest, so that a
function can say its function value takes or leaves however many values the caller gives it:
// The builtin `dip` (7.7), written as a function
fn under<..a, ..b, T>(..a x:T q:fn(..a -- ..b) -- ..b x:T) {
-> q -> x
q call
x
}
fn main() {
1 2 3 fn (a:i64 b:i64 -- s:i64) { + } under // 3 3: + runs under the 3
print " " print print nl
}
A stack variable is .. followed by a name. It MUST be declared in the <...> list with the
type parameters, and MAY appear only as the first element of a signature's inputs or outputs, or
of a function type's inputs or outputs; a list has at most one. An implementation MUST reject a
stack variable that is used without being declared, or declared without being used.
In a function type, fn(..a x:T -- ..b) is a function value that consumes the values ..a
stands for and an x, and leaves the values ..b stands for. In a signature, the variable at
the bottom of the inputs is the part of the caller's stack below the named inputs that the
function reaches into, and the one at the bottom of the outputs is what it leaves there.
At a call, the stack variables are bound by unifying each function-typed parameter with the
function value passed for it: the tops of the lists are matched type by type, and a stack
variable is bound to what is left below them. A function type written without a stack variable
has one implicitly, the same for its inputs and its outputs: fn(T -- U) is fn(..r T -- ..r U)
for a fresh ..r. After binding, a variable that is the same at the bottom of the call's inputs
and outputs is the part of the stack the call does not touch, and cancels; what remains is a
fixed effect. An implementation MUST reject a call whose stack variable no function argument
binds, since how far it reaches cannot be known.
In a body, the modelled stack stands on the input variable: the body MAY move the values above it but MUST NOT reach into it, which is an underflow. Calling a function value whose type reaches into that variable MUST find nothing else above it, and replaces it with the value's output variable; this MAY change the variable only at the top level of the body, not inside a branch or loop. The body MUST end on the declared output variable.
A fallible function MUST NOT have stack variables: its failure exit restores a depth computed from its parameters (§10.3), and a stack variable has no depth until the call.
3.5 Special Types
| Type | Description |
|---|---|
any |
Wildcard type for operations accepting any type |
A value of type any carries its type with it, so a parameter of type any accepts every value. Passing an any on to a parameter of a definite type is checked when the call runs: the value MUST hold that type, or an i64 where the parameter takes f64 or d128, which widens as a plain i64 argument does. Anything else MUST stop the program with a type mismatch naming the function and the parameter.
fn next(x:i64 -- r:i64) { 1 + }
fn relay(a:any -- r:i64) { next }
1 relay print nl // 2
"two" relay print nl // fatal: Type mismatch for parameter 1 (expected int, got str)
3.5.1 ptr
A ptr is raw memory: an address the program allocated (mem::alloc), took from a string
(strings::data), or was handed by a native library. Nothing is counted behind it, and the
runtime MUST NOT retain or release one. A struct, an array, a string and a function value are
counted objects and MUST NOT be passed, stored or returned where a ptr is declared;
implementations MUST reject it at compile time, and MUST reject a ptr passed where a
function value, a struct or a *T is declared. null is a ptr, and is the one ptr also
accepted wherever a struct type or a *T is (§3.2.1); var p = null declares a global that
holds one.
Memory reached through a ptr holds raw words. mem::get_ptr reads a raw ptr back from it,
never a struct or an array; a struct kept in raw memory goes through mem::set_any and
mem::get_any, whose tagged slot keeps the value's type and owns a reference to it (§11.2.2).
3.6 Null
The null keyword pushes the integer value 0 with pointer semantics. It is used to represent the absence of a value, particularly for pointer-typed struct fields.
3.6.1 Value Semantics
null MUST evaluate to 0 and MUST be comparable with standard integer operations:
null 0 == if { "true" print nl } // true — null equals 0
42 null != if { "true" print nl } // true — non-zero is not null
null print nl // prints: null, as any null ptr does
3.6.2 Pointer Fields
null is used to initialize pointer-typed struct fields to indicate "no value":
struct Node {
value:i64
next:*Node
}
Node { value = 10 next = null } -> a
Node { value = 20 next = a } -> b
b <<next <<value print nl // 10 — follow pointer chain
A *T field holds either a T, as a counted reference the field owns (§11.2.2), or null;
an implementation MUST reject any other ptr stored into it (§3.2.1). *T is valid only as the
type of a struct field, and MUST be rejected as the type of a parameter, an output, a local or a
global, where the struct type T itself is written.
null MAY also be used as a default value in struct field definitions:
pub struct Crc32 {
state:i64 = 4294967295
tbl:ptr = null
}
3.6.3 Switch Behavior
In switch statements, null matches the 0 case. There is no special null case:
null switch {
0 { "null/zero" print nl }
_ { "other" print nl }
}
// prints: null/zero
3.7 Type Coercion
Explicit casting via cast<Type>:
3.14 cast<i64> // Float to int (truncates toward zero)
42 cast<f64> // Int to float
42 cast<d128> // Int to d128 (exact)
0.1 cast<d128> // f64 to d128: its binary value, 0.1000000000000000055511151231257827
2.5d cast<f64> // d128 to the nearest f64
100 cast<str> // Any to string
cast<i64> of a d128 truncates toward zero and, being total, saturates at the i64
limits and turns NaN into 0. There is no cast between d128 and ptr.
cast<ptr> of a struct or an array gives its raw address, and the result is a raw ptr
(§3.5.1): it gives up the reference its slot held, so the address keeps nothing alive and is
valid only while some other reference does.
cast<T> MUST be total: every conversion it offers always produces a value, so its result
never needs to be checked. A string MUST NOT be cast to a numeric type -- parsing can fail
and cast has nowhere to report it. Implementations MUST reject "42" cast<i64> and
"42" cast<f64> at compile time; strconv::atoi, strconv::parse_int,
strconv::parse_float, strconv::parse_d128 and strconv::parse_bool are the fallible
conversions.
Implicit coercion: Implementations MUST NOT perform implicit type coercion, with one
exception: an i64 widens to f64 or d128 where it meets one, as an operand of arithmetic or
comparison (§12.1, §3.1.2), as an argument to a parameter of that type, or as a struct field of
that type (§8.2). Every other conversion MUST be explicit.
4. Stack Machine Model
4.1 Runtime Stack
The Quadrate runtime MUST maintain a single data stack shared across all function calls.
Stack element structure:
// C
struct qd_stack_element {
union {
int64_t i; // Integer value
double f; // Float value
void* p; // Pointer value
qd_string_t* s; // String reference
qd_d128_t d; // d128 value, held in place
} value;
qd_stack_type type; // Type tag: INT=0, FLOAT=1, PTR=2, STR=3, D128=4
bool is_error_tainted; // Error propagation flag
uint8_t ptr_kind; // For PTR: RAW=1, STRUCT=2, ARRAY=3
};
A slot of type PTR MUST record what it points at. A raw ptr (§3.5.1) has nothing to count,
and the slot neither retains nor releases it. A struct, a function value (which is a counted
struct) and an array are counted references: the slot owns one, and copying or dropping the
slot moves the count (§11.2.2). Whatever writes a PTR slot writes its kind with it, so the
runtime never has to look an address up to learn what it is.
4.2 Stack Operations
All operations MUST be postfix. Arguments MUST be popped from the stack, and results MUST be pushed.
Duplication:
| Operation | Stack Effect | Description |
|---|---|---|
dup |
( a -- a a ) |
Duplicate top |
dup2 |
( a b -- a b a b ) |
Duplicate top two |
Swapping:
| Operation | Stack Effect | Description |
|---|---|---|
swap |
( a b -- b a ) |
Swap top two |
Removal:
| Operation | Stack Effect | Description |
|---|---|---|
drop |
( a -- ) |
Remove top |
drop2 |
( a b -- ) |
Remove top two |
nip |
( a b -- b ) |
Remove second |
Rearrangement:
| Operation | Stack Effect | Description |
|---|---|---|
over |
( a b -- a b a ) |
Copy second to top |
rot |
( a b c -- b c a ) |
Rotate three |
rrot |
( a b c -- c a b ) |
Rotate three the other way |
rot4 |
( a b c d -- b c d a ) |
Rotate four |
rrot4 |
( a b c d -- d a b c ) |
Rotate four the other way |
tuck |
( a b -- b a b ) |
Copy top below second |
pick |
( x y z -- x y z x ) |
Copy the third value to the top |
Every stack word has a fixed effect. A word whose depth comes from a value on the stack cannot be
given one, so an implementation cannot say what the code around it leaves — pick therefore
copies the third value rather than an indexed one, and there is no roll; rot4 and rrot4 reach
the fourth value, a fixed depth like the rest. Deeper than that, the values are named with ->
(§4.4).
4.3 Stack Effect Signatures
Functions declare their stack effects:
fn name(input1:type1 input2:type2 -- output1:type1 output2:type2)
- Left of
--: Parameters consumed from stack (bottom to top) - Right of
--: Values produced on stack (bottom to top)
Examples:
fn add(a:i64 b:i64 -- sum:i64) // Consumes 2, produces 1
fn swap_pair(a:i64 b:i64 -- b:i64 a:i64) // Consumes 2, produces 2
fn print_value(x:i64 -- ) // Consumes 1, produces 0
fn get_constant( -- c:i64) // Consumes 0, produces 1
4.4 Local Variables
The -> operator pops values into named local variables:
fn example( -- result:i64) {
10 20 // Push two values
-> b // Pop top into b
-> a // Pop next into a
a b + // Use variables
}
The input parameters of a def are bound on entry, so it MUST NOT re-bind them with ->.
The parameters have already been consumed from the stack, and attempting -> x for a declared
parameter x is a stack underflow:
def good(x:i64 y:i64 -- result:i64) {
x y + // Parameters are already in scope
}
def bad(x:i64 -- result:i64) {
-> x // ERROR: nothing left on the stack to bind
x 2 *
}
A fn (§5.7) binds nothing: its inputs stay on the stack for the body to work
on, and any names they carry are documentation that is NOT in scope. A body MAY therefore bind a
local of the same name:
fn scaled(value:i64 -- result:i64) {
10 * // The argument is on the stack, `value` is not in scope
-> value // ... until the body binds a local of that name
value 1 +
}
Variables MUST be stored in function-local allocas and MAY be referenced multiple times.
Binding multiple values:
10 20 30 -> z -> y -> x // Each -> binds one value: z=30, y=20, x=10
Note: Each -> MUST bind exactly one value. Multiple values require multiple -> operators.
5. Syntax and Grammar
5.1 Program Structure
program := declaration*
declaration := use_statement
| const_declaration
| var_declaration
| enum_declaration
| type_alias_declaration
| struct_declaration
| function_declaration
| import_declaration
| test_declaration
5.2 Use Statements
use module_name // Import module by name
use "path/to/file.qd" // Import file by path
use "./relative/path" // Relative import
5.3 Constant Declarations
const NAME = literal
const PI = 3.14159
const MESSAGE = "hello"
const FROM_ENV = env("VAR_NAME")
const WITH_DEFAULT = env("VAR", "default")
5.4 Enum Declarations
[pub] enum Name {
Variant1 // 0
Variant2 // 1
Variant3 = 10 // explicit value
Variant4 // 11 (auto-increment from previous)
Variant5 = -1 // negative values allowed
}
Enums define scoped named integer constants. Each variant is an i64 value, fully interchangeable with i64 in all operations (arithmetic, bitwise, comparison).
5.4.1 Value Assignment
- Variants auto-increment from
0unless explicitly assigned - After an explicit value, auto-increment continues from that value + 1
- Negative values are allowed
- Each enum has independent numbering
enum Color { Red Green Blue } // Red=0, Green=1, Blue=2
enum Token { Int Float Str = 10 Ident } // Int=0, Float=1, Str=10, Ident=11
enum Result { Err = -1 Ok = 0 Warn } // Err=-1, Ok=0, Warn=1
5.4.2 Variant Access
Access variants with EnumName::Variant:
Color::Red print nl // 0
Color::Blue print nl // 2
From imported modules, use triple-scoped access: module::EnumName::Variant:
use mymod
mymod::Status::Ok print nl
5.4.3 Visibility
Use pub enum to export an enum from a module. Without pub, the enum is private to its module:
pub enum Status { Ok Error Pending } // Accessible from other modules
enum Internal { A B C } // Private to this module
5.4.4 Operations
Enum values are i64 and support all integer operations:
use bits
enum Perm { None Read = 1 Write = 2 Execute = 4 All = 7 }
// Arithmetic
Perm::Read Perm::Write + print nl // 3
// Bitwise (flags/bitmasks)
Perm::All Perm::Execute bits::and print nl // 4
// Comparison
Color::Red Color::Blue < print nl // 1
5.4.5 Switch on Enums
Enum variants can be used as switch cases:
direction switch {
Direction::Up { "up" print nl }
Direction::Down { "down" print nl }
Direction::Left { "left" print nl }
Direction::Right { "right" print nl }
_ { "unknown" print nl }
}
Since enums are i64, a non-enum integer value will match if it equals a variant's numeric value. The wildcard _ case handles unmatched values.
5.4.6 Enums in Structs
Enum values can be stored in struct fields (typed as i64):
struct Token {
kind:i64
value:i64
}
Token { kind = TokenType::Int value = 42 } <<kind TokenType::Int == if { "integer token" print nl }
5.4.7 Compile-Time Validation
Implementations MUST reject:
- Duplicate enum definitions: Two enums with the same name in the same scope
- Unknown variants: Accessing a variant that does not exist in the enum (e.g., Color::Yellow when Yellow is not defined)
5.5 Type Alias Declarations
[pub] type Name = ExistingType
Type aliases create a new name for an existing type. The alias is fully interchangeable with its underlying type.
type Transform = fn(i64 -- i64)
type IntList = []i64
pub type Callback = fn(str -- bool)
Type aliases are resolved at compile time and carry no runtime overhead. They are especially useful for giving readable names to complex function types.
5.6 Struct Declarations
[pub] [packed] struct Name [<TypeParams>] {
field1:type1
field2:type2 = default_value
field3:*StructName // Pointer type
}
packed: lays fields out adjacent at their exact declared widths with no padding (§8.1). Without it, every field occupies an 8-byte slot.
5.7 Function Declarations
[pub] [inline] fn name [<TypeParams>] (params -- returns) [!] {
body
}
[pub] [inline] def name [<TypeParams>] (params -- returns) [!] {
body
}
pub: Makes function publicly accessible from other modulesinline: Requests the compiler to inline the function at call sites, eliminating call overhead. The compiler will inline in most cases, but may decline for recursive functions or indirect calls. Useful for small wrapper functions. Aninline fnSHOULD be replaced by its body where the body can stand in the caller unchanged -- afn(not adef), neither fallible, generic nor a method, whose body declares no local and has noreturnordefer-- so that a word factored into smaller words costs what it would written out in one piece, whatever results the smaller words leave. That holds for a call in the declaring file and in the files sharing its names (§9.7), and for a call of a module's word asmodule::namewhen its body names only the module's functions and constants, which then keep their meaning by their qualified names; a body that reads a field, calls a method, names a global or takes&nameis resolved in its module, and is called.fn: The inputs stay on the stack for the body to work on (§4.4); names on them are documentation and are not in scope, so naming is optional and naming some inputs and not others is permitted.def: Each input parameter is bound as a local at entry and taken off the stack, so the body starts on an empty stack and reads its inputs by name. Every input MUST be named, since each is bound, and adefMUST declare at least one input.<TypeParams>: Generic type parameters, and stack variables (..a, §3.4.1)!: Marks function as fallible (can fail with error)
pub comes first, then inline, then fn or def. A receiver (§7.4) is always bound, in a
fn as in a def.
An identifier in the body of a fn that names one of its inputs, and nothing else in scope,
MUST be reported as an input that is not bound, with a hint to write def.
5.8 Import Declarations (FFI)
import "library.a" as "namespace" {
[pub] fn funcname(params -- returns) [!]
...
}
Import blocks declare bindings to native C functions. Only function declarations are allowed inside the block. Constants associated with the library (such as error codes) should be declared at module top-level using pub const.
5.9 Test Declarations
test "test name" {
// test body
}
6. Control Flow
6.1 If-Else
Condition MUST be popped from stack; non-zero MUST be treated as truthy:
condition if {
// then branch
} else {
// else branch (optional)
}
Chained conditions:
x 10 > if {
"greater than 10"
} else {
x 5 > if {
"greater than 5"
} else {
"5 or less"
}
}
6.1.1 Branch stack effects
Both arms of an if/else MUST leave the stack at the same depth. An implementation MUST
reject a program whose arms disagree:
// doccheck: expect-error arms leave 1 and 2 values respectively
fn choose(c:i64 -- r:i64) {
if {
1
} else {
2 3
}
}
fn main() {
1 choose print nl
}
This is the one place where the declared stack effect cannot be checked by eye, and where an
unreported mismatch is not merely unchecked but wrong: whatever follows the if reads a value
whose identity depends on which arm ran.
One case is exempt, because the arm never reaches the merge point:
- A diverging arm. An arm containing a top-level
return,panic,breakorcontinuenever reaches the merge point and contributes no stack effect, so the guard idiomc if { "..." panic }is unaffected whatever the other arm leaves. Any statement after the diverging one is unreachable and does not count.
An if testing a bare fallible call (§10.3) is no exception. Both arms start from the same
stack, the call's results, which on failure are zero values; the arm that does not use them
drops them, and an arm that forgets is the mismatch this rule reports:
// doccheck: expect-error the success arm consumes the result, the failure arm leaves it
fn divide(a:i64 b:i64 -- result:i64)! {
dup 0 == if { "division by zero" -1 panic }
/
}
fn main() {
10 2 divide ok if { print nl } else { "failed" print nl }
}
An if without an else is an if whose other arm is empty, so the same rule binds it: its
then-arm MUST leave the stack at the depth it found it, and an implementation MUST reject an arm
that does not. The reasoning is the one above — the arm may not run, so what follows cannot read
a value whose presence depends on it — and the exemption for a diverging arm applies here too.
6.2 For Loops
start end step for iterator {
// body - iterator is available as local
}
Stack: MUST pop step, end, start from stack.
The iterator MUST start at start and advance by step, and end is exclusive: the loop runs
while the iterator is below end for a positive step, and above it for a negative one. 0 10 1
for runs for 0 through 9, and 10 7 -1 for for 10, 9 and 8.
0 10 1 for i {
i print nl
}
// Reverse iteration: 10 down to 1
10 0 -1 for i {
i print nl
}
6.3 Infinite Loops
loop {
// body
// must use 'break' to exit
}
6.4 Conditional Exits
while and until are words with the effect ( flag -- ), written inside the body of a loop
or for. Each pops a flag and either leaves the innermost loop or lets the body go on:
| Word | Leaves the loop when the flag is |
|---|---|
while |
zero |
until |
non-zero |
The condition is whatever precedes the word, as for any other word; nothing is delimited by looking backwards, so values below it on the stack are no concern of the loop's. Where in the body the word is written decides the shape of the loop:
0 loop { dup 5 < while dup print nl 1 + } drop // tested first: may run no times
0 loop { 1 + dup 3 >= until } drop // tested last: runs at least once
Leaving by while or until is a break taken with the stack as it stands after the flag is
popped (§6.6), and is checked as one: in a loop every exit MUST leave the same depth, and in a
for it MUST leave the depth the loop head had. Pending defers run as for break. When the loop
goes on, the rest of the body runs on that same stack.
An implementation MUST reject while or until outside a loop or for. A switch is not a
loop, so one inside a switch with no loop around it is an error.
6.5 Switch-Case
value switch {
1 { "one" }
2 { "two" }
3 { "three" }
_ { "other" } // Default case (wildcard)
}
Cases can match:
- Integer literals
- String literals
- Constants (including scoped: module::Constant)
- Wildcard _ for default
6.5.1 Arm stack effects
The rule of §6.1.1 applies to switch arms: every arm that reaches the merge point MUST leave
the stack at the same depth, and an implementation MUST reject a program whose arms disagree.
Diverging arms are exempt as for if. A switch with no _ arm may match nothing, in which
case no arm runs; its arms MUST therefore leave the stack at the depth it had before the
switch. After a bare fallible call (§10.3) every arm starts from the call's results, which
are zero values in the arms a failure reaches.
6.6 Break and Continue
break // Exit innermost loop
continue // Skip to next iteration
flag while // Exit innermost loop if flag is zero (§6.4)
flag until // Exit innermost loop if flag is non-zero (§6.4)
All four act on the innermost loop or for. A switch is not a loop: written in a switch
arm, they act on the loop around the switch, and an implementation MUST reject them in a
switch that has no loop around it.
6.7 Defer
Deferred code MUST execute when scope exits in LIFO order:
fn process() {
resource_open -> handle
defer { handle resource_close }
// ... work with handle ...
// cleanup runs automatically
}
Multiple defers execute in reverse order:
fn example() {
defer { "third" print nl }
defer { "second" print nl }
defer { "first" print nl }
}
// Prints: first, second, third
6.7.1 Registration
A defer MUST be registered when control reaches the statement, not merely because the
statement appears in the function. A defer written inside a branch that was not taken, or
after a point from which the function already returned, MUST NOT run:
fn open_maybe(c:i64 -- ) {
if {
acquire -> r
defer { r release } // registered only when c is non-zero
}
// if c was zero, nothing is released -- nothing was acquired
}
This is what makes defer usable for cleanup in a switch arm: the arm that acquires the
resource is the arm that registers its release, and the failure arms register nothing.
The same applies to ? (§10.3). A ? that propagates out of the function before reaching a
defer MUST NOT run that defer:
fn use_it( -- )! {
open? -> f // if this propagates, the defer below is never registered
defer { f close }
// ... work with f ...
}
Deferred code registered inside a loop body MUST run at the end of the iteration that
registered it, and MUST NOT carry over to a later iteration that does not reach the statement
again. break and continue MUST run the deferred code registered so far in that iteration
before transferring control.
7. Functions
7.1 Function Definition
[pub] fn name [<T, U>] (input_params -- output_params) [!] {
body
}
7.2 Function Calls
Functions are called by name; arguments must already be on stack:
10 20 add // Call 'add' with 10 and 20 on stack
"hello" print // Call 'print' with string on stack
Module-qualified calls:
3.14 math::sin // Call 'sin' from the 'math' module
"hello" strings::upper // Call 'upper' from the 'strings' module
len is a builtin (§12.5), not a module's function, and is called unqualified: "hello" len.
7.3 Generic Functions
fn identity<T>(x:T -- y:T) {
}
fn pair<A, B>(a:A b:B -- first:A second:B) {
}
Type parameters are inferred from arguments at call sites.
7.4 Methods
Methods are functions with a receiver parameter in parentheses before the function name:
struct Vec2 { x:f64 y:f64 }
fn (v:Vec2) length( -- len:f64) {
v <<x v <<x * v <<y v <<y * + math::sqrt
}
// Call as method
vec length
7.5 Anonymous Functions (Closures)
fn (params -- returns) [!] { body }
def (params -- returns) [!] { body }
fn { body }
An anonymous function is a function that has no name. Every rule in §5.7 about a named function's parameters, body and fallibility applies to it unchanged, and an implementation MUST NOT accept in one what it rejects in the other:
- A
fnleaves the inputs on the stack, and naming is optional. - A
defbinds them: every input MUST be named, and each name is bound as a local at entry, so the body reads its arguments by name and does not find them on the stack. AdefMUST declare at least one input. !marks it fallible. Only then may its bodypanic, and acallon it MUST be written!,?, or read as a status:ok/failthenif, orswitch(§10.3) — the rule that governs a call to a fallible name. Without!acallon it is an ordinary call, and!or?there is an error.- The body MUST leave exactly what the signature declares, counted and typed as §5.7 requires.
- A parameter's type MUST be a valid type name, and a name that is not one is an error. An unused named parameter is diagnosed the same way it is in a named function: a warning, not an error, so the program still compiles.
A bare identifier in the parameter list is a type, as it is in a named function's parameter
list: fn (Point -- r:f64) takes a Point. It does not declare a parameter called Point.
Implicit capture: Variables from the enclosing scope MUST be automatically captured when referenced inside the closure body. An explicit capture list MUST NOT be required. A for iterator is in scope for the loop body and MUST be capturable there.
A local is captured by reference: a later assignment to it is visible through the closure. A local
declared inside a loop body gets a fresh binding on each iteration, so a closure created in one
iteration and called after the loop MUST report that iteration's value rather than the last. A for
iterator is captured by value, as it stood when the closure was created — it is not a storage
location the body can assign to, since assigning to its name declares a shadowing local instead, so
by-reference capture would have no meaning distinct from this one. The practical consequence is
that a closure built in one iteration and called after the loop reports that iteration's value.
Example:
42 -> x
fn ( -- r:i64) { x } -> get_x // x is automatically captured
get_x call print nl // Prints 42
Multiple captures:
10 -> a
20 -> b
fn ( -- r:i64) { a b + } -> sum // Both a and b are captured
sum call print nl // Prints 30
Closure without captures (a function value that captures nothing):
def (x:i64 y:i64 -- r:i64) { x y + } -> add_fn
3 4 add_fn call print nl // Prints 7
Arguments left on the stack:
3 4 fn (i64 i64 -- r:i64) { + } call print nl // Prints 7
Fallible:
0 fn (x:i64 -- r:i64)! { dup 0 == if { "divide by zero" 1 panic } 100 swap / } call ok if {
print nl
} else {
drop "caught" print nl // Prints caught
}
7.5.1 Inferred Stack Effect
fn { body } has no signature. Its body works on the stack, as any function's does, and its stack
effect is inferred from the body rather than declared:
- Inputs. The fewest values the body has to find on the stack for none of its words to underflow. A body that never reaches below what it pushes takes none.
- Outputs. What the body leaves, with those inputs consumed.
- Types. An output's type is the one the body gives it:
fn { 2.0 * }leaves anf64. An input's type is not inferred, and neither is the type of an output that is an input passed through, or that arithmetic on an input produced. These are written_where the type is shown, in a diagnostic or an editor's hint, and match any type.
The inferred effect is the function value's type, fn(_ -- f64), and every check that applies
to a declared type applies to it: call, a parameter of function type, and a stack variable
(§3.4.1) all see exactly that effect. Errors in the body are reported as in any body. Every
function value has a type, so a body that calls one has an effect the checks can see.
A fn { } captures as any anonymous function does. It is not fallible: its body MUST NOT
panic, and ? inside it is an error. A fallible function value needs a signature.
def { } is an error, since there are no inputs for it to bind.
5 fn { 2 * } call print nl // 10
3 4 fn { + } call print nl // 7
10 20 fn { 1 + } dip print " " print print nl // 20 11
[1 2 3] fn { dup * } map -> squares // [1 4 9]
7.6 Function Values
&function_name // The named function as a function value
f call // Call the function value f
&name MUST give a static function value of the function's type (§3.4); an anonymous function
gives one that owns its captures. Both are counted values, and call MUST accept only a function
value: a raw ptr is not one, and calling it MUST be a compile-time error. A function type is a
valid element type, so [n]fn(...) builds a table of null function values (§3.2.2) that set
fills; calling an entry still null MUST stop the program with a fatal "NULL function value".
7.7 Combinators
A combinator is a builtin that runs function values in a fixed pattern. Each takes its function values from the top of the stack and the values they work on from below them:
| Combinator | Effect | Runs |
|---|---|---|
dip |
( ..a x q -- ..b x ) |
q on what is under x, then pushes x back |
keep |
( ..a x q -- ..b x ) |
q on x, then pushes x back |
dip2 |
( ..a x y q -- ..b x y ) |
q on what is under x and y, then pushes them back |
keep2 |
( ..a x y q -- ..b x y ) |
q on x and y, then pushes them back |
bi |
( ..a x p q -- ..c ) |
p on x, then q on x pushed again |
tri |
( ..a x p q r -- ..d ) |
p, q and r on x in turn, as bi does |
bi_star |
( ..a x y p q -- ..c ) |
p on x and what is under it, then q on y pushed back |
tri_star |
( ..a x y z p q r -- ..d ) |
p on x, q on y and r on z, as bi_star does |
both |
( ..a x y q -- ..c ) |
q on x, then q on y |
times |
( ..a n q -- ..a ) |
q n times |
each |
( ..a arr q -- ..a ) |
q with each element of arr pushed, in order |
map |
( arr q -- arr2 ) |
q on each element alone; arr2 holds what it leaves |
filter |
( arr q -- arr2 ) |
q on each element alone; arr2 holds the elements it leaves a true flag for |
fold |
( arr acc q -- acc ) |
q on the accumulator and each element in turn, starting from acc |
any |
( arr q -- flag ) |
q on each element alone until one leaves a true flag; 1 if one did |
all |
( arr q -- flag ) |
q on each element alone until one leaves a false flag; 1 if none did |
find |
( arr q -- elem flag ) |
q on each element alone until one leaves a true flag; that element and 1, or the zero of the element type and 0 |
index |
( arr q -- i ) |
q on each element alone until one leaves a true flag; its position, or -1 |
scan |
( arr start q -- i ) |
as index, from position start on; a negative start is 0 |
A combinator MUST be type-checked by doing what it does to the modelled stack: a function value
it runs on the stack (dip, dip2, keep, keep2, bi, tri, bi_star, tri_star, both, times,
each) MAY take and leave
any number of values, and its effect is applied where it runs. The function value of times and
each runs again on what it leaves, so it MUST leave the stack as it found it, in depth and in
types. That of map, filter, any, all, find, index and scan MUST take one value
and leave one, a flag for all but map; any, all, find, index and scan MUST stop at
the first element that decides the answer; that of fold MUST take two and leave one, of the
accumulator's type. The start position of scan MUST be an i64.
each, fold, any, all, find, index and scan MUST also accept a str in place of the
array. Its
elements are its characters, each an i64 codepoint, in order (§3.1), and a position is a
character index, as strings::char_at counts them. A string that is not well-formed UTF-8 MUST
be read as the strings module reads it: a byte that does not begin a well-formed sequence is one
character, whose value is that byte.
A function value of a combinator MUST NOT be fallible: there is nowhere for its failure to go.
Written in place. When the function values are fn { } literals written immediately before
the combinator, their bodies MUST be checked on the stack where they run, with the types of the
real values, and an implementation SHOULD compile them inline, creating no function value. A
body runs under the rules of an anonymous function's body (7.5) wherever it is compiled: it is
not fallible, and a loop exit in it does not leave a loop outside it. Any other function value
-- a local, a parameter, &name, a lambda with a signature -- is called, and checked by its
type.
10 20 fn { 1 + } dip // 11 20
0 [1 2 3] fn { + } each // 6
[1 2 3 4] fn { 2 % 0 == } filter fn { dup * } map 0 fn { + } fold // 20
The combinators are builtins, so a function in a program MUST NOT take one of their names, nor any other builtin's: a call by that name would run the builtin. A module's function MAY, since it is called qualified.
8. Structs
8.1 Struct Definition
[pub] [packed] struct Name [<TypeParams>] {
field1:type1
field2:type2 = default_value
}
By default every field MUST occupy an 8-byte slot, whatever its declared width. A packed
struct MUST instead lay its fields out adjacent at exactly their declared widths, with no
padding, in target byte order — so a struct of u32, u32, u64 is 16 bytes packed and 24
bytes unpacked. Combined with the sized integer types (§3.1.1), this is what lets a program
map a struct directly onto a byte-exact binary format.
packed struct FileLump {
offset:u32
size:u32
name:u64
}
8.2 Struct Construction
StructName {
field1 = expr1
field2 = expr2
}
Generic struct construction:
Box<i64> { value = 42 }
Pair<str, i64> { first = "key" second = 100 }
Each expr is an ordinary expression, and an implementation MUST accept in that position anything
it accepts as a value elsewhere — including a nested struct literal, an array literal and an
anonymous function:
Box { items = [1 2 3] f = fn (x:i64 -- r:i64) { 10 * } }
The same holds for the elements of an array literal (3.2.2).
Positional construction. A struct's name used as a word builds one from the stack: it takes one value per field, in declaration order -- the first field deepest, the last on top -- as a function takes its inputs.
struct Point { x:f64 y:f64 }
1.0 2.0 Point -> p // Point { x = 1.0 y = 2.0 }
fn new_point(x:f64 y:f64 -- p:Point) { Point }
Every field MUST be given, including one with a default, and each value MUST have the field's
type, an i64 widening to an f64 field as it does for an argument. A module's struct is built
by its qualified name, 1.0 2.0 3.0 math::Vec3, and a generic struct takes its type arguments
from the values, 7 Box. The named form above stays the one to use when the values do not
arrive on the stack in field order, or when the field names say something the order does not.
8.3 Field Access (Read)
Use << operator (data flows left, out of struct):
point <<x // Read field 'x' from point
point <<x <<y // Chained access (if x is a struct)
When the struct type cannot be determined and the field name exists in multiple struct definitions, implementations MUST produce an error; declaring the value with its struct type resolves it.
8.4 Field Set (Write)
Use >> operator (data flows right, into struct). The struct and value are popped from the stack:
>>field— writes the field and pushes the same struct back, so writes chain>>field drop— writes the field, then discards the struct reference
A struct is a reference, and >>field writes through it. It does not produce a new
struct: the value pushed back is the one that was passed in, already modified, and every
other name bound to that struct sees the change. drop discards the reference, not an
update — the write has already happened.
struct value >>field // Write the field, push the same struct back
struct value >>field drop // Write the field, discard the reference
Example:
// Chaining writes
Point { x = 0.0 y = 0.0 } 5.0 >>x 10.0 >>y -> p
// Standalone mutation
p 99 >>x drop
// Two names for one struct: writing through either is visible from both
p -> q
q 42 >>x drop
p <<x // 42
Copying
clone MUST produce a new struct of the same type with the fields copied, and MUST be
shallow: a field that holds a reference is retained, not copied, so the copy and the
original share whatever their fields point to. A str field cannot expose the
difference, strings being immutable; an array or a struct field can, and does.
p clone -> r
r 7 >>x drop
p <<x // unchanged
Implementations MUST reject clone where the struct type is not known at the call site,
including on a ptr: the type is what gives the size to allocate and the fields to retain.
clone on an array MUST produce a new array of the same element type and length, with the
elements copied, and is shallow in the same way: a string, array or struct an element refers
to is shared.
8.5 Generic Structs
struct Box<T> {
value:T
}
struct Result<T, E> {
value:T
error:E
is_ok:i64
}
9. Module System
9.1 Module Structure
A module is either:
- A single .qd file
- A directory containing .qd files (all files are loaded and merged into the module namespace)
Test files (*_test.qd) are excluded from module loading.
9.2 Module Resolution
When use modulename is encountered, the first of these that holds .qd files is the
module, and every tool -- the compiler, the language server, the REPL -- searches in this
order:
modulename/beside the file that wrote theuse- Each include path (
-I, and the local dependenciesqd.jsonnames): the path itself when itsqd.jsonnames the module, elsemodulename/in it - The installed packages, in
$QUADRATE_PATH, else$XDG_DATA_HOME/quadrate/modules, else~/quadrate/modules: the package registered under the namespacemodulename, or with-l modulename@versionthat version $QUADRATE_ROOT/modulename/share/quadrate/modulename/beside the compiler's installation~/quadrate/modulename/- The system's
share/quadrate/modulename/
A namespace that more than one installed package declares is an error, which names each
package by its full path: use "github.com/user/repo" selects one, and its words go under
the namespace that package declares. The compiler does not build a full-path import yet --
it reports one, naming the namespace to use instead -- though the language server and the
validator resolve it. use "path/file.qd"
names a single file, found beside the file that wrote the use, then beside the module that
file belongs to.
9.3 Public and Private
By default, declarations MUST be private to their module.
pub fn public_function() { } // Accessible from other modules
fn private_function() { } // Only accessible within module
pub inline fn fast_helper() { } // Public, inlined at call sites
pub struct PublicStruct { }
struct PrivateStruct { }
pub const PUBLIC_CONST = 1
const PRIVATE_CONST = 2
9.4 Scoped Access
Use :: to access module members:
use math
use io
use json
math::sin // Function
math::Pi // Constant
io::Read // Constant
json::Value // Struct
9.5 FFI Imports
Import C functions from static libraries:
import "libfoo.a" as "foo" {
pub fn bar(x:i64 -- y:i64)
pub fn baz(s:str -- )! // Fallible
}
// Usage
42 foo::bar
9.6 Multi-File Modules
mymodule/
├── api.qd // Public API functions
├── helpers.qd // Helper functions
└── types.qd // Type definitions
All .qd files in the directory are automatically loaded and merged into the same module namespace. No file has special significance - they are all equal. No explicit imports between files in the same module are needed.
// api.qd
pub fn main_feature() {
helper_function // Can call functions from helpers.qd
}
// helpers.qd
fn helper_function() { }
9.7 A Program's Directory
A program's own directory is a namespace too: the .qd files beside the file being compiled are merged into the program, with no use. Excluded are:
- test files (
*_test.qd); - files with their own
fn main, which are programs of their own; - a file the program brings in with
use "file.qd", or that brings the program in, which theusealready loads.
Where a directory sits does not matter: one named lib or tests is a namespace like any other. A directory of independent programs therefore gives each one a main, and keeps a helper that only one of them uses in a directory with that program.
10. Error Handling
10.1 Fallible Functions
Functions that can fail MUST be marked with !:
fn divide(a:i64 b:i64 -- result:i64)! {
dup 0 == if {
"division by zero" -1 panic
}
/
}
Note that a and b are inputs of a fn, so they stay on the stack (§4.4); the names
document them, and the body works on the values directly.
10.2 The panic Instruction
Signal an error from within a fallible function:
"error message" error_code panic
- Stack effect:
(msg:str code:i64 -- ) - Sets runtime error state and returns from the enclosing function immediately
- Only valid in fallible functions
The error code is chosen by the program and MAY be any i64 except 0. A caller reads the code
as the call's status (§10.3), where 0 is Ok, so a failure carrying it would read as a success.
An implementation MUST reject a panic whose code is written as 0 or Ok, and MUST stop the
program when a code computed at run time turns out to be 0.
10.3 Error Handling at Call Site
Abort on error (! operator):
10 0 divide! // Aborts program if divide fails
Propagate error (? operator):
fn wrapper(a:i64 b:i64 -- result:i64)! {
divide? // Propagates error to caller if divide fails
2 *
}
The ? operator requires the enclosing function to be fallible. On error, the function returns immediately, preserving the callee's error state.
A bare call — neither ! nor ? — MUST leave the same shape whichever way it went: the
function's results, then a status. The status MUST be Ok (0) on success and the error code
on failure. On failure each result MUST be the zero value of its declared type (§3.2.2): 0,
0.0, an empty string, or null. The call's stack effect therefore never depends on what follows
it, and the status is an ordinary i64 that MAY be bound, stored, returned or passed on:
fn main() {
10 0 divide -> status -> q
status ok if { q print nl } else { "failed with code " print status print nl }
}
That guarantee holds whatever the callee's body did before it failed. A fallible function's
failure exit MUST discard anything above the depth the caller expects — the depth at entry minus
the declared inputs (and the receiver) — and then push a zero value of each declared result. This
holds for anonymous functions marked ! as for named ones.
Test with ok or fail and if:
ok (( status -- flag )) is 1 when the status is Ok, and fail is its inverse. Both arms
start with the call's results; the arm that does not use them drops them.
fn main() {
10 0 divide ok if {
print nl
} else {
drop
"Division failed" print nl
}
}
An implementation MUST reject an if written immediately after a bare fallible call. The status
is 0 on success, so such an if would take its first arm when the call failed — the opposite of
what a reader expects, and of what the same code meant when the status was a success flag. The
status is tested with ok or fail first.
Match with switch:
switch reads the status itself, so the Ok arm is the success arm and a specific error code,
or _, a failure arm. Every arm starts with the call's results:
use io
fn main() {
"/no/such/file" io::Read io::open switch {
Ok {
io::close
}
io::ErrNotFound {
drop
"File not found" print nl
}
_ {
drop
"Unknown error" print nl
}
}
}
This MUST hold identically for functions defined in Quadrate and for those declared in an
import block (§5.8).
10.4 Error Constants
Ok= 0, the status of a call that succeededErr= 1, the generic error code- Module-specific errors start at 2
Example from io module:
pub const ErrNotFound = 2
pub const ErrPermission = 3
pub const ErrInvalidHandle = 4
10.5 The err Instruction
Retrieve error information after a failed call:
err // Stack effect: ( -- msg:str code:i64 )
err reports the code the panic carried. Reading the error state clears it.
A fallible function implemented natively rather than in Quadrate MUST report failure through the
error state: on failure it MUST set the error code and an error message, push the code, and
return it; on success it pushes its results and then 1. The call site turns either into the
status of §10.3, pushing the zero results a failed native call did not. The ! and ? operators
read the error state, so a native that only pushed a code would make switch see a failure that
! did not.
10.6 Worked Example
A complete program exercising the call-site forms against one fallible function:
fn divide(a:i64 b:i64 -- result:i64)! {
dup 0 == if {
"division by zero" -1 panic
}
/
}
// `?` propagates: doubled is fallible too, so a failure in divide returns from it immediately.
fn doubled(a:i64 b:i64 -- result:i64)! {
divide?
2 *
}
fn main() {
// 1. ok/fail and if -- the status turned into a flag
10 2 divide ok if { "10/2 = " print print nl } else { drop "failed" print nl }
10 0 divide ok if { "unreachable: " print print nl } else { drop "10/0 failed as expected" print nl }
// 2. switch -- the status is the error code, so specific codes can be matched
10 0 divide switch {
Ok { "unreachable: " print print nl }
-1 { drop "caught code -1: " print err print " " print print nl }
_ { drop "some other error" print nl }
}
// 3. the status kept as a value
10 0 divide nip
"status: " print print nl
// 4. ! aborts the program on failure; here it succeeds
"20/4 = " print 20 4 divide! print nl
// 5. ? propagates to the caller
10 2 doubled switch {
Ok { "(10/2)*2 = " print print nl }
_ { drop "failed" print nl }
}
}
Output:
10/2 = 5
10/0 failed as expected
caught code -1: -1 division by zero
status: -1
20/4 = 5
(10/2)*2 = 10
11. Memory Management
11.1 Allocation Strategy
Stack allocation: - Local structs that don't escape their function - Faster, no reference counting overhead - Automatic cleanup when function returns
Heap allocation: - Structs returned from functions - Strings - Arrays - Captured closure variables
Allocation failure:
mem::alloc, mem::realloc and mem::alloc_aligned are fallible and report failure as
mem::ErrAlloc, so a program that has something useful to do when memory runs out can handle it
like any other error.
The standard library does not. Its allocation sites call these with !, which aborts the process
with a message naming the allocation and a stack trace. This is a deliberate policy rather than an
oversight: a library function such as sb::new or regex::compile has no way to report the
failure that would not make every one of its callers fallible for a condition none of them can act
on. Where a program needs a different policy, it allocates for itself and handles the error.
This differs from the treatment of malformed input, which a library MUST NOT abort on: input is chosen by whoever is talking to the program, whereas allocation failure is a property of the machine.
11.2 Reference Counting
Heap objects MUST use atomic reference counting:
// C
struct qd_refcounted {
atomic_size_t refcount; // Initially 1
// ... object data ...
};
Operations: - Retain: Increment refcount (when sharing) - Release: Decrement refcount; free when reaches 0
11.2.1 Reference Cycles
Reference counting alone MUST NOT be expected to reclaim a cycle. Two objects that refer to each other keep each other's count above zero, so neither is ever freed, and an implementation is NOT required to detect this. The memory is unreachable and stays allocated until the process exits.
Only cycles are affected. A non-cyclic chain of pointer-typed fields is reclaimed in full: when the last reference to the head goes away, releasing it releases the field it holds, and so on down the chain.
This is reachable with the pointer-typed struct fields of §3.6.2 — the same Node shape the
specification uses to illustrate them:
struct Node {
value:i64
next:*Node
}
fn main() {
Node { value = 1 next = null } -> a
Node { value = 2 next = null } -> b
a b >>next drop
b a >>next drop // a and b now reference each other and are never freed
"built a cycle" print nl
}
A program that builds cyclic structures — a doubly-linked list, a parent pointer in a tree, a
graph with back edges — MUST break the cycle itself before dropping the last external reference
if the memory is to be reclaimed. Setting one of the two fields back to null is enough. A
long-running program that repeatedly builds and discards such structures will otherwise grow
without bound.
Implementations MAY provide a cycle detector or weak references; this specification requires neither, and the reference implementation provides neither.
11.2.2 Ownership
Reference counting says how a count moves; it does not say who moves it. This is the contract, and every part of an implementation MUST hold to the same one. None of it is visible in a program's output, so an implementation that gets it wrong in one place and right in another still passes every test of what programs print.
The counted values are strings, structs, arrays and function values (§3.4); a closure's
captures are counted with it (§11.6), and &name gives a static function value whose count is
never taken. A raw ptr (§3.5.1), an i64, an f64 and a d128 are not counted.
A value on the stack carries a reference of its own. Reading a local, a field, an array element or a global retains what it reads before pushing it. A value that was just created -- by a struct literal, a string operation, an array literal -- arrives with the single reference its allocation gave it.
Somewhere that holds a value owns a reference. There are four such places, and they behave alike:
- a local variable, from
->until it is rebound or its scope ends; - a struct field, from the store until it is overwritten or the struct is destroyed — a field of generic type (§3.3) included, which holds a whole stack slot;
- an array element, until it is overwritten or the array is destroyed;
- a tagged slot (
mem::set_any), until it is overwritten or cleared.
Storing into one of these MUST take over the reference the stack supplied, and MUST release
whatever the place held before. Emptying one -- rebinding a local, leaving a scope, running a
destructor, releasing an array, mem::clear_any -- MUST give its reference back. It follows
that a region of memory that will hold references MUST be zeroed before first use, since the
store reads the old contents in order to release them; the standard library's containers zero
the capacity they allocate, and a zeroed slot holds nothing.
An instruction that pops a value releases it, unless it hands the value on. drop releases;
== and != release both operands; dup retains the copy it makes; swap, over, rot and
nip leave the net count unchanged. The parameters of a def are bound as locals and
released when it returns; those of any other function stay on the stack and are released by
whatever consumes them. Its results are pushed with a reference the caller then owns.
A value may be held in several places at once, and each gives its reference back independently: a node reachable from a list's head pointer and from its tail pointer is freed when both stop pointing at it, not when the first does.
None of this is visible in what a program prints, which is why an implementation SHOULD test it
by measuring: build and drop the same structure at two iteration counts far apart and compare
peak memory. tests/run_memory_test.sh in the reference implementation does exactly that, over
a linked structure, a returned struct, the JSON parser and the containers.
11.3 String Memory
Strings MUST be reference-counted and immutable:
// C
struct qd_string {
char* data;
size_t length;
size_t capacity;
atomic_size_t refcount;
};
- Copying a string increments its refcount (shallow copy)
- String operations that modify create new strings
- In-place mutation only when refcount == 1
11.4 Struct Memory
Heap-allocated structs have a hidden header:
// C
struct qd_struct_header {
size_t magic; // Validation marker
atomic_size_t refcount;
void (*destructor)(void*);
};
Destructors: - Automatically generated for structs with fields that hold references: strings, structs, arrays, function values, and fields of generic type - Called when refcount reaches 0 - Release nested references
A function value is a counted struct of this shape, holding the function, its captured environment and their count, and is retained and released as any struct is (§11.2.2).
11.5 Array Memory
// C
struct qd_array {
size_t magic;
atomic_size_t refcount;
size_t length;
size_t capacity;
qd_array_type elemType; // INT=0, FLOAT=1, STR=2, PTR=3, ANY=4, D128=5
uint8_t elemKind; // For PTR elements: RAW=1, STRUCT=2, ARRAY=3
union {
int64_t* i;
double* f;
void** p; // strings and pointers
qd_d128_t* d; // d128 elements, sixteen bytes each
} data;
};
ANYis the element type of an array that has not yet adopted one: an empty[], or[n]Tfor a type parameter (§3.2.2). The first value stored sets it.elemKindis adopted with the first pointer element stored, and every later one MUST be of the same kind (§3.2.2), so an element is retained, copied and released as what it is: a struct, function value or array element is counted, a rawptrelement is not.- Dynamic resizing with 2x growth factor
- Element-type-aware cleanup (strings released, nested arrays, structs and function values released)
11.6 Closure Captures
Variables referenced inside a closure MUST be automatically detected and captured (implicit capture). Captured variables MUST be heap-allocated with reference counting:
// C
struct captured_var {
int64_t refcount;
qd_stack_element_t elem;
};
- A closure is a counted function value (§3.4); it holds a reference to each captured variable
- Variables freed when all closures using them are released, and a captured variable that holds a counted value releases it then
- A captured
foriterator has no such variable to point at, so the closure is given a block of its own holding the iterator's value, with a refcount of one, released the same way
11.7 Defer for Cleanup
Use defer for explicit cleanup:
fn process(path:str -- )! {
io::Read io::open!
-> file
defer { file io::close }
// ... process file ...
// close runs automatically on scope exit
}
12. Built-in Instructions
12.1 Arithmetic
| Instruction | Stack Effect | Description |
|---|---|---|
+ |
(a b -- c) |
Addition |
- |
(a b -- c) |
Subtraction |
* |
(a b -- c) |
Multiplication |
/ |
(a b -- c) |
Division |
% |
(a b -- c) |
Modulo |
neg |
(a -- b) |
Negation |
++ |
(a -- b) |
Increment by 1 |
-- |
(a -- b) |
Decrement by 1 |
Integer semantics. Integer arithmetic is two's-complement and wraps on overflow:
9223372036854775807 1 + yields -9223372036854775808, and -9223372036854775808 -1 /
yields -9223372036854775808 with remainder 0. Division or modulo by zero is a fatal
error; when the divisor is a literal 0 it is a compile-time error. An exponent makes a
literal a float, so 1e3 is an f64 and there is no exponent spelling for an integer.
Mixed operands. An i64 operand beside an f64 is converted to f64, and the
operation is an f64 one: 5 3.5 + is 8.5. An i64 operand beside a d128 is widened
to d128 exactly (§3.1.2). An f64 operand beside a d128 is a compile-time error. The
same rules apply to the comparisons (§12.2).
Float semantics. f64 arithmetic follows IEEE 754. Division by zero is therefore
defined, not an error: 1.0 0.0 / is inf, -1.0 0.0 / is -inf, and 0.0 0.0 / is
NaN. The integer rule above does not apply to floats, and neither the compiler nor the
runtime rejects a zero float divisor. NaN compares unequal to everything including itself,
so x x == is 0 when x is NaN; test for it with math::is_nan rather than ==.
Infinity and NaN have no literal spelling — math::inf and math::nan name them, and
math::is_inf and math::is_finite classify. % is integer-only and reports a type
error on float operands; math::fmod is the float remainder.
d128 semantics. d128 arithmetic follows IEEE 754-2008 decimal128, with the rules of
§3.1.2: every result is rounded to 34 digits with roundTiesToEven, the operands of + - * /
and the comparisons are both d128, or one d128 and one i64 that is widened to it, or it
is a compile-time error; and division by zero gives
inf or NaN. The exponent of a result is IEEE's preferred exponent, so 1.5d 2d * is 3.0
and 10d 4d / is 2.5.
12.2 Comparison
| Instruction | Stack Effect | Description |
|---|---|---|
== |
(a b -- flag) |
Equal |
!= |
(a b -- flag) |
Not equal |
< |
(a b -- flag) |
Less than |
> |
(a b -- flag) |
Greater than |
<= |
(a b -- flag) |
Less than or equal |
>= |
(a b -- flag) |
Greater than or equal |
within |
(a lo hi -- flag) |
lo <= a <= hi |
Operands of == and !=. Numbers compare by value, and an i64 may be compared with an
f64. Strings compare by content, so two strings with the same characters are equal whether or
not they are the same string. Pointers compare by identity: a b == is true when both name the
same address, which is also how two struct values are asked whether they are the same struct,
since a struct is a reference. A pointer may be compared with an integer, which is what the
idiomatic null check p null == is. Any other mixture -- a string against a pointer, say -- is
a runtime type error.
The ordering operators are numeric only. Comparing two pointers with < is a type error rather
than an address comparison: the relative order of two allocations is not something a program
should be written against.
12.3 Logical
Every non-zero value counts as true and the result is always 0 or 1, so 2 1 and is 1.
Both operands are always evaluated: these are ordinary stack words, and a guard of the
form i len < xs i nth ... and reads xs[i] whether or not the bound check passed.
| Instruction | Stack Effect | Description |
|---|---|---|
and |
(a b -- flag) |
1 if both operands are non-zero |
or |
(a b -- flag) |
1 if either operand is non-zero |
not |
(a -- flag) |
1 if the operand is zero |
12.3.1 Bitwise
AND, OR, XOR and NOT would collide with the logical words above, so they live in the bits
module with the shifts, and MUST be written bits::and, bits::or, bits::xor, bits::not,
bits::shl and bits::shr.
| Function | Stack Effect | Description |
|---|---|---|
bits::shl |
(a n -- b) |
Shift left |
bits::shr |
(a n -- b) |
Shift right (logical) |
Shift semantics. bits::shr is a logical shift: the operand is treated as unsigned and
zeros are shifted in. The shift count n MUST be in the range 0..63; any other count is
a fatal error, whether the operation is compiled, inlined, or executed by the runtime.
12.4 Stack Manipulation
See Section 4.2 for complete list.
12.5 Array Operations
| Instruction | Stack Effect | Description |
|---|---|---|
append |
(arr x -- arr) |
Append an element |
set |
(arr i x -- ) |
Store an element at index i |
nth |
(arr i -- elem) |
The element at index i |
len |
(arr -- n) |
The number of elements |
clone |
(arr -- arr2) |
A shallow copy |
len and nth MUST also accept a str, as a sequence of characters: len is its length in
characters and nth the codepoint of the character at a character index, the values
len and strings::char_at give. An index outside the string is a fatal error, as it
is for an array.
12.6 Type Operations
| Instruction | Stack Effect | Description |
|---|---|---|
cast<T> |
(a -- b) |
Cast to type T (total conversions only; see §3.7) |
sizeof<T> |
( -- n) |
Size of type T in bytes; the type is a type parameter, not a value |
12.7 I/O Operations
| Instruction | Stack Effect | Description |
|---|---|---|
print |
(x -- ) |
Print value |
dump |
(x -- ) |
Print value with type info |
nl |
( -- ) |
Print newline |
12.8 Error Handling
| Instruction | Stack Effect | Description |
|---|---|---|
panic |
(msg code -- ) |
Signal error (fallible functions only) |
err |
( -- msg code) |
Get last error info |
ok |
(status -- flag) |
1 if a fallible call's status is Ok (§10.3) |
fail |
(status -- flag) |
1 if a fallible call's status is an error code |
12.9 Function Calls
| Instruction | Stack Effect | Description |
|---|---|---|
call |
(f:fn(...) -- ...) |
Call a function value; its type gives the rest of the effect. A ptr is not one (§7.6) |
13. Standard Library Interface
The Quadrate standard library provides these core modules:
13.1 math
Mathematical functions and constants.
Constants: Pi, E, Tau, Phi, Sqrt2, Ln2, etc.
Functions:
- Trigonometric: sin, cos, tan, asin, acos, atan, atan2
- Hyperbolic: sinh, cosh, tanh, asinh, acosh, atanh
- Exponential: exp, exp2, pow, sqrt, cbrt, log, log2, log10
- Rounding: ceil, floor, round, trunc
- Utility: abs, min, max, clamp, lerp, sign
13.2 strings
String manipulation.
Functions:
- len, concat, contains, starts_with, ends_with
- index_of, last_index_of, substring!
- upper, lower, trim, trim_left, trim_right
- split!, join!, replace!, repeat, reverse
- char_at, from_char, compare, count
13.3 io
File and stream I/O.
Constants: Read, Write, Append, ReadWrite, SeekSet, SeekCur, SeekEnd
Error codes: ErrNotFound, ErrPermission, ErrRead, ErrWrite, etc.
Functions:
- open!, close, read!, write!, seek!, tell!, eof
- readline!, read_file!, write_file!
13.4 fmt
Formatted output.
Functions: printf, sprintf
13.5 os
Operating system interface.
Functions:
- Process: exit, system, getpid, exec!, popen!
- Environment: getenv, setenv
- Filesystem: exists, delete!, rename!, copy!, mkdir!, rmdir!
- Directory: list!, walk!, glob!, cwd!
13.6 time
Time operations.
Constants: Duration units, weekday/month names
Functions:
- unix, now, sleep
- year, month, day, hour, minute, second, weekday
- is_leap_year, days_in_month, add, sub, before, after
- format!, parse! -- the two fallible ones, since a format string can be malformed and an
input can fail to match it
13.7 thread
Threading primitives.
Structs: Thread, Mutex, Channel, WaitGroup
Functions:
- Thread: spawn!, join!, detach!, is_alive
- Mutex: mutex_new!, lock!, unlock!, try_lock
- Channel: chan_new!, send!, recv!, close
- WaitGroup: wg_new!, add, done, wait!
13.8 mem
Low-level memory.
Functions:
- alloc!, realloc!, free
- set_byte, get_byte, set_i64, get_i64
- set_ptr, get_ptr — a raw ptr only; get_ptr MUST return raw memory, never a struct or
an array (§3.5.1)
- set_any, get_any, clear_any — a tagged slot that keeps the value's type and owns a
reference to it (§11.2.2); the way to keep a struct, an array or a string in raw memory
- copy, zero, fill
13.9 decimal
The decimal module: IEEE 754-2008 decimal128 operations on d128 beyond the operators, and the elementary functions
(§3.1.2). Every result is rounded to 34 digits with roundTiesToEven; sqrt, exp, ln,
log10 and fma MUST be correctly rounded.
Functions:
- Elementary: sqrt, exp, ln, log10, pow, sin, cos, tan, asin, acos,
atan, atan2
- Arithmetic: fma, abs, copysign, remainder, fmod, min, max
- Rounding to an integer: round_even, round, trunc, floor, ceil
- Exponent and digits: quantize, reduce, scaleb, logb, next_up, next_down
- Classification: is_nan, is_inf, is_finite, is_zero, is_normal, is_subnormal,
is_signed, total_order
- Constants, as functions taking nothing and leaving a d128: pi, e, inf, nan
(decimal::pi)
13.10 Additional Modules
base64- Base64 encoding and decodingbits- Bit manipulation utilitiesbytes- Byte buffer operationscrypto- Cryptographic hashes (SHA-256, SHA-512, MD5, CRC32)ct- Generic containers (Vec, Map, Set, Queue, Deque)error- Errors as values: theErrorstruct, holding a failure's message and codeflag- Command-line flag parsingfuzzy- Fuzzy string matching (Levenshtein distance)hex- Hexadecimal encoding and decodinghof- Higher-order function combinatorshttp- HTTP client and serverjson- JSON parsing and buildinglimits- Numeric type limitslog- Structured logging with rotationnet- TCP network socketspath- File path manipulationrand- Random number generation (xorshift64*)regex- Regular expression matching (Thompson NFA)sb- StringBuilder for efficient string buildingsignal- Signal handlingsort- Sorting and array utilitiesstrconv- String/number conversionsys- Low-level system operations: x86 port I/O, interrupt control, raw loads and storesterm- Terminal colors and formattingtesting- Unit testing utilitiestls- TLS/SSL secure socketstty- Terminal detection and dimensionsunicode- Unicode character constantsuri- URI encoding, decoding, and parsinguuid- UUID v4 generation
14. Runtime Requirements
14.1 Context Structure
The runtime MUST maintain an execution context:
// C
typedef struct {
qd_stack* st; // Data stack
int64_t error_code; // Current error (0 = none)
char* error_msg; // Error message
int argc; // Command-line arg count
char** argv; // Command-line args
// Call stack for debugging
const char* call_stack[256];
const char* call_stack_files[256];
size_t call_stack_lines[256];
size_t call_stack_depth;
} qd_context;
14.2 Stack Implementation
// C
typedef struct {
qd_stack_element_t* data;
size_t capacity;
size_t size;
} qd_stack;
14.3 Required Runtime Functions
Implementations MUST provide the following runtime functions:
Context:
- qd_create_context(capacity) - Create new context
- qd_free_context(ctx) - Destroy context
Stack:
- qd_push_i(ctx, int64) - Push integer
- qd_push_f(ctx, float64) - Push float
- qd_push_s(ctx, string) - Push string (copy)
- qd_push_s_ref(ctx, string) - Push string (reference)
- qd_push_p(ctx, ptr) - Push a pointer to raw memory, never an array, a struct or a function value; nothing is counted for it
- qd_push_struct(ctx, p), qd_push_array(ctx, p) - Push a struct or an array with the reference the caller holds
- qd_call_value(ctx, fn) - Call a function value from native code
- qd_pop_i(ctx, &val) - Pop integer
- qd_pop_f(ctx, &val) - Pop float
- qd_pop_s(ctx, buf, size) - Pop string into buffer
- qd_pop_p(ctx, &val) - Pop pointer
- qd_push_d(ctx, d128) - Push d128 (by value)
- qd_pop_d(ctx, &val) - Pop d128 (by value)
Operations:
- qd_add, qd_sub, qd_mul, qd_div, qd_mod - Arithmetic
- qd_lt, qd_gt, qd_eq, qd_neq, qd_lte, qd_gte - Comparison
- qd_land, qd_lor, qd_lnot - Logical (§12.3): the operations and, or and not name
- qd_and, qd_or, qd_xor, qd_not, qd_shl, qd_shr - Bitwise (§12.3.1): the operations
bits::and, bits::or, bits::xor, bits::not, bits::shl and bits::shr name
Memory:
- qd_struct_alloc(size, destructor) - Allocate struct
- qd_struct_retain(ptr) - Increment refcount
- qd_struct_release(ptr) - Decrement refcount
- qd_string_retain(str) - Retain string
- qd_string_release(str) - Release string
- qd_array_create(capacity, type) - Create array
- qd_array_release(arr) - Release array
Debug:
- qd_push_call(ctx, func, file, line) - Push call frame
- qd_pop_call(ctx) - Pop call frame
- qd_print_stack_trace(ctx) - Print trace
Appendix A: Grammar Summary
program = { declaration } ;
declaration = use_stmt | const_decl | var_decl | enum_decl | type_alias_decl | struct_decl | fn_decl | import_decl | test_decl ;
use_stmt = "use" ( identifier | string ) ;
const_decl = "const" identifier "=" expression ;
var_decl = ["pub"] "var" identifier [ ":" type ] "=" ( literal | const_name | struct_construction | array_literal | "&" identifier ) ;
enum_decl = ["pub"] "enum" identifier "{" { enum_variant } "}" ;
enum_variant = identifier [ "=" integer ] ;
type_alias_decl = ["pub"] "type" identifier "=" type ;
struct_decl = ["pub"] ["packed"] "struct" identifier [type_params] "{" { field_decl } "}" ;
fn_decl = ["pub"] ["inline"] ( "fn" | "def" ) identifier [type_params] signature ["!"] block ;
import_decl = "import" string "as" string "{" { import_fn } "}" ;
test_decl = "test" string block ;
type_params = "<" type_param { "," type_param } ">" ;
type_param = identifier | stack_var ;
stack_var = ".." identifier ; /* 3.4.1 */
signature = "(" [ stack_var ] [ param_list ] "--" [ stack_var ] [ param_list ] ")" ;
param_list = param { param } ;
param = identifier ":" type ;
field_decl = identifier ":" type [ "=" expression ] ;
import_fn = ["pub"] "fn" identifier signature ["!"] ;
block = "{" { statement } "}" ;
statement = expression | if_stmt | for_stmt | loop_stmt
| switch_stmt | defer_stmt | "break" | "continue" | "return"
| "while" | "until" ; /* each pops a flag, see 6.4 */
if_stmt = expression "if" block [ "else" block ] ;
for_stmt = expression expression expression "for" identifier block ;
loop_stmt = "loop" block ;
switch_stmt = expression "switch" "{" { case_clause } "}" ;
case_clause = ( literal | identifier | "_" ) block ;
defer_stmt = "defer" ( block | statement ) ;
expression = literal | identifier | scoped_id | struct_const | array_lit
| field_access | field_set | local_bind | fn_call | anon_fn
| operator | instruction | fn_ref | interp_string ;
interp_string = "$\"" { character | "{" ( identifier | scoped_id ) "}" } "\"" ;
fn_ref = "&" ( identifier | scoped_id ) ; /* a static function value, 7.6 */
literal = integer | float | d128 | string | "true" | "false" | "Ok" | "Err" | "null" ;
scoped_id = identifier "::" identifier { "::" identifier } ; /* mod::Enum::Variant, 5.4.2 */
struct_const = identifier [type_args] "{" { field_init } "}" ;
array_lit = "[" { expression } "]" ;
field_access = "<<" identifier ;
field_set = ">>" identifier ;
local_bind = "->" identifier ;
anon_fn = ( "fn" | "def" ) signature [ "!" ] block /* captures are implicit */
| "fn" block ; /* effect inferred, 7.5.1 */
fn_call = identifier [ "!" ] ;
type = "i64" | "f64" | "d128" | "str" | "ptr" | "bool" | sized_int
| "[]" type | identifier [type_args] | "*" identifier [type_args]
| "fn" signature [ "!" ] ; /* "*" only as a struct field's type, 3.6.2 */
sized_int = "i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "u64" ;
type_args = "<" type { "," type } ">" ;
operator = "+" | "-" | "*" | "/" | "%" | "++" | "--"
| "<" | ">" | "==" | "!=" | "<=" | ">="
;
instruction = "dup" | "dup2" | "swap" | "drop" | "drop2" | "over" | "rot" | "rrot" | "tuck" | "nip"
| "pick" | "nth" | "len" | "append" | "set"
| "clone" | "cast" "<" type ">" | "sizeof" "<" type ">"
| "print" | "nl" | "call" | "panic" | "err" | "ok" | "fail" | ... ;
Appendix B: Operator Reference
B.1 Arithmetic Operators
| Operator | Stack Effect | Description |
|---|---|---|
+ |
(a b -- c) |
a + b |
- |
(a b -- c) |
a - b |
* |
(a b -- c) |
a * b |
/ |
(a b -- c) |
a / b |
% |
(a b -- c) |
a mod b |
++ |
(a -- b) |
a + 1 |
-- |
(a -- b) |
a - 1 |
B.2 Comparison Operators
| Operator | Stack Effect | Result |
|---|---|---|
== |
(a b -- flag) |
1 if a == b, else 0 |
!= |
(a b -- flag) |
1 if a != b, else 0 |
< |
(a b -- flag) |
1 if a < b, else 0 |
> |
(a b -- flag) |
1 if a > b, else 0 |
<= |
(a b -- flag) |
1 if a <= b, else 0 |
>= |
(a b -- flag) |
1 if a >= b, else 0 |
B.3 Logical Operators
| Word | Stack Effect | Description |
|---|---|---|
and |
(a b -- flag) |
1 if both operands are non-zero |
or |
(a b -- flag) |
1 if either operand is non-zero |
not |
(a -- flag) |
1 if the operand is zero |
B.3.1 Bitwise Operators
| Function | Stack Effect | Description |
|---|---|---|
bits::and |
(a b -- c) |
a & b |
bits::or |
(a b -- c) |
a | b |
bits::xor |
(a b -- c) |
a ^ b |
bits::not |
(a -- b) |
~a |
bits::shl |
(a n -- b) |
Shift left |
bits::shr |
(a n -- b) |
Shift right |
B.4 Special Operators
| Operator | Description |
|---|---|
-> |
Bind top of stack to local variable |
:: |
Scope resolution (module::member) |
<< |
Field access (read): struct <<field |
>> |
Field set (write): struct value >>field — writes the field, pushes the same struct back; add drop to discard the reference |
& |
The named function as a function value (§7.6) |
! |
Abort on error (after fallible call) |
? |
Propagate error to caller (after fallible call) |
as |
Names the module in an import |
Document History
- Unreleased:
ptris raw memory only (§3.5.1): a struct, an array and a function value are counted references that are notptrs, a stack slot and an array record which kind of pointer they hold (§4.1, §11.5), and the runtime's registries of counted objects are removed. Function values are counted,&namegives a static one, and[n]fn(...)builds a table of them (§3.4, §7.6). Theas Typecast is removed;asremains only inimport(§5.8). - 0.5.0: Sized integer types (§3.1.1),
[n]Tarray literals and nested array types (§3.2.2),while(§6.4),fnleaving its inputs on the stack besidedef, and the anonymous-function rules (§7.5), branch and switch-arm stack effects (§6.1.1, §6.5.1), logicaland/or/notwith the bitwise operations inbits(§12.3), reference cycles and ownership (§11.2) - 0.2.0: Method syntax for stdlib, expanded regex/fmt/sort/crypto/net, unified block parsers
- 2.0.0-alpha: Initial specification document
This specification is provided for implementers of Quadrate compilers and interpreters. For user documentation, see the Quadrate Documentation.