Start & syntax
Build
Star99 → C99. Alpha edition: 2026-10-23. The linked source defines this edition. Requires a suitable C99 compiler on a supported Unix-like platform. Save hello.star99 before compiling. Generated C goes to .star99/NAME/ beside the program (see Build outputs); a directory builds as one module.
curl -fLO https://control-core.com/tmp/star99.c
cc -std=c99 -O2 star99.c -lm -o star99
./star99 hello.star99
./hellohello.star99fn main() {
println("hello, world")
}Output
hello, world
Syntax
# comment; { ... } block; do expr single-expression body. Newline-separated statements. Parameters/fields: commas or newlines, no semicolons.
struct Point (x, y: Int)
fn doubled(n: Int) -> Int do n * 2
fn main() {
# A comment explains why the next operation is useful.
const p = Point(x: 3, y: 4)
println(doubled(p.x))
}Output
6
Declaration and expression forms
| Form | Meaning |
|---|---|
| var x: T / var x = value | Mutable local or global. |
| const x = value | Read-only binding. |
| fn f(x: T) -> R { ... } | Named function. |
| fn (x: T) do expression | Function value / closure. |
| struct T (fields) | Record type. |
| union T (variants) | Tagged alternatives, plus nil. |
| no_nil(union T (...)) | Union without nil. |
| macro declaration | Compile-time declaration. |
| private declaration / private { ... } | Module-private names. |
| module (...) / collection name = "path" | Module parameters / collection mapping. |
Reserved words cannot name variables or fields. Use and/or/not, not &&/||/!. Write n += 1, not n++. No ternary ?:; use if ... do ... else ....
Lexical forms and statement boundaries
Identifiers contain ASCII letters, underscores, and digits, with no leading digit. Type names begin with an uppercase letter; variable/function names begin lowercase or with an underscore. Reserved words cannot be identifiers. A lone _ is the discard marker. # comments continue to the newline.
Statements/declarations are separated by newlines or semicolons. Parenthesized/bracketed lists accept their documented comma/newline separators and trailing commas. Fields, variants, and parameters use commas or newlines, rather than statement semicolons. Blocks use braces; do introduces one statement/body where the grammar permits it.
| Literal | Rule |
|---|---|
123 / 1_000 / 0xff / 0b1010 | Decimal, hexadecimal, binary integer literals; underscores are ignored in the digit sequence. Values take a compatible contextual numeric type. |
1.5 / 1e3 / 1.5e-3 | Float literals; the exponent is decimal. Float uses C double in generated code. |
"text" / 'A' | Escaped String / U8 (a one-byte single-quoted character). Character literals require exactly one decoded byte. |
"""raw "text" \n""" | Raw String, on one line or many: nothing is escaped, so backslashes and quotes remain as written. It ends at the first """ and cannot contain one; one or two quotes just before the closing """ belong to the text (""""x"""" is "x"), and more is an error. The backtick forms of earlier editions are errors. |
"""
multiline text
""" | On many lines: the line break after the opening """, the closing line's indentation (removed from every line), and the line break before the closing """ are left out. |
true / false / nil | Bool literals / contextual absence. nil needs a compatible destination type. |
Escaped strings and characters support \n, \t, \r, \0, \\, \", \', and \x followed by exactly two hexadecimal digits. Strings store bytes, including zero bytes. There is no interpolation syntax or automatic Unicode character indexing.
Literal forms: complete program
literal-forms.star99fn main() {
const escaped = "a\tb"
const raw = """a\tb"""
const long = """
first
second
"""
println(raw == "a\\tb", " ", len(escaped))
println(long == "first\nsecond")
println(0b1010 + 0x0f + 1_000)
println(2.5e2)
println('\'' == U8(39), " ", len("\0"))
}Output
true 3 true 1025 250.0 true 1
Values
var: mutable; const: read-only binding. Types infer from initializers. Grouped declarations create independent values. Initialization: zero/empty plus field defaults. Defaults must be constant; ordinary function calls and parameter references are rejected, while constant aggregates are permitted.
struct Panel (rows = 4, name: String)
fn main() {
var count: Int
var left, right: Int = 3
const title = "status"
var panel: Panel
count = left + right
println(count, " ", title, " ", panel.rows)
}Output
6 status 4
Grouped declarations and default propagation
Fragmentstruct Panel (rows = 4, title: String)
var a, b: Panel # Independent starting values.
var n, m: Int = 3 # Both start at 3.
var panels: List(Panel)
resize(&panels, 2) # Each new panel has rows == 4.Defaults belong to the type: declarations, omitted fields, nested fields, and new list elements all receive them. Group initializers evaluate once per name, not once for the group. A default cannot reference an earlier parameter or call a function.
Numbers & operators
T(x) converts; integer conversions check bounds. Float → Int truncates toward zero. Integer overflow, integer division/remainder by zero, and negative integer exponents fail. Float arithmetic uses C double operations. Power is integer-only. abs, sqrt, floor are built in. Numeric literals can take a compatible contextual type.
| Type | Meaning |
|---|---|
| Int | Signed 64-bit integer. |
| I8, I16, I32, I64 | Signed integers with the stated bit width. |
| U8, U16, U32, U64 | Unsigned integers with the stated bit width. |
| Float | Floating-point number; generated C uses double. |
| Bool | true or false. |
| String | Byte sequence that prints as text. |
fn main() {
const byte = U8(65)
const whole = Int(-2.9)
println(byte == 'A', " ", whole)
println(2 ** 10, " ", -2 ** 2, " ", 2 ** 3 ** 2)
println(7 / 2, " ", 7 % 2)
}Output
true -2 1024 -4 512 3 1
| Operators, strongest first | Meaning |
|---|---|
| ** | Integer power; groups right to left and binds more tightly than unary minus. |
| * / % | Multiply, divide, remainder. |
| + - | Add, subtract. |
| ..< ..= <..< <..= | Integer ranges with selectable inclusive/exclusive endpoints. |
| == != < <= > >= in not in | Comparison and membership. |
| not | Logical negation; write not (a == b) for clarity. |
| and | Logical conjunction. |
| or | Logical disjunction. |
Integer ranges and conversion failures
| Type | Range |
|---|---|
| I8 / U8 | -128…127 / 0…255 |
| I16 / U16 | -32768…32767 / 0…65535 |
| I32 / U32 | -2147483648…2147483647 / 0…4294967295 |
| Int / I64 | -9223372036854775808…9223372036854775807 |
| U64 | 0…18446744073709551615 |
A literal outside its destination range fails during compilation. Dynamic conversions check at run time. Converting NaN, infinity, or an out-of-range Float to an integer fails. Float-to-integer conversion truncates toward zero: Int(-2.9) == -2.
Power groups right: 2 ** 3 ** 2 == 512. Unary minus follows power: -2 ** 2 == -4. Both power operands have the same integer type. abs, sqrt, and floor do not provide a general numeric parsing API.
Operators, comparisons, and ranges
| Precedence | Syntax | Meaning |
|---|---|---|
| 9 (tightest) | call(...), index[...], .field, .* | Postfix call, indexing, field access, checked dereference. |
| 8 | ** | Right-associative integer power; 2 ** 3 ** 2 means 2 ** (3 ** 2). |
| 7 | unary +, unary -, & | Numeric sign / checked reference to a mutable place. Power binds inside unary minus. |
| 6 | * / % | Left-associative multiplication, division, integer remainder. |
| 5 | + - | Left-associative arithmetic. No String concatenation with +. |
| 4 | ..< ..= <..< <..= | Int range syntax; upper/lower arithmetic binds inside its endpoints. |
| 3 | == != < <= > >= in not in | Comparison or membership; ordinary comparisons cannot chain. |
| 2 | not | Boolean negation; not a == b means not (a == b). |
| 1 | and | Bool conjunction, short-circuiting left to right. |
| 0 | or | Bool disjunction, short-circuiting left to right. |
| Statement | = += -= *= /= %= | Assignment / compound assignment; not value expressions. |
Integer division truncates toward zero; remainder has the dividend's sign. Integer arithmetic checks overflow and division/remainder by zero; negative integer powers fail. Float arithmetic uses C double operations, including NaN and infinities where the platform provides them. Dynamic numeric conversions are explicit with T(value); compatible numeric literals can take a contextual type.
| Range containing b | Equivalent condition |
|---|---|
| b in a..=c | a <= b and b <= c |
| b in a..<c | a <= b and b < c |
| b in a<..=c | a < b and b <= c |
| b in a<..<c | a < b and b < c |
| b in ..<c / b in ..=c | The corresponding range starting at zero, including zero. |
The table gives truth conditions for already computed values. The tested expression in membership is evaluated once. These identities are not unrestricted source rewrites for effectful expressions: range-bound work can be prepared before the comparisons, and an expanded and condition can evaluate the tested expression twice. Bind values first when evaluation effects matter. Descending and endpoint-excluded empty ranges contain no integers. The four forms work in for, reversed, in/not in, and draw. Exclusive endpoints remain safe at Int minimum and maximum. Bounds and the tested value must be Int; ranges are syntax for these operations, not stored values or slices. Only ..< and ..= have an omitted-start form.
fn +, -, *, /, %, **, ==, <, and in may define operators for user types; operands are values, not var parameters. The comparison forms >, <=, >=, and != are derived from < or == as implemented by the checker. Equality hooks are used inside aggregates and membership. Bool and/or/not do not invoke numeric truthiness. There are no bitwise, shift, increment/decrement, ternary, or user-defined-precedence operators. Write a < b and b < c rather than a < b < c.
ranges.star99fn main() {
for n in 0<..<4 do print(n)
println()
for n in ..<5 do print(n)
println()
reversed(for n in 0<..=3 do print(n))
println()
println(2 in 0<..<4, " ", 4 in 0<..=4, " ", 0 in 0<..<4)
}Output
123 01234 321 true true false
Functions & control flow
Functions
Arguments evaluate left to right; positional before named; then defaults. Plain parameters are read-only, without entry copies. do/final expression returns a value; return exits explicitly. Recursion needs a result type. Discard results with _ = call().
fn scale(value: Int, factor = 2) -> Int do value * factor
fn factorial(n: Int) -> Int {
if n <= 1 do return 1
return n * factorial(n - 1)
}
fn main() {
println(scale(4), " ", scale(4, factor: 3))
println(factorial(5))
_ = scale(8)
}Output
8 12 120
Evaluation order and mutation
Fragmentfn bump(var a, b: Int) {
a += 1
b += 1
}
# Inside a caller:
var x = 1
var y = 2
bump(&x, &y)var applies to every parameter in its group. Use the parameter directly inside the function; no .* is needed. A plain parameter is read-only. Assignment into owned storage copies its value.
Arguments evaluate left to right. For a[i()].b[j()] = value(), i() runs, then j(), then value(); the destination is reached last. Compound assignment follows the same ordering.
Access parameters and constant defaults
var is a parameter mode, not a storable field type. Inside the function, storing n from var n: T copies the T value; it does not store an alias to the caller. Use an explicit Ref(T) when a link must be retained. A const binding or plain parameter forbids mutation of its owned value, but does not freeze an independently referenced target.
Defaults permit literals, named constants, constant arithmetic, and constant aggregate construction. They reject ordinary function calls and references to other parameters. A type projection such as Point.x names that record field's type; a union projection such as Shape.circle can select a particular variant in a function parameter.
if / switch / blocks
All can produce values. Value branches need complete coverage; mixed numeric types are rejected. Other differing types can form unions. default comes last; no fallthrough. return exits the function.
fn describe(n: Int) -> String {
switch n {
case 0: return "zero"
case 1, 2: return "small"
default: return "other"
}
}
fn main() {
const n = 2
const sign = if n > 0 do "positive" else "nonpositive"
const total = {
var sum = 0
for i in 1..=3 do sum += i
sum
}
println(sign, " ", describe(n), " ", total)
}Output
positive small 6
Narrowing and mutable switch
mutable-switch.star99union V (Int, String)
fn main() {
var v: V = 3
switch &v {
case Int: v += 1
default:
}
println(v)
}Output
4
switch value in expression introduces an explicit binding. switch value is shorthand only for a plain name. A normal binding is read-only; switch &value updates the original payload. The same form works for Any. A switch binding also labels its switch.
A block used as a value ends in an expression. break cannot supply a value or leave such a value block. return always exits the function, including from nested switches and blocks.
Case labels and exhaustiveness
Fragmentswitch n {
label selected = case 1: {
if finished do break selected
println(n)
}
default:
}A case can have label name = case ...: or label name = default:. break name leaves the labeled case/switch region; it does not fall through to the next case. Case labels are also placement regions for macros. A union switch must cover every variant and nil when present, or provide default. A Bool switch may cover true and false without default; value switches over open-ended sets and Any switches require default. Duplicate patterns and a default before another case are errors.
Loops, labels, defer
..< excludes the upper bound; ..= includes it. <..< and <..= also exclude the lower bound; ..<end and ..=end imply an inclusive zero start. for xs binds it; two names bind index/value or key/value. for x: T in xs filters union/Any payloads. Pool bindings are checked references; other built-in loop bindings are read-only values. break name exits a label; continue name requires a loop. reversed accepts list/string/range loops. List/string length is captured once; shrinking can invalidate later indices. defer runs on block exit, last-in-first-out, after evaluating a return value.
fn main() {
var n = 0
while n < 3 {
n += 1
}
for i, value in [10, 20] {
println(i, ": ", value)
}
reversed(for x in 1..=3 do print(x))
println()
label outer = for row in [[1, 2], [3, 4]] {
for cell in row {
if cell == 3 do break outer
print(cell)
}
}
println()
defer println("finished")
}Output
0: 10 1: 20 321 12 finished
Mutation during iteration
| Source | Rule |
|---|---|
| List / String | Initial length, current values at each step. Append is not visited; shrink may cause a bounds failure. |
| Reversed list / string | Same mutation rules; reverse index order, not a copied snapshot. |
| Map | Initial entries in insertion order. Skip removed keys; do not visit newly added or re-added entries. |
| Managed element binding | A copy, not an implicit mutable reference to the element. |
| Temporary source such as make_list() | Iterates over that produced value. |
var total = 0
for [1, 2, 3] do total += it
for number: Int in values do println(number)
# values must be a list or pool of union/Any values.Both names in for i, item in xs label the loop. break item and continue i target it. Labels and variables share a namespace; labels cannot shadow visible variables. it_index is supplied by custom loop templates, not by every implicit built-in loop.
Deferred work
Fragmentfn example() -> Int {
defer println("last")
defer println("first")
return 7
}The return value is computed first; defers then run in reverse order: first, last. A loop-body defer runs on each step’s exit. break and continue also leave scopes and trigger their deferred work.
Binding types and range endpoints
| Source | One binding | Two bindings |
|---|---|---|
| List(T) / List(T, n) | T value | Int index, T value |
| String | U8 byte | Int byte index, U8 byte |
| Map(K, V) | K key | K key, V value |
| Pool(T) | Ref(T) to the live item | Rejected |
| Int range | Int value | Rejected |
Ordinary list/map bindings are read-only values; mutate the container through explicit indexing/access. A pool binding is a copied Ref(T), so item.* addresses the pool item. Filtered loops use for x: T in a list or pool of union/Any values; the body runs only for matching payloads. Range endpoints are evaluated once before forward or reversed iteration. Use the four range operators in the operator reference to choose inclusive/exclusive endpoints.
Current reversed syntax limitation
Give reversed an explicit loop binding: reversed(for x in items do use(x)). The current macro does not support the implicit-it form reversed(for items do use(it)). Ordinary forward for items loops still support it. This is an implementation limitation of reversed, not a different container iteration rule.
Closures
Function type: fn (Int) -> Int. Captures are live locals; escaping closures keep them alive. Copies share captures. Globals are not captured.
fn counter() -> fn () -> Int {
var n = 0
return fn () -> Int {
n += 1
return n
}
}
fn main() {
var next = counter()
var same = next
println(next(), " ", same(), " ", next())
}Output
1 2 3
Copying function values
closure-sharing.star99fn main() {
var n = 0
var f = fn () { n += 1 }
var g = f
f()
g()
println(n)
}Output
2
Nested named functions can also capture locals. Function literals use named parameters; function types omit parameter names. A function returning a closure must state a function result type when inference cannot determine it. Calling a nil function value is a run-time failure.
Coroutines
coroutine(fn name(...) -> R { ... }, Y) declares a function that pauses. yield(v) hands out a Y and stops there. The function is never called directly: it runs inside a value of type Coroutine(name), and resume(&c) runs it to its next yield or to its end. -> R is optional and never inferred.
coroutine(fn countdown(from: Int) -> String {
var n = from
while n > 0 {
yield(n)
n -= 1
}
return "liftoff"
}, Int)
fn step(var c: Coroutine(countdown)) {
switch v in resume(&c) {
case .yielded: println("yielded ", v, " at ", c.at)
case .returned: println("returned ", v, " at ", c.at)
}
}
fn main() {
var c: Coroutine(countdown) = .(args: .(from: 3))
var saved = c # a copy goes on by itself
while c.at != -1 do step(&c)
step(&c) # finished: gives its result again
step(&saved)
saved.s1.n = 10 # kept locals can be changed between resumes
step(&saved)
}Output
yielded 3 at 1 yielded 2 at 1 yielded 1 at 1 returned liftoff at -1 returned liftoff at -1 yielded 3 at 1 yielded 9 at 1
| Coroutine(name) field | Meaning |
|---|---|
| args | The arguments, as an anonymous struct. Fields start at zero; parameter defaults do not apply. |
| s1, s2, ... | Locals that live across a yield, one field per scope in source order; s1 is the body. Other locals stay ordinary C locals. |
| returned | What it returned, once finished. Only with -> R. |
| at | 0 before the first resume, k while paused at yield point k (source order, from 1), -1 once finished. |
| resume(&c) gives | When |
|---|---|
| .yielded(v) | The body reached yield(v). |
| .returned(r) | The body returned; at becomes -1. Resuming again gives .returned(r) again. Without -> R, .returned carries nothing. |
The result type is no_nil(union (yielded: Y, returned: R)), so a switch needs no case nil. Every field can be read and changed between resumes; the body reads them when it continues. A copy is a value: it keeps its arguments, locals, and position and goes on by itself. Coroutine(name)(args: ...) also builds one, and args_of(name) and ret_of(name) work.
coroutine(fn pairs(xs: List(Int)) {
fn twice(n: Int) {
yield(n)
yield(n)
}
for x in xs do twice(x) # yields 1 1 2 2 for [1, 2]
}, Int)Functions nested in the body may yield; each call of one is inlined with yield points of its own. Function values, other top-level functions, and recursion through a yielding nested function cannot yield. A yield is a statement, not part of a used value, except the value that ends the body or follows return. It cannot be in defer, in a loop over a map, in a case of switch &, or in a loop over an element such as rows[0].
| Rule | Detail |
|---|---|
| Declaration | File scope only, also in a module (Coroutine(alias.name), alias.resume). May be private. Cannot be named resume, share its name with a function, or take var parameters. |
| Calling name() | Compile error: resume runs it. |
| Kept locals | A reference to one cannot be stored, and a function value that may outlive the resume cannot use one; nested functions and function values passed down can. |
| Failures | A check or fail inside the body fails at the resume that ran it, with the coroutine's source location. An at that is none of its yield points stops the next resume. |
| Implementation | Stackless: the body is a C function that jumps to the yield point in at. No assembly, so tcc works. Programs without coroutines compile to the same C as before. |
| Not in version 1 | Sending values in with resume (write to args instead), a scheduler or I/O waiting, threads, and coroutines declared inside a function or made by a code template. |
Parenless calls
a b c → a(b(c)); commas belong to the innermost call. Bare marked names call with zero arguments. Arguments start after a space on the same line. All overloads must agree. overload_of gets the function value. Indexing/subtraction keep their normal meaning.
parenless(fn double(n: Int) -> Int do n * 2)
parenless(fn show(n: Int) do println(n))
fn main() {
show double double 5
}Output
20
Types, containers & memory
Structs
Construct positionally or by field name. Omitted fields use defaults/zero. Assignment copies owned data; equality is structural. Anonymous type: struct (x, y: Int); contextual value: .(x: 1, y: 2).
struct Point (x, y: Int)
struct Panel (origin: Point, rows = 4, name: String)
fn moved(p: Point, dx: Int) -> Point {
return Point(x: p.x + dx, y: p.y)
}
fn main() {
var panel = Panel(origin: Point(2, 3), name: "main")
panel.origin.y = 8
const q = moved(panel.origin, 10)
println(q.x, " ", q.y, " ", panel.rows)
println(q == Point(12, 8))
}Output
12 8 4 true
Anonymous records and equality
Fragmentvar position: struct (x, y: Int) = .(x: 2, y: 3)
struct Row (name: String, count = 1)
const row = Row(name: "sample")Field groups share their type/default syntax with parameters. Constructors accept positional values first, named values second. Structural equality includes private fields. For maps, equality ignores insertion order; for pools it compares live items in slot order, ignoring removed slots.
Containers
len(x), never x.len. Empty map: [:]. Missing reads/bad indices fail; &map[key] inserts a missing key. Nested indexing: a[i, j]. Maps preserve insertion order; iteration skips removed keys and excludes newly inserted keys.
fn main() {
var xs = [10, 20]
add(&xs, 30)
insert(&xs, 0, 5)
remove(&xs, 1)
resize(&xs, 4)
println(xs, " ", len(xs))
var ages: Map(String, Int) = ["ann": 30]
ages["bob"] = 41
if "ann" in ages do println(ages["ann"])
remove(&ages, "ann")
var pool: Pool(String)
const item = add(&pool, "kept")
println(item.*, " ", item in pool)
remove(&pool, item)
println(item in pool)
}Output
[5, 20, 30, 0] 4 30 kept true false
| Container | Use and operations |
|---|---|
| List(T) | Variable length. Index from zero; add, insert, remove, resize. |
| List(T, n) | Fixed length specified in the type. |
| Map(K, V) | Read and assign by key; membership checks keys; remove by key. |
| Pool(T) | Stable item identity through versioned Ref values returned by add. |
Fixed-size and nested lists
fixed-lists.star99fn main() {
var a: List(Int, 3)
a[1] = 5
println(a, " ", len(a))
var g: List(List(Int, 2), 2)
g[1][0] = 7
println(g)
}Output
[0, 5, 0] 3 [[0, 0], [7, 0]]
A fixed list’s length is part of its type. Use it for a known shape; use List(T) for add/remove/resize. Nested indexing may be written grid[1, 0] or grid[1][0]. Negative resize lengths fail. Growing initializes new elements; shrinking drops the tail.
Operations by container
| Operation | List / String | Map | Pool |
|---|---|---|---|
| Read | xs[index] | map[key] | ref.* |
| Write | xs[index] = value | map[key] = value | ref.* = value |
| Add | add(&xs, value) | map[key] = value | add(&pool, value) → Ref |
| Remove | remove(&xs, index) | remove(&map, key) | remove(&pool, ref) |
| Membership | Value equality / byte or substring | Key exists | Reference still identifies an item |
| Length | len(xs) | len(map) | len(pool) |
insert(&xs, index, value) inserts before a list position. List membership uses structural or overloaded equality. Membership can be overloaded with fn in. There is no string + or built-in elementwise list arithmetic.
Types, empty values, and key restrictions
List(T) is dynamic; List(T, n) is a fixed-size value with a nonnegative compile-time integer length. [] is an empty list literal and [:] an empty map literal; an empty literal needs a destination/context that establishes its types. Map(K, V) keys must be integer types, Bool, or String. Pool(T) stores live items reached by checked Ref(T).
Map reads of absent keys fail, while map[key] = value and &map[key] create a missing entry with type defaults. remove(&map, absent_key) is a no-op. Re-added keys go to the end of insertion order. Fixed lists support indexing, membership, copying, equality, and iteration, but not add/insert/remove/resize.
Strings & bytes
String: distinct byte-list type. Length/indexing count bytes, not Unicode characters. Character literals must be one U8 byte. Escapes: \n \t \r \0 \\ \x41. Raw strings: """...""", one line or many, nothing escaped. add(&s, values...) appends bytes or printed values; str(...) returns text. Printing adds no separators.
fn main() {
var text = "cat"
text[0] = 'b'
add(&text, " ", 12)
println(text)
println("at" in text, " ", 'b' in text)
const bytes = List(U8)(text)
println(String(bytes))
println(len("cat"), " ", 'A' == U8(65))
}Output
bat 12 true true bat 12 3 true
Literal escapes and text construction
Fragmentconst newline = '\n'
const letter = '\x41'
var text = "line 1\nline 2"
add(&text, '\n', "count = ", 3)
const message = str("answer: ", 42)Single quotes produce exactly one byte; empty, multi-byte, or multi-character literals fail. Use double-quoted strings for UTF-8 text. There is no automatic Unicode character indexing. String and List(U8) select different overloads even though both contain bytes.
Copies & references
&place → Ref(T); ref.* dereferences. References follow reassigned variables and keep targets alive. Copies retarget internal self-links; external links stay shared. var parameters mutate the caller via &; they cannot be stored or have defaults. Use Ref for stored links. No raw pointers, pointer arithmetic, or size_of.
fn bump(var n: Int) do n += 1
fn main() {
var xs = [10, 20, 30]
var copy = xs
add(©, 40)
const position = &xs[1]
insert(&xs, 0, 5)
println(position.*, " ", len(xs), " ", len(copy))
xs = [7, 8]
println(position.*)
var count = 1
bump(&count)
println(count)
}Output
10 4 4 8 2
| Reference into | What it follows |
|---|---|
| List | The position, not the element originally stored there. |
| Map | The versioned entry; deletion and re-insertion creates a different entry. |
| Pool | The item and its version; removing it makes access fail. |
| Variable | The variable, including after reassignment. |
Lifetime, self-links, and pool snapshots
Owned fields form trees. Optional union children are owned; Ref fields represent external links or cycles. Copying does not recursively follow Ref targets. Internal links into a copied value are redirected into that copy.
Pool references store an item version. Versions survive a pool copy, so restoring a saved pool can restore its references. A stale reference fails when used; it never silently becomes a reference to a replacement item in the same slot.
Lifetimes are automatic. Stored references keep targets alive. This is not a promise that all storage is promptly returned to the OS: this snapshot uses eager copies with compiler-elided moves, reusable allocation blocks, and permanent cells for some referenced locals. Repeatedly retaining new locals can grow memory use.
Position routes, entry versions, and copies
A list reference records a position, not the identity of an element: insert/remove can change which value occupies that position. Reassignment follows the variable's current list; using a position that no longer exists fails. Nested list references retain the route through the outer place.
Map references identify a versioned entry. Updating its value preserves the reference; deletion, deletion followed by re-insertion, or replacement with independently created entries invalidates it. Restoring a saved map copy restores the copied entries and versions. Pool references have the analogous version rule. These rules prevent a stale reference from silently selecting a new entry.
Identity and narrowed payload access
Reference equality compares checked routes/identity rather than recursively comparing target values. Plain function values cannot be compared in source. Any equality includes the stored type and payload. Shared fields read through a multi-variant union are not mutable places; use switch &value to update a narrowed payload. A reference into a union/Any payload can become invalid when that payload is replaced.
Unions
Ordinary unions start as nil. no_nil(union State (idle, busy)) starts with its first variant and forbids owned recursive containment. Ref links do not contain their targets by value. Use an explicit variant when conversion would be ambiguous. switch v narrows its payload; switch &v mutates it. union (Tree) is an owned optional child; field access through nil fails.
union Value (Int, String, count: Int, done)
fn describe(v: Value) -> String {
switch v {
case Int: return str("integer ", v)
case String: return str("text ", v)
case .count: return str("count ", v)
case .done: return "done"
case nil: return "empty"
}
}
fn main() {
var values: List(Value) = [.Int(3), "hi", .count(9), .done, nil]
for v in values do println(describe(v))
}Output
integer 3 text hi count 9 done empty
struct Tree (value: Int, left, right: union (Tree))
fn main() {
var root = Tree(value: 1)
root.left = Tree(value: 2)
if root.left != nil do println(root.left.value)
}Output
2
Unions without nil
nonil.star99no_nil(union Mode (fast, careful))
struct S (m: Mode, n: Int)
fn main() {
var s: S
println(s)
}Output
(m: .fast, n: 0)
The first variant provides the starting value. Owned recursive containment is forbidden directly and indirectly, including through List. Ref links do not contain their targets by value. Ordinary unions retain nil even when every explicit variant has a payload.
Shared fields and variant names
Fragmentstruct Circle (x: Int, radius: Float)
struct Rect (x, width, height: Int)
union Shape (Circle, Rect)
# Both payload types have x: Int, so shape.x is available.
# Check for nil before reading a possibly empty shape.A shared field has its common field type when all variants agree; otherwise its result is an anonymous union of field types. Named variant groups share a payload type: union Axis (x, y: Int). Use Axis.x(3) or a contextual .x(3) to select one.
Owned recursion and reference links
no_nil forbids owned recursive containment, including paths through lists, pools, maps, structs, and unions. Ref(T) points to T instead of containing it, so reference links are distinct from owned recursion. Ordinary optional union children terminate at nil. A variant with no payload is written by name; payload-bearing variants require their value or a default construction as appropriate.
Overloads & dispatch
Preference: exact → listed union → case dispatch → Any. Ties fail. Union dispatch requires one case per variant; dispatching nil fails. Dispatch is on one argument; other arguments evaluate once. Different case result types form a union. Operator overloads apply inside aggregate operations too.
dispatch.star99struct Circle (radius: Float)
struct Rect (width, height: Float)
union Shape (circle: Circle, rect: Rect, dot)
fn area(c: Shape.circle) do 3.0 * c.radius * c.radius
fn area(r: Shape.rect) do r.width * r.height
fn area(d: Shape.dot) do 0.0
fn main() {
var shapes: List(Shape) = [Circle(2.0), Rect(3.0, 4.0), .dot]
for shape in shapes do println(area(shape))
}Fragmentstruct Vec (x, y: Int)
fn +(a, b: Vec) do Vec(a.x + b.x, a.y + b.y)
fn ==(a, b: Vec) do a.x == b.x and a.y == b.yConversion paths and case selection
Exact matches beat conversions. A value can enter nested unions, but ambiguous alternatives require an explicit variant. Among applicable listed-union conversion paths, shorter paths win ties. Remaining ties are compile errors.
A function accepting the union directly takes precedence over per-case dispatch. Dispatch handles one union argument. Each variant needs exactly one case; the compiler checks coverage. A numeric literal passed as another argument must acquire the same type in every case. Any is accepted through an Any parameter, not automatic case dispatch.
Type & Any
Type values compare with ==; zero is nil. type_of(e) does not evaluate e. args_of(f) yields a parameter struct; ret_of(f) yields the result type. overload_of(f, T, ...) selects exact parameter types. Any copies its payload; inspect with switch. Any does not case-dispatch automatically.
struct Point (x, y: Int)
fn area(w, h: Float) -> Float do w * h
fn main() {
const kinds: List(Type) = [Int, Point, type_of("text")]
var args: args_of(area) = .(w: 2.0, h: 3.0)
println(kinds)
println(type_of(area(args.w, args.h)) == Float)
var value: Any = 7
switch &value {
case Int: value += 1
default:
}
println(value)
}Output
[Int, Point, String] true 8
Type values versus code describing types
| Expression | Kind |
|---|---|
| Int / List(Int) / type_of(x) | Type value; may be compared, stored, printed. |
| args_of(f) | Anonymous parameter-struct type. |
| ret_of(f) | Function result type. |
| overload_of(f, Int) | One function value, selected by exact parameter types. |
| type(def) | TypeExpr syntax returned by a compile-time program query. |
| Expr(Int) | Macro argument syntax checked to produce Int. |
type_of checks its operand without evaluating it. TypeExpr describes syntax; Type is the language’s type value. Type has nil as its zero value. Layout and byte size remain hidden.
Qualified type values
Qualified names such as geometry.Rect work as type syntax and constructors. This compiler does not accept every qualified type name directly as a value expression: println(geometry.Rect) is rejected. When a Type value is needed, use type_of(geometry.Rect()) or type_of(an_existing_value). type_of checks its operand without running the constructor.
All built-in type families and initial values
| Type | Starting value / operations |
|---|---|
| Int = I64; I8/I16/I32; U8/U16/U32/U64 | Zero; checked numeric operations and conversions. Exact integer bounds are in Numbers. |
| Float | 0.0; C double arithmetic. |
| Bool | false; conditions and boolean operators require Bool. |
| String | Empty byte string; distinct from List(U8) for overloading. |
| List(T) / List(T, n) | Empty dynamic list / n initialized elements. |
| Map(K, V) / Pool(T) | Empty container. |
| Ref(T) | Invalid zero reference; dereferencing it fails. |
| fn (T...) -> R / fn (T...) | Nil function value; calling it fails. The latter returns nothing. |
| Type | nil type value; types can be printed and compared. No layout API. |
| Any | nil; switch narrows its stored payload. |
| File | Zero File selects stdout; stdout and stderr are built-in values. No general open/close API. |
| Draw | Choice source passed to arbitrary(d: Draw) by fuzz builders. |
| struct (...) / union (...) | Anonymous composite types with ordinary field/default or optional-union rules. |
| no_nil(union (...)) | Non-nil union, initialized to its first variant. |
| Expr(T) / Raw(CodeType) | Macro parameter wrappers: checked expression syntax / unexpanded syntax. Not generic runtime containers. |
T() constructs the starting value of a constructible type. A typed nil is distinct from an empty list or empty String, even when their implementations share zero representations. Named structs/unions have their own type identity. The compiler supplies no user-visible Void type, type alias declaration, inheritance, or general generic declaration syntax.
Memory model and limits
Value semantics describe behavior, not a fixed C layout. The compiler chooses storage and may elide copies. A checked reference either resolves or reports an error.
Snapshot implementation
This version uses eager deep copies with moves at eligible last uses and returns. It does not implement copy-on-write. Short lists can store elements in their headers; allocated blocks are reused by size class. Some loops use temporary allocation regions when the compiler proves no managed value escapes. None of these optimizations changes the value model.
Retention and analysis
Escaping closures retain counted cells; stored references may retain permanent cells. Free blocks may stay reserved for reuse and generation checking. Do not assume scope exit reduces process memory. Use locals, allocates, and checks in build to investigate lifetimes and potential work.
Programs & modules
I/O
fn print(x: T) customizes printing and inherits the current output stream. run executes shell syntax; quote data with shell_quote. A zero File is stdout.
fn main() {
println("ready")
println(stderr, "status: ", 3)
const message = str("items: ", 4)
println(message)
println(arguments())
}| Operation | Behavior |
|---|---|
| print(values...) / println(values...) | Write to standard output; println adds a newline. |
| println(stderr, values...) | Write to the selected File stream. stdout is also a File value. |
| str(values...) | Return printed values as one String. |
| read_file(path) | Read a file as text; path "-" reads standard input. |
| write_file(path, text) | Write text to a file. |
| arguments() | Run-time arguments, or compiler arguments following -- during macro execution. |
| file_exists(path) | Test whether a file exists. |
| getenv(name) | Read an environment variable. |
| run(command) | Execute a shell command and return its status. |
| exit(code) | End the program with a status. |
struct Point (x, y: Int)
fn print(p: Point) do print("<", p.x, ", ", p.y, ">")
fn main() {
println(Point(2, 3))
}Output
<2, 3>
File and shell fragments
Fragmentconst text = read_file("input.txt")
write_file("output.txt", text)
assert(file_exists("output.txt"))
const input = read_file("-") # Standard input.
const status = run("printf hello")
const captured = shell("printf hello")File fragments perform real I/O when run. write_file replaces file contents. run returns status; shell captures command output (stdout and stderr together) through a pipe. getenv reads environment values. Use shell_quote for data embedded in command text; arguments are not automatically shell-escaped by run.
Fragmentfn main() {
const args = arguments()
if len(args) == 0 {
println(stderr, "usage: app NAME")
exit(1)
}
println("hello ", args[0])
}Prelude helpers: complete program
library-helpers.star99fn main() {
println(lines("a\n\nb\n"))
println(shell_quote("it's ready"))
println(shell("printf captured"))
write_file("sample.txt", "saved")
println(file_exists("sample.txt"), " ", read_file("sample.txt"))
println(last_number("result: 42\n"))
println(abs(-3), " ", floor(-2.5), " ", sqrt(9.0))
}Output
["a", "", "b"] 'it'\''s ready' captured true saved 42 3 -3.0 3.0
Checks
assert(c[, message]) is always enabled. fail(message) aborts; unreachable() marks an impossible path. Checks report source locations; failed comparisons show operands. Macro failures become compile errors.
fn sum(xs: List(Int)) -> Int {
var result = 0
for x in xs do result += x
return result
}
fn main() {
assert(sum([1, 2, 3]) == 6)
assert(len([4, 5]) == 2, "expected two items")
println("checks passed")
}Output
checks passed
| Diagnostic or symptom | Correction |
|---|---|
| Unused call result | Use the result or write _ = call(). |
| Unknown generated name | Place the macro that generates it before the use. |
| Inferred recursive result | Write -> ResultType on the function. |
| Missing map key | Check key in map before reading, or assign the entry. |
| Invalid reference | Check container mutation and whether the route still exists. |
| Mixed numeric values | Write compatible literals or explicit conversions. |
Modules
Module = directory of shared declarations. First fragment: lib/geometry/geometry.star99; second: main.star99. collection is main-module-only. Block imports require an alias and precede other statements. private hides names, not printed/compared data. Parameterized modules declare module (family: String, scan_ms = 10); distinct constant arguments create distinct aliased instances.
struct Rect (width, height: Int)
fn area(r: Rect) -> Int do r.width * r.height
private fn doubled(n: Int) -> Int do n * 2Fragmentcollection lib = "lib"
import "lib:geometry" as geometry
fn main() {
println(geometry.area(geometry.Rect(3, 4)))
}Fragmentcollection lib = "lib"
import "lib:plc" (family: "Micro800", scan_ms: 50) as small
import "lib:plc" (family: "CompactLogix") as largeParameterized module: complete layout
Create these two files. The two imports instantiate the same source with different constant parameters. The ZIP includes this layout in parameterized/.
Fragmentmodule (prefix: String, count = 1)
fn message() -> String do str(prefix, ": ", count)lib/message/message.star99Fragmentcollection lib = "lib"
import "lib:message" (prefix: "one") as first
import "lib:message" (prefix: "two", count: 2) as second
fn main() {
println(first.message())
println(second.message())
}The second block is main.star99; only two source files are needed (the module is instantiated twice). Build from their parent directory with star99 main.star99. Expected output: one: 1, then two: 2.
Identical argument keys reuse a module instance (see the instance-identity rules). Module arguments may use literals, importing-file constants, and constant arithmetic. Imports in blocks must come first and use an alias. Collection declarations belong to the main module; there is no -collection flag.
Privacy and generated code
private may mark one declaration, fields, or a block of declarations. Outside code cannot name a private member. Whole-value print and equality still include private fields. A module’s macros may emit references to its private names; therefore exported --expand text is not always independently compilable.
Discovery, scope, and instance identity
A directory module reads its non-hidden .star99 files in sorted filename order; it does not recursively include subdirectories. A single-file invocation reads that file as the main module. Module declarations share a scope, while imports and aliases belong to their importing file or explicit block. Relative module paths are resolved from the importing source file; absolute imports are rejected.
Instance caching uses the module path plus the supplied argument sequence, including argument names and omissions, after the compiler's constant normalization. Identically keyed imports reuse the instance. Supplying the same effective values through different named/positional/default forms is not guaranteed to share type identity. Keep the argument form consistent when shared instance identity matters.
Symbolic algebra
Builds an expression tree with overloaded operators. The build hook formats its source and compiles with tcc.
union Symbol (
expr: struct (
op: union (add, multiply)
left, right: union (Symbol)
)
String
Float
Int
)
fn *(a, b: Symbol) do Symbol.expr(op: .multiply, left: a, right: b)
fn +(a, b: Symbol) do Symbol.expr(op: .add, left: a, right: b)
fn print(a: Symbol) {
switch a {
case nil: print(stdout, "nil")
case .expr: {
var op = switch a.op {
case nil: "nil"
case .add: "+"
case .multiply: "*"
}
print("(", a.left, str(" ", op, " "), a.right, ")")
}
case String: print(a)
case Float: print(a)
case Int: print(a)
}
}
fn main() {
var x: Symbol = "x"
var f = 2 * x + 3 * x * x
println(f)
}
macro fn build(b: Build) {
for f in b.sources {
const text = read_file(f)
const tidy = format(text)
if tidy != text do write_file(f, tidy)
}
_ = run(command(Cc(compiler: "tcc"), b))
}Output
((2 * x) + ((3 * x) * x))
Metaprogramming
Macros
macro fn executes at compile time; returned code replaces its call. code { ... } / code(expr) create templates; $x splices. Template-local names are hygienic. literal(v) constructs code for a value; str(code) formats syntax. Typed arguments expand first; Raw receives unexpanded syntax.
import "std:code"
macro fn swap(a, b: Expr) -> Code do code {
var tmp = $a
$a = $b
$b = tmp
}
fn main() {
var x = 1
var y = 2
var tmp = 99
swap(x, y)
println(x, " ", y, " ", tmp)
}Output
2 1 99
| Parameter type | Accepted input |
|---|---|
| Expr | An expression as syntax. |
| Expr(Int) | An expression checked to produce Int. |
| Stmt / Decl | A statement or declaration. |
| TypeExpr | Syntax that describes a type. |
| Function / For / Call | A particular syntax construct. |
| Code | General code: Stmt or TypeExpr. |
| Raw(Expr) | Expression syntax before its own macros expand. |
import "std:code"
macro fn answer() -> Code do literal(42)
fn main() {
println(answer())
macro for n in [1, 2] {
println("step ", $(literal(n)))
}
}Output
42 step 1 step 2
Template splices and names
Fragmentmacro fn make_constant(id: String, value: Int) -> Code {
const expression = literal(value)
return code { const $id = $expression }
}$x can fill an expression, statement list, declaration name, field name, type name, or label when its value fits that position. String splices used as code are parsed during compilation. literal(text) instead produces a quoted string value.
Template-declared names are fresh per expansion. Caller-supplied names and labels retain their meaning. Code values are ordinary typed data; code templates also work at run time where the involved operations do not require compiler parsing. Expr → Stmt → Code and Decl → Stmt → Code are the code-union conversion paths.
Typed sites, parsing, and code data: complete program
syntax-api.star99import "std:code"
macro fn checked(e: Expr(Int)) -> Expr {
assert(str(type_at(e)) == "Int")
var names = 0
for n: Name in walk(e) {
assert(def_of(n) == nil)
assert(local_of(n) != nil)
names += 1
}
assert(names == 1)
assert(str(parse_expr("1+2")) == "1 + 2")
assert(str(parse_type("List(Int)")) == "List(Int)")
assert(len(parse_stmts("var x = 1")) == 1)
assert(str(splice_expr("1+2")) == "1 + 2")
assert(str(name("n")) == "n")
assert(str(splice_exprs(3)[0]) == "3")
assert(len(splice_params("x")) == 1)
assert(fresh("temporary") != fresh("temporary"))
return e
}
fn main() {
var n = 2
println(checked(n + 1))
println(code(a<..<b))
println(code__decode(List(Int), code__encode([1, 2])))
}Output
3 a<..<b [1, 2]
Expansion results and constant-value arguments
A macro expanded from ordinary source returns syntax (Expr, Stmt, Decl, TypeExpr, Code, or their concrete syntax types), or returns nothing. An Int/String/Bool result is not automatically inserted as a literal: return literal(value) instead. A macro returning no code can be used as a statement but not as a value. Empty Code produces no statements. Inside compile-time code, macro functions are ordinary calls, so compile-time helpers can use ordinary value types.
| Value argument to a source macro call | Accepted form |
|---|---|
| Int / integer type | Compiler-known integer constant expression. |
| Bool | true or false literal. |
| Float | Integer/Float literal syntax; arbitrary constant computations and unary-negative Float syntax are not generally encoded. |
| String | String literal, or a global const directly initialized with a String literal. |
| List(T) | List literal whose elements can each be encoded for T. |
| Type / arbitrary runtime value | Not a general source-macro argument channel. Use TypeExpr or Expr(T) syntax as appropriate. |
Use Expr(T) to accept a runtime expression as checked syntax, rather than trying to send its unknown runtime value to the macro. Raw(CodeType) retains unexpanded syntax as the fallback; checked Expr(T) overloads are tried first, then ordinary syntax overloads, then Raw overloads. Within one pass the first matching macro overload is selected in declaration order. This is separate from runtime overload conversion ranking.
Macro state & placement
One shared metaprogram, source order. macro var persists between calls. macro if/switch/for select/unroll; untaken branches are parsed, not checked. macro {} creates no scope. Hand-written declarations are collected early; generated names exist only after generation. place adds code to enclosing regions: function, label, macro-label block, file. Positions: start/end/before/after; default start. Identical placements deduplicate; conflicting names fail. Placed names are not hygienic. error(at, ...) / warning(at, ...) report at syntax sites. Returned code cannot introduce macro if/for/switch.
import "std:code"
macro var serial = 0
macro fn next_id() -> Code {
serial += 1
return literal(serial)
}
fn main() {
println(next_id(), " ", next_id())
}Output
1 2
place(end(main), code { println("done") })
place(file, code { const generated = 42 })Working placement example
code-placement.star99import "std:code"
# counter(name) gives a counter variable placed once at the start of main
macro fn counter(id: String) -> Expr {
place(main, code { var $(name(id)) = 0 })
name(id)
}
macro fn helper() -> Expr {
place(file, code { fn twice(n: Int) -> Int do n * 2 })
code(twice)
}
fn main() {
println("start")
for i in 0..<3 {
counter("hits") += 1
counter("hits") += 1
}
println(hits)
label work = {
println(helper()(21))
}
}Output
start 6 42
Timing and placement restrictions
| Situation | Rule |
|---|---|
| Macro/function share a name | If no macro overload fits, ordinary functions may handle the call. |
| Plain global used in macros and run time | Separate values in the two programs. |
| Macro-only name used at run time | Compile error. |
| Early call to inferred function whose body runs macros | Declare its result type to avoid early-body inference. |
| Generated print/equality/arbitrary/valid overload | Cannot retroactively affect earlier use of its type. |
| place(target, code) | Target must enclose the macro call; only adds code. |
| place(main.setup, code) | Paths address nested named regions. |
| Placement into function.params or For.source | Rejected: only code-holding regions accept statements. |
| Placement into loop body | Placed work runs on every iteration. |
| Placement of switch cases | At end(switch), before default. |
| Repeated position | Preserves placement order; identical code deduplicates. |
macro label name = { ... } creates a placement region without a new scope. Its declarations remain visible afterward. A bare macro label name is not supported. Macro-generated code is processed at its insertion point; pending macros are not run by inspection queries.
Compile-time output and checked queries
Macros execute in a shared child process. Its stdout is routed to the compiler's stderr, so macro println output appears during compilation rather than in the executable's later stdout. Ordinary global values have separate instances in the metaprogram and runtime program. Compile-time code can perform I/O; it is executable code, not a sandboxed expression evaluator.
Custom iteration
for_expansion(Expr(T), Code) supplies iteration. Declare it (and optionally it_index); splice $body exactly once. break exits the expansion; unqualified continue targets its inner loop. No named continue to the custom loop, built-in overrides, or reversed custom loops.
import "std:code"
struct Repeat (count: Int)
macro fn for_expansion(r: Expr(Repeat), body: Code) -> Code {
return code {
const times = $r
for it in 0..<times.count {
$body
}
}
}
fn main() {
for n in Repeat(3) do println(n)
}Output
0 1 2
Program inspection
Def: id/name/kind/site. Names in Def positions identify declarations; overloaded names need overload_of. type(def) returns TypeExpr, not Type. walk visits parents before children. Some queries require completed bodies; build is the safest whole-program stage. Reachability/allocation answers can be conservative. This example also prints during compilation.
import "std:code"
fn twice(n: Int) -> Int do n * 2
macro fn inspect() -> Code {
println(type(twice))
println(recursive(twice))
return code {}
}
inspect()
fn main() {
println(twice(4))
}| Queries | What they answer |
|---|---|
| defs, lookup, overloads | Which declarations exist at this point. |
| type, decl_of, made_by | Declaration type syntax, syntax tree, and generating macro call. |
| calls, callers, reaches, recursive | Direct calls, incoming uses, reachable functions, and recursion. |
| calls_by_value | Sites that invoke function values. |
| reads, writes, effects | Global state and observable actions, including reached functions. |
| reads_elsewhere, writes_elsewhere | Access through references, var parameters, and captured locals. |
| locals | Local types, storage lifetime, and sites that keep values alive. |
| allocates, checks, ranges | Generated allocation sites, remaining checks, and known Int ranges; build only. |
| known(query) | An optional answer without forcing an unfinished answer. |
| walk, type_at, def_of, calls_at, local_of | Syntax traversal and information associated with source sites. |
Availability and interpretation
defs returns declarations currently known, in source order. lookup fails for missing or ambiguous names. def_of(Function) identifies the declaration after the macro has returned it and it has been declared. made_by returns an optional generating Site.
calls includes every dispatch case. callers includes function values taken. reaches conservatively includes possible function-value targets. Closures count as part of their creating function. reads and writes cover reachable global accesses; &x counts as a write.
locals reports stack, counted_cell, or permanent_cell lifetimes and keeping sites. allocates, checks, and ranges require build time. with_main preserves these facts from the primary build. known(query) returns an optional answer without forcing early checking.
type_at requires an Expr(T) argument checked before the macro runs. calls_at returns an empty list for built-ins or calls through values. def_of on names may be nil for locals. A query that needs an unfinished body can cause a timing error; move whole-program queries to build.
Declaration questions in build: complete program
program-api.star99import "std:code"
var count = 0
fn increment(n: Int) -> Int {
count += 1
return n + 1
}
fn compute(n: Int) -> Int do increment(n) * 2
fn main() do println(compute(2))
macro fn build(b: Build) {
const d = lookup("compute")
assert(def_handle(d.id).name == d.name)
assert(str(type(d)) == "fn (Int) -> Int")
assert(not recursive(d))
assert(len(calls(d)) == 1)
assert(calls(d)[0].name == "increment")
assert(len(reads(d)) == 1 and reads(d)[0].name == "count")
assert(len(writes(d)) == 1 and writes(d)[0].name == "count")
assert(len(callers(lookup("increment"))) >= 1)
assert(known(writes(d)) != nil)
_ = defs()
_ = overloads(d)
_ = decl_of(d)
_ = made_by(d)
_ = calls_by_value(d)
_ = reaches(d)
_ = reads_elsewhere(d)
_ = writes_elsewhere(d)
_ = effects(d)
_ = locals(d)
_ = allocates(d)
_ = checks(d)
_ = ranges(d)
assert(run(command(Cc(), b)) == 0)
}Output
6
std:code: every record and union
Import "std:code" for syntax data, traversal, printers, and program questions. Every exported record/union declaration is reproduced exactly, including defaults and variant order. Constructor arguments follow these fields. Missing fields receive their type defaults; optional syntax unions use nil. Site positions are one-based line/column values when the compiler provides a source location; constructed nodes may have a zero Site.
| Representation | Meaning |
|---|---|
| Expr → Stmt → Code; Decl → Stmt → Code | Nested tagged-union conversions, not inheritance. |
| Binary.op = ..< / ..= / <..< / <..= | Explicit-start range, with left and right bounds. |
| Unary.op = ..< / ..= | Omitted zero start; operand is the upper bound. |
| Call.names / Anonymous.names / Variant.names | Parallel argument-name list; empty names denote positional values. |
| For.binding / index / loop_label | Element/key binding, optional second/index binding, explicit loop label as encoded by the compiler. |
| For.variant | Type filter in for x: T in source; nil without a filter. |
| Case.patterns | Empty list denotes default. |
| Template.statements | Distinguishes code { statements } from code(expression). |
| Param / Function / Closure | Syntax metadata is exactly the fields listed; do not infer additional source-layout or semantic fields. |
| Def / Local / Check / Range | Compiler analysis records. Range.low/high are inclusive analysis bounds, not source range operators. |
Site
Fragmentstruct Site (file: String, line, column: Int)Name
Fragmentstruct Name (name: String, site: Site)Literal
Fragmentstruct Literal (text: String, site: Site)Call
Fragmentstruct Call (
callee: Expr,
arguments: List(Expr),
names: List(String),
site: Site,
)Field
Fragmentstruct Field (base: Expr, name: String, site: Site)Binary
Fragmentstruct Binary (op: String, left, right: Expr, site: Site)Unary
Fragmentstruct Unary (op: String, operand: Expr, site: Site)Index
Fragmentstruct Index (base: Expr, indices: List(Expr), site: Site)Deref
Fragmentstruct Deref (operand: Expr, site: Site)Addr
Fragmentstruct Addr (operand: Expr, site: Site)ListLiteral
Fragmentstruct ListLiteral (items: List(Expr), site: Site)Entry
Fragmentstruct Entry (key, value: Expr)MapLiteral
Fragmentstruct MapLiteral (entries: List(Entry), site: Site)Anonymous
Fragmentstruct Anonymous (arguments: List(Expr), names: List(String), site: Site)Variant
Fragmentstruct Variant (
name: String,
arguments: List(Expr),
names: List(String),
called: Bool,
site: Site,
)TypeValue
Fragmentstruct TypeValue (type: TypeExpr, site: Site)BlockValue
Fragmentstruct BlockValue (body: List(Stmt), site: Site)IfValue
Fragmentstruct IfValue (condition, then, otherwise: Expr, site: Site)SwitchValue
Fragmentstruct SwitchValue (value: Switch, site: Site)Closure
Fragmentstruct Closure (
params: List(Param),
result: TypeExpr,
body: List(Stmt),
site: Site,
compile_time: Bool,
do_body: Bool,
)Template
Fragmentstruct Template (body: List(Stmt), statements: Bool, site: Site)Splice
Fragmentstruct Splice (value: Expr, site: Site)Expr
Fragmentunion Expr (
Name,
Literal,
Call,
Field,
Binary,
Unary,
Index,
Deref,
Addr,
ListLiteral,
MapLiteral,
Anonymous,
Variant,
TypeValue,
BlockValue,
IfValue,
SwitchValue,
Closure,
Template,
Splice,
)TypeName
Fragmentstruct TypeName (name: String, arguments: List(TypeExpr), site: Site)FunctionType
Fragmentstruct FunctionType (params: List(TypeExpr), result: TypeExpr, site: Site)StructType
Fragmentstruct StructType (fields: List(Param), site: Site)UnionType
Fragmentstruct UnionType (variants: List(Param), site: Site, no_nil: Bool)TypeCall
Fragmentstruct TypeCall (call: Call, site: Site)Size
Fragmentstruct Size (value: Expr, site: Site)TypeExpr
Fragmentunion TypeExpr (TypeName, FunctionType, StructType, UnionType, TypeCall, Size)Param
Fragmentstruct Param (
name: String,
type: TypeExpr,
value: Expr,
is_var: Bool,
site: Site,
is_private: Bool,
)Function
Fragmentstruct Function (
name: String,
params: List(Param),
result: TypeExpr,
body: List(Stmt),
site: Site,
compile_time: Bool,
is_private: Bool,
parenless: Bool,
)Struct
Fragmentstruct Struct (
name: String,
fields: List(Param),
site: Site,
compile_time: Bool,
is_private: Bool,
)Union
Fragmentstruct Union (
name: String,
variants: List(Param),
site: Site,
compile_time: Bool,
is_private: Bool,
no_nil: Bool,
)Global
Fragmentstruct Global (
name: String,
type: TypeExpr,
value: Expr,
constant: Bool,
site: Site,
compile_time: Bool,
is_private: Bool,
)Import
Fragmentstruct Import (
path: String,
alias: String,
arguments: List(Expr),
site: Site,
compile_time: Bool,
)Group
Fragmentstruct Group (
body: List(Stmt),
site: Site,
compile_time: Bool,
is_private: Bool,
)MacroLabel
Fragmentstruct MacroLabel (name: String, body: List(Stmt), site: Site)Module
Fragmentstruct Module (params: List(Param), site: Site)Collection
Fragmentstruct Collection (name, path: String, site: Site)Decl
Fragmentunion Decl (
Function,
Struct,
Union,
Global,
Import,
Group,
MacroLabel,
Module,
Collection,
)DefKind
Fragmentunion DefKind (
function,
macro_function,
global,
constant,
struct_type,
union_type,
)Def
Fragmentstruct Def (id: Int, name: String, kind: DefKind, site: Site)EffectKind
Fragmentunion EffectKind (output, input, files, run, environment, exit, fail)Effect
Fragmentstruct Effect (kind: EffectKind, site: Site)LocalKind
Fragmentunion LocalKind (variable, constant, parameter, var_parameter, binding)Lifetime
Fragmentunion Lifetime (stack, counted_cell, permanent_cell)Local
Fragmentstruct Local (
name: String,
type: TypeExpr,
site: Site,
kind: LocalKind,
lives: Lifetime,
kept_by: List(Site),
)CheckKind
Fragmentunion CheckKind (
bounds,
overflow,
division,
removed,
missing_key,
variant,
nil_dispatch,
conversion,
assert,
fail,
nil_function,
)Check
Fragmentstruct Check (kind: CheckKind, site: Site, in_loop: Bool)Range
Fragmentstruct Range (local: Local, low, high: Int)For
Fragmentstruct For (
binding: String,
source: Expr,
body: List(Stmt),
index: String,
site: Site,
loop_label: String,
compile_time: Bool,
do_body: Bool,
variant: TypeExpr,
)Return
Fragmentstruct Return (value: Expr, site: Site)Assign
Fragmentstruct Assign (op: String, target, value: Expr, site: Site)If
Fragmentstruct If (
condition: Expr,
then: List(Stmt),
otherwise: List(Stmt),
site: Site,
compile_time: Bool,
do_body: Bool,
do_else: Bool,
)While
Fragmentstruct While (condition: Expr, body: List(Stmt), site: Site, do_body: Bool)Block
Fragmentstruct Block (body: List(Stmt), site: Site)Break
Fragmentstruct Break (target: String, site: Site)Continue
Fragmentstruct Continue (target: String, site: Site)Defer
Fragmentstruct Defer (body: Stmt, site: Site)Discard
Fragmentstruct Discard (value: Expr, site: Site)Labeled
Fragmentstruct Labeled (name: String, body: Stmt, site: Site)Switch
Fragmentstruct Switch (
value: Expr,
binding: String,
by_ref: Bool,
cases: List(Case),
site: Site,
compile_time: Bool,
)Case
Fragmentstruct Case (
patterns: List(Expr),
body: List(Stmt),
case_label: String,
site: Site,
)Statements
Fragmentstruct Statements (body: List(Stmt), site: Site)Stmt
Fragmentunion Stmt (
For,
Return,
Assign,
Expr,
Decl,
If,
While,
Block,
Break,
Continue,
Defer,
Discard,
Labeled,
Switch,
Case,
Statements,
)Code
Fragmentunion Code (Stmt, TypeExpr)Node
Fragmentunion Node (
Name,
Literal,
Call,
Field,
Binary,
Unary,
Index,
Deref,
Addr,
ListLiteral,
MapLiteral,
Entry,
Anonymous,
Variant,
TypeValue,
BlockValue,
IfValue,
SwitchValue,
Closure,
Template,
Splice,
TypeName,
FunctionType,
StructType,
UnionType,
TypeCall,
Size,
Param,
Function,
Struct,
Union,
Global,
Import,
Group,
MacroLabel,
Module,
Collection,
For,
Return,
Assign,
If,
While,
Block,
Break,
Continue,
Defer,
Discard,
Labeled,
Switch,
Case,
Statements,
)std:code: every callable and support variable
All public overloads are listed, including the helper functions used by template expansion and syntax printing. Source signatures marked fn are ordinary functions; those that ask the compiler still require compile-time execution. This includes program questions and parse_expr/parse_type/parse_stmts. Constructing, traversing, and printing syntax data can run in ordinary programs when no compiler query is needed. Splice fallbacks that parse Strings require the compiler channel.
allocates · binding · blank_names · callers · calls · calls_at · calls_by_value · checks · decl_of · def_handle · def_of · defs · effects · fresh · is_block · is_if · items_text · literal_code · local_of · locals · lookup · made_by · marked_text · name · overloads · parse_expr · parse_stmts · parse_type · precedence · print · print_arguments · print_body · print_indent · print_marked · print_operand · print_prefix · print_quoted · ranges · reaches · reads · reads_elsewhere · recursive · same_group · simple · site_of · splice_decl · splice_expr · splice_exprs · splice_name · splice_params · splice_stmt · splice_stmts · splice_type · splice_types · type · type_at · visit · visit_case · visit_switch · walk · writes · writes_elsewhere
allocates (1 overload)
Build-stage allocation sites in generated reachable code. Conservative: an empty answer means no reported allocation; a site means allocation may occur, not that every execution allocates there.
Fragmentfn allocates(f: Def) -> List(Site)binding (1 overload)
Printing binding strength of an Expr. Uses operator precedence, special unary/range rules, and weak binding for closures and conditional values. Does not type-check an expression.
Fragmentfn binding(e: Expr) -> Intblank_names (1 overload)
Produce n encoded empty argument-name strings (s0:) for compiler transport. A negative n produces none. Prefer ordinary names lists when constructing Call syntax.
Fragmentfn blank_names(n: Int) -> Stringcallers (1 overload)
Whole-program incoming function uses: direct calls and taking the function as a value. Requires a completed program because later code can add callers.
Fragmentfn callers(f: Def) -> List(Def)calls (1 overload)
Compile-time direct function calls, including every case of dispatch. Builtins are not ordinary Def declarations. Function-value call sites are reported separately.
Fragmentfn calls(f: Def) -> List(Def)calls_at (1 overload)
List of ordinary function Defs a Call site can invoke: one resolved overload or all dispatch cases. Empty for builtins and calls through function values. This returns a List, never nil; a non-Call syntax node is not accepted.
Fragmentfn calls_at(c: Call) -> List(Def)calls_by_value (1 overload)
Sites invoking function values, where no unique direct callee is known. Includes relevant closure-body uses in the owning function's analysis.
Fragmentfn calls_by_value(f: Def) -> List(Site)checks (1 overload)
Build-stage checks remaining in generated code, with CheckKind, Site, and in_loop. Describes generated checking work, not all source-level conditions or a runtime count.
Fragmentfn checks(f: Def) -> List(Check)decl_of (1 overload)
Compile-time declaration syntax, incorporating generated/expanded content known to the compiler. The returned Decl is typed code data, not an editable reference to the existing declaration.
Fragmentfn decl_of(d: Def) -> Decldef_handle (1 overload)
Resolve a compiler declaration ID into its Def record through a compile-time query. IDs belong to this compilation; do not persist them across compiler runs.
Fragmentfn def_handle(id: Int) -> Defdef_of (2 overloads)
Function overload: construct a site-based Def handle for a Function syntax value, usable after that function is declared. Name overload: query the declaration selected at its source site, or nil for locals/builtins and a dispatch callee without one unique declaration. Checked overloaded calls use the selected overload; calls_at exposes dispatch cases.
Fragmentfn def_of(
f: Function,
) -> Def
fn def_of(n: Name) -> union (Def)defs (1 overload)
Compile-time declarations known at this point, in source order. Pending macro expansions are not run merely to populate this list.
Fragmentfn defs() -> List(Def)effects (1 overload)
Possible output, input, files, run, environment, exit, and fail effects through reachable code. Returns Effect records with source sites; it is a compiler approximation, not a runtime trace. In a program with C plugins, EffectKind gains a last variant plugin: String, and C functions report their module's effect, as .plugin("network").
Fragmentfn effects(f: Def) -> List(Effect)fresh (1 overload)
Generate a distinct name base__N using shared fresh_count state, initially seeded by compiler-provided STAR99_FRESH. Normal macro use avoids source-name collisions; manually resetting the exported counter defeats that guarantee.
Fragmentfn fresh(base: String) -> Stringis_block (1 overload)
True when a Stmt value holds Block; a printer predicate.
Fragmentfn is_block(s: Stmt) -> Boolis_if (1 overload)
True when a Stmt value holds If; a printer predicate.
Fragmentfn is_if(s: Stmt) -> Boolitems_text (1 overload)
Remove the leading length field through the first semicolon from an internally encoded list String. Compiler transport helper, not a general text-list parser.
Fragmentfn items_text(s: String) -> Stringliteral_code (1 overload)
Construct literal Expr from already serialized text and Site. Simple literal-leading text is wrapped directly as Literal; other text is parsed through parse_expr. Normally used by literal's compiler implementation, not a replacement for literal(value).
Fragmentfn literal_code(text: String, site: Site) -> Exprlocal_of (1 overload)
Optional Local record for a Name's site. Returns nil when it is not a local. Respect lexical shadowing and use checked syntax when a resolved answer is needed.
Fragmentfn local_of(n: Name) -> union (Local)locals (1 overload)
Local variables, constants, parameters, access parameters, and loop/switch bindings, including TypeExpr, Site, LocalKind, storage Lifetime, and retaining sites. Requires the function's body to be checked.
Fragmentfn locals(f: Def) -> List(Local)lookup (1 overload)
Resolve a declaration by a String name in the compiler's query scope. Missing or ambiguous names are errors; use overloads/overload_of for overloaded functions.
Fragmentfn lookup(name: String) -> Defmade_by (1 overload)
Optional Site of the macro call that generated a declaration; nil for a hand-written declaration.
Fragmentfn made_by(d: Def) -> union (Site)marked_text (1 overload)
Print Code to String while preserving internal module-ownership markers: set keep_marks true, print, then reset it to false. It does not restore a previously true flag. Intended for compiler transport, not ordinary display.
Fragmentfn marked_text(c: Code) -> Stringname (1 overload)
Construct Name syntax wrapped as Expr. It does not parse or validate the String as a complete expression; the compiler checks generated code when inserted.
Fragmentfn name(text: String) -> Exproverloads (1 overload)
Compile-time list of the named function declaration's overloads. Pass a resolved declaration handle; use overload_of when the source name itself is ambiguous.
Fragmentfn overloads(d: Def) -> List(Def)parse_expr (1 overload)
Compile-time compiler parsing of one expression from String, returning Expr. Parsing does not itself execute the code or establish its runtime type. Malformed text is a compile error.
Fragmentfn parse_expr(text: String) -> Exprparse_stmts (1 overload)
Compile-time compiler parsing of statement text into List(Stmt). Useful for statement-list splices; invalid syntax is a compile error.
Fragmentfn parse_stmts(
text: String,
) -> List(Stmt)parse_type (1 overload)
Compile-time compiler parsing of type syntax from String, returning TypeExpr. This is syntax construction, not name resolution or a Type value.
Fragmentfn parse_type(text: String) -> TypeExprprecedence (1 overload)
Printing precedence for an operator String. Power: 8; multiplication/division/remainder: 6; addition/subtraction: 5; all four range operators: 4; comparisons/in/not in: 3; and: 1; or: 0; unknown strings: 9. This does not add a parser operator.
Fragmentfn precedence(op: String) -> Intprint (64 overloads)
Print the corresponding syntax or program-information record to the active stream. All overloads are listed. Code printers use four-space indentation and grammar-aware parentheses, but do not retain source comments or the formatter's explicit multiline-list metadata. Printing a syntax value does not type-check or execute it.
Fragmentfn print(d: Def)
fn print(s: Site)
fn print(e: Effect)
fn print(l: Local)
fn print(c: Check)
fn print(r: Range)
fn print(e: Name)
fn print(e: Literal)
fn print(e: Call)
fn print(e: Field)
fn print(e: Binary)
fn print(e: Unary)
fn print(e: Index)
fn print(e: Deref)
fn print(e: Addr)
fn print(e: ListLiteral)
fn print(e: MapLiteral)
fn print(e: Anonymous)
fn print(e: Variant)
fn print(e: TypeValue)
fn print(e: BlockValue)
fn print(e: IfValue)
fn print(e: SwitchValue)
fn print(e: Closure)
fn print(e: Template)
fn print(e: Splice)
fn print(e: Expr)
fn print(xs: List(TypeExpr))
fn print(t: TypeName)
fn print(t: FunctionType)
fn print(t: StructType)
fn print(t: UnionType)
fn print(t: TypeCall)
fn print(t: Size)
fn print(t: TypeExpr)
fn print(p: Param)
fn print(ps: List(Param))
fn print(body: List(Stmt))
fn print(d: Function)
fn print(d: Struct)
fn print(d: Union)
fn print(d: Global)
fn print(d: Import)
fn print(d: Group)
fn print(d: MacroLabel)
fn print(d: Module)
fn print(d: Collection)
fn print(d: Decl)
fn print(s: For)
fn print(s: Return)
fn print(s: Assign)
fn print(s: If)
fn print(s: While)
fn print(s: Block)
fn print(s: Break)
fn print(s: Continue)
fn print(s: Defer)
fn print(s: Discard)
fn print(s: Labeled)
fn print(s: Switch)
fn print(c: Case)
fn print(s: Statements)
fn print(s: Stmt)
fn print(c: Code)print_arguments (1 overload)
Print comma-separated argument expressions with aligned optional names from the parallel names list. Missing/empty names mean positional arguments.
Fragmentfn print_arguments(arguments: List(Expr), names: List(String))print_body (1 overload)
Print a single statement following do when requested and applicable; otherwise print a braced statement body using indentation state.
Fragmentfn print_body(body: List(Stmt), do_body: Bool)print_indent (1 overload)
Print four spaces per current indentation level. This reads the exported syntax-printer state.
Fragmentfn print_indent()print_marked (1 overload)
Print a name, hiding its internal module marker unless keep_marks is enabled. Compiler/template support helper.
Fragmentfn print_marked(name: String)print_operand (1 overload)
Print Expr with parentheses if its binding is below least. Uses the active output stream and syntax-printer state.
Fragmentfn print_operand(e: Expr, least: Int)print_prefix (1 overload)
Print macro/private declaration prefixes according to the supplied flags. A syntax-printer helper; it declares nothing.
Fragmentfn print_prefix(compile_time, is_private: Bool)print_quoted (1 overload)
Print a String as escaped, double-quoted Star99 string syntax to the active stream. It is not shell quoting.
Fragmentfn print_quoted(s: String)ranges (1 overload)
Build-stage inclusive lower/upper Int bounds inferred for locals. Returns none when optimization is disabled. The Range record here is analysis data, distinct from source range syntax.
Fragmentfn ranges(f: Def) -> List(Range)reaches (1 overload)
Transitive possible callees. Function-value calls conservatively include functions whose values are taken in the program, so the answer can exceed a particular execution's calls. Whole-program finality may be required.
Fragmentfn reaches(f: Def) -> List(Def)reads (1 overload)
Globals possibly read by the function and everything it reaches. Function-value reachability is conservative. Queries can require completed bodies.
Fragmentfn reads(f: Def) -> List(Def)reads_elsewhere (1 overload)
Sites reading through references, var parameters, or captured access where a named global alone does not describe the target. Includes reached functions.
Fragmentfn reads_elsewhere(
f: Def,
) -> List(Site)recursive (1 overload)
Whether the function participates in possible recursion according to compiler call analysis. Function-value conservatism can affect the answer.
Fragmentfn recursive(f: Def) -> Boolsame_group (1 overload)
Whether two Params can print as one grouped declaration: named, no defaults, matching var/private flags, and equal printed non-nil types.
Fragmentfn same_group(a, b: Param) -> Boolsimple (1 overload)
Printer predicate for a case body that is not If, For, While, Switch, Block, or Labeled. It is not a compiler purity or effect analysis.
Fragmentfn simple(s: Stmt) -> Boolsite_of (5 overloads)
Return a code value's stored Site across expression, type, declaration, statement, and Code union overloads. Nil code yields a zero Site. Does not calculate a runtime caller location.
Fragmentfn site_of(e: Expr) -> Site
fn site_of(t: TypeExpr) -> Site
fn site_of(d: Decl) -> Site
fn site_of(s: Stmt) -> Site
fn site_of(c: Code) -> Sitesplice_decl (2 overloads)
Preserve a Decl or unwrap a Decl held inside Code/Stmt. Fail when the supplied Code is not a declaration; it does not insert or mutate a compiler declaration by itself.
Fragmentfn splice_decl(d: Decl) -> Decl
fn splice_decl(c: Code) -> Declsplice_expr (8 overloads)
Convert supported syntax/value inputs to one Expr. Expr is unchanged; TypeExpr becomes TypeValue; Def becomes a site-marked Name. String is parsed as expression source. Int/Float/Bool become literal-building syntax. Code unwraps expression/type values or falls back to parsing printed text.
Fragmentfn splice_expr(e: Expr) -> Expr
fn splice_expr(t: TypeExpr) -> Expr
fn splice_expr(d: Def) -> Expr
fn splice_expr(s: String) -> Expr
fn splice_expr(n: Int) -> Expr
fn splice_expr(f: Float) -> Expr
fn splice_expr(b: Bool) -> Expr
fn splice_expr(c: Code) -> Exprsplice_exprs (9 overloads)
Produce a List(Expr) for an argument/item-list splice. An existing List(Expr) is unchanged; singleton overloads wrap one converted expression, and List(Code) converts each item. String denotes one parsed expression, not an arbitrary comma-separated list.
Fragmentfn splice_exprs(e: Expr) -> List(Expr)
fn splice_exprs(xs: List(Expr)) -> List(Expr)
fn splice_exprs(s: String) -> List(Expr)
fn splice_exprs(n: Int) -> List(Expr)
fn splice_exprs(f: Float) -> List(Expr)
fn splice_exprs(b: Bool) -> List(Expr)
fn splice_exprs(c: Code) -> List(Expr)
fn splice_exprs(d: Def) -> List(Expr)
fn splice_exprs(cs: List(Code)) -> List(Expr)splice_name (3 overloads)
Convert String unchanged, Def to its name, or Expr to a Name's name / printed syntax. The insertion context ultimately validates the resulting identifier.
Fragmentfn splice_name(s: String) -> String
fn splice_name(d: Def) -> String
fn splice_name(e: Expr) -> Stringsplice_params (3 overloads)
Wrap a Param, preserve List(Param), or make one name-only Param from String. It does not parse a full parameter declaration from String.
Fragmentfn splice_params(p: Param) -> List(Param)
fn splice_params(xs: List(Param)) -> List(Param)
fn splice_params(s: String) -> List(Param)splice_stmt (2 overloads)
Unwrap Code that is already Stmt; otherwise parse its printed text and wrap Statements. A String is parsed as statement source. Parsing paths require compile time.
Fragmentfn splice_stmt(c: Code) -> Stmt
fn splice_stmt(s: String) -> Stmtsplice_stmts (6 overloads)
Produce a List(Stmt) from Code, parsed String, List(Stmt), List(Code), List(Expr), or List(Decl). Existing statement lists are unchanged; other lists are converted element by element.
Fragmentfn splice_stmts(c: Code) -> List(Stmt)
fn splice_stmts(s: String) -> List(Stmt)
fn splice_stmts(xs: List(Stmt)) -> List(Stmt)
fn splice_stmts(xs: List(Code)) -> List(Stmt)
fn splice_stmts(xs: List(Expr)) -> List(Stmt)
fn splice_stmts(xs: List(Decl)) -> List(Stmt)splice_type (4 overloads)
Convert TypeExpr unchanged, parse a String, turn Def into TypeName, or extract/parse Code as TypeExpr. Fallback parsing requires compile-time execution.
Fragmentfn splice_type(t: TypeExpr) -> TypeExpr
fn splice_type(s: String) -> TypeExpr
fn splice_type(d: Def) -> TypeExpr
fn splice_type(c: Code) -> TypeExprsplice_types (4 overloads)
Wrap TypeExpr/Code, preserve List(TypeExpr), or parse one String as a type. Type lists and expression lists use distinct helpers.
Fragmentfn splice_types(t: TypeExpr) -> List(TypeExpr)
fn splice_types(xs: List(TypeExpr)) -> List(TypeExpr)
fn splice_types(s: String) -> List(TypeExpr)
fn splice_types(c: Code) -> List(TypeExpr)type (1 overload)
Compile-time TypeExpr describing a declaration's type: function signature, global type, or declared struct/union syntax. This is written type syntax, not a Type value or byte layout.
Fragmentfn type(d: Def) -> TypeExprtype_at (1 overload)
Compile-time checked-site type query returning TypeExpr. Use Expr(T) macro arguments so the expression and its sites have been checked before querying.
Fragmentfn type_at(e: Expr) -> TypeExprvisit (8 overloads)
Append traversal results to an existing List(Node), across expression/type/statement/declaration and list overloads. These are the public implementation helpers used by walk; the out access parameter is mutated in place.
Fragmentfn visit(var out: List(Node), es: List(Expr))
fn visit(var out: List(Node), body: List(Stmt))
fn visit(var out: List(Node), ps: List(Param))
fn visit(var out: List(Node), ts: List(TypeExpr))
fn visit(var out: List(Node), e: Expr)
fn visit(var out: List(Node), t: TypeExpr)
fn visit(var out: List(Node), d: Decl)
fn visit(var out: List(Node), s: Stmt)visit_case (1 overload)
Append a Case, then its patterns and statements, to traversal output.
Fragmentfn visit_case(var out: List(Node), c: Case)visit_switch (1 overload)
Append a Switch and its value/cases to traversal output in the same order used by walk.
Fragmentfn visit_switch(var out: List(Node), s: Switch)walk (5 overloads)
Parent-before-child traversal of Expr, TypeExpr, Stmt, Code, or List(Stmt), returning List(Node). Node contains concrete syntax types; filter with for n: Call in walk(...), for example. Sites must be checked for semantic queries even though syntax traversal itself works on constructed data.
Fragmentfn walk(e: Expr) -> List(Node)
fn walk(t: TypeExpr) -> List(Node)
fn walk(s: Stmt) -> List(Node)
fn walk(c: Code) -> List(Node)
fn walk(body: List(Stmt)) -> List(Node)writes (1 overload)
Globals possibly written by the function and everything it reaches; taking mutable access with & counts as a potential write.
Fragmentfn writes(f: Def) -> List(Def)writes_elsewhere (1 overload)
Sites writing through references, var parameters, or captured access. Includes reached functions and conservatively exposed mutable access.
Fragmentfn writes_elsewhere(
f: Def,
) -> List(Site)The following support variables are exported in this compiler. They are included for completeness; normal use leaves their state to the library functions that own it.
indentation
Fragmentvar indentation = 0Current syntax-printer indentation level. print_indent emits four spaces per level; printers temporarily change it for nested bodies.
keep_marks
Fragmentvar keep_marks = falseWhether syntax printing preserves internal module-ownership name markers. Normally false; marked_text temporarily enables it.
fresh_count
Fragmentvar fresh_count = -1Counter used by fresh; -1 means not initialized from STAR99_FRESH. Resetting it can create name collisions. This is exported support state, not a reset API.
Builds & entry functions
Build outputs
star99 hello.star99 writes its C to .star99/hello/hello.c beside the program and compiles it with cc -std=c99 -O2 -g -Wall -Wextra -Wpedantic. Everything star99 makes for a program stays in .star99/NAME/: its C, its debug C, its macros' metaprogram (kept by hash, built with tcc when available), and its with_main C files. A directory program keeps its folder inside the directory. Nothing goes to ~/.cache.
| Rule | Detail |
|---|---|
| Only the latest outputs | After each compile the folder holds exactly what that compile made; an edit's older C, metaprogram, or with_main file goes. |
| Removed programs | The folder of a program whose source was deleted or renamed goes too. |
| Failed compile | Leaves the folder as it was. |
| git | .star99/ holds a .gitignore of *, so git ignores it. |
| -o hello.c | Writes the C there instead and stops before the C compiler or build(). |
| STAR99_CC / STAR99_CFLAGS | Another C compiler / more flags; command() in a build() follows them too. |
The prelude is two embedded modules loaded when used: std:prelude (assert, reversed, unreachable) and std:build (Build, Cc, command, and the fuzzing library). A small program without macros loads neither, which makes it compile much faster.
Build hooks
macro fn build(b: Build) replaces the C compiler step; returns no code. Build: c_file/sources/name/strings. Cc: compiler/flags/extra/libs. command(cc, b) respects STAR99_CC and STAR99_CFLAGS. with_main(b, "simulate") selects another zero-argument, no-result entry. format(text) formats; expanded(b) expands. The second fragment requires scan.
fn main() {
println("custom build")
}
macro fn build(b: Build) {
const cc = Cc(extra: "-O0")
assert(run(command(cc, b)) == 0, "C compilation failed")
}Output
custom build
macro fn build(b: Build) {
for a in allocates(scan) do error(a, "scan may allocate here")
for c in checks(scan) {
if c.in_loop do error(c.site, "loop retains a run-time check")
}
assert(run(command(Cc(), b)) == 0, "C compilation failed")
}| Build field | Meaning |
|---|---|
| c_file | Generated C path, in .star99/NAME/ beside the program. |
| sources | Program source files. |
| name | Executable output path used by command(). |
| strings | Program string literals. |
| c_flags, link | Only in a program with C plugins: what their compile hooks gave (see C plugins). command() adds them. |
| Cc field | Default / use |
|---|---|
| compiler | cc; use gcc to select GCC for the final executable. |
| flags | -std=c99 -O2 -g -Wall -Wextra -Wpedantic |
| extra | Additional flags; empty by default. |
| libs | -lm |
The hook runs during compilation, after C generation. It replaces automatic compilation: call run(command(...)) for every executable you want. command returns a shell command; it does not run it. Check each exit status. Building does not run the resulting programs.
Fragmentconst cc = Cc(compiler: "gcc", flags: "-std=c99 -O0 -g0")
assert(run(command(cc, b)) == 0, "GCC failed")This fragment belongs inside build. STAR99_CC overrides Cc.compiler; STAR99_CFLAGS adds flags. Cc controls the final C compilation, not the compiler used to build the macro process. With -o output.c, Star99 writes C and stops before invoking the build hook.
Multiple entry functions
One source program, several executables. Each executable starts at one function. Keep one main; give alternate entries distinct names. No std:code import is required.
multiple-main.star99var runs = 0
fn report(mode: String) {
runs += 1
println(mode, " run ", runs)
}
fn main() {
report("app")
}
fn simulate() {
report("simulation")
}
fn self_test() {
assert(2 + 2 == 4)
report("tests passed")
}
macro fn build(b: Build) {
const cc = Cc()
assert(run(command(cc, b)) == 0, "app compilation failed")
for entry in ["simulate", "self_test"] {
var target = with_main(b, entry)
target.name = str("demo-", entry)
assert(run(command(cc, target)) == 0, "target compilation failed")
}
}Shell./star99 multiple-main.star99
./multiple-main
./demo-simulate
./demo-self_testOutput
app run 1 simulation run 1 tests passed run 1
| Executable | Entry | Output |
|---|---|---|
| multiple-main | main() | app run 1 |
| demo-simulate | simulate() | simulation run 1 |
| demo-self_test | self_test() | tests passed run 1 |
Run the commands from the source directory, with star99 there or with its executable path substituted. Each executable is a separate process: globals start fresh. The runs variable is not shared between them.
| with_main(b, "simulate") | Result |
|---|---|
| Return value | A new Build describing a program rooted at simulate. |
| c_file | A separate generated C file for this entry. |
| name | simulate by default; assign target.name to rename/place the executable. |
| sources / strings | Same source-file and string-literal lists as the original build. |
| Included code | The selected entry and code reachable from it. |
| Side effects | Generates C; does not compile, execute, or recursively invoke build. |
The original b stays unchanged. command(cc, b) builds the normal main executable. Omit that call for alternate-only output. Use distinct target.name paths to avoid replacing another output; create parent directories before compiling into them.
Entry rules: a single, non-macro function resolved by name in the main module; no overloads, parameters, or result. Use fn simulate() { ... }, not fn simulate(args: List(String)) or fn simulate() -> Int. Read arguments with arguments(); set an exit status with exit(code). Call with_main only while the build hook is running.
Fragmentfn simulate() {
println(arguments())
}
# After building: ./demo-simulate fast 100Ordinary simulate() calls only execute that function inside the current process. with_main chooses a separate executable entry. Build-time arguments after star99 ... -- are also separate from arguments passed when launching the executable.
| Problem | Fix |
|---|---|
| No function to start at | Pass the exact function name as a String; not a call or executable filename. |
| A main is one function | Use a non-overloaded entry wrapper. |
| A main takes no parameters and returns nothing | Move parameterized work into a helper; call it from the entry. |
| Works only in build | Move with_main into macro fn build(b: Build). |
| No executable appeared | Run command(cc, target) and check its status; generating Build alone is insufficient. |
C plugins, libraries & the editor
C plugins
A plugin is a module with C in it: how Star99 programs use C libraries. One built-in, c, writes the C, in two places, and the module's compile hook says what the C needs to build. Plain values cross between Star99 and C; no pointer ever reaches Star99 code.
| Form | Meaning |
|---|---|
c("""...""", effect: "name") | At file scope: C the module's functions share (includes, types, helpers, state), and what those functions do. One effect per module. |
fn name(...) -> T do c("""...""") | A whole body: a function written in C. Its parameters are C variables of their names; its C returns the result. effect: "..." overrides the module's, effect: "" for none. Calls are checked like any calls, with defaults and named arguments. |
macro fn compile(var b: Build) | The module's compile hook: ordinary compile-time Star99 that adds to b.c_flags (-I, -D) and b.link (-l, -L), each a List(String). It may ask shell("pkg-config --libs sdl3"), choose flags per platform, or fail with what to install. |
| Star99 | C |
|---|---|
| Int, I8 ... I64, U8 ... U64 | int64_t, int8_t ... uint64_t |
| Float | double |
| Bool | bool |
| String, List(U8) | s99_str (s99_list *): read with s99_str_len(s) and s99_str_data(s); give a new one with s99_bytes(p, n). |
Parameters are lent: the C reads them during the call and keeps nothing of them. A C object is an Int that stands for it, kept by the plugin's C; the Star99 side wraps it in a struct with a private field, so other code cannot make or change one, and gives errors as values, union (Counter, Error). This plugin keeps counters in C and needs TALLY_MAX from its compile hook:
# A C plugin: counters kept by C, which Star99 code holds as handles.
c("""
static int64_t tally_counts[TALLY_MAX + 1] = {0};
static int64_t tally_used = 0;
""", effect: "tally")
# What its C needs to compile; runs only in programs that carry its C
macro fn compile(var b: Build) do add(&b.c_flags, "-DTALLY_MAX=2")
struct Counter (private id: Int)
struct Error (message: String)
private fn next_slot() -> Int do c("""
if (tally_used >= TALLY_MAX) return 0;
return ++tally_used;
""")
fn counter() -> union (Counter, Error) {
const id = next_slot()
if id == 0 do return Error(message: "no counters left")
return Counter(id: id)
}
private fn bump(id, by: Int) -> Int do c("""
tally_counts[id] += by;
return tally_counts[id];
""")
fn count(n: Counter, by = 1) -> Int do bump(n.id, by)
# A String arrives as s99_str; s99_bytes gives a new one
fn upper(text: String) -> String do c("""
char out[64] = {0};
int64_t n = s99_str_len(text) < 64 ? s99_str_len(text) : 64;
const uint8_t *in = s99_str_data(text);
for (int64_t i = 0; i < n; i++)
out[i] = (char)(in[i] >= 'a' && in[i] <= 'z' ? in[i] - 32 : in[i]);
return s99_bytes(out, n);
""", effect: "")c-plugin/main.star99collection lib = "lib"
import "lib:tally" as tally
import "std:code"
fn three() -> Int {
var total = 0
for i in 0..<3 {
switch n in tally.counter() {
case tally.Counter: total += tally.count(n, by: i + 1)
case tally.Error: println(i, ": ", n.message)
case nil:
}
}
return total
}
macro fn report() -> Code {
println(effects(three))
return code {}
}
report()
fn main() {
const total = three()
println(tally.upper("total: "), total)
}Shellcd c-plugin
/path/to/star99 main.star99
./mainOutput
[.output at main.star99:10:34, .plugin("tally") at lib/tally/tally.star99:13:12, .plugin("tally") at lib/tally/tally.star99:24:12]
2: no counters left
TOTAL: 3The first output line is printed while compiling, by report(); the rest by ./main. effects(f) reports what the C functions f reaches do, by name: .plugin("tally"). In a program with C, EffectKind gains a last variant, plugin: String; an effect named like a std:code kind (effect: "files") reports that kind. Name the function in the main module: a module's function through its alias is a function value, not a Def.
| Building a program with C | What happens |
|---|---|
| 1. C | Generated with only the C functions the program reaches, and the file-scope C of their modules. |
| 2. Compile hooks | The hook of each module whose C it carries runs, in import order (a module's imports before it), each given the Build the one before made. |
| 3. The executable | The C compiler gets the flags the hooks gave; or the program's own macro fn build(b: Build) runs last and gets them in b. command(cc, b) passes them on; a build can read or change them first. |
| Rule | Detail |
|---|---|
| Unused library | Costs nothing: no C, no hook, no flags. |
| Build.c_flags, Build.link | In programs with C only: std:build then declares them, and command() and the fuzz builds add them. Line breaks in an entry (from shell()) become spaces. |
| Placement | c(...) anywhere else is an error: "c(...) is C: it is the whole body of a function, or C at file scope". |
| Types | Parameters and results are numbers, Bool, String or List(U8); no structs, lists of other types, or var parameters. |
| C words | A parameter cannot be named for something C defines (errno). |
| Effects | Two different effect: names in one module are an error. |
| A module's own c | A module that declares a function, macro or variable named c has no C: c(...) there calls its own. |
| Compile time | A C function called from compile-time code runs there too, with the C library only. |
| -o, --expand | Run no compile hooks. |
| with_main | In a program with build(), the hooks of modules that any main-shaped function reaches run too, so with_main builds link. |
| --debug | The plugins' C is preprocessed for its names before the hooks run, so headers that need a hook's -I are read as written. |
Networking: plugins/net
TCP and UDP sockets with timeouts, and the little-endian encoding of binary protocols such as EtherNet/IP and CIP. Effect network. Hosts are names or numeric addresses, IPv4 or IPv6; timeouts are in milliseconds, -1 for none. Everything that can fail gives union (T, Error), Error (message, code) with the errno; a timeout is an error too. Sockets stand for an open socket: copies share it, and using one after close stops the program. The ZIP has the plugin in plugins/net/.
collection plugins = "plugins"
import "plugins:net" as net| Function | Does |
|---|---|
| connect(host, port, timeout_ms = 5000) | A TCP connection: Socket or Error. |
| listen(host, port, backlog = 16) | A Listener; port 0 takes a free one, port(l) says which. |
| accept(l, timeout_ms = -1) | The next connection. |
| send(s, bytes) | Sends all of a List(U8); gives the count. |
| receive(s, max = 65536, timeout_ms = -1) | What came, up to max bytes; no bytes: the other end closed. |
| receive_exactly(s, n, timeout_ms = -1) | Exactly n bytes, or an error. |
| close, is_open, local_address, peer_address, port | For Socket, Listener and Udp. Address (host, port) prints as host:port. |
| set_no_delay(s, on) | TCP_NODELAY. |
| udp_open(host = "0.0.0.0", port = 0) | A UDP socket. |
| send_to(u, bytes, Address), receive_from(u, max, timeout_ms) | Datagrams; receive_from gives Datagram (data, from). |
| set_broadcast(u, on) | Allows sending to a broadcast address. |
| put_u8 ... put_u64, put_i8 ... put_i64, put_f32, put_f64, put_u16_be, put_u32_be, put_bytes | Append to a var List(U8), little-endian unless _be. put_u8 and put_i8 check their range. |
| reader(bytes), u8(&r) ... u64(&r), i8 ... i64, f32, f64, u16_be, u32_be, bytes(&r, n), skip, left | A Reader: reading past the end gives zeros and sets r.failed, so a message is checked once. |
| bits_and, bits_or, bits_xor, bits_not, shift_left, shift_right, bit, with_bit | Bit operations on Int. |
| f32_bits, f32_from_bits, f64_bits, f64_from_bits | The bits of floats. |
Both ends of this example are in one process, on 127.0.0.1 and a port the system chooses:
net-loopback.star99# TCP over 127.0.0.1 inside one process, and a little-endian message.
collection plugins = "plugins"
import "plugins:net" as net
fn main() {
var server: net.Listener
switch r in net.listen("127.0.0.1", 0) {
case net.Listener: server = r
case net.Error: fail(r.message)
case nil:
}
var client, peer: net.Socket
switch r in net.connect("127.0.0.1", net.port(server), timeout_ms: 2000) {
case net.Socket: client = r
case net.Error: fail(r.message)
case nil:
}
switch r in net.accept(server, timeout_ms: 2000) {
case net.Socket: peer = r
case net.Error: fail(r.message)
case nil:
}
# A message: a 16-bit command, a 32-bit length, then the bytes
var out: List(U8)
net.put_u16(&out, 0x65)
net.put_u32(&out, 4)
net.put_bytes(&out, List(U8)("ping"))
_ = net.send(client, out)
switch r in net.receive_exactly(peer, 10, timeout_ms: 2000) {
case List(U8): {
var m = net.reader(r)
const command = net.u16(&m)
const size = net.u32(&m)
const text = String(net.bytes(&m, size))
println("command ", command, ", ", size, " bytes: ", text)
println("past the end: ", net.u32(&m), " failed: ", m.failed)
}
case net.Error: println(r.message)
case nil:
}
# Nothing more comes: the timeout is an error value
switch r in net.receive(peer, timeout_ms: 20) {
case List(U8): println(len(r), " bytes")
case net.Error: println("error: ", r.message)
case nil:
}
net.close(client)
switch r in net.receive(peer, timeout_ms: 2000) {
case List(U8): println("closed: ", len(r), " bytes")
case net.Error: println(r.message)
case nil:
}
net.close(peer)
net.close(server)
println("open: ", net.is_open(server))
}Output
command 101, 4 bytes: ping past the end: 0 failed: true error: timed out closed: 0 bytes open: false
Graphics: plugins/sdl3
Windows, keys and typed text, the mouse, the clipboard, and drawing on a canvas of the window's pixels: rectangles, rounded rectangles, clipping, and FreeType text through SDL3_ttf blended in linear light. Effect graphics. Needs SDL3 and SDL3_ttf; the compile hook asks pkg-config and says what to install. Windows and fonts stand for an open one, as sockets do; opening gives union (T, Error). Sizes are in pixels of the window; scale(w) gives pixels per point on HiDPI screens.
collection plugins = "plugins"
import "plugins:sdl3" as sdl| Function | Does |
|---|---|
| open_window(title, width, height, resizable = true, hidden = false) | A Window with a canvas of its pixels. |
| size(w), scale(w), set_title, close, is_open | Size (width, height), pixels per point. |
| next_event(timeout_ms = -1) | An Event, nil if none came: quit, key: Key, key_up: Key, text: String, resized: Size, mouse_down, mouse_up, mouse_move, wheel: Mouse, focus: Bool, expose. |
| Key (name, code, scancode, ctrl, shift, alt, gui, repeat) | name as SDL gives it ("Return", "Up", "+"); scancode is the key's place, the same with any layout. |
| start_text_input(w), stop_text_input(w) | Typed text arrives as .text events. |
| clear(w, c), fill(w, x, y, width, height, c), fill_rounded(..., radius, c) | Drawing on the canvas. Color (r, g, b, a = 255); rgb(0xrrggbb), with_alpha(c, a). |
| clip(w, x, y, width, height), unclip(w) | Limits drawing to a rectangle. |
| present(w) | Shows the canvas. |
| open_font(path, pixels, lcd = false, hinting = .light) | A Font from a file; lcd for subpixel glyphs on an opaque ground. |
| metrics(f), text_width(f, text), add_fallback(f, other), set_text_gamma(g) | Metrics (ascent, descent, height, advance); a font for the glyphs f lacks. |
| draw_text(w, f, x, y, text, c) | Text with its line's top at y; gives the x after it. |
| save_png(w, path), pixel(w, x, y) | For headless checks: the canvas as a PNG; a pixel as 0xrrggbb, -1 outside. |
| use_video_driver("dummy") | Draws nowhere, for tests and screenshots; before the first window. |
| clipboard(), set_clipboard(text), ticks(), delay(ms) | The clipboard; milliseconds since SDL started; a pause. |
This example opens no window on a screen: the dummy driver and a hidden window. Remove those two to see one.
sdl3-canvas.star99# Drawing with the sdl3 plugin and no screen: the dummy video driver, a
# hidden window, and its pixels read back.
collection plugins = "plugins"
import "plugins:sdl3" as sdl
fn main() {
sdl.use_video_driver("dummy") # before the first window
switch w in sdl.open_window("canvas", 64, 48, hidden: true) {
case sdl.Window: {
println("size ", sdl.size(w), ", scale ", sdl.scale(w))
sdl.clear(w, sdl.rgb(0x1a1b26))
sdl.fill(w, 8, 8, 16, 16, sdl.rgb(0xff8800))
sdl.clip(w, 40, 0, 24, 48) # only x 40 to 63 is drawn now
sdl.fill_rounded(w, 0, 0, 64, 48, 6, sdl.Color(r: 0, g: 200, b: 0))
sdl.unclip(w)
sdl.present(w)
println("orange square: ", sdl.pixel(w, 12, 12) == 0xff8800)
println("background: ", sdl.pixel(w, 30, 30) == 0x1a1b26)
println("clipped green: ", sdl.pixel(w, 50, 20) == 0x00c800)
println("outside: ", sdl.pixel(w, 99, 0))
sdl.close(w)
println("open: ", sdl.is_open(w))
}
case sdl.Error: println("no window: ", w.message)
case nil:
}
}Output
size (width: 64, height: 48), scale 1.0 orange square: true background: true clipped green: true outside: -1 open: false
A real library: pylogix
lib/pylogix reads and writes Allen-Bradley Logix (ControlLogix, CompactLogix) and Micro800 PLCs over EtherNet/IP and CIP. It is a port of pylogix 1.1.6, the Python library by Dustin Roeder (Apache License 2.0), to one Star99 file on the net plugin: the same requests, byte for byte, and the same answers. It imports the plugin by a relative path, so a program needs only collection lib; the ZIP has lib/ and plugins/ side by side.
It talks to a real PLC: point it only at a controller you are allowed to change. Every example in this guide runs against lib/plcsim, a simulated ControlLogix on 127.0.0.1, never a PLC or another host. discover broadcasts to 255.255.255.255 unless given broadcast:.
# pylogix against lib/plcsim: a simulated ControlLogix in a child process
# on 127.0.0.1. Nothing else is contacted.
collection lib = "lib"
import "lib:pylogix" as pylogix
import "lib:plcsim" as plcsim
fn main() {
const sim = plcsim.start(plcsim.demo(), "")
var plc = pylogix.PLC(ip_address: "127.0.0.1", port: sim.port)
println(pylogix.read(&plc, "DintTag"))
println(pylogix.read(&plc, "Pump.Speed"))
const w = pylogix.write(&plc, "DintArray[2]", 17)
println(w, " ok: ", pylogix.ok(w.status))
println(pylogix.read(&plc, "DintArray", count: 4))
for r in pylogix.read_many(&plc, ["BoolTag", "StringTag", "Nope"]) {
println(r)
}
# A value is a union: switch on it to use it
const speed = pylogix.read(&plc, "Pump.Speed")
switch v in speed.value {
case .float: println("twice the speed: ", v * 2.0)
default: println("not a REAL: ", speed.status)
}
var udts = 0
const tags = pylogix.get_tag_list(&plc)
for t in tags.value do if t.struct_flag == 1 do udts += 1
println(len(tags.value), " tags, ", udts, " of them UDTs, ", tags.status)
const device = pylogix.get_device_properties(&plc).value
println(device.product_name, ", ", device.vendor)
pylogix.close(&plc)
plcsim.stop(sim)
}Output
DintTag 123456789 Success Pump.Speed 12.5 Success DintArray[2] 17 Success ok: true DintArray [0, 11, 17, 33] Success BoolTag True Success StringTag Hello from plcsim Success Nope None Path segment error twice the speed: 25.0 29 tags, 5 of them UDTs, Success 1756-L83E/B, Rockwell Automation/Allen-Bradley
For a real controller: pylogix.PLC(ip_address: "192.168.1.9", slot: 0); the connection opens at the first request and stays open until close(&plc).
| PLC field | Meaning |
|---|---|
| ip_address, slot, port = 44818 | Where the controller is. |
| timeout = 5.0 | Seconds, for connecting and for each reply. |
| micro800 | A Micro800: no slot, no route. |
| route: List(Hop) | Hop (port, link: .slot(n) or .address("...")), as pylogix's Route. |
| connection_size | 0: a Large Forward Open (4002 bytes), else 504. |
| string_id = 0x0fce | The STRING type of the controller. |
| known_tags, tag_list, program_names, udt, udt_by_name | What earlier requests learned, as in pylogix. |
| pylogix | Here |
|---|---|
| Read(tag, count, datatype) | read(&plc, tag, count:, data_type:) -> Response |
| Read([tags]) | read_many(&plc, ["A", "B"]), or read_requests(&plc, [ReadRequest(tag, count, data_type), ...]) |
| Write(tag, value, datatype) | write(&plc, tag, value, data_type:); a list from the element named on: write(&plc, "Speeds[0]", values(xs)) |
| Write([(tag, value), ...]) | write_many(&plc, [WriteRequest(tag, value), ...]) |
| GetTagList(allTags), GetProgramTagList(name), GetProgramsList() | get_tag_list(&plc, all_tags:), get_program_tag_list(&plc, name), get_programs_list(&plc) |
| GetPLCTime(raw), SetPLCTime(dst) | get_plc_time(&plc, raw:), set_plc_time(&plc, dst:) |
| Discover() | discover(plc, broadcast:, timeout_ms:) |
| GetDeviceProperties(), GetModuleProperties(slot) | get_device_properties(&plc), get_module_properties(&plc, slot) |
| Message(service, class, instance, attribute, data) | message(&plc, service, cip_class, instance, attribute:, data:) |
| Close() | close(&plc) |
| (none) | read_many_plcs(&plcs, tags): several PLCs at once, a coroutine for each; a poll takes as long as the slowest PLC. |
| Type | Meaning |
|---|---|
| Response (tag, value: Value, status: Status) | Prints as pylogix prints it: tag, value, status text. |
| Value | A union: bool, int, u64, float, string, bytes, list: List(Value), time: DateTime. Numbers, Bool and String convert to it. |
| Status | cip: Int, the CIP general status (0 is success), or error: String where pylogix raises; ok(s) tests success, status_text(n) names a code. |
| TagsResponse, NamesResponse, DeviceResponse, DevicesResponse | Typed values: List(Tag), List(String), Device, List(Device). |
| Tag, Udt, Device, DateTime | As pylogix's; Tag.struct_flag is pylogix's Struct (struct is a Star99 word). |
| type_dint, type_real, ... type_string | CIP data type codes; 0 means none given. |
Where pylogix raises an exception, the port gives a Response whose status is an error; it never stops the program. Not ported: ReceiveMessage, the Adapter class, and the context manager. lib/plcsim answers sessions, Forward Open and Close, routes, reads and writes (also fragmented), the Symbol and Template classes, the Wall Clock, Identity, and ListIdentity over UDP, and logs every request as hex. plcsim.start(plcsim.demo(), log_path) runs it in a child process on a free 127.0.0.1 port (sim.port) until plcsim.stop(sim); demo_micro800() is a Micro800. tools/plcsim.star99 runs it as a program for clients in other processes.
star99 tree
star99 tree FILE prints the file as star99 fmt writes it, then its syntax tree, for tools that edit code by its parts. The editor below makes every change through it. - reads the standard input. A file that does not parse prints its error, and the status is 1.
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice(21))
}Output
42
star99 tree twice.star99Output
star99-tree 1
text 84
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice(21))
}
nodes 18
-1 File - 0 84
0 Function decls 0 32
1 Param params 9 15
2 TypeName type 12 15
2 Name name 9 10
1 TypeName result 20 23
1 Binary body 27 32
6 Name left 27 28
6 Literal right 31 32
1 Name name 3 8
0 Function decls 47 83
10 Call body 63 81
11 Name callee 63 70
11 Call arguments 71 80
13 Name callee 71 76
13 Literal arguments 77 79
10 Name name 50 54
0 Comment comment 34 46| Line | Meaning |
|---|---|
| star99-tree 1 | The format's version. |
| text N | Then the formatted text: N bytes and a line break. |
| nodes M | Then one line per node; node k is the k-th line, from 0. |
| PARENT KIND FIELD LO HI | PARENT is a node number (-1 for the File, node 0). KIND is the std:code type (Function, Param, Call, Name, Binary, ...), or File, Comment, or Named for an argument given by name. FIELD is which part of its parent it is, named as in std:code; name for the name of a declaration, field or binding. LO and HI are byte offsets in the text, HI past the end. |
A node's children are the nodes whose PARENT it is. The name of a declaration is listed after its other parts: sort by LO for source order. Statements span their lines from their first word; other nodes their tokens and the brackets they open.
The projectional editor
tools/edit.star99 is an editor for Star99 written in Star99, on the sdl3 plugin. The program is edited as a tree, never as free text: a node is chosen and replaced, deleted or moved, or a new one is put beside it. Each change is made to the text of a node and goes through star99 tree, so the file stays as star99 fmt writes it, comments and layout kept. A replacement that would change the tree around it (x = 1 typed for an expression) is refused with the reason. Holes (hole__, Hole__ for a type) stand for parts not written yet and show as boxes.
It needs SDL3 and SDL3_ttf, and fontconfig's fc-match to find JetBrains Mono (else the system monospace). Build it from the ZIP's tools/ folder, which finds the plugin in ../plugins:
Shellcd tools
/path/to/star99 edit.star99 # builds tools/edit
STAR99=/path/to/star99 ./edit prog.star99STAR99 names the compiler it checks, runs and formats with (else ../star99 beside the editor, else star99 on the PATH). Checking and running use the text as it is, unsaved: a copy beside the file, so what it imports is found, removed after. Input is handled a frame at a time, and a held key's repeats stop as soon as it is let go.
| Keys | Do |
|---|---|
| arrows, h j k l | Parent, previous and next part, first child. |
| n N, Tab | Next and previous node of the file; next hole. |
| Return or r, c | Edit the node in place; write it anew. |
| o O, a | A new node after, before; at the end of what it holds. |
| d, J K | Delete; move down, up. |
| y p P, # | Copy, paste after, paste over; a comment before. |
| u U, / Ctrl+G | Undo, redo; find, find again. |
| Ctrl+B, Ctrl+R | Check with the compiler (the error's node is selected); build and run. |
| Ctrl+= Ctrl+- Ctrl+0 | Larger, smaller text; as it was. |
| Ctrl+S, Ctrl+O, Ctrl+Q, ? | Save, open, quit, all the keys. |
--test KEYS FILE runs a key script without a window and prints the message, the output of Ctrl+R, the selection and the text; nothing is saved without Ctrl+S. KEYS: key names (j, Return, Escape, Ctrl+S), text typed in braces ({20 + 1}), j*30 for a held key, up:j when it is let go, and | between frames. Here j j l j l j l j walks to the literal 21:
STAR99=/path/to/star99 tools/edit --test 'j j l j l j l j' twice.star99Output
selected: Literal arguments [21]
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice(21))
}STAR99=/path/to/star99 tools/edit --test 'j j l j l j l j c {20 + 1} Return Ctrl+R' twice.star99Output
message: ran twice
output: 42
selected: Binary arguments [20 + 1]
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice(20 + 1))
}STAR99=/path/to/star99 tools/edit --test 'j j l j l j l j c {x = 1} Return' twice.star99Output
message: 5:21: error: expected ')', found '='
selected: Literal arguments [21]
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice(21))
}STAR99=/path/to/star99 tools/edit --test 'j j l j l j l j d Ctrl+B' twice.star99Output
message: line 5: twice needs n
selected: Name callee [twice]
fn twice(n: Int) -> Int do n * 2
# the answer
fn main() {
println(twice())
}--shot FILE.png --keys KEYS draws the editor into a PNG with SDL's dummy driver and no screen (--width, --height, --scale 2 for HiDPI, --lcd for subpixel glyphs).
tools/edit --shot twice.png --keys 'j j l j' --width 640 --height 240 twice.star99Output
wrote twice.png
Built-ins & prelude reference
Built-in API: every operation
Compiler-recognized operations. A signature ending without an arrow returns nothing. Generic words such as numeric and T describe accepted types; they are reference notation, not user-defined generic syntax. Runtime operations also work in compile-time code unless noted. File selectors and access arguments still follow the rules in their entries; a String is never automatically shell-escaped.
print · println · str · len · add · insert · remove · exit · arguments · read_file · write_file · file_exists · run · getenv · shell · abs · sqrt · floor · fail · resize · expanded · ask · known · code__encode · code__decode · with_main · draw · assume · format · literal · here · error · warning · place · type_of · args_of · ret_of · overload_of · yield
print([stream: File,] values...)Write values to the active output stream, stdout initially. No separators or newline are inserted. A leading File selects a stream. A custom print(value: T) overload also affects nested printing and str. Function values and untyped nil cannot be printed.
println
Fragmentprintln([stream: File,] values...)Like print, followed by one newline. println() prints a newline. A leading File is a stream selector.
str
Fragmentstr(values...) -> StringCapture printed representations in a String, with no inserted separators. A custom print overload is honored. Code values print as syntax; this does not perform general parsing or JSON serialization.
len
Fragmentlen(value) -> IntLength of String, dynamic or fixed List, Map, or Pool. String length counts bytes; map/pool length counts live entries. Checked references to containers are followed automatically.
add
Fragmentadd(&list, value); add(&text, values...); add(&pool, value) -> Ref(T)Append one element to List(T), or one item to Pool(T). Pool insertion returns its checked reference. For String, U8 values append bytes and other values append their printed text. List and string forms return nothing. Fixed lists cannot grow.
insert
Fragmentinsert(&list, index: Int, value)Insert before a position in a dynamic list or String; positions 0 through len(list), inclusive, are valid. Later elements move right. String elements are U8. Returns nothing.
remove
Fragmentremove(&list, index); remove(&map, key); remove(&pool, ref)Remove a dynamic-list/String position, map key, or live pool item. List positions must exist; pool references must belong to the pool and identify a live item. An absent map key is a no-op. Returns nothing.
exit
Fragmentexit(code: Int)Terminate the process with the requested status. In a fuzz build it ends the current input; a nonzero status is a failure. This is process termination, not a function return or a deferred-work mechanism.
arguments
Fragmentarguments() -> List(String)Arguments after the executable name. In compile-time code, these are the arguments after -- in the Star99 invocation. They are separate from arguments later passed to the compiled executable.
read_file
Fragmentread_file(path: String) -> StringRead bytes into String; path "-" reads standard input. Failure to open the path aborts. In a fuzz build, read_file("-") returns the current input bytes.
write_file
Fragmentwrite_file(path: String, text: String)Replace a file with the String's bytes. Opening, writing, or closing failure aborts. Returns nothing; no parent directories are created.
file_exists
Fragmentfile_exists(path: String) -> BoolTest whether fopen(path, "rb") succeeds. This is an open-for-reading probe, not a general filesystem metadata or permissions API.
run
Fragmentrun(command: String) -> IntRun shell command text through C system(). Returns the shell exit status on Unix, 128 plus the terminating signal for a signaled shell, or -1 if system() fails. Quote embedded data with shell_quote; the command itself is not automatically escaped.
getenv
Fragmentgetenv(name: String) -> StringCopy an environment variable's value. Missing variables yield an empty String; unset and empty are not distinguished.
shell
Fragmentshell(command: String) -> StringRun shell command text and return what it printed, standard output and standard error together, read through a pipe; no temporary files. The command's exit status is discarded: use run when the status matters. Quote embedded data with shell_quote.
abs
Fragmentabs(x: numeric) -> same numeric typeAbsolute value, preserving the operand's numeric type. Signed minimum has no positive value in the same type and fails the overflow check. Unsigned values are unchanged.
sqrt
Fragmentsqrt(x: Float) -> FloatC math-library square root. This is a Float operation, not an integer square root; domain results follow the platform math library.
floor
Fragmentfloor(x: Float) -> FloatRound toward negative infinity, returning Float. Use an explicit checked integer conversion when an integer is needed.
fail
Fragmentfail(message: String)Stop deliberately with a source-located failure. Ordinary execution aborts; a macro-process failure is reported as a compile error. This is not catchable error propagation.
resize
Fragmentresize(&list, length: Int)Set dynamic List or String length. Growth initializes new elements with zero/type defaults; shrinking drops the tail. Negative or unrepresentable lengths fail. Fixed lists cannot resize. Returns nothing.
expanded
Fragmentexpanded(b: Build) -> StringCompile-time only. During compile-time execution, obtain the main module with macros expanded and placed code included. The Build argument establishes the build interface. Imported-module declarations are not inlined into this text, and private module references can prevent standalone compilation.
ask
Fragmentask(T, "question", values...) -> TCompile-time only. Low-level compile-time query interface used by std:code. The first argument is a type and the question must be a String literal. Prefer the typed wrappers below; their return types and argument encodings must match the question. Additional protocol questions include parse and with_main.
known
Fragmentknown(question(...)) -> union (AnswerType)Compile-time only. Ask a compile-time query without forcing an unfinished answer: returns nil while it is not final, otherwise the answer wrapped in an optional union. A final empty List or false Bool is an answer, not nil. Not a general exception handler.
code__encode
Fragmentcode__encode(value) -> StringCompiler transport helper: encode a typed value in the internal wire representation. It is available in ordinary code too. This is an implementation-specific format, not a stable storage, interchange, or JSON API.
code__decode
Fragmentcode__decode(T, text: String) -> TDecode the compiler's internal representation as the specified type. T must be a type expression. Intended for compiler/template plumbing and matching code__encode; malformed or mismatched encodings are unsupported input.
with_main
Fragmentwith_main(b: Build, name: String) -> BuildCompile-time only. Build-hook-only C generation for another main-module entry. The named entry must be one non-macro function with no parameters and no result. Returns a separate Build without compiling it or invoking build recursively; the primary build's analysis facts remain the query baseline.
draw
Fragmentdraw(d: Draw, range | list | T) -> selected typeConsume fuzz choices to produce an Int in one of the four range forms, a dynamic/fixed-list element, or a compiler-built value of T. Empty ranges/lists fail. Range endpoints are Int and exclusion is safe at their limits. Draw is supplied to arbitrary hooks; ordinary non-fuzz execution cannot create a useful choice stream.
assume
Fragmentassume(condition: Bool)Reject a fuzz input when false, without reporting a crash. Outside a fuzz build, false terminates the process successfully. It is not an assertion or a compiler optimization promise.
format
Fragmentformat(text: String) -> StringCompile-time only. Compile-time entry to the same parse-only formatter as star99 fmt, including safe range-membership rewrites. Does not load imports or execute macros in the text. Invalid source is a compile error at the call.
literal
Fragmentliteral(value) -> ExprCompile-time only. Compile-time code constructing a typed value, including aggregate contents, rather than parsing a String as source. Untyped nil is rejected. Values with unsupported literal representations, including Ref, function, File, and Pool values, cannot be serialized this way. Use a syntax splice or parse_expr for source text.
here
Fragmenthere() -> SiteCompile-time only. Compile-time location of the active macro call. Use it for generated-code diagnostics; it is not a runtime stack inspection operation.
error
Fragmenterror(site_or_code, values...)Compile-time only. Issue a compile error at Site or at site_of(code). Message values are printed together without added separators. Stops compilation.
warning
Fragmentwarning(site_or_code, values...)Compile-time only. Issue a compile-time warning at Site or at site_of(code). Message values are printed together; compilation can continue.
place
Fragmentplace(target, code: Stmt)Compile-time only. Compile-time insertion into an enclosing statement/declaration region. Bare target means start(target); start/end/before/after and named region paths select positions. file is the current file region. Identical placements deduplicate; names are deliberately not hygienically renamed. It adds code rather than editing existing interfaces or expressions.
type_of
Fragmenttype_of(expression) -> TypeCheck an expression and return its type without executing it. Works in type positions too. Compile-time checking/expansion can still be needed to determine that type.
args_of
Fragmentargs_of(function) -> TypeAnonymous struct type whose fields are the selected function's parameters. Parameter defaults are not propagated into this struct. Functions with var parameters are rejected because access parameters cannot be stored as fields. Select overloads explicitly.
ret_of
Fragmentret_of(function) -> TypeResult type of the selected named function, also usable in type positions. A function returning nothing is rejected; this does not invent a user-visible Void type.
overload_of
Fragmentoverload_of(function, ParameterType...) -> function valueSelect one named overload by exact parameter types. No conversion-based selection. Useful for overloaded names, program queries, and obtaining a parenless function as a value.
yield
Fragmentyield(value: Y)Pause the enclosing coroutine and hand value, of its declared yield type Y, to the resume that ran it. Allowed only in a coroutine body and the functions nested in it; anywhere else it is a compile error. A statement of its own; not a function value, and the name cannot be declared or overloaded. See Coroutines.
Prelude API: records, functions, state
Available without an import. Exact fields, defaults, and overloads below come from the same compiler source as this edition. Fuzz functions invoke external tools and filesystem operations; they are ordinary functions, commonly called inside build. The private implementation helpers are not exported APIs. The prelude is two modules, each loaded the first time one of its names is used: std:prelude (assert, reversed, unreachable) and std:build (Build, Cc, command, lines, shell_quote, and the fuzzing library). A program that uses neither, and no macros, loads none of the standard library.
Build
Fragmentstruct Build (
c_file: String,
sources: List(String),
name: String,
strings: List(String),
)Cc
Fragmentstruct Cc (
compiler = "cc",
flags = "-std=c99 -O2 -g -Wall -Wextra -Wpedantic",
extra: String,
libs = "-lm",
)Fuzz
Fragmentstruct Fuzz (
target = "main", # "main", a function name, or "*" for all of them
seconds = 600, # for each target
plateau = 300, # stop a target after this many seconds without new paths
instances: Int, # fuzzers in parallel; 0 means half the free cores
dir = "fuzz", # binaries, and per target: seeds, campaign and crashes
tokens: List(String), # dictionary entries besides the program's own
skip: List(String), # functions that "*" leaves out
fail_on_crash: Bool, # a crash fails the build, for continuous integration
)FuzzCrash
Fragmentstruct FuzzCrash (target, input, stack, call, reproduce: String)FuzzReport
Fragmentstruct FuzzReport (
crashes: List(FuzzCrash),
paths: Int,
errors: List(String),
targets: List(String),
)assert · command · dict_entry · fuzz · fuzz_build · fuzz_crashes · fuzz_errors · fuzz_replay · fuzz_seeds · fuzz_start · fuzz_targets · last_number · lines · reversed · shell_quote · unreachable
assert (4 overloads)
In ordinary source, inspect condition syntax and generate an always-enabled check; failed direct comparisons also show operand values where their types allow it. The optional message is String. In compile-time code the Bool overloads report a compile error. Returns no runtime value.
Fragmentmacro fn assert(c: Expr) -> Code
macro fn assert(
c: Expr,
message: String,
) -> Code
macro fn assert(c: Bool)
macro fn assert(c: Bool, message: String)command (1 overload)
Construct, but do not execute, the final C compilation command from Cc and Build. STAR99_CC overrides compiler and STAR99_CFLAGS is appended to extra. Input/output paths are quoted; compiler, flags, extra, and libs are command fragments.
Fragmentfn command(cc: Cc, b: Build) -> Stringdict_entry (1 overload)
Encode one String as an AFL++ dictionary entry surrounded by double quotes. Nonprintable bytes, quotes, and backslashes use hexadecimal byte escapes.
Fragmentfn dict_entry(token: String) -> Stringfuzz (1 overload)
Run build, target selection, seed checks, campaigns, error collection, and crash triage. Print a summary and return FuzzReport. Build failure, no runnable corpus/crash result, or crashes with fail_on_crash cause a failure. Always inspect errors as well as crashes; the report's paths is the aggregate AFL++ corpus statistic.
Fragmentfn fuzz(f: Fuzz, b: Build) -> FuzzReportfuzz_build (1 overload)
Create f.dir and build plain, asan, and cmplog target executables and dict. Prefer afl-clang-lto when available, otherwise afl-clang-fast. Returns false on a compiler failure. Its instrumented compiler selection is separate from Cc/STAR99_CC.
Fragmentfn fuzz_build(f: Fuzz, b: Build) -> Boolfuzz_crashes (1 overload)
Collect target crash inputs, including failed seeds, group using extracted stack names, and minimize with afl-tmin (copying the original if minimization fails). Return FuzzCrash records with reconstructed calls and replay commands. Grouping is an implementation heuristic, not semantic equivalence of bugs.
Fragmentfn fuzz_crashes(f: Fuzz, target: String) -> List(FuzzCrash)fuzz_errors (1 overload)
Inspect a target's logs for AFL++ PROGRAM ABORT and missing fuzzer_stats. Returns startup/abort descriptions; it does not prove the absence of every possible external-process failure.
Fragmentfn fuzz_errors(f: Fuzz, target: String) -> List(String)fuzz_replay (1 overload)
Replay saved DIR/crashes inputs with the asan executable and the target inferred from the filename. Return how many still exit unsuccessfully. Requires previously built binaries and crash files.
Fragmentfn fuzz_replay(f: Fuzz) -> Intfuzz_seeds (1 overload)
Create/check a target's seeds, moving failing seeds to out/seeds/crashes before AFL++ starts. If empty, populate a few small inputs plus program strings. Returns the number of nonfailing seeds. Uses the asan executable and bounded seed runs.
Fragmentfn fuzz_seeds(f: Fuzz, b: Build, target: String) -> Intfuzz_start (1 overload)
Start one target's AFL++ instances, subject to seconds and plateau. Uses a main CMPLOG instance, a sanitizer instance when requested count exceeds one, and additional scheduled instances. Returns the sum of reported corpus_count values, not a proof of unique execution paths.
Fragmentfn fuzz_start(f: Fuzz, target: String) -> Intfuzz_targets (1 overload)
Return [f.target] for an explicit target. For *, run the instrumented target listing and exclude f.skip. The instrumented binaries must already exist.
Fragmentfn fuzz_targets(f: Fuzz) -> List(String)last_number (1 overload)
Accumulate decimal digits, ignoring newline bytes; any other nondigit resets the accumulator to zero. Thus digits on adjacent lines can concatenate. Intended for the final number in tool output, not a general numeric parser. Absent digits yield zero; overly large values can overflow.
Fragmentfn last_number(text: String) -> Intlines (1 overload)
Split at newline bytes, removing newline separators. Internal empty lines are retained; a final newline does not add another empty element. Empty input yields an empty list. Carriage returns are retained.
Fragmentfn lines(text: String) -> List(String)reversed (2 overloads)
Macro accepting a complete for loop over a built-in list, String, or any of the four Int range forms. Visits the same values backward. Bounds/initial length are captured once; container elements are read when visited. Maps, pools, and custom for_expansion are rejected. The Code overload supplies the diagnostic for an unsuitable construct.
Fragmentmacro fn reversed(f: For) -> Code
macro fn reversed(c: Code) -> Codeshell_quote (1 overload)
Quote one String as one POSIX shell word using single quotes and escaped embedded apostrophes. Use this for data arguments in run/shell commands.
Fragmentfn shell_quote(text: String) -> Stringunreachable (1 overload)
Macro expanding to a source-located failure if execution reaches it; it does not grant permission for undefined behavior.
Fragmentmacro fn unreachable() -> CodeThe following support variables are exported in this compiler. They are included for completeness; normal use leaves their state to the library functions that own it.
Testing, tools & limits
Fuzzing
Coverage-guided campaigns require compatible AFL++ tooling. Targets: main, function name, or "*". Compiler-derived argument builders; a single List(U8) parameter receives raw bytes. assume rejects inputs; assertions/checks are failures. arbitrary(d: Draw) -> T customizes generation; draw takes ranges/lists/types. valid(x: T) -> Bool filters inputs/checks outputs. Report: crashes/paths/errors/targets. Crash: target/input/stack/call/reproduce. Inspect errors as well as crashes. Replay: fuzz_replay. Every field, default, and lower-level step is listed in the Prelude API reference.
fn twice(n: Int) -> Int {
assume(n >= 0 and n <= 1000000)
const result = n * 2
assert(result >= n)
return result
}
fn main() {
println(twice(4))
}
macro fn build(b: Build) {
assert(run(command(Cc(), b)) == 0, "C compilation failed")
const report = fuzz(Fuzz(target: "twice", seconds: 60), b)
for e in report.errors do println(stderr, e)
for c in report.crashes do println(c.call)
}| Fuzz field | Purpose |
|---|---|
| target | main by default, a function name, or *. |
| seconds / plateau | Time budget per target and limit without new paths. |
| instances | Parallel fuzzers; zero selects half the free cores. |
| dir / tokens / skip | Output location, extra dictionary entries, and targets omitted by *. |
| fail_on_crash | Make detected crashes fail the build. |
Targets, builders, and campaign results
| Input type / hook | Generation |
|---|---|
| Numbers | Zero, small values, boundaries, compared constants, arbitrary values. |
| Strings | Bytes, printable bytes, program string literals. |
| Struct | Defaults, then chosen field changes. |
| Union | Variant choice; nil first; bounded recursion. |
| List / map / pool | Repeated choices to add another element. |
| Ref / function / File / Type parameters | Not supported as ordinary generated target inputs. |
| arbitrary(d: Draw) -> T | Custom builder used wherever T occurs. |
| valid(x: T) -> Bool | Input filter and returned-value validator. |
| assume(condition) | Reject this input without reporting a crash. |
main reads the current fuzz input with read_file("-"). Its globals reset between inputs; exit ends the input. STAR99_TARGET selects a target; list lists them. STAR99_SHOW prints reconstructed calls. The library builds normal, sanitizer, and comparison-logging binaries and manages seeds, campaigns, minimization, and replay.
Fuzz defaults: 600 seconds per target, 300 seconds without new paths, half the free cores for instances=0, directory fuzz. Inspect report.errors as well as report.crashes. For CI, use fail_on_crash and retain the failing input and reproduction command.
Builder hooks and one-input replay without AFL++
This complete program builds both its normal executable and draw-replay, then replays one empty input through the check target. It exercises arbitrary, valid, and draw without starting AFL++. A coverage-guided campaign is a separate step using the campaign API.
draw-hooks.star99struct Point (x, y: Int)
fn arbitrary(d: Draw) -> Point do Point(
draw(d, -3<..=3),
draw(d, ..<5),
)
fn valid(p: Point) -> Bool do p.x in -3<..=3 and p.y in ..<5
fn check(p: Point) do assert(valid(p))
fn main() do println("hooks ready")
macro fn build(b: Build) {
assert(run(command(Cc(), b)) == 0)
var replay = b
replay.name = "draw-replay"
assert(run(command(Cc(extra: "-DSTAR99_FUZZ"), replay)) == 0)
assert(run("printf '' | STAR99_TARGET=check ./draw-replay") == 0)
}Output
hooks ready
Hook scope and replay limits
arbitrary and valid customize compiler-derived fuzz input generation and result checking. A valid hook does not automatically guard ordinary non-fuzz function calls. Generated builders bound recursive depth and container growth, so fuzzing does not enumerate every possible value. The standalone non-AFL harness reads at most 1 MiB from stdin per invocation. Target wrappers are emitted when the main module has a macro build hook; the driver can emit their C with -o without running that hook.
Debugging
star99 prog.star99 --debug builds ./prog for a debugger from .star99/prog/prog-debug.c. #line directives make gdb, lldb, sanitizers, perf, and crash reports name .star99 files and lines. The C uses the Star99 names of functions, parameters, locals, globals, types, and fields wherever they cannot clash; overloads add their parameter types (area_Shape_rect). Without --debug the C is unchanged.
star99 prog.star99 --debug # build ./prog for a debugger
star99 prog.star99 --gdb # build, then gdb with the Star99 script loaded
star99 prog.star99 --lldb # the same with lldb
star99 debug-script > star99.pyThe program carries a Python script for gdb: values print as println prints them inside a list (strings quoted), whatis gives Star99 types, backtraces show Star99 names, and step stays in Star99 code, over the runtime, checks, copies, and the allocator. gdb runs it once the program is in its auto-load safe path; --gdb puts it there. star99 debug-script writes the script out, for source star99.py in gdb or command script import star99.py in lldb.
| Debugger command | Does |
|---|---|
| star99 print EXPR | Evaluates a Star99 expression: xs[1], ages["bob"], p.x, r.*, len(xs). |
| star99 locals | The parameters and locals of the frame, and what a closure captured. |
| star99 break NAME | A breakpoint on every overload of NAME. |
A debug build that fails (a check, fail, a crash signal, a stack overflow, or a sanitizer report) names the calls that led there:
prog.star99:1:29: error: integer overflow
prog.star99:1:27: note: in bump(n: Int)
prog.star99:4:5: note: called from main()The debug flags are found once per C compiler and kept in .star99/; STAR99_DEBUG_CFLAGS replaces them, and a build() gets them through STAR99_CFLAGS. The sanitizers leave the stack uninstrumented (asan-stack=0) so a breakpoint shows a function's parameters.
| C compiler | Debug flags | In the debugger |
|---|---|---|
| gcc, clang | -O0 -g, AddressSanitizer and UndefinedBehaviorSanitizer | Everything below. |
| tcc | -b -gdwarf: tcc's bounds checker | No typedef names in its debug info, so print shows lists, maps, and strings as pointers; star99 print and star99 locals show them. |
A coroutine's resume is its body, named after it: star99 break NAME stops at its first statement on every resume, and next goes on from the yield it stopped at. Its state is in c (star99 print c.s1.n). Not yet: the Debug Adapter Protocol for editors, debugging compile-time code, and a coroutine's locals by their own names.
Commands
Formatter: four spaces, preserved comments/list breaks, explicit final returns. Tests require the compiler repository. Complete examples are in the ZIP; syntax fragments need context.
| Command | Result |
|---|---|
| ./star99 app.star99 | Compile an executable. |
| ./star99 app.star99 -o app.c | Write generated C instead of building the executable. |
| ./star99 app.star99 --expand | Print the main module after macro expansion. |
| ./star99 app.star99 -- option | Supply compile-time arguments. |
| ./star99 fmt --stdout app.star99 | Print formatted source. |
| ./star99 fmt app.star99 | Format the source file in place. |
| ./star99 tree app.star99 | Print the formatted source and its syntax tree, for editing tools. |
| ./star99 test [NAME...] | Run the compiler repository’s tests; requires its test files. |
| ./star99 gen SEED | Generate a valid random program for compiler fuzzing. |
| ./star99 dict | Print a token dictionary for AFL++. |
Exact formatter behavior
Four spaces; source comments and explicit list line breaks are preserved. A one-line list splits when it exceeds 80 columns; split lists have one entry per line and trailing commas. Outermost lists split first. Type arguments and indexes retain explicit breaks but do not split just for width. A nested struct/union can remain explicitly multiline.
Typed function bodies gain explicit final returns. Safe Int comparison pairs become in expressions with the appropriate one of four range operators. An inclusive literal-zero start uses ..<end or ..=end; an exclusive zero start stays 0<..<end or 0<..=end. The rewrite accepts only proven Int names/literals and preserves observable evaluation and failure behavior. Calls/arithmetic/accesses inside the compared operands, unknown or different numeric types, and checks carrying comments stay unchanged.
The formatter is parse-only. Quoted code and macro bodies retain comparison syntax. Functions with opaque calls, block imports, macro statements, or custom loop expansion are conservatively left alone by the range rewrite. Files with top-level macro expansion or a custom build hook are also left alone by that rewrite. The reparse consistency check validates the normalized syntax before a file is written. Formatting twice should produce the same text.
Invocation, environment, and development tools
| Setting / option | Behavior |
|---|---|
| star99 FILE / star99 DIRECTORY | Compile one file / one directory module. A file output is named after its basename in the current working directory; a directory invocation can place the executable inside that directory. |
| -o OUTPUT.c | Generate C and stop before the build hook or final C compilation. |
| --debug | Build for a debugger from .star99/NAME/NAME-debug.c: #line directives, Star99 names in the C, sanitizers where the C compiler has them, and Star99 calls named on a failure. See Debugging. |
| --gdb / --lldb | Build as --debug, then start gdb or lldb on the program with the Star99 script loaded. Cannot be combined with -o or --expand. |
| --expand | Print the main module after expansion/checking; no final C compilation/build hook. Imported modules remain imports. |
| -- ARGUMENTS... | Arguments for compile-time arguments(); these do not run the executable. |
| fmt [--stdout] FILE... | Format all supplied source files, in place unless --stdout. Supports more than one file. |
| test [NAME...] | Compiler suite; filters are substring matches and multiple names select their union. Requires tests/ next to the invoked compiler path. |
| tree FILE | The file as fmt writes it, then its syntax tree (see star99 tree); - reads stdin. Status 1 if it does not parse. |
| gen SEED / dict | Random program / AFL++ token dictionary on stdout. |
| debug-script | Print the Python script that teaches gdb and lldb Star99 values, types, frames, and commands. |
| STAR99_CC | Final C compiler command and fallback macro-process compiler; tcc is tried first for macro execution. |
| STAR99_CFLAGS | Additional final C compilation flags, including command(Cc(), b); not the macro-process compilation flags. |
| STAR99_OPT=0 | Disable the Star99 generated-code optimization pass; ranges() is empty. This does not disable the C compiler's -O2; override final C flags separately. |
| STAR99_DEBUG_CFLAGS | Replaces the debug flags found for the C compiler in a --debug build. A build() receives the debug flags through STAR99_CFLAGS. |
| STAR99_GDB / STAR99_LLDB | Debuggers used by the compiler's own debugger tests; a missing debugger skips those tests. |
| STAR99_TARGET / STAR99_SHOW | Instrumented-program target name (main default; list lists targets) / presence enables reconstructed call output. |
| STAR99_FRESH | Compiler-to-macro-process fresh-name seed; normally managed internally. |
| -DSTAR99_FUZZ | Compile generated C with the application fuzz harness; ordinary input builders and target reset behavior apply. Distinct from compiling the compiler with -DFUZZ. |
| -DFUZZ | Compiler fuzz driver: parse/format/reparse/check/generate in memory; does not run macros or external compilation. |
| STAR99_FUZZ_REPEAT / STAR99_FUZZ_VERBOSE | Standalone compiler fuzz-driver repeated-input count / diagnostic output. Development controls, not application APIs. |
The repository also supplies build.sh, fuzz.sh, benchmarks/compile.py (time, scale, profile, and same: compile time per program, growth from 1k to 20k lines, a perf profile, and whether a change kept the generated C the same), Kakoune support, and the projectional editor tools/edit.star99 (bundled in the examples ZIP; see The projectional editor). build.sh runs clang-format and a warning enabled C99 build. fuzz.sh build creates compiler-fuzz binaries/dictionary/seeds; gen compares generated programs; run performs an AFL++ campaign. Kakoune support provides star99-format and star99-check and is installed separately from the standalone compiler. These repository tools are not additional Star99 runtime APIs.
Application fuzz campaigns require matching AFL++/LLVM tooling plus the external Unix commands used by the prelude (shell, timeout, nproc, awk, grep, sed, afl-fuzz, afl-tmin, and related utilities). Instrumented binaries without AFL++ can replay one input from stdin; that is not a coverage-guided campaign. Fuzz globals reset per input. Builders reject unsupported target signatures, limit recursive depth and container growth, and can use arbitrary/valid hooks.
Diagnostics and test files
Compiler diagnostics use file:line:column, an underlined source expression, optional notes, and a concrete help message. Run-time checks report a location and abort. Assertions remain enabled.
| Test companion | Meaning |
|---|---|
| NAME.out | Expected stdout. |
| NAME.error | Expected compiler diagnostic text. |
| NAME.fail | Expected run-time failure text. |
| NAME.fmt | Expected formatted source. |
| NAME.warn | Expected compiler/build-output lines for a successful build. |
| NAME.gdb / NAME.lldb | Debugger commands, ---, then lines the debugger output must have (with !, must not). A missing debugger skips the test. |
| NAME.trace | Lines in the error of a debug build. |
| NAME/ directory | Additional module/input files for the test. |
Compiler tests live beside the compiler executable in tests/. Each runs in its own process and directory under .star99/tests-PID with a home of its own; writing into ~/.cache fails a test. The runner treats C warnings as failures and checks formatter stability. Program tests are separate from an AFL++ fuzz campaign. For application checks, use assertions or a self_test entry and build it with with_main.
Unsupported features and portability
| Not in this snapshot | Use instead / implication |
|---|---|
| Classes, methods, inheritance | Structs, unions, free functions, overloads. |
| Raw pointers, explicit layout, size_of | Checked Ref and built-in APIs. |
| Calling C from any function | C plugins: a module with c(...) functions that take and give numbers, Bool, String and List(U8). See C plugins. |
| String + | str(...) or add(&text, ...). |
| try / error-propagation operators | Explicit result values/branches; failures abort. |
| Union extension (open / extend) | Declare all variants together. |
| Threads / parallelism | Not provided. Coroutines are cooperative and stackless; see Coroutines. |
| Slices library / typed JSON literal | Not provided. |
| List-like structs / list arithmetic | Ordinary structs and explicit iteration. |
| Macro access to the caller’s expected result type | Typed arguments and explicit code generation. |
| .s9 directory discovery | Use .star99; only that extension is reliably supported. |
Compiler and platform details
The linked source is the current alpha edition. The compiler and generated runtime use Unix process, file, and memory-mapping APIs; Linux with the tested C toolchain is the verified environment. C99 output does not itself guarantee compatibility with every C99 implementation or operating system.
Macro compilation tries tcc, then STAR99_CC or cc at -O0. The metaprogram is kept by hash in the program's .star99/NAME/ and reused while the macros stay the same. Cc(compiler: ...) selects the final-program compiler, not the macro compiler. Platform-specific feature macros and mmap flags can require a port on other systems.
Reference coverage and edition
This edition follows the linked compiler source, rather than planned language features or older design notes. The reference inventory is extracted during generation: new public names without behavior notes fail the documentation build. Exact overloads and record fields come from the embedded modules. Generated signatures are reference fragments, not executable programs.
| Surface | Entries |
|---|---|
| Compiler built-ins | 39 |
| Public library function overloads | 193 |
| Public library records/unions | 73 |
| Public library support variables | 3 |
| Reserved keywords | 31 |
Compiler SHA-256: 78ba789e2507f33a170f859551bb99701dd4944c77bef9660f49996812e4d185
Machine-readable API inventory · std:code source · std:prelude source · std:build source
Reserved words and chapter links
| Keyword | Chapter |
|---|---|
| fn | functions |
| struct | structs |
| union | unions |
| var | values |
| const | values |
| if | branches |
| else | branches |
| for | loops |
| while | loops |
| in | operators |
| not | operators |
| and | operators |
| or | operators |
| return | functions |
| break | loops |
| continue | loops |
| switch | branches |
| case | branches |
| default | branches |
| do | branches |
| macro | macros |
| import | modules |
| private | modules |
| label | loops |
| module | modules |
| collection | modules |
| nil | unions |
| true | operators |
| false | operators |
| defer | loops |
| as | modules |