Envzn (pronounced envision) is a modern, fast, and readable systems programming language. It uses an ahead-of-time compiler that produces native code and achieves memory safety without the overhead of a garbage collector. Designed to be intuitive for developers, Envzn is primarily targeted at data science, finance, and systems development.
Envzn includes the essential features expected in a modern programming language:
The design of Envzn draws inspiration from many industry-standard languages. While it incorporates memory safety similar to Rust, it takes a different approach (discussed below). It also adopts generics like many languages, matrix handling like Fortran, data manipulation like Python, mathematical capabilities similar to Julia, an intermediate representation like Java, and aspires to the versatility of Go.
Envzn intentionally avoids common developer pain points, such as pre-processor commands (e.g. #pragma, #define), silent integer wrapping, and steep learning curves.
To eliminate the complexities associated with pointers, Envzn uses stack-based object handles and references. While object creation is explicit with CREATE(), deletion is handled automatically; a destructor runs as soon as a handle falls out of scope. Furthermore, explicit conversion operators are used in place of traditional type casting.
The concept for Envzn originated in 1995 when language author Brian Haughton met with the original Java team at Sun Microsystems. This meeting inspired the vision for a memory-safe language that operates without garbage collection while remaining readable, modern, world-class, fast, and intuitive.
These six principles became the core tenets of Envzn. After initial design work in 2001, followed by revisions in 2011 and 2018, the language was fully implemented in 2026. Envzn aims to relocate the cost of complexity inward, providing a better experience for both software engineers and end-users. For example, the compiler automatically detects the target platform and emits platform-specific adjustments, freeing the developer from manual configuration.
This guide assumes familiarity with basic development concepts (such as libraries and JSON) as well as object-oriented principles. The following terms are specific to Envzn:
modulename.evir file.MODULE hello // Define the module
// Double-slash for single-line comments
/* C-style for multi-line
comments */
CLASS Main IMPLEMENTS TaskStarter { // TaskStarter is a standard interface
METHOD start() RETURNS STATUS { // start() is where the program begins
printline("hello world") // Print to standard output
RETURN (SUCCESS) // Return success status
}
}
You will notice that all keywords are in uppercase, with the exception of primitive types. This is so that all keywords stand out.
Envzn has 29 distinct types divided into families:
int8, int16, int32, int64*, int128uint8, uint16, uint32, uint64, uint128float32, float64*char8, char16, char32*TRUE or FALSEint64 to uint64 to float64number types written with the im literal — 3 + 4imUNSAFE blockUNSAFE.HANDLE: container for an untyped FOREIGN pointerUNSAFE.MUTEX: raw OS mutex; use the kernel Mutex class insteadUNSAFE.CONDVAR: raw OS condition variable; use the kernel ThreadCondition class insteadC.size_t, C.ssize_t, C.long, C.unsignedLong, C.mode_t* the default for that family, e.g. int is an alias for int64
SHARED MUTABLE REFERENCE handleEnvzn has strong native arrays available on any type in three forms (T[], T[size], T[size+]) for rank 1 with examples below:
int32[]: native array of int32 elements, growable, with starting size=0binary[64]: native array of binary elements, fixed size of 64char32[128+]: native array of char32 elements, growable with a starting size of 128 char32 elements (512 bytes)For rank 2:
int64[,]: native array of int64 elements, type spinefloat64[m,n]: native array of float64 elements, extents defined at run timefloat32[5,8]: native array of float32 elements, fixed sizeFor rank 3:
int64[,,]: native array of int64 elements, type spinefloat64[j,k,l]: native array of float64 elements, extents defined at run timefloat32[5,8,9]: native array of float32 elements, fixed sizeNative arrays work with user defined types also, so class and struct types may also be used in these. Ranks are valid up to 15 dimensions.
Native arrays have a limited set of methods. (If you need more functionality, use the standard library Array class.)
Data fields are internal variables for a CLASS or STRUCT. Plain data fields are public; they may be marked INTERNAL, PROTECTED, or PRIVATE for limiting access. They are immutable by default and may only be changed in a MODIFY method. Example:
CLASS MyClass {
String name // public data field name of type String
INTERNAL int8 age // data field age of type int8;
// INTERNAL means it is only seen inside
// the module of MyClass
}
STATUS is an in-built type to have a standard way for returning SUCCESS, FAILURE, or PARTIAL_SUCCESS to the caller. It is used often with the Either-Or Return of methods.
This handle can be assigned to a reference handle, which allows read-only access. For write access, the handle can be assigned to a mutable reference, though only one active mutable reference is permitted at a time. Alternatively, shared mutable references allow multiple references to modify the object for a class declared as SHARED.
To assign a value to a variable there are three assignment operators:
= assignment for a primitive or a String constant:= assignment for an owned handle of a class instance or object; moves ownership into the handle on the left hand side of the operator=@ assignment for REFERENCE and MUTABLE REFERENCE handlesExamples:
int32 n = 5
Widget w := CREATE()
REFERENCE Widget rw =@ w
The Envzn standard library has four classes for text and two views to aid in searching those.
String: immutable char32 array (any change creates a new String object)DynamicString: mutable char32 array (changes update the same object)ByteBuffer: immutable binary arrayDynamicByteBuffer: mutable binary arrayStringView: search and other utility methods for StringByteBufferView: search and other utility methods for ByteBufferWhile one may use native arrays for text storage, these 6 classes have a rich API to provide access developers expect in modern development.
Envzn has multiple means for flow control:
IF (conditional-expression) THEN { } ELSE { }: logical branchingWHILE (conditional-expression) DO { }: tests the conditional expression first, then executes the code block repeatedly as long as the conditional expression is TRUEUNTIL (conditional-expression) DO { }: tests the conditional expression first, executes the code block repeatedly as long as the conditional expression is FALSEDO { } WHILE (conditional-expression): executes the code block, repeats while the conditional expression is TRUEDO { } UNTIL (conditional-expression): executes the code block, repeats while the conditional expression is FALSEFOR i=a TO b STEP s { }: i is assumed to be int64FOR (int32 i=0; i<5; i++) { }: C-style loopFOR element IN MyArray { }: requires MyArray to have an IteratorLOOP element IN MyArray WITH INDEX i { }: element plus its int64 positionREPEAT n { }: repeat the loop n times; an infinite loop without nLABEL name <loop or block>: a name for a block of codeBREAK / CONTINUE: breaks out of a loop or continues at the startBREAK name / CONTINUE name: breaks out of the named block of code to resume after it; continues at the start of the named block of code; very useful in nested loopsMethods accept zero or more inbound arguments and may return multiple results. Any method that modifies an object's internal data fields must be explicitly declared with MODIFY. Read-only references cannot invoke modifying methods.
When plain handles are passed as arguments, ownership is transferred ("moved") into the method. Reference handles, however, do not transfer ownership. Primitive values and structs are always copied. Examples:
Widget w := CREATE() // Create a Widget; w is the owning handle
REFERENCE Widget rw =@ w // Assign a read-only reference
MUTABLE REFERENCE Widget mrw =@ w // Assign a mutable reference
METHOD foo(REFERENCE Widget myref) { // pass in object handle 'w'
myref->doSomething() // the myref handle is read-only so
// doSomething() cannot modify myref
}
Envzn allows generic types, and they are used extensively. Many types that developers expect in a modern language, such as Array[T], Dictionary[K,V,H], LinkedList[T], Set[T], and Queue[T], are found in the standard library. These have a rich API and describe the types that are allowed to be used with them. Each generic class has a "template qualifier" preamble prior to the class definition to constrain what types may be used by that class. An example:
TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT opaque, boolean):
CLASS Array[T] IMPLEMENTS Cloneable, Collection OF T, Shuffleable OF T {
…
}
In this example, generic type T is constrained to something that implements the Cloneable interface, or be a primitive (like int32) but it cannot be opaque or boolean types.
To achieve memory safety, Envzn aims to address eight main challenges:
REFERENCE to the origin object is held by anotherThe compiler today covers 7 of the 8 challenges: the only one that has not been built and tested thoroughly is #6, data races. Challenges #5, #7, and #8 are checked at runtime, while #2 and #4 are checked at compile time. For memory safety coverage of #1 and #3, the compiler generates an EvIR file for libraries, and at compile time, walks through code that has passed the analysis rules engine to track the lifecycle of every handle and reference from initial assignment to its end. By analyzing both the current program and the EvIR files of used libraries, Envzn works to ensure complete memory safety with minimal impact on compilation time.
Status: Extracted from ENVZN_CONSTITUTION.md, where this material stood as Article III. **Renumbered ** to a plain outline — 1, a, i — because a guide is read in order rather than cited by label, and carrying the Constitution's lettering into a document that is explicitly not normative only invited the two to be confused.
Note for anyone chasing an old reference: the Constitution still cites ENVZN_USER_GUIDE.md III.C in a few places. That was §III.C, Testing, which is now §3. The mapping is positional throughout: III.A→1, III.B→2, III.C→3, III.D→4, III.E→5.
Authority: Non-normative. Nothing here constrains a conforming implementation or adds to the language. Where this guide and Article I of the Constitution disagree, Article I wins.
This guide collects the idioms, organizational conventions, and testing practices that experienced Envzn code follows. It is advice, not rule — a program that ignores every word of it is no less correct for doing so.
The idiomatic shapes for recurring tasks, each built entirely from the constructs of Article I — guidance for the reader, not new rules.
a. The patterns below are the idiomatic way to express recurring tasks in Envzn. They are not new rules; every one is built from the constructs of Article I. But they are the shapes a reader of an Envzn codebase should expect to see, and writing against them is what keeps a codebase legible to the next person.
b. For composing text, reach for the ->format() template of I.F.vi in nearly every case. There is no + on String — text has no arithmetic, so "Hello, " + name is a compile error, just as "Hello, " - name would be. Write ("Hello, $1")->format(name) even for two pieces: a template keeps the literal text and the inserted values visually separate, allocates once, and reads in a single scan. Text built up in steps goes in a DynamicString. format() converts its arguments for you — pass a number, a boolean, an enum case directly; there is no pre-conversion step, and an EMPTY handle renders as "EMPTY". The four text and binary containers of I.D.vi reach the print surface by different routes, and the routes are worth keeping straight. A String is passed directly. A DynamicString is snapshotted with toString() first. A ByteBuffer or DynamicByteBuffer is bridged through an explicit conversion: HexCodec for hexadecimal opaque-byte display, or ByteBuffer INTO String (on TextConverter) for a validated text interpretation. Binary data has no canonical text form, so the conversion should name its intent at the call site.
String msg := ("Processing item $1 of $2")->format(current, total)
DynamicString d := CREATE()
d->append("partial")
d->append(" message")
printline(d->toString()) // snapshot, then print
c. For control flow, let a conditional tree that has grown past two or three levels become a MATCH — the compiler warns at the same threshold for the same reason. To work with a value that may be EMPTY, choose by what the code needs. A full MATCH when the present and absent cases call for genuinely different logic. An IS VALID guard when it wants to branch on presence without binding.
MATCH person.middleName {
WHEN String name: { printline(name) }
WHEN EMPTY: { printline("no middle name") }
}
d. For ownership, let the assignment operator carry the intent: = for a fresh value or a literal, := for a move or a clone, =@ for a non-owning reference. When a value enters a collection, choose the bare mutator to move it and the *Copy mutator to keep the source valid. Make that choice deliberately, rather than defaulting to one. For a recoverable failure, consume a pipe-XOR call with the IF-it-is-the-condition form of I.M, and handle a STATUS with a MATCH when more than one variant matters. Panic only for a genuine defect or a truly exceptional condition, and let the recoverable vocabulary carry the ordinary outcomes.
IF (portString INTO int32) THEN {
int32 port = $RETURNED // bind it first: $RETURNED is typeless (I.M.i(c.iii))
connectToPort(port)
} ELSE {
printline($!) ; useDefaultPort()
}
e. For dispatch over a closed set of related types, a GROUP matched with MATCH is the idiom. For a closed set of named constants, use an ENUM, with an interface when the cases need behaviour. For traversal, FOR IN over a collection is the default, and the explicit LOOP forms are for the cases that genuinely need index tracking or peek-ahead.
f. To ask the compiler what a type is, read IDENTITY(…) where you need the answer: IDENTITY(Person).dataFields[i].name, IDENTITY(p).kind. It costs nothing. The compiler builds each Identity once and every IDENTITY(…) refers to it, so the read allocates nothing, in a loop or anywhere else, and there is nothing to hoist into a local. Identity id := IDENTITY(Person) is legal but makes an owned copy, and REFERENCE Identity id =@ IDENTITY(Person) saves nothing over the direct read. dataFields lists every data field, private and inherited ones included, each with its access; methods lists every method, INIT, CLEANUP and RESTORE included (Constitution I.K.iii(e)).
FOR (int32 i = 0; i < IDENTITY(Person).numberOfDataFields; i++) {
printline(IDENTITY(Person).dataFields[i].name)
}
The half-dozen habits a developer arriving from another language brings with them, and what Envzn does instead. Each is a compile error rather than a style point, so the compiler will tell you — but knowing them first saves the round trip.
a. . reaches into a value; -> sends a message to an instance. They are never interchangeable. A data field or a NAMESPACE member is reached with a dot — p.name, Math.PI, Math.sqrt(x) — and a method on a live instance with an arrow: p->getName(), System->exit(0). Writing p.getName(), p->name, or Math->sqrt(x) is an error in each case. The division is worth internalising because it makes the two kinds of access visible at a glance: a dot never runs code you did not write, and an arrow always might.
b. There is no null, no optional type, and no ? suffix. Absence is EMPTY, a state of a class-typed binding rather than a value it can hold. Primitives, STATUS, enums and structs are never EMPTY at all. Writing ? anywhere a type appears is a parse error, so a habit carried from Swift or Kotlin fails immediately rather than quietly.
c. == on a String is a compile error. Use ->equals() for content. On a class instance == compares references, not contents — and == on a module's own class is rejected outright, because reference identity is almost never the question being asked. == and != are value comparisons on primitives and nowhere else.
d. Methods are read-only by default; mutation is declared. This is the opposite of C++'s const: a method that writes the receiver's state must say MODIFY, and one that does not, cannot. The consequence worth planning for is that MODIFY is contagious upward — a method calling a MODIFY sibling must itself be MODIFY — so a mutation deep in a call chain surfaces in the signature of everything above it. That is the point.
e. There is no SELF. Reach a field with .field and call a method with ->method(); where another language would pass self, pass the specific field the callee needs. The pattern that replaces it is the two-layer cake: a minimal storage layer holding the data, and a richer public face composed over it — char32[] under String is the canonical example. A builder therefore accumulates through plain MODIFY methods that return nothing, and you call them on a named local, one line at a time, rather than chaining.
f. The C++ standard library is not available to you. T[] is the array, Array[T] the growable collection, String the text type, and the kernel's Dictionary family the maps. There is no std::vector, no std::string, no std::optional. This holds even in hand-written kernel C++, where the equivalent is EvArray.
g. Integer overflow panics; it does not wrap. A bare +, - or * that overflows raises a MathError rather than rolling over silently. When wrapping is what you want — a hash, a checksum, a ring buffer — say so with &+, &-, &*. Two exceptions are documented and deliberate: number promotes up its ladder rather than panicking, and decimal128 rounds.
Envzn has no statement terminator, so the shape of the text carries meaning the compiler enforces. These are the rules that bite first, and they are compile errors rather than style advice.
a. A statement ends at a newline. There is no semicolon and no other terminator, and a stray one is rejected rather than tolerated (E1026). The end of the line is the end of the statement, which removes the entire class of missing-semicolon errors along with the character itself.
b. Two statements may not share a line. Writing int32 a = 1 int32 b = 2 is an error, not a warning. Be warned that the message is unhelpful: it surfaces as a generic E1009 parse:expression: Unexpected token in expression pointing at the second statement, rather than saying what the rule is — so if you get that error on a line that looks fine, count the statements on it.
c. A newline terminates only at bracket depth zero. Inside an unclosed ( or [ — a multi-line argument list, a wrapped compound condition, a long index or type-argument list — a newline is ordinary whitespace and the statement continues. So wrapping a long call across lines is fine and needs no continuation character.
d. Braces do not suppress termination. Inside { … } every newline ends a statement exactly as it does outside. Braces group; they do not change how statements end.
e. A one-line block is legal, with exactly one statement in it. IF (c) THEN { grade = "A" } is fine — the closing } may itself close the final statement. Two statements separated only by a space before that } fall under rule b, one-line block or not.
f. } ELSE { is an error after a multi-line block. A continuation keyword must start its own line when the block it continues spans lines (E1123):
IF (c) THEN {
a()
} ELSE { // ERROR — cuddled after a multi-line block
IF (c) THEN {
a()
}
ELSE { // correct — ELSE begins its own line
A one-line block may still cuddle, because there is no multi-line shape for the keyword to be hiding at the end of.
g. The one exception is the C-style FOR header. Its three clauses are separated by the only two semicolons the language admits outside a template qualifier, and the whole header must occupy a single line; splitting it is a parse error.
h. A brace that starts a statement always opens a block. Envzn has no set literal, so {x} or {a, b} on its own line is a block holding a bare expression, and a bare expression is not a statement. Build a set with CREATE Set[...] and its methods.
i. A multi-line string uses the /" delimiter (E8009), not a plain quote carried across lines.
Conventions for laying out a module's files and writing readable Envzn, so that a module's public class surface stays visible at a glance.
a. A module is a folder, and a well-organized one keeps its public class surface visible at a glance. The grouping files — interfaces.ev, structs.ev, enums.ev — collect the type-level declarations, and every other file holds exactly one class named for the file. Related classes that might otherwise share a file each take their own, with the file's doc comment carrying any cross-class context. Subfolders by role — models, controllers, and so on — are a reasonable way to group a larger module's classes, since the module is the whole folder tree.
b. The naming conventions are conventional and worth stating only because consistency across a codebase is itself a readability feature. A type — a class, interface, struct, group, or enum — is named in PascalCase, with an acronym treated as a single word, so JsonParser rather than JSONParser. A method or a field or a local variable is named in camelCase, a method preferring an action verb and a boolean query reading as a yes-or-no question. A name is descriptive rather than abbreviated; the language already declined several abbreviations — boolean is never bool — and developer-chosen names should hold the same line.
The three test harnesses and how they confirm runtime behavior, given that the compiler's analyzer passes already serve as the language's lint layer.
a. Linting is built into the compiler rather than bolted on beside it: the analyzer passes carry the advisory rules, and envzn lint (I.H.viii) reports them without blocking a build. What testing adds on top is confirmation that a program does at runtime what it claims to. Three harnesses serve that, and they are the right tools in roughly increasing scope. A smoke module is a small, self-contained module whose program prints a known line; the convention is <name> ok. The smoke suite is the language-feature regression set, run after any change to the compiler. A probe module is a focused module written to verify a single claimed compiler capability, before any larger code is built on it. A probe that fails is a compiler bug, filed as such. An integration test is a multi-module arrangement that exercises dependency resolution and cross-module references together.
b. For a module's own classes, the simplest pattern is a test class whose INIT calls a series of test methods, each exercising one behavior. ASSERT is the right tool when a failed check should stop the run — it halts, so the first failure is the last thing you learn. A suite that should run to completion and report every failure wants the collect-and-report assertions described in (c) instead:
CLASS PersonTest {
INIT() {
testCreation()
testEquality()
}
METHOD testCreation() RETURNS VOID {
Person p := CREATE("Alice", 30)
ASSERT(p.name->equals("Alice")) => "name should match"
ASSERT(p.age == 30) => "age should match"
}
}
c. The assertion family is a distinct programmer-error failure category — not catchable by TRY/RECOVER, separate from STATUS (recoverable) and PANIC/Error (handleable). It has three statement-form constructs, all of which HALT on failure (abort without unwind — no CLEANUP runs; broken state is not run over):
ASSERT(cond) => "msg" — the dev-only correctness tier. Active in any non-production build; stripped entirely under -prod (no condition evaluation, zero cost).ASSERT!(cond) => "msg" — the always-on production-invariant tier. Survives -prod — the ! marks an assertion that fires in production (it is not "halts"; all three halt).UNREACHABLE! => "msg" — the always-on, unconditional, diverging impossible-marker (the exhaustive-MATCH default, the NYI stub, a dead branch). The message is optional, and the analyzer treats it as a control-flow terminator, so it satisfies definite-return / exhaustiveness in a branch that cannot produce a value.The condition may reference both compile-time and runtime values, must fit on a single source line, and is separated from its message by the => token (reserved for this family). On failure the runtime writes the message and the failing site's file:line to standard error. When instrumentation is present — -debug, including the -prod -debug observable-release build — it then writes a SNAPSHOT of the in-scope variables and a STACKTRACE. Then it aborts. The non-halting, collect-and-report test-assertion role is not part of this family — it belongs to evTest's expectX and to Logger for observability.
d. Shipped V1. The three constructs above, with the THROW→PANIC / CATCH→RECOVER rename (I.M.ii) they compose with, are implemented. The FOR/IN iterator invariant (I.J.iii) moves from a defensive panic to UNREACHABLE!, resolving the "no defensive panic for can't-happen" tension. Deferred: three follow-ons. The out-of-range index and view checks (I.D.vi) migrate from the catchable IndexOutOfBoundsError to ASSERT! in V2, since that crosses the frozen _ValueArray surface. The NO_RETURN verified-divergence method modifier is deferred to V3, with the keyword reserved now. Declarative Design-by-Contract (REQUIRE/ENSURE/INVARIANT) is deferred to V2.
(What the compiler tells you when it rejects your code, and what you can do with
it. The normative surface is ENVZN_IR_SPEC.md C.viii; this is the developer-facing view.)
a. The shape. A rejection points at the offending text, not merely at the line:
error [E1174] parse:numeric-literal-malformed: `0x` must be followed by hex digits
╭─ src/Main.ev:6:19
6 │ int32 h = 0x
│ ^^
╰─
at src/Main.ev:6:19-21
situation: empty_hex
Example: 0x · 0b · 1e · 0b1201
Corrected: 0x1F · 0b1011 · 1.5e-3
See: ENVZN_CONSTITUTION.md §I.C
Read it in this order: the code (E1174) is a stable identifier you can search for and quote in
a bug report; the frame shows the offending text with a caret under it; Example:/Corrected:
teach the shape rather than describe it; See: names the spec section that decides the rule.
b. The caret is a range, not a point. Where the compiler knows the full extent, the caret spans
it and the location reads as a range — the example above is one, 6:19-21, with a caret under each
column. Where it knows only where the problem starts, you get a single caret and a plain 6:19. Both are honest: a one-column caret means the compiler is not claiming
an extent it has not established, not that the problem is one character wide. Coverage is still
growing — many diagnostics report a point today.
c. help: is a literal edit. When a line begins help:, the text in backticks is the exact
replacement — not advice, an edit:
help: remove the semicolon
Most diagnostics have no help: line, and that is expected rather than a gap. A type error or a
missing interface method is resolved by a decision only you can make; there is no substitution that
is right in general. Auto-fixes are reserved for the cases where one literal edit always resolves
the diagnostic.
d. No frame? Nothing is wrong. The frame is drawn only when the compiler can read the source and knows the column — a diagnostic about a manifest, a module-level rule, or a construct with no single offending token prints its location line alone. The compiler prefers a correct plain message to a confident wrong caret.
e. Machine-readable output. evc --diagnostics=json --diagnostics-out=diags.json <module>
writes every diagnostic as an LSP Diagnostic — 0-based lines, UTF-16 character offsets, any fix as
a TextEdit, Envzn extras namespaced under evzn. in data. The document is always written,
including "diagnostics": [] for a clean build, so a tool can tell "compiled clean" from "the
compiler died". This is what an editor integration consumes. Default sink is stderr; prefer
--diagnostics-out — warnings render to stdout and would interleave.
f. Two flags worth knowing. --no-source-frame prints the bare form (useful when piping into a
tool that does not render box glyphs). Colour is automatic on a terminal and off when piped, and
honours NO_COLOR / FORCE_COLOR.
a. Install. One command, from the repo root:
./editors/install.sh # every editor it finds
./editors/install.sh --vim # or name them: --vim --emacs --vscode
./editors/install.sh --dry-run # report only, write nothing
It never edits a config file you own. Where a change belongs in your init — emacs — it prints the lines and leaves the editing to you.
b. What you get.
| vim | emacs | VS Code / Cursor | CotEditor | |
|---|---|---|---|---|
| Syntax highlighting | ✓ | ✓ | ✓ | ✓ |
| Diagnostics (on open + save) | ✓ | ✓ | ✓ | — |
| Hover: the full catalog entry | ✓ | ✓ | ✓ | — |
| Quick fixes | ✓ | ✓ | ✓ | — |
| Outline, go-to-definition | ✓ | ✓ | ✓ | — |
| Completion | <C-x><C-o> |
✓ | ✓ | — |
Highlighting is generated from the compiler's own keyword and type tables, so it cannot drift from the language. CotEditor has no LSP client, which is why its column stops at highlighting.
c. Two prerequisites, both worth checking first. The language server runs the real compiler, so
it needs Python 3.10 or newer — macOS ships 3.9.6 at /usr/bin/python3, which cannot import the
compiler at all — and a staged kernel (make install). The installer reports both. Get either
wrong and the server does not crash; it simply declines to analyse anything, which is the confusing
failure, hence the check.
d. Analysis is per MODULE, not per file. One save analyses the whole module and reports on every
file in it, so an error you introduced in A.ev appears while you are looking at B.ev. Cost is
roughly half a second for a small module and a few seconds for a large one; the kernel itself takes
about six.
e. When it says "analysis unavailable". A buffer outside a module folder, a dependency that has not been built, or a missing staged kernel — the server names which and stops. It will not guess: a file analysed outside its module reports errors that are not real, and a confident wrong diagnostic costs more than an absent one.
f. What the editor cannot tell you. Diagnostics stop where analysis stops. Envzn's
whole-program memory-safety checks (E3040 and its family) and the emit-stage diagnostics run
after the point the editor's analysis reaches, so they appear only in a full build. Compile before
you trust that a file is clean.
Each of these has cost someone real time. They are not defects — every one follows from a rule elsewhere in the language — but the rule and the symptom can be far apart.
a. A T[] has no append. append and appendCopy are methods on the Array[T] class; a bare T[] is storage. You extend one by writing at the high-water mark — arr[arr.length] := value — where an index equal to the current length extends by one and an in-range index replaces. Use := for class and String elements and = for primitives. Reach for Array[T] when you actually want the richer surface.
b. Prefer T[N] whenever N is known. A fixed-size array declares N live, default-initialized slots inline in the object: no CREATE, no heap allocation, no zero-fill loop, because every numeric primitive already defaults to zero. The saving is not theoretical — one kernel scan went from 553 ms to 81 ms, a factor of six, by changing a growable int32[] field to int32[256] and deleting the loop that cleared it. Two consequences to write around: whole-array := onto a fixed array is an error, so build it in place; and T[N] and T[] are distinct types that will not assign to each other.
c. An object-element N-D array is not default-initialized. float64[m,n] arrives zeroed, but String[m,n] does not — reading a slot you never wrote is a segfault with no diagnostic. Fill it before any read.
d. A view must not outlive what it borrows. StringView and ByteBufferView borrow rather than copy, so storing one in a field or returning it as an escaping value is a compile error. A view over a parameter may be returned, because that storage belongs to the caller and outlives the call by construction.
e. IS VALID on a String or ByteBuffer is a compile error. Those types are always present — an empty one is "", not absent — so the test could never be false. Ask about content with ->isEmpty() instead. The same family of error covers REFERENCE, primitives, STATUS, enums and structs, each of which is likewise always present.
f. Dictionaries are held through the interface. Dictionary[K,V,H] is an interface with several concrete implementations behind it, chosen for the shape of your keys: a general-purpose chained hash, an ordered red-black tree, a DoS-resistant SipHash variant, and fast tiers for dense integer and byte-string keys. Hold the interface, construct the implementation.
g. One new typed variable per assignment line, and no shadowing. Declare the others first. A name already in scope may not be re-declared anywhere — not in an inner block, not in a different method of the same class where a label is involved.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Two questions decide it: is it text or bytes, and will it change after you make it?
| Made once, never changes | Built up or changed | |
|---|---|---|
| Text, printable characters | String, the default |
DynamicString |
| Bytes, any content at all | ByteBuffer: files, wire data, dictionary keys |
DynamicByteBuffer |
Start with String. Reach for the dynamic pair only when the content really changes, and turn
it back into its immutable twin with toString() once it is done. Most text in a program is made
once and read many times, and an immutable value can be shared without anyone wondering who
changed it.
Text and bytes are different things. A String holds characters (Unicode code points), one
per position, so length() counts characters and reaching any position takes the same time. A
ByteBuffer holds bytes, which might be text in some encoding, an image, or a network packet. Move
between them at the edge of your program, once: INTO ByteBuffer encodes a String as UTF-8, and
INTO String decodes it back.
To look inside without copying, take a view. StringView and ByteBufferView borrow a window
over the owner's storage, and the search and slicing methods live there. A view borrows, so the
string or buffer it looks into must outlive it; the compiler checks that.
There is no + on text. Compose with format, as in ("$1 of $2")->format(done, total), or
build in steps with a DynamicString.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// Text that never changes is a String.
String name := "Zoë"
// Text built in steps is a DynamicString, turned into a String when it is done.
DynamicString greeting := CREATE DynamicString("Hello, ")
$? := greeting->append(name)
String done := greeting->toString()
printline(done)
// Bytes for a file, a socket or a dictionary key: convert once, at the edge.
ByteBuffer bytes := done INTO ByteBuffer
printline(("$1 characters, $2 bytes")->format(done->length(), bytes->size()))
RETURN (SUCCESS)
}
}
The last line prints 10 characters, 11 bytes: the ë is one character and two bytes of UTF-8.
Every dictionary has the same interface, Dictionary[K, V, H]: a key type, a value type and a
hasher. What differs is how each one stores its keys, and so how fast it is. Choose by your keys,
and start at the top of the table.
| Your keys | Use | Why |
|---|---|---|
| Integers | IntKeyedDictionary |
The fast choice for integer keys: it uses the integer itself as the hash and keeps keys and values in flat arrays. |
| Strings or bytes | StringKeyedDictionary |
The fast choice for text keys: keys are kept as bytes in one flat pool. You convert a String key to bytes once, then look it up as bytes. |
| Any other type | ChainedHashDictionary |
The general choice when neither fast dictionary fits your key. |
These three are the ones to use. They are the dictionaries that have been tuned for speed. The others exist for one need each, have not been optimized yet, and may be much slower. Use one only when you need what it adds:
ProHashDictionary, for keys that come from outside (users, files, the network). It hashes with a
secret key, so nobody can choose keys that all land in one slot and slow every lookup down.RedBlackTreeDictionary, for keys you need in sorted order. It walks its keys in order, and every
lookup, insert and remove is O(log n).ShallowDictionary, for integer keys you do not control, which might cluster.Hold the interface, create the implementation. The implementations are hidden: you name one only
in CREATE, and every variable, field and parameter has the type Dictionary[K, V, H]. Changing
your mind later is a one-line change.
The hasher is the third type. InlineIntHasher pairs with IntKeyedDictionary, and
DefaultHasher suits the rest. SipHasher is the keyed hash behind ProHashDictionary.
The byte-keyed dictionaries take two type parameters, not three. In StringKeyedDictionary (and
ProHashDictionary) the key is always a BinaryWord: a borrowed window over bytes you already hold.
Convert the String once with INTO ByteBuffer, copy out its bytes, and keep them alive for as
long as the dictionary uses the key.
Reading a value can fail, and says so. lookup returns the value or a failure, and you test it
in an IF: there is no "missing key" value to forget to check.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// Integer keys: IntKeyedDictionary, with the hasher passed in.
Dictionary[int32, int64, InlineIntHasher[int32]] stockById := CREATE IntKeyedDictionary[int32, int64, InlineIntHasher[int32]](CREATE InlineIntHasher[int32]())
$? := stockById->insert(1001, 12)
int32 wantedId = 1001
IF stockById->lookup(wantedId) THEN {
int64 count = $RETURNED
printline(("item $1 has $2 in stock")->format(wantedId, count))
}
// Text keys: StringKeyedDictionary. The key is the String's bytes, converted once.
Dictionary[BinaryWord, int64, DefaultHasher[BinaryWord]] stockByName := CREATE StringKeyedDictionary[int64, DefaultHasher[BinaryWord]]()
ByteBuffer pears := "pears" INTO ByteBuffer
binary[] pearsBytes := DUPLICATE pears->data()
BinaryWord pearsKey = CREATE BinaryWord(pearsBytes, 0, pearsBytes.length)
$? := stockByName->insert(pearsKey, 7)
IF stockByName->lookup(pearsKey) THEN {
int64 count = $RETURNED
printline(("pears: $1")->format(count))
}
ELSE {
printline("no pears")
}
RETURN (SUCCESS)
}
}
A set is a dictionary with only keys: Set[V, H] wraps a ChainedHashDictionary, takes the same
hashers, and is created directly.
Start with an array. Choose something else when the way you add and remove items says so.
| You need | Use | Cost to know |
|---|---|---|
| Items by position: the default | Array[T], also written T[] |
Reading any position and adding at the end are fast. Inserting or removing in the middle shifts everything after it. |
The same, plus sort and contains |
OrderedArray[T] |
Its elements must be comparable. |
| Work that waits its turn: first in, first out | Deque[T] |
Adding and removing at either end take the same short time, however long it gets. |
| First in, first out, and the line stays short | Queue[T] |
Built on an array, so taking from the front shifts the rest. Use Deque when the queue grows long. |
| Last in, first out | Stack[T] |
Push and pop at the top are fast. |
| Items kept in sorted order as they arrive | SortedList[T] |
Each insert walks to its place; the smallest and largest are always at hand. Elements must be comparable. |
| Each value once, and quick "is it there?" | Set[V, H] |
See Which dictionary?: a set is a dictionary with only keys. |
| Fast insert and remove at both ends of a long list | LinkedList[T] |
Finding an item means walking to it. |
| Items that must never be copied | OwnedList[T] |
It only ever moves its items, and you remove one by the id add gave you. |
| One value of its own on the heap | Box[T] |
Mostly for a type that contains itself, such as a tree of expressions. |
Storing an item takes it, unless you ask for a copy. append, push, enqueue, insert and
add take ownership of the value you pass, and the compiler stops you using it afterwards.
appendCopy, pushCopy and the other …Copy forms make a deep copy and leave yours alone. The name
says which one you chose.
Taking an item out can fail, and says so. popFront, dequeue, pop and peekFirst return the
item or a failure, which you test in an IF or a WHILE: an empty list is never a crash.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// Work waiting its turn: a Deque takes from the front and adds at the back.
Deque[String] jobs := CREATE Deque[String]()
$? := jobs->pushBack("compile")
$? := jobs->pushBack("link")
WHILE jobs->popFront() DO {
String job := $RETURNED
printline(("running $1")->format(job))
}
// Values kept in order as they arrive: a SortedList.
SortedList[int64] scores := CREATE SortedList[int64]()
$? := scores->insert(42)
$? := scores->insert(7)
$? := scores->insert(19)
IF scores->peekFirst() THEN {
int64 lowest = $RETURNED
printline(("lowest score: $1")->format(lowest))
}
RETURN (SUCCESS)
}
}
Choose by what happens if someone could predict the numbers.
| You are making | Use | What it does |
|---|---|---|
| Games, sampling, jitter, shuffles: anything that just needs to look random | CasualRandom |
Fast. Seeded once from the operating system, so every run differs. |
| Tests and simulations that must replay exactly | SeededRandom(seed) |
The same seed gives the same sequence, on every run and every platform. |
| Tokens, session ids, salts, keys: anything someone might try to guess | SecureRandom |
Draws fresh entropy from the operating system on every call. No seed, nothing to replay. |
Never use CasualRandom or SeededRandom for a secret. Both are fast generators whose next
number follows from their state. That is exactly what makes SeededRandom replayable, and exactly
what makes either one guessable. SecureRandom is slower, and it is the only one of the three for
secrets. If the operating system cannot supply entropy, creating one fails with a RandomError
rather than quietly handing you weaker numbers.
All three answer the same questions. nextInt(bound) gives an integer from 0 up to, but not
including, bound. nextFloat() gives a number from 0 up to, but not including, 1.
nextBoolean() and nextUInt128() do what they say. A bound of zero or less is a mistake, and
it fails loudly with a RandomError.
Shuffling takes any of them. Array->shuffle(rng) asks only for something that can draw a
bounded integer, so a shuffle in a test can use a SeededRandom and replay, and the same code in
production can use a CasualRandom.
One generator per thread. A generator changes each time it draws, so it belongs to one thread.
The compiler stops you sharing one with a PARALLEL body; give each thread its own, or move one in.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// A simulation that must replay: the same seed gives the same rolls every time.
SeededRandom replay := CREATE SeededRandom(42)
int64 roll = replay->nextInt(6) + 1
// A code someone might try to guess: fresh entropy on every draw.
SecureRandom secure := CREATE SecureRandom()
int64 code = secure->nextInt(1000000)
// Everything else: fast, and different on every run.
CasualRandom casual := CREATE CasualRandom()
float64 jitter = casual->nextFloat()
printline(("roll $1, code $2:06d, jitter $3")->format(roll, code, jitter))
RETURN (SUCCESS)
}
}
AS / INTO ReferenceAudience: Envzn developers and future Claude sessions. This is the practical lookup
for "I have a value of type X and I want type Y — is it valid, do I write AS or
INTO, and what do I get back?"
Source of truth: the normative spec is ENVZN_CONSTITUTION.md I.D.viii + IV.A.viii;
the design rationale is conversion-operators-design.md. This document is a derived
catalogue of the surface those define, enumerated from the kernel hosts that implement it
(kernel/src/PrimitiveConversions.ev, NumberConverter.ev,
FloatConverter.ev, CharConverter.ev, CharWidthConverter.ev, TextConverter.ev).
Every row below is an OPERATOR that exists in those files today and compiles. When the
kernel hosts change, re-derive this doc from them — do not let it drift.
Envzn has no casts. There is no syntax that reinterprets one type as another. Every crossing between numeric types, between numbers/chars and text, and between the text and binary container columns is a checked conversion written with one of two operators.
Two operators, split by the LOSS axis:
- INTO = lossless. The target can represent every value of the source. Widening
(int32 INTO int64), value→text (42 INTO String), and parse ("42" INTO int32).
- AS = lossy. The conversion can lose data or cross a sign/range boundary, so it is
range-checked at runtime, never a silent truncation (int64 AS int32,
float64 AS int32, char32 AS char8).
A second, independent axis — FALLIBILITY — decides the return shape:
- Total → a plain value. Consume it directly: String s := 42 INTO String.
- Fallible → the pipe-XOR shape (T value | STATUS status) (I.M.i). Consume it as
the condition of an IF/WHILE; in the success branch read the value with $= (the
alias $RETURNED is equivalent), and in the failure branch read the failure STATUS
with $! and its numeric error code with $#. $# is not always meaningful: it is
0 whenever the failure carried no numeric code — which is the case for every
conversion operator here (they raise FAILURE("message") with a message but no code), so
rely on $! for conversion failures and treat $# as 0. The code is only non-zero for
STATUS values from sources that set one (e.g. an errno-bearing SETS_ERRNO FFI bind).
The two axes combine into exactly three live cells (there is no lossy-total cell — any lossy conversion is range-checked, hence fallible):
| Total (plain value) | Fallible (T \| STATUS) |
|
|---|---|---|
INTO (lossless) |
widening, value→text | parse (String INTO T), ByteBuffer INTO String |
AS (lossy) |
— (none) | narrowing / sign-cross / char-width narrowing |
x INTO T or x AS T; the compiler resolves the
single operator whose (source, target) signature matches. NumberConverter,
PrimitiveConversions, etc. are where the operators live, not something you type at the
call site. (They are extensible: a module can add its own CONVERSIONS host for its own
types — see IV.A.viii.)// TOTAL — plain value, used directly
String label := 42 INTO String // "42"
int64 wide := myInt32 INTO int64 // widening
float64 d := myInt32 INTO float64
// FALLIBLE — pipe-XOR, consumed by IF; $= (alias $RETURNED) is the value,
// $! is the failure STATUS, $# is its error code
IF (userInput INTO int32) THEN {
int32 n = $RETURNED // success: the parsed value; note that $= and $RETURNED are equivalent
process(n)
} ELSE {
String why := $! // failure: the STATUS (auto-converts to text)
int32 errorcode = $# // error code, if any — 0 for conversion failures (no code set)
}
// narrowing is fallible too
IF (myFloat64 AS int32) THEN { pixel = $= } // out-of-range / NaN → ELSE branch
The classic trap.
int32 AS Stringis invalid — number→text loses nothing, so it isint32 INTO String. Reaching forASwhere the conversion is lossless (orINTOwhere it is lossy) is a compile error, by design. Use the matrix below to pick correctly.
✓total = plain value · ✓fallible = (T | STATUS), consume with IF — value via $=
(alias $RETURNED), failure STATUS via $!, its error code via $#.
Anything not listed is not a valid conversion (compile error) — including the reverse of
many one-way rows (e.g. there is no String AS int32; parse is String INTO int32).
| From | To | Operator | Shape | Notes |
|---|---|---|---|---|
int8 |
float32 / float64 |
INTO |
✓total | int→float widening |
int8 |
int16 / int32 / int64 / int128 |
INTO |
✓total | widening |
int8 |
uint8 / uint16 / uint32 / uint64 / uint128 |
AS |
✓fallible | range-checked sign cross — a negative has no target value |
int16 |
float32 / float64 |
INTO |
✓total | int→float widening |
int16 |
int32 / int64 / int128 |
INTO |
✓total | widening |
int16 |
uint8 / uint16 / uint32 / uint64 / uint128 |
AS |
✓fallible | range-checked sign cross — a negative has no target value |
int16 |
int8 |
AS |
✓fallible | range-checked narrowing |
int32 |
float32 / float64 |
INTO |
✓total | int→float widening |
int32 |
int64 / int128 |
INTO |
✓total | widening |
int32 |
uint8 / uint16 / uint32 / uint64 / uint128 |
AS |
✓fallible | range-checked sign cross — a negative has no target value |
int32 |
int8 / int16 |
AS |
✓fallible | range-checked narrowing |
int64 |
float32 / float64 |
INTO |
✓total | int→float widening |
int64 |
int128 |
INTO |
✓total | widening |
int64 |
uint8 / uint16 / uint32 / uint64 / uint128 |
AS |
✓fallible | range-checked sign cross — a negative has no target value |
int64 |
int8 / int16 / int32 |
AS |
✓fallible | range-checked narrowing |
int128 |
float32 / float64 |
INTO |
✓total | int→float widening |
int128 |
uint8 / uint16 / uint32 / uint64 / uint128 |
AS |
✓fallible | range-checked sign cross — a negative has no target value |
int128 |
int8 / int16 / int32 / int64 |
AS |
✓fallible | range-checked narrowing |
uint8 |
int16 / int32 / int64 / int128 |
INTO |
✓total | cross-sign widen — every value fits the target's non-negative half |
uint8 |
float32 / float64 |
INTO |
✓total | int→float widening |
uint8 |
uint16 / uint32 / uint64 / uint128 |
INTO |
✓total | widening |
uint8 |
int8 |
AS |
✓fallible | range-checked sign cross — the upper half has no target value |
uint16 |
int32 / int64 / int128 |
INTO |
✓total | cross-sign widen — every value fits the target's non-negative half |
uint16 |
float32 / float64 |
INTO |
✓total | int→float widening |
uint16 |
uint32 / uint64 / uint128 |
INTO |
✓total | widening |
uint16 |
int8 / int16 |
AS |
✓fallible | range-checked sign cross — the upper half has no target value |
uint16 |
uint8 |
AS |
✓fallible | range-checked narrowing |
uint32 |
int64 / int128 |
INTO |
✓total | cross-sign widen — every value fits the target's non-negative half |
uint32 |
float32 / float64 |
INTO |
✓total | int→float widening |
uint32 |
uint64 / uint128 |
INTO |
✓total | widening |
uint32 |
int8 / int16 / int32 |
AS |
✓fallible | range-checked sign cross — the upper half has no target value |
uint32 |
uint8 / uint16 |
AS |
✓fallible | range-checked narrowing |
uint64 |
int128 |
INTO |
✓total | cross-sign widen — every value fits the target's non-negative half |
uint64 |
float32 / float64 |
INTO |
✓total | int→float widening |
uint64 |
uint128 |
INTO |
✓total | widening |
uint64 |
int8 / int16 / int32 / int64 |
AS |
✓fallible | range-checked sign cross — the upper half has no target value |
uint64 |
uint8 / uint16 / uint32 |
AS |
✓fallible | range-checked narrowing |
uint128 |
float32 / float64 |
INTO |
✓total | int→float widening |
uint128 |
int8 / int16 / int32 / int64 / int128 |
AS |
✓fallible | range-checked sign cross — the upper half has no target value |
uint128 |
uint8 / uint16 / uint32 / uint64 |
AS |
✓fallible | range-checked narrowing |
float32 |
float64 |
INTO |
✓total | widening |
float32 |
int32 |
AS |
✓fallible | range-checked; NaN/∞ → FAILURE |
float64 |
int32 |
AS |
✓fallible | range-checked; NaN/∞ → FAILURE |
113 numeric↔numeric operators — 51 total INTO, 62 fallible AS — read from kernel/src/*.ev at build time. Regenerate with python3 docs/build_conversions_table.py; do not hand-edit between the markers.
The table above is generated from the kernel registry. It used to be kept by hand, and it drifted the way a hand-kept list of a hundred-odd rows does: it went on saying sign-mixing and narrowing were unregistered, and that
int32 AS int16was "not yet provided", after both had stopped being true. Brian's Phase 8 ruling 4 made it derived — a generator readskernel/src/*.evand rewrites the region between the markers, so the doc cannot disagree with what actually resolves. Everything outside the markers, including this paragraph, is hand-written and carries the rationale the registry has no way to state.The rule behind every row: every TOTAL conversion has an
INTO, every FALLIBLE one anAS. Totality is a range question and nothing else — the source's range fits inside the destination's, or it does not — so the keyword is derived rather than chosen. The integer half is now complete: all 90 ordered pairs across the ten integer types are registered (Phase 8 family #2), which closed 59 crossings a developer could name but not spell. Before that, the analyzer refused those pairs with E2007 ("requires IS or Convert") while no Convert existed to reach for.Every implicit widening of constitution I.J.iii.c — a same-signedness integer to a wider integer, ANY integer to a float, and
float32 INTO float64— is also a registered totalOPERATOR INTO. int→float is registered even where wide (int64 INTO float32), following C++'s value conversion exactly as the pre-existingint32 INTO float32does.A registered sign cross is still an EXPLICIT one.
widens_to(compiler/primitives.py) treats all sign-mixing as non-implicit, so anint64parameter does not silently accept auint32— you write theINTO. That holds even for the ten cross-sign pairs that are total (uint8anduint16into the wider signed types,uint32 INTO int64,uint64 INTO int128), where every source value lands in the target's non-negative half and nothing can be lost: a sign change is chosen by the developer, and the keyword is how they say the reading changed, even where the value cannot. (#38, and Phase 8 family #2 for the other eight.)What is still not a conversion is a pair with no operator in either direction —
int32 INTO boolean, for instance, since family #4 ruledINTO/ASclosed to boolean both ways withb INTO Stringthe sole exception. Those are a clean E2086 at analysis time (> it no longer slips to a clang reject). For a deliberately unchecked truncation, useNumericUtilities(§5), notAS.A widening that reaches several overloads takes the one that changes least The rows above say which conversions are implicit; they do not say which overload a call takes when its argument widens into more than one. An exact match wins; failing that, staying in the argument's family (integer to integer, float to float) beats leaving it, and within that the narrowest target wins.
uint32intotruncateToInt32(int64 | uint64 | float32 | float64)takesuint64—int64is never a candidate, the sign change being explicit — andnumber, having no fixed width, is the last target chosen. A tie still standing is ambiguous: write theINTO. A literal is not ranked this way; it adopts its slot (I.D.i).
String (rendering — always lossless + total)| From | To | Operator | Shape | Result |
|---|---|---|---|---|
int32 int64 int128 uint32 uint64 uint128 |
String |
INTO |
✓total | decimal text, e.g. 42 INTO String → "42" |
boolean |
String |
INTO |
✓total | "true" / "false" |
float32 float64 |
String |
INTO |
✓total | shortest round-trip decimal (Ryu), e.g. 0.1 INTO String → "0.1" |
char8 char16 char32 |
String |
INTO |
✓total | one-character string |
char32[] |
String |
INTO |
✓total | code-point array → string (backs print/format auto-convert) |
You rarely write
INTO Stringjust to print:->format(...)and theStdioprint methods auto-convert any argument (I.F.vi). Reach for explicitINTO Stringwhen you need theStringas a value (storing it, concatenating, returning it).
String → value (parse — lossless but can fail)| From | To | Operator | Shape | On bad input |
|---|---|---|---|---|
String |
int32 int64 int128 uint32 uint64 uint128 |
INTO |
✓fallible | FAILURE status |
String |
float32 float64 |
INTO |
✓fallible | FAILURE status |
String |
boolean |
INTO |
✓fallible | FAILURE status |
IF ("42" INTO int32) THEN { int32 n = $= } ELSE { /* not a number */ }
String ↔ ByteBuffer, UTF-8)| From | To | Operator | Shape | Notes |
|---|---|---|---|---|
String |
ByteBuffer |
INTO |
✓total | UTF-8 encode — every code point encodes |
ByteBuffer |
String |
INTO |
✓fallible | UTF-8 decode — invalid bytes → FAILURE |
INTOhere assumes UTF-8 (the canonical encoding). Other encodings are bulk operations, not single-pair operators — seeUTFCodec(§5). For opaque-byte display (hex), useHexCodec, not this bridge.
A code point's own arithmetic is not a conversion. (I.D.i(b.ii), )
char ± integeris an OFFSET yielding the char's own type — range-checked at runtime against that width's code-unit range — andchar - charis a DISTANCE yieldingint32. Neither needs a door. What still does: a plain integer landing in a char slot (char digit = 0x30 + d) is a crossing and is refused (E10096); write the offset,char digit = '0' + d. Everything else with a char operand —char + char,n - c,* / ~/ % ^ &* &+ &-, unary minus — is E2150, not a missing conversion.
Bit-equivalent twins — INTO, total, both directions (same storage width):
| Pair | Operator |
|---|---|
uint8 ↔ char8 |
INTO (either direction) |
uint16 ↔ char16 |
INTO (either direction) |
uint32 ↔ char32 |
INTO (either direction) |
A code point never lands in an integer slot implicitly, and never in another char width implicitly. (Phase 8, I.D.i(b.ii)/(d.i)) every row in the two tables below is a DOOR that must be written:
int64 n = candint64 n = c + pare bothE10096— the offset's result is the code point's own type, so an integer slot receives a crossing — andchar16 u = c8isE10096too.(c + p) INTO int64and(c8 INTO char16)are the spellings. The one thing that still crosses nothing is the DISTANCEc1 - c2, which is anint32from the start. The keyword-bitwise operators (BAND BOR BXOR BNOT LSHIFT RSHIFT) yield an INTEGER across any two char widths (I.D.i(e)), so that result needs no door into an integer slot — and needs one back into a char slot.
Widening into a wider char or a wider/equal integer — INTO, total:
| From | To (any of) | Operator |
|---|---|---|
char8 |
char16 char32 int16 int32 int64 uint32 uint64 float32 float64 |
INTO ✓total |
char16 |
char32 int32 int64 uint32 uint64 float32 float64 |
INTO ✓total |
char32 |
int32 int64 uint64 float32 float64 |
INTO ✓total |
uint8 |
char16 char32 |
INTO ✓total |
uint16 |
char32 |
INTO ✓total |
int32 |
char32 |
INTO ✓total — total: char32 is 32-bit storage, so any int32 fits |
Integer/float → char, narrowing — AS, fallible (range/scalar-checked):
| From | To | Operator | Check |
|---|---|---|---|
int8 int16 int32 int64 uint16 uint32 uint64 float32 float64 |
char8 |
AS ✓fallible |
must be in [0, 0xFF] |
int8 int16 int32 int64 uint32 uint64 float32 float64 |
char16 |
AS ✓fallible |
must be in [0, 0xFFFF] |
int8 int16 int64 uint64 float32 float64 |
char32 |
AS ✓fallible |
valid Unicode scalar [0,0x10FFFF], no surrogates |
char → narrow integer, narrowing — AS, fallible:
| From | To | Operator | Check |
|---|---|---|---|
char8 char16 char32 |
int8 |
AS ✓fallible |
must be ≤ 0x7F |
char16 char32 |
uint8 |
AS ✓fallible |
must be ≤ 0xFF |
char16 char32 |
int16 |
AS ✓fallible |
must be ≤ 0x7FFF |
binary — the octetbinary is the language's 8-bit unsigned octet, and it is the only one. It is deliberately not in GROUP Numeric — a bit pattern is not a number — and it does not widen at all: no implicit conversion crosses the octet boundary in either direction any more, so every row below is an explicit INTO/AS, never the free widening uint8 would give:
| From | To (any of) | Operator | Notes |
|---|---|---|---|
binary |
uint16 uint32 uint64 uint128 |
INTO |
total widening |
binary |
int16 int32 int64 int128 |
INTO |
total — 0x00..0xFF fits every signed word of 16 bits and up |
binary |
float32 float64 |
INTO |
total |
binary |
char8 char16 char32 |
INTO |
total; the octet reinterpreted as a code unit |
binary |
int8 |
AS |
fallible — 128..255 has no int8 spelling |
And INTO binary — the inbound ladder. there was none, because uint8 -> binary was implicit: an octet and a number were interchangeable at the same width. That is what let DynamicByteBuffer.append(uint8) compile at 15 kernel call sites, with clang unable to object because both lowered to uint8_t. Closing the implicit edge without providing an explicit one would leave a denial with no remedy, so:
| From | To | Operator | Notes |
|---|---|---|---|
uint8 |
binary |
INTO |
total — same width, same signedness |
char8 |
binary |
INTO |
total — a UTF-8 code unit already is an octet |
int8 |
binary |
INTO |
total — every int8 has an octet spelling; -1 is 0xFF |
uint16 uint32 uint64 uint128 |
binary |
AS |
fallible — must be ≤ 255 |
int16 int32 int64 int128 |
binary |
AS |
fallible — both bounds; a negative has no octet spelling |
float32 float64 |
binary |
(none) | a float has no octet meaning — go via an integer |
Note the asymmetry with the outbound row above, which is deliberate rather than
an oversight: binary AS int8 is fallible because 128..255 has no int8
spelling, while int8 INTO binary is total because every bit pattern is a
valid octet. The octet is the wider domain in that pair.
The masked idiom needs none of these. x BAND 0xFF is typed binary — the
mask literal fits an octet, so the AND yields one — which is why
acc->append(x BAND 0xFF) compiles with no operator at all: the argument the
call receives already is the octet type it wants. A masked integer assigned to
an integer slot is the other half of the same idiom and stays a number, also
with no operator (uint64 masked = word BAND 0xFF) — nothing in it was ever a
stored bit pattern, so there is nothing to convert. Which one you get depends on
the slot, not the expression; every hash and wire codec in the kernel reads
unchanged either way. The AS rows cover the case the compiler cannot bound.
byte is gone. It was a third 8-bit unsigned spelling alongside uint8 and
binary, all three lowering to uint8_t, and the primitives table described it
as "distinct from uint8 only by intent" — an intent nothing enforced. Every one
of its 19 type-position sites in the kernel existed only to support byte
itself, and GROUP Numeric listed it while excluding binary, which settled
what it actually was: the numeric octet, i.e. uint8. Sites that meant an octet
are now binary; sites that meant a small number are now uint8.
The signed INTO rows above (int16/int32/int64/int128) exist because that implicit widening is gone: a caller who wanted a signed target and knew the value fit used to get there by plain assignment (int32 d = raw[i]); the same read now has to say INTO at the call site, which is why the rows have to exist for it to say. Two codes name the two refused directions — E2139 when an octet is read where a number is wanted, E2145 when a number is written where an octet is wanted.
Why this exists. The byte containers store binary[] (§I.J.i(c)), so
buf[i] INTO uint64 — the first move of every hash and every wire codec — is
ordinary code. It worked only by accident before: the storage was spelled
char8[], and char8, being signedness-neutral, carries the full numeric
ladder including the signed targets. When the storage became binary[] the
idiom stopped compiling in three kernel hot paths at once, which is how the gap
was found — and the same audit is what closed the implicit crossing outright
rather than patching the one site it broke.
boolean — the truth valueNo conversion crosses the boolean boundary implicitly, and INTO/AS is not a
door either (I.D.i(b.iii)). There is no conversion operator into a boolean
from a number, a code point or an octet, and none out of one — in any position:
declaration, assignment, argument or return. All four arms report the same code,
E10096, so the crossing is never named two ways at two positions (until
this ruling a declaration said E2002 while the other three said E10096, and
boolean x = someInt128 said nothing at all).
| From | To | Operator | Shape |
|---|---|---|---|
boolean |
String |
INTO |
✓total — the one outbound door (§2b) |
String |
boolean |
INTO |
✓fallible (§2c) |
boolean |
any numeric / char* / binary |
(none) | there is no number a truth value is |
any numeric / char* / binary |
boolean |
(none) | IF n != 0 is the test that was meant |
The same ruling refuses the operator positions a crossing used to reach through:
arithmetic with a boolean operand and unary minus are E2152 ("a boolean is
not a number"), ordering is E2118, a boolean array subscript is E2144,
and equality against anything but another boolean is E2025.
CharWidthConverter)Widening between char widths is in §2e (INTO, total). Narrowing a wider char to a
narrower one can fail (the code point may need multiple code units) — AS, fallible:
| From | To | Operator | Succeeds only when |
|---|---|---|---|
char16 |
char8 |
AS ✓fallible |
code point is single-byte UTF-8 (ASCII) |
char32 |
char8 |
AS ✓fallible |
code point is single-byte UTF-8 (ASCII) |
char32 |
char16 |
AS ✓fallible |
code point is in the BMP (single UTF-16 unit) |
Implicit cross-char-type conversions are REFUSED (
E10096). Writing one char type where another is expected without an explicitAS/INTO(e.g.char16 u = someChar8, or returning achar8from aRETURNS char16) is a compile error — a code unit of one encoding is not the same unit in another. Every char-type pair, with no exemption, in every position (declaration, assignment, argument, return). It is the Envzn-native parallel to clang's-Wcharacter-conversion, and--no-clang-char-warningssilences clang's, not Envzn's. The refusal is exempt inside anOPERATOR AS/INTObody whose declared target is the destination width (that is where the conversion is defined).Changed (Phase 8, I.D.i(d.i)). This was the warning
W10095, withchar16→char32exempt on the grounds that a non-surrogate UTF-16 unit is the same UTF-32 scalar. Half of thechar16space — the surrogates0xD800..0xDFFF— is not a UTF-32 scalar at all, which is the case a decoder exists to handle, and §2f already calls the reverse direction fallible.W10095is retired;E10096is the one code, and the ASSIGNMENT arm had been reporting it on all nine pairs all along.
number and complex (the value-class numeric primitives, §I.D.i(g))number holds an int64 XOR a uint64 (the UNSIGNED overflow arm, #38) XOR a float64; complex is a pair of numbers. A fixed-width integer or float up to 64 bits widens into number implicitly. Into a complex slot, only a number crosses implicitly (a complex's real part is a number); every fixed-width real writes the door, x INTO complex (I.D.i(b.iv), E10096 at every position; Brian, /02). A real operand still computes in the complex domain (z + 1), which is not a slot crossing. Narrowing out of number is lossy ⇒ AS (fallible); extracting a real out of complex is lossless-but-precondition'd ⇒ INTO (fallible). (Hosts: NumberConversions.ev, ComplexConversions.ev.)
| From | To | Operator | Shape | Notes |
|---|---|---|---|---|
int8…int64 / uint8…uint64 / float32 / float64 |
number |
INTO |
✓total | implicit widen-in (a bare number n = anyInt is the same total widen). A uint64 past int64_max value-classifies to the UNSIGNED arm (#38) — still total |
int128 / uint128 |
number |
AS |
✓fallible | may exceed the uint64 arm → range-checked. Never implicit: number n = w is E10096; it used to compile to an int64 truncation |
number |
int8 / int16 / int32 / int64 / uint8 / uint16 / uint32 / uint64 |
AS |
✓fallible | a float-subtype value, or one out of the target's range, → FAILURE. An UNSIGNED-arm value extracts totally via AS uint64, but fails AS int64 and every narrower type (it is > int64_max) |
number |
float32 |
AS |
✓fallible | overflow (float subtype beyond float32 max) → FAILURE; int subtype always succeeds (precision loss tolerated) |
number |
float64 |
INTO |
✓total | int arm widens to double, float arm is identity |
number |
String |
INTO |
✓total | tag-aware: integer subtype → 5, float subtype → Ryu 2.0 |
int8…int64 / uint8…uint32 / float32 / float64 |
complex |
INTO |
✓total | the door: complex(value, 0). Required at every slot position; the implicit crossing is E10096 |
number |
complex |
implicit | ✓total | a complex's real part is a number, so no information moves between models (ruling (a), ) |
int128 / uint128 / uint64 |
complex |
— | — | no door of their own (ruling (b)): w AS number (uint64: number n = u), then the implicit number → complex |
complex |
float64 (any real) |
INTO |
✓fallible | lossless-fallible: succeeds iff the imaginary part is zero; nonzero imaginary → FAILURE |
complex |
a real (AS) |
— | — | compile error E2106 — Re-vs-magnitude ambiguous; use an accessor (c.real / c.magnitude) then convert, or complex INTO <real> |
number/complexareEquatableonly (notHashable/Comparable): fine as values, never aDictionary/Setkey orSortedListelement. There is nonumber AS String(text rendering is lossless ⇒INTO), and no lossy-total cell here either — everyASabove is fallible.
decimal128 (the exact base-10 primitive, §I.D.i)decimal128 is an IEEE 754-2008 exact base-10 numeric ({ int128 coefficient; int32 exponent }). Unlike the bare primitives, the kernel cannot construct it from a plain operator — so every inbound … INTO/AS decimal128 is compiler-assembled (a kernel helper returns the parts, the compiler builds the value); the outbound operators are ordinary OPERATORs in DecimalConversions. Widening a ≤64-bit int into decimal128 is exact/total; everything else inbound is INTO fallible — exact-when-representable, else FAILURE, never a silent round (decimal128's exactness contract; that is the lossless-fallible cell, so it is INTO, not AS). Narrowing out is lossy ⇒ AS (fallible). The fallible inbound rows return the pipe-XOR shape, not a plain value — so decimal128 d = (f INTO decimal128) is E6064 and the consume is IF (f INTO decimal128) THEN { d = $= }. These pairs are compiler-ASSEMBLED rather than registry-declared, and the exemption that kept them out of the "no operator" check returned before the fallibility was stamped, so the shape check never saw them and the emitted _EvTuple<Decimal128, _EvStatus> reached a bare Decimal128 slot (Phase 8 family #3, ruling R5). (Hosts: DecimalConversions.ev; inbound parts-helpers DecimalText / FloatToDecimal / NumberToDecimal / DecimalCodec.)
| From | To | Operator | Shape | Notes |
|---|---|---|---|---|
int8…int64 / uint8…uint64 |
decimal128 |
INTO |
✓total | exact widen + implicit (≤20 digits, always fits) |
int128 / uint128 |
decimal128 |
INTO |
✓fallible | exact when < 10³⁴; a wider value → FAILURE (never silently rounds). Explicit — not implicit-widen |
float32 / float64 |
decimal128 |
INTO |
✓fallible | shortest round-trip decimal (Ryu); non-finite → FAILURE |
number |
decimal128 |
INTO |
✓fallible | tag-aware (int arm exact, float arm via Ryu) |
complex |
decimal128 |
INTO |
✓fallible | real projection — succeeds iff the imaginary part is zero |
String |
decimal128 |
INTO |
✓fallible | exact decimal-text parse ("19.99"); bad text → FAILURE |
ByteBuffer |
decimal128 |
INTO |
✓fallible | IEEE BID 16-byte decode; wrong length / non-canonical / >34 digits → FAILURE |
decimal128 |
String |
INTO |
✓total | EXACT decimal text — the headline display feature (19.99→"19.99", cohort preserved) |
decimal128 |
ByteBuffer |
INTO |
✓total | IEEE BID 16-byte big-endian wire encoding (simple 113-bit form) |
decimal128 |
int8…int64 / uint8…uint64 / int128 / uint128 |
AS |
✓fallible | non-integral or out-of-range → FAILURE |
decimal128 |
float32 / float64 |
AS |
✓fallible | lossy (binary can't hold most decimals exactly); overflow → FAILURE |
decimal128 |
number |
AS |
✓fallible | integral → exact number(int64); else the lossy float64 arm; float64 overflow → FAILURE |
decimal128stays "clean": adecimal128operand in arithmetic/comparison combines only with anotherdecimal128or a ≤64-bit integer (which widens exactly). Afloat/number/complex/int128counterpart is a compile error (E2121) — convert it explicitly so precision is never silently lost.
decimal128ISHashable+Comparable(cohort-normalized), so it is a validDictionary/Setkey andSortedListelement — the contrast withnumber/complexabove. There is nodecimal128 AS String(text is lossless ⇒INTO), and theByteBuffer⇄decimal128pair is the IEEE BID wire codec (a single canonical encoding, henceAS/INTO, not a parameterized §5 codec).
->format) and auto-conversion — what is handled, what is notConversion and formatting are related but distinct. ->format(...) (and the Stdio
print methods, I.F.vi) auto-convert their arguments to text for you, which is why you
rarely write an explicit INTO String just to print. But the auto-convert covers a fixed
set of argument types — anything outside it either renders as a placeholder (with a compile
warning) or must be converted by hand first. This section is the line between the two.
String msg := ("Processing item $1 of $2")->format(current, total) // $1..$9 filled in order
String hex := ("color = #$1:0>6X")->format(v) // "color = #0000FF"
$1..$9 are the placeholders (filled left-to-right by the arguments); $$ is a literal
$. Each placeholder may carry a spec $N:<fill><align><sign><width><type> mirroring
Python's mini-language — type letters :d :x :X :o :b (integer bases) and :s (default
render). The compiler chooses the right render for each argument at the call site, so a
value never has to be threaded through (value INTO String) before a format call.
| Argument type | Renders as |
|---|---|
any primitive numeric (int*, uint*, float*, char) |
its value as text; numeric base controlled by :d/:x/:X/:o/:b |
boolean |
"true" / "false" |
String |
itself, directly |
DynamicString |
snapshotted to String first (you do not pre-toString()) |
binary byte, ByteBuffer |
space-separated uppercase hex — "DE AD BE" — by default; :x/:X/:o/:b re-bases, packed without spaces |
DynamicByteBuffer |
snapshotted to ByteBuffer first, then as hex |
a class instance with METHOD toString() RETURNS String |
whatever its toString() returns |
a class handle whose value is EMPTY |
the literal "EMPTY" |
| Argument | What happens | What to do |
|---|---|---|
a class instance without toString() |
renders [??] and the compiler warns |
add METHOD toString() RETURNS String to the class |
an opaque value with no recognizable carried type |
renders "??" |
extract/convert the real value before formatting |
an array or collection (int32[], Array[T], Dictionary, Set, …) |
not in the accepted argument set — not a single formattable value | format the elements yourself (e.g. build a DynamicString, or loop and ->format each) |
a ByteBuffer you want shown as text, not hex |
the default render is hex, not the decoded characters | convert first: bb INTO String (§2d, fallible UTF-8 decode) and pass the String |
a ByteBuffer you want shown as a specific non-default form (Base64, etc.) |
only the integer bases (:x/:X/:o/:b/:d) are reachable via the spec |
use the matching codec (§5) — e.g. Base64Codec->toBase64(bb) — and pass the resulting String |
If the value is a single primitive, a String/DynamicString, a byte container (and hex is
what you want), or a class with a toString(), just pass it — ->format handles it. If
it is a collection, a byte buffer you want as text, or a class without toString(), the
auto-convert stops and you reach for an explicit conversion (§2, §5) or render the parts
yourself. The format auto-convert is a convenience over the conversion surface in this
document, not a replacement for it.
You never name these at the call site; they are listed so you know where to edit the
surface and what each guarantees. All are CONVERSIONS hosts in kernel/.
PrimitiveConversions.ev — the numeric/char widen+narrow matrix (§2a, §2e). Orders
early in the kernel (depends only on primitives + STATUS), so every kernel class can use
it. int32 INTO char32 is deliberately total: char32 is 32-bit storage, so
no bits are lost; Unicode-scalar validity is not this conversion's concern.
NumberConverter.ev — integer/boolean → String (total) and String → integer/
boolean parse (fallible) (§2b, §2c). Orders early (depends only on String/
DynamicString) so foundational classes can render with x INTO String. 128-bit values
render via hand-rolled decimal (no libc path).
FloatConverter.ev — float32/float64 → String (total), via the Ryu/FloatFormat
engine: shortest decimal that round-trips. (Float parse lives in NumberConverter.)
CharConverter.ev — char8/char16/char32 → String and char32[] → String
(all total). The char32[] operator backs the compiler's error-message print auto-convert.
CharWidthConverter.ev — the fallible char-width narrowings only (§2f). Delegates the
actual encode to UTFCodec and succeeds only when the result is exactly one code unit.
TextConverter.ev — the String ↔ ByteBuffer hard line (§2d), UTF-8. String INTO
ByteBuffer is total (every code point encodes); ByteBuffer INTO String is fallible
(arbitrary bytes may not be valid UTF-8).
NumberConversions.ev — the number narrow-out matrix (§2g): number AS int*/uint*
and number AS float32 (lossy, fallible — range-checked, float32 overflow detected via the
finiteness identity (f - f) == 0 since a float32-max literal needs V2 scientific notation),
plus the total number INTO float64 and the tag-aware number INTO String. Widening into
number is implicit (no operator).
ComplexConversions.ev — complex INTO String (total, canonical (a + bim), sign-aware
on the imaginary part) and complex INTO float64 (lossless-fallible, succeeds iff the
imaginary part is zero). complex AS <real> is intentionally absent — it is a compile error
(E2106, Re-vs-magnitude ambiguity). A fixed-width real into a complex slot is x INTO complex;
a number crosses implicitly, and a real operand computes in the complex domain.
DecimalConversions.ev — the decimal128 OUTBOUND matrix (§2h): decimal128 INTO String
(total, exact decimal text), decimal128 INTO ByteBuffer (total, IEEE BID encode), and the
decimal128 AS int*/uint*/float* narrowings (lossy, fallible). The INBOUND … INTO decimal128
conversions are NOT operators here — the kernel can't construct the value-class primitive, so the
compiler assembles each from a parts-helper (String→DecimalText.parseDecimalParts, float*→
FloatToDecimal, number/complex→NumberToDecimal, ByteBuffer→DecimalCodec.bidToParts,
int*→an exact-widen Decimal128(coeff, 0)).
DecimalCodec.ev — the INBOUND half of the IEEE BID wire codec: bidToParts(ByteBuffer) →
(DecimalParts | STATUS), decoding 16 big-endian BID bytes (simple 113-bit form) and rejecting a
wrong length, the non-canonical "11" combination form, an out-of-range exponent, or a >34-digit
coefficient. The compiler's ByteBuffer INTO decimal128 lowering calls it and builds the value.
AS/INTO — reach for these insteadSome type crossings are deliberately not checked conversions, so they are ordinary
NAMESPACE free-function calls (Host->method(...)), not operators. Use these when the
matrix above has no row for what you want:
| You want… | Use | Example |
|---|---|---|
ByteBuffer/binary → hex String (and back) |
HexCodec |
HexCodec->toHex(bb) · HexCodec->fromHex(s) (fallible) |
| bytes ↔ Base64 text | Base64Codec |
Base64Codec->toBase64(bb) · Base64Codec->fromBase64(s) (fallible) |
| number ↔ bytes with a chosen endianness | ByteOrderCodec |
ByteOrderCodec->toBytes(n, endian) · ->toInt32(bb, endian) (fallible) |
| bulk transcode between UTF-8/16/32 arrays | UTFCodec |
UTFCodec->encodeToUTF8(char32[]) (fallible) |
| an unchecked, data-losing truncation/reinterpret cast | NumericUtilities |
NumericUtilities->truncateToInt32(int64) · ->toUint64(int32) |
| a char/string predicate (is-digit, is-alpha…) | CharClassifier |
CharClassifier->isDigit(c) — a test, not a conversion |
Why they are not operators: a codec is parameterized (endianness, encoding) or many-to-one
(bulk arrays), and AS/INTO are single-source/single-target; and NumericUtilities is
intentionally unchecked — making it an AS would collide with the checked AS for the
same type pair and hide the data loss the caller explicitly wants. (DateTime construction
from parts/strings is fallible too but lives on the DateTimeFactory singleton, since Envzn
has no static methods or fallible INIT.)
C.* FFI boundary conversion is NOT an AS/INTO operator (Constitution I.D.x). C.size_t · C.ssize_t · C.long · C.unsignedLong · C.mode_t name a C
typedef at a FOREIGN/FOREIGN BIND declaration and lower verbatim to that spelling.
You never write a conversion for them and you never declare one: they are legal only
in a foreign declaration (else E2143), so no C.* value exists in Envzn code to
convert. The caller passes and receives an ordinary Envzn integer (uint64, int64) and
the compiler converts at the boundary, in both directions, for a by-value argument
and for the LOAD C.<type> in/out out-param alike.
Inbound is CHECKED: a value outside the platform's range for that C type raises the
MathError of I.F.ii(a.iii) rather than truncating — a silently narrowed size_t is
precisely the wrapped-size defect the memory-safety floor forbids. Outbound is widening
on every supported target and needs no check. Why the family exists at all: a
fixed-width primitive cannot express a pointer to a C typedef — size_t is
unsigned long where uint64_t is unsigned long long on Darwin, and the two swap on
Linux, so the wrong spelling compiles on one target and fails on the other. By value the
old advice merely worked by implicit conversion; by pointer it could not work at all.
W2146 warns when a LOAD uses a 64-bit fixed-width type instead.String AS T and no lossy-total cell. Parse is String INTO T (lossless-fallible).
Every AS is fallible.AS integer narrowings
are those in §2a (int64 AS int32, float* AS int32) plus the char-target narrowings.
Other pairs (e.g. int32 AS int16, int64 AS uint32) are not yet provided — if you need a
deliberate unchecked narrowing, NumericUtilities covers it; a new checked pair is a
one-operator addition to PrimitiveConversions.ev.CONVERSIONS host with
OPERATOR AS/INTO for its own types (IV.A.viii); the same x INTO T / x AS T surface
and $=/$RETURNED/$!/$# consumption apply.AS/INTO on arrays or N-D arrays. A value-array T[] and a dense N-D array
T[,] / T[m,n] / T[3,4] (#31) are containers, not convertible scalars — there is no
T[] AS … / float64[,] INTO …. Convert the elements (loop + x INTO U), or reach for
the relevant codec (§5). N-D arithmetic / reshaping is the numeric-module (AdvancedMath)
surface, not a conversion.Maintenance: when you add or change an OPERATOR in any CONVERSIONS host under
kernel/, update the matching row here. To re-verify the full inventory:
grep -nE 'OPERATOR (INTO|AS)' kernel/{PrimitiveConversions,NumberConverter,FloatConverter,CharConverter,CharWidthConverter,TextConverter,NumberConversions,ComplexConversions,DecimalConversions}.ev
(plus the compiler-assembled … INTO decimal128 set — sources in compiler/analyze/expr_diagnostics.py _ASSEMBLED_DECIMAL_SRC and the build_ir/lower_expr.py parts-helper map.)
Every operator in the language, grouped by what it does: the symbols, the word
operators, and the pipe-result sigils with their word forms. The normative rules
live in ENVZN_CONSTITUTION.md (Part I.F.ii for arithmetic, comparison and
bitwise; the grammar in Article III); this page is the quick reference.
Generated by
bin/build_operators_doc.pyfrom the compiler's lexer (compiler/parse/tokens.py). Do not edit by hand: change the generator and re-run it. The build fails if the lexer gains an operator this page does not describe.
| Operator | Description |
|---|---|
+ |
Adds two numbers, or joins two Strings. Integer overflow is a MathError PANIC, never a silent wrap. |
- |
Subtracts the right operand from the left; as a prefix, negates its operand. Integer overflow PANICs. |
* |
Multiplies two numbers. Integer overflow PANICs. |
/ |
Divides the left operand by the right. Integer division by zero PANICs. |
~/ |
Floor division: divides and rounds toward negative infinity (-7 ~/ 2 is -4). Spelled ~/ because // starts a comment. |
% |
The remainder of integer division. A zero divisor PANICs. |
^ |
Power: raises the left operand to the right, right-associative. It is not bitwise XOR, which is BXOR. |
! |
Postfix factorial (n!). Integer overflow PANICs; != is lexed first, so it never collides. |
# |
Hash-combine: folds two hash values into one with defined wraparound. The one arithmetic operator that never PANICs. |
++ |
Increments a mutable numeric variable. Prefix ++i yields the new value, postfix i++ the old one. |
-- |
Decrements a mutable numeric variable. Prefix --i yields the new value, postfix i-- the old one. |
| Operator | Description |
|---|---|
&+ |
Wrapping add: the true sum modulo 2ⁿ, never a PANIC. The sanctioned way to ask for modular arithmetic. |
&- |
Wrapping subtract: the true difference modulo 2ⁿ, never a PANIC. |
&* |
Wrapping multiply: the low n bits of the full product, never a PANIC. |
| Operator | Description |
|---|---|
== |
Value equality. On floats it is exact IEEE equality, so NaN == NaN is FALSE. |
!= |
Value inequality, the negation of ==. |
< |
Less than. An ordering comparison on a complex operand is an error (E2118). |
<= |
Less than or equal. |
> |
Greater than. |
>= |
Greater than or equal. |
≈ |
Approximate equality for number operands (U+2248): a relative tolerance with an absolute floor. It has no ASCII spelling. |
≉ |
Not approximately equal (U+2249), the negation of ≈. |
BEQUALS |
Bit-pattern equality: compares the raw bits of two values rather than the values themselves. |
BNEQUALS |
Bit-pattern inequality, the negation of BEQUALS. |
| Operator | Description |
|---|---|
AND |
Boolean and. Each clause of a compound condition is parenthesized (I.H.i). |
OR |
Boolean or. |
XOR |
Boolean exclusive or: TRUE when exactly one side is TRUE. |
NOT |
Boolean negation. |
| Operator | Description |
|---|---|
BAND |
Bitwise and. |
BOR |
Bitwise or. |
BXOR |
Bitwise exclusive or. |
BNOT |
Bitwise complement: flips every bit of its operand. |
LSHIFT |
Shifts left by a count. A count at or past the bit width is an error when provable (E2130), otherwise a PANIC. |
RSHIFT |
Logical right shift: the vacated high bits are filled with zeros. |
ASHIFT |
Arithmetic right shift: the vacated high bits copy the sign bit. |
LROTATE |
Rotates the bits left; bits shifted out re-enter at the low end. |
RROTATE |
Rotates the bits right; bits shifted out re-enter at the high end. |
| Operator | Description |
|---|---|
= |
Binds a value: any primitive, value class, STATUS or enum expression. A String takes only a literal, and any other class only EMPTY. |
:= |
Binds ownership: construct (CREATE), copy (DUPLICATE) or move. A moved-from local cannot be read again. |
=@ |
Binds a non-owning reference to an existing value (REFERENCE T r =@ x). |
+= |
x += e means x = x + e, with +'s overflow rules. A statement on a plain local variable only. |
-= |
x -= e means x = x - e. |
*= |
x *= e means x = x * e. |
/= |
x /= e means x = x / e. |
%= |
x %= e means x = x % e. |
| Operator | Description |
|---|---|
?? |
Not an operator: lexed only so the compiler can stop it with E1164. Test presence with IS VALID / IS NOT VALID. |
IS VALID |
Presence test on a class-typed binding; narrows it to present inside the THEN branch. IS NOT VALID is the negation. |
IS |
Compile-time type test in WHEN and MATCH (WHEN T IS String). IS NOT negates it, and IS PRIMITIVE tests for any primitive. |
AS |
A checked conversion that can fail: narrowing or reinterpreting, range-checked at run time, never a silent truncation (int64 AS int32). |
INTO |
A lossless conversion into a type that can represent every source value (int32 INTO int64, 42 INTO String). |
Set)| Operator | Description |
|---|---|
|+| |
Union: a new Set holding every element of either operand. Both operands must be Sets (E2034). |
|&| |
Intersection: a new Set holding the elements present in both operands. |
|-| |
Difference: a new Set holding the elements of the left operand that are not in the right. |
| Operator | Description |
|---|---|
-> |
Calls a method on an object: obj->method(args). |
:: |
Qualifies a name with its module or namespace: Json::Parser, FOREIGN::open. |
... |
Marks a variadic parameter: Type... name. |
=> |
Attaches the message to ASSERT(cond) => msg and UNREACHABLE! => msg. Reserved everywhere else (E1023). |
IF / WHILE)| Operator | Description |
|---|---|
$= |
The success value in the success branch; $=[1] reads a second slot. |
$RETURNED |
The word form of $=. |
$! |
The failure message (a String) in the failure branch. |
$ERR_MESSAGE |
The word form of $!. |
$# |
The failure's numeric code (int32; 0 when none was supplied) in the failure branch. |
$ERR_CODE |
The word form of $#. |
$? |
Discards a returned slot: $? := call(), or a $? slot in a multi-value receive. |
| Operator | Description |
|---|---|
$* |
The C result is owned by the caller: copy it into the Envzn value, then free() it. |
$(freer) |
As $*, but frees with the named C function: $(sqlite3_free). |
Every primitive type in the language, grouped by what it is for, with the
aliases the compiler accepts. The normative rules live in
ENVZN_CONSTITUTION.md (Part I.D); conversions between them are in
Conversions. This page is the quick reference.
Generated by
bin/build_primitives_doc.pyfrom the compiler's primitive table (compiler/common/primitives.py). Do not edit by hand: change the generator and re-run it. The build fails if the compiler gains a primitive this page does not describe.
| Primitive | Description |
|---|---|
int8 (i8) |
Signed 8-bit integer. Overflow is a MathError PANIC, never a silent wrap. Range −128 to 127. |
int16 (i16) |
Signed 16-bit integer. Overflow PANICs. Range −32,768 to 32,767. |
int32 (i32) |
Signed 32-bit integer. Overflow PANICs; name it explicitly when you want 32 bits. Range −2^31 to 2^31−1. |
int64 (integer, int, i64) |
The default integer: int and integer mean int64, as does a FOR counter and an array's .length. Overflow PANICs. Range −2^63 to 2^63−1. |
int128 (i128) |
Signed 128-bit integer, a full V1 primitive with arithmetic, comparison and the keyword-bitwise operators. Range −2^127 to 2^127−1. |
| Primitive | Description |
|---|---|
uint8 (u8) |
Unsigned 8-bit integer. Overflow, including going below zero, PANICs exactly as a signed type does. Range 0 to 255. |
uint16 (u16) |
Unsigned 16-bit integer. Overflow PANICs. Range 0 to 65,535. |
uint32 (u32) |
Unsigned 32-bit integer. Overflow PANICs. Range 0 to 2^32−1. |
uint64 (uint, u64) |
Unsigned 64-bit integer. Overflow PANICs. Range 0 to 2^64−1. |
uint128 (u128) |
Unsigned 128-bit integer, a full V1 primitive. Range 0 to 2^128−1. |
| Primitive | Description |
|---|---|
float32 (float, f32) |
IEEE 754 single precision. Untrapped: overflow gives ±Infinity and underflow a signed zero, the type's defined results. 32 bits. |
float64 (f64) |
IEEE 754 double precision, the usual choice for real numbers. Untrapped, like float32; == is exact IEEE equality. 64 bits. |
| Primitive | Description |
|---|---|
number |
A self-aware int64 or float64 that promotes up INTEGER → UNSIGNED → FLOAT instead of overflowing. Opt-in, and Equatable only. |
complex |
A pair of numbers written with im (3 + 4im), with .real, .imaginary, .magnitude and .phase. Equatable only; it has no ordering. |
decimal128 (decimal) |
IEEE 754-2008 exact base-10 with 34 significant digits, rounding half-even. Comparable and Hashable, so it can key a Dictionary. |
| Primitive | Description |
|---|---|
boolean |
TRUE or FALSE. Never converts implicitly to or from a number. |
char8 (c8) |
One 8-bit UTF-8 code unit, which is not a code point (a lead byte is not a character). Stored like uint8 but a distinct type. 8 bits. |
char16 (c16) |
One 16-bit UTF-16 code unit. Stored like uint16 but a distinct type. 16 bits. |
char32 (char, character, c32) |
One Unicode code point, U+0000 to U+10FFFF: char and character mean char32. A code point plus an integer is still a code point. 32 bits. |
binary |
An opaque 8-bit octet: a bit pattern, not a number. It takes assignment, the offset operators, the keyword-bitwise operators and comparison, and defaults to 0x00. 8 bits. |
| Primitive | Description |
|---|---|
opaque |
A value carried behind a runtime type tag, for heterogeneous storage the static types cannot express, such as a dictionary whose values differ in type per key. |
| Primitive | Description |
|---|---|
C.size_t |
C's size_t, spelled exactly, for FOREIGN BIND declarations only. No guaranteed width and no arithmetic; that is its contract. |
C.ssize_t |
C's ssize_t, for FOREIGN BIND declarations only. |
C.long |
C's long, for FOREIGN BIND declarations only; its width differs by platform, which is why it is named rather than guessed. |
C.unsignedLong |
C's unsigned long, for FOREIGN BIND declarations only. |
C.mode_t |
C's mode_t, for FOREIGN BIND declarations only; 16 bits on Darwin and 32 on Linux, which is why it is named rather than guessed. |
| Primitive | Description |
|---|---|
complex_int32 |
Retired in favour of complex. Kept reserved so the name is rejected (E2009), not reused. |
complex_float32 |
Retired in favour of complex; reserved so the name is rejected. |
complex_float64 |
Retired in favour of complex; reserved so the name is rejected. |
bigint |
Reserved for an arbitrary-precision integer. Not usable yet. |
rational |
Reserved for an exact fraction. Not usable yet. |
bit |
Reserved for a single bit. Not usable yet. |
Everything the kernel gives every Envzn program, with no dependency to declare, grouped into families by what it is for.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
| Family | What it is for | Types |
|---|---|---|
| Core interfaces | The contracts every other family is built on: copying, equality, ordering, hashing, iteration, views, and reading and writing text. | BidirectionalIterator, Collectable, Collection, Collectors, Countable, Iterator, ObjectIterator, ReferenceIterator, Searchable, ValueIterator, Cloneable, Inoperative, Comparable, Equatable, HashKey, Hashable, Incomparable, OperatorEquatable, WordKey, Printable, Readable, Text, Writable, View, Viewable |
| Strings | Text and bytes: the immutable String and ByteBuffer, their mutable twins, and the views and iterators over them. |
String, DynamicString, StringView, ByteBuffer, DynamicByteBuffer, ByteBufferView, ByteBufferIterator |
| Collections | Arrays, lists, queues, sets and dictionaries, with their iterators. | Array, ArrayIterator, OrderedArray, NativeArray, NativeNdArray, Deque, Queue, Stack, SortedList, Set, Box, GrowthHint, EvArr, EvNdArr, LinkedList, LinkedListIterator, OwnedList, OwnedListIterator, Dictionary, ChainedHashDictionary, HashBucket, HashBucketIterator, CollisionNode, IntKeyedDictionary, IntKeyedDictionaryIterator, ProHashDictionary, ProHashDictionaryIterator, RedBlackTreeDictionary, RedBlackTreeDictionaryIterator, ShallowDictionary, ShallowDictionaryIterator, StringKeyedDictionary, StringKeyedDictionaryIterator, BinaryWord |
| Numbers | The class-backed numeric primitives and the math that works on every number type. | NumStore, Number, Complex, Decimal128, DecimalText, Math, NumericLimits, NumericUtilities, FloatFormat, Arithmetic, Floating, Multiplier, Numeric, ValuePrimitive, NumberKind, RoundingMode, DecimalParts |
| Date and time | Instants, durations, and timing. | DateTime, DateTimeFactory, TimeDuration, DurationText, MeasuringTimer, TimeConstants, TimeComparison, DateTimeFields |
| Concurrency | Threads, tasks, channels, locks, worker pools and atomics. | Task, Future, Channel, MessageBroker, Subscription, Mutex, Lock, WorkerPool, WorkerPoolCore, AtomicBoolean, AtomicBinary, AtomicChar8, AtomicChar16, AtomicChar32, AtomicInt8, AtomicInt16, AtomicInt32, AtomicInt64, AtomicUint8, AtomicUint16, AtomicUint32, AtomicUint64, Concurrency, Shareable, TaskStarter, TaskStarterOptions, TaskStarterWithOptions, BackpressurePolicy |
| System | The runtime and the outside world: processes, files, paths and standard I/O, plus the codecs, the conversions between types, and randomness. | System, Stdio, CommandLineArguments, Process, File, Path, BuildInfo, EnumReflection, Formatter, FormatArgument, FormatValue, EntryOptions, Formattable, BinaryMode, Build, Encoding, Endianness, FormatKind, IdentityAccess, EnumKind, FormatSpec, Identity, IdentityField, IdentityMethod, IdentityParameter, ProcessResult, Base64Codec, ByteOrderCodec, DecimalCodec, HexCodec, UTFCodec, TextEncoding, PrimitiveConversions, NumberConversions, ComplexConversions, DecimalConversions, TextConverter, CharConverter, CharWidthConverter, NumberConverter, FloatConverter, FloatParseConverter, FloatParse, FloatParseResult, FloatBigInt, FloatToDecimal, NumberToDecimal, CharClassifier, FloatingDecimal32, FloatingDecimal64, Pow5Entry, CasualRandom, SecureRandom, SeededRandom, Shuffleable, Random, Shuffler |
| Hashing | The hashers behind the dictionaries and sets. | Hasher, DefaultHasher, StringHasher, SipHasher, SipState, FastIntHasher, InlineIntHasher, HashConstants, SipVariant |
| Errors | The error classes the kernel throws. | Error, CompileError, FileError, IndexOutOfBoundsError, MathError, NetworkError, EmptyHandleError, RandomError, OutOfMemoryError, ResourceExhaustedError, CloneError, LensMismatchError, Severity |
| Misc | DataValue, the dynamic value behind JSON serialisation, and opaque. |
DataValue, DataValueBuilder, DataValueReader, Fields, Reconstructable, Reconstructor, Serializable, Serializer, DataKind, DataNodeKind, ParseMode, DataNode, Opaque, OpaqueType, OpaqueArrayCell, OpaqueKind |
Envzn's compiler, evc, reads your .ev files and writes C++20, which clang++ turns into a
native program. Between those two ends, the work is split into stages, and each stage has exactly
one job. That split is what lets the compiler promise that a program it accepts is memory-safe,
and what will let the C++ step be replaced without changing what any program means.
REFERENCE is followed. A program
that breaks a rule stops here, with a code, a location and a remedy.clang++ compiles the C++, and epm, the package manager, orchestrates modules,
dependencies and the link.Compiling through C++ gets Envzn onto every platform clang reaches today, with a mature
optimizer behind it, while the language itself was the work that mattered. Because the emitter
makes no decisions of its own, C++ is a replaceable last step: everything a program means is
settled in the EvIR. A native LLVM backend is designed to replace the C++ step, starting from the
same EvIR, so a program will compile to the same behaviour either way.
The compiler itself is written in Python today. Everything a program runs on is written in Envzn: the kernel (strings, collections, numbers, files, threads) and the standard library built on it, with a thin layer of C and C++ only for what the operating system alone can do. That is the design principle at work, relocate the cost inward: the hard machinery lives in the compiler and the library, so the code you write stays readable.
What the language gives you, one feature at a time. The Introduction covers the basics; this page goes further into each design choice.
Envzn has no null, no optional type, and no ? suffix. The absence of an object is a state of the binding, EMPTY, which the compiler tracks to the point of use, and primitives cannot be absent at all. Ownership is explicit (one owner per object, except a SHARED class, which is co-owned), borrows are checked, and the analysis is a whole-program walk rather than a per-file approximation. Safety is the trait that is never traded away for any of the other five.
There are no pointers to manage. Envzn uses ownership handles and reference handles for objects, and these are never null — with one exception, WEAK REFERENCE.
Envzn compiles ahead of time to native code through a C++20 backend, over an intermediate representation of its own (EvIR) that is specified node by node. The standard library is written in Envzn, not in a faster language behind a wrapper, which means the performance you can reach is the performance the library already reached.
When the size is known, T[N] declares N live, default-initialized slots inline in the object. No CREATE, no heap allocation, no zero-fill loop — it arrives usable, because every numeric primitive defaults to zero. The growable T[] pays an allocation plus whatever initialization you write for it. The difference is not theoretical: a membership table in the kernel's string scanner was building a 256-entry growable array per call; declaring the field as int32[256] and deleting the loop took the same scan from 553 ms to 81 ms — 6.8×, with no change to the algorithm.
A compiler error carries a stable code, a file, a line and a column, a remedy, and a reference to the clause of the specification it enforces. It was important for the evc compiler to become a “teaching compiler”, so someone new to the language can learn it from the errors it reports. Every code has its own entry on the Diagnostics page.
The kernel carries text, collections, math, time, and I/O; around it sit modules for JSON, logging, regular expressions, tabular data, networking, testing, and multi-dimensional arrays, with a package manager (epm) that fetches a module and its dependencies rather than a whole distribution. Every kernel type has its own page, generated from its source; the module pages follow.
Generics and templates are not two things in Envzn. There is one mechanism, written TEMPLATE, and it exists to let you write a single homogeneous, type-preserving container instead of many. What opens one is a preamble of qualifiers on its type parameters, so a template states what it will accept before it states what it does:
TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT boolean, opaque, complex, number):
Several parameters each carry their own group of qualifiers, and compile-time dispatch (WHEN K IMPLEMENTS Equatable[K]) narrows a parameter further at instantiation. The payoff is in the error messages: because the contract is declared, a misuse is reported against the line the author wrote rather than against something deep inside an instantiation, which is most of the difference between a template a person can read and the error output C++ became notorious for.
What Envzn deliberately does not offer is template metaprogramming. Heterogeneity is expressed with an interface instead, because a generic system powerful enough to compute types is also powerful enough to make an error message unreadable.
A class may IMPLEMENT interfaces and EXTEND a base class. Interfaces carry the contract and are the handle you hold; inheritance is available where a genuine specialization exists, rather than being the only tool in the box for sharing behavior. Holding a value through an interface does not throw away what it is. An interface in Envzn is a lens rather than an erasure: the value keeps its concrete identity underneath, and where the flow of a program proves that concrete type, recovering it binds directly and costs nothing. Where the concrete type is genuinely not known, the compiler says so and points at the WHEN … IS check rather than letting the program assert its way through.
Envzn separates the things other languages let blur together. A char is never an octet, and neither one is a number: char, binary, and uint8 are three distinct types and none implicitly converts into another. Conflating a byte with a character is the classic Unicode defect, so the language refuses the conflation at the type level rather than documenting it and hoping. The same goes for signed and unsigned integers, which never mix without a conversion you write. Every primitive, with its aliases, is on the Primitives page.
Four containers fall out of two independent questions — text or bytes, immutable or mutable: String, ByteBuffer, DynamicString, DynamicByteBuffer. Text prints as text and binary prints as hexadecimal; a String is never a place to carry arbitrary bytes.
A StringView or ByteBufferView is a window onto storage someone else owns — a bounded range of code points or bytes, obtained with ->view(start, length), with no copy. A window of a window is a window, so a view narrows further with its own ->view, and materialises into an owning array with ->copy() when you actually need one. What makes it safe rather than merely fast is that a view cannot outlive what it borrows: storing one in a field or returning it as an escaping value is a compile error, not a documented hazard. The Which text type? guide says which to reach for.
Between the struct and the class sits a third kind. A VALUE CLASS carries the methods, generics, and interface conformance of a class, but the value identity and inline storage of a struct: it lives where it is declared rather than behind a heap handle, and is passed and copied by value. (One that holds owning fields moves instead, like the objects it holds.) This is what lets a number-like type carry real behaviour without paying for an object — decimal128, number, and complex are all value-class-backed, which is why they have methods and operators when the bare primitives do not.
A multi-dimensional array is a real type, not an array of arrays. float64[m,n] constructs at runtime and float64[3,4] stores inline; one comma-subscript a[i,j] gives one coordinate per axis. The storage order is column-major — axis 0 is contiguous — which is the order the numerical libraries of the last fifty years expect, so an Envzn matrix hands to BLAS and LAPACK without a transpose. Loop with the first index innermost, and the compiler will tell you when you have not.
int32 m = 3
int32 n = 4
float64[m,n] a
a[0,0] = 1.5
a[2,3] = 9.0
FOR j = 0 UNTIL n {
FOR i = 0 UNTIL m {
a[i,j] = 0.0 // column-major: first index innermost
}
}
Destruction happens at a point the source determines, not whenever a collector next runs. Every owned object is released at the end of the scope that owns it, and a CLEANUP block runs on the way out — including the unwind path of a panic, and in reverse construction order, so the last thing built is the first thing torn down. Leaving a scope early by any route unwinds it the same way: a labelled BREAK, a return, a panic. This is what “memory-safe without garbage collection” actually costs and actually buys — release is a fact about the program text rather than about a runtime's schedule.
RETURNS either-orThe two are different situations, so they get different mechanisms. Errors are recoverable and are returned as a STATUS value — a file that is not there, a parse that did not match, a socket that closed. PANIC occurs when a foundational law has been violated: a divide by zero, an index outside its array, an arithmetic overflow. A panic is minimally recoverable, deliberately so — enough for a developer to catch it, log it, and shut the application down gracefully, and not so much that a program can make a habit of continuing past a broken invariant.
Many methods have to answer with one thing or the other: here is the object you asked for, or here is why you cannot have it. Envzn writes that directly into the return declaration with a | separator, and exactly one side is populated per call — the success side or the failure side, never both:
METHOD subscript(int64 index) RETURNS (MUTABLE REFERENCE T result | STATUS s)
MODIFY METHOD next() RETURNS (REFERENCE T value | STATUS s)
The success side may carry several typed slots, all populated together; the failure side is a single STATUS. Because the two sides are declared, the caller cannot read the value without having dealt with the possibility that there isn't one — there is no sentinel to miss, no null to forget, and no exception travelling invisibly up the stack. It is also distinct from an ordinary multi-value return, where every slot is always populated.
An integer operation that overflows raises a MathError panic. It does not wrap around silently, and it is not undefined. Where wrapping is genuinely what you want — a hash, a checksum, a ring buffer — you ask for it by name with the modular operators &+, &-, and &*, so the intent is on the page rather than in the reader's assumptions. Shift counts are policed the same way: a count outside the width is a compile error where the compiler can prove it and a panic where it cannot, never a silently zeroed result.
A developer writing concurrent Envzn does not write threads — they write tasks inside a scope. The unit of work is a Task, and every task's lifetime is bound to the CONCURRENT { … } block that launched it. The closing brace is a join point, which gives a guarantee worth stating plainly: a function call cannot leave background work running after it returns. The everyday shapes — a pool of workers draining a queue, a pipeline of stages, a broker fanning a message out to subscribers — are named, typed classes in the standard library rather than primitives you assemble; Channel, Future, Mutex, and the atomics stay in the kernel for the cases the standard shapes do not fit.
IDENTITY(x) asks the compiler what something is and hands back a struct describing it: the bare name, the module it lives in, its parameterized full name, its kind (class, value class, interface, enum, primitive …), whether it is generic, whether it is internal, whether it is blittable, and the ancestry it was reached through. For an enum it also carries the cases, name and value, in declaration order. All of it is computed during compilation and costs nothing at run time, and the compiler is its only producer — a program cannot fabricate one. That is enough to write serialization, logging, and configuration binding as ordinary library code rather than as a framework with its own annotations.
There is no syntax in Envzn that reinterprets one type as another. No C-style cast, no parenthesised type in front of a value, nothing that lets a program assert a type it has not earned. What a strongly typed language actually needs is not casting but conversion, and conversion is common, so it gets two operators that say which kind it is. x INTO T is the widening, lossless one and always succeeds. x AS T is the narrowing, lossy one and is fallible — it hands back a value or a status, so the case where it does not fit is a case the code has to handle rather than a surprise at runtime.
Where a program needs to branch on a more specific type, it asks with a WHEN type-check. The narrowing inside the true arm is something the compiler has proved, not something the developer has asserted — and that difference is the whole reason the cast is missing.
There are no static variables and no static functions sitting at a global level. Where a set of functions belongs together but no object needs to exist to hold them, the mechanism is a NAMESPACE: a stateless host of free functions and constants, reached by name — Math.PI, Math.sqrt(x). It holds behaviour and constant data and nothing else; a variable field, a mutating method, or a lifecycle in a namespace is a compile error, because a namespace has no instance to have state in. A namespace exists so that not everything need be a class.
SELFThere is no SELF and no this, and there never will be: SELF is a reserved word, held so that it can never be used, now or in the future. The author's view is that the keyword is a vestige that enables identity-centric bad design: god objects, self-referential mutation, and fluent builders that hand themselves back so a caller can write x->a()->b()->c(). The urge to reach for it is really the urge to avoid naming structure, and the language would rather you named the structure.
What replaces it is the two-layer cake. Split the thing in two: a minimal storage layer that holds the data and carries little behaviour, and a rich public face composed over that storage, which holds the behaviour actually worth using. The canonical example is in the text types — char32[] is the storage, and String is the face built over it. Applied to a builder, the storage type accumulates with plain MODIFY methods that mutate their own fields and return nothing, and the face type consumes it; you call the methods on a named local, one line at a time, instead of threading a chain through an object that keeps handing itself back. The result is that no object ever gives out a reference to the whole of itself, and the structure a program actually has ends up written down.
Calling a C function is a declaration, not an escape hatch. A FOREIGN BIND names the C symbol and gives it Envzn types; from then on it is called like anything else, and the compiler type-checks the call site the way it checks every other one. Where the C types line up with Envzn's, the binding is a one-to-one passthrough and no hand-written shim exists at all — the kernel's Math namespace binds straight to <math.h>:
FOREIGN BIND sqrt(float64 x) RETURNS float64
FOREIGN BIND pow(float64 base, float64 power) RETURNS float64
FOREIGN BIND atan2(float64 y, float64 x) RETURNS float64
FOREIGN BIND hypot(float64 x, float64 y) RETURNS float64
Where the C types do not line up, the declaration says so rather than guessing. Five C-ABI types — C.size_t, C.ssize_t, C.long, C.unsignedLong, C.mode_t — lower verbatim to the C spelling they name and are legal only inside a foreign declaration. They carry no arithmetic and no guaranteed width, and that absence is the contract: size_t is unsigned long where uint64_t is unsigned long long, and which of the two matches flips between macOS and Linux, so a fixed-width primitive would compile on one target and fail on the other. This is the Networking module binding POSIX sockets:
FOREIGN BIND send(int32 fd, binary[] data, C.size_t nbyte, int32 flags) RETURNS C.ssize_t
FOREIGN BIND recv(int32 fd, LOAD binary[] buf, C.size_t nbyte, int32 flags) RETURNS C.ssize_t
Two details are worth reading off that pair. The buffer is binary[] — a byte array, not a text type — because bytes off a socket are bytes. And recv marks its buffer LOAD, which says the C function writes into it rather than reading from it, so the direction of an out-parameter is visible in the declaration instead of living in a comment. Validation stays on the Envzn side: a bind performs the raw call and nothing else, and the checking a caller should get is written in Envzn around it.
Envzn is defined by a written constitution, and the implementation is measured against it rather than the other way round. The document describes the language as it is intended to be, and a conformance check compares the compiler against it. Where the two diverge, the gap is work not yet overtaken rather than an error in the design — and a construct described in the specification but not yet implemented is marked as such rather than quietly implied. The discipline that comes with it is the part worth having: when the specification and the code disagree, that is a defect to be fixed in the same change, not a divergence to be explained later.
Two application domains shaped the type system rather than being served by libraries after the fact.
Money. decimal128 is a first-class primitive: an IEEE 754-2008 exact base-10 number with round-half-even arithmetic, a rounding-context surface, and a defined 16-byte wire encoding. It is comparable and hashable, so it is a valid dictionary key and a valid sort element. Mixing it with binary floating point in one expression is a compile error, not a silent rounding — if you want that conversion you write it down. On top of it sit the money and quant modules.
Data. Alongside the fixed-width numerics, number is a self-aware integer-or-float value and complex is a pair of them written with an im literal (3 + 4im). Column-major N-D arrays, a tabular Data module, and the AdvancedMath → stats → mlearn chain give the numerical stack, written in Envzn over vetted BLAS and LAPACK rather than reimplemented.
Language version: 2.0 Document status: Working draft. Article I is normative and wins on conflict; Article II describes the EvIR and its lowering, and Article III is the grammar. Author: Brian Haughton
Copyright © 2026 The Data Science Group, LLC.
This Constitution is the reference description of the Envzn programming language. It is a working document rather than a finished standard, and it is written with the understanding that a language under active construction will always describe a little more than it has so far built. Two earlier habits made the document harder to use than it needed to be. The language was specified once and then partially re-specified a second time under a different heading, so a reader chasing a single rule could find two accounts of it that no longer agreed. And the material that describes what Envzn is sat in the same flat sequence as the material that describes how the current compiler implements it, with no signal telling the reader which one they were standing in. This rework separates those concerns deliberately.
The document is now organized into three articles, and the distinction between them is the most important thing to understand before reading further:
Article I — The Envzn Language is the normative specification. It describes the language as conceived: its purpose, its principles, its definitions, and every one of its constructs, laid out in the ordinary categories a compiler text would use — types, expressions, statements, control flow, memory, and so on. Article I is implementation-independent. It says what a correct Envzn program means, not how any particular compiler produces it. Where Article I and any other article disagree, Article I is authoritative.
Article II — The Envzn Intermediate Representation and its Lowering indexes Envzn's own intermediate representation, the EvIR. It summarises the EvIR's fourteen node groups and points into the companion ENVZN_IR_SPEC.md, which carries the full node specification, the C++ lowering of every node, and the lowering model. That companion is generated from the compiler's own spec-trace and kept in sync with this constitution; like the lowering it records, it describes current behavior and is expected to change as the compiler does.
Article III — Grammar (EBNF) is the normative concrete grammar, consolidating in one place the lexical and syntactic rules stated in prose across Article I. It is a formalization of Article I, not a second authority: where the grammar and Article I disagree, Article I wins and the grammar is the defect. It is built in tranches; every not-yet-expanded non-terminal is flagged so its coverage is never silently overstated.
Which document wins. The order of authority is fixed, and it is worth having in one place. Article I governs what a program means; where it and anything else disagree, Article I decides. Article III is normative for concrete syntax and formalizes Article I — where the grammar and the prose diverge, the grammar is the defect. Article II is descriptive rather than normative: it summarises how the EvIR lowers today, and where it and the generated ENVZN_IR_SPEC.md disagree, the specification wins, because it is anchored to the compiler's own trace. ENVZN_USER_GUIDE.md is non-normative throughout and constrains nothing.
Two divisions that this document formerly carried have been moved out, and their section labels are preserved unchanged so existing cross-references still resolve. The former Article III — The Developer Guide (non-normative idioms, code style, and testing practice, labelled III.A–III.C) is now ENVZN_USER_GUIDE.md; references of the form III.C are written here as ENVZN_USER_GUIDE.md III.C to distinguish them from the grammar's III.0–III.7. The former Article IV — Roadmap and Pending Surface recorded work that was specified but not shipped; it is maintained separately and is not part of this Constitution's closed set. Where a construct here is designed but not yet available, this document says so in place rather than referring out. Neither companion is normative, and nothing in this Constitution depends on either for a rule.
Two conventions run through the whole document. Normative statements — the rules a conforming implementation must obey — are written as plain declarative prose; where a rule names a specific compiler behavior, it says so. Informative statements — rationale, examples, and cross-references — explain rather than constrain, and are marked as such when the distinction matters. Throughout, code blocks show Envzn source unless they are explicitly labelled as emitted C++ or as shell commands.
Every rule carries a stable label of the form Article.Section.Part.Paragraph —
I.J.ii.c names paragraph (c) of Part ii of Section J of Article I. Labels are
append-only and are never reused, so a reference written today resolves to the same rule
later, even as the document grows around it.
One gap is deliberate, and worth stating because a careful reader will notice it. Under
I.J.i the source once carried two paragraphs both labelled (o); resolving that collision
relabelled them (s) and (t), leaving (r) unused. The sequence there runs a–q, s,
t. (r) is not a missing paragraph.
Article I — The Envzn Language (normative)
Article II — The Envzn Intermediate Representation and its Lowering (spec; full node/lowering tables in ENVZN_IR_SPEC.md)
Article III — Grammar (EBNF) (normative concrete grammar; formalizes Article I)
Appendix — Reserved Identifiers Catalog
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The normative specification of Envzn. This article describes the language as conceived — its purpose and character, then every construct in the ordinary categories a compiler text uses: types, declarations, expressions, statements, control flow, memory, aggregates, abstractions, concurrency, errors, modules, and the standard-library surface. It is implementation-independent: it says what a correct Envzn program means, not how any particular compiler produces it. Where this article and any other disagree, this article is authoritative.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Establishes why Envzn exists and the standard every design decision is judged against: the six character traits, the fixed tiebreak that makes memory-safety the floor and otherwise relocates cost inward, and the principles and growth-commitments a proposed feature is obeyed-or-rejected by.
(a) Envzn (pronounced "envision") is a compiled, statically typed, object-oriented language for building robust application software. It rests on a deliberate premise: that a single language can carry the full weight of modern systems work — ownership, concurrency, a real module system, a typed foreign-function boundary — while keeping a surface plain enough that a reader new to the language can still follow a program. Complexity in Envzn is not eliminated, because it cannot be; it is relocated. The difficult machinery lives inside the compiler, the kernel, and the standard library, where it is written once and audited carefully, so that the code a developer writes from one day to the next stays close to ordinary description rather than ceremony.
(b) That premise produces a particular set of trade-offs, and it is worth being honest about them at the outset. Envzn prefers an English keyword to a punctuation symbol almost everywhere the choice arises. Code is read far more often than written, and a reader should not need an operator-precedence table in working memory to scan a function. It prefers one obvious way to express a thing over several interchangeable ways, accepting that an experienced developer will occasionally find the one obvious way slightly longer than a terser alternative would have been. And it resolves questions of memory safety through a compile-time ownership model rather than a garbage collector, accepting a stricter set of rules at authoring time in exchange for predictable destruction and no runtime collection pauses.
(c) Beneath that premise sit six traits that describe the character the language is reaching for. They are not constructs and they are not rules a compiler can check; they are the qualities Envzn is meant to exhibit when it is working as intended, and together they are the standard against which any proposed change is weighed. When a question about the language is genuinely open — when two reasonable designs present themselves and the only thing left to decide is which is the more Envzn of the two — these six are the terms the argument is settled in.
(d) These six are held in balance rather than ranked, and most of the time a sound design serves all of them at once — finding the option that does is much of the craft of the language. But they can pull against one another: the fastest implementation of a thing is rarely its most readable form, and a check that makes a program safe is seldom free. When they conflict, the order of resolution is fixed. Memory safety is the floor, and it is never traded — a faster or simpler design that cannot be shown safe is rejected for that reason alone, exactly as the ownership principle below requires. Above that floor, the standing resolution is to relocate the cost inward. The intricate, fast, difficult machinery moves into the compiler, the kernel, and the standard library, written once and audited closely, so the surface a developer reads and writes stays readable and intuitive while the implementation beneath stays fast. This is the premise that opened the section, turned to use as a tie-breaker. Where even that does not decide, the conflict is settled case by case, in the open, against these six traits. There is no further mechanical rule; inventing one to dodge the judgment would serve the traits less well than making it.
(e) One tension, finally, the language does not try to resolve at all. A readable surface and the terse shortcut an experienced developer reaches for pull in opposite directions, and always will. The construct that reads most plainly on first encounter is rarely the most economical for someone who has written it a hundred times. Envzn does not pretend this tension away. It leans, by default, toward the reader: the one obvious way is the readable one, and power lives a step off the routine path rather than across it. An advanced developer will now and then find that path longer than a denser language would have made it. That cost is real, it is permanent, and the language pays it on purpose.
(f) The traits describe what the language is reaching for; the principles below are the fixed commitments that make the reaching possible. A trait is weighed, but a principle is obeyed — it is not a goal to be traded against a feature, and a proposed feature that violates one is rejected on that ground alone:
(g) Beyond the principles, a set of commitments governs not what the language is but how it is allowed to grow, and they belong in its constitution because a language is only ever as world-class as the discipline that tends it. The first is that surface simplicity is structural and may not be spent down quietly. A feature that buys capability by adding syntax the routine reader must carry has moved cost from the implementer onto every future reader. That trade is made deliberately, with a stated reason. The second is that a shipped feature is world-class or it is diagnosed. A capability either works completely, or its limits are reported at compile time and carry a documented path to removal that the present design does not foreclose. There is no silent "good enough": a limitation a developer meets only by colliding with it is treated as a defect. The third is a commitment to honesty in the work itself. A change that quiets a visible symptom while leaving the real problem in place is rejected: it turns a problem that could be seen into one that cannot. A pragmatic shortcut is taken only when named and bounded, never when silent. The last is that the specification runs slightly ahead of the implementation on purpose. This Constitution describes Envzn as it is intended to be; the canonical compiler measures what exists today. Where the two diverge, the gap is work not yet overtaken rather than an error in the design. Article II records only what the compiler actually does, and is the place to confirm whether a construct is live. A construct described in Article I but marked here as not yet implemented is aspirational: part of the designed language, not yet part of what a developer can compile today.
(a) An Envzn program is built up in layers, and it is worth seeing the whole shape of that composition before any single layer is examined in detail. At the top stand applications and libraries. An application is a program that runs; a library is one or more modules combined to provide some specific, reusable capability rather than to run on its own. Both an application and a library are composed of modules, and every module depends — always, and without having to declare it — on the Envzn kernel module, together with whatever other modules its particular work requires.
(b) The module is the unit of composition below the application or the library, and I.N describes it in full; what matters at this overview level is what a module contains. A module is composed primarily of classes, supported by interfaces, enumerations, and structs. The file layout of a module follows directly from that division of roles. Each class is placed in its own .ev file, named for the class it holds, so that the .ev files of a module enumerate its classes one for one. The supporting types are grouped by kind, each grouping file named for the kind of declaration it collects: every interface and group into interfaces.ev, every enumeration into enums.ev, structs into structs.ev. A struct closely tied to one type may instead take its own file beside it (I.N.g).
(c) A class is a named block, and it is composed of two kinds of member: its data fields, which hold primitive values and instances of other classes, and its methods, which carry the behavior. A class may inherit the methods of a single parent through EXTENDS, and it may implement zero or more interfaces through IMPLEMENTS. An interface, by contrast, is a contract rather than a container: it must declare at least one method, and it may not declare any data fields at all. The constructs that relate classes and interfaces to one another are the subject of I.K.
(c.i) Rule — no phantom computed fields. A class's data fields are exactly those it declares. The compiler synthesizes no computed or phantom data field, so a .name access always reads a declared data field and never silently dispatches to a method. A quantity a class exposes through behavior — a length, a size, a count derived from its contents — is a method, reached with ->name(), and is never also surfaced as a bare .name field. What the API declares is what a . access sees: no more, no less (I.B.b: . reads a data field, -> invokes a method — not interchangeable). Accessing .name where name is not a declared data field is a compile error (it does not fall through to a synthesized accessor), and where a same-named method exists the diagnostic points the reader at ->name().
(d) A method is itself a named block. It may take inputs and produce outputs. Between the two it is composed of its own local data fields — again, primitive values and instances of other classes — together with the control structures that set and manipulate both those and the enclosing class's data fields. Within a method, further blocks may appear, and they are of two kinds. A named block is introduced by a keyword — LAMBDA and SYNCHRONIZED are the examples — while an anonymous block is a bare pair of braces with no keyword at all. Every block, named or anonymous, opens with { and closes with }, and blocks may be nested one within another up to fifteen levels deep.
(e) The block is also the unit of storage lifetime. Local variables declared inside a block are placed on the stack as the block executes. When the block closes they are removed in the reverse of the order they were added: the last variable pushed is the first popped. This is the same last-in, first-out discipline that I.I describes for the destruction of owned values, and it is the mechanism by which a block's closing brace is also the end of its local variables' lives.
(a) The trait the language will not trade is memory safety, and the mechanism that discharges it is worth stating plainly in one place, together with an honest account of how far the current proof actually reaches. The guarantee has two halves. The first is single ownership. Every class instance has exactly one owner, and a move transfers that ownership and poisons the source. Escaping references the ownership proof cannot reach become reference-counted handles, and their combined graph of owning and strong edges must be acyclic. The absence of leaks is therefore a theorem the compiler discharges at compile time (I.I.i, I.I.v), not a behaviour a running program merely tends to exhibit. The second is aliasing discipline: for any one referent, at any one time, either any number of read-only references exist or exactly one writable reference does, never both, and no value may be mutated through another path while a reference to it is live. Together these are what the reference checker of I.I.v enforces, and what every other guarantee in the language rests on.
(b) That discipline is enforced in two layers. The first is a structural analysis: fixed rules over the shapes a program's references and fields may take, together with the acyclicity check over the owning-and-strong graph that discharges the no-leak theorem for the cases that graph can express. The structural layer reasons about one method body at a time. At every boundary where control leaves a body it relies on the callee's checked contract rather than the callee's code: whether a method mutates its receiver, whether a parameter is observed or consumed, whether a reference it hands back is read-only or writable. A call through dynamic dispatch is sound because the marker it trusts has already been checked on the other side. A call whose target monomorphization has made statically known is sound because the concrete body is then available to walk directly.
(c) The structural analysis is conservative, and in narrow cases its shape rules are at once too strict and too loose for the same structure. The second layer is therefore not stricter shape rules but a different kind of analysis altogether. An Envzn program compiles whole-program to its own intermediate representation, with no signatures-only view of a dependency, so the compiler can follow every reference from creation to cleanup through the actual code. The memory-safety proof walks the bodies rather than inferring lifetimes from annotations. A cheap structural pass discharges the references whose safety is obvious, and a flow-sensitive walk runs the precise creation-to-last-use analysis only on the small residue that escapes into fields. This is the analysis that makes the language's central claim true: it can accept a program a signature-based checker must reject, because it sees a body that checker refuses to look at. It is implemented and enforcing — the walk runs after the intermediate representation is built and before any C++ is written, and a reference it proves dangling is rejected outright, so a build cannot proceed past it. What remains is a residue of edge cases the project intends to close: the escape shapes beyond a field store, and the whole-program tier that overlays a dependency's bodies rather than resting on its checked contract.
(d) Two boundaries stand outside the compile-time proof by construction, and the language marks both rather than hiding them. At the foreign-function boundary there is no Envzn code to analyze, so a foreign value is reached only inside an UNSAFE block whose every use is confined and greppable and where the guarantee is explicitly suspended rather than silently weakened (I.I.viii). Across threads the static checker reasons about sequential aliasing only. Concurrent safety is carried by a separate, structural mechanism: ownership transfers on a channel send, task bodies may not capture shared mutable state, and shared mutable state is reachable only through a monitor that serialises its own access (I.L). A data race is prevented by what the language forbids at compile time, not by an analysis of interleavings.
(e) The whole-program walk needs a dependency's bodies, and a library distributed without its source still supplies them. Every compiled module writes its intermediate representation beside its library (<module>.evir), and every module that depends on it reads that file and walks the bodies in it: a call into a dependency is judged by the method's body, not only by its signature. Each file is sealed and fingerprinted, and one that fails those checks stops the build (E9042). The designed next step is a contract inferred from those bodies and frozen at publication, so that a library is proved once in isolation and every consumer is checked against it. Whether that is the final shape of the package artifact is pending rather than settled. This is the memory model held to the same standard as the rest of the document: what is proved is claimed, what is intended is labelled as intended, and the boundaries where the proof stops are named.
(f) One resource lies outside every compile-time proof: the stack. How deep a correct program recurses, or how long an owned chain it drops, depends on its input, so no analysis bounds it. The language's commitment is therefore about the outcome: running out of stack is never a silent crash, and never memory corruption. Every thread Envzn starts records its stack's real bounds, and a stack overflow ends the program with the report fatal: stack overflow in task <name> and exit status 134, on every backend. A fault anywhere else in safe code is reported as fatal: memory fault at <address> and named as what it is, a defect in the compiler or runtime rather than in the program. A frame too large for the space left cannot step over the guard page, because the compiler probes it page by page. This is the floor. Above it, the project intends that dropping a value never uses stack in proportion to its size, and that deep recursion raises a catchable StackOverflowError (I.M.ii(b.iv)) with CLEANUP run; both are labelled intended until they ship. (, kernel-runtime-natives M5.D; the thread stack size is the manifest's, I.N(c.iv).)
Fixes the precise meaning of the foundational terms — handle, owning, EMPTY, STATUS, pipe-XOR, lowering — that the rest of the document relies on, and states the notational conventions (the . / -> sigils, the E#### codes) used throughout.
(a) The terms below carry precise meanings throughout this document, and several of them are used in ways that differ from their ordinary use in other languages. A reader who treats handle, owning, EMPTY, or pipe-XOR as loosely synonymous with a familiar concept from C++ or Swift will misread the rules that depend on them, so the definitions are given here once and relied upon everywhere after.
ENVZN. The terms kernel and ENVZN module are used interchangeably in prose; ENVZN is the precise name when the discussion turns to libraries, linking, or dependency resolution. The kernel is always available to every Envzn program without being declared as a dependency.CLASS, ABSTRACT CLASS, or SINGLETON CLASS declaration, together with String, which is a built-in value type that follows class-type rules for assignment and absence. Class-typed values are heap-allocated and reached through a handle.REFERENCE keyword — observes a value without responsibility for it. Ownership is decided by the REFERENCE keyword alone, never by whether a value may be absent.EMPTY. There is no null, and there is no separate optional type: absence is a state a class-typed binding may occupy, not a wrapper applied to a type. Primitives, STATUS values, enum values, and struct values are never EMPTY — they always hold a defined value.SUCCESS, PARTIAL_SUCCESS, or FAILURE — together with an optional message and numeric code. STATUS is the language's vocabulary for recoverable failure and is distinct from the absence vocabulary built on EMPTY.| separator in a RETURNS clause, in which exactly one of the two declared sides is populated per call — the success side or the failure side, never both. The success side is a tuple of one or more typed value slots, all populated together on success; the failure side is a single STATUS. It is named for its exclusive-or semantics, to distinguish it from the comma-separated multi-return shape in which every slot is always populated.(b) On notation: a fenced code block contains Envzn source unless it is explicitly introduced as emitted C++, as JSON, or as a shell command. Member access is written with two distinct sigils that are not interchangeable — . reads a data field and -> invokes a method — and examples rely on that distinction without re-explaining it each time. A diagnostic code in the form E#### names a specific compiler error; the codes are stable identifiers, and ENVZN_IR_SPEC.md C.viii describes how they are reported. Where a passage describes a construct that is specified but not yet implemented, it says so directly, at the point the construct is described.
The smallest units a tokenizer recognizes before any grammar applies: comments, the newline-terminated statement, the identifier rules, and the numeric, character, and string literals. These are the alphabet every later category is built from.
(a) Rule. Lexical forms are the smallest units of an Envzn program — the shapes a tokenizer recognizes before any grammar is applied. They are the alphabet from which every later category is built, and the language keeps them deliberately few and deliberately plain.
Rationale. Everything the grammar later assembles is spelled out of this fixed, small alphabet; keeping the alphabet plain keeps the whole surface readable, because a reader never has to decode an exotic token before they can parse a statement.
(b) Rule. Envzn has three comment forms. A // begins a single-line comment, and everything from the slashes to the end of the line is ignored. A /* opens a comment that runs, across as many lines as needed, until the matching */. A /// begins a documentation comment, which is retained rather than discarded and is the sole mechanism by which prose written in source reaches the generated API documentation. The first two forms may appear wherever whitespace may appear — at the end of a line of code, alone on their own line, or inside a block — and they carry no meaning to the compiler beyond their own removal.
A documentation comment is governed by four rules. First, a single optional space after the /// is consumed and is not part of the text. Second, consecutive documentation-comment lines form one run, and their text is joined with newlines. Third, a run attaches to the immediately following token that is not itself a documentation comment; where that token introduces a declaration — a class, interface, struct, enum, group, union, primitive, alias, method, initializer, or field — the text is preserved on that declaration, travels with it into the module's emitted .headers, and is therefore visible to consumers of the module as well as to the documentation generator. A run at end of file, attached to nothing, is discarded. Fourth, a documentation comment cannot change the meaning of a program: it is removed before parsing, and no emitted output depends on it.
The form is deliberately the one Rust and C# already use, rather than a spelling invented here. A declaration's description belongs immediately above the declaration it describes, where the person changing the code will see it; a file's identity — its copyright, licence, and purpose — belongs in the ordinary // header block at the top of the file, and module-level prose belongs in a README or other Markdown file. These three homes do not overlap.
Example.
// a single-line comment
/* a comment that
spans several lines */
int32 total = 1_000_000 // trailing comment after code
IF total > 0 THEN {
/* inline, inside a block */
printline("positive")
}
Rationale. Two forms — one line-scoped, one delimited — cover every commenting need without a third variant, and allowing them anywhere whitespace is allowed means the reader is never forced to move a note to an unnatural place.
(c) Rule. A statement ends at a newline. Envzn has no semicolon and no other terminator character; the end of the line is the end of the statement, and a stray terminator is rejected rather than tolerated. Two statements may not share a line: writing a second statement after the first on the same line is a compile error, not a style warning. A newline is a statement terminator only at bracket depth zero: inside an unclosed ( or [ — a multi-line argument list, a wrapped compound condition, a long index or type-argument list — the newline is ordinary insignificant whitespace and the statement continues. The braces of a statement block never suppress termination; inside { … } every newline ends a statement as usual. A closing } (or the end of the file) may itself close the final statement of a block, so the one-line form IF (c) THEN { grade = "A" } is legal. Exactly ONE statement may precede that }: two separated only by a space fall under the two-statements-one-line error, one-line block or not. A continuation keyword must start its own line when the block it continues spans multiple lines; only after a one-line block may it share the line. The continuation keywords are ELSE, ELSE IF, RECOVER, FINALLY, and the DO-loop's WHILE/UNTIL tail. So IF (c) THEN { a() } ELSE { b() } is legal, and a multi-line block's cuddled } ELSE { is a layout error. (Pinned /22 — the document was previously silent on the newline-inside-brackets, brace-closes-statement, and continuation-keyword-layout questions; raised by the GOLDEN clean-room probe, AMB-007/008/009. AMB-009 enforcement in the live parser is pending — ~744 existing cuddled sites migrate when it lands.)
Example.
int32 x = 5 // statement ends at the newline
int32 y = 10
int32 a = 1 int32 b = 2 // ERROR — two statements on one line
int32 c = 3; // ERROR — stray terminator character
Rationale. The newline is a boundary every reader already sees, so making it the terminator removes a redundant character and the whole class of "missing semicolon" errors; rejecting a stray terminator and one-line-two-statements keeps the visual layout an honest map of the statement structure.
(c.i) Rule. The single, narrow exception is the C-style counted-loop header described in I.H, where two semicolons separate the loop's three clauses and the whole header must occupy one line. The semicolon appears in exactly two places in the language: there, and as the constraint-group separator of the multi-parameter template-qualifier preamble (TEMPLATE: GIVEN TYPES V, H; V IS …; H IS …: — I.K, III.6). (found by the GOLDEN clean-room probe, AMB-025.)
Example.
FOR int32 i = 0; i < n; i = i + 1 { // the ONLY place a semicolon is legal
// ...
}
Rationale. The counted-loop header is one conceptual unit whose three clauses are conventionally read together on one line; confining the semicolon to exactly this construct preserves that familiar shape without reintroducing the terminator anywhere a statement actually ends.
(d) Rule. Every identifier a developer introduces begins with a letter, A through Z or a through z, and after the first character may contain letters, digits, and underscores. The rule is the same for a module, class, interface, group, struct, enum, method, field, or variable.
Example.
int32 count = 0
int32 wordCount2 = 0
CLASS HttpConnection { }
int32 2fast = 1 // ERROR — may not begin with a digit
Rationale. One naming rule for every kind of introduced name means a reader learns the shape of an identifier once and applies it everywhere, with no per-category special cases to remember.
(d.i) Rule. An identifier may not begin with an underscore. A leading underscore is legal C++ but is reserved in Envzn for compiler-generated names, and a developer who writes one receives a compile error.
Example.
int32 temp = 0
int32 _temp = 0 // ERROR — leading underscore is reserved
Rationale. Reserving the leading-underscore namespace for the compiler lets generated names coexist with developer names without ever colliding, and rejecting it at the source keeps that boundary visible rather than silent.
(d.ii) Rule. A reserved keyword may not be used as an identifier. The full keyword list is in the Appendix.
Example.
int32 total = 0
int32 CLASS = 0 // ERROR — CLASS is a reserved keyword
Rationale. A keyword must read as a keyword everywhere it appears; letting one double as an identifier would make the same token mean two things depending on position, which is exactly the ambiguity the language avoids.
(d.iii) Rule. The character $ is reserved exclusively for placeholder syntax inside format-string literals; using it anywhere else is a compile error.
Example.
String greeting := ("Hello, $1")->format(name) // $ is legal inside a format literal
int32 $count = 0 // ERROR — $ outside a format literal
Rationale. Giving $ one and only one job — format placeholders (I.F) — means the reader always knows what a $ signals and the tokenizer never has to guess whether it starts a placeholder or a name.
(d.iv) Rule. A locally declared type may not collide with a name the kernel reserves; the reserved set is given in I.N and the Appendix.
Rationale. The kernel's reserved names (I.N) form part of the language's built-in vocabulary; letting a local declaration shadow one would silently redefine a built-in type out from under later code, so the collision is rejected at declaration.
(e) Rule. Numeric literals may be written in three bases. A plain sequence of digits is decimal; a 0x prefix introduces hexadecimal; a 0b prefix introduces binary. Octal is not supported, because the leading-zero convention that usually carries it is a known source of silent error and the language declines to inherit it.
Example.
uint8 mask = 0xFF // hexadecimal
uint8 flags = 0b1011_0100 // binary
int32 million = 1_000_000 // decimal
uint32 color = 0xFF_00_FF
int32 legacy = 0755 // ERROR — octal is not supported
Rationale. Two explicit prefixes and a plain decimal cover every base a systems language needs; octal is refused specifically because the bare leading-zero form silently changes a number's value, and inheriting that would trade a memory-safe, intuitive surface for a legacy convenience.
(e.i) Rule. Underscores may be placed between digits as separators, purely for the reader's benefit — 1_000_000 and 1000000 are the same literal to the compiler — but an underscore may not lead or trail a literal.
Example.
int32 million = 1_000_000 // same literal as 1000000
uint32 color = 0xFF_00_FF // grouping inside a hex literal
int32 bad1 = _1000 // ERROR — underscore may not lead
int32 bad2 = 1000_ // ERROR — underscore may not trail
Rationale. Digit grouping is a pure readability aid the compiler ignores, so it never changes a value; forbidding a leading or trailing underscore keeps the separator unambiguously between digits and stops it from blurring into an identifier or a stray token.
(e.ii) Rule. A literal carries no fixed type of its own; it takes its type from the context that consumes it. The resolution rules, and the range check that rejects a literal too large for its target, belong to the type system and are given in I.D.
Example.
uint8 small = 200 // literal typed as uint8 by its target
int64 large = 200 // the same literal, typed as int64 here
uint8 over = 300 // ERROR — 300 exceeds uint8 range (see I.D)
Rationale. Because a literal has no intrinsic type, the same 200 fits wherever it is legal without a suffix or cast, and the target's type carries the range check. Relocating that work inward to the type system (I.D) keeps the literal surface clean.
(e.iii) Rule. A decimal literal may carry an exponent, in the ordinary scientific form: a mantissa, e or E, an optional sign, and one or more digits. The mantissa's decimal point is optional, so 1e5 is as valid as 1.5e5, and a literal carrying an exponent is a floating-point literal regardless of whether it has a point. The exponent form composes with the type resolution of (e.ii) like any other literal, and a decimal128 target decomposes it exactly from the lexeme rather than through a binary float.
Example.
float64 small = 1e-12 // no decimal point — still a float literal
float64 milli = 2.0e-3
float64 big = 1e5 // 100000.0
decimal128 d = 1e-30 // decomposed exactly, not via binary float
Rationale. Scientific notation is how the quantities a numeric program actually carries are written — tolerances, rates, magnitudes — so requiring a hand-expanded decimal would make the source less readable than the domain it models. Making the exponent alone enough to mark a literal as floating-point means 1e5 never has to be written 1.0e5 to be read correctly.
(f) Rule. The imaginary unit is the constant im (the complex value 0 + 1i). A coefficient written immediately before it forms a complex term: 4im is 4 * im, and 3.14im and 2.0e-3im likewise. A variable coefficient juxtaposes the same way — ip im for a number ip, equivalent to ip * im. i is not a numeric suffix and stays an ordinary identifier.
Example.
complex a = 4im // 4 * im
complex b = 3.14im
complex c = 2.0e-3im
number ip = 5.0
complex d = ip im // variable coefficient — ip * im
int32 i = 0 // 'i' is an ordinary identifier, not a suffix
Rationale. Choosing im over i/j keeps loop-variable names like i free for ordinary use. A Unicode imaginary unit ⅈ was rejected as both identifier-legal under UAX #31 and an i-confusable under UTS #39, so a plain two-letter constant is the safest readable choice.
(f.i) Rule. A complex in the two-part real + imaginary form composes by ordinary arithmetic and so is commutative — 3 + 4im and 4im + 3 both denote (3, 4), im being a genuine constant rather than a syntactic marker.
Example.
complex p = 3 + 4im // denotes (3, 4)
complex q = 4im + 3 // also denotes (3, 4) — commutative
Rationale. Because im is a real constant and not a positional marker, the two-part form is just ordinary addition, so it obeys the ordinary commutative law and the reader is never surprised by an order-dependent literal.
(f.ii) Rule. The canonical printed form parenthesizes the value, (3 + 4im), and a complex value used as a sub-operand of a tighter operator ((3 + 4im)^2) is written parenthesized so its boundary is unambiguous.
Example.
complex z = 3 + 4im
printline(("$1")->format(z)) // canonical printed form: (3 + 4im)
complex w = (3 + 4im)^2 // parenthesized as a sub-operand of ^
Rationale. A two-part complex spans an additive expression, so under a tighter operator like ^ its boundary would otherwise be ambiguous; the parentheses make where the value begins and ends explicit, and the canonical print mirrors that so read and write forms match. The literal form, superseding the earlier i-suffix design and its real-part-first rule; the (a + bim) rendering is specified here but not yet implemented — a complex value does not print in this form today.
(g) Rule. A character literal is a single Unicode code point between single quotes, such as 'a'. Its value is a code point across the full scalar range, not an octet. The escape sequences it accepts are catalogued with the char primitive in I.D.i: the familiar \n, \t, \r, \\, \', \0, the \v and \f controls, and the numeric \xHH, \uHHHH, and \UHHHHHHHH forms that name a code point directly.
Example.
char newline = '\n'
char tab = '\t'
char letter = 'a'
char nul = '\0'
char hexEsc = '\x41' // names a code point directly (I.D.i)
char uEsc = 'é'
char bigEsc = '\U0001F600'
Rationale. A character is a code point, not a byte, so the literal ranges over the full Unicode scalar space. The escape set is the familiar one plus direct numeric forms — conventional, and able to name any scalar unambiguously (full catalogue in I.D.i).
(g.i) Rule. A string literal is a sequence of characters between double quotes. String content is fixed at the literal: "Hello" is a constant the compiler interns.
Example.
String greeting = "Hello" // a constant the compiler interns
Rationale. Fixing string content at the literal lets the compiler intern each one as a shared constant — fast and memory-safe — while the reader sees exactly the text that ends up in the program.
(g.ii) Rule. Inside an ordinary string literal the dollar sign is always a literal dollar sign and never introduces interpolation — Envzn has no interpolating string literal, and positional composition is done instead through the ->format(...) method described in I.F.
Example.
String price = "Costs $5" // $ is a literal dollar sign here
String named := ("Hello, $1")->format(name) // composition via ->format (I.F)
Rationale. Keeping the literal inert — no hidden interpolation — means a $ in quotes always prints as written, and the reader never has to scan a literal for embedded expressions. Positional composition moves to the explicit ->format(...) call (I.F), where the substitutions are visible.
(g.iii) Rule. The escape sequences inside a string literal are the familiar small set: \n for newline, \t for tab, \\ for a backslash, and \" for a double quote.
Example.
String line = "col1\tcol2\n" // tab, then newline
String path = "C:\\Users" // an escaped backslash
String quote = "she said \"hi\"" // an escaped double quote
Rationale. A small, familiar escape set covers the characters a string literal cannot otherwise contain, with no exotic additions to learn — the same readability-first economy applied to comments and numeric bases.
(g.iv) Rule. A multi-line string opens and closes with /", and may span any number of source lines.
Example.
String block = /"
This string
spans several
source lines
"/
Rationale. A dedicated multi-line delimiter lets a literal carry embedded newlines directly, so the source reads as the text it produces instead of a chain of \n-joined fragments.
How Envzn assigns a compile-time type to every value: the primitive types, literal typing, Unicode mode, the EMPTY absence model, the opaque type, the text and binary containers, String, the AS / INTO conversions, and the reserved type surface.
(a) Rule. Envzn is strongly and statically typed: every value has a type fixed at compile time, and the compiler will not produce a program in which a value is used at a type it does not have. Type inference is available only where the type is unambiguous; at method signatures and class fields the developer always writes the type explicitly. One ordering convention holds everywhere — the type precedes the name it qualifies.
Example.
int32 count // type first, then name
String name // never `name String`
METHOD area(float64 radius) RETURNS float64 { ... }
Rationale. Fixing the type at compile time is what lets the compiler reject a mis-typed use before the program runs. The type-first ordering is chosen for readability: a declaration reads left-to-right as "an int32 named count". Keeping the explicit type at the boundaries that matter — signatures and fields — means a reader never has to run inference in their head to know a shape.
The value types built into the language — the integer and floating-point widths, and the small set of truth/octet/character primitives.
(a) Rule. The primitive types are value types built into the language. They are not objects, carry no methods, and always hold a defined value — a primitive is never EMPTY. The signed and unsigned integers come in five widths each, the floating-point types in three.
| Signed | Unsigned | Floating point | Width |
|---|---|---|---|
int8 |
uint8 |
— | 8-bit |
int16 |
uint16 |
float16 |
16-bit |
int32 |
uint32 |
float32 |
32-bit |
int64 / int |
uint64 / uint |
float64 / float |
64-bit |
int128 / i128 |
uint128 / u128 |
— | 128-bit |
Example.
int32 count // defaults to 0
uint8 flags // defaults to 0
float64 ratio // defaults to 0.0
int i := (count INTO int) // `int` is the int32 alias
Rationale. Primitives are the language's floor of speed and predictability: no method-dispatch overhead, no allocation, and no absent state to guard against. That every primitive always holds a defined value is what removes an entire class of null-handling from the code that uses them.
(b) Rule. Every numeric primitive default-initializes to zero. float16 is a half-precision type intended for GPU work. The 128-bit integers int128 and uint128 (aliases i128 and u128) are full V1 primitives. They carry the arithmetic, comparison, and keyword-bitwise operators of I.F.ii like any other integer; their C++ lowering is given in ENVZN_IR_SPEC.md C.ii. The remaining primitives are boolean (TRUE/FALSE, defaults to FALSE, never abbreviated to bool; its operator set is given in (c.iii)); binary (an 8-bit opaque octet — a bit pattern rather than a number, defaulting to zero; its operator set is given in (c.i)); char (a single Unicode code point in U+0000..U+10FFFF, defaulting to the empty character; its operator set is given in (c.ii)); and opaque (a type-erased value primitive, described in I.D.v, which alone among primitives has no default and must be initialized explicitly).
Example.
boolean ready // defaults to FALSE — never `bool`
binary octet // an opaque 8-bit octet, defaults to 0x00
int128 huge = (n INTO int128) // i128 also valid
char c // defaults to the empty character
opaque slot // ERROR — opaque has no default, must be initialized
Rationale. boolean is spelled out rather than abbreviated so truth reads as truth. binary and uint8 are separate types rather than two spellings of one, because an octet and a small number are different things and the compiler is expected to say so: a bit pattern admits no arithmetic, and a number is not addressed a bit at a time. The language previously carried a third spelling, byte, documented as distinct from uint8 "by intent" — an intent nothing enforced, which is precisely why it was retired (I.D.i(c)). opaque is the deliberate exception to the zero-default rule because a type-erased slot has no meaningful zero to fall back to.
(b.i) Rule. binary carries exactly five things: assignment from another octet; the offset operators (+ - &+ &-) against an octet or an integer partner, whose result conforms to whatever slot receives it — int32 i = b + n computes as int32, binary b2 = b + n computes as an octet and is range-checked at runtime, raising the MathError PANIC of I.F.ii(a.iii) on overflow above 0xFF or underflow below 0x00, exactly as every other checked arithmetic does; the keyword-bitwise operators (BAND BOR BXOR BNOT RSHIFT LSHIFT); and the six comparisons, against an octet or any signed or unsigned integer. Nothing else — multiplication, division, remainder or exponentiation (* / ~/ % ^ &*) is E2135. No conversion crosses the octet boundary implicitly, in either direction: INTO/AS is the door both ways — outbound to every integer width and to float32/float64/char8/char16/char32 is INTO except the fallible AS int8; inbound from uint8/char8/int8 is INTO, from a wider integer AS. An octet read where a number is wanted (int32 n = b) is E2139; a number written where an octet is wanted (binary b = u) is E2145. Two shapes are not crossings and stay implicit: an integer masked by a literal bit pattern that fits an octet, landing in an integer slot (uint64 masked = word BAND 0xFF), and a literal beside a typed operand, which adopts that operand's type as any literal does (c == 0x0B beside a char). A binary literal is written in hexadecimal or binary — 0xC3, 0b11000011 — never in decimal (E2136); a bare 0 is exempt, since 0 and 0x0 name the same bit pattern. A literal outside 0x00..0xFF, in an octet slot or beside an octet operand, is E2147. The shift count is a uint8 quantity (E2137); a bare literal count adopts that type as any literal adopts its slot, and the count is policed exactly as I.F.ii(c.iv) polices every integer's: an octet is eight bits wide, so a count outside [0, 8) that the compiler can prove is E2130, and one it cannot prove raises the MathError PANIC at runtime — never a silent 0x00, and never the undefined behaviour C leaves. An octet is never a counter or an index — a FOR start, bound or step, a REPEAT count, or an array subscript typed binary is E2144; iterate with FOR e IN bytes or LOOP e IN bytes WITH INDEX i instead. And an octet has no truth value — IF/WHILE on a bare binary, NOT on one, or a boolean-returning RETURN of one, is E2149.
(b.ii) Rule. char carries exactly three things beyond assignment: the offset operators (+ -) against an integer partner, whose result is the code point's OWN type — a code point moved by an integer is still a code point — and is range-checked at runtime against that width's code-unit range (char8 0x00..0xFF, char16 0x0000..0xFFFF, char32 U+0000..U+10FFFF), raising the MathError PANIC of I.F.ii(a.iii) outside it, exactly as the octet's offset does; the distance c1 - c2 between two code points of the same width, which is an int32 count and may be negative; and the six comparisons, which order code points and are unchanged — against another code point of the same width or an integer, never against a number, decimal128, complex or a float32/float64, none of which is a code point (E2025). It also carries the keyword-bitwise operators (BAND BOR BXOR BNOT RSHIFT LSHIFT), whose result is INTEGER-typed and not a code point, exactly as (e) describes for the mixed-width case — so the result lands in an integer slot with no door, and landing it in a char slot is the crossing that owes one. Nothing else. char + char (two code points do not sum), n - c (subtracting a code point from a number names nothing), multiplication, division, remainder, exponentiation and the wrapping trio (* / ~/ % ^ &* &+ &-), and unary minus, are all E2150. A literal beside a char operand adopts the char type as any literal does, so '0' + d is an offset and c == 0x0B is a comparison. A plain integer landing in a char slot is a crossing like any other and takes INTO/AS: char digit = 0x30 + d is refused (E10096) where char digit = '0' + d says what was meant. The crossing runs both ways: because the offset's result is the code point's own type, a code point landing in an INTEGER slot is equally a crossing — int64 n = c and int64 n = c + p are both E10096, and (c + p) INTO int64 is the door. The one exception is the DISTANCE, which is an int32 from the start and crosses nothing. And a cross-width char conversion is the door, not a warning: widening char8 → char16 → char32 is INTO, narrowing back is the fallible AS of (d.ii), and neither is ever implicit in any position — declaration, assignment, argument or return (E10096). (Amended, Phase 8 family #3 — the FLOAT joined the refused comparison partners. The rule already enumerated the legal set, and a float is not in it; the float matrix measured all six operators admitted against all three code-point widths, lowering to a C++ arithmetic comparison over a code-unit number. Same code, same reason as the three value classes. Brian's ruling R7b.) (Amended, Phase 8 — the char probe matrix found the rule stated in three voices: the assignment arm refused all nine char/char pairs, the declaration arm warned on some and admitted the rest, and char16 → char32 was exempted outright on a scalar-equivalence argument that (d.ii)'s fallible narrowing contradicts. One door, one code.) (that a code point admits no arithmetic at all, was written into the rule and contradicted by every codec in the kernel, which offset and differenced code points thirteen times while the compiler said nothing.)
(b.iii) Rule. boolean carries exactly four things: assignment from another boolean; the logical operators (AND OR XOR); NOT; and equality (== !=) against another boolean. Nothing else — a truth value has no magnitude, no order, and no position. Arithmetic is E2152: + - * / ~/ % with a boolean operand, and unary minus on one (^ on a boolean is E2084 and the wrapping trio &+ &- &* is E2134, the two codes that already refuse a non-numeric operand — one refusal, stated by whichever code owns that operator). The refusal runs both ways, because a boolean is no more the result of arithmetic than an operand of it: an arithmetic value landing in a boolean slot — boolean r = a + b — is the crossing E10096 refuses. Ordering (< <= > >=) is E2118, against anything including another boolean: FALSE is not less than TRUE, and the C++ lowering that says otherwise is an artefact of the backing byte. A boolean is neither counter nor index — an array subscript typed boolean is E2144, and a FOR start, bound or step is E4014. No conversion crosses the boolean boundary implicitly, in either direction, and INTO/AS is not a door either: there is no conversion operator into a boolean or out of one, in any position — declaration, assignment, argument or return (E10096, the same code and the same one door as every other arm, so the crossing is never reported two ways at two positions). The one outbound rendering is b INTO String, which is total and lossless and says which two words were meant. Two shapes are not this rule's business: a boolean[] is an ordinary array of ordinary elements, and IF b / WHILE b is a boolean doing the one job it exists for. On the two axes this rule separates: equality is boolean-to-boolean ONLY — b == n against an integer, float, code point, octet or String is E2025 (a String partner is E8013's sentence, and a class partner E2069's), because ok == 1 reads as a comparison and is the truthiness bug wearing a comparison's clothes — while ordering is refused even when both sides ARE booleans, since the question it asks has no answer at any partner type. (, Phase 8 family #4 — the boolean probe matrix measured 1,586 cases and found boolean + <any integer or float> admitted in all three slots, all six comparisons admitted against every integer width, both floats and all three code-point widths, xs[b] admitted as a subscript, -b admitted as unary minus, boolean x = p admitted for int128/uint128 while every narrower width refused, and one E9039 — the emit catch-all — on boolean + String. The cause was one fact: boolean is not in the typer's numeric set, so _binop_type answered UNKNOWN for boolean + int32, and an UNKNOWN expression type is precisely what every slot arm returns early on. The refusal is therefore on the OPERATOR, where the type was never formed.)
(b.iv) Rule. The three value-class-backed numerics — number, complex, decimal128 — carry exactly the arithmetic their backing class defines, and nothing beyond it. number carries + - * / ~/; complex and decimal128 carry + - * /. None of the three carries %, and neither complex nor decimal128 carries ~/: an operator the type does not define is E2019, not a result to be conformed anywhere. Where an operator IS defined, the value class is the domain the expression is computed in, so the result is that value class and a mixed integer or float operand widens into it — f + n is a number, f * c is a complex, d + i is a decimal128. A decimal128 operand additionally keeps its counterpart clean on every arithmetic operator and on all six comparisons: the counterpart must be another decimal128 or an integer of 64 bits or fewer, and a float, number, complex or String partner is E2121 (I.F.ii(a.ii)'s division rule is about width; this is about domain).
A crossing into or out of a value class is E10096, at every position. Declaration, assignment, argument, return, an array element and an array-literal element are one rule with one code, and the declaration is not the exception it used to be. So a fixed-width real lands in a complex slot as x INTO complex (total for int8…int64, uint8…uint32, float32, float64), and an int128 or uint128 reaches a number only through the fallible w AS number, which is also its route into complex (uint64 widens into number first). A real operand is not a slot crossing: z + 1 still computes in the complex domain (g.i). Narrowing out of any of the three is explicit and runtime-fallible, as (g) already says. Conversions INTO decimal128 are compiler-assembled rather than registry-declared, and INTO is the right keyword for all of them — the inbound decimal set is the lossless-fallible cell of I.D.viii: exact when representable, FAILURE otherwise, never a silent round. What the assembly does still decides the shape: a source of 64 bits or fewer widens exactly and returns a plain value, while a float, number, complex, String or ByteBuffer source is fallible and returns the pipe-XOR (T value | STATUS status) of I.M.i, so it is consumed as the condition of an IF/WHILE and never as a plain value (E6064, the same code and the same walk a fallible call answers to — a conversion is the same shape). Only ~5.7% of binary64 values land exactly in decimal128's 34 significant digits, which is why float → decimal128 is fallible however wide the destination looks, and why the implicit-widening lattice has no edge for it.
A float is neither counter nor index. An array subscript typed float32/float64 is E2144 — the same sentence the octet, the code point and the boolean get, for the same reason: an index asks which position, and only a whole number names one. xs[2.5] reads element 2 in C++ and says nothing about it. A FOR start, bound or step is E4014, whose rule is that a loop counts and its bounds are therefore whole numbers. The three value classes answer the same way: a subscript typed number, complex or decimal128 is E2144, and none of the three has a truth value — NOT on one is E2149, as it is on a code point. (admitted by the analyzer and refused by clang.) NOT belongs to the boolean alone. It inverts a truth value, and no other primitive has one: NOT on an integer of any width, a float, a code point, an octet, a number, a complex or a decimal128 is E2149. The bit complement is BNOT (I.F.ii(c.iii)); a test against zero is written n == 0. (a silent test against zero that clang accepts, so the matrix scored them admit and only a ruling could close them.)
And operator legality is answered before destination conformance, everywhere. An operator that is not defined on its operands has no result, and a result that does not exist cannot conform to a slot — so the operand verdict is the one the developer is given. int32 r = f BAND i is E2031 (a float has no bitwise operators), never E2007 (a narrowing conversion), because no conversion the reader could add would make BAND exist on a float. This holds at every position that carries a destination.
(, Phase 8 family #3 — the float probe matrix measured 3,812 cases and found 130 BROKEN rows, every one of them a position the conversion check does not police. 106 were a single wrong answer in the typer: number and complex are not in its numeric set, so float32 + number typed as UNKNOWN, and an UNKNOWN expression type is exactly what every slot-conformance arm returns early on — so the crossing was admitted into all four slots and refused by clang. The same shape as family #4's 71 boolean rows, one level up. The last twelve were the declaration arm, which returned before judging any of the three destinations while the assignment arm refused all three — so complex c = f compiled and c = f did not, one crossing with two answers decided by which line it was written on. Brian's rulings R1, R4, R5 and R7.)
Example.
binary b = 0xC3 // hex — 195 would say how MUCH, not WHICH BITS
binary zero = 0 // 0 == 0x0 — the one decimal exempt from E2136
binary bad = 195 // E2136 — decimal in an octet slot
binary huge = 0x1FF // E2147 — outside 0x00..0xFF
binary lo = b BAND 0x0F // bitwise: yes
uint64 masked = word BAND 0xFF // not a crossing — a number masked by a literal stays a number
int32 i = b + n // offset conforms to the int32 slot
binary next = b + n // offset conforms to the octet slot — PANICs above 0xFF
binary bad2 = b * 0x02 // E2135 — an octet is not a magnitude
binary shift = b RSHIFT 4 // the literal count adopts uint8
int32 n2 = b // E2139 — an octet is not a number
binary b2 = u // E2145 — a number is not an octet
int8 n3 = (b AS int8) // the door — AS/INTO, never implicit
FOR i2 = 0 TO 10 STEP b { print(i2) } // E2144 — an octet is not a counter
IF b THEN { ... } // E2149 — an octet has no truth value
Rationale. The line is not "arithmetic is numeric so an octet has none" — it is narrower and more useful than that. Offsetting an octet moves within the 256 values it can hold, which is what every codec does: c - 0x30 turns the ASCII digit '7' into the value 7, and the result conforms to whatever slot it lands in because the meaning of the arithmetic doesn't change with the receiver — only whether it's checked as a bit pattern or as a number. Multiplying, dividing, taking a remainder or raising to a power all assume the value counts something, and a bit pattern counts nothing. Closing the implicit crossing in both directions is the same distinction carried through to assignment: int32 n = b used to read a bit pattern as a number for free, and binary b = u used to read a number as a bit pattern for free, and both hid the same reinterpretation that INTO/AS now has to say out loud. The two exempted shapes — a literal-masked integer, a literal beside a typed operand — are not octets at all; nothing in either was ever a stored bit pattern, so nothing is crossing. The literal rule is the same distinction at the surface: 0xC3 says which bits, 195 says how much, and only one of those is a thing an octet means. The shift count is a uint8 because you shift by a quantity, not by a bit pattern — the one place in an octet expression where a number is what is meant. And an octet is not a counter or a truth value for the same root reason it is not a magnitude: counting and testing both ask what a value is worth, and a bit pattern isn't worth anything.
(b.v) Rule. String is deliberately absent from the primitive list — it is a built-in value type with its own assignment and absence rules, not a primitive, and is the subject of I.D.vii.
Rationale. Listing String as a primitive would imply it shares the primitive contract: no methods, never EMPTY, bit-copied. But String carries methods, follows class-type assignment rules, and has its own always-present exception, so it belongs to its own category.
(c) Rule. A char is a Unicode code point and nothing narrower: it spans the full scalar range U+0000..U+10FFFF and is deliberately not a C char. The octet primitive is binary; char is the text primitive and uint8 the numeric one, and the language keeps the three apart on purpose — a char is never an octet, and neither is a number.
Example.
char letter = 'a' // valid code point — a valid char
char emoji = '\U0001F600' // one code point, not four bytes
binary b = 0xC3 // an octet — NOT a char, and NOT a number
Rationale. A C char is an 8-bit storage unit; an Envzn char is a decoded code point that does not fit in eight bits. Conflating the two is the classic Unicode bug — treating a byte as a character — so the language gives text (char), raw octets (binary), and small numbers (uint8) separate primitives that never implicitly interconvert.
(c.i) Rule. A character literal is written between single quotes. It accepts the escapes \n, \t, \r, \\, \', \0, \v (vertical tab), and \f (form feed), plus three numeric code-point escapes: \xHH (two hex digits), \uHHHH (four), and \UHHHHHHHH (eight).
Example.
char nl = '\n'
char quote = '\''
char tab = '\t'
char hexE = '\x41' // 'A'
char bmp = 'é' // 'é'
char astral = '\U0001F600' // 😀
char space = ' ' // ordinary char literal
Rationale. The three numeric escapes name a code point directly across the whole scalar range. Any character, including ones a keyboard cannot type, is expressible as an ordinary char literal without leaving the text primitive.
(d) Rule. char is the canonical name in a family of three widths: char8 is a single 8-bit UTF-8 code unit (char8 ≡ uint8 at storage) and char16 a single 16-bit UTF-16 code unit (char16 ≡ uint16). char32 (≡ uint32) is the code-point width, of which char is the alias. The three name three distinct types; a value of one width is never implicitly a value of another. Crossing widths is a conversion, always explicit through the AS/INTO operators of I.D.viii (hosted on CharWidthConverter).
Example.
char8 unit = 0xC3 // lead byte of a 2-byte UTF-8 sequence — NOT U+00C3
char32 cp = (unit INTO char32) // explicit widen — required across widths
char32 same = someChar16 // ERROR (E10096) — implicit cross-char conversion
Rationale. A code unit is not a code point: a char8 of 0xC3 is the lead byte of a two-byte sequence, not the scalar U+00C3. Because encoded-unit work and decoded-code-point work are genuinely different, the widths are kept as distinct types so the compiler forces an explicit conversion at every boundary rather than silently reinterpreting bytes as scalars.
(d.i) Rule. An implicit cross-char-type conversion — one width written where another is expected, with no AS/INTO — is a compile error, E10096, on every char-type pair without exception, in every position (declaration, assignment, argument, return). The refusal is suppressed inside an OPERATOR AS/INTO body whose declared target is the destination width, where the conversion is being defined. (Amended, Phase 8 — this was the warning W10095, with char16 → char32 exempt "because a non-surrogate UTF-16 unit is the same UTF-32 scalar". The exemption was unsound on its own terms: the operand may be a surrogate, which is exactly the case UTFCodec exists to handle, and (d.ii) already calls the reverse direction fallible. W10095 is retired; E10096 is the one code.)
Example.
char16 u = 0x00E9
char32 c = u // ERROR (E10096) — no pair is exempt; write (u INTO char32)
char8 b = 0x41
char32 d = b // ERROR (E10096) — implicit char8 → char32
Rationale. A warning that the build ignores is a rule the code does not have, and the probe matrix found three different answers to one question depending on which slot the value landed in. The formerly exempt pair was the weakest of them: a char16 is a UTF-16 code unit, and half of them — the surrogates 0xD800..0xDFFF — are not UTF-32 scalars at all, so "provably lossless" was true of the values a decoder has already handled and false of the ones it has not. Suppressing the refusal inside an OPERATOR AS/INTO body is still necessary because that body is precisely where the conversion is legitimately being authored.
(d.ii) Rule. char8 INTO char32 widens by bit-equivalence and never fails; char32 AS char8 narrows and is pipe-XOR, succeeding into one char8 only on single-byte ASCII (a code point may need one to four UTF-8 bytes). The bulk encode/decode between widths lives in the kernel's UTFCodec, which holds the kernel's one UTF-8 encoder (appendUTF8 for a window of code points, appendScalarUTF8 for one); every other encoder in the kernel and its modules routes through it, and a String's code points reach it through the TextEncoding namespace, since UTFCodec orders before String and cannot name it. Bulk UTF-8 decode (decodeUTF8) and the encode of a window into an empty buffer (fillUTF8) are carried out by the vendored simdutf library, and a decoded code point is still held to the Tier-1 text rule before it may become a String.
Example.
char32 wide = (asciiUnit INTO char32) // total — never fails
IF (wide AS char8) THEN { char8 narrow = $RETURNED } // pipe-XOR — succeeds only on ASCII
ELSE { printline($!) } // non-ASCII code point cannot collapse to one char8
Rationale. Widening is total because every 8-bit unit is a valid 32-bit scalar. Narrowing is fallible because most code points do not fit in a single UTF-8 byte, so the collapse can genuinely fail and must be checked rather than truncated. Bulk multi-byte encode/decode is the job of UTFCodec, not of the single-value width operators.
(e) Rule. Two char values of ANY two widths may appear in the same keyword-bitwise expression — BAND BOR BXOR BNOT LSHIFT RSHIFT — where each operand contributes its storage bits to an integer-typed result. Mixing widths in a bitwise expression is not a cross-char conversion — it is integer arithmetic over bits, and the result is a number, so landing it back in a char slot is a crossing that takes INTO/AS like any other. (Phase 8 — the rule named four of the six operators and one width pair, the analyzer always admitted all six across all three widths, so the text was the narrower of the two.)
Example.
int32 bits = (cp LSHIFT 6) BOR (contUnit BAND 0x3F) // UTF-8 decode step — int32, no per-step conversion
cp = ((cp LSHIFT 6) BOR (contUnit BAND 0x3F)) INTO char32 // ONE door, where the bits land back in a code point
char32 wide = (c INTO char32) // treating one char8 AS one char32 is still explicit
Rationale. Making bit operations mix widths freely is what lets a UTF-8 decoder be written without a conversion call at every shift-and-or step — the one door it owes is at the end, where the accumulated bits land back in a code point, not inside the loop. It is not a hole in the width discipline: the bitwise expression yields an integer over bits, whereas reinterpreting one isolated char8 as one char32 value remains the explicit (c INTO char32) conversion.
(f) Rule. Envzn provides no companion or wrapper classes for primitives — no Integer, no Float64, no boxed Boolean. When a primitive must become text or change width, that work is done by the AS/INTO conversion operators of I.D.viii, not by methods on a wrapper.
Example.
String label := (42 INTO String) // conversion operator, not `42->toString()`
float64 d = (myInt32 INTO float64) // widen via operator, no wrapper class
// Integer big := ... // ERROR — no boxed primitive types exist
Rationale. Wrapper classes exist in other languages to give primitives a method surface and a nullable form; Envzn needs neither — conversions are operators and absence never applies to a primitive — so the boxed forms would be pure overhead and are simply absent.
(g) Rule. Two further numeric primitives are designed for V1: number and complex. Each is a special value-type like opaque — a primitive backed by a compiler-known special class (Number / Complex) that a developer never instantiates directly, value-copied like any primitive. The backing class is never named: Number, Complex, Decimal128 and Opaque may not appear in any type position — a declaration, a signature, a type argument, CREATE, IDENTITY — outside that class's own PRIMITIVE body, the kernel included (E2173). Everything a developer needs is reached through the primitive's own name: its methods and fields, and IDENTITY(complex), which reflects the backing class's data fields and methods while naming complex. A number holds an integer (int64) or a float (float64) — exactly one at a time, self-aware of which. It is the opt-in choice when a value is genuinely int-or-float, since a number parameter accepts either. It is never the default; a developer who means int32 writes int32. Widening into a number is implicit; narrowing out requires an explicit AS/INTO and is runtime-fallible (the held subtype is a runtime fact).
Example.
number n = 5 // holds int64 — widened in implicitly
number m = 2.0 // holds float64
IF (n AS int32) THEN { int32 i = $RETURNED } // narrow out — explicit + fallible
ELSE { printline($!) }
Rationale. number exists for the genuine int-or-float case that a fixed width cannot express. Making it the default would silently cost the predictability of a concrete width, so widening in is free while narrowing out is checked — matching where the loss of information actually is.
(g.i) Rule. A complex is a pair of numbers, written real + coeff im (commutative, I.C), so a single type spans both Gaussian-integer (3 + 3im) and float (3.0 + 4.0im) complexes. It exposes .real, .imaginary (each a number), .conjugate (a complex), and .magnitude / .phase (each a float-subtype number). The four arithmetic operators work on each, with a real operand widening implicitly to a complex (value, 0) (z + 1, f * c); a real landing in a complex slot is a crossing and writes x INTO complex (b.iv).
Example.
complex gauss = (3 + 3im) // Gaussian integer
complex z = (3.0 + 4.0im) // float complex
number re = z.real // 3.0
number mag = z.magnitude // 5.0 — float-subtype number
complex sum = z + 1 // real 1 widens to (1, 0)
Rationale. One complex type spanning both integer and float components (rather than separate fixed primitives) follows from complex being a pair of numbers, each self-aware of its subtype. Widening a real to (value, 0) lets ordinary arithmetic mix reals and complexes without a conversion call.
(g.ii) Rule. Equality on complex is defined but the ordering operators are not — complex numbers have no canonical order, so writing < between two complexes is a compile error. A complex extracts back to a real only through complex INTO <real> (checked, succeeding iff the imaginary part is zero); complex AS <real> is a compile error, the real-part-vs-magnitude choice being ambiguous — use the accessors.
Example.
IF (z INTO float64) THEN { float64 r = $RETURNED } // succeeds iff z.imaginary == 0
// IF z1 < z2 THEN { ... } // ERROR — complex has no canonical order
// float64 r = (z AS float64) // ERROR — real-part vs magnitude ambiguous
float64 justReal = z.real // use an accessor when you mean a specific part
Rationale. Ordering is undefined because there is no order on the complex plane consistent with arithmetic; AS-to-real is rejected because "the real part" and "the magnitude" are both plausible lossy readings and the language refuses to guess — the accessors make the intended one explicit.
(g.iii) Rule. A number reports its held subtype through n->kind(), which returns a NumberKind { INTEGER, FLOAT, UNSIGNED } enum. That enum is the typed, MATCH-able V1 introspection surface — the stand-in for the V2 runtime WHEN n IS int64 narrowing.
Example.
MATCH n->kind() {
WHEN NumberKind.INTEGER: { print("int") }
WHEN NumberKind.FLOAT: { print("float") }
WHEN NumberKind.UNSIGNED: { print("large positive int") }
}
Rationale. Until V1 gains runtime type narrowing, kind() gives a MATCH-able, statically-typed way to branch on which arm a number currently holds. It is the same information a future WHEN n IS int64 would carry, exposed as an enum today.
(g.iv) Rule. The third NumberKind arm, UNSIGNED, is a purely value-classified overflow extension. It is never written at the surface, and is reached only when an integer value overflows the int64 arm into (int64_max, uint64_max] — giving a number full [int64_min, uint64_max] integer fidelity. Because of it, integer arithmetic on a number promotes rather than wraps — a sum that overflows int64 classifies up the ladder INTEGER → UNSIGNED → FLOAT. The arms hold disjoint value ranges, so an INTEGER never compares equal to an UNSIGNED.
Example.
number big = int64Max // INTEGER arm
number sum = big + big // promotes to UNSIGNED (or FLOAT) — does NOT wrap
// bare int* scalars PANIC on overflow (I.F.ii(a.iii)) — this promote-not-wrap policy is number-only
Rationale. Promoting up the ladder preserves the mathematical value that a MathError PANIC would otherwise stop the computation over, giving number full integer fidelity across the whole signed-and-unsigned 64-bit range. This is one of the two documented exceptions to the overflow-PANIC rule of I.F.ii(a.iii) (the other is decimal128, which rounds); disjoint arm ranges keep equality honest across the ladder.
(g.v) Rule. A number is Equatable and ordered; a complex is Equatable only. == compares by mathematical value across subtypes on both (so number(3) == number(3.0) is TRUE, and complex equality is component-wise). A number additionally carries the four ordering operators < > <= >=, which order by mathematical value across the INTEGER/UNSIGNED/FLOAT arms — the same value-based rule == follows. A complex carries no ordering: ℂ has no canonical order, and writing one is a compile error. Neither type is Hashable, so neither is a valid Dictionary/Set key, though both remain fine as Dictionary values and ordinary collection elements.
Example.
IF number(3) == number(3.0) THEN { ... } // TRUE — == is value equality (Equatable)
IF number(2) < number(2.5) THEN { ... } // TRUE — ordering is by mathematical value
number n = 5
IF n > 4 THEN { ... } // OK — the 4 widens into a number (g)
Dictionary[String, number, DefaultHasher[String]] scores // OK — number as a VALUE
// Dictionary[number, String, DefaultHasher[number]] bad // ERROR — number is not Hashable, not a key
// IF (3 + 4im) < (1 + 2im) THEN { } // ERROR — complex has no ordering
Rationale. The two exclusions this rule once bundled have different force, and were split. Hashing genuinely cannot work: which arm a number holds is a runtime fact, so there is no statically-stable key — that keeps both types out of Dictionary/Set keys. Ordering was excluded on the grounds that NaN compares false to everything, but the language does not apply that argument to float64, which carries exactly the same NaN and is ordered anyway (interfaces.ev: built-in Comparable behaviour for float32/float64). Holding number to a stricter standard than the type it can hold made number unusable for the ordinary comparisons it exists to serve. A number is therefore ordered, and NaN behaves as it does on float64 — every comparison against it is FALSE. complex keeps its exclusion for the reason that was always specific to it: ℂ has no canonical order at all. Neither change affects use as a stored value, where no such property is needed.
(g.vi) Rule. Being value-class-backed, a number/complex legitimately carries the methods and operators its backing class defines — the sanctioned exception to "primitives have no methods." The companion approximate-equality operators ≈/≉ are described in I.F.ii.c. A number renders tag-aware: an integer subtype prints as a decimal integer (5), a float subtype keeps the float distinction visible (2.0). A format-spec radix letter (x/X/o/b) is honoured only on an integer-subtype value, and silently ignored on a float.
Example.
number i = 5 // renders "5"
number f = 2.0 // renders "2.0" — float distinction visible
String hex := ("$1:x")->format(i) // radix honoured on integer subtype
String noHex := ("$1:x")->format(f) // radix silently ignored on a float subtype
IF a ≈ b THEN { ... } // approximate equality — I.F.ii.c
Rationale. number/complex are the sanctioned method-carrying primitives because they are backed by real value classes; the method surface is where their arithmetic and formatting live. Tag-aware rendering preserves the one bit of information a bare width would lose — whether the held value is an integer or a float — so 2.0 never silently prints as 2.
(g.vii) Rule. number is shipped in V1. It is a value-class over the kernel UNION storage construct, carrying arithmetic, ==, ≈, kind(), the AS/INTO conversions, and tag-aware formatting. The UNSIGNED overflow arm adds a third NumStore arm, promote-not-wrap integer arithmetic computed in int128, a total AS uint64, and disjoint-range comparison. complex is shipped in V1 as a value-class pair of numbers. It provides the im constant with commutative literals, the four arithmetic operators and unary −, component-wise ==, and the .real/.imaginary/.conjugate/.magnitude/.phase accessors. It converts through complex INTO String (canonical (a + bim)) and the fallible complex INTO float64. Math.squareRoot is redefined to RETURNS complex, so complex c = Math.squareRoot(-4.0) is (0 + 2im).
Example.
complex c = Math.squareRoot(-4.0) // (0 + 2im) — squareRoot RETURNS complex
String s := (c INTO String) // canonical "(0 + 2im)"
Rationale. Recording the ship dates, backing files, and the superseded fixed-primitive design keeps the spec aligned with what actually exists in the kernel. Redefining Math.squareRoot to return complex is what lets squareRoot(-4.0) yield a real answer rather than fail on a negative input.
(h) Rule. The UNION construct is a kernel-internal raw-storage primitive: a named block of typed fields that, unlike a STRUCT, holds exactly one at a time and carries no discriminant of its own. It lowers directly to a C++ union. It exists to give a value-class a tight tagged-union layout without trading the memory-safety floor. A UNION is legal only inside the ENVZN kernel — in ordinary code it is a compile error, E6062 — declares no INIT and no methods, and every access goes through the enclosing value-class's tag. UNION is a reserved keyword. An arm is one of three kinds (for opaque and FormatArgument): a value — a scalar primitive, an enum, UNSAFE.HANDLE, number/complex/decimal128, or a STRUCT, UNION or VALUE CLASS whose fields are themselves values; an owning class or interface handle, which the enclosing value class drops by its tag; or a REFERENCE, which owns nothing and is legal only in a union with no owning arm. An array, a SHARED or WEAK arm, a SHARED CLASS, and a struct or value class with a heap field are refused (E6110). A union with an owning arm moves by its bytes and is never copied; one without is copied by its bytes. The union never switches arms under a live owner: an owning arm is written only into a value the same body just built (the first write on any path, outside a loop), or refilled after the same arm was moved out on that path, and the write constructs in place; = EMPTY releases the live arm. Any other write is E6111. Status: shipped in V1 (2026-06; backs number).
Example.
// inside the ENVZN kernel only:
// the Number value-class is { NumberKind tag; UNION { int64 i; float64 f } }
UNION NumStore { int64 i float64 f } // one arm live at a time; no discriminant of its own
// UNION Foo { ... } // ERROR (E6062) — UNION outside the kernel
Rationale. A UNION gives Number an eight-byte-plus-tag layout instead of a fat all-fields class, but the one-arm-live read is unsafe. So the language encapsulates it entirely: kernel-only, no methods, every read routed through the enclosing tag. It is the "relocate the cost inward" tiebreak of I.A made concrete — the unsafe machinery lives behind a safe value-class surface and is never exposed to a general developer.
How a numeric literal takes its type from the context that expects it, and when a range check fires.
(a) Rule. A numeric literal carries a polymorphic marker rather than a fixed type until the type-checker resolves it against its context's expected type. A context-free integer literal defaults to int64 — the language's default integer — and a context-free decimal literal to float64, but any context supplying an expected type gives the literal that type instead, provided it fits. The fit is checked after any constant folding of literal arithmetic, so an out-of-range folded result is a compile error rather than a runtime overflow. A hexadecimal or binary literal that does not fit its declared target is rejected the same way. (Corrected : this clause read int32 until now. The default was changed to int64 several sessions ago and the code has said so since — analyze/expr_typing._literal_default_type returns the int64 default for a decimal spelling — so the divergence was in this document, not in the compiler. A decimal spelling says nothing about width, so it takes the language's default integer type rather than a width inferred from magnitude; typing 1 by magnitude would make count - 1 a sign-mix in every loop in the repo.) A floating-point literal must land on a finite value of its type. A folded value that is non-finite — an overflow such as 1e400, or a literal division like 1.0 / 0.0 — is a compile error, because NaN and Infinity are computation results and are never developer-authorable. A non-zero literal that underflows to exactly zero (1e-400) is rejected as a lost value, while a representable subnormal (1e-320) is accepted. (decimal128 folds its literal exactly from the lexeme, so its fit is checked as coefficient-and-exponent, not through binary float.)
Example.
100 // context-free integer literal → int32
3.14 // context-free decimal literal → float64
int8 small = 100 // literal takes int8 — it fits
int8 bad = 100 + 28 // ERROR — folds to 128, out of int8 range
uint8 mask = 0xFF // fits — 255
uint8 tooBig = 0x1FF // ERROR — hex literal exceeds uint8
Rationale. Letting a literal adopt its context's type is what makes int8 small := 100 work without an explicit conversion. Checking the fit after constant folding means 100 + 28 is caught at compile time exactly as the bare literal 128 would be, so the overflow can never survive to runtime.
The V3 per-module Unicode modes, what ->length() counts under each, and the link-time mode-match rule — designed, not implemented.
(a) Rule. The per-module Unicode-mode system described in this Part is V3, designed and not implemented. Today every module compiles under one behaviour: a String stores UTF-32 code points and ->length() is the code-point count. The rules below fix the shape that system will take. Text in Envzn is Unicode, and every module declares in its manifest which of three Unicode modes it compiles under. The declaration is optional; a module that says nothing compiles as UTF16. The mode is recorded in the compiled binary, and the compiler refuses to link two modules built under different modes. A mismatch is a build-time error, not a latent inconsistency.
| Mode | Internal storage | ->length() counts |
Suited to |
|---|---|---|---|
UTF8 |
UTF-8 bytes | bytes | servers, networking, file I/O |
UTF16 |
UTF-16 code units | UTF-16 code units | general and multilingual application work |
GRAPHEME |
UTF-32 with a cluster map | visible characters | V3 — reserved. A compile error if declared before then. |
Example.
// module manifest (<name>.json):
// "unicodeMode": "UTF8" // servers, networking, file I/O
// (omit the field entirely → compiles as UTF16)
// "unicodeMode": "GRAPHEME" // ERROR before V3 — reserved
Rationale. Two modules disagreeing on what ->length() means would be a silent, corrupting inconsistency. Baking the mode into the binary and refusing to link across a mismatch turns it into a loud build-time failure.
(b) Rule. The mode affects how text is stored and what ->length() counts. It does not affect what a char is: a char is always a Unicode code point regardless of mode. Because ->length()'s meaning will shift with the mode, a string also exposes ->size(), the UTF-8 byte count, so code needing a specific count independent of the module's mode can ask for it by name. A grapheme count arrives with the modes themselves in V3.
Example.
int32 modeCount = s.length // meaning depends on the module's mode
int32 bytes = s.byteLength // always the UTF-8 byte count
int32 points = s.codePointLength // always the code-point count
// int32 g = s.graphemeLength // reserved for V3
char first = ... // a char is a code point under every mode
Rationale. Making ->length() mode-dependent serves the common case: each mode's most natural count. A by-name count method gives any code a stable, mode-independent number when it needs one, so you never have to know the module's mode to get the byte count.
The single absence model: no optional type, no null — a class-typed binding either holds an instance or is EMPTY, and presence must be proven before use.
(a) Rule. Envzn has no optional type and no ? type-suffix. Every field, variable, parameter, and return is declared with its bare type. Writing a ? anywhere a type may appear — as a declaration suffix, in a RETURNS clause, inside a type argument — is a compile error, rejected by the parser.
Example.
String name // bare type — correct
METHOD find() RETURNS Circle { ... } // bare return type
// String? maybe // ERROR — no `?` type-suffix
// METHOD find() RETURNS Circle? { ... } // ERROR — parser rejects `?`
Rationale. This is the single most important type-system rule to absorb, because it differs sharply from the languages Envzn most resembles. There is one absence model, not two: absence is a state, not a type constructor, so there is no ? to write.
(b) Rule. Absence is a state a class-typed binding may occupy, not a wrapper on a type. A binding of a class type either holds an instance or is EMPTY, and EMPTY is the only absence value — there is no null. A binding of a primitive type can never be EMPTY: a primitive always holds a defined value, so absence does not arise for it.
Example.
CLASS Person {
String firstName // holds a String, never EMPTY
String middleName // holds a String, never EMPTY
String lastName
Circle badge // owns a Circle, or is EMPTY
}
Rationale. The distinction is exactly the two columns of the type system — class-typed values can be absent, primitive values cannot — and the language attaches no syntax to it because the type already carries the information: knowing a binding's type is knowing whether it can be EMPTY.
(c) Rule. EMPTY is a reserved literal, valid only as the value of a class-typed binding. It is a compile error everywhere else: assigned to a primitive, a STATUS, an enum, or a struct, it names a state those types do not have. A class-typed field left unassigned by every path through INIT is EMPTY; a class-typed field is never silently uninitialized.
Example.
Circle badge := EMPTY // valid — class-typed binding
IF badge IS VALID THEN { ... } ELSE { ... } // valid — presence test
// int32 n = EMPTY // ERROR — a primitive has no absent state
// STATUS s = EMPTY // ERROR — STATUS has no EMPTY state
Rationale. Restricting EMPTY to the one abstraction that has an absent state keeps the model coherent. Absence means exactly one thing — a class-typed binding holding no instance — and the compiler catches any attempt to apply it to a primitive, STATUS, enum, or struct, where "absent" is meaningless.
(d) Rule. Using a class-typed value requires that its presence be proven. The null-safety analyzer will not finish a compilation in which a class-typed value is dereferenced where it cannot prove the value is not EMPTY. Presence is established by the IS VALID / IS NOT VALID test, which branches on presence. Inside the truthy branch of IS VALID, or after an early return guarded by IS NOT VALID, the analyzer narrows the value to non-EMPTY and permits direct field and method access. Envzn has no coalescing operator.
Example.
IF person.middleName IS VALID THEN {
print(person.middleName) // present — narrowed, direct access
}
ELSE {
print("no middle name") // absent
}
IF candidate IS NOT VALID {
RETURN (EMPTY)
}
candidate->use() // analyzer carries the narrowing past the early return
Rationale. Each fits a different need: MATCH when both states need handling, IS VALID when a branch or guarded early return suffices. The analyzer refusing to finish otherwise is what makes "dereference of an absent value" impossible to ship. The exhaustive-MATCH requirement exists because a missing arm on a statically two-state value can only be an oversight.
(e) Rule. The presence vocabulary built on IS VALID and the failure vocabulary built on STATUS are kept strictly apart. A possibly-EMPTY class value is tested with IS VALID / IS NOT VALID; a STATUS value is tested with IS SUCCESS, IS FAILURE, and IS PARTIAL_SUCCESS. The two never alias, and the compiler rejects a test applied to the wrong abstraction. The full table of IS VALID subjects is in I.I.
Example.
IF badge IS VALID THEN { badge->draw() } // presence test — class value
IF s IS FAILURE THEN { printline($!) } // failure test — STATUS value
// IF badge IS SUCCESS THEN { ... } // ERROR — presence tested with a failure verb
// IF s IS VALID THEN { ... } // ERROR — STATUS tested with a presence verb
Rationale. Absence ("is there a value?") and failure ("did an operation succeed?") are different questions, and letting their verbs alias would blur the two into a single ambiguous truthiness. Keeping the vocabularies disjoint — and rejecting a cross-applied test — makes every check say exactly which question it is asking.
(f) Rule. Absence and ownership are independent properties. Whether a class-typed binding may be EMPTY says nothing about whether it owns what it holds; ownership is decided by the REFERENCE keyword and nothing else. A plain Type field is owning and may be EMPTY or hold its target. A REFERENCE Type field is non-owning and is never EMPTY: the borrow checker proves it live, so it must be bound with =@ in INIT (E1121), and that always-valid guarantee is exactly what lets it lower to a raw pointer with no runtime check. A back-pointer must therefore be non-owning — a REFERENCE cannot keep memory alive — to avoid an ownership cycle, and where such a back-pointer may legitimately have nothing to point at, as the root of a tree or the head of a list does, the rung that is non-owning and nullable is WEAK REFERENCE, whose deref yields (REFERENCE T | EMPTY) and narrows through IS VALID. WEAK REFERENCE is reserved, pending implementation: until it lands there is no way to spell a nullable non-owning edge at all, which is why kernel/src/LinkedList.ev carries no per-node prev. The full ownership model is I.I. (Corrected : this clause read that a REFERENCE field “may be EMPTY” — a statement E1121 has always rejected, and one that made the nullable non-owning edge look spellable when it is not. The example below was itself unbuildable for a root Node on exactly that point.)
Example.
CLASS Node {
Node next // owning — may be EMPTY or hold the next Node
REFERENCE Node parent // non-owning back-pointer — bound in INIT, never EMPTY
}
// A ROOT node, whose parent is genuinely absent, needs `WEAK REFERENCE Node parent`
// and cannot be spelled in V1 — see the rule above.
Rationale. Conflating absence with ownership is a common first mistake, so the spec separates them explicitly. Because a plain field owns what it holds, an unguarded back-pointer would form an ownership cycle. The language's answer is not to break the cycle silently but to make the developer mark the back-pointer REFERENCE, encoding the non-owning intent in the type. Holding REFERENCE to always-valid is what keeps that mark free at runtime, and the price of it is that nullability has to be asked for separately rather than assumed — which is the whole reason WEAK REFERENCE exists as a third rung rather than as a property a REFERENCE could simply have.
The type-erased primitive for heterogeneous storage: how it wraps, unwraps destructively, and clones by the kind it carries.
(a) Rule. opaque is a primitive value type carrying a typed value behind a runtime type tag. It exists for the heterogeneous-storage cases the static type system cannot otherwise express; a dictionary whose values differ in type per key is the canonical example. It is the mechanism by which a single collection slot can hold a value whose type is unknown until recovered.
Example.
opaque box := opaque[Circle]->wrap(c) // one slot holding a value of statically-unknown type
Rationale. A homogeneous container cannot hold values of differing types (bounded genericity, I.A). The language therefore provides one type-erased primitive for the genuine heterogeneous case, rather than weakening the static type system everywhere.
(b) Rule. opaque is not a parametric type. The bracket form opaque[T] is call-site syntax for the two static operations only. A field or local declared as opaque[Esquire] is a compile error: the type position is always the bare word opaque. The type exposes four operations — two type-parameterized statics (wrap, unwrap) and two plain instance methods (loaded, clone):
opaque[T]->wrap(value) produces an opaque carrying value and records in the runtime tag the kind it holds: which primitive, a C handle, or an object. It takes ownership of value, as any plain parameter does (I.I.vi), so a later read of a handle passed to it is E3010.opaque[T]->unwrap(d) recovers the value. It is a pipe-XOR producer: it yields the moved-out value when d holds a T, and a STATUS failure on a mismatch or an already-emptied opaque. A primitive, a C handle and an array match exactly: an int32 is not an int64, nor an int32[] an int64[]. A class or interface T matches by is-a, decided on the object at run time, so an object wrapped as Circle unwraps as its base Shape or as any interface it implements. It never panics. Recovery is destructive on success: a successful unwrap consumes the value, and a later unwrap of the same opaque finds it empty. On failure it is a no-op, so a caller may retry a failed unwrap with a different T.loaded() reports whether the opaque currently carries a value: TRUE after a successful wrap or clone, FALSE after an unwrap has consumed the payload.clone() deep-copies the wrapped value by the kind it holds — a primitive is copied, an object or an array through its own clone() — and it is non-destructive, leaving both source and copy loaded, and cloning an unloaded opaque yields a fresh unloaded one. An opaque that carries a C handle has no copy, and its clone() raises CloneError (c).No other method may be called on an opaque, whatever the receiver: a local, a parameter, a field, an opaque[] element, or a call's result. d->getName() or shelf[0]->getName() is E2078, because the payload's type is erased and nothing at the call site says which getName is meant. To call a method on the value inside, take it out first: unwrap it into a local or a field of the concrete type, and call the method there. loaded() and clone() are called on the opaque itself, including through an element (shelf[0]->loaded()).
Example.
opaque box := opaque[Circle]->wrap(c) // bracket form — call-site only
// opaque[Circle] field // ERROR — bracket form is not a declarable type
IF opaque[Circle]->unwrap(box) THEN { Circle back := $RETURNED } // destructive on success
ELSE { ... } // tag mismatch or already emptied — box unchanged, retry OK
boolean has := box->loaded() // FALSE after a consuming unwrap
opaque copy := box->clone() // non-destructive deep copy through Circle's own clone()
Rationale. Keeping opaque non-parametric — bracket form for the statics only — is what prevents type erasure from leaking into declarations and re-introducing the metalanguage bounded genericity refuses. Destructive-on-success/no-op-on-failure unwrap gives clean move semantics with a safe retry path: you can probe a tag with one T, and on a miss try another without having disturbed the payload.
(c) Rule. When T is a class type, the opaque temporarily owns the instance; unwrap moves that ownership to the caller and leaves the opaque empty. The wrapped type must itself be a concrete, non-absent type, and it must be one clone() can copy: both statics are declared under TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT opaque), FOREIGN_TYPE:, because a later clone() copies whatever wrap stored. A runtime-shape array (T[], T[N+], T[,]) of such a T is admitted; a fixed-size array (T[N]) is not, because its extent is part of its type and an opaque holds one array shape, so it is E2171 ("fixed-size arrays cannot be loaded into an opaque") — convert it first with INTO T[]. A T that is neither Cloneable, a primitive, nor a FOREIGN_TYPE handle — a class that does not implement Cloneable, or opaque itself, which is move-only — is a compile error at the opaque[T] site (E2114). opaque is the carrier for typed storage of a C handle, where UNSAFE.HANDLE (I.I.viii (b)) holds an untyped void*. A FOREIGN_TYPE T is admitted only inside an UNSAFE block, where the handle itself lives (E3050). Its unwrap is destructive like any other. A C object has exactly one owner, so an opaque carrying a C handle has no copy: its clone() raises CloneError (I.M.ii) rather than hand a second opaque the same pointer, one of which would free it under the other. The tag records at wrap time that it holds a C handle, so the refusal holds wherever the opaque travels, including through a bare opaque whose payload the compiler cannot see. To give a C handle to a second holder, lend it with REFERENCE.
opaque is move-only, and it is bound like an object. Every ownership transfer is spelled := and moves the value: a plain parameter (which owns its argument, I.I.vi), an INIT argument, a store into a field, local or array slot, and a RETURN. After the transfer the source is consumed, and a later read of it is a use-after-move (E3010). = from another opaque would give one value two owners and is E3023, as it is for a class handle; clone() is the only copy. Inside UNSAFE, a typed C handle on the right of = or := is wrapped into a fresh opaque, in a declaration (opaque o = handle) as in an assignment (I.I.viii (c.i)). Equality and ordering on opaque values are not defined in V1 — a caller compares by unwrapping to a typed value first.
Storage. opaque is a primitive backed by the kernel PRIMITIVE Opaque, exactly as number is backed by Number (I.D.i (g)): code always spells the type opaque, never Opaque, and both backends lower the one to the other. Its payload is a kernel UNION (I.D.i (h)) under an OpaqueKind tag. A primitive or a C handle is stored in place, with no allocation. An object is owned through a Cloneable handle, and an array is owned inside a kernel cell (OpaqueArrayCell) that records its element type. wrap[T] and unwrap[T] are Opaque's two generic methods, and a module that calls opaque[T]->wrap gets its own instance for that T, as for any dependency's generic method; each instance picks its arm with MATCH T (I.K.iii (c)). The opaque's CLEANUP releases an owned object — a backing PRIMITIVE may declare a CLEANUP beside its INIT and methods — and a C handle is released by the class that holds it. (Formatter/opaque plan Phase 5, this replaces a heap box over void* with a captured cloner.)
Example.
Dictionary[String, opaque, DefaultHasher[String]] storage
storage["esquire"] := opaque[Esquire]->wrap(e)
storage["manuscript"] := opaque[Manuscript]->wrap(m)
IF storage["esquire"] THEN {
opaque slot =@ $RETURNED
IF opaque[Esquire]->unwrap(slot) THEN {
Esquire back := $RETURNED
// use back
}
}
Rationale. The canonical heterogeneous-storage idiom pairs a Dictionary of opaque values with a typed unwrap at each use site, recovering the static type exactly where it is needed. Equality/ordering are left undefined because comparing two type-erased boxes is meaningless without knowing their contents' types — so a caller unwraps to a concrete type and compares that.
The two-by-two grid of text/binary × immutable/mutable containers, the column discipline that keeps them apart, and the non-owning views that host the search surface.
(a) Rule. Envzn provides four built-in containers for sequences of characters or bytes, understood as a two-by-two grid along two independent axes: what the sequence holds — text (Unicode characters) or binary (uninterpreted bytes) — and whether it may change — immutable (fixed at construction) or mutable (built up in place).
| Text — Unicode, code-point indexed | Binary — opaque bytes | |
|---|---|---|
| Immutable | String |
ByteBuffer |
| Mutable | DynamicString |
DynamicByteBuffer |
Example.
String greeting = "hi" // immutable text
ByteBuffer payload := readBytes() // immutable binary
DynamicString builder // mutable text
DynamicByteBuffer sink // mutable binary
Rationale. Two orthogonal axes give exactly four containers with no overlap and no gap. Every character/byte sequence need lands in one cell, and the grid makes the choice — text vs. binary, immutable vs. mutable — explicit at the declaration.
(b) Rule. All four forms are heap-allocated. The mutable pair were stack-resident with a small-buffer optimization, and were VALUE CLASS declarations ; with the inline storage gone they are ordinary classes, and the only axis that still separates the pair from the other is mutability. The mental model: a String is a constant character buffer with a length, a ByteBuffer the same for raw bytes, and the two Dynamic forms are the growable character and byte builders you append into and then snapshot.
Rationale. Starting the mutable builders on the stack was meant to make the common "build a small string, then snapshot it" path allocation-free until it genuinely needed the heap. It did not: the inline capacity and the growth threshold were owned by different halves of the implementation, so the inline buffer never once engaged, and removing it moved the benchmarks by well under a percent. What survives is the readable surface, which never depended on the storage — a builder you append into and then snapshot, whatever backs it.
(c) Rule. The two axes are enforced, not merely suggested. The text pair is built from char (a full Unicode code point), the binary pair from binary (an uninterpreted octet). The two are deliberately not interchangeable: text containers expose only code-point operations, and byte-level access lives exclusively on the binary containers. Text containers are not binary-safe — they assume valid UTF-8 content, and carrying arbitrary bytes in a String is a defect. Text prints as text; binary prints as hexadecimal. The mutable forms are the builders for the immutable forms — mutate a DynamicString in place, then snapshot to a String with toString() (likewise DynamicByteBuffer → ByteBuffer), and a snapshot always stays within its column.
Example.
DynamicString db
db->append("café")
String snapshot := db->toString() // snapshot stays in the text column
// crossing columns is a conversion, never a container method:
ByteBuffer bytes := (snapshot INTO ByteBuffer) // hosted on TextConverter (I.D.viii)
Rationale. Reaching for an individual byte is precisely the act of stepping from the text column into the binary column, which is the entire reason the binary pair exists. Keeping the two apart stops arbitrary bytes from silently corrupting a UTF-8 String. Crossing between text and binary (or between either and numbers/encodings) is a conversion, and conversion is the job of the AS/INTO operators of I.D.viii (the String↔ByteBuffer bridge on TextConverter), never of a method on the container.
(d) Rule. Alongside the four owning containers the Text family carries two non-owning views: StringView, a bounded window of code points into a String over char32[], and ByteBufferView, a window of bytes into a ByteBuffer over binary[]. Both are critical public-facing members, not implementation details. A view is obtained with ->view(start, length) and is non-owning: it borrows the container's storage rather than copying. It is a short-lived local descriptor that must not outlive the container, be stored into a field, or be returned as an escaping value — the last two are rejected at compile time (E3044), on a view obtained through ->view(start, length). A view is also poisoned with its source: a borrower is only as alive as the value it borrows, so once that value is moved away every later read through the view is E3047. This is the third way a view can outlive what it points at, and the one the two escape clauses do not name — the rule is structural rather than about views alone, and holds for any class that declares a REFERENCE data field. A view over a parameter may be returned: that storage is the caller's and outlives the call by construction. A view narrows further with its own ->view(start, length) (a sub-window of a window is a window) and materialises its slice into a fresh owning array with ->copy() — char32[] from a StringView, binary[] from a ByteBufferView.
Example.
StringView win := text->view(0, 5) // non-owning window of 5 code points
StringView sub := win->view(1, 3) // sub-window — bounds checked against `win`
char32[] pts := sub->copy() // materialise into an owning array
String back := CREATE String(sub->copy()) // escape hatch back to owned storage
Rationale. Making views non-owning is what makes slicing free — no copy until you ask for one with ->copy(). The restrictions (no outliving the container, no storing, no escaping) are what keep a borrowed window memory-safe. ->copy() is the deliberate escape hatch back to owned storage, wrappable with CREATE String(...) / CREATE ByteBuffer(...).
(d.i) Rule. One error policy across all six. An out-of-range operator [] panics with IndexOutOfBoundsError — on every one of the six, text and binary alike. A search that may legitimately find nothing (find, lastIndexOf, find_first_of, find_first_not_of) reports a miss through a pipe-XOR (int64 index | STATUS s), never a -1 sentinel. Everything else is total: substring and subBuffer panic on a bad range rather than returning a status, and both accept length == 0 as an empty result rather than an error. There is exactly one element accessor, []; a second fallible at existed on the binary pair and is retired.
Rationale. The binary pair once declared the opposite policy — "no method throws" — and that single divergence is what generated the drift the two axes accumulated: a second element accessor, a pipe-XOR subBuffer facing a throwing substring, and a -1 the language rejects everywhere else. The policy was also never true of the code that stated it: ByteBuffer's own [] has always delegated to the value array's subscript, which panics. Reaching for an element out of range is a precondition violation — a bug in the caller — while a search that finds nothing is an ordinary outcome; the two deserve different mechanisms, and which class you are holding is not what should decide it.
(d.ii) Rule. A live view mutation-locks its source. ->view(start, length) exists on all six, the mutable pair included. While a view over a growable container is in scope, that container may not be mutated: a call to any MODIFY method of the source, or a rebind of the source variable, is a compile-time error (E5003). The lock is released when the view's binding leaves scope, so the idiom is to bound the view in its own block and mutate afterwards. This is the same per-source lock that has covered iterators, and it is a compile-time analyzer rule — no lock object, no runtime cost, no deadlock.
Rationale. A view holds a borrow of the container's storage, so a growth that reallocates, or a truncation that shortens, leaves a window describing a range the storage no longer has. Measured, the substrate survives reallocation and a later out-of-range read panics rather than corrupting — so this is not closing a corruption hole. It converts a runtime panic into a build-time diagnostic about a fact the compiler can already see, which is the trade this language makes everywhere else. What the lock does not cover is a view outliving its source; that remains the escaping-borrow restriction of (d) above, which is stated but not yet enforced.
(e) Rule. The substring search surface lives on the views, not the owning containers: ->find, ->contains, ->count, ->startsWith, ->endsWith, ->lastIndexOf, ->find_first_of, and ->find_first_not_of are all methods of StringView and ByteBufferView. The needle/set argument is the view's element array — char32[] for a StringView, binary[] for a ByteBufferView — and a needle String/ByteBuffer is presented by taking a full-span view of it and ->copy()-ing that to the element array. A StringView search offers a case-fold variant (->find(needle, caseMatch), likewise contains/count); a ByteBufferView does not, because a byte carries no case. A search that may find nothing (find, lastIndexOf, find_first_of, find_first_not_of) reports a miss through a pipe-XOR (int64 index | STATUS s) return, while startsWith/endsWith/contains return a plain boolean; a returned index is relative to the view it was found in. An out-of-range view(...) or operator[] on a view is a precondition violation and panics. The convenience search methods on String itself are thin forwarders to this one canonical scan.
Method (on StringView / ByteBufferView) |
Returns | Description |
|---|---|---|
->length() |
int64 |
element count of the window (code points / bytes) |
->view(int64 start, int64 length) |
a view of the same kind | narrow to a sub-window; bounds checked against this view, so a sub-view can never escape its parent |
->copy() |
char32[] / binary[] |
materialise the window into a fresh owning element array |
->find(needle) |
(int64 index \| STATUS s) |
first occurrence, or a FAILURE when absent; view-relative index |
->contains(needle) |
boolean |
whether needle occurs at least once |
->count(needle) |
int64 |
non-overlapping occurrence count; empty needle yields 0 |
->startsWith(needle) |
boolean |
prefix test; empty needle is TRUE |
->endsWith(needle) |
boolean |
suffix test; empty needle is TRUE |
->lastIndexOf(needle) |
(int64 index \| STATUS s) |
last occurrence, or a FAILURE when absent; view-relative index |
->find_first_of(set) |
(int64 index \| STATUS s) |
first index whose element is a member of set, or a FAILURE when none is |
->find_first_not_of(set) |
(int64 index \| STATUS s) |
first index whose element is not a member of set, or a FAILURE when every one is |
Example.
StringView hay := text->view(0, text.codePointLength) // full-span view makes indices absolute
char32[] ndl := needleString->view(0, needleString.codePointLength)->copy()
IF hay->find(ndl) THEN { int64 at := $RETURNED } // pipe-XOR miss report
ELSE { print("not found") }
boolean pre := hay->startsWith(ndl) // plain boolean
IF hay->find(ndl, caseMatch) THEN { ... } // StringView-only case-fold variant
Rationale. Hosting the search surface on the views gives one canonical scan that both columns and every convenience forwarder delegate to — the single source of truth for searching. Reporting a miss with pipe-XOR rather than a sentinel index means "not found" is a state the type system forces the caller to handle, not a magic -1 that can be used by mistake. A full-span view makes a view-relative index absolute in the underlying container.
The built-in immutable text value type: its assignment rules, the always-present exception to EMPTY, its count methods, and its method surface.
(a) Rule. String is a built-in value type — neither a primitive nor a user-defined class, and it cannot be subclassed. Its content is immutable: every String method that appears to change a string in fact returns a new String, leaving the original untouched. The compiler manages a string's storage automatically; it is never EMPTY. String satisfies Cloneable (so it composes with the *Copy collection methods and with :=) and Hashable (so it may serve as a Dictionary key).
Example.
String greeting = "hello"
String shout := greeting->toUpper() // returns a NEW Uppercase String; greeting untouched
Dictionary[String, int32, DefaultHasher[String]] counts // String is Hashable — valid key
Rationale. Immutability is what makes a String safe to share and hash: nothing can mutate it out from under a holder, so Cloneable and Hashable hold unconditionally, and the "appears to change" methods returning fresh strings preserves that guarantee.
(b) Rule. String follows class-type assignment rules, and the assignment operator is meaningful. A string literal is assigned with =, and the compiler interns the constant. A string produced by a method call, expression, or another variable is assigned with := (an owned copy bound to the new binding), and using = there is a compile error (E2020). A String is never EMPTY: it is always present, and an empty string is the present value "", not absence. So assigning EMPTY to a String is a compile error, and a string field needs no empty initial state. ByteBuffer is immutable in the same way and follows the same always-present rule; both are the deliberate exceptions to the absence model of I.D.iv.
Example.
String name := "Bob" // literal — := is correct
String upper := name->toUpper() // expression — := required
String copy := name // variable — := required
// String bad = name->toUpper() // ERROR (E2020) — computed value needs :=
// String s := EMPTY // ERROR — String is never EMPTY; use "" for present-empty
String empty := "" // present empty string, not absence
Rationale. The operator encodes what actually happens: = binds an interned constant, := binds an owned copy, so E2020 fires when the two are confused. String/ByteBuffer are always-present because an empty string "" is a genuine value, not an absent state — making them the two deliberate exceptions to I.D.iv means string fields never need an empty-initial guard.
(c) Rule. There is no index operator on a string: name[0] is a compile error, because a code-point index into Unicode text is not the constant-time array access the bracket syntax implies. A string exposes two count methods — ->length(), the code-point count, and ->size(), the UTF-8 byte count — alongside the methods below. A grapheme count is reserved for V3, with the Unicode modes of I.D.iii. Where a method may legitimately produce no result, it does so through a pipe-XOR return rather than a ?-typed one.
| Method | Returns | Description |
|---|---|---|
->isEmpty() |
boolean |
TRUE when the length is zero |
->equals(other) |
boolean |
content equality — the correct (and required) test for two strings; ==/!= on a String is a compile error (E8013) |
->equalsIgnoreCase(other) |
boolean |
content equality, case-insensitive |
->contains(other) |
boolean |
substring test |
->startsWith(prefix) / ->endsWith(suffix) |
boolean |
prefix and suffix tests |
->find(other) / ->find(other, fromIndex) |
(int64 idx \| STATUS s) |
first-occurrence index, or a FAILURE when absent. indexOf was : it was a second name for this search on the byte axis only, and it reported a miss with a -1 sentinel the language rejects everywhere else |
->lastIndexOf(other) |
(int64 idx \| STATUS s) |
last-occurrence index, or a FAILURE when absent |
->find_first_of(set) |
(int64 idx \| STATUS s) |
first index whose code point is a member of set (the code points of set, treated as a set), or a FAILURE when none is |
->find_first_not_of(set) |
(int64 idx \| STATUS s) |
first index whose code point is not a member of set, or a FAILURE when every code point is |
->toUpper() / ->toLower() |
String |
a new string with the case changed |
->trim() / ->trimStart() / ->trimEnd() |
String |
a new string with whitespace stripped |
->split(String delimiter) |
String[] |
split on a fixed delimiter |
->substring(int32 start, int32 length) |
String |
a new string holding the named range |
Example.
// name[0] // ERROR — no index operator on a String
IF name->charAt(0) THEN { char first := $RETURNED } // pipe-XOR — may be out of bounds
IF a->equals(b) THEN { ... } // content equality — required test
// IF a == b THEN { ... } // ERROR (E8013) — ==/!= on a String
int32 bytes := name.byteLength // count field, not a method
String[] parts := csv->split(",")
Rationale. The bracket syntax implies constant-time access, which a code-point index into variable-width Unicode is not — so it is disallowed, and indexing goes through ->charAt/->codeUnitAt which name the cost and the fallibility. Every may-fail method returns pipe-XOR (never a ?-type, which does not exist), so a caller cannot forget to handle the miss.
(d) Rule. Conversion of a String to or from any other type is the work of the AS/INTO operators of I.D.viii, not of a method on String. Pattern-based operations are not methods on String. Regex match, replace, and single-group captureGroup live on the Regex type in the separate, optional Regex module, and String carries no dependency on it. (Multi-group capture, captureNamed, and pattern split — which would return String[] / Dictionary — are deferred until arrays can cross the FFI boundary (ENVZN_IR_SPEC.md C.i).)
Example.
int32 n = 0
IF (name INTO int32) THEN { n = $RETURNED } // conversion is an operator, not name->toInt()
// regex work lives on the optional Regex module, not on String:
// Regex r := CREATE Regex("[0-9]+")
// IF r->match(name) THEN { ... }
Rationale. Keeping conversion off String and on the AS/INTO operators is what makes String's surface purely about text and lets the conversion rules live in one place (I.D.viii). Keeping regex in a separate optional module means a program that never pattern-matches carries no regex dependency — the String type stays lean.
AS / INTO)The two conversion operators — no casts — their loss and fallibility axes, and the named kernel hosts that carry the conversion families.
(a) Rule. Envzn permits no cast: there is no syntax that reinterprets one type as another. All conversion is written with the two operators AS and INTO: between numeric types, between numbers and text, and between the text and binary container columns of I.D.vi. This Part is their full specification — the declaration form in (d), the use site and its resolution in (e), the coherence rules in (f). A conversion is not a method call on a singleton: the former Convert gateway was retired in V1, its families redistributed into the named conversion hosts below.
Example.
String label := (42 INTO String) // conversion operator
// float64 d := (int64Val AS float64)* // no C-style cast syntax exists anywhere
// Convert.toString(42) // retired — the Convert gateway is gone
Rationale. A cast is an assertion the compiler is asked to trust; the language prefers a conversion the compiler can check. So the reinterpreting syntax simply does not exist, and every type change is a checked operator whose loss and fallibility are visible in the code.
(b) Rule. Two orthogonal properties shape every conversion. The loss axis is the operator keyword: INTO is lossless, AS is lossy. The fallibility axis is the return shape. A total conversion yields a plain value; a fallible one yields the pipe-XOR shape of I.M.i, consumed as the condition of an IF/WHILE whose body reads $RETURNED. From these follow three shapes. A widening numeric conversion — a narrow integer to a wider one of the same sign, or an integer to a float — is lossless-total, so INTO. A narrowing or sign-crossing conversion can lose data, so it is the range-checked lossy-fallible AS: a checked conversion, never a silent truncation. Parsing text into a number can always fail, so it is the lossless-fallible INTO from a String.
Example.
// parsing — lossless but may fail, so pipe-XOR consumed by IF
IF (userInput INTO int32) THEN {
int32 n = $RETURNED
process(n)
}
ELSE { printline($!) }
// number to text — lossless and total, a plain value
String label := (42 INTO String)
// widening — lossless and total
float64 d = (myInt32 INTO float64)
// narrowing float → int — lossy and range-checked, so AS + pipe-XOR
IF (myFloat64 AS int32) THEN { pixel = $RETURNED }
Rationale. Carrying loss on the keyword and fallibility on the return shape lets the four practical cases fall out mechanically — the reader sees INTO vs. AS and knows whether data can be lost, and sees a plain value vs. pipe-XOR and knows whether it must handle a failure. Range-checking AS rather than truncating is what turns a whole class of silent narrowing bugs into a handled STATUS.
(c) Rule. The conversion families the former Convert singleton carried now live as named kernel hosts. Each family has a named host, and all of them are CONVERSIONS hosts of AS/INTO operators. Value-to-String renderings are INTO String operators on NumberConverter, FloatConverter, and CharConverter. Numeric widenings and narrowings are PrimitiveConversions, the char-width crossings of I.D.i are CharWidthConverter, and the String↔ByteBuffer bridge of I.D.vi is TextConverter. A few operations are deliberately not checked conversions, and stay ordinary NAMESPACE method calls rather than operators: the truncating bit-exact casts on NumericUtilities, the hex and Base64 codecs (HexCodec, Base64Codec), the UTF codec and its String side (UTFCodec, TextEncoding), the endian binary serialization (ByteOrderCodec), and the character predicates (CharClassifier). I.O catalogues the surface; (d)–(f) below are the normative operator spec.
Example.
String s := (myFloat64 INTO String) // FloatConverter host
char32 wide = (someChar8 INTO char32) // CharWidthConverter host
ByteBuffer bb := (text INTO ByteBuffer) // TextConverter host
uint64 raw = NumericUtilities.truncateToUint64(x) // NAMESPACE call — deliberately unchecked
String hex := HexCodec.toHex(bb) // codec is a NAMESPACE method, not an operator
Rationale. The checked, loss-visible conversions belong on CONVERSIONS hosts because they are exactly what AS/INTO model. The casts, codecs, and predicates are not checked conversions, so routing them through NAMESPACE calls keeps the operator surface meaning only "checked conversion" — never blurring into "reinterpret these bits."
(d) Rule. A conversion is declared in a top-level construct, CONVERSIONS Name { OPERATOR AS|INTO (FROM <source>) RETURNS <target> { … } }, or as an OPERATOR AS|INTO member on a class. RETURNS is mandatory. Beside its operators a CONVERSIONS block may declare PRIVATE METHOD helpers and CONSTANT fields, exactly as a NAMESPACE may (I.K.ii.d), so an operator body names its limits — INT8_MIN, NumericLimits.INT64_MAX — rather than spelling them as literals. The block is typeless, so there is no self to infer the target from, and the return doubles as the target lookup key and the fallibility marker: a bare RETURNS T declares a total conversion, a pipe-XOR RETURNS (T | STATUS) a fallible one. There is no LOSSY/LOSSLESS keyword: the operator keyword and the return shape already carry both axes. All four combinations are real — a lossless total count INTO String, a lossless fallible parse "42" INTO int32, a lossy fallible checked narrowing pi AS int32, and a lossy total conversion a developer writes for a knowing downsample. Because a conversion may be hosted wherever the developer owns the source or the target type, a conversion whose target is a kernel or primitive type lives in a neutral user CONVERSIONS block — the escape hatch the orphan rule of (f) leaves open.
Example.
CONVERSIONS TemperatureConversions {
OPERATOR INTO FROM Celsius RETURNS Fahrenheit { ... } // total — bare RETURNS
OPERATOR AS FROM Celsius RETURNS (int8 | STATUS) { ... } // fallible — pipe-XOR RETURNS
}
Rationale. A CONVERSIONS block lowers to a C++ namespace of inline free functions — declaration-only, never instantiated, never named at a use site — so it structurally cannot be the singleton it retires.
(e) Rule. At a use site, x AS T and x INTO T are expressions usable wherever a T is expected — an assignment right side, a RETURN, a call argument. A total conversion is a plain value; a fallible one follows the pipe-XOR rule of I.M, consumed as the condition of an IF/WHILE whose body reads $RETURNED. Conversions across a hard line must be written with AS/INTO: any text↔number, String↔ByteBuffer, or numeric narrowing/sign-cross. A bare assignment across one is a compile error. The soft line is numeric widening: a same-signedness integer to a wider integer, any integer to a float, float32 to float64. It stays implicit in a bare assignment and is a registered total INTO operator, so written explicitly, x INTO T resolves through the conversion registry like any other conversion. Resolution is keyed on the (source, target) pair. x INTO T requires a lossless conversion; using INTO where only a lossy one is declared is diagnostic E2087 ("use AS"). Symmetrically, x AS T requires a lossy conversion; writing AS where the declared conversion is lossless is diagnostic E2105 ("use INTO"). No declared conversion for the pair — including an explicit INTO/AS whose pair has no registered operator — is diagnostic E2086. Conversions do not chain: A→B and B→C never synthesize A→C.
Example.
String label := (count INTO String) // total — a plain value
IF ("42" INTO int32) { int32 n = $RETURNED } // fallible — pipe-XOR, read $RETURNED
IF (pi AS int32) { int32 n = $RETURNED } // lossy, range-checked — never a silent truncation
float64 wide = narrow // soft line — widening stays implicit
Rationale. The operator keyword always names the loss axis truthfully, so a reader who sees AS knows data may be lost and one who sees INTO knows it cannot be. A missing pair is caught here rather than at code generation, because an emitter has no intrinsic conversion path to fall back on. The no-chaining rule is what keeps resolution decidable.
(f) Rule. The conversion surface is a coherent, owned registry, and two declaration-site rules keep it sound across modules. Coherence (E2088): a (source, target) pair may be declared only once across a module and its dependencies. A redefinition is a major error naming the pair and where it was previously defined — exact file:line for an in-module prior, the host and module for a dependency prior. Orphan rule (E2089): a CONVERSIONS OPERATOR for (source, target) may be declared only by the module that owns the source or the target type. Primitives and kernel types are owned by the kernel module (ENVZN), so only the kernel may declare primitive↔primitive and primitive↔kernel-class conversions.
Rationale. Together these mean x INTO T has exactly one meaning everywhere — no module can silently shadow another's conversion — mirroring the trait-coherence and orphan rules of typeclass systems.
The PascalCase convention for user types and the rule that no module may name — or shadow — a kernel type.
(a) Rule. A user-defined type is named in PascalCase by convention, and the naming rules of I.C apply to it as to any identifier. A module may not declare a type whose name coincides with any kernel (ENVZN) type — neither the utility gateways — System, Stdio, Process, Math, File, Path, and the retired Convert — nor the collection and value types String, Array, Set, Dictionary, Box, DynamicString, and the rest. An attempt to do so is a compile error. Kernel types are not shadowable. I.N gives the resolution order, and the Appendix catalogues every reserved identifier.
Example.
CLASS InvoiceLine { ... } // PascalCase user type — fine
// CLASS Set { ... } // ERROR — Set is a reserved kernel type name
// CLASS Dictionary[K, V, H] { ... } // ERROR — cannot shadow a kernel type
// NAMESPACE Math { ... } // ERROR — Math is a reserved gateway name
Rationale. Allowing a module its own Set, with the kernel's still reachable as ENVZN::Set, silently corrupts type resolution: a concrete field in the shadowing class can be mis-typed as the shadowed kernel generic's T, and the emitter lowers it wrongly. The rule is therefore uniform — every kernel type name is reserved. Convert keeps its reservation even though its gateway is gone, so old code naming it fails loudly rather than resolving to a user type.
(a) Rule. Five type names exist solely to name a C type at the foreign-function boundary: C.size_t, C.ssize_t, C.long, C.unsignedLong, and C.mode_t. A FOREIGN BIND names the type its C declaration names (I.N (h.vii)), and these exist for the C types no fixed-width primitive matches on every target: size_t is unsigned long where uint64_t is unsigned long long, and mode_t is 16 bits on Darwin and 32 on Linux. Each lowers verbatim to the C spelling it names. Each is a single reserved word that contains a dot — C is not a namespace, declares nothing, and reserves no identifier; a class, module, or variable named C remains perfectly legal.
These types are admissible only inside a FOREIGN or FOREIGN BIND declaration. They may not be the type of a local, a field, a collection element, or a return of an ordinary method. One exception, the native array: a local may be a native array of one, C.size_t[] sizes, so a C function can fill or read a buffer of C-width values. Its element size and alignment are the target's C type's, by construction, and it crosses a FOREIGN BIND as a pointer to that type (I.N(h.vi)). An element never enters Envzn at the C width: reading one yields the widest fixed-width integer of the same signedness (uint64 for C.size_t, C.unsignedLong and C.mode_t; int64 for C.ssize_t and C.long), and writing one converts the Envzn integer with the range check of a C.* argument, raising MathError rather than truncating. A scalar local of a C.* type, a field, and an ordinary method signature remain refused. They carry no arithmetic and no ordering, they are not members of the Numeric group, and they are not valid dictionary keys. They have no guaranteed width — that absence is their contract, not an omission. A caller passes and receives an ordinary Envzn integer; the compiler converts at the boundary, and an inbound value outside the platform's range for that C type raises the MathError of I.F.ii(a.iii) rather than truncating.
Example.
FOREIGN BIND EVP_DigestSign(EvpMdCtx ctx, LOAD uint8[] sig,
LOAD C.size_t siglen,
uint8[] tbs, C.size_t tbsLen) RETURNS int32
uint64 siglen = 256 // an ordinary Envzn integer
UNSAFE { rc = FOREIGN::EVP_DigestSign(ctx, sig, siglen, tbs, tbsLen) }
// siglen now holds the length the C function wrote back
// C.size_t n = 0 // ERROR — not a declarable type
// CLASS C { ... } // fine — `C` is not reserved
Rationale. Envzn's fixed-width primitives lower to the exact-width <cstdint> types, which is right for Envzn's own semantics and wrong for naming a C typedef. On a 64-bit platform size_t and uint64_t occupy the same width yet are distinct types, and C++ refuses to convert between pointers to them — so a size_t * out-parameter cannot be expressed by any fixed-width primitive. Worse, which primitive would happen to match flips between platforms: uint64_t is unsigned long long on Darwin and unsigned long on Linux, so a binding written against the wrong one compiles on one target and fails on the other. Naming the C type makes the match true by construction everywhere, which is why the family names C's spelling rather than a width. The boundary-only restriction is what keeps that platform-variable width from ever entering Envzn storage, where it would reintroduce exactly the silently-wrong-size defect the memory-safety floor forbids.
How a name is given a type and storage — locals, fields, parameters, and constants — together with the one-new-declaration-per-line rule, the no-shadowing rule, and the modifiers that adjust a field.
(a) Rule. A declaration introduces a name, gives it a type, and provides it with storage. Envzn has four kinds of declared binding: local variables, class fields, method parameters, and constants. Their deeper semantics differ, but they share one surface form — the type precedes the name, and the name follows the identifier rules of I.C. Every local variable, every field, and every parameter is written with its type stated. Type inference operates within a declaration, resolving the types of literals and sub-expressions on the right-hand side against the declared type on the left; it is not a way to omit the type.
Example.
int32 count = 0 // local variable
int64 total = 3 + 4 // literals 3, 4 typed int64 against the declared type
String name = "Ada" // String literal binds with =
Circle c := CREATE(5.0) // local, ownership bind (concrete type inferred)
Rationale. The type at a binding site is exactly the information a later reader needs, and the language declines to make that reader reconstruct it. Inference resolves the right-hand side against the stated type rather than replacing it, so the surface never omits the one fact the reader came for.
(b) Rule. A local variable is declared inside a method body or block. It is initialized at the point of declaration with one of the three assignment operators described in I.G: = to bind a value, := to take ownership of an object (construct, clone, or move), =@ for a non-owning reference. The operator is part of the declaration's meaning and not a stylistic choice; I.G gives the rules that pair an operator with the shape of binding it may introduce.
Example.
int32 n = readCount() // = binds a value (primitive)
String label := computeLabel() // := computed String takes ownership
Buffer b := CREATE Buffer(1024) // := construct → ownership
REFERENCE Node r =@ .head // =@ non-owning reference to a place
Rationale. Because the operator carries the meaning, a reader can tell a value-copy from an ownership transfer from a borrow without reading the right-hand side or the type. The pairing rules live in I.G so the operator alone is enough to know what a binding does.
(c) Rule. An assignment line may declare at most one new typed variable. When a method returns several values, the additional receiving variables are declared on their own lines first, and only the final new variable is introduced on the assignment line itself.
Example.
// correct — one new declaration on the assignment line; STATUS s declared above
STATUS s
int32 n, s = scanInt(text) // a comma-shape (int32, STATUS) producer
// compile error — two new declarations on one assignment line
int32 n, STATUS s = scanInt(text)
Rationale. A reader scanning a line of code can see at a glance which names it brings into existence; predeclaring the extra receivers keeps that count to one on the line where the values arrive.
(d) Rule. A declaration may not shadow a name already visible to it. A local variable whose name matches a class field, a method parameter, a return variable, or any local already declared in an enclosing scope is a compile error. Envzn permits no shadowing at any level.
Example.
CLASS Account {
int32 balance // field
METHOD adjust(int32 delta) RETURNS STATUS {
int32 balance = delta // ERROR — shadows the field `balance`
int32 delta = 0 // ERROR — shadows the parameter `delta`
}
}
Rationale. A name that silently means two things in one method is a reliable source of error and offers nothing in exchange, so the language forbids the collision outright rather than resolving it by scope.
(e) Rule. A class field is declared inside a class body, and a field is public and immutable unless a modifier says otherwise: visibility narrows only where the declaration says so, while mutability widens only through a MODIFY method. Immutable is what a read-only view sees: through a REFERENCE a field cannot be written, and a class's own methods write SELF's fields only when MODIFY (I.K.vi(b)); the owner of an object, or a MUTABLE REFERENCE to it, may write its public fields directly (I.I.vi(a)). The modifiers that adjust a field are the access modifiers — PRIVATE, PROTECTED, and the module-scoped INTERNAL — together with CONSTANT, which declares a field whose value is fixed at compile time. SHARED is not among them: it is a modifier on a CLASS declaration (I.K.ii), never on a field — its one field form is SHARED MUTABLE REFERENCE (I.I.vi), and any other SHARED field, SHARED CONSTANT included, is E1182. (A V1 field is mutated through MODIFY methods, and shared mutable state across tasks goes through Mutex[T] / AtomicX / a SHARED CLASS monitor, not a raw VOLATILE field.)
Example.
CLASS Point {
int32 x // public + immutable by default
PRIVATE int32 y // confined to Point
PROTECTED int32 z // visible to subclasses
INTERNAL int32 tag // module-scoped
CONSTANT int32 ORIGIN = 0 // compile-time-fixed value
}
Rationale. The default a developer gets for free is the one that needs no ceremony to read, so visibility opens and every narrowing of it is spelled out with a modifier — the audience is named exactly where it is restricted, and a declaration carrying no modifier makes no claim to hide. Safety rides the other axis: a field is immutable by default and every write path goes through a named MODIFY method, so the guarantee that matters — nothing mutates the receiver behind your back — never rested on the visibility default. The class as a whole, its INIT, its methods, and its inheritance are the subject of I.K. The ownership a field declaration implies is described in I.I.
(e.i) Rule. A primitive field, and a String or ByteBuffer field, is auto-initialized to its default before INIT runs — the two containers because they are the always-present exceptions of I.D.vii and can never be EMPTY. Any other class-typed field is not: the compiler requires it to be assigned on every path through INIT, and an unset class-typed field is a compile error rather than a silent EMPTY.
Example.
CLASS Widget {
int32 count // auto-initialized to 0 before INIT
String name // auto-initialized to "" before INIT
ByteBuffer blob // auto-initialized to empty before INIT
Buffer buf // class-typed — NOT auto-initialized
INIT() {
.buf := CREATE Buffer(64) // must be assigned on every path, or compile error
}
}
Rationale. Primitives, String, and ByteBuffer have a well-defined default, so the compiler can supply it silently. An ordinary class instance has none, and leaving one unset would be an absent object masquerading as present. Forcing the assignment turns a would-be silent EMPTY into a compile error at the one place it can be fixed.
(e.ii) Rule. The auto-initialization of a String or ByteBuffer field is a semantic guarantee, not a promise about when the storage is built. The value is "" from the moment the object exists: an unassigned field is observably an empty string, never absent and never a fault. But the compiler is free to materialize that empty value lazily, at the field's first read, rather than constructing one in every constructor. A field the developer's own INIT assigns therefore costs exactly one construction, not two, and a field that is never read costs nothing at all.
Example.
CLASS Person {
PRIVATE String name // never assigned by INIT …
INIT() { }
METHOD greet() RETURNS String {
RETURN (("Hello, $1")->format(.name)) // … and reads as "" here, not a fault
}
}
Rationale. This is the I.A tie-break — relocate the cost inward — applied to the most common field type in the language. Eagerly default-constructing every String field would put an allocation in every constructor for a value the developer usually overwrites on the next line, and every object in the program pays it. Deferring it keeps the developer's surface exactly as the rule states: a String field is always there. The machinery that makes it true lives in the compiler and the kernel. (Dropping the guarantee instead of relocating it is what goes wrong: the field is left as a null handle, and reading it faults with no diagnostic and no way to guard, since a String cannot be EMPTY and IS VALID does not apply to one.)
(f) Rule. A CONSTANT field is set at its declaration with a literal right-hand side, may hold only a primitive or String value, and may never be reassigned. It composes freely with PRIVATE and INTERNAL, or may stand with no access modifier at all — in which case it is public; the order of CONSTANT relative to the access modifier does not matter. It does not compose with PROTECTED, REFERENCE, or FOREIGN_TYPE, and each such combination is a compile error. (VOLATILE was retired as a field modifier in V1 and is rejected on any field, CONSTANT or not; the keyword itself stays reserved for future use.)
Example.
CONSTANT int32 MAX = 100 // no access modifier → public
PRIVATE CONSTANT int32 SEED = 42 // composes with PRIVATE
CONSTANT PRIVATE int32 SEED2 = 42 // order of CONSTANT vs modifier does not matter
CONSTANT String NAME = "envzn" // String value
// errors — CONSTANT does not compose with these
VOLATILE CONSTANT int32 v = 1 // ERROR — runtime mutability contradicts a fixed value
PROTECTED CONSTANT int32 p = 1 // ERROR — PROTECTED does not compose with CONSTANT
REFERENCE CONSTANT int32 r = 1 // ERROR — a borrow storage shape contradicts a fixed value
SHARED CONSTANT int32 s = 1 // ERROR E1182 — SHARED is a CLASS modifier, never a CONSTANT's
Rationale. PROTECTED, REFERENCE, and FOREIGN_TYPE each describe a storage shape or visibility rule that contradicts a compile-time-fixed value, so the combination is rejected rather than silently reinterpreted. The modifiers that do compose only adjust visibility, which a fixed value tolerates.
(g) Rule. A method parameter is declared in a method or INIT signature, type before name, exactly as a local is. Every call is positional and supplies every argument: a parameter may not carry a default value, and there is no named-argument call syntax. A method that would want an omitted argument is spelled as two overloads, or as a method taking a value the caller computes. Overloads of one name are told apart by their parameters' types and modes, so two overloads may take the same types and differ only in mode. A call then chooses by what it passes: a plain value selects the owning overload, and a REFERENCE or MUTABLE REFERENCE local selects the matching reference overload — with take(String s) beside take(REFERENCE String s), take(name) moves name into the first, while REFERENCE String r =@ name followed by take(r) lends it to the second and name survives. When a typed primitive argument matches no overload exactly but widens implicitly (I.J.iii.c) into several, the call takes the widening that changes least: one that keeps the argument in its family (integer to integer, float to float) before one that leaves it, then the narrowest target — so a uint32 passed to truncateToInt32 over int64, uint64, float32 and float64 takes uint64, int64 never being in the running because a sign change is explicit. A choice still tied is ambiguous, and the call states its conversion with INTO. A literal is placed by its own adoption rule (I.D.i), not by this one.
Example.
METHOD greet(String name, int32 times) RETURNS STATUS { ... } // type before name, as a local
obj->greet("Ada", 3) // positional — every argument supplied
Rationale. Every argument being written at every call site keeps a call readable without consulting the signature: what is passed is what is there. It also keeps one call shape rather than two, so a reader never has to know whether a given argument was omitted or defaulted. The ownership a parameter declaration implies, and what a callee may do with each parameter shape, are given in I.I.
The forms that compute a value — member access, operators, object construction, method calls, lambdas, and format strings — and the rule governing each.
(a) Rule. An expression computes a value. This section covers the forms that do so — operators, member access, object construction, method calls, lambdas, and format strings — and states the rules of each.
Example.
int32 sum = a + b // operator expression
String name := person.name // member-access expression
Circle c := CREATE(5.0) // object-construction expression
Identity id := IDENTITY(person) // compile-time reflection expression (I.K.iii)
int32 len = items->count() // method-call expression
String label := ("$1 of $2")->format(i, n) // format-string expression
Rationale. Naming the closed set of value-producing forms up front lets each subpart specify one form in isolation.
Two sigils, chosen by what you hold: . reaches into a value or scope, -> sends a message to an instance.
(a) Rule. A . accesses a data field and a NAMESPACE member; no instance handle is involved. A . reaches a declared data field (person.name), a struct field, a builtin-array field (myArray.length — a T[] carries its length as real data), an iterator-state field (iter.index), and a NAMESPACE function or constant (Math.PI, Math.sqrt(2.0)). A namespace has no instance, so its functions and constants are reached directly, like any scoped name. The compiler synthesizes no phantom computed field (I.C.c.i). A quantity a class exposes through a method — a length, a size, a count computed from its contents — is read ->length() / ->size(), never .length / .size.
Example.
String who := person.name // data field
int32 len = myArray.length // synthesized field
int32 at = iter.index // iterator-state field
float64 pi = Math.PI // NAMESPACE constant
float64 root = Math.sqrt(2.0) // NAMESPACE function
Rationale. A namespace is a scope, not an object; there is nothing to dereference, so its members are reached the same way as any other named-scope member.
(b) Rule. A -> invokes a method on an instance or actor: person->getName(), items->append(x), System->exit(0). The rule is uniform across instance and inherited methods, the kernel collection methods, and SINGLETON actor methods — all ->.
Example.
String n := person->getName() // instance method
items->append(x) // kernel collection method
System->exit(0) // SINGLETON actor method
Rationale. A reader should be able to tell, from the sigil alone and without consulting a declaration, whether a fragment reaches into a value/scope or sends a message to an instance.
(c) Rule. The compiler holds the line in every direction. person.getName() is an error: an instance method reached with the field sigil. person->name is an error: a field reached with the method sigil. Math->sqrt(2.0) is an error (E1106) because a namespace function is reached with the instance sigil, and a namespace has nothing to dereference.
Example.
String n := person.getName() // ERROR — instance method reached with the field sigil
String m := person->name // ERROR — data field reached with the method sigil
float64 r = Math->sqrt(2.0) // ERROR (E1106) — namespace function reached with the instance sigil
Rationale. Enforcing the distinction in both directions is what makes the sigil a reliable signal: if the compiler allowed either form to slip, the reader could no longer trust it.
(d) Rule. A field is always named with its .. Inside the class it is .field, the implicit-SELF read; on another object it is x.field. A bare field name, read (count) or written (count = 0), names no binding and is an error (E2051, whose fix is .count). This differs from a method: a bare method name is an implicit self-call (I.F.iv(a)), but a bare data name means a local or a parameter, never a field. A class CONSTANT is not a data field, and is still named bare.
Example.
CLASS Counter {
int32 count
MODIFY METHOD bump() {
.count = .count + 1 // OK — the field, with its dot
count = count + 1 // ERROR (E2051) — a field named without its `.`
}
}
Rationale. One spelling per read means the reader knows a field from a local at a glance, without checking the declarations above. The bare form also misled the compiler: when a FINAL class's method was inlined into a caller, the bare name was carried into a scope where no such variable exists.
English keywords for most operators; punctuation reserved for arithmetic and comparison where a symbol is universally understood.
(a) Rule. The arithmetic operators are the five ordinary ones (+ - * / %) together with two Envzn adds: ^ raises to a power, and # takes a hash word. ^ is right-associative and binds tighter than * and /, and tighter than unary minus on its left — so -2 ^ 2 is -(2 ^ 2). Its result is an integer when both operands are integers and the exponent is provably non-negative: a non-negative literal, or an unsigned-typed exponent. Otherwise — a float operand, or an exponent that could be negative — the result is float64. Overflow does not wrap silently — it raises a MathError PANIC, as for * (the overflow-and-range contract of (a.iii)). # has two forms, and both take only a WordKey operand: an integer (int8…int128, uint8…uint128), a char (char8, char16, char32) or binary. The prefix #k is k's value mod 2⁶⁴, as a uint64: an unsigned value or a code point is unchanged, a signed value wraps in two's complement, a 128-bit value keeps its low 64 bits, and an octet gives its bit pattern. The binary a # b combines #a and #b into one uint64. Any other operand is a compile error (E2153) — a float, decimal128, number, complex, boolean, an array or a class. Being a hash fold, # wraps by design and is the one arithmetic operator exempt from the overflow PANIC of (a.iii).
Example.
int32 sq = -2 ^ 2 // -(2 ^ 2) == -4 (^ binds tighter than unary minus)
int32 cube = 2 ^ 3 // 8 (both operands int, exponent non-negative → int)
float64 inv = 2 ^ -1 // 0.5 (exponent could be negative → float64)
uint64 w = #key // key's hash word: -1 as an int32 → 0xFFFFFFFFFFFFFFFF
uint64 h = keyA # keyB // the two hash words combined → uint64
// uint64 bad = #2.5 // ERROR E2153 — a float's bits are not its value
Rationale. A negative exponent has no integer result, so the type widens to float64 exactly when the exponent is not provably non-negative. ^'s tight binding matches the mathematical reading of -2^2, # admits exactly the values that ARE a bit pattern: mod 2⁶⁴ of an integer, a code point or an octet is a fold that equal keys survive, while a float has several encodings of one number and a class has no value word. That is what lets a hasher over a numeric K reach the key's bits with uint64 v = #key, with no cast and no failure.
(a.i) Rule. The postfix ! is the factorial operator: 5! is 120. It applies to an integer operand only; a float operand is a compile error, the gamma function being reserved for V2. It binds tighter than ^, so 2 ^ 3! is 2 ^ (3!), and follows the empty-product convention, so 0! is 1. On overflow it raises a MathError PANIC (the contract of (a.iii)) rather than wrapping silently.
Example.
int32 f = 5! // 120
int32 one = 0! // 1 (empty-product convention)
int32 p = 2 ^ 3! // 2 ^ (3!) == 2 ^ 6 == 64 (! binds tighter than ^)
int32 bad = 3.0! // ERROR — factorial on a float operand (gamma reserved for V2)
Rationale. Factorial binds tighter than ^ so the common 2 ^ n! reads without parentheses, and it is integer-only because the float generalization (the gamma function) is deliberately held back to V2.
(a.ii) Rule. Ordinary division / is integer division when both operands are integers — 7 / 2 is 3 — and becomes float division as soon as either operand is a float. The result is then the wider float operand's own type, not float64 unconditionally: float32 / float32 is a float32, and so is float32 / int32 (the integer widens into the float beside it, as it does under every other arithmetic operator), while float32 / float64 is a float64 and 7.0 / 2 is a float64 because 7.0 is one. This is the same common-type join + - * use; / is not a special case of it.
^ is the special case, and it is deliberate. Exponentiation always yields a float64 the moment a float is involved — float32 ^ float32 is a float64, not a float32 — because ^ lowers to std::pow at double precision and a negative exponent has no integer result at all (I.F.ii(a)). So float32 r = f ^ g is a narrowing and is refused (E2007), where float32 r = f / g is exact and is not. The two operators are written here as two rules because they are implemented as two: / preserves the operands' width, ^ promotes out of it. (Amended, Phase 8 family #3 — this rule said / "yields a float64 as soon as either operand is a float", which would have made float32 r = f / g a narrowing at every site the kernel and the data-science chain write it.)
The ~/ operator is the explicit floor-division form. It always yields an integer-shaped value — the largest integer not exceeding the true quotient — flooring toward negative infinity rather than truncating toward zero, so -7 ~/ 2 is -4. Its domain violations panic rather than yield a silent wrong value — division by zero, a NaN or infinite float operand, and an integer-shaped result outside the int64 range each panic with MathError.
Example.
int32 a = 7 / 2 // 3 (both int → integer division)
float64 b = 7.0 / 2 // 3.5 (`7.0` is a float64 → float64)
float32 e = f32a / f32b // the WIDER FLOAT OPERAND's type, not float64
float32 g = f32a / 2 // the integer widens into the float beside it
float64 h = f32a / f64b // float32 with float64 → the wider one
float64 i = f32a ^ f32b // `^` is the exception: always float64 (std::pow)
// float32 j = f32a ^ f32b // E2007 — narrowing out of `^`'s float64 result
int32 c = -7 ~/ 2 // -4 (floors toward negative infinity, not toward zero)
int32 d = 5 ~/ 0 // panics with MathError — division by zero
Rationale. ~/ is spelled ~/ rather than the // some languages use because // opens a line comment in Envzn. Floor division panics on domain violations rather than returning a silent wrong value, so a broken computation surfaces at the point it goes wrong.
| Operator | Operation | Operator | Operation | |
|---|---|---|---|---|
+ |
addition | % |
modulo (integer or float by operands) | |
- |
subtraction | ^ |
exponentiation | |
* |
multiplication | # |
hash word: prefix #k, combine a # b (WordKey operands, uint64) |
|
/ |
division (integer or float by operands) | ! |
factorial (postfix, integer operand) | |
~/ |
floor division (integer result) | &+ &- &* |
wrapping add / subtract / multiply (a.iv) |
(a.ii.a) Rule — the domain of %. Modulo is defined on the fixed-width integers and on
float32/float64, mirroring /. The float form is C's fmod: the result takes the sign of
the dividend and satisfies a == trunc(a/b)*b + (a % b) exactly, introducing no rounding error of
its own — so -7.5 % 2.0 is -1.5, not 0.5. The two divisor-zero behaviours differ because the
two types' overflow philosophies do (a.iii): an integer % by zero raises the tier-2 MathError
PANIC, while a float % by zero yields NaN, floating-point being IEEE-untrapped.
Modulo on complex has no accepted meaning — the complex numbers carry no ordering to take a
remainder against — and is rejected.
number and decimal128 are intended to support % and do not yet. Both declare
+ - * / and stop there, because % is the one arithmetic operator with no operator-method
spelling for a class to declare, so neither can define it. For decimal128 the operation is exact
and needs no floating-point machinery — align the exponents and take the remainder of the
coefficients — and it is the operation a money type owes its callers: an allocation waterfall
splitting an amount N ways distributes the residual with %. The result's exponent rule is settled
with that work.
(a.iii) Rule — the overflow and range-violation contract. A bare arithmetic operator whose result leaves its type's representable range does not wrap silently — it raises a MathError PANIC. The PANIC is tier-2: it unwinds the stack running CLEANUP and is catchable by a top-level RECOVER for graceful shutdown — not an ASSERT!-tier abort that halts without teardown. The contract is uniform across + - *, unary -, ^, and ! on every fixed-width integer, signed and unsigned alike (int8..int128, uint8..uint128). A uint32 that overflows PANICs exactly as an int32 does: a silently-wrapped unsigned value — the classic wrapped size — is precisely the exploit the floor forbids. The same tier-2 PANIC covers integer division-by-zero (/ and %) and a shift past the operand's bit width. The one arithmetic operator exempt is # (hash-combine): hashing is modular by definition, so # folds its operands with defined wraparound and never PANICs. This contract is always on — it is part of the correctness floor, not a debug-only check, so it is not stripped under -prod (unlike the tier-3 ASSERT! family); a production build keeps its graceful-shutdown-on-overflow guarantee. There are exactly two documented type exceptions, each carrying its own overflow philosophy at its own type: number promotes up the INTEGER → UNSIGNED → FLOAT ladder (I.D.i(g.iv)) to preserve the mathematical value, so it never PANICs on integer overflow. decimal128 rounds within its precision (round-half-even), and PANICs only on true divide-by-zero or exponent overflow. Floating-point types are untrapped. float16/float32/float64 follow IEEE 754 exactly: an operation that leaves the finite range yields ±Infinity, and one that underflows yields a signed zero. Those are the type's defined results, not out-of-range conditions. Code that genuinely wants modular wraparound reaches for the first-class, greppable wrapping operators &+ &- &* (a.iv); silent wrap is never the operator default. *(The contract covers every expression position, including the bodies of PARALLEL, CONCURRENT, UNSAFE, REPEAT, UNTIL, DO-WHILE, MATCH arms and the N-D FOR (i, j) IN walk.
Example.
int32 big = 2_000_000_000 + 2_000_000_000 // PANIC (MathError) — int32 overflow, never a silent wrap
int32 wrap = 2_000_000_000 &+ 2_000_000_000 // explicit modular wrap — the greppable opt-in, no PANIC
float64 huge = 1e308 * 10.0 // Infinity — float is IEEE-untrapped, no PANIC
int32 z = 5 % 0 // PANIC (MathError) — integer divide-by-zero
Rationale. A silently-wrong number is the classic C footgun. A size = a * b that wraps to a small value and is then used to allocate or index is exactly how memory-safe code is subverted, so the memory-safe floor makes the natural operator refuse to produce it. The cost is relocated inward. The wrap philosophy lives in the explicit &+ &- &* operators (a.iv) rather than the default, and the runtime check falls on bare fixed-width integers alone — number, complex, and decimal128 are value-class-backed and carry it nearly for free. PANIC rather than abort is deliberate. A range violation cannot let the computation continue, but a server or fintech process must still catch it at a boundary, flush logs, close sockets, and exit cleanly. The CLEANUP-unwinding, RECOVER-catchable tier-2 gives exactly that, where a bare abort would leak resources on the way out. (Policy confirmed. The checked lowering IS this contract's implementation and it has landed, so the -fwrapv soundness stopgap — defined two's-complement wrap, the explicit opposite of this rule — is removed, from the emitter and,, from every remaining build. The hand-written C units in kernel/native/ carry the equivalent explicitly via EV_ckarith_native.h, which reports an overflow rather than defining it. Nothing in the language now relies on signed overflow being defined.)
(a.iv) Rule — the wrapping operators. The modular-arithmetic escape hatch of (a.iii) is a family of three operators — &+ (wrapping add), &- (wrapping subtract), &* (wrapping multiply) — spelled with a leading &. On a fixed-width integer they compute the true result modulo 2ⁿ and never PANIC: a &* b is the low-n bits of the full product, the defined two's-complement wrap. They are integer-only — a float, number, complex, or decimal128 operand is a compile error (E2134), since those types carry their own overflow philosophy (a.iii). &+/&- bind at additive precedence and &* at multiplicative, exactly like their panicking counterparts. This is the only place silent modular arithmetic is sanctioned, and it is loud at the use site — a reader sees &* and knows the wrap is intentional. Each lowers to a single machine instruction, so hashing / PRNG / checksum code pays nothing for the safety of the default.
Example.
uint64 mixed = acc &* prime // FNV mix — wraps mod 2^64, no PANIC
uint32 idx = (h &+ step) BAND mask // ring index — wrapping add, then mask
int64 bad = 3.0 &* x // ERROR (E2134) — wrapping ops are integer-only
Rationale. An operator, not a method: it carries no namespace reference, so it reads as arithmetic and introduces no spurious module/class dependency (a Math.wrap* call would). The & leader follows the established systems-language convention (Swift's &+ &- &*), is visually distinct from the panicking + - *, and greps cleanly, so every deliberate wrap is auditable.
(b) Rule. Increment and decrement apply to a mutable numeric variable, in both prefix and postfix position. The prefix forms ++i and --i change i and yield the new value; the postfix forms i++ and i-- yield the current value and then change i. Applying either to a literal, a constant, or a compound expression is a compile error, because there is no storage to update. An integer increment or decrement that overflows raises the MathError PANIC of (a.iii), exactly as i = i + 1 does; a deliberate wrap is written i = i &+ 1.
Example.
int32 i = 0
int32 a = ++i // i becomes 1, a == 1 (prefix: change then yield)
int32 b = i++ // b == 1, i becomes 2 (postfix: yield then change)
int32 c = ++5 // ERROR — no storage to update (literal)
int32 d = ++(a + b) // ERROR — no storage to update (compound expression)
Rationale. Increment and decrement mutate storage in place; a literal, constant, or compound expression names no storage, so there is nothing to write back.
(b.i) Rule — compound assignment. x += e, x -= e, x *= e, x /= e and x %= e are statements, not expressions, and each means exactly x = x <op> e: the same operator with the same overflow, division-by-zero and type rules of (a.iii), so += on an int32 PANICs where + would. The target is a plain local variable name; a field, subscript or other place is written out in full (.total = .total + n). There is no compound form of the wrapping operators, the keyword operators or ^.
Rationale. The short form earns its place in the one position it is unambiguous — a statement updating a named local — and it is defined by desugaring, so it carries no semantics a reader has to learn separately from the operator it abbreviates.
(c) Rule. The comparison operators are the six ordinary ones — ==, !=, >, <, >=, <= — together with BEQUALS and BNEQUALS, which compare bit patterns rather than values. The ordinary == and != compare primitive values directly.
Example.
IF a == b THEN { ... } // primitive value equality
IF x >= 0 AND x < n THEN { ... } // ordinary comparisons on primitives
IF f1 BEQUALS f2 THEN { ... } // bit-pattern equality (distinguishes NaN, -0.0)
Rationale. Value comparison is the common case, so it gets the ordinary symbols; bit-pattern comparison is a distinct, rarer intent and gets its own named operators.
(c.i) Rule. == and != do not do what a reader from another language might expect on a String or a class instance. On a String, == and != are a compile error (diagnostic E8013): a reference comparison there is almost never intended, so the language refuses it and directs the reader to the content test ->equals(). On a class instance, == compares references (identity); content equality is the Equatable interface's ->equals(), and == on a module's own class is likewise rejected (E2069) in favour of a named method.
Example.
IF s1 == s2 THEN { ... } // ERROR (E8013) — String ==; use s1->equals(s2)
IF s1->equals(s2) THEN { ... } // content comparison of Strings
IF a == b THEN { ... } // class instance: reference identity
IF a->equals(b) THEN { ... } // content equality via the Equatable interface
Rationale. A reference comparison on a String is almost never what the writer meant, so the language refuses it outright rather than silently doing the surprising thing. The same reasoning rejects == on a module's own class, in favour of a named, greppable method.
(c.ii) Rule. On a float operand == is exact IEEE value equality, with no built-in tolerance: NaN == NaN is FALSE, 0.0 == -0.0 is TRUE, and 0.1 + 0.2 == 0.3 is FALSE. It is the same value comparison a number's == performs across its subtypes. For a principled tolerance there is the approximate-equality pair ≈ (U+2248) and its negation ≉ (U+2249), a number-only relational operator at the same precedence as ==: a ≈ b is TRUE when |a − b| ≤ max(rtol·max(|a|,|b|), atol) — a relative tolerance with an absolute floor so comparison to zero works. Because a number knows its subtype, two integer-subtype operands compare exactly (5 ≈ 6 is FALSE), and the tolerance applies only when a float subtype is involved. Any int*/float* operand widens into number, so n ≈ 3.0 compiles, while a non-numeric operand is a compile error. A custom tolerance is supplied through the companion method a->isClose(b, rtol, atol). There is no settable global tolerance, and ≈ has no ASCII spelling (an input method expands \approx/\napprox to the glyph; ~= is deliberately not reused, as it means not-equal elsewhere).
Example.
boolean e1 = NaN == NaN // FALSE (exact IEEE)
boolean e2 = 0.0 == -0.0 // TRUE
boolean e3 = 0.1 + 0.2 == 0.3 // FALSE (no built-in tolerance)
boolean e4 = a ≈ b // TRUE when |a − b| ≤ max(rtol·max(|a|,|b|), atol)
boolean e5 = 5 ≈ 6 // FALSE (integer subtypes compare exactly)
boolean e6 = n ≈ 3.0 // compiles — int* / float* widens into number
boolean e7 = a->isClose(b, rtol, atol) // custom tolerance via the companion method
Rationale. Exact IEEE equality is what a float == must mean to stay predictable, so principled tolerance is a separate operator rather than a hidden fuzz on ==. ≈ is number-only because tolerance is only meaningful once a subtype is known; there is no global tolerance knob because a hidden, mutable epsilon would make every comparison non-local.
(c.iii) Rule. Where the intent is instead bit-exact float comparison — distinguishing NaN from NaN and 0.0 from -0.0 — that is BEQUALS/BNEQUALS. The boolean operators are the keywords AND, OR, NOT, and XOR. The bitwise operators are likewise keywords — BAND, BOR, BXOR, and the ones-complement BNOT — as are the shift and rotate operators LSHIFT, RSHIFT (logical, zero-filled), ASHIFT (arithmetic, sign-filled), LROTATE, and RROTATE.
Example.
IF ready AND NOT paused THEN { ... } // boolean keywords
IF (a > 0) XOR (b > 0) THEN { ... } // boolean XOR
int32 masked = flags BAND 0x0F // bitwise AND
int32 flipped = BNOT flags // ones-complement (unary)
int32 hi = value LSHIFT 4 // logical left shift (zero-filled)
int32 lo = value RSHIFT 4 // logical right shift (zero-filled)
int32 signed = value ASHIFT 4 // arithmetic right shift (sign-filled)
int32 rot = value LROTATE 8 // rotate left
Rationale. Writing the bitwise and shift operators as keywords keeps them visually distinct from the arithmetic operators and removes the precedence guesswork that the C-style symbols invite.
(c.iv) Rule. A shift count must lie in [0, W), where W is the declared bit width of the shifted operand — int8 is 8, int32 is 32, uint64 is 64. Shifting significant bits off the end is legitimate and untouched; it is the count that is policed. A count the compiler can prove out of range is a compile error (E2130). A count it cannot prove is checked at runtime and raises a MathError — a PANIC, so it unwinds and FINALLY/CLEANUP run — rather than producing an undefined result. A count the compiler proves in range is emitted with no check at all. Separately, a bare integer literal shifted by a count that is not a provable constant is a compile error (E2131). A bare literal is int32, so 1 LSHIFT p silently shifts at 32-bit width no matter how wide its surroundings are; the literal must be given an explicit type.
Example.
int32 a = 5
int32 b = a LSHIFT 40 // E2130 — 40 >= 32, the width of int32
int8 c = 5
int8 d = c LSHIFT 10 // E2130 — 10 >= 8, the width of int8
int64 e = 5
int64 f = e LSHIFT 40 // fine — 40 < 64
uint64 mask = 1 LSHIFT p // E2131 — the literal `1` is int32, so this shifts at 32-bit
// width even though the target is 64-bit
uint64 one = 1
uint64 ok = one LSHIFT p // correct — the operand is genuinely 64-bit (count checked
// at runtime, since `p` is not provably in range)
Rationale. C leaves an over-width shift undefined, and a language whose floor is "memory safe — no crashes" (I.A) cannot inherit that: an under-specified shift is how a corrupted control byte became an infinite loop. The rule follows the same prove-or-check discipline as the array bounds check and HOTLOOP (I.H.iii(f)) — prove it safe and pay nothing; where that cannot be proven, a runtime check appears — with one step further: a shift proven wrong refuses to compile. The width is the operand's declared width rather than C's promoted width because that is what a reader means: you cannot shift a value by more than its own size. E2131 exists because the bare-literal case is invisible — the expression looks 64-bit and is not.
(c.v) Rule — mixed-sign integers. A comparison between a signed and an unsigned integer compares their mathematical values. -1 < 1u is TRUE in Envzn, where C's usual arithmetic conversions turn the -1 into the unsigned maximum and make it FALSE. The verdict is settled in three steps, for a signed operand against an unsigned one: if the signed operand is negative, it is the smaller, and the unsigned operand is never read; if the unsigned operand exceeds the signed type's maximum, it is the larger; only otherwise is the unsigned operand converted into the signed type, where the comparison is exact. All six operators (== != < <= > >=) and both operand orders read off that one three-way verdict. Mixed-sign + - * follows the same principle: the result is computed in a representation wide enough to hold the exact value, then checked against the destination's declared range, raising the MathError PANIC of (a.iii) if it does not fit. Neither a mixed-sign comparison nor mixed-sign arithmetic ever reinterprets a bit pattern.
Example.
int32 delta = -1
uint32 count = 1
IF delta < count THEN { printline("true in Envzn") } // C says FALSE: -1 becomes 0xFFFFFFFF
int64 offset = -5
uint64 size = 3
int64 sum = offset + size // -2, computed exactly
uint64 bad = offset + size // MathError — -2 does not fit uint64
Rationale. C's rule is not an edge case at the end of a range: it inverts the answer over half the input domain, silently, with no warning at -Wall and nothing in the emitted code to look at. Go and Rust avoid it by refusing to compare the two types at all, which pushes a conversion — and its own chance of error — onto every call site. Envzn gives the comparison its mathematical meaning instead, the intuitive answer at the cost of a few instructions the compiler places inward (I.A). The implementation is the kernel's EV_intsign_native family, checked against an exhaustive oracle (kernel/tests/native_tests/intsignOracle.c).
(d) Rule. Arithmetic and comparison are defined on the numeric primitives, on String for equality and ordering, and on any user-defined type that opts in by implementing the operator interfaces. A type opts in one of two ways, and both keep an operator traceable to a named, greppable method — an operator never dispatches to something a reader cannot find by name.
Interface derivation is the default: implement one or more of the four reserved interfaces Equatable, Comparable, Arithmetic, and Multiplier, and the compiler derives the operators from the interface methods. The interfaces and the derivation are described in I.K.iv.
A direct OPERATOR declaration is the alternative, for a type whose operator cannot be expressed as an interface method. The declarable set is +, -, *, /, ~/, ^, <, >, <=, >=, [] and []=: [] is the read recv[i], []= the write recv[i] = v, declared beside it by a type whose write differs from an assignment through the read (an array that grows to the index written, I.J.i). Any CLASS or PRIMITIVE may declare one, and the compiler honours it at every use; a class declaring one is valid for that operator, and declaring OPERATOR < alone is enough for all four orderings — the compiler derives >, <= and >= from it, so a single method carries the ordering logic. % and the unary operators are not declarable (E2061), and ==/!= on a class stay reserved to Equatable's ->equals() (E2069).
The direct form exists because a partial operator cannot be an interface method. Money's ordering has no answer across currencies, so it needs two doors onto the same comparison: a < b answers boolean and PANICs on a mismatch, while a->isLessThan(b) returns a pipe-XOR (boolean | STATUS) the caller can handle. Comparable's isLessThan returns a bare boolean, and a pipe-XOR cannot be the result of an operator sitting in an IF, so the interface route cannot express the recoverable door. It is the same reason Money implements neither Arithmetic nor Multiplier: those interfaces presume total operations, and adding USD to EUR is not one. Applying an arithmetic operator to a char — other than the offset and distance shapes I.D.i(b.ii) admits — or any operator to an object that does not implement the relevant interface, is a compile error.
Example.
// ROUTE 1 — interface derivation, for a TOTAL operator.
VALUE CLASS Meters IMPLEMENTS Cloneable, Comparable[Meters], Equatable[Meters] {
float64 length
}
IF m1 < m2 THEN { ... } // derived from Comparable.isLessThan()
boolean same = m1->equals(m2) // Equatable.equals()
// ROUTE 2 — a direct `OPERATOR`, for a PARTIAL one. Money's ordering has
// no answer across currencies, so it needs both doors onto the same comparison.
VALUE CLASS Money IMPLEMENTS Cloneable {
decimal128 value
CurrencyCode code
OPERATOR <(Money other) RETURNS boolean { // the bare door
IF .code != other.code THEN {
PANIC MathError("Money: cannot order different currencies")
}
RETURN (.value < other.value)
}
METHOD isLessThan(Money other) RETURNS (boolean r | STATUS s) { // recoverable
IF .code != other.code THEN {
s = FAILURE("Money: cannot order different currencies")
RETURN (s)
}
r := .value < other.value
RETURN (r)
}
}
IF m1 < m2 THEN { ... } // PANICs on a currency mismatch
IF m1->isLessThan(m2) THEN { boolean r := $= } // handles it instead
ELSE { printlineErr($!) }
// `operator <` alone is enough — `>`, `<=` and `>=` are derived from it.
char c1 = 'a'
IF c1 < 'z' THEN { ... } // ERROR — comparison operator applied to a char
Rationale. Both routes keep every operator traceable to a greppable method rather than to opaque overload syntax, and a type that opted into neither gets a clear compile error (E2060) instead of a silent surprise. The direct route exists because an interface method cannot express a PARTIAL operator: Comparable.isLessThan returns a bare boolean, so it has no way to say "these two are not comparable" — and a pipe-XOR return, which does, cannot be the result of an operator sitting in an IF. Deriving the three remaining orderings from < keeps one method carrying the ordering logic, so a partial-order check cannot drift between four copies.
A class instance is built with CREATE; the concrete class name appears only when the compiler cannot infer it.
(a) Rule. A class instance is constructed with the CREATE keyword, which allocates the instance on the heap, stores an owning handle in the receiving binding, and calls the matching INIT. When the receiving binding's type is a concrete class, the class name is inferred and not repeated — Circle c := CREATE(5.0). When the receiving binding's type is an interface or an abstract class, the concrete class name is required after CREATE — Drawable d := CREATE Circle(5.0). The compiler cannot otherwise know which implementation to build.
Example.
Circle c := CREATE(5.0) // concrete type inferred — class name not repeated
Drawable d := CREATE Circle(5.0) // interface/abstract LHS — concrete class required
Rationale. When the binding's type already fixes the class, repeating it is noise. When the binding is an interface or abstract class, the compiler genuinely cannot pick an implementation, so the concrete name is required rather than guessed.
(b) Rule. When the receiving binding's type is a GROUP, CREATE is a compile error: a group has no fields or methods, so there is nothing to construct. A group binding is assigned a concrete value directly. CREATE appears only on the right-hand side of a typed declaration; passing a bare CREATE(...) as a call argument is a compile error, and the instance is given a name first.
Example.
Color col := CREATE(...) // ERROR — a GROUP has nothing to construct
draw(CREATE Circle(5.0)) // ERROR — bare CREATE as a call argument
Circle c := CREATE Circle(5.0) // name the instance first ...
draw(c) // ... then pass it
Rationale. A group carries neither fields nor methods, so there is nothing to allocate or initialize. Confining CREATE to a typed declaration means every constructed instance is named at birth, which keeps ownership visible rather than buried inside an argument list.
A method is called with -> on a receiver; the return shape determines how the call is consumed.
(a) Rule. A method is called with ->, on a receiver. Inside a class body, a bare method name followed by an argument list is an implicit self-call: validate(x) within a method of the class is exactly SELF->validate(x). Where a bare name could resolve either to a class method or to a module-level function, the method wins, and the function is reached by its module-qualified name. Cross-module calls use the same -> on a handle whose declared type carries a module qualifier; I.N gives the resolution rules.
Example.
METHOD process(int32 x) RETURNS STATUS {
validate(x) // implicit self-call — exactly SELF->validate(x)
...
}
person->getName() // explicit receiver
logger->write(msg) // cross-module call — resolution rules in I.N
Rationale. Inside a class the receiver is almost always self, so requiring SELF-> on every internal call would be noise. The method-wins rule means an internal call never silently binds to a same-named module function, and the module-qualified name is always available when the function is what was meant.
(b) Rule. A method's return shape determines how a call is consumed. A method returning a single value yields that value as an ordinary expression. A method returning several values with the comma shape, RETURNS (T a, STATUS s), populates every slot. The call is consumed by an assignment line that names a receiver for each. A method returning the pipe-XOR shape — RETURNS (T t | STATUS s) — populates exactly one slot, and the call is consumed by an IF or WHILE whose condition is the call; I.M describes that consumption form and the $= and $! tokens that read its slots.
Example.
int32 n = counter->value() // single value — ordinary expression
String data, STATUS s := readFile(path) // comma shape — every slot receives a name
IF q->dequeue() THEN { Token t := $RETURNED } // pipe-XOR — the call IS the condition
ELSE { printline($!) } // $= reads the value slot, $! the fail message
Rationale. Matching the consumption form to the return shape makes the shape self-documenting. A comma return populates every slot, so it is multi-assigned; a pipe-XOR return populates exactly one, so it is consumed as a condition that also selects the live slot.
(b.i) Rule. A return value is discarded deliberately and visibly with the marker $?. $? := call() drops a single return, and a $? slot drops one position of a multi-value return — String data, $? := readFile(path) keeps data and discards the STATUS. Because $? marks a value flowing out to the caller, it is valid only in return position. Writing it as a call argument (foo($?), E1136) or as a parameter name (METHOD foo(T $?), E1137) is a compile error: a don't-care is meaningful only for an output, never for an input the callee relies on.
Example.
$? := call() // drop a single return, visibly
String data, $? := readFile(path) // keep data, discard the STATUS slot
foo($?) // ERROR (E1136) — $? as a call argument
METHOD foo(T $?) // ERROR (E1137) — $? as a parameter name
Rationale. Discarding a result silently hides that a value was produced and ignored; the $? marker makes the discard visible. It is output-only because a don't-care is meaningful for a value flowing out, but an input the callee relies on can never be a don't-care.
(b.ii) Rule. (Requiring every non-void return to be consumed or explicitly $?-discarded is reserved and not yet enforced — a bare fire-and-forget call currently compiles.) ($_ is a separate token)
Rationale. The enforcement is specified ahead of implementation so the document is stable when the gap closes; $_ is called out here only to keep it from being confused with the $? discard marker — the two remain distinct even though $_ now has no form of its own.
Every lambda is announced by LAMBDA; its form follows from its body; a V1 lambda is non-escaping.
(a) Rule. Every lambda is announced by the LAMBDA keyword. There is no implicit-lambda form anywhere in the language: a bare brace block, or a parenthesized parameter list, is not treated as a lambda unless LAMBDA precedes it. The rule holds uniformly at every call site, assignment, and constructor argument.
Example.
LAMBDA x: x + 1 // a lambda — announced by LAMBDA
{ x + 1 } // NOT a lambda — a bare brace block is never a lambda
(x): x + 1 // NOT a lambda — a bare parameter list is never a lambda
Rationale. The keyword exists so that a reader never has to infer, from punctuation alone, that a fragment of code is a deferred computation rather than an immediate one.
(b) Rule. A lambda takes one of four forms, and the form follows from the body. The expression form is a single expression after a colon, and its value is the result — LAMBDA x: x + 1, or with several parameters LAMBDA acc, x: acc + x. Its parameter list may optionally be parenthesized, with no change of meaning. The block form is a brace-delimited sequence of statements with an explicit RETURN, and it requires its parameter list to be parenthesized so that the opening brace is unambiguously the body. The no-parameter form serves concurrent-task bodies and other zero-argument callbacks, written either as a bare LAMBDA: colon-block or as LAMBDA(). A lambda's parameter and return types are inferred from the signature it is passed to; where that inference is ambiguous, the lambda is assigned to a typed local first. A block-form lambda has exactly one RETURN.
Example.
LAMBDA x: x + 1 // expression form
LAMBDA acc, x: acc + x // expression form, several parameters
LAMBDA (x): x + 1 // expression form, parameters optionally parenthesized
LAMBDA (a, b) { RETURN (a + b) } // block form — parenthesized params, no colon before the brace
LAMBDA: { doWork() } // no-parameter form (colon-block)
LAMBDA() // no-parameter form (empty parens)
Rationale. Parenthesizing the block form's parameter list is what lets the opening brace be read unambiguously as the body rather than as part of the parameters. The expression form needs no such disambiguation, so its parentheses are optional.
(b.i) Rule. Capture is decided by context. Within a single task a lambda may capture any in-scope variable as a non-owning observation, the original owner remaining responsible for cleanup. A lambda used as the body of a CONCURRENT { … } task, or sent through a Channel, may not capture a caller-scoped variable non-owningly: it may reference only what it owns outright. I.L explains that restriction in full.
Rationale. Within one task the owner outlives the lambda, so a non-owning capture is safe. Across tasks the owner may not, so an escaping lambda must own what it references. The full concurrency rules are in I.L.
(c) Rule. A lambda is also a value with a type, and a method declares that it accepts one by naming LAMBDA as a parameter type — METHOD map(LAMBDA transform) RETURNS (…). A V1 lambda is non-escaping. It may be passed into a method and invoked there, but it may not be stored in a field, returned, or otherwise outlive the call that received it. The canonical use of the form is the higher-order collection surface. Array[T] exposes ->map(LAMBDA transform), ->filter(LAMBDA predicate), and ->reduce(seed, LAMBDA combine), each applying its lambda to the elements in turn (I.J.iii).
Example.
METHOD map(LAMBDA transform) RETURNS (Array[T]) // LAMBDA as a parameter type
Array[int32] doubled := nums->map(LAMBDA x: x * 2)
Array[int32] evens := nums->filter(LAMBDA x: x % 2 == 0)
int32 sum = nums->reduce(0, LAMBDA acc, x: acc + x)
(c.i) Rule. Status: shipped in V1. A method may declare a LAMBDA parameter and invoke it in its body, and the higher-order collection surface built on that is live — Array[T]'s ->map, ->filter, and ->reduce are ordinary pure-Envzn loops over an invoked lambda. What remains deferred is the escaping lambda of (d): one stored in a field, returned, or otherwise outliving the call that received it. The shape specified here is the intended one, recorded ahead of the implementation per I.A; the document will not change when the gap closes, only the compiler will.
Rationale. Confining V1 to the non-escaping lambda is what keeps capture analysable: a lambda that cannot outlive its call site can borrow from the caller's scope without an ownership question, which is exactly the guarantee (e) relies on.
Positional composition with ->format(...) on a format-string literal; $1–$9 placeholders, argument auto-conversion, and per-placeholder format specs.
(a) Rule. Positional string composition is done with the ->format(...) method, called on a format-string literal. Inside a format string the placeholders $1 through $9 are active and are filled, in order, by the method's arguments; $$ produces a literal dollar sign, and $: a literal colon. A : directly after a placeholder opens that placeholder's format spec ($1:>8), so a colon meant as text right after a placeholder is written $: — ("$1$: $2"), ("$1$://$2$:$3"); a : there that opens no spec is E8022, never a silently swallowed character. This is the only context in which $ carries meaning — in an ordinary string literal it is always a literal character. Because $9 is the last placeholder, a format call takes at most nine arguments: a tenth could never print, and passing one is E8023 at the call site. + is not defined on String: "Hello, " + name is a compile error, exactly as "Hello, " - name is. Every composition, of two pieces or many, is written with ->format(); text that is built up in steps is accumulated in a DynamicString.
Example.
String msg := ("Processing item $1 of $2")->format(current, total)
String greet := ("Hello, $1")->format(name) // a two-part join is a format too
String bad := "Hello, " + name // ERROR — `+` is not defined on String
String price := ("Cost: $$$1")->format(amount) // $$ → literal '$', then $1 fills
Rationale. Text has no arithmetic. A + that joined strings would promise a - that has no meaning, and an operator that works in one direction only is an asymmetry a reader has to memorise — so there is none. ->format() is the one way to compose text from parts: it allocates once, it keeps the template visually separate from the values, and it reads in a single scan. $ carries meaning only inside a format string, so an ordinary literal never needs escaping.
(b) Rule. Arguments are converted on the developer's behalf. A ->format(...) argument may be of any primitive type — the integer and float families, number, complex, decimal128, boolean, char, binary — or a String, DynamicString, ByteBuffer, DynamicByteBuffer, a character array, or any class, interface, value class or FOREIGN_TYPE value. The compiler builds one kernel FormatArgument per argument at the call site, inside the call's own expression, so the developer never threads a value through an explicit (value INTO String) conversion first. A scalar or a 16-byte value is copied into it, keeping its source width, so an int8 and a float32 print as written; a text value or an object is borrowed, never copied, so the call copies no argument. An integer literal is an int64 and a float literal a float64 — the kind its digits name, never the narrowest one it would fit. A binary byte and a ByteBuffer render as space-separated uppercase hexadecimal by default — "DE AD BE" — under the rules of the binary column of I.D.vi. A character array (an error's message) renders as the String its INTO String operator makes. An object renders through the kernel interface Formattable (METHOD toString() RETURNS String): the test is made on the object, at run time, so an interface-typed handle whose object implements Formattable renders through it. Any other object renders as [??] and the call site surfaces W10090, because the argument's type does not implement Formattable; a handle whose value is EMPTY renders as the literal "EMPTY". A value class's type is exact, so it is decided at the call site: one that implements Formattable renders through its toString(), any other as [??] with W10090. A FOREIGN_TYPE value is a C pointer the runtime cannot read: it is never borrowed, renders "EMPTY" when null and [??] otherwise. An array renders [??]. An opaque value with no recognizable carried type renders as "??". A FormatArgument may borrow, so it is confined to the call that built it — the element of a FormatArgument... parameter, or a REFERENCE FormatArgument / REFERENCE FormatArgument[] renderer parameter; anywhere else (a local, a field, a return) is E8024.
Example.
String s := ("count=$1 ready=$2 tag=$3")->format(n, isReady, byteBuf)
// n rendered by its numeric type, isReady as boolean, byteBuf as "DE AD BE" (uppercase hex)
String t := ("point = $1")->format(p) // p's class IMPLEMENTS Formattable: its toString()
String u := ("handle = $1")->format(maybeNull) // an EMPTY class handle renders as "EMPTY"
Rationale. Auto-conversion at the call site removes the boilerplate of a per-argument INTO String step and keeps the template readable. Borrowing rather than copying keeps a format call as cheap as the values it prints, and confinement is what makes the borrow safe: the argument cannot outlive the call it was built for. Formattable names the contract a type opts into, rather than inferring it from a method that happens to be spelled toString.
(c) Rule. Each placeholder may carry a format spec — $N:<spec> — that adjusts how the value is rendered. The spec mirrors Python's format() mini-language: an optional <fill><align> pair, then an optional sign character, an optional minimum width, an optional grouping separator, and an optional type letter. The grouping separator is , or _, inserting a break every three digits for decimal and every four for the radix bases. The separators go into the digits and the width is then applied to the result, so they count toward the width and a zero-filled field carries them among its zeros; padding itself does not re-group. The integer-base type letters — :d, :x, :X, :o, :b — apply both to the integer-family arguments and to the binary containers (binary, ByteBuffer, DynamicByteBuffer). For an integer they choose decimal, lower-case hex, upper-case hex, octal, or binary digits. For a byte container they render every byte in that base, packed without the default inter-byte spaces. :s is the universal "default render" letter and accepts every argument shape. Width is a minimum, not a cap, for numeric renders; a String whose rendered length exceeds the requested width is truncated with ... when width ≥ 6. The grammar of the spec is given in (d), the type letters in (e), the width and sign rules in (f), and truncation and the special renders in (g). A type letter incompatible with its argument's type — :x on a float, say — is diagnosed E8020 by the compile-time linter the compiler runs over every literal template.
Example.
int32 current = 3
int32 total = 10
String msg := ("Processing item $1 of $2")->format(current, total)
String greet := "Hello, " + name // acceptable — a trivial two-part join
String report := ("Error at $1:$2 — $3")->format(filename, lineNum, errorMsg)
int32 v = 255
float64 pi = 3.14
String hex := ("color = #$1:0>6X")->format(v) // "color = #0000FF"
String padded := ("[$1:>8] = [$2:<+8]")->format("pi", pi) // "[ pi] = [+3.14 ]"
Rationale. Mirroring Python's mini-language means the spec grammar is already familiar to most readers, so the one piece of punctuation-dense syntax in the language is the piece a developer is most likely to already know.
(d) Rule. The spec is parsed by position, each element optional:
$<N>[:<spec>]
<spec> := [<fill> <align>] [<align>] [<sign>] [<width>] [<grouping>] [<type>]
<fill> := any single Unicode code point (default: U+0020 space)
<align> := '<' | '>' | '^' // left / right / center
<sign> := '+' | '-' // default '-' — show only negatives
<width> := one or more decimal digits
<grouping> := ',' | '_' // separator every 3 digits decimal, 4 for x/X/o/b
<type> := 'd' | 'x' | 'X' | 'o' | 'b' | 's'
A <fill> is recognized by lookahead: if the spec's second character is one of <, >, ^, the first character is the fill. Otherwise the spec begins at the optional <align>. Grouping is applied to the digits before the width, so the separators count toward the width; the padding that follows does not re-group, which makes 1234 at 0>9,d render 00001,234. V1 fixes the group at three digits for decimal and four for the radix bases.
Example.
"$1:5d" // no fill, no align, width 5, decimal
"$1:>5d" // no fill, right align, width 5, decimal
"$1:0>5d" // fill '0', right align, width 5, decimal
Rationale. One character of lookahead is all the fill rule needs, because an alignment character can never itself be a fill: a spec that means to pad with > writes it as the fill and the alignment after it. Fixing the grouping sizes rather than making them configurable keeps the spec a fixed grammar a reader can learn once.
(e) Rule. Six type letters are defined.
| Letter | Applies to | Effect |
|---|---|---|
d |
int family, char, binary, ByteBuffer, DynamicByteBuffer |
decimal — for char the code point; for a byte container each byte in decimal, space-separated |
x / X |
int family, binary, ByteBuffer, DynamicByteBuffer |
hexadecimal, lower / upper case |
o |
int family, binary, ByteBuffer, DynamicByteBuffer |
octal |
b |
int family, binary, ByteBuffer, DynamicByteBuffer |
binary digits |
s |
any | generic — default-render, then apply width, align, and truncation |
| (none) | any | default render per (b), then width and align, without truncation |
Applied to a byte container, a type letter renders without inter-byte separators — :x over the bytes [0xDE, 0xAD, 0xBE] yields "DEADBE", where the default render yields "DE AD BE".
Rationale. :s exists so a developer who wants only the width and alignment tools need not know which default render applies to the argument's type.
(f) Rule. <width> is a minimum rendered length, counted in Unicode code points rather than bytes; a shorter render is padded to width with <fill>, and a width of 0 behaves as no width at all. Default alignment follows the argument's category. Numbers align right: the integer and float families, binary, ByteBuffer, DynamicByteBuffer. Everything else aligns left: String, boolean, char, opaque, and a class rendered through toString(). + forces a sign character on positive values, - is the default and shows a sign only on negatives, and the sign applies to int8…int64 and float32/float64. On the unsigned family (uint8…uint64) a + spec is a no-op, as it is on binary, which carries no sign at all.
Rationale. Right-aligning numbers and left-aligning text is what makes a column of output line up the way a reader expects, so the default matches the common case and the explicit alignment characters cover the rest. A + on an unsigned value is a no-op rather than an error because the value is never negative, and printing a sign there would mislead.
(g) Rule. When a <width> is given and the rendered value is longer than it, the output is truncated. At width 6 or greater it is the first <width> characters followed by ..., a final length of <width> + 3. Below width 6 it is the first <width> characters with no ellipsis. Truncation is defined for every argument type, though for numeric renders the case is rare. Three renders are produced before any width or alignment applies: a class-typed argument that is EMPTY renders the literal "EMPTY", an opaque value with no recognizable carried type renders "??", and an argument that is not Formattable (or a non-null FOREIGN_TYPE value, or an array) renders "[??]".
Rationale. Below width 6 an ellipsis would consume half the field or more, so the truncation drops it rather than spend the space saying that space ran out. The three placeholder renders are produced first so that width and alignment treat them like any other text — an EMPTY handle in a right-aligned column lines up with the values around it.
Example.
("[$1:>10]")->format(myEmptyHandle) // "[ EMPTY]" — EMPTY rendered, then right-aligned
("$1:10")->format("HelloWorldGoodbye") // "HelloWorld..." — width 10, so ellipsis is added
("$1:4")->format("HelloWorldGoodbye") // "Hell" — width below 6, no ellipsis
Statements, executed for their effect rather than a value. Centred on the three assignment operators — = copy, := move, =@ reference — and the binding shape each one may introduce.
(a) Rule. A statement is executed for its effect rather than for a value it produces. Statements end at a newline (as I.C establishes) and run in the order written. The principal statement is assignment.
Example.
count = 0 // executed for effect, ends at newline
System->exit(0) // a statement; the value, if any, is discarded
Rationale. Distinguishing statements from expressions keeps the reading model simple: an expression names a value, a statement makes something happen. Assignment repays careful reading most, because the operator chosen is itself part of the statement's meaning.
(b) Rule. Envzn has three assignment operators, and each has exactly one meaning: = binds a value, := binds ownership, and =@ binds a reference. The operator is not shorthand for something the left-hand side already implies; it is itself part of the statement's identity, and changing it is a visible semantic change.
| Operator | Meaning |
|---|---|
= |
Value assignment. Bind the left-hand side to a value — never to ownership of an object. For a primitive, a value-class, a STATUS, or an enum this is a bit copy of any compatible expression. For a String the sole permitted right-hand side is a string literal (String is the one object with a literal form, and it is never EMPTY). For any other class type the sole permitted right-hand side is EMPTY, which holds no object and so transfers no ownership. |
:= |
Ownership. Bind the left-hand side as the new owner of an object, by constructing it (CREATE), copying it (->clone()), or moving it from another owner. A move leaves the source unusable: a moved-from field becomes EMPTY, or, when it is always present, moved out until it is written again (I.I.i(e)); a moved-from local or parameter is poisoned, and any later read of it is a compile error. No clone is ever inserted implicitly. |
=@ |
Reference. Establish a non-owning reference to a place expression. The binding is subject to the reference checker's lifetime and aliasing rules, given in I.I. |
Example.
int32 count = 0 // = value: bit copy of a primitive
String name = "Ada" // = value: String's sole RHS is a literal
Widget w = EMPTY // = value: the only class RHS under = is EMPTY
Widget w2 := CREATE Widget(5) // := ownership: construct a new owner
Widget w3 := other->clone() // := ownership: copy is an owning bind
REFERENCE Widget r =@ w2 // =@ reference: non-owning view of a place
Rationale. One operator, one meaning, keeps the cost of an object visible in the source that causes it. A reader never has to infer from the left-hand side's type whether a line copies a value, transfers ownership, or takes a borrow.
(c) Rule. The operator and the shape of the left-hand side must agree, and the agreement is enforced. =@ requires a REFERENCE or MUTABLE REFERENCE left-hand side; using it with an owning left-hand side is a compile error. = and := require an owning left-hand side; using either with a reference left-hand side is a compile error.
Example.
REFERENCE Widget r =@ w // =@ needs a reference LHS — ok
Widget owned =@ w // ERROR — =@ with an owning LHS
Widget owned := CREATE Widget(1) // := needs an owning LHS — ok
REFERENCE Widget r2 := CREATE Widget(1) // ERROR — := with a reference LHS
Rationale. The left-hand side's shape and the operator declare the same fact: whether this binding owns or observes. Requiring them to agree makes a mismatch a caught error rather than a silent contradiction the reader must reconcile.
(c.i) Rule. The right-hand side shapes follow from the operator's meaning. A = takes a value, never ownership of an object. That is a literal or computed expression for a primitive, value-class, STATUS, or enum; a string literal for a String; and EMPTY for any other class type. Every other class right-hand side under = is a compile error: a CREATE, a ->clone(), a method result, or a bare variable-to-variable copy. Constructing, cloning, copying, or moving an object is ownership, and the language refuses to launder it through the value operator. String reports this as E2020, every other class as E3023.
Example.
int32 n = a + b // = value: a computed primitive expression
String greeting = "hello" // = value: a String literal
Widget w = EMPTY // = value: EMPTY for any other class
String s = other->clone() // ERROR E2020 — clone is ownership, not a value
Widget w2 = CREATE Widget(1) // ERROR E3023 — CREATE is ownership under =
Widget w3 = existing // ERROR E3023 — variable-to-variable copy is a move
Rationale. Ownership operations look like values only if you let them. Forcing a CREATE, ->clone(), or copy to announce itself with := keeps every allocation and every ownership transfer visible at the line that causes it, and E2020/E3023 name the laundering attempt precisely.
(c.ii) Rule. A := takes exactly the ownership-bearing right-hand sides: a CREATE, a ->clone(), a method-call result, or an owning place expression. Each constructs or moves ownership. A =@ takes a place expression only: a variable, a field, an indexed access, or a method result that itself returns a reference. It never takes a literal, an arithmetic expression, or a method result that returns an owned value.
Example.
Widget w := CREATE Widget(5) // := construct ownership
Widget c := source->clone() // := copy is an owning bind
Widget m := factory->make() // := method result carrying ownership
Widget moved := oldOwner // := move from an owning place expression
REFERENCE Widget r =@ w // =@ a variable — a place expression
REFERENCE Widget f =@ w.child // =@ a field — a place expression
REFERENCE Widget e =@ arr[i] // =@ an indexed access — a place expression
REFERENCE Widget bad =@ CREATE Widget(1) // ERROR — =@ with a constructed value, not a place
Rationale. Each operator accepts only the right-hand-side shapes its meaning supports, so the operator alone tells the reader what class of thing follows: := an owning source, =@ a durable place to borrow from — never a temporary value that would dangle.
(d) Rule. A move from an owning place expression is where ownership visibly changes hands, so its outcome is stated precisely. When the right-hand side of a := is a field that owns its target, the move transfers ownership to the left-hand side and leaves the source field EMPTY. When it is a local or a parameter, the move leaves the source poisoned: the binding still exists, but any subsequent read of it is a compile error. A := whose right-hand side is a non-owning reference is itself a compile error. A reference does not own what it observes, so there is nothing for it to transfer. An indexed access is such a reference: a[i] names a slot the array keeps owning, so x := a[i] and a[k] := a[j] are the same error (I.J.i(d)). To take a copy from a reference, the developer writes it explicitly — DUPLICATE r, or r->clone() where the class implements Cloneable; the language never inserts a clone on the developer's behalf.
Example.
Widget taken := .child // move from an owning field
// → .child becomes EMPTY after this line
Widget moved := local // move from a local
printline(local->name()) // ERROR — local is poisoned; read after move
REFERENCE Widget r =@ source
Widget bad := r // ERROR — := from a non-owning reference
Widget copy := r->clone() // ok — explicit clone (class must be Cloneable)
Widget e := arr[i] // ERROR — arr[i] is a reference to arr's slot
Widget d := DUPLICATE arr[i] // ok — explicit copy of the element
Rationale. A move must leave no usable second handle to a single owner, so the source is neutralized. A field becomes EMPTY, since it may be re-used; a local or parameter is poisoned, since its lifetime is ending anyway. Refusing := from a reference, and never inserting a clone silently, upholds the principle that an allocation should be visible in the source that causes it. If a copy happens, ->clone() says so.
(e) Rule. A bare pair of braces inside a method body is an anonymous block — a scoping statement with no keyword and no name. Variables declared inside it go out of scope, and owned values are freed, at the closing brace. A RETURN inside an anonymous block returns from the enclosing method, not merely from the block; BREAK and CONTINUE still apply to the nearest enclosing loop. Anonymous blocks nest up to fifteen levels deep. An empty one is legal but draws a compiler warning, since an empty block is more often unfinished code than deliberate.
Example.
METHOD process() RETURNS STATUS {
{ // anonymous block — bounds a lifetime
Buffer scratch := CREATE Buffer(1024)
scratch->fill()
RETURN (SUCCESS) // returns from process(), not just the block
} // scratch freed here if we had not returned
{ } // WARNING — empty anonymous block
}
Rationale. The anonymous block is two tools at once. It bounds the lifetime of an owned value, or an iterator's mutation lock, precisely; and it groups the statements of one phase of a method under a visible boundary. Keeping RETURN, BREAK, and CONTINUE bound to the method and loop (not the block) means adding braces for scoping never silently changes control flow. The empty-block warning catches the common case where the braces mark work not yet written.
Branching and looping built to stay locally legible: the conditional headers, the conditional, the loops, FINALLY, MATCH, and conditional compilation.
(a) Rule. Control flow in Envzn is built to be locally legible. A reader can see where a condition ends and a body begins without holding the operator-precedence table in mind, and is nudged toward polymorphism when a tree of conditionals has grown deep enough to be hard to follow. The constructs below — the conditional, the loop family, the guaranteed-cleanup block, and the destructuring MATCH — all serve that goal.
Example.
IF x > 5 THEN { ... } // condition ends at THEN, body begins at {
MATCH shape { // destructuring — each arm BINDS
WHEN Circle c: { ... }
WHEN Square s: { ... }
}
Rationale. Local legibility is the through-line for the whole section. Every rule that follows spends exactly as much syntax as it takes to keep a header or a branch unambiguous to a reader scanning top-to-bottom, and no more.
(a) Rule. Every conditional keyword takes a condition between the keyword and the opening brace, and pairs it with a marker word that signals end of condition, start of body: IF and ELSE IF pair with THEN; WHILE and UNTIL pair with DO. The post-condition loops DO { … } WHILE and DO { … } UNTIL take no marker.
Example.
IF x > 5 THEN { ... }
WHILE i < n DO { ... }
DO { ... } WHILE (more) // the trailing keyword is its own marker
Rationale. The marker exists so that the parser, and the reader, can always find where the condition ends. The post-condition loops need no marker because their trailing keyword already is one.
(b) Rule. A condition is either simple or compound. A simple condition is a single boolean expression with no top-level boolean operator. It must be written either parenthesized, in which case the marker is optional, or with the marker word, in which case the parentheses are omitted. A bare simple condition with neither is a compile error. A compound condition joins two or more sub-expressions with a boolean operator; each sub-expression must be parenthesized, while the outer parentheses around the whole and the marker are both optional.
Example.
IF (x > 5) { ... } // simple, parenthesized — marker optional
IF x > 5 THEN { ... } // simple, marker form — parentheses omitted
IF x > 5 { ... } // ERROR — neither parentheses nor marker
IF (x > 5) AND (y < 0) { ... } // compound — each clause parenthesized
Rationale. Requiring one of the two disambiguators on a simple condition guarantees a unique end-of-condition token in every case. On a compound condition the per-clause parentheses already supply that boundary, so the marker and the outer parentheses become redundant and are optional rather than required. The rule asks for exactly as much punctuation as it takes to keep the header unambiguous.
(a) Rule. IF, with optional ELSE IF and ELSE branches, is the ordinary conditional. Nesting is permitted, but the compiler issues a warning past three nested IF statements.
Example.
IF (score >= 90) { grade = "A" }
ELSE IF (score >= 80) { grade = "B" }
ELSE { grade = "C" }
IF (a) { // depth 1
IF (b) { // depth 2
IF (c) { // depth 3
IF (d) { ... } // WARNING — past three nested IFs; likely a MATCH
}
}
}
Rationale. A conditional tree that deep is usually a MATCH that has not yet been recognized as one. The compiler flags it toward the clearer construct rather than forbidding it outright.
(a) Rule. Collection iteration is written with FOR … IN.
Example.
FOR item IN items { process(item) }
FOR order IN orders { process(order) }
Rationale. Envzn offers several loop forms because the cases genuinely differ, and the guiding rule is to use the form whose surface most nearly matches the intent. The iterator model and the mutation lock that underpin collection iteration are described with the aggregates in I.J.
(b) Rule. Counted iteration has two forms. The range form — FOR i = 0 TO 10, optionally with STEP — is preferred for a simple constant range; TO INCLUDES its bound; UNTIL STOPS BEFORE it. FOR i = 1 TO 6 runs six times and ends with i == 6; FOR i = 1 UNTIL 6 runs five times and ends with i == 5. The bound of an UNTIL is a value the loop never takes. This is the same pairing Kotlin and Scala use for the same two words, and it is what makes FOR i = 0 UNTIL a.length walk an array exactly — the dominant idiom, and the reason the exclusive form carries the shorter, commoner spelling. STEP defaults to +1 and accepts a negative value for a countdown. The C-style form, FOR int i = 0; i < total; i = i + 1, is for cases where the condition or the step is more complex than a constant range allows.
Example.
FOR i = 1 TO 6 { print(i) } // 1 2 3 4 5 6 — six times, INCLUDES 6
FOR i = 1 UNTIL 6 { print(i) } // 1 2 3 4 5 — five times, STOPS BEFORE 6
FOR i = 0 UNTIL a.length { print(a[i]) } // walks the array exactly; a.length is never an index
FOR i = 0 TO a.length { print(a[i]) } // WRONG — runs one past the end
FOR i = 0 TO 10 STEP 2 { print(i) } // 0 2 4 6 8 10 — STEP, still inclusive of 10
FOR i = 10 TO 0 STEP -1 { print(i) } // negative STEP counts down
FOR int i = 0; i < total; i = i + 1 { ... } // C-style form — the only place a bound is written out
Rationale. The range form covers the common case in the fewest tokens; the C-style form is the escape hatch for a header a constant range cannot express.
(b.i) Rule. The C-style header carries the only semicolons in the language. Its three clauses and two semicolons must occupy the single line of the FOR keyword; splitting the header across lines is a parse error.
Example.
FOR int i = 0; i < total; i = i + 1 { ... } // three clauses, two semicolons, one line
FOR int i = 0; // ERROR — header split across lines
i < total;
i = i + 1 { ... }
Rationale. Keeping the three-clause header on one line means the reader never hunts across lines for a stray semicolon, and confines the language's only semicolons to a single, recognizable place.
(c) Rule. When no loop variable is needed at all, REPEAT n { … } runs its body a fixed number of times, and REPEAT { … } with no count runs it indefinitely — the bare infinite loop, left only by BREAK, RETURN, or PANIC. Dropping the count reads as "repeat indefinitely", so no separate keyword is spent on it, and writing a condition that is constantly true (WHILE TRUE) is a style warning that points here instead. The pre-condition loops WHILE and UNTIL test before each iteration, UNTIL being a readable spelling of WHILE NOT. The post-condition loops DO { … } WHILE and DO { … } UNTIL test after, and so always run at least once.
Example.
REPEAT 3 { printline("tick") } // body runs exactly 3 times, no loop variable
REPEAT { IF done() THEN { BREAK } } // no count — runs until something leaves it
WHILE i < n DO { i = i + 1 } // tests before — may run zero times
UNTIL done DO { step() } // UNTIL c ≡ WHILE NOT c
DO { attempt() } WHILE (retries > 0) // tests after — always runs at least once
Rationale. Each form names its intent on the surface: a fixed count, a guard checked first, or a body that must run once before its guard is checked.
(d) Rule. The LOOP keyword has exactly one form: collection iteration that carries the element's position alongside the element. It is written LOOP name IN collection WITH INDEX index { … }, and both clauses are mandatory — a LOOP without WITH INDEX is a compile error, and so is WITH INDEX on any other loop keyword. name binds the element exactly as FOR … IN does, as a non-owning REFERENCE, and the collection is locked against mutation for the body. index binds the element's zero-based position as an int64 — the width of every count and extent in the language (it was int32 before). It is read-only: assigning to it is a compile error, because it is the loop's own state and a writable copy reintroduces the off-by-one this form exists to remove. Both names are scoped strictly to the loop block.
Example.
LOOP row IN orders WITH INDEX i {
IF i > 100 THEN { BREAK } // i — zero-based int64 position
process(row) // row — REFERENCE to the element
}
Rationale. Reading an element together with its position is the most common iteration need after plain traversal, and every language Envzn is measured against provides it. Without it the developer must hand-roll a counter beside the loop — the classic off-by-one site, and one the compiler cannot check. LOOP is the construct that makes the position a binding rather than a bookkeeping chore. This is why the choice between FOR … IN and LOOP is functional and never stylistic: if the position is needed, LOOP is the only construct that has it; if it is not, FOR … IN is the only construct that should be reached for.
(d.i) Rule. LOOP accepts exactly what FOR … IN accepts. Over an ordered collection the index is the element's position; over an unordered one it is the position in that traversal, which is well defined for the traversal but not stable across runs or implementations — a developer choosing to index an unordered collection has accepted that, and the compiler does not warn. The index always starts at 0 and increases by one per iteration, including when the body executes CONTINUE; BREAK ends the loop with the index at the element that triggered it.
Example.
LOOP name IN roster WITH INDEX i {
printline(("$1. $2")->format((i INTO String), name))
}
LOOP entry IN scores WITH INDEX position {
IF position == 0 THEN { CONTINUE } // skip the first; position still advances
tally(entry)
}
Rationale. Constraining LOOP to what FOR … IN already iterates keeps one iteration model rather than two. Declining to warn on an unordered collection matches the language's general posture: it reports what it can prove, and traversal order is the developer's to reason about.
(d.ii) Rule. LOOP is not a counter loop, and writing it as one is a compile error; counter loops use FOR. LOOP carries no iterator handle: a loop needing peek-ahead, conditional advancement, or explicit cursor control uses a kernel iterator directly, consumed through its pipe-XOR navigation in a WHILE (I.J).
Example.
LOOP i = 0 TO 10 { ... } // ERROR — LOOP is not a counter loop; use FOR
LOOP row IN orders { ... } // ERROR — LOOP requires WITH INDEX; use FOR … IN
// explicit cursor control — a kernel iterator, not LOOP
ReferenceIterator OF Order it := orders->iterator()
WHILE it->next() DO {
REFERENCE Order row =@ $RETURNED
process(row)
}
Rationale. Steering counter loops to FOR keeps each keyword to the one job its surface advertises. The iterator surface is already a first-class, fully expressive part of the language — next(), peek(), and skip() return the pipe-XOR shape that a WHILE consumes directly — so wrapping it in a second syntax would add a way to do something the language already does one way. (Earlier drafts specified a LOOP iterator-handle form exposing .item / .index / .hasNext as fields, and an anonymous LOOP $_ IN form. Both are withdrawn: the handle contradicted I.A.i(c.i)'s prohibition on phantom computed fields and named a kernel type, Iterator[T], whose surface is methods and carries no position; the $_ form never tokenized.)
(e) Rule. BREAK exits the innermost enclosing loop immediately and CONTINUE skips to its next iteration; both are valid in every loop form. A block or loop may additionally be given a name with the LABEL prefix — LABEL <name> <statement> — and BREAK <name> then exits that named block, while CONTINUE <name> begins the next iteration of that named loop. LABEL prefixes any loop form or a bare block: LOOP, REPEAT (counted or bare), all three FOR forms, WHILE, UNTIL, DO-WHILE, and { … }. Both jumps are lexical and structured: BREAK transfers only forward, to immediately after the named block's closing brace; CONTINUE transfers only backward, to the top of the named loop. The named label must lexically enclose the jump, control may never enter a block or move sideways, and no jump may leave the enclosing method. CONTINUE <name> requires the name to belong to a loop. A label's extent is the block it prefixes, but its NAME is unique within the class: the same name may not be used for two labels anywhere in one class file, even in different methods, and may not collide with an in-scope variable or parameter. Every scope the jump leaves is unwound exactly as an ordinary scope exit: each intervening local is destroyed in reverse declaration order, every CLEANUP runs, and a TRY being left runs its FINALLY first. BREAK <name> and CONTINUE <name> may not appear inside a FINALLY, and may not name a label outside an enclosing PARALLEL, CONCURRENT, task body, or LAMBDA.
Example.
FOR item IN items {
IF (item->isSentinel()) { BREAK } // exits this loop
IF (item->isSkippable()) { CONTINUE } // next iteration
process(item)
}
LABEL scan LOOP row IN grid WITH INDEX r {
FOR cell IN row {
IF cell->isBad() THEN { BREAK scan } // exits the LOOP
IF cell->isSkip() THEN { CONTINUE scan } // next row
}
}
LABEL attempt { // a named block, not a loop
IF NOT connect() THEN { BREAK attempt }
IF NOT auth() THEN { BREAK attempt }
send()
} // BREAK attempt lands here
LABEL outer FOR a IN xs {
PARALLEL { FOR b IN ys { BREAK outer } } // ERROR — crosses a PARALLEL boundary
}
Rationale. Exiting more than one level of nesting is a real need, and the alternative Envzn offered until now — a boolean threaded through the inner exit, the outer guard, and a post-loop test — smears one intent across three places the reader must reassemble. That is the opposite of control flow being visible on the page. LABEL is deliberately not a goto: both jump targets are block boundaries determined lexically, the compiler proves the target encloses the jump, and control can never enter a block or move sideways. Requiring the name to be unique class-wide, though the label's extent is only its own block, is a readability rule rather than a scoping necessity — searching a class for a label finds exactly one declaration, and no reader has to work out which one a jump means. This is the same capability Java, Rust, Swift, Go, Kotlin, Zig, and JavaScript provide, obtained without adding an unstructured jump to the language.
(e.i) Rule. For a single-statement body, the postfix shorthands read like English.
Example.
print(item) FOR item IN items // postfix FOR
x = x / 2 WHILE x > 1 // postfix WHILE
Rationale. When the body is a single statement, the postfix form puts the action first and the iteration second, reading as a sentence rather than a block.
(f) Rule. HOTLOOP is a modifier written immediately before a counted FOR (or a WHILE). It is a suggestion, not a promise: it asks the compiler to hoist the loop body's per-element array bounds checks into a single up-front range check per array, so the body's indexed reads run without a per-iteration bounds branch. It is not a request to skip checks — the memory-safety floor is never traded. The compiler proves every indexed access covered by the one hoisted check before it hoists anything, and the proof is all or nothing: if any access in the loop fails it, none is hoisted. A HOTLOOP the compiler cannot prove compiles and keeps every check — it is optimized exactly as the same loop written without HOTLOOP, and it is never an error. Why a HOTLOOP was not proven is the business of evc --explain (planned), not of a diagnostic. A HOTLOOP is provable only when four conditions hold together. The loop is a simple counted range, FOR i = 0 UNTIL n. The loop variable is not reassigned. The bound n is loop-invariant, since the C++ condition re-reads it each iteration. And every array subscript is an affine index in the loop variable — arr[i], or arr[c + i] with a loop-invariant c — over an array that is read-only in the body. Any write, reassignment, .field or method use, or call-argument use of the array could change its length and stale the hoisted check.
Example.
// BENEFICIAL — an offset slice: the bound `len` is NOT the indexed array's own
// length, so the compiler cannot correlate them and the ordinary loop keeps a
// per-element check. HOTLOOP hoists it to one `off + len <= key.length` check.
HOTLOOP FOR i = 0 UNTIL len {
h = (h BXOR (key[off + i] INTO uint64)) &* PRIME
}
// NO-OP — the bound IS the array's length, so the ordinary compiler already
// proves `arr[i]` in range and elides the check; HOTLOOP changes nothing here.
HOTLOOP FOR i = 0 UNTIL arr.length { sum = sum + arr[i] }
// NOT PROVABLE — `buf` is mutated in the body, so a hoisted check would be stale.
// It compiles, and every read keeps its check; `evc --explain` will say why.
// HOTLOOP FOR i = 0 UNTIL n { buf->clear() total = total + buf[i] }
Rationale. HOTLOOP earns its keep in exactly one shape: a loop whose bound is not the indexed array's own .length — an offset slice, a caller-supplied length, several arrays of differing lengths. There the ordinary optimizer cannot prove the relationship, so it keeps a bounds branch on every element. When the bound is the array's length the optimizer already elides the check, and HOTLOOP is a harmless no-op. A developer reaches for it only after the emitted code shows a per-element check that structure alone will not remove. Because the compiler proves the hoist rather than trusting the developer, a HOTLOOP can never read out of bounds. An out-of-range run panics with IndexOutOfBoundsError from the up-front check, before any element is touched. This is the I.A tie-break — the fast machinery (the proof and the hoisted check) lives in the compiler; the developer writes one readable keyword and the floor is kept. An unprovable HOTLOOP is silent rather than an error because the keyword is advice about speed, not a claim about correctness: the program is exactly as safe without the hoist, and refusing to build it would make a hint cost more than it can save. The proof lives in analyze/hotloop_diagnostics.py; the hoisted check and the unchecked reads it authorizes are the value-array .data()[i] lowering of I.J.i.
(f.i) Rule — HOTLOOP over an N-D array. HOTLOOP may also prefix the coordinate walk FOR (i, j) IN g (I.J.i(q.i)), and a hot counted FOR may read N-D subscripts. Over N-D, as in (f), HOTLOOP is a suggestion, not a promise: the compiler proves what it can and every read it cannot prove keeps its per-axis check — never an error, because memory safety is never the thing that gives. Inside FOR (c0, …) IN g, a read g[c0, …] of the walked array at exactly its own coordinates needs no check at all, provided the body cannot change g's shape (no reassignment, no method call on g, no passing it); writing a cell does not change a shape. In a counted loop, each coordinate must be affine in the loop variable or independent of it, and each gets one guard before the loop — the same proof the compiler applies to un-annotated loops automatically (analyze/loop_elision.py).
Example.
HOTLOOP FOR (i, j) IN g { total = total + g[i, j] } // no check: the walk's bounds ARE g's extents
HOTLOOP FOR j = 0 UNTIL g->dim(1) { t = t + g[0, j] } // one guard, on axis 0
HOTLOOP FOR i = 0 UNTIL n { t = t + g[i * 2, 0] } // not affine: keeps its check, compiles
Rationale. The 1-D HOTLOOP rejects what it cannot prove because it was written to earn a specific hoist the developer read off the emitted code. Over N-D the automatic proof already covers the coordinate walk and the common nests, so the annotation mostly states intent; making an unprovable one an error would punish the reader for naming a hot loop. The decision each N-D HOTLOOP receives is marked in the compiler (EXPLAIN-SITE) for a future --explain to report.
(f.ii) Rule — a fresh array filled in a counted loop. An append dst[dst.length] = e writes past the array's length, so it is not a bounds check the hoist of (f) can remove: it is a grow. The compiler removes it anyway, automatically and without HOTLOOP, when it can prove the write lands in storage that already exists. Four conditions must hold together. The loop is FOR i = 0 UNTIL n or the C-style FOR (int64 i = 0; i < n; i++) (++i and i = i + 1 also qualify), and the body does not assign i, pass it to a call, or mention n at all. dst is a local T[] of a primitive element, declared in the same block above the loop by CREATE(n) with the loop's own n, and untouched between the declaration and the loop. The append is a top-level statement of the body and the body's only mention of dst. And the body has no early exit. Then iteration i writes slot i of the storage CREATE(n) reserved, and the array takes its length, n, once when the loop ends. A loop that fails any condition keeps its grow-on-write append; it is never an error. Nothing about the result changes: a filled array has the same elements and the same length either way.
Example.
char32[] cps := CREATE(n)
FOR i = 0 UNTIL n { cps[cps.length] = src[off + i] INTO char32 } // filled: no grow per element
FOR i = 0 UNTIL n { IF ok THEN { cps[cps.length] = 0x20 } } // conditional: keeps its append
Rationale. Filling a fresh array is the most common loop that writes, and its per-element cost is the length test, the capacity test and the high-water bump the grow-on-write needs only because it cannot see that the loop count and the reservation are the same n. The compiler can see it, so the cost moves inward (I.A) and the reader writes the plain append. The proof is deliberately narrow — same block, same n, one write — because a wrong one is an out-of-bounds write, and the floor is never traded for speed.
(a) Rule. FINALLY is the optional trailing clause of a TRY (I.M.ii) — it is not a standalone method-level construct. When present it runs last on every exit path of its TRY: whether the TRY/RECOVER completes normally, a RECOVER handles a PANIC, or a PANIC unwinds through it.
Example.
TRY {
parse(handle)
}
FINALLY {
handle->close() // runs on both the normal and the unwinding exit
}
Rationale. Attaching cleanup to the TRY whose scope it guards keeps the intent local to the code that can fail. It also guarantees the cleanup runs on every way out of that scope.
(b) Rule. A TRY carries at most one FINALLY; placing a RETURN or PANIC inside it is a compile error.
Example.
TRY { work() } FINALLY { cleanup() } FINALLY { more() } // ERROR — a second FINALLY on one TRY
TRY { work() } FINALLY { RETURN (0) } // ERROR — RETURN inside FINALLY
Rationale. One cleanup block per TRY, with no exit of its own, keeps the guarantee simple to reason about. There is exactly one place cleanup lives for that scope, and it can never itself divert control.
(a) Rule. MATCH is the language's destructuring branch: exhaustive dispatch over a closed set of alternatives, binding whatever the alternative carries. Envzn has three closed sets, and MATCH is how each is taken apart. A GROUP (I.J.v) is a closed set of types — each WHEN names a member and binds the subject narrowed to it. A dev-defined ENUM (I.K.viii) is a closed set of cases — each WHEN names one case; a V1 enum case is a bare name and carries no payload, so the arm selects without binding. A STATUS (I.M.i) is a closed set of kinds — FAILURE / PARTIAL_SUCCESS bind the message and optional code. STATUS is not a special construct here: it is the built-in instance of the enum form, and it is the instance that carries a payload — a dev enum has no way to declare one in V1. There is no fallthrough between WHEN blocks.
MATCH is not a multi-way branch on open-ended values. A closed set is one the compiler can enumerate — a group's members, an enum's cases, a status's kinds. An int32, a char, or a String is not such a set, so MATCH does not accept literal, list, or range patterns, implicit-subject comparisons, IF guards, a subjectless condition role, or a DEFAULT arm. Dispatch on an open-ended value is written IF / ELSE IF; dispatch on behaviour is written with polymorphism. (Removed — see (a.i).)
Example.
MATCH shape { // GROUP — a closed set of TYPES
WHEN Circle c: { printline(c->radius() INTO String) }
WHEN Square s: { printline(s->side() INTO String) }
}
MATCH direction { // ENUM — a closed set of CASES
WHEN NORTH: { ... } // bare case — selects, binds nothing
WHEN SOUTH: { ... }
}
MATCH status { // STATUS — the built-in enum
WHEN SUCCESS: { printline("ok") }
WHEN FAILURE(msg): { printline(msg) }
WHEN PARTIAL_SUCCESS(msg): { printline(msg) }
}
Rationale. What the surviving roles share is a set the compiler can enumerate, which is the only setting in which exhaustiveness means anything — and two of the three do something IF cannot: they bind a narrowed instance or a status message that is otherwise unreachable. The bare enum case binds nothing, and is kept for the other half of the justification: naming every case of a closed set is checkable, where an IF chain over the same cases is not. Value dispatch has neither property — an open-ended value can be neither enumerated nor destructured — so it earned no keyword of its own; it is an IF chain wearing different punctuation, and a long one is the signal to reach for polymorphism instead. Forbidding fallthrough removes the classic footgun of a forgotten break carrying control into the next branch.
(a.i) Rule. The value role of MATCH is removed from the language: value and list patterns, the inclusive TO range pattern, the implicit-subject comparison (WHEN == x:, WHEN .method():), the IF guard on a WHEN, the subjectless condition role (MATCH { WHEN <bool>: }), the DEFAULT arm, and the WHEN EMPTY arm. Matching on a dev-defined ENUM is retained — an enum is a closed set and its MATCH is the general form of which STATUS is the built-in instance. Each removed form has an exact IF / ELSE IF replacement with identical lowering, and absence is handled by IS VALID (I.D.iv) with dereference safety enforced at the point of use by E2080, not by the shape of a branch. A pattern that is not a member of a closed set — a literal, a range, an implicit-subject comparison, a guard, a DEFAULT, or a subjectless MATCH — is E4030 (control:match-not-closed-set), which names the IF / ELSE IF replacement. The diagnostics that policed the removed forms retire with them, and are named here by slug rather than number because a retired code must not be cited as live: control:optional-match-incomplete, style:match-single-arm, and style:empty-when-none. E4013 (duplicate WHEN) does not retire — its fire sites police the type-narrowing and enum forms, both retained, so a repeated WHEN NORTH: is still unreachable code.
Rationale. One keyword had accreted six syntactic forms across two AST node shapes, with three different names for the same else-arm and two different places a binder could live. That inconsistency — not the concept of matching — was the defect source: four independent compiler bugs traced to it, including passes that silently skipped every MATCH body. Measured against the whole corpus the removed forms had one production use in 211 shipping source files, against 2,104 IF statements, and every form lowered to the same if/else if chain, so nothing was bought at the cost. What remains is the part that carries meaning: destructuring that binds.
(b) Rule. Every WHEN arm names one alternative of the subject's closed set and binds what that alternative carries, for that arm only. A MATCH whose arms do not cover every alternative — an uncovered GROUP member, ENUM case, or STATUS kind — is a warning: for a GROUP the alternatives are its written members, which is also its transitive set, because only a group whose members all have one concrete representation can type a value at all (I.J.v(a.i)) — the set is closed, so a gap is usually an oversight, but leaving one deliberately unhandled is a legitimate choice the compiler flags rather than refuses. A possibly-EMPTY subject is not matched at all — absence is IS VALID per I.D.iv, and dereferencing an unproven value is E2080 wherever it occurs.
Example.
MATCH shape { // GROUP Shape { Circle, Square, Triangle }
WHEN Circle c: { ... }
WHEN Square s: { ... }
} // WARNING — Triangle uncovered
MATCH direction { // ENUM Direction { NORTH, SOUTH, EAST, WEST }
WHEN NORTH: { ... }
WHEN SOUTH: { ... }
} // WARNING — EAST, WEST uncovered
Rationale. The binding arm is the reason the construct exists: it yields a value — narrowed instance, associated payload, status message — that the analyzer can then trust. Coverage over any closed set is checkable, so the compiler reports the gap; it warns rather than errors because deliberate partial handling is a real pattern and the fallthrough is silent, not unsafe.
(b.i) Rule. A MATCH is a statement and does not itself yield a value; its arms read as ordinary bodies. A WHEN carries no guard — a runtime test that further refines an arm is an ordinary IF inside that arm's body.
Example.
MATCH request {
WHEN Order o: {
IF o->isPaid() THEN { ship(o) } ELSE { hold(o) } // the guard, written plainly
}
}
Rationale. Guards were part of the value role removed in (a.i) and share its fate: a guard is an IF folded into the arm header, where it reads as part of the pattern rather than as the branch it is. Written inside the body it is the same code, one construct fewer, and the arm's binding is already in scope.
(a) Rule. WHEN is reused for compile-time conditional blocks, resolved entirely at build time. An excluded block is removed before semantic analysis and never type-checked, so it costs nothing at runtime. Three forms exist. A platform test against the System vocabulary; a build-mode test against the reserved Build enum, with its DEBUG and RELEASE values; and a feature-flag test, WHEN FEATURE "name", against flags passed to the compiler with --feature. Conditional-compilation WHEN blocks may nest and may appear at any point in a source file.
Example.
WHEN Build IS DEBUG {
printline("verbose diagnostics")
}
ELSE {
// release path — the DEBUG arm above is removed before analysis
}
WHEN FEATURE "experimental" { enableExperimental() } ELSE { } // --feature experimental
Rationale. Resolving these at build time means an excluded arm is never analyzed or emitted. Debug-only or feature-gated code carries no runtime cost, and cannot even fail to type-check in a build where it is switched off.
(a.i) Rule. The grammar is positive-identity only (WHEN Build IS DEBUG / WHEN Build IS RELEASE, each with the mandatory ELSE) — no build-identifier algebra.
Example.
WHEN Build IS RELEASE { ... } ELSE { ... } // positive identity, mandatory ELSE
WHEN Build IS NOT DEBUG { ... } // ERROR — no negation / build-identifier algebra
Rationale. Restricting the grammar to a positive identity test with a mandatory ELSE keeps every conditional-compilation site to two plainly-labeled arms. It avoids the tangle of boolean build-flag algebra that makes preprocessor conditionals hard to read.
(a.ii) Rule. Status: the build-mode form — WHEN Build IS DEBUG/RELEASE — is implemented (compiler/analyze/build_conditionals.py splices the live arm before analysis; posture is RELEASE iff -prod/--build release, else DEBUG). It is resolved at statement level (the V1 target — debug-only code paths). The platform and WHEN FEATURE forms remain specified-but-not-yet-implemented, as does declaration-level conditional compilation (whole classes/methods).
Rationale. This records the shipped-versus-specified split. The build-mode form is live today at statement level; the platform, feature-flag, and declaration-level forms are still on the roadmap.
(a) Rule. A statement that can never execute, because the statement directly before it in the same block unconditionally leaves that block, is a compile error (E4001). The unconditional terminators are RETURN, a multi-value return, PANIC, UNREACHABLE!, BREAK, and CONTINUE. Any statement following one of these within the same block is dead, and must be removed or reordered.
Example.
METHOD f() RETURNS int32 {
RETURN (1)
log("done") // ERROR (E4001) — dead, directly after RETURN
}
FOR item IN items {
BREAK
process(item) // ERROR (E4001) — dead, directly after BREAK
}
Rationale. Unreachable code is a logic error rather than a style nit: the author plainly meant something other than what they wrote. That is why it blocks the build rather than producing an advisory.
(b) Rule. The rule is deliberately direct-only. It does not treat a compound construct whose every arm terminates — an IF in which both branches RETURN — as a terminator. Proving that is the separate concern of definite-return analysis (I.K).
Example.
IF (c) { RETURN (1) } ELSE { RETURN (2) }
log("after") // NOT flagged by E4001 — the IF is not a direct terminator
Rationale. Keeping E4001 to the directly-preceding statement makes it cheap and unambiguous; whether an all-arms-terminating construct leaves the block is the province of definite-return analysis (I.K), not this rule.
envzn lint)(a) Rule. Beyond the errors above, the compiler exposes a report-only linter, envzn lint, that runs the parser and analyzer over a module and stops before code generation. It surfaces the same errors a build would, plus an opt-in set of advisory diagnostics a normal build does not raise. These are the W10060-range "lint" codes: empty control-flow blocks, a constant IF condition, a long IF/ELSE IF cascade better replaced by polymorphism, and the pre-existing style advisories.
Example.
IF (TRUE) { ... } // W10060-range — constant IF condition
WHILE (more) DO { } // W10060-range — empty control-flow block
Rationale. Running through analysis but stopping before code generation lets the linter surface style-level smells: dead-obvious constant conditions, empty blocks, an IF cascade that wants to be a MATCH. None is a defect a build must reject, but each is worth an author's attention.
(b) Rule. Advisory severities are tunable per code through a lint block in the module manifest (off/info/warn/error), and --strict promotes every advisory to error severity. The surface is otherwise non-blocking, and never rewrites source.
Example.
// module manifest — lint block
"lint": { "W10060": "off" } // any W10060-range advisory, tuned to off/info/warn/error
// envzn lint --strict → every advisory promoted to error severity
Rationale. Per-code severity plus a --strict promotion lets a team dial each advisory to its own tolerance, without the linter ever blocking a build or editing source behind their back. The tool reports; the team decides.
The ownership model that gives Envzn memory safety without a garbage collector: single ownership, the handle types, REFERENCE and the non-owning reference, the reference checker, parameter passing, CLEANUP, and the UNSAFE escape hatch.
(a) Rule. Envzn manages memory through ownership rather than through a garbage collector. Destruction is deterministic — it happens at a point a reader can identify from the source — and there is no collection pause at runtime. The rest of this section describes the discipline that buys those two properties — who owns what, how non-owning observation is expressed, and how the compiler proves the result safe.
Rationale. Ownership-not-GC is one of the language's fixed principles. The two properties it buys matter for application software; the price is a stricter authoring-time discipline, which is exactly what the rules below define.
(a) Rule. A class instance is owned uniquely by default. The default owning handle is non-copyable at the type level, so an accidental duplication is a compile error rather than two owners of one instance. Ownership transfers: it moves at a := from a CREATE, from a method result, or from an owning place expression. Observation of an instance owned elsewhere is expressed by a non-owning reference. Where the compiler can prove the referent outlives the reference, that reference is a borrow: a checked pointer that keeps nothing alive, carrying no control block, no reference count, and no runtime test.
Example.
Widget w := CREATE Widget() // owns — constructed via :=
Widget w2 := makeWidget() // owns — moved from a method result
// Widget w3 = w // ERROR — owning handle is non-copyable; no two owners
REFERENCE Widget r =@ w // borrow — observes w, owns nothing
Rationale. Making the owning handle non-copyable turns "two owners of one instance" from a runtime hazard into a rejected program. Most observation is of the provable-outlives kind, so the borrow — the cost-free case — is the common case, and it costs nothing at runtime.
(b) Rule. A reference that escapes — one stored in a field, so that it lives as long as the object holding it — is sound only if its referent outlives the holder, and the compiler proves that where the holder is constructed. The owner must be declared before the holder, in the same scope or an enclosing one, so that it is dropped after it. A holder returned from a method passes that obligation to the method's caller. A holder stored in a field must be declared after the field it points into, because fields drop in reverse declaration order. The holder is any object with a REFERENCE or MUTABLE REFERENCE field, an iterator or a view included, and the rule holds whether or not the holder is read after its referent dies. A holder proven to outlive its referent is a compile error (E3040), and so is one the compiler cannot prove safe: E3045 when the proof turns on a callee whose body it cannot read, E3046 when it cannot follow the holder or name its owner. For a SHARED MUTABLE REFERENCE each of these is E3048. Nothing is ever promoted to make it legal. The developer redesigns: reorder the declarations, keep the holder inside the owner's scope, or give the holder its own copy with DUPLICATE. Where the holder itself owns the referent, the reference is redundant, and writing one in place of owning the value directly is a compile error (E3032). A plain REFERENCE field stays a borrow — a raw pointer with no reference count. The one escaping form that also co-owns is the SHARED MUTABLE REFERENCE field onto a SHARED CLASS (I.I.vi(c)): it holds a strong count, so its referent lives until the last holder drops. That count is a runtime backstop behind the proof, never a substitute for it — the SHARED MUTABLE REFERENCE must pass E3048 exactly as a borrow does. (That promotion is retired; the strong handle is not.)
Example.
Channel[int32] results := CREATE Channel[int32](5, BackpressurePolicy.BLOCK)
WorkerPool pool := CREATE WorkerPool(2, 8, BackpressurePolicy.BLOCK)
pool->submit(CREATE SquareJob(3, results)) // OK — results is declared first, so dropped last
// swap the two declarations: the pool, and the job it holds, outlive results → E3048
Rationale. A reference the compiler cannot prove is a design the compiler cannot prove. Accepting it because a reference count would keep the referent alive hides that, and it changes what the program means: shared ownership keeps an object alive past the point the source says it ends. So the proof is required everywhere, and the developer, who knows which object should outlive which, does the redesign. A monitor shared across tasks keeps its count anyway, because a task is the one holder whose end the source does not pin to a line — there the count is the backstop that turns a mistake in the proof into a delayed free rather than a use-after-free.
(b.i) Rule. Shared ownership — a SHARED CLASS owned through its strong count and co-owned by each SHARED MUTABLE REFERENCE holder — reintroduces the one hazard unique ownership had ruled out: a cycle of strong handles can never reach a last drop, and so can never be freed. The compiler closes it statically — the graph of owning and strong edges must be acyclic, and a strong-reference cycle is a compile error (E3033). Owning recursion, where a node owns the next node in a list or tree, is acyclic at the object level and is not a cycle in this sense.
Example.
// LinkedList node owns the next node — owning recursion, acyclic, accepted:
TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT boolean, opaque, complex, number):
CLASS Node[T] {
T value
Node[T] next // owning edge down the list — OK
}
// two objects each holding a STRONG handle to the other → E3033 (strong-reference cycle)
Rationale. Because a strong cycle is the one structure refcounting cannot reclaim, catching it at compile time makes "no leaks" a property proven rather than hoped for. A uniquely owned instance is still destroyed deterministically when its owner drops. A strongly shared instance is destroyed at the last strong drop — a point the source still identifies, though it is the last of several rather than a single one.
(c) Rule. A borrow observes; it does not own, and cannot be made to own. A plain parameter takes ownership of its argument (I.I.vi), so the argument must be an owned value rather than a borrow. A borrowed argument — an element read as arr[i], or any value held through a REFERENCE or MUTABLE REFERENCE — points at storage owned elsewhere. For a non-blittable type it can be neither moved nor silently copied into an owning parameter, so passing one is a compile error (E3038). The remedy is to hand over an owned value — DUPLICATE x or ->clone() (when the type is Cloneable) — or, when the callee only reads, to declare the parameter REFERENCE T. A blittable type is the exception: owning one is holding a copy, so a borrow of a blittable value passes to a plain parameter by an implicit trivial copy.
Example.
// take(Widget w) owns its argument:
REFERENCE Widget r =@ shelf[0]
// take(r) // ERROR E3038 — a borrow cannot be moved or copied into an owning param
take(DUPLICATE shelf[0]) // OK — hand over an owned deep copy
take(shelf[0]->clone()) // OK — likewise, through Cloneable
observe(shelf[0]) // OK — observe(REFERENCE Widget w) only reads the borrow
Rationale. An owning parameter must end up owning a value; a borrow owns nothing, so silently copying it would hide an allocation the reader can't see. Requiring an explicit DUPLICATE/->clone() — or switching the parameter to REFERENCE — keeps the cost visible at the call site. A blittable copy is a bit copy with no allocation, so there is nothing to make visible.
(c.i) Rule. The text family has no exemption. A String or ByteBuffer parameter follows the same three modes as every other non-blittable type: one that only reads is declared REFERENCE String, and a plain String parameter owns its argument. (Withdrawn : the former exemption made a plain String parameter a read-only borrow while a plain parameter of every other class was a mutable one — one spelling, two meanings. See I.I.vi.)
Example.
REFERENCE String s =@ names[0]
greet(s) // OK — greet(REFERENCE String name) reads; no copy
// keep(s) // ERROR E3038 — keep(String name) owns its argument
keep(DUPLICATE s) // OK — hand over an owned copy
Rationale. String and ByteBuffer are immutable (I.D.vi), which made a read-only borrow safe for them — but safety was never the question. The exemption made the meaning of a plain parameter depend on the type's name, which a reader cannot see at the call site. Declaring the mode states it.
(d) Rule. Class instances live on the heap. Primitives, String, STATUS values, enum cases, and STRUCT fields are value types and live on the stack, or inline within whatever contains them. When a stack frame exits — by an ordinary return, the end of a block, or exception unwinding — the owned heap objects it held are released in reverse declaration order. Non-owning handles are skipped during that release, because they never owned anything.
Example.
METHOD run() {
Widget a := CREATE Widget() // owned heap object
Widget b := CREATE Widget() // owned heap object
REFERENCE Widget r =@ a // non-owning — skipped at release
} // frame exits: b released, then a (reverse decl order); r skipped
Rationale. Reverse-declaration-order release means a later object (which may reference an earlier one) is torn down first. The owner is responsible for release, and only the owner — so a non-owning handle must never trigger one.
(e) Rule. A field may be moved out with :=. What happens to it depends on whether it is always present. A field is always present when its type has no EMPTY state (String, ByteBuffer, or a type parameter some instantiation binds to one, I.D.vii), or when it is class-typed and its own class never assigns it EMPTY. Any other class field is EMPTY-able: moving out of it leaves it EMPTY, a state its readers already test with IS VALID. An always-present field cannot become EMPTY, so moving out of it leaves it moved out instead. The field may be written again, and its object may be overwritten, removed or dropped, but it may not be read until it is written. The rule follows the field across method boundaries. A method that ends with one of its own fields moved out invalidates its object, and its caller may then write, overwrite, remove or drop that object, but never read it. If the object is an array element, reached through =@ .arr[i], it must leave the array (.arr->remove(i)) or be overwritten before the method ends, and i may not be rebound in between. An invalidating method must be INTERNAL or PRIVATE, because a caller in another module cannot see its effect. A PANIC while a field of the object is moved out is rejected, because the RECOVER that catches it could read the field. Each of these is a compile error, E3026.
Example.
INTERNAL MODIFY METHOD takeOut() RETURNS (K k, V v) { // CollisionNode
k := .key // legal: .key is moved out
v := .value
RETURN (k, v) // the node is invalidated — INTERNAL, so only its module calls it
}
MUTABLE REFERENCE CollisionNode[K, V, HASH] slot =@ .data[pos] // HashBucket
removedKey, removedValue := slot->takeOut() // .data[pos] is invalidated
$? := .data->remove(pos) // and leaves the array before anything reads it
Rationale. "Move in ⇒ move out" (no deep copy on a container's removal path) needs a field to give up its value, and an always-present field has no EMPTY to fall back to. Refusing the move outright forced a clone wherever a container hands back what it held. The hazard was never the move; it was a later read of the gutted field. Tracking the field the way a moved local is tracked keeps the move and refuses only that read. The rule is decided per method body, so a method that leaves the object broken carries that fact to its callers. Since .headers publishes signatures and not that fact, such a method must stay inside the module that can see it.
DUPLICATE and the implicit duplication of a CONSTANT.
DUPLICATE x yields an independent deep copy of x, whatever storage shape x
has: an owning handle clones its referent, a value class or primitive copies.
It is the explicit form of "I want my own".
A CONSTANT read in an owning position duplicates implicitly — no
DUPLICATE is written, and none is required:
CONSTANT String tag = "date"
METHOD nameOf() RETURNS String {
RETURN (tag) // implicit duplicate; `DUPLICATE tag` is redundant
}
.slots[.slots.length] := tag // likewise
Rationale. An explicit ownership annotation earns its place by carrying
information the compiler does not already have. For an ordinary binding it does:
x may legitimately be moved or copied, so DUPLICATE / := records which
the author meant. For a CONSTANT there is exactly one legal answer — a copy —
because a move would gut a shared, immutable binding that every later reader
still depends on. The annotation conveys nothing, so requiring it is ceremony,
and by I.A the compiler is the side that should absorb it.
The owning positions are the three where a value's ownership is decided: the
initializer of a := binding, the value of a := assignment (including a cell
store), and a by-value RETURN. A borrow position is untouched — passing a
CONSTANT to a REFERENCE T or a bare type-parameter parameter hands over a
pointer and copies nothing.
(a) Rule. A binding of a class type is reached through a handle, and Envzn has three handle shapes. They apply uniformly to every kind of value — there is no separate handle vocabulary for primitives, for value classes, or for collections.
| Handle | Owning | Mutable | Description |
|---|---|---|---|
T x |
yes | yes | Owns its value. Reading, writing, and moving out of x are all permitted. |
REFERENCE T x |
no | no | An immutable reference — read-only observation of storage owned elsewhere. Always valid, by the reference checker's guarantee. |
MUTABLE REFERENCE T x |
no | yes | A mutable reference — exclusive write access to storage owned elsewhere. Always valid, by the reference checker's guarantee. |
Example.
Counter c := CREATE Counter() // T x — owns
REFERENCE Counter ro =@ c // read-only borrow
MUTABLE REFERENCE Counter rw =@ c // exclusive-write borrow
Rationale. One handle vocabulary for every value kind means a reader learns the ownership/mutability of a binding from its handle shape alone, with no per-type special cases to memorize.
(b) Rule. Optionality is not encoded in a handle, because there is no ? suffix; absence, where it applies, is the EMPTY state described in I.D.iv. An owning class handle may be EMPTY, and a read of it requires that presence first be established. An owning primitive, STATUS, enum, or struct value always holds a defined value and has no EMPTY state. A reference of either kind is always valid by the reference checker's guarantee, and so needs no presence check at all.
Example.
Widget w := EMPTY // owning class handle may be EMPTY
IF w IS VALID THEN { w->use() } // presence established before the read
int32 n = 0 // primitive — no EMPTY state ever
REFERENCE Widget r =@ shelf[0] // always valid — no presence check needed
Rationale. Folding absence into a ? suffix would duplicate what the EMPTY state already expresses. Keeping it out of the handle means the three handle shapes stay about ownership and mutability, and nothing else.
(a) Rule. Because the EMPTY state applies only to some bindings, the presence test IS VALID is meaningful only on those. Applying it elsewhere is a compile error, with a diagnostic that names the correct alternative. The table below is the complete account.
Subject of IS VALID |
Applies | Reason |
|---|---|---|
| Owning class handle | yes | May be EMPTY if assigned EMPTY or never assigned. |
String / ByteBuffer |
no | Always present (I.D.vii.b) — an empty string is the present value "", not absence, so the test could never be false. Test the content with ->isEmpty(). Diagnostic E6068. |
| The value slot of a pipe-XOR return | yes | The slot is populated only on the success branch. |
REFERENCE T or MUTABLE REFERENCE T |
no | Always valid by the reference checker's guarantee. |
| A primitive value | no | Always holds a defined value. |
A STATUS value |
no | Always holds a defined status — test with IS SUCCESS / IS FAILURE / IS PARTIAL_SUCCESS. |
| An enum value | no | Always holds a defined case. |
A STRUCT value |
no | Always holds defined member values. |
Example.
IF handle IS VALID THEN { handle->use() } // OK — owning class handle
// IF status IS VALID { ... } // ERROR — use IS SUCCESS / IS FAILURE on a STATUS
// IF r IS VALID { ... } // ERROR — a REFERENCE is always valid
Rationale. IS VALID tests the one axis — presence — that only EMPTY-capable bindings have. Naming the correct alternative in the diagnostic steers a STATUS to IS SUCCESS/IS FAILURE rather than leaving the author to guess.
(a) Rule. A REFERENCE T is a non-owning, immutable reference to a value; a MUTABLE REFERENCE T is a non-owning, exclusive-write reference. Both work uniformly across every T. A reference is a typed pointer whose lifetime the compiler has checked. It carries no control block, no reference count, and no runtime validity test, because the reference checker has proved at compile time that it is sound.
Example.
REFERENCE int32 ro =@ scores[0] // immutable reference to a primitive
MUTABLE REFERENCE Widget rw =@ w // exclusive-write reference to a class
Rationale. Because soundness is a compile-time proof, a reference lowers to a bare typed pointer with none of the runtime machinery a checked-at-runtime scheme would need.
(b) Rule. A reference is established with =@ against a place expression, and read directly thereafter with no presence check. A reference is never EMPTY: the place bound with =@, and every argument passed to a REFERENCE or MUTABLE REFERENCE parameter, must be provably present at that point — a variable that may be EMPTY is rejected with E2080 until IS VALID proves it, and the literal EMPTY is rejected with E2169. Writing through a MUTABLE REFERENCE to a primitive looks like an ordinary assignment with the reference on the left; writing through one to a class field uses ordinary field and method syntax. REFERENCE composes with the access modifiers and may appear on class fields, on method parameters and returns, and on locals. MUTABLE REFERENCE may appear on parameters, returns, and locals, but not on a class field.
Example.
MUTABLE REFERENCE int32 m =@ counts[0]
m = m + 1 // write through a MUTABLE REFERENCE to a primitive
MUTABLE REFERENCE Widget mw =@ w
mw->recolor(RED) // write through one to a class — ordinary method syntax
// CLASS C { MUTABLE REFERENCE Widget field } // ERROR — MUTABLE REFERENCE not allowed on a class field
Rationale. A mutable reference stored in a field would let the class retain exclusive write access past the reference's checked lifetime. That is exactly the property the checker exists to prevent, so the one position is forbidden.
(b.i) Rule. A MUTABLE REFERENCE to a scalar primitive is a valid parameter: an out-parameter (I.I.vi(a)). METHOD bump(MUTABLE REFERENCE int32 n) lowers to int32&, and the callee's write lands on the caller's variable. When the updated value reads better as a result, the multi-return form says it directly: RETURNS (int32 n, boolean ok).
(c) Rule. There is one carve-out: SHARED MUTABLE REFERENCE may appear on a class field, provided the referent type T is a SHARED CLASS (I.K.ii) — a referent that is not is E2117. A SHARED MUTABLE REFERENCE field is bound at INIT from a MUTABLE REFERENCE parameter, and the bind takes a new strong count on the referent: the field co-owns its SHARED CLASS instance alongside the instance's owner, and the instance is destroyed when the last of them drops. Nothing else is counted — REFERENCE and MUTABLE REFERENCE stay plain pointers even onto a SHARED CLASS, and only a declared SHARED CLASS is ever co-owned. The count is a runtime backstop, not a licence: the referent must still outlive the holder, proven by the compiler where the holder is constructed (I.I.i(b)); an unprovable one is E3048, whatever the count would have done. The field is therefore always valid where it is in scope, and calling the monitor's mutating methods through it is ordinary method syntax.
Example.
CLASS Subscription[T] {
// Channel is a SHARED CLASS, so several subscriptions may alias it.
// The bind takes a strong count, but the broker that owns the channel
// must still outlive this subscription, and each caller of
// Broker.subscribe must show it (E3048).
PRIVATE SHARED MUTABLE REFERENCE Channel[T] chan
INIT(MUTABLE REFERENCE Channel[T] c) { .chan =@ c }
}
// SHARED MUTABLE REFERENCE PlainClass f // ERROR E2117 — referent is not a SHARED CLASS
Rationale. A MUTABLE REFERENCE field is forbidden because it would alias exclusive write access; SHARED waives that exclusivity, and doing so is sound only because a SHARED CLASS is a monitor that serialises its own access, so concurrent aliased mutation cannot race. The waiver is narrow — only exclusivity is given up; lifetime remains the analyzer's concern, with the strong count behind it as a backstop. This is the mechanism behind Broker[T] / Subscription[T], where each subscription holds a SHARED MUTABLE REFERENCE to a broker-owned Channel. The broker owns the channel, so the broker must outlive every subscription it hands out — which the caller shows by declaring the broker first.
(d) Rule. A reference's lifetime begins at its =@ and ends at the last use of the reference in its scope, and the referent must outlive that span. While a reference is alive, its source cannot be moved, dropped, replaced, or — for a collection source — structurally mutated. A reference local may be rebound with a fresh =@ to a different source, provided the previous reference's lifetime has already ended at the point of rebinding.
Example.
REFERENCE int32 r =@ scores[0] // reference established
// scores->append(99) // ERROR — cannot mutate scores while r is alive
printline((r INTO String)) // last use of r — its lifetime ends here
scores->append(99) // permitted now — r's lifetime has ended
r =@ scores[1] // OK — rebind after the previous lifetime ended
Rationale. Bounding a reference's lifetime by its last use, and freezing its source for that span, is what lets the checker prove the referent still exists at every read. No runtime validity test is needed.
(e) Rule. A reference field is subject to structural conditions at INIT time, and those conditions decide the field's disposition. The referent is a provable borrow in two cases: when it is ownership-reachable through a chain of owning fields from the enclosing instance, or when it is a constructor parameter locked against rebinding for the instance's lifetime. A field that satisfies either is a borrow, and must be written as one. A field that satisfies neither has an escaping referent, and its referent must be proven to outlive the holder at each place the holder is constructed (I.I.i(b)); a referent that cannot be is refused (E3040, E3045 or E3046; E3048 for a SHARED MUTABLE REFERENCE). Nothing is promoted to a strong handle to make it legal — the only strong reference field is the declared SHARED MUTABLE REFERENCE of I.I.vi(c), and it is held to the same proof.
Example.
CLASS Cursor {
PRIVATE Buffer buf // owning field
PRIVATE REFERENCE Buffer cur // ownership-reachable through .buf → provable borrow
INIT() { .buf := CREATE Buffer() .cur =@ .buf }
}
// an escaping reference field whose owner is dropped before the holder → E3048
Rationale. Deciding disposition from the field's shape discharges the common case cheaply, before any flow analysis is needed: a borrow where a borrow is provable, and a construction-site proof — or E3048 — where the referent escapes.
(e.i) Rule. An escaping reference into value storage — a field reference into a T[], {K : V}, {T}, or char[], where there is no per-element heap object to reference-count — cannot be made safe and is forbidden in V1 (E3034); references of that shape are confined to the scope they are created in, as the collection iterators of I.J are. Where the structural conditions cannot decide a field-stored reference's fate they leave it to a runtime check. But a case the flow-sensitive escape walk of I.I.v can prove does dangle is rejected outright (E3040): a reference to a method-local that the enclosing instance outlives, where the local is freed at method exit while the field lives on and is not moved into the instance's ownership in the same body.
Example.
// PRIVATE REFERENCE int32 pick =@ scores[i] // ERROR E3034 — reference into value storage stored in a field
METHOD attach() {
Widget local := CREATE Widget()
// .held =@ local // ERROR E3040 — field outlives a method-local it references
}
Rationale. Value storage holds no per-element heap object to reference-count, so an escaping reference into it can neither borrow nor be promoted — the only safe answer is to confine it. E3040 is the flow walk's floor-advancing complement to the structural conditions: it rejects a proven dangle rather than deferring it to a runtime check.
(a) Rule. The reference checker is the compile-time analysis that enforces the rules above; it is part of the analyzer pipeline and adds nothing to the running program. Three core rules govern it. First, a reference does not outlive its referent: every reference's lifetime is bounded by its last use, and the referent must outlive it. Second, shared exclusive-or mutable: for any one source, at any one time, either any number of immutable references exist or exactly one mutable reference exists, never both. Third, no mutation through another path while referenced: while any reference to a source is alive, the source may not be moved, dropped, or mutated by any other route, structural mutations of a collection included.
Example.
REFERENCE int32 a =@ data[0]
REFERENCE int32 b =@ data[0] // OK — many immutable references may coexist
// MUTABLE REFERENCE int32 m =@ data[0] // ERROR — a mutable reference may not coexist with them
Rationale. These three rules are the classic aliasing discipline (many-readers-xor-one-writer, plus no-mutate-behind-a-reference) applied at compile time, which is what makes every checked reference safe to lower to a bare pointer.
(b) Rule. Beyond enforcing those rules on borrows, the checker assigns each stored reference its disposition and proves the program leak-free. The disposition decision is borrow-mandatory-where-provable. For every reference field and reference return, the checker asks whether a borrow is provable; where it is, the borrow is required. A reference written where the holder owns the referent outright is rejected (E3032) — own the value instead. Nothing falls back on a strong handle: an escaping reference is proven at its construction sites or rejected (E3048), SHARED MUTABLE REFERENCE included, and one into value storage is forbidden outright (E3034). The strong edges are the SHARED MUTABLE REFERENCE fields and the owned elements of a SHARED CLASS collection. The leak-freedom proof is an acyclicity check over the combined graph of owning and strong edges: a strong-reference cycle is a compile error (E3033), while owning recursion is recognized as acyclic and passes.
Example.
// E3032 — a reference to a referent the holder already owns (own it instead)
// E3048 — an escaping reference the compiler cannot prove outlives-safe
// E3034 — escaping reference into value storage
// E3033 — a cycle of strong edges (leak the acyclicity check catches)
Rationale. Together these make "no leaks" a theorem the compiler discharges rather than a runtime behavior the program merely tends to exhibit. The set of borrows the checker is willing to prove is held to a documented baseline. Otherwise an improvement to the proof would retroactively change which programs are accepted.
(b.i) Rule. An advisory rounds out the surface, non-blocking: the checker flags a reference held past its last use (W10091). (The advisory that reported each promotion to a strong handle, memory:arc-strong-reference, it is named by slug because a retired code must not be cited as live.)
Example.
// W10091 — advisory: this reference is held past its last use
Rationale. A held-too-long reference over-freezes its source; surfacing it as a warning keeps it visible without blocking a build.
(c) Rule. For a method that returns a reference paired with a STATUS in the pipe-XOR shape, the returned reference is valid only inside the success branch of the consuming IF. A read through it elsewhere is a compile error. Method signatures that return a reference rely on lifetime elision. A method taking one reference parameter and returning a reference infers the return's lifetime from that parameter; a method whose receiver is a reference infers it from the receiver. Where elision is genuinely ambiguous, as with two reference parameters, the compiler reports an error and asks for an explicit annotation, a syntax reserved for V2.
Example.
IF cache->lookupRef(key) THEN {
REFERENCE Value v =@ $= // valid only inside the success branch
v->use()
}
// reading through that reference outside the success branch is a compile error
Rationale. The pipe-XOR value slot is populated only on success, so its reference is only meaningful there. Lifetime elision covers the one- and receiver-reference cases so that V1 needs no explicit lifetime annotation syntax at all; the genuinely ambiguous multi-reference case is deferred to V2 rather than guessed.
(c.i) Rule. The keyword VOLATILE is reserved for a future runtime-checked observer, for the cross-thread sharing patterns the static checker cannot prove safe; V1 has no such observer, and a pattern that would need one is expected to be redesigned through channel-mediated communication. The reference checker is not a runtime check, requires no explicit lifetime annotations in V1, and leaves code that uses only owned handles and value copies entirely unaffected.
Rationale. Naming what the checker is not forecloses the common misreadings. Code that never takes a reference pays nothing, and cross-thread aliasing the static proof cannot reach is routed to channels rather than an unproven VOLATILE in V1.
(d) Rule. A reference whose safety turns on flow — whether a referent actually outlives a holder along every path — is beyond a shape rule. For the field-stored escaping residue the compiler adds a flow-sensitive escape walk: a whole-program analysis running after the intermediate representation is built and before code is emitted, the last memory-safety diagnostic in the pipeline. It classifies each field-stored reference by the lifetime of what it names: reachable from the enclosing instance, a constructor parameter, a local moved into the instance's ownership, or a local that merely dies at the method's end. Where it proves the last, it rejects the store as a dangle (E3040) rather than leave it to a runtime check. The same walk follows every holder — any object with a reference field — from the call or CREATE that binds it to the drops that end it, through returns, moves and fields, and across module seams by reading each dependency's method bodies. A holder proven to outlive its source is E3040; one it cannot decide is E3045 or E3046, never E3040, which asserts a proof. The walk is additive: it fires only on residue the structural conditions do not already resolve, and never revokes a reference they accept.
Example.
METHOD attach() {
Widget local := CREATE Widget() // dies at method exit
// .held =@ local // ERROR E3040 — the field outlives this local
.held := local // OK — move the local INTO the instance's ownership instead
}
Rationale. Shape rules decide the common case cheaply; the flow walk advances the floor on the residue they can't, turning a provable dangle into a rejected program instead of a deferred runtime check. In V1 it reaches within a single module. The cross-module case — a referent behind a dependency's boundary — is resolved by the same walk once dependency bodies are carried in the .evir sidecar. Until then, a reference whose safety only that whole-program analysis could establish is rejected rather than assumed safe.
(e) Rule. A borrow also travels inside values. A referer is any value of a type that can carry a borrow of storage outside itself: a type with a reference field bound from outside the object, or a type that holds such a type — as a field, an array element, or a type argument. Every copy of a referer borrows what the original borrows, not the original. When a referer is stored into a holder — a collection, an array, a field, any object that keeps it — the checker follows its residence there, and the residence must end before the referent (the storage it borrows) dies, on every path — the paths a PANIC unwinds included. It ends at the first of three events: a paired remove, which takes an element out of the storage the referer went into using the same key the add used, unchanged and with nothing stored into or taken from that holder in between; a release-all, which replaces every field the holder keeps elements in; or the death of the holder itself. A remove or a release-all is a call, and a call can PANIC before it completes; the unwind then drops the frame's locals in reverse declaration order (I.M) and runs no remove. So on the unwind paths only the order of the drops protects the referent: a holder released by a call must be declared after the referent, so that it dies first on every path, and a field or a caller's object, which no unwind of this frame drops, cannot keep a borrow of a frame local at all. A residence the checker proves outlives its referent, and one it cannot prove does not, are both E3040. The message says which, and names the referent, the holder, and the referer. What a method does to its receiver's storage — what it keeps, what it takes out, what it replaces, and what its result borrows — is read from its body and the bodies it calls, down to the storage crossings themselves; no collection or method is known to the checker by name. One fact is trusted rather than proven: a Hasher is deterministic, so a remove with the add's key finds the add's entry.
Example.
Pool p := CREATE Pool()
Dictionary[int64, BinaryWord, DefaultHasher[int64]] d := CREATE ChainedHashDictionary[int64, BinaryWord, DefaultHasher[int64]]()
BinaryWord w := CREATE BinaryWord(p.bytes, 0, 3) // w borrows storage p owns
d->insertCopy(1, w) // d keeps a copy of w
IF d->remove(1) THEN { … } // OK — d, declared after p, dies first on every path
// p = EMPTY with the copy still in d ERROR E3040 — d still holds a borrow of p's storage
// d declared BEFORE p, even with the remove ERROR E3040 — a PANIC in remove() would unwind,
// freeing p while d still holds the copy
Rationale. Without a garbage collector a borrow that hides inside a value is still a borrow, and the dictionary, the array and the field are exactly where it hides; following the value rather than the declared type is what closes that gap (memory safety is the floor, I.A). Judging the residence rather than the holder's whole life is the precise question; requiring it to end on every path, the unwind paths included, is what keeps the answer a proof rather than a hope — a remove that never ran because a PANIC unwound past it would otherwise leave the borrow behind. The nested lifetimes this asks for are the same discipline the language already asks of every reference. Reading behaviour from bodies rather than from a list of known collections keeps the rule true for a collection written tomorrow.
(a) Rule. Envzn has no address-of operator and no parameter marker at the call site: what a call does to its argument is determined entirely by the parameter's declared mode. There are three modes, mutually exclusive, with exactly one spelling each:
T — own. The callee receives ownership: it may keep the value, store it, move it on, return it, and mutate it. For a non-blittable type the caller's source is consumed by the call and poisoned afterward, so a later use of it at the call site is a compile error (E3010). For a blittable type — a primitive, enum, STATUS, or blittable STRUCT or value class — owning is holding a copy, so the caller's value is untouched.REFERENCE T — read. The callee may read the value and call its non-MODIFY methods. Calling a MODIFY method through it (E6071) or writing one of its fields is a compile error. It never outlives the call.MUTABLE REFERENCE T — write. The callee may read the value, write its fields, and call any of its methods, and the checker guarantees no other reference to the same source coexists with it for the duration of the call. It never outlives the call.A non-blittable parameter — a class, interface, String or ByteBuffer, array, type parameter, or non-blittable value class — therefore always states which of the three it means. A blittable parameter is written plain in the ordinary case; REFERENCE and MUTABLE REFERENCE remain legal on it (a large struct read without copying; an out-parameter). The modes apply to every METHOD, INIT and OPERATOR parameter, and to interface method signatures. They do not apply to a FOREIGN parameter (I.N), whose shape is the C ABI's, nor to the FROM source of a conversion operator (I.D.viii), which a conversion only ever reads.
Example.
METHOD store(Widget w) // own — w is the callee's now
METHOD observe(REFERENCE Widget w) // read-only; a MODIFY call through w is E6071
METHOD edit(MUTABLE REFERENCE Widget w) // read + write + any method; exclusive for the call
Widget w := CREATE Widget()
observe(w) // lends w; w is still the caller's
edit(w) // lends w mutably; still the caller's
store(w) // w is consumed here
// w->use() // ERROR E3010 — w was moved into store
Rationale. Deciding pass semantics from the declaration alone — no &, no call-site marker — keeps the call site readable: the reader learns from the signature whether a call takes, reads, or writes its argument. There is one spelling per meaning (I.A), and plain means ownership here exactly as it does for a local, a field, and a RETURNS T; the borrowing directions are the same two words in both positions (REFERENCE T / MUTABLE REFERENCE T as parameters and as RETURNS). A primitive's modes collapse because a copy cannot be observed; a class's cannot, which is why a class parameter always says which one it is. The C++ lowering of each mode is given in ENVZN_IR_SPEC.md C.ii.
(a.i) Rule. The collection-insertion methods of I.J.ii — append, prepend, push, enqueue, insert, add — declare their value-to-store plain: they own it. Their *Copy twins declare it REFERENCE and store a deep copy. The analyzer reads the mode, never the method name, to decide which call sites poison their argument.
Example.
Widget w := CREATE Widget()
list->append(w) // append(T value) owns → w is poisoned after this call
// w->use() // ERROR E3010 — consumed by append
list->appendCopy(other) // appendCopy(REFERENCE T value) reads; other stays valid
Rationale. Keying poisoning off the visible mode, rather than a memorized list of method names, means an author can see at the signature whether a call consumes its argument, and a new insertion method gets the semantics right for free by declaring the mode.
(a.ii) Rule — what may be passed where. An owned value (a local, a temporary, a field) may be passed to any mode: a plain parameter moves it, a REFERENCE or MUTABLE REFERENCE parameter lends it. A REFERENCE value may be passed to a REFERENCE parameter only: passing it to a MUTABLE REFERENCE parameter is a loosening and a compile error (E6067), and passing it to a plain parameter requires an owned copy (I.I.i(c)). A MUTABLE REFERENCE value may be passed to either reference mode; passing it to a plain parameter requires an owned copy likewise. Moving a field into a plain parameter leaves the field EMPTY, as := from a field does, and because that mutates self it is legal only inside a MODIFY method (E1098).
Example.
METHOD tighten(MUTABLE REFERENCE Widget w) {
observe(w) // OK — MUTABLE REFERENCE → REFERENCE tightens
// store(w) // ERROR E3038 — a borrow cannot satisfy an owning param
store(DUPLICATE w) // OK — an owned copy
}
METHOD peek(REFERENCE Widget w) {
// edit(w) // ERROR E6067 — REFERENCE cannot be loosened to MUTABLE REFERENCE
}
Rationale. A borrow may always be narrowed, never widened, and never turned into ownership without an explicit copy — the same three facts that govern =@ locals (I.I.ix) applied at the call boundary, so a value's rights never grow by being passed.
(a.iii) Rule — implementations conform. A method that implements an interface slot, or overrides a parent method, declares the same mode as that slot, parameter by parameter. A mismatch is a compile error (E6097).
Example.
INTERFACE Equatable OF T {
METHOD equals(REFERENCE T other) RETURNS boolean
}
CLASS Point IMPLEMENTS Equatable OF Point {
METHOD equals(REFERENCE Point other) RETURNS boolean { … } // OK — same mode
// METHOD equals(Point other) RETURNS boolean // ERROR — the slot reads; this would own
}
Rationale. A caller holding the interface sees only the slot's mode. An implementation that asked for more — ownership where the slot lends, a write where it reads — would receive what the caller never gave it.
(a.iv) Rule — LAMBDA. A LAMBDA-typed parameter is always plain: the callee owns the closure it is handed. REFERENCE or MUTABLE REFERENCE on a lambda-typed parameter is a compile error (E7033). A lambda expression's own parameters (LAMBDA x: x + 1) carry no mode; the algorithm that invokes the closure lends it each argument as a REFERENCE.
Example.
METHOD map(LAMBDA func) RETURNS Array[T] // OK — the callee owns the closure (Array.map)
// METHOD map(REFERENCE LAMBDA func) RETURNS Array[T] // ERROR — a lambda parameter is always plain
Array[int32] doubled := nums->map(LAMBDA x: x * 2) // x is lent to the closure as a REFERENCE
Rationale. A closure is nearly always written inline at the call, where handing over ownership costs nothing, and a borrowed closure buys a caller nothing it needs. One mode keeps the tenet with no exception.
(b) Rule — MOVE is not a mode. MOVE is a reserved word, and it is not a parameter marker: a plain parameter already owns (a). Writing MOVE on a parameter is a compile error whose fix is to remove it (E1164).
Example.
// METHOD store(MOVE Widget w) // ERROR — MOVE is not a mode; write store(Widget w)
METHOD store(Widget w) // OK — a plain parameter owns
Rationale. Two spellings for one meaning are a trap for the reader, who must learn that they coincide; and a marker that could exist only on arguments would leave returns described by a different rule. Plain means ownership everywhere, in both directions, so one rule covers both.
A class may additionally define a CLEANUP block for teardown the language cannot perform on its own — closing a file handle, releasing a GPU buffer, shutting a socket. CLEANUP runs automatically when the owner's stack frame exits, exception unwinding included. A PANIC raised inside CLEANUP must not escape it: if one does, on a normal exit or during unwinding, the program ends at once with a CES diagnostic, uncatchable by any RECOVER; a step that may fail is caught by a TRY/RECOVER inside the CLEANUP itself. The destruction order is fixed. First the instance is marked no longer alive, so any concurrent observation sees absence. Then the developer-defined CLEANUP block runs. Then the member fields are destructed in reverse declaration order, each running its own destructor chain.
Example.
CLASS FileWriter {
PRIVATE opaque handle
CLEANUP {
.closeHandle() // runs automatically at frame exit, unwinding included
}
}
Rationale. The implicit destructor covers memory; CLEANUP covers the resources the compiler can't see. Fixing the order — mark-dead, then CLEANUP, then fields in reverse — means a field a CLEANUP body relies on is still alive while that body runs. Concurrent observers see absence the instant teardown begins.
(a.i) Rule. An attempt inside CLEANUP to observe a self-reference always sees absence, because the not-alive mark has already been set, and the analyzer rejects any code path in CLEANUP that would try.
Example.
CLEANUP {
// IF SELF-observing path ... // ERROR — analyzer rejects observing a self-reference in CLEANUP
.releaseBuffer() // OK — act on fields, not a self-observation
}
Rationale. Because the not-alive mark is set first, any self-observation in CLEANUP would necessarily see absence — a bug a teardown routine reliably gets wrong. The analyzer rejects the path rather than let it read absence at runtime.
(a) Rule. The memory model so far — owning handles, references, and the reference checker — describes storage the compiler can reason about. Two constructs deliberately step outside that reasoning, for the narrow case of holding and reaching a raw pointer that originates across the foreign-function boundary (I.N, ENVZN_IR_SPEC.md C.vi). Both carry UNSAFE in their name precisely so the escape is greppable and never silent.
Rationale. Some FFI storage is genuinely beyond the compiler's reasoning; making every such escape carry UNSAFE in its name keeps the two constructs auditable by grep rather than silent.
(b) Rule. The UNSAFE.<NAME> handle family. UNSAFE is a runtime-adjective prefix on a small set of primitive handle types: UNSAFE.HANDLE is an opaque heap pointer, UNSAFE.MUTEX an OS mutex handle, and UNSAFE.CONDVAR an OS condition-variable handle — the three valid names, with any other UNSAFE.X rejected by name. The prefix parses as the bare handle type carrying an UNSAFE runtime adjective. Each crosses the C ABI as a C pointer. UNSAFE.HANDLE has no pointee, so it lowers to a plain void * in C and C++ alike: Envzn code can only store it, test it (IS VALID), clear it (EMPTY) and pass it to a FOREIGN BIND, never dereference it, and every declaration of one starts null. UNSAFE.MUTEX and UNSAFE.CONDVAR have typed pointees and lower to the kernel's null-checked _UnsafeHandle<T> wrapper (<pthread_mutex_t>, <pthread_cond_t>): a dereference of a null one does not corrupt memory but raises an EmptyHandleError (I.M.ii), catchable like any kernel error. An UNSAFE.<NAME> value may be stored in a PRIVATE or INTERNAL class field and passed across a FOREIGN BIND boundary. DIRTY, SECRET, and ENCRYPTED are reserved sibling adjectives; UNSAFE is the only one implemented in V1.
Example.
CLASS Mutex {
PRIVATE UNSAFE.MUTEX handle // lowers to _UnsafeHandle<pthread_mutex_t>, null-checked
INIT() { .handle = pthread_mutex_create() }
CLEANUP { pthread_mutex_destroy(.handle) } // ERROR - check MUTEX for exact syntax
}
// UNSAFE.SOCKET s // ERROR — not one of HANDLE / MUTEX / CONDVAR
Rationale. This is the carrier the kernel's lock-free atomics (AtomicBoolean, AtomicInt32, …), Mutex, and ThreadCondition use to own their C-level handle across the object's lifetime — created in INIT, destroyed in CLEANUP. For the typed handles the null-check is the safety margin over a bare opaque: a null dereference becomes a catchable EmptyHandleError rather than memory corruption. UNSAFE.HANDLE needs none, because Envzn code cannot dereference it; its safety is that it always starts null and is only handed to C.
(c) Rule. The UNSAFE { … } block. A FOREIGN_TYPE BIND handle — an Envzn name bound to a concrete C struct or type (ENVZN_IR_SPEC.md C.vi) — lowers to a raw, untracked C pointer. Reaching through it, reading or writing a field like p.ai_family, is a memory-unsafe operation whose validity the compiler cannot vouch for. Every such access must sit lexically inside an UNSAFE { … } block; a bare access outside one is diagnostic E3036. The block is purely a compile-time gate, lowering to an ordinary C++ scope with no runtime effect. The gate does not cross a task boundary: a CONCURRENT or PARALLEL body nested inside an UNSAFE block is not itself unsafe, because a spawned task does not inherit the lexical scope.
Example.
UNSAFE {
int32 fam = p.ai_family // OK — field access through a FOREIGN_TYPE handle, gated
}
// int32 fam2 = p.ai_family // ERROR E3036 — bare access outside an UNSAFE block
Rationale. Reaching through a raw C pointer is exactly the operation the compiler can't vouch for, so it must be lexically fenced and greppable. The gate is compile-time only (no runtime cost) and does not follow a spawned task, because the task's body is a new lexical scope that never inherited the fence.
(c.i) Rule. A companion confinement rule keeps the raw pointer from escaping: a FOREIGN_TYPE handle may not be a class field, a method parameter, or a return type (E3037) — it lives only as an UNSAFE-block-scoped local. A C handle that must persist across calls is stored instead as an opaque field — the confinement-legal carrier of I.D.v — and rehydrated inside an UNSAFE block. Within the block the compiler auto-wraps and unwraps between an opaque and the typed handle at each FOREIGN call boundary, so the field is read and assigned directly as though it were the typed pointer. The assigned value may be any expression of the handle type: a FOREIGN call result, or a typed local filled through a LOAD out-parameter (.db = handle); the same holds for an opaque local. The explicit spelling opaque[H]->wrap(h) / opaque[H]->unwrap(d) of I.D.v (c) is equally legal inside the block. Outside the block no such conversion is offered.
Example.
CLASS TlsConnection {
PRIVATE opaque ssl // persistent SSL* held as opaque (confinement-legal)
METHOD send(ByteBuffer data) {
UNSAFE {
SSL_write(.ssl, data) // .ssl auto-rehydrates to the typed handle in-block
}
}
}
// CLASS C { PRIVATE FOREIGN_TYPE addrinfo ai } // ERROR E3037 — FOREIGN_TYPE handle as a field
Rationale. Confining the raw handle to UNSAFE-block locals stops an untracked pointer from leaking into fields, parameters, or returns where the checker could not follow it. The opaque/typed auto-wrap lets a handle persist across calls without ever exposing the raw pointer outside the fence. The Networking TLS and socket layers are the worked examples — persistent SSL* / SSL_CTX* handles held as opaque, every OpenSSL and POSIX call made inside UNSAFE.
(d) Rule. Choosing between an UNSAFE.<NAME> handle and an opaque field. Both persist a foreign handle across calls, and they are not interchangeable — the choice follows the handle's shape. An UNSAFE.<NAME> field carries a raw, untyped C pointer of one of three blessed kinds — a void*, an OS mutex, an OS condition variable — with no runtime type tag. It is handed directly to a FOREIGN BIND function, and its safety margin is the intrinsic null-check (b). An opaque field (I.D.v) carries a typed value behind a runtime type tag. For FFI it holds a FOREIGN_TYPE BIND typed handle such as an SSL*, which the compiler auto-rehydrates to and from the opaque at each FOREIGN call inside an UNSAFE block (c.i). An opaque is the right carrier for exactly two kinds of handle: a typed FOREIGN_TYPE pointer and an object handle. Each is recovered by its own type — the typed handle by wrap / unwrap and the automatic read at a FOREIGN call, the object by unwrap — so what comes out is what went in. An opaque is not a carrier for an untyped void*: a bare opaque handed to a FOREIGN BIND void* parameter is not read for the developer, because the payload could be any type and a read of it as a pointer (peek) may return something the developer does not expect. UNSAFE.HANDLE is the best carrier for an untyped pointer — a true void*: its field is the bare pointer, null-checked, with no tag to consult. An opaque stores a C handle in place, with no allocation, but it still pays for its runtime tag and for the wrap / peek calls at each boundary. A raw pointer read on a hot path with no type to track — a growable buffer's backing store, an atomic cell — likewise belongs in UNSAFE.HANDLE. opaque's tag earns its keep only where there is a type worth tracking. (and that opaque was the better choice for a void* field.) Reach for UNSAFE.HANDLE for any untyped pointer, a true void*, and for UNSAFE.HANDLE / .MUTEX / .CONDVAR when the field is a single raw pointer of one of those three kinds, owned INIT→CLEANUP and passed to bare C functions (the kernel's AtomicX, Mutex, ThreadCondition). Reach for opaque when the handle is a typed FOREIGN_TYPE pointer you want carried type-tagged and rehydrated, as with Networking's SSL* / SSL_CTX*, or an object handle. Reach for it also — this is opaque's primary purpose, unrelated to FFI — when you need heterogeneous typed storage, such as a Dictionary holding a different value type per key.
UNSAFE.<NAME> |
opaque field |
|
|---|---|---|
| Carries | a raw, untyped C pointer | a typed value behind a runtime type tag |
| Blessed kinds | exactly three — HANDLE, MUTEX, CONDVAR |
any Envzn type; any typed FOREIGN_TYPE pointer — never an untyped void* |
| As a class field | yes (PRIVATE / INTERNAL) |
yes (confinement-legal carrier, I.D.v) |
Crossing FOREIGN BIND |
passed directly, as the pointer | auto-wrap/unwrap to the typed handle inside UNSAFE |
| Absence / failure | null deref → EmptyHandleError (I.M.ii) |
unloaded → unwrap pipe-XOR STATUS failure (I.D.v) |
| Copy | none — the field is the pointer | := moves it; clone() deep-copies, and raises CloneError for a C handle (I.D.v (c)) |
| Primary use | one OS/C handle owned INIT→CLEANUP; any untyped void* |
heterogeneous typed storage; object handles; persistent typed FFI handle |
Example.
// UNSAFE.HANDLE — a raw C pointer handed straight to FOREIGN BIND (the atomics / Mutex pattern)
CLASS AtomicInt32 {
PRIVATE UNSAFE.HANDLE native // an _Atomic int32 on the heap; a void* carrier
METHOD store(int32 v) { ev_atomic_i32_store(.native, v) } // passed directly across FOREIGN BIND
}
// opaque — a TYPED FOREIGN_TYPE handle carried across calls (the Networking TLS pattern)
CLASS TlsConnection {
PRIVATE opaque ssl // SSL* held type-tagged; confinement-legal
METHOD send(ByteBuffer data) {
UNSAFE { SSL_write(.ssl, data) } // .ssl auto-rehydrates to the typed SSL* in-block
}
}
// opaque's primary, non-FFI purpose — heterogeneous typed storage (I.D.v)
Dictionary[String, opaque, DefaultHasher[String]] props
props["port"] := opaque[int32]->wrap(8080) // each value a different type behind a tag
Rationale. The two carriers answer two different questions. UNSAFE.<NAME> answers "I hold one raw C handle of a known kind and want to pass it to C with a null-check for a safety margin"; opaque answers "I hold a typed value whose type the static system can't otherwise track" — whether that value is a FOREIGN_TYPE pointer persisted across calls or an ordinary Envzn value in a heterogeneous collection. Using opaque for a raw OS handle would pay for a type tag and wrap/unwrap ceremony the handle does not need. Using UNSAFE.HANDLE for a typed FFI pointer would throw away the tag that lets the compiler rehydrate it safely at the FOREIGN boundary. Matching the carrier to the handle's shape keeps each escape as small and as checked as it can be — the I.A "relocate the cost inward" tiebreak applied to the FFI surface.
(a) Rule. A method's return reference-kind is normally fixed by its signature, which forces a type readable through both a const and a mutable receiver to declare two near-identical accessors. Envzn collapses that pair with a mirror accessor: a non-MODIFY method whose primary return is a MUTABLE REFERENCE. Its declared kind is a ceiling and the receiver's mutability a floor, so the reference a call yields is min(ceiling, receiver). A mutable receiver gets the writable MUTABLE REFERENCE; a const (REFERENCE) receiver gets a read-only REFERENCE. There is no call-site marker — selection is by the receiver's mutability alone, and the one source method serves both. A MODIFY method returning MUTABLE REFERENCE is not a mirror (it stays mutable-only), and a method returning a plain REFERENCE stays read-only always.
Example.
// Dictionary.lookupRef is a mirror: one accessor replacing lookupReference / lookupMutableReference
MUTABLE REFERENCE Widget mw =@ shelf[i] // mutable receiver → writable reference
REFERENCE Widget ro =@ frozenShelf[i] // const/REFERENCE receiver → read-only reference
Rationale. Selection by receiver mutability, with the declared kind as a ceiling and the receiver as a floor, lets one source method serve both const and mutable callers. It collapses the near-identical accessor twin: Dictionary.lookupRef in place of the former lookupReference / lookupMutableReference pair.
(b) Rule. Mirror selection rests on a single mutability predicate over the receiver. A receiver is const exactly when it is a REFERENCE borrow, or a SELF-rooted path inside a non-MODIFY method. It is mutable otherwise: a MUTABLE REFERENCE, an owned value, a plain value parameter (whose handle is shallow-const but whose pointee may be mutated, I.I.vi), or SELF inside a MODIFY method.
Rationale. Grounding the selection in one predicate — const iff REFERENCE-borrow or a non-MODIFY SELF-path, mutable otherwise — keeps a mirror's behaviour fully determined by the receiver at each call. There is no call-site marker to get wrong.
(c) Rule. Tightening a reference is always legal: a mirror's MUTABLE REFERENCE result may be bound (=@) into a REFERENCE. Loosening is always an error. A MUTABLE REFERENCE may not be =@-bound from a result the receiver's mutability narrowed to a read-only REFERENCE (diagnostic E6067), since that would widen a read-only borrow back to writable.
Example.
REFERENCE Widget ro =@ mutableShelf[i] // OK — tighten a MUTABLE REFERENCE result to REFERENCE
// MUTABLE REFERENCE Widget mw =@ frozenShelf[i] // ERROR E6067 — loosening a read-only borrow to writable
Rationale. Selection is realized by emitting a mirror as two C++ forms — const T* f() const and T* f(), and across an interface two virtual slots — so overload resolution picks the correct referent const-ness. The loosening rule is enforced in the analyzer (E6067) rather than merely by the C++ backend, so it holds for a backend without overload resolution.
The fixed library of aggregate types — arrays, the eight collections, and the iterators they hand out — together with STRUCT and GROUP and the move/copy convention that governs putting values into a collection and taking them back out.
(a) Rule. An aggregate holds many values under one name. Envzn provides a fixed standard library of aggregate types — the array, eight collections, and the iterators they hand out — together with two further grouping constructs: STRUCT for a pure-data record and GROUP for a named set of related types. This library is closed: user code does not add a new aggregate — a new collection or storage engine. It may, however, declare a parametric class of its own, so long as that class wraps a library aggregate rather than reimplementing one. A program needing a specialized container — RingBuffer[T], a null-aware Column[T] — writes exactly such a class, holding a T[] or a collection as a private field. Such a class is subject to the bounded-genericity rules of I.K.ix: a mandatory TEMPLATE: qualifier, no unconstrained ANY, no compile-time metalanguage. Being an ordinary declaration, it may live in the kernel or in any module, and be instantiated across a module boundary through the module's exported headers.
Example.
int32[] primes // the array — foundation aggregate
Array[Token] parsed // one of the eight collections
STRUCT Point { int32 x; int32 y } // pure-data record
GROUP Shape { Circle, Rectangle } // named set of related types
FINAL CLASS RingBuffer[T] { // a specialized container = a class wrapping a library aggregate
PRIVATE T[] storage
// ...
}
Rationale. The library of aggregates is fixed, and the grouping constructs are few, because Envzn refuses a container metalanguage (bounded genericity, I.A): the low-level storage machinery lives in the kernel and is not re-invented. A user parametric class is not that machinery — it is a typed wrapper over it (RingBuffer[T] over T[]), which composes the fixed aggregates without enlarging them. Permitting the wrapper while closing the aggregate set keeps the surface small without denying the one construct — a container specialized to its element type — that data-domain modules such as mda genuinely need.
(a) Rule. Envzn provides two array forms whose distinction is driven by the element type. A type T is blittable, defined formally in the Appendix, when its value can be copied by a flat byte-copy. That covers every primitive, and any STRUCT or VALUE CLASS whose every data field is transitively blittable. No member of the String family is blittable. A String is an owning handle to its storage, which the no-handles clause below excludes, and the same is true of DynamicString, ByteBuffer, and DynamicByteBuffer. A value class qualifies on its stored fields alone, provided it declares no EXTENDS: its methods and any IMPLEMENTS leave the value's bytes untouched, and so do not affect blittability. A blittable type has no handles to other instances and no REFERENCE fields; its value lives entirely in its own bytes. A plain heap CLASS instance is always an owning handle, so a CLASS[] is always the object-array, never a value-array. T[] is the array for every element type T: the storage backing divides on this property, and is otherwise transparent to the developer.
Example.
int32[] a // blittable element → value-array backing
Token[] b // non-blittable (Token is a class) → object-array backing
Rationale. A single spelling T[] covers every element type; the developer never chooses the backing. Blittability is what lets the value-array skip per-element ownership machinery, so the split is a performance decision the compiler makes, not a surface the developer manages.
(b) Rule. For blittable T, the syntax T[] (unbounded) and T[N] (fixed-capacity) declares a value-array: a contiguous buffer of T whose copy semantics are a deep value copy of every slot. Its API is deliberately minimal, and the developer never names its underlying class.
Example.
int32[] primes = [2, 3, 5, 7, 11] // contiguous, deep-value-copied on assignment
uint64[8] hash_state // fixed-capacity value-array
Rationale. The value-array is the form reached for whenever the elements are plain numbers, strings, or data records — the Ryu lookup table, the FNV constants, the bytes of a hash state, the rows of a fixed-shape struct. A flat byte layout is exactly what is wanted there, and the larger collection API would be dead weight.
(c) Rule. For non-blittable T — a class instance, an interface, a struct carrying references — T[] is an object-array. Each element is an owning handle, and copying the array clones every element, so the copy owns its own deep copies rather than aliasing the originals. The object-array exposes the same minimal surface as the value-array. Array[T], the class-typed collection wrapper whose richer surface (append, insert, map / filter / reduce, …) is described in I.J.ii, is layered over T[].
Example.
Token[] tokens // object-array — each slot an owning handle
Array[Token] parsed // the rich-API collection wrapper over Token[]
Rationale. Because both backings expose the same surface, T[] is genuinely the array for every element type. A developer reaches for Array[T] when the workload wants the larger API rather than the bare storage surface.
(d) Rule. The sole outward difference between a blittable T[] and an object T[] is how an element is relocated. Because Envzn keeps no class instance on the stack — every class value is a handle to a heap object — an object element is never implicitly value-copied. Moving an owned value into a slot uses :=, which transfers ownership and poisons the source (a[i] := obj). A slot is never moved out of with :=: a[i] is a reference to an element the array keeps owning (I.G(d)), so x := a[i] and a[k] := a[j] are compile errors, diagnostic E6040. An element leaves an array through a->remove(i) and moves within one through a->swap(i, j); Array[T] adds replace(i, v), which stores v and returns the element it displaced. A plain = between object slots is rejected, diagnostic E5025, because it would silently clone the handle; for a blittable element, where move and copy coincide, = is permitted. An element whose value class holds owning fields is an object element for these rules. A whole-array := from a local (Widget[] b := a, or b := a) moves the array: the handle transfers and a is poisoned, so a later read of it is use-after-move (E3010); a copy is spelled b := DUPLICATE a. Reading an object element binds a reference (REFERENCE T x =@ a[i]) or takes an explicit copy (T x := DUPLICATE a[i]); a value element additionally permits a value read (T x = a[i]).
Example.
int32[] primes = [2, 3, 5, 7, 11] // value-array — blittable element; `=` writes
Token[] tokens // object-array — Token is a class; `:=` relocates
Array[Token] parsed // the rich-API collection wrapper over Token[]
tokens[2] := obj // move an owned local into a slot
tokens[3] = obj // ERROR — E5025: `=` would silently clone the handle
tokens[0] := tokens[1] // ERROR — E6040: tokens[1] is a reference to a slot
tokens->swap(0, 1) // move between slots — no slot is ever empty
REFERENCE Token r =@ tokens[0] // non-owning read of an object element
Token t := DUPLICATE tokens[0] // owned copy of an object element — explicit
Token u := tokens->remove(0) // take the element out; the array shrinks
Token bad := tokens[0] // ERROR — E6040: := from a reference
int32 p = primes[0] // value read — permitted only for blittable elements
Rationale. The operator carries the meaning: := makes ownership transfer visible at every slot write, and rejecting = on object slots prevents a silent alias. Blittable elements can use = because for them move and copy are the same byte-copy, so nothing is hidden.
(e) Rule. Both backings expose one surface: .length and .capacity as read-only fields, indexed access with [ ] through both reads and writes, a clear() method that resets length to zero while leaving capacity intact, a remove(i) method that moves element i out and shifts the tail down, a swap(i, j) method that exchanges two elements in place, an equals(other) method that reports whole-array value-equality (e.i), and an iterator() method that returns a forward Iterator OF T whose .item yields each element by value for a value-array and by reference for an object-array. Nothing else is on the surface — no append, no insert, no map / filter / reduce.
Example.
int32[] xs := CREATE(16)
int32 n = xs.length // read-only field
int32 c = xs.capacity // read-only field
xs[0] = 42 // indexed write
int32 v = xs[0] // indexed read
xs->clear() // length → 0, capacity kept
ValueIterator OF int32 it := xs->iterator() // forward iterator over the value-array
WHILE it->nextValue() DO { // pipe-XOR navigation (I.M.i)
int32 v = $RETURNED // bound first (I.M.i(c.iii))
printline((v INTO String))
}
Rationale. The array is the shape for a known, contiguous buffer. A workload that needs append, insert, or map is asking for Array[T], so those methods live there and not on the bare storage type.
(e.i) Rule. T[]->equals(other) reports value-equality: two arrays are equal when they have the same length and every element pair is equal. It is the only equality an array has: == and != are not defined between arrays of any shape (T[], T[N], T[N+], N-D), and writing either is a compile error (E2168) that points at ->equals(). An array's elements still compare with == (a[i] == b[i]). How an element pair is compared is fixed by the element type, and invisible at the surface. A value-array whose element T has a unique object representation — the integer, char, binary, and boolean types — compares by a single length-checked byte compare, so equality is one memcmp. A float/double element compares element-wise with IEEE ==, so -0.0 equals +0.0 and NaN is unequal to itself — outcomes a byte compare would get wrong. A value-class element (a String-family value, DynamicString, …) and every object-array element compare element-wise through the element's own ->equals(), with two EMPTY object slots equal and an EMPTY-versus-present pair unequal. Because a class or value-class element is compared through ->equals(), its type must implement Equatable. A T[]->equals() whose element type is a non-Equatable class is a compile error (E5026); a primitive element carries no such requirement.
Example.
int32[] a = [1, 2, 3]
int32[] b = [1, 2, 3]
boolean same = a->equals(b) // TRUE — one memcmp (int32 is uniquely represented)
String[] xs := csv->split(",")
String[] ys := csv->split(",")
boolean eqs = xs->equals(ys) // element-wise String->equals(); String IS Equatable
// Widget[] w // Widget lacks IMPLEMENTS Equatable →
// w->equals(other) // ERROR E5026
Rationale. One equals on the shared surface gives every array a value-equality test whose lowering the compiler picks: memcmp where byte-equality is value-equality, IEEE == for floats, ->equals() for elements that define their own equality. The reader writes one call and the machinery stays inside the kernel — the I.A "relocate the cost inward" tie-break applied to array comparison. Requiring Equatable for a class element is the same "world-class or diagnosed" stance the Set element (E2114) and Dictionary key (E2037) already take.
(f) Rule. On the growable forms — the unbounded T[] and the pre-sized T[N+] — indexed write x[i] = v observes a high-water mark rule. The write always proceeds: capacity grows to admit i if it must, and length := max(length, i + 1). capacity is an allocation hint — what CREATE(n) reserves up front to avoid reallocation — never a bound on what may be written, so no index is "past capacity" on a growable form. Slots between the previous length and i, exclusive of i itself, are zero-filled. The zero for a primitive is its numeric zero, for a String the empty string, and for a struct the all-field-zero default initialization. The same rule covers append: writing x[length] = v extends length by one, with no intermediate slots to fill. The fixed-size T[N] of (h) is exempt. All N slots are live from construction (length == N), so it is indexed and mutated directly, with no high-water-mark bookkeeping and no append.
Example.
int32[] xs := CREATE(8) // capacity 8, length 0
xs[0] = 10 // length → 1
xs[xs.length] = 20 // append idiom — writes at index == length, length → 2
xs[5] = 99 // length → 6; slots 2,3,4 zero-filled (numeric 0)
xs[100] = 7 // capacity grows; length → 101; slots 6..99 zero-filled
Rationale. The high-water-mark rule gives a single, predictable meaning to every write on a growable array and makes x[length] = v the append primitive on a type that has no append method. The rule is deliberately blind to capacity: a bound that came from the argument to CREATE would make the same write succeed or panic depending on a performance hint, which is not something a reader can reason about locally. The fixed form is where a real bound lives — see (h), where N is part of the type and an index at or past it traps.
(g) Rule. A write that would push (length + 1) past 0.79 × capacity triggers growth before it proceeds. The new capacity is capacity + max(capacity ÷ 2, 8), with integer arithmetic, except from a capacity of zero, which seeds at 4 — the general form would yield 8 there and put every later capacity on a different trajectory. Growth repeats until the post-write length sits at or under the threshold. A zero capacity always triggers growth. Construction is lazy: an unbounded T[] starts at capacity 0 and allocates on its first write. The schedule from a default-constructed array runs 0 → 4 → 12 → 20 → 30 → 45 → 67 → 100 → 150 → 225 → 337 → 505 → …, with the growths landing on the writes at index 0, 3, 9, 15, 23, 35, 52, 79, 118, 177 and 237. A pre-sized T[N+] array starts at capacity N and follows the same rule thereafter — T[8+]: 8 → 16 → 24 → ….
The 79% threshold is computed in two regimes, because one arithmetic form cannot serve both ends of the range. At capacity ≤ 225 it is the tabulated exact value floor(0.79 × capacity) — 3, 9, 15, 23, 35, 52, 79, 118, 177. Above it the threshold is (capacity ÷ 100) × 79, divide-first: the multiply-first form overflows a signed 32-bit integer once capacity exceeds 27,183,338, and an overflow PANICs (I.F.ii(a.iv)), so a large array would trap. Dividing first makes the product unreachable at the cost of a coarser threshold, which is why the growth at capacity 337 lands on the write at index 237 rather than 266. Below capacity 100 the divide-first form yields zero, which is precisely why the small regime is tabulated rather than computed.
An explicit reservation is exempt from the threshold. CREATE(N) and reserveExact(n) set the capacity to N + 1 and set the growth threshold to the whole capacity, so writes to indices 0 … N never reallocate and the first write past the reserved range resumes the ordinary schedule. reserve(n) is the other half of the pair and carries the opposite contract: it is an incremental hint for an array still growing, so it leaves the 79% trigger in force and the fill overshoots to roughly 1.5n on its way through — which is what makes a builder that calls it with the running total on every append amortized O(1). The two share a word and nothing else, and collapsing them into one method makes such a builder quadratic. The 79% trigger is a policy for an array growing on its own, where the next size is a guess; a reservation is not a guess, and applying a growth heuristic on top of a stated size would discard the statement. The spare slot is append headroom, so "build N, then append one" is free. The threshold may equal the capacity but never exceed it — a threshold above the allocation would admit a write the buffer cannot hold.
Example.
int32[] xs := CREATE() // capacity 0 — lazy; the first write allocates 4
FOR int32 i = 0; i < 5; i = i + 1 {
xs[xs.length] = i // the append at index 3 crosses 0.79 × 4 and grows 4 → 12
}
int32[] ys := CREATE(100) // capacity 101, threshold 101 — a stated size, not a guess
FOR int32 i = 0; i < 100; i = i + 1 {
ys[i] = i // no reallocation; the schedule is not consulted
}
ys[100] = 7 // still fits — the spare slot is append headroom
ys[101] = 8 // past the reservation: the ordinary schedule resumes
Rationale. Small arrays grow by a minimum of eight slots, so a hot-path append loop does not pay for many small reallocations. Larger arrays grow by 50%, so the amortised cost of repeated growth stays predictable. A reservation is exempt because it carries information the schedule does not have: the caller already knows the final size, and a heuristic applied on top of that can only be wrong. Before the exemption a caller who reserved exactly 100 and wrote 100 elements still reallocated — at element 80 — and reserving more did not help until 200, because the divide-first threshold is constant across capacities 100 through 199. Honouring an exact request should not require a 2× overshoot.
(h) Rule. The unbounded value-array, T[] x, is constructed through CREATE() — equivalent to CREATE(4) — or CREATE(N) for an explicit starting capacity. The fixed-size form, T[N] x, is constructed implicitly. The declaration allocates N live, default-initialized slots: length is N from the outset, every slot is immediately readable and writable, and no CREATE call is required. It never grows: N is fixed and an index at or past N is IndexOutOfBoundsError. Nothing may grow or shrink it either: reserve, reserveExact, clear, appendRange, remove and convertFrom on a T[N], and reshapeTo on a fixed T[M,N], are compile errors (E2172). Its cells live inline in their owner, so a growth would ask for memory the array does not own. T[N+] is growable and keeps every growth method. Because a fixed array never relocates its storage, each element is addressable in place. arr[i] is a mutable lvalue: arr[i] = v writes a whole element, arr[i].field = v mutates a STRUCT or VALUE CLASS element's field directly, and MUTABLE REFERENCE T e =@ arr[i] binds a mutable borrow into the buffer. A bare REFERENCE binds a read-only borrow. This in-place mutability is the fixed form's alone; the growable forms present each element through a write proxy and follow the high-water-mark rule of (f) instead.
Example.
int32[] xs := CREATE(16) // growable — starting capacity 16, length 0
String[] ys := CREATE() // growable — starting capacity 4, length 0
uint64[8] hash_state // fixed — 8 live slots, length 8, no CREATE call
hash_state[3] = 1 // in-place write to an existing slot
hash_state[8] = 1 // ERROR — IndexOutOfBoundsError: index at/past N
Point[4] quad // fixed array of a value class — 4 live slots
quad[0].x = 5 // in-place field mutation of an element
MUTABLE REFERENCE Point p =@ quad[1] // mutable borrow into the buffer
p.y = 9 // writes through to quad[1]
Rationale. The unbounded form is a heap buffer that must be sized, so it takes a CREATE. The fixed form is a known-size allocation the declaration itself pins down, so requiring a CREATE would be ceremony. Its slots are live from the start: a fixed array is its N elements, not an empty buffer to fill. Because its size is fixed and its storage never moves, it can safely hand out a genuine mutable reference to any slot — the basis of arr[i].field = v — where a growable array, which may relocate on the next write, cannot.
(i) Rule. A CONSTANT T[] field, like the primitive CONSTANT of I.K.i, takes a literal array initialiser. The compiler infers capacity from the literal's element count, length equals capacity, and every slot is read-only thereafter. CONSTANT T[N] is the explicit form: the literal must contain exactly N elements or the compiler fires E1084. A CONSTANT value-array is only legal for blittable T; the form lowers to a static constexpr storage that lives in the program's read-only data and never re-allocates.
Example.
PRIVATE CONSTANT uint64[] POW10 = [10, 100, 1000, 10000, 100000,
1000000, 10000000, 100000000,
1000000000] // capacity 9, inferred
PRIVATE CONSTANT uint64[9] POW10_EXPLICIT = [10, 100, 1000, 10000, 100000,
1000000, 10000000, 100000000,
1000000000] // same shape, explicit N
PRIVATE CONSTANT uint64[9] WRONG = [10, 100] // ERROR — E1084: literal ≠ N
Rationale. Inferring capacity from the literal keeps the common case terse; the explicit-N form lets a declaration assert its expected length, and E1084 catches a miscount. Restricting CONSTANT value-arrays to blittable T is what makes the static constexpr lowering into read-only data possible.
(j) Rule. Array literals are written with square brackets, and all elements share one type; a mixed-type literal is a compile error. EMPTY initialises a zero-length value-array, capacity zero for the unbounded form. A statically-detectable out-of-bounds access is a compile error; a runtime one panics with IndexOutOfBoundsError.
Example.
int32[] a = [2, 3, 5, 7] // all elements one type
int32[] b = [1, "two", 3] // ERROR — mixed-type literal
int32[] c = EMPTY // zero-length value-array, capacity 0
int32 x = a[9] // ERROR — statically-detectable out-of-bounds
Rationale. One element type per literal keeps the array homogeneous, under bounded genericity. Catching an out-of-bounds access at compile time, when it is statically knowable, moves the failure as early as possible; it defers to the runtime IndexOutOfBoundsError only when it cannot.
(k) Rule. One element type is rejected outright: boolean[] is a compile error, diagnostic E2083, because the runtime's element-access machinery is incompatible with the proxy-reference representation a boolean vector would need. Boolean data is stored instead as uint8[] with 0 and 1 values, and the restriction extends transitively to the collections that compose on the array. The same rule applies to Array[boolean].
Example.
boolean[] flags // ERROR — E2083
Array[boolean] more // ERROR — E2083 (same rule on the collection)
uint8[] flags = [0, 1, 1, 0] // store boolean data as uint8 with 0/1
Rationale. A packed boolean vector would need a proxy-reference element the array's uniform element-access machinery cannot represent. Rather than special-case it, the language points at uint8[], which stores the same information with the ordinary machinery.
(l) Rule. A third value-array form, T[N+], declares a pre-sized growable array: one whose backing begins at a capacity of N and grows from there on the same schedule as T[]. The + is mandatory, and is what distinguishes it from the never-growing fixed-capacity T[N] — with the +, N is a starting size; without it, N is the whole array and the array cannot grow. The dimension N is either an integer literal or a previously-declared CONSTANT, and must lie in [4, 65536]. Multi-dim chaining is not legal in this form — T[N+][M] is a compile error. The element type T must be blittable, the same constraint as the other value-array forms.
Example.
PRIVATE char32[128+] codepoints // starts at 128 codepoints, grows as needed
PRIVATE char8[512+] bytes // starts at 512 bytes, grows as needed
PRIVATE Vec3[CAP+] recent // starts at CAP positions (CAP a CONSTANT)
PRIVATE char32[128][4+] grid // ERROR — T[N+][M] chaining not legal
Rationale. The + is the visible tell that separates a growable array from the never-growing T[N]. Naming the starting size is the developer saying what they expect to hold, so a build of roughly known length performs one allocation instead of walking the growth schedule from the seed.
(m) Rule. The surface is identical to T[]: .length and .capacity reads, indexed [ ] with the high-water-mark rule, clear(), and iterator(). The only difference is the capacity the array starts at, and that difference is not observable through the surface — nothing reports it but .capacity, and nothing depends on it but the number of reallocations a build performs.
(n) Rule. The starting size is honoured only where the declaration owns the storage: a local, or a class data field. At a parameter, a return type, or a REFERENCE binding the array is supplied by the caller and already has a capacity, so T[N+] there means exactly T[] and the N is ignored.
Rationale. A starting size is a statement about an allocation, and those positions do not allocate. Reading N as a constraint on what the caller may pass would make the two spellings different types for no gain; reading it as advice would make it silently inert. It is a declaration-site hint, so it applies at declaration sites.
Note. This form was T[N+] for small-buffer optimization until the SBO backing was removed: storage for up to N elements lived inline in the enclosing struct and spilled to the heap beyond it. The measured win did not survive the removal of the inline path — the benchmarks moved by well under a percent — and the split ownership of the growth threshold between the inline and heap regimes was the defect that kept SBO from ever engaging (see I.J.i(g)). The spelling is kept because a starting size is worth naming; the inline storage is not.
(o) Rule. Beyond the one-dimensional forms above, Envzn provides a dense N-dimensional array as a first-class native type — as native as T[N], and distinct from chaining brackets. Three surface forms share one underlying shape. The type spine T[,] (rank 2), T[,,] (rank 3), and so on carries only the rank, the number of axes. It is what a parameter, field, or return type names when the extents are not part of the type. The runtime form T[m,n] declares and constructs an array whose extents are the run-time values m and n (a Fortran "automatic array"). The fixed form T[3,4] declares an array whose extents are compile-time constants. A bracket spec must be all-empty (the spine) or all-sized; mixing them — float64[m,] — is E1135. Chained brackets T[N][M] are retired: the comma form T[N,M] is the one spelling for a multi-dimensional array, and using them is E2124. A parametric Foo[K,V][] — a type-argument list followed by the array shorthand — is unaffected.
Example.
METHOD solve(float64[,] grid) RETURNS STATUS { ... } // type spine — rank 2, extents not in the type
float64[m,n] board // runtime form — extents are expressions
float64[3,4] fixed // fixed form — compile-time constant extents
float64[m,] bad // ERROR — E1135: mixing empty and sized
float64[3][4] chained // ERROR — E2124: chained brackets retired
Foo[K,V][] ok // fine — type-arg list + array shorthand
Rationale. The comma inside the brackets is the N-D tell. Retiring chained brackets leaves exactly one spelling for a multi-dimensional array.
Because the element type may be an object (p), the comma is not by itself decisive: Foo[A,B] is token-identical to a parametric instantiation. The rule is that a slot shape a type-argument list could never hold settles it as N-D at once: an empty slot (Foo[,]), an integer literal (Foo[3,4]), or any other expression (Foo[n+1,m]). An all-identifier list (Foo[m,n]) is settled after name resolution on the head, since a type that takes no type parameters cannot be instantiated — so String[m,n] has exactly one available reading. This is the same deferral the single-bracket T[X] form already uses, where X is resolved to a class-scope CONSTANT before the fixed-array reading is chosen. Extents are values; type arguments are types. The grammar records the rule in Article III.
(p) Rule. The element type may be a primitive (the blittable numeric path: float64, float32, the integer widths) or an object — a String, a CLASS, an INTERFACE, a VALUE CLASS, or a non-blittable STRUCT. The two are the same language surface; they differ only in the storage the compiler selects (see the lowering rule (t)) and in the cell semantics below. The layout is column-major (Fortran / Julia / BLAS order: axis 0 is the contiguous, stride-1 axis), a fixed property of the language, not a per-array choice. Indices are 0-based. The rank is capped at 15. There is no CREATE for the array itself: like T[N] and the number primitive, an N-D array is constructed implicitly by its declaration.
An N-D array does not grow, so it has no analogue of the 1-D high-water-mark append; an object cell is therefore EMPTY at declaration and is filled in place. A cell whose element is handle-stored — a String, a CLASS, an INTERFACE — reads as EMPTY until it is assigned. It is tested with IF a[i, j], exactly like any other bare-type-with-EMPTY value (I.D.iv). A cell whose element is a value-stored STRUCT or VALUE CLASS is default-constructed instead, and so is never EMPTY. A primitive cell is value-initialised (zero) as before.
Example.
float64[m,n] a // implicit construction — no CREATE
// column-major: axis 0 is contiguous/stride-1; loop the first index innermost (see (s), W10094)
String[2,2] names // 4 EMPTY cells — an N-D array does not grow
names[0,0] := "alpha" // fill a cell in place
IF names[0,1] THEN { … } // EMPTY-checked read (I.D.iv)
Rationale. Column-major is fixed so numeric modules can hand the buffer straight to BLAS without a per-array layout question. The rank cap of 15 is high enough that no real array meets it, and low enough that the shape descriptor stays inline. Object elements admit the text-and-object grids the data surface needs — a column of String is a rank-1 case of the same primitive — without a second, parallel array type. The surface is one thing, and the blittable-versus-owning split is relocated inward to the compiler and kernel.
(q) Rule. An element is read and written with a single multi-coordinate subscript a[i, j] — one coordinate per axis. The coordinate count must equal the array's rank (E2122 otherwise). A fixed extent must be positive (E2123). An out-of-range coordinate is a runtime bounds violation: it PANICs with IndexOutOfBoundsError, recoverable with RECOVER, exactly as a 1-D subscript does (I.J.i(f)). The container surface is the shape-and-bulk minimum: .rank and .count (read-only fields), dim(k) and stride(k) (per-axis), fill(v), reshapeTo(p, q, …) (a descriptor-only re-extent that succeeds only when the new extents have the same total count), clone(), and isContiguous(). Binding one N-D array to another with := is a deep value copy; for an object element that copy clones every cell, and fill(v) likewise clones v into every cell.
An object cell obeys the relocation rule of I.J.i(d) verbatim, on the multi-coordinate subscript. An object element is never implicitly value-copied, so moving an owned value into a cell uses :=, which transfers ownership and poisons the source (a[i,j] := obj). A cell is never moved out of: a[k,l] is a reference to a cell the array keeps owning, so x := a[k,l] and a[i,j] := a[k,l] are E6040. A plain = between object cells is rejected, E5025. Reading an object cell binds a reference (REFERENCE T x =@ a[i,j]) or takes an explicit copy (T x := DUPLICATE a[i,j]); a primitive cell additionally permits a value read (T x = a[i,j]). A live cell reference stays valid across reshapeTo, a descriptor-only re-extent that neither reallocates nor moves data. It is invalidated by an assignment to the array as a whole: that replaces the storage the reference points into, so holding a cell reference across it is E6048. This is the same rule, and the same diagnostic, as a live reference into a 1-D collection cell.
Whole-array element-wise arithmetic — b + c, b - c, and b * c, element-wise or Hadamard rather than a matrix product — produces a fresh array over conforming operands. Both must have the same rank, and the compile-time fixed forms must have the same dims, or the operation is E2125. There is no scalar broadcast in V1; stride-0 broadcast is V2. Arithmetic is defined only for a numeric element type: +, -, and * on an N-D array whose element is an object, or any non-numeric type, is E2132. The operation is element-wise, and there is no element-wise + on a String or a class. Walk the cells instead.
Example.
float64[3,4] a
a[0, 0] = 1.0 // one coordinate per axis
a[0] = 1.0 // ERROR — E2122: rank mismatch (rank-2 array, 1 coord)
a[0,1,2] = 1.0 // ERROR — E2122: rank mismatch (rank-2 array, 3 coords)
float64[0,4] z // ERROR — E2123: fixed extent must be positive
int64 r = a.rank // read-only field — the whole extent family is int64
int64 n = a.count // read-only field
int64 d = a->dim(0) // per-axis extent
int64 s = a->stride(1) // per-axis stride
a->fill(0.0)
a->reshapeTo(4, 3) // descriptor-only; same total count; never moves data
float64[3,4] cp := a->clone()
boolean cont = a->isContiguous() // always true for a dense array
float64[3,4] b
float64[3,4] c
float64[3,4] sum := b + c // element-wise; fresh array; := deep-copies
float64[3,4] had := b * c // Hadamard (element-wise), NOT a matrix product
float64[2,4] wrong
float64[3,4] bad := b + wrong // ERROR — E2125: non-conforming dims
Rationale. Evaluation is naive — each operator materialises one temporary, free for a single operation and one extra temporary-plus-pass per additional operator in a compound expression; fused evaluation, reductions, and linear algebra (matrix multiply, decompositions) belong to the numeric module layer (AdvancedMath) that builds on this substrate and owns the performance trade-off.
(q.i) Rule — the coordinate iterator. FOR (i, j) IN a visits every cell of an N-D array, binding one coordinate per axis. The coordinate count must equal the array's rank (E2122), exactly as a subscript's must. Each coordinate is an int64, the width of the N-D extent family. The walk is column-major by construction: the compiler places axis 0 — the contiguous, stride-1 axis — in the innermost loop and the highest axis in the outermost, so the coordinates are written in natural order while the traversal is always cache-optimal and a cache-hostile nest (W10094) cannot arise. Each axis runs over [0, dim(k)) of the array being walked, so a zero extent visits nothing. The form serves every N-D array — runtime or fixed shape, numeric or object element. It is the idiomatic way to walk an N-D array; an explicit nest of FOR i = 0 UNTIL a->dim(0) loops is equivalent but leaves the loop order, and so the cache behaviour, to the writer.
Example.
float64[3,4] a
FOR (i, j) IN a { // j outer, i inner — axis 0 innermost
a[i, j] = 1.0
}
float64 total = 0.0
FOR (i, j) IN a { total = total + a[i, j] }
FOR (i, j, k) IN a { … } // ERROR — E2122: rank-2 array, 3 coordinates
Rationale. Column-major is a property of the language (p), so the order that walks it well should not be something every writer has to remember. Writing the coordinates in reading order and letting the compiler invert the nest relocates that knowledge inward (I.A). Because the extents come from the array itself, every a[i, j] inside the loop is in range by construction, which is also what makes this the form a bounds-check elision can discharge with no guard at all.
(s) Rule. The substrate exposes its raw contiguous column-major buffer as a first-class performance seam so a numeric module can hand it straight to a tuned loop or a C-ABI BLAS without copying. The seam exists only for a numeric element type — an owning handle has no meaning across a C ABI — so it is unavailable, by construction, on an object-element array. The fixed form T[3,4] stores its elements inline, with no heap and no pointer. When the element is blittable this makes the fixed-shape N-D array itself blittable, and therefore nestable inside a STRUCT or another array. When the element is an object the fixed form is still inline but not blittable, since it owns its cells, and so is not nestable in a blittable aggregate. The runtime form T[m,n] holds a heap buffer and is never blittable. A cache-hostile loop nest — one whose innermost loop strides a slow (non-contiguous) axis — draws the advisory W10094, which suggests reordering the loops so the contiguous axis runs innermost. The lowering is given in (t) and in ENVZN_IR_SPEC.md: a runtime T[m,n] is the kernel PRIMITIVE NativeNdArray[T], and a fixed T[3,4] is C's own cells, flat and column-major, with every cell zero when it is allocated.
Example.
float64[3,4] a
STRUCT Tile { float64[2,2] block } // fixed form is blittable → nestable in a STRUCT
FOR int32 j = 0; j < a->dim(1); j = j + 1 { // contiguous axis 0 innermost — cache-friendly
FOR int32 i = 0; i < a->dim(0); i = i + 1 {
a[i, j] = 0.0
}
}
// striding axis 1 in the inner loop instead → advisory W10094
Rationale. Exposing the raw buffer lets a numeric module reach BLAS without a copy; making the fixed form inline/blittable lets it nest in structs and arrays; W10094 nudges the loop order toward the contiguous axis without forbidding the slow shape.
(t) Rule. Every array is a native one. The runtime forms are two kernel PRIMITIVEs written in Envzn, which a developer never names (E2173): T[] and T[N+] are NativeArray[T], and T[,] / T[m,n] is NativeNdArray[T], each over a C descriptor (STRUCT EvArr, STRUCT EvNdArr) and the C floor that does every element-wise loop and every allocation once, for every T. The two forms of T[] differ only in the capacity the array begins at. A fixed T[N] or T[M,N] is not a class at all but C's own cells, inline and zeroed at the allocation, and a CONSTANT table is static constant cells. Where a method, an operator, a whole-array copy or a REFERENCE T[] / REFERENCE T[,] parameter needs an array, the compiler presents the cells as a REFERENCE view of the native array, which owns nothing and can never grow, so one body serves the fixed and the runtime forms, and a fixed array's shape queries are the constants its type states. What stays an IR node, lowered by each backend in place, is the subscript, the growing write a[i] = v, an array literal and a FOREIGN crossing. Whether a subscript is checked is decided before any backend sees it: every coordinate carries its bounds check as an explicit node of the EvIR, except one loop elision or HOTLOOP proved in range (I.H), which is a proven access with no branch, and the compiler's own loops (FOR … IN over an array, the hoisted range checks) are written out as ordinary EvIR. A failed check raises IndexOutOfBoundsError.
Rationale. Writing the arrays in Envzn over a C floor is what lets a backend other than C++ translate them without first having to understand a C++ template, and stating every bounds decision in the EvIR is what lets two backends agree on it without either deciding it a second time (I.A, relocate the cost inward). The fixed form being plain cells is the same shape T[N] already had, and the one an alloca with a zeroinitializer spells in LLVM.
(a) Rule. Beyond the array, the kernel ships eight collection types, summarized below. Each has both a bracket short form and an OF long form, and the two are identical to the compiler.
| Collection | Short form | Shape |
|---|---|---|
Dictionary |
Dictionary[K, V, H] |
interface; pluggable hasher H; pure-Envzn HIDDEN impls behind it (ChainedHashDictionary unordered; RedBlackTreeDictionary ordered/K Comparable; ProHashDictionary SipHash-128 DoS-resistant); unique keys |
Set |
Set[V, H] |
concrete wrapper over a Dictionary (element is the key); pluggable hasher H; unique values, unordered |
Box |
Box[T] |
single-slot heap indirection, for recursive types |
Queue |
Queue[T] |
first-in, first-out |
Stack |
Stack[T] |
last-in, first-out |
Deque |
Deque[T] |
double-ended queue |
LinkedList |
LinkedList[T] |
doubly-linked list |
SortedList |
SortedList[T] |
insertion-sorted sequence |
Example.
Queue[Token] q // bracket short form
Queue OF Token q2 // OF long form — identical to the compiler
Rationale. The two spellings exist so a declaration can read either way; they compile to the same type.
(b) Rule. Every collection default-initializes to EMPTY, supports FOR IN, and exposes an ->iterator() method. Bracketed collection types compose by nesting directly; the OF form parenthesizes an inner parameterized type.
Example.
Dictionary[String, Array[Token], DefaultHasher[String]] index // bracketed types nest directly
Dictionary OF (String, Array OF Token) idx2 // OF form parenthesizes the inner parameterized type
FOR t IN q { ... } // FOR IN
LOOP t IN q WITH INDEX i { ... } // FOR IN, carrying the position
ReferenceIterator OF T it := q->iterator() // explicit cursor — WHILE-consumed
WHILE it->next() DO { ... }
Rationale. Direct nesting keeps the bracket form compact; the OF form parenthesizes its inner parametric type to keep the grouping unambiguous when written long-hand.
(c) Rule. The Dictionary interface ships three pure-Envzn implementations; the choice is made by which concrete class is CREATEd, since the interface is held uniformly. ChainedHashDictionary is the general-purpose default — a separate-chaining hash table, unordered, O(1) average. RedBlackTreeDictionary is the ordered map — a guaranteed-O(log n) left-leaning red-black tree that iterates in key order and therefore additionally requires K to be Comparable. ProHashDictionary is the hardened table for untrusted keys — keyed by SipHash-2-4-128, caching the full uint128 digest per entry. Hashing for the hash-based impls is supplied through the H (Hasher OF K) type parameter, and the kernel ships a small hasher family: DefaultHasher (FNV-1a, the hasher constructed when none is named), StringHasher, and SipHasher (keyed SipHash; the default inside ProHashDictionary). Set[V, H] wraps a Dictionary, so the same hasher choices apply to it.
Example.
Dictionary[String, int32, DefaultHasher[String]]
a := CREATE ChainedHashDictionary[String, int32, DefaultHasher[String]]() // hold interface, CREATE impl
Dictionary[String, int32, DefaultHasher[String]]
b := CREATE RedBlackTreeDictionary[String, int32, DefaultHasher[String]]() // ordered; K must be Comparable
Dictionary[String, int32, SipHasher[String]]
c := CREATE ProHashDictionary[String, int32, SipHasher[String]]() // DoS-resistant, keyed SipHash
Set[String, StringHasher[String]] s := CREATE Set[String, StringHasher[String]]()
Rationale. Holding the interface uniformly and selecting behaviour at the CREATE site lets a caller swap ordering or DoS-resistance without changing the variable's type. The hasher H slot keeps the hash function pluggable rather than baked in.
(c.i) Rule — set algebra. Three operators combine two Sets into a new Set, leaving both operands unchanged: a |+| b is the union, a |&| b the intersection, and a |-| b the difference (the elements of a not in b). They bind to the kernel methods unionWith, intersectionWith and differenceWith. |+| and |-| sit at additive precedence and |&| at multiplicative. Both operands must be Set-typed (E2034) and the element type must implement Cloneable, since the result holds copies.
(d) Rule. Every method that takes a value to store comes in two named forms. The bare-named form — append, push, enqueue, insert, add, prepend, and the rest — declares its value-to-store as a plain parameter, which owns (I.I.vi). It moves the value into the collection and poisons the source, so for a class-typed value a later use of the source at the call site is a compile error. The *Copy form — appendCopy, pushCopy, insertCopy, and so on — takes the same value as a REFERENCE parameter and stores a deep copy, leaving the source fully valid. The analyzer recognizes the move-on-call behavior from the parameter's mode, not from the method's name.
Example.
Queue[Token] q
q->enqueue(tok) // move — tok is consumed; later use of tok is a compile error
q->enqueueCopy(other) // deep copy — other stays valid
// a user-defined collection following the same naming gets the same enforcement,
// because the parameter's mode — not the name — drives it
Rationale. For a primitive or a String the two forms are observably identical, since those copy by value regardless. The distinction carries weight for class-typed elements, and stating it through two method names rather than one overloaded one means a reader of the call site can see which happened. Because enforcement keys off the parameter's mode, a user-defined collection that follows the append/appendCopy naming gets the same enforcement automatically.
(e) Rule. An accessor that may legitimately find nothing returns the pipe-XOR shape (T value | STATUS s) described in I.M: a present value on the success branch, a FAILURE status when the collection is empty or the key is absent. That covers dequeue and peek on a queue, pop on a stack, first and last on a sorted list, and lookup on a dictionary. Those accessors are consumed by an IF whose condition is the call, and not assigned directly.
Example.
IF q->dequeue() THEN {
Token next := $= // success — the dequeued value
}
ELSE {
// the queue was empty — $! is the failure message
}
Rationale. The accessors reuse the language's existing failure vocabulary (I.M) rather than inventing one, so "might find nothing" is expressed the same way everywhere and cannot be silently ignored.
(f) Rule. The accessors carry a stronger guarantee than the pipe-XOR shape alone implies: when the success branch fires, the value returned is real, not EMPTY. The mutators that store a value reject an EMPTY class-typed source at entry, with a FAILURE status and before any state change. They are append, prepend, push, enqueue, insert, add, setAt, and their *Copy siblings. A successful peek / pop / at / lookup therefore returns an IS VALID value by construction. The check is gated on the stored type being class-shaped, through the WHEN T IMPLEMENTS Cloneable proxy in the kernel implementations. It is elided for primitive and struct elements, where EMPTY is not a possible state (I.I.iii).
Example.
Queue[Token] q
q->enqueue(tok) // move — tok is consumed
q->enqueueCopy(other) // deep copy — other stays valid
IF q->dequeue() THEN {
Token next := $= // success — guaranteed IS VALID, never EMPTY
}
ELSE {
// the queue was empty
}
Rationale. By refusing an EMPTY class-typed value at the store site, the collection only ever holds populated handles, so a caller who took the success branch never has to re-check for EMPTY. The gate is elided for primitive/struct elements because those cannot be EMPTY (I.I.iii).
(g) Rule. Dictionary keys must implement Equatable and be hashable; Set elements likewise; SortedList elements must implement Comparable. Box[T] is the exception: a single-slot, heap-allocating wrapper whose purpose is to break the type cycle that a recursive GROUP member would otherwise create. A Box[T] field is transparent: reading it yields T directly, and a MATCH sees T. It is never EMPTY, because it always holds a value, so a class with Box fields always provides an INIT that sets them.
Example.
Dictionary[String, int32, DefaultHasher[String]] d // String key: Equatable + hashable — OK
SortedList[int32] sl // int32 element: Comparable — OK
GROUP Tree { Leaf, Node }
STRUCT Node { Box[Tree] left; Box[Tree] right } // Box breaks the recursive type cycle
// reading a Box[Tree] field yields Tree directly; it is never EMPTY, so INIT must set it
Rationale. Keys and elements carry the contracts their collection needs (equality/hashing for hash keys, ordering for sorted elements). Box is the deliberate exception because its only job is to introduce a heap indirection that breaks an otherwise-unresolvable recursive type cycle, so it is transparent and always populated.
The Collection interface — the minimum every container carries.
Collection OF T is the contract that marks a type as a container. It extends
Countable and adds one method of its own:
INTERFACE Collection OF T EXTENDS Countable { // size(), isEmpty()
METHOD iterator() RETURNS ReferenceIterator OF T
}
Three methods — size, isEmpty, iterator — and none of them asks anything
of T. That is the point: membership is open to every container in the
library, so it is a real marker rather than a badge some containers happen to
qualify for. Collection's own qualifier is correspondingly the widest of any
container's.
contains is deliberately not in the minimum. Containment needs equality
on T, and Array[T] requires only Cloneable of its elements; putting
contains in the minimum would force Equatable onto every element type in the
language the moment Array joined. Containment belongs with Searchable OF T,
whose find needs exactly the same equality and of which contains is the
boolean shadow.
Rationale. Iteration is the more primitive notion — contains is derivable
from iterating and comparing, while iteration cannot be derived from containment
— so the minimum is drawn at the irreducible core. This also tracks a real split
among languages: where equality is universal, a collection interface can require
contains; where equality is opt-in, as it is here, it cannot.
Dictionary equality and ordering. A Dictionary is Equatable and is not
Comparable. Two dictionaries are equal when they hold the same keys, each
mapping to an equal value; a hash dictionary has no canonical enumeration and
therefore no well-defined order, so none is offered (see I.K.iv).
An N-D array is walked with the coordinate iterator FOR (i, j) IN a (I.J.i(q.i)), which binds one int64 coordinate per axis and runs axis 0 innermost; the rules below are for collections and 1-D sequences.
(a) Rule. Every collection hands out a fresh iterator from ->iterator(), and each call yields a new, independent cursor. Two iterators over the same collection share no state, and traversal never mutates the collection it walks. There are two iterator interfaces. Iterator OF T is forward-only, with hasNext, next, peek, and skip. BidirectionalIterator OF T extends it with reverse traversal — hasPrevious, previous, skipBack. The navigation methods return a non-owning handle into the source collection, in the pipe-XOR shape (REFERENCE T t | STATUS s). That is a reference to the element on the success branch, and a FAILURE status when the cursor has run past the end.
Example.
Iterator OF Token it := q->iterator()
IF it->next() THEN {
REFERENCE Token t =@ $= // non-owning handle into the source collection
Token owned := t->clone() // a caller who needs an owned copy clones explicitly
}
ELSE {
// cursor ran past the end
}
Rationale. The handle is non-owning by design, because iteration does not clone. A caller needing an owned copy writes ->clone() explicitly inside the validated branch, which keeps the default traversal allocation-free.
(b) Rule. Iteration imposes a mutation lock. Holding an iterator on a collection locks that collection against mutation for the scope in which the iterator lives. That applies whether the iterator is bound explicitly from ->iterator() or implicitly through a FOR IN loop. Two operations on a locked collection are compile errors: calling any of its mutating methods, and rebinding the variable that names it. The lock is a compile-time analysis with no runtime cost, it propagates into nested blocks, and it lifts when the declaring scope ends. FOR IN over any collection, and over any user-defined class implementing Iterator OF T, reaches its body through the same ->iterator(), hasNext(), next() sequence. The loop bakes in no per-collection knowledge; its exact lowering is given in ENVZN_IR_SPEC.md C.iii.
Example.
FOR t IN q {
q->enqueue(other) // ERROR — mutating a collection locked by iteration
q := makeAnother() // ERROR — rebinding the iterated variable
}
{ // anonymous block bounds the lock precisely
Iterator OF Token it := q->iterator()
// ... q is locked here ...
} // lock lifts when this scope ends
q->enqueue(other) // OK — the iterator's scope has ended
Rationale. Forbidding mutation and rebinding under an active cursor rules out iterator invalidation at compile time, with no runtime cost. Because the lock is scoped, the anonymous block of I.G is a useful tool for bounding an iterator's lock precisely.
(c) Rule. Beyond explicit iteration, Array[T] carries the higher-order traversals that consume a lambda (I.F.v). ->map(LAMBDA transform) produces a new Array of the transformed elements; ->filter(LAMBDA predicate) produces a new Array of the elements the predicate keeps. ->reduce(seed, LAMBDA combine) folds the elements into a single accumulated value, threading the accumulator from seed through each element in order. Each applies its non-escaping lambda to the elements without mutating the source, and each holds the same iteration mutation-lock for its duration. All three are ELEMENT-TYPE-PRESERVING: map on an Array[T] returns an Array[T], and reduce folds to a T. There is no Array[T] → Array[U] map, and that is a decision rather than a gap — deriving U from a lambda's return type means inferring a second type parameter out of a lambda body, which is the template-metaprogramming direction that bounded genericity (I.A) exists to keep shut. A transformation that changes type is written as an explicit loop, where the reader can see the target type. Status: shipped in V1. map, filter, and reduce are live on Array[T] as pure-Envzn loops over an invoked lambda, exercised end-to-end by lambdaSmoke.
Example.
Array[int32] nums
Array[int32] doubled := nums->map(LAMBDA x: x * 2)
Array[int32] evens := nums->filter(LAMBDA x: x % 2 == 0)
int32 total := nums->reduce(0, LAMBDA (acc, x): acc + x) // seeded fold — 0 + every element
Rationale. The shape given here is the intended one recorded ahead of the implementation (I.A); each traversal applies a non-escaping lambda without mutating the source and holds the mutation-lock for its duration, matching explicit iteration's guarantees.
(a) Rule. A STRUCT is a pure-data record. Unlike a class it has no handle: a struct is stored inline, as a plain value, wherever it is declared — on the stack for a local, inside its holder for a field or an array element. It is also far more constrained. All of its fields are public, each field is a primitive or a String, it has no methods, and it neither extends nor implements anything. It has no INIT — the compiler generates construction directly from the field declarations in order, and construction is positional, in declaration order. A STRUCT field may be marked VOLATILE. A struct is a value, not an owner: = and := both take a deep copy (a String field is cloned), and the source stays valid.
Example.
STRUCT Point { int32 x; int32 y }
Point p := CREATE Point(3, 4) // positional — compiler-generated construction
Point r := p // a deep copy; p is still valid
STRUCT Counter { VOLATILE int32 ticks } // a STRUCT field may be VOLATILE
Rationale. The struct exists for the case where a value is genuinely just a bundle of named fields, and any method would be a method on something else. The constraints — all-public, primitive or String fields, no methods, no inheritance — keep it a pure record, so the compiler can generate its construction directly.
(a) Rule. A GROUP declares a named type classifier — a set of types that share a conceptual category. A member is a primitive, a class, a struct, an interface, or another GROUP; a name that classifies no value — a NAMESPACE, an ENUM — is not a member (E6081), and a member that resolves to no type at all is E6080. A member naming a parametric class may omit its type arguments (Array, not Array[T]): the bare head is the classifier, so every instantiation of it is a member, including instantiations that do not exist yet. Membership is transitive — a type belonging to a member group belongs to the enclosing group — while the written members remain members in their own right; group→group membership may not form a cycle (E6082). A group has no fields and no methods. A group body must list at least one member, and CREATE on a group is a compile error since there is nothing to construct. A group member containing a field of the group's own type must declare that field Box[GroupType], to break the otherwise-unresolvable type cycle.
(a.i) Rule. A group is a classifier always and a storage type only when every member has a single concrete representation. A group all of whose members are primitives, classes, structs or interfaces may type a variable, parameter, return or field: it holds exactly one member value at runtime, stored as a heterogeneous variant, and MATCH unwraps it to the concrete type. A group with a GROUP member or a bare parametric head has no such representation and may not type a value (E6083); it still classifies, so it remains legal as a template-qualifier atom and in a WHEN … IS on a type parameter.
Example.
GROUP Shape { Circle, Rectangle, Triangle }
MATCH currentShape {
WHEN Circle c: { ... } // MATCH unwraps to the concrete member type
WHEN Rectangle r: { ... }
WHEN Triangle t: { ... }
}
Shape s := CREATE Shape(...) // ERROR — CREATE on a group: nothing to construct
GROUP Empty { } // ERROR — a group body must list at least one member
Rationale. A group is a closed classifier over concrete types, so it needs no construction of its own — each variable holds one member value — and MATCH is the way to recover the concrete type. A self-typed member field must be Boxed for the same cycle-breaking reason as I.J.ii(g).
(b) Rule. The kernel provides one built-in group, Numeric, globally available without declaration. Its members are enumerated, not the whole numeric primitive family: int8 int16 int32 int64 int128, uint8 uint16 uint32 uint64 uint128, float32 float64. char is not a member: a code point admits an offset and a distance, I.D.i(b.ii), and nothing else; and binary is not, because a bit pattern is not a number. No octet type is numeric: the group once admitted byte on the grounds that it was "structurally an unsigned 8-bit integer", which was true of its storage and false of its meaning, and is why that spelling was retired in favour of uint8 where a number was meant. The kernel's declaration in interfaces.ev is the authority for this set. The four arithmetic operators, and the equality and ordering comparisons, are defined on a Numeric value and dispatch to the concrete type at runtime. Any other method call on a group-typed value is a compile error. User-defined groups are declared in a module's interfaces.ev and are module-scoped.
Example.
Numeric n // built-in group, globally available, no declaration
// + - * / and == / < are defined on a Numeric value (dispatch to the concrete type)
// any other method call on a group-typed value is a compile error
Rationale. Numeric is built in because it is the one classifier every program shares. Restricting the callable surface to the arithmetic and comparison operators keeps a group a classifier rather than an interface; anything richer is expressed with a MATCH to the concrete type.
(a) Rule. A VALUE CLASS is the third type-kind, sitting between the STRUCT and the CLASS. It carries the methods, generics, and interface conformance of a class, but the value identity and inline storage of a struct. Declared VALUE CLASS Name[T,…] IMPLEMENTS I { … } (with the optional TEMPLATE: GIVEN … preamble), it is reached by value rather than through a heap handle — stored inline wherever it lives, passed by value, and copied as a whole value. Its data fields are read with .; its methods are still invoked with -> (the value-class exception to "-> sends a message to an instance", shared with number/complex).
Example.
VALUE CLASS Vec3 IMPLEMENTS Equatable {
PRIVATE float64 x
PRIVATE float64 y
PRIVATE float64 z
METHOD magnitude() RETURNS float64 { ... }
}
Vec3 v := CREATE Vec3(1.0, 2.0, 3.0) // stored inline, no heap handle; bind with :=
float64 m = v->magnitude() // method reached with ->
Rationale. It exists for the case where a value is genuinely a small bundle that also behaves: a collision-node, a point, a fixed-size record. There a struct's "no methods" is too strict, and a class's heap identity too heavy. Data-with-., methods-with--> keeps the value-class consistent with number/complex.
(b) Rule. A value class is strict when all of its fields are themselves value-typed — a primitive, an enum, a STRUCT, or another value class. It is then trivially copyable and stored as a contiguous value. It is managed when a field owns heap through a class-typed handle, and the compiler then synthesizes its copy constructor, so that copying deep-clones the owned content. This distinction is derived from the field types, never declared, and is invisible at the surface. Because a value class is still a class, every owning bind uses := — construct, clone, or move. The value operator = of I.F.iv, reserved for primitives, STATUS, and enums, is a compile error on a value class.
Example.
VALUE CLASS Point2 { PRIVATE float64 x; PRIVATE float64 y } // strict — all value-typed fields
VALUE CLASS Owner { PRIVATE Buffer buf } // managed — owns heap; copy ctor synthesized
Point2 p := CREATE Point2(1.0, 2.0) // := whether strict or managed — always
Point2 q := p // ERROR would be `q = p` — E3023: `=` is a compile error here
Rationale. A developer therefore never has to inspect a value class's field composition to choose the assignment operator: it is always :=. The strict-vs-managed split is a compiler concern (whether to synthesize a deep-copy constructor), invisible at the surface.
(c) Rule. A value class is an inheritance leaf: it may IMPLEMENTS interfaces but may neither EXTENDS another type nor be extended (E1132), value layout having no vtable and no base-slicing model. It satisfies an interface for the purpose of a generic type constraint — a Dictionary's hasher, an Equatable key, a Cloneable element — resolved statically at the instantiation site. It may also be borrowed through an interface: REFERENCE Iface r =@ v, or a value passed to a REFERENCE Iface parameter, reaches the value class's own methods. This works because every value carries its class's tag, exactly as an object does. That tag is the second thing that separates a value class from a STRUCT, which carries none. Storing a value class behind a polymorphic interface-typed handle — existential boxing, an owning hold — is reserved for V2 and is a compile error in V1 (E1133). The remedy is to hold the concrete value type, or to use an object CLASS where interface polymorphism is required. A VALUE modifier may not combine with ABSTRACT or SINGLETON and must precede CLASS.
Example.
VALUE CLASS Vec3 EXTENDS Base { ... } // ERROR — E1132: a value class is an inheritance leaf
VALUE CLASS Vec3 IMPLEMENTS Equatable { ... } // OK — IMPLEMENTS satisfies a generic constraint
REFERENCE Equatable b =@ someVec3 // OK — a borrow through the interface
Equatable e := someVec3 // ERROR — E1133: existential boxing reserved for V2
VALUE ABSTRACT CLASS Bad { ... } // ERROR — VALUE may not combine with ABSTRACT/SINGLETON
Rationale. Value layout has no vtable and no base-slicing model, so inheritance (E1132) and existential boxing (E1133) are refused in V1. The value class still satisfies interfaces for statically-resolved generic constraints, which is enough for hashers, keys, and cloneable elements, and a borrow through an interface works because the value knows its own class. A developer who writes IMPLEMENTS can use the interface. The tag costs one word per value; a type for which that matters is a STRUCT. Where interface polymorphism is genuinely needed, the remedy is an object CLASS.
(d) Rule. Status: shipped in V1. The construct generalizes the mechanism that previously expressed value-with-behaviour in the kernel: the compiler-known number and complex value-classes (I.D.i(g)), which remain primitive-backed. A consuming module re-derives a dependency's value semantics from the VALUE modifier carried in its .headers interface file. An imported value class therefore lowers to inline storage exactly as a local one does.
Rationale. Making VALUE CLASS a first-class kind let the kernel's value-with-behaviour types be ordinary declarations rather than hand-recognized special cases, while number and complex stay primitive-backed. Propagating the VALUE modifier through the .headers file means a consumer lowers an imported value class to inline storage exactly as a local one does.
(e) Rule. A value class's default is the value its zero-argument INIT() builds or, when it declares no INIT at all, the value its fields' own defaults make. An array slot nothing was written to holds the element's default: the gap a growing write opens past the length, every cell of a T[N], every cell of an N-D array. So does a local declared with no initializer, T x, in any body, a generic one included. A value class whose every INIT takes arguments has no default, so it cannot be an array element, whether the array is written (Price[]) or reached through a container (Array[Price]) — E1159. A STRUCT's default is its zero bytes, so a struct element never needs one. **
Example.
VALUE CLASS Price { int64 cents INIT(int64 c) { .cents = c } }
Price[] prices // ERROR — E1159: Price has no INIT()
VALUE CLASS Tally { int64 n INIT() { .n = 5 } INIT(int64 v) { .n = v } }
Tally[] ts
ts[3] := CREATE Tally(9) // ts[0], ts[1], ts[2] are each Tally(), n = 5
Rationale. Zeroed bytes are not a value of a value class: its INIT may set fields to non-zero values, and its tag is its own class. Building the default where a slot appears keeps every live slot a real value, so a slot read through an interface dispatches like any other. Requiring the INIT() names the default where a reader can see it, rather than letting the compiler invent one.
The class and everything arranged around it: interfaces, abstract classes, singletons, and namespaces; inheritance and FINAL; operator interfaces and Cloneable; construction; methods, OVERRIDE, and MODIFY; polymorphic collections; enumerations; and the template qualifier.
(a) Rule. The class is the primary unit of abstraction in Envzn. Around it sit the interfaces, enumerations, and inheritance rules that let a program describe behaviour in terms of contracts rather than concrete types, and this section gathers all of them. The field declaration form is given in I.E, and the ownership a field implies in I.I; what follows describes the class as a whole and the constructs that relate classes to one another.
Rationale. Gathering the relating constructs in one Section keeps the class readable as a whole. A reader learning what a class is should not have to assemble it from the declaration rules of I.E, the ownership rules of I.I, and the abstraction rules here at once.
(a) Rule. A class instance is heap-allocated and reached through a stack handle. A class's data fields are public by default, and are mutated through MODIFY methods (I.K.vi). A developer narrows or fixes them deliberately. PRIVATE, PROTECTED, and INTERNAL restrict the audience, and CONSTANT declares a compile-time-fixed field under the rules of I.E. SHARED is a class modifier (I.K.ii), not a field modifier (E1182). A class has no class-level storage, so a class name is not a value: Account.balance and Account->total() name nothing and are E6093. The one member read through the class name is a CONSTANT (Account.MAX_HOLDS).
Example.
CLASS Account {
PRIVATE int64 balance // narrowed to Account — mutated only via MODIFY methods
PROTECTED String owner // subclasses may read this field
CONSTANT int32 MAX_HOLDS = 5 // compile-time-fixed
}
Rationale. Naming the audience only where it is restricted, and gating mutation behind MODIFY, makes every narrowing of visibility and every write path an explicit, auditable choice rather than an accident.
(a.i) Rule. Envzn permits no anonymous types, and a CLASS, INTERFACE, or GROUP may only appear at the top level of a module — nesting one inside a class body is diagnostic E6028.
Example.
CLASS Widget {
CLASS Helper { ... } // ERROR E6028 — a CLASS may not nest inside a class body
INTERFACE Drawable { ... } // ERROR E6028 — nor an INTERFACE
GROUP Numbers { ... } // ERROR E6028 — nor a GROUP
}
Rationale. A type worth sharing is a type worth naming and locating by name at the module's top level; anonymous or nested types hide behavior where a reader cannot find it.
(a.ii) Rule. The two exceptions are ENUM and STRUCT, which a class may declare in its body as implementation-detail types provided they are marked PRIVATE. A bare ENUM or STRUCT inside a class is diagnostic E6039, with a fix-it pointing either to adding PRIVATE or to moving the declaration into the module's enums.ev or structs.ev. A class-nested PRIVATE ENUM or PRIVATE STRUCT is scoped to its declaring class: the name is unreachable outside it, and the symbol is not hoisted into the module-flat enum or struct namespace. A declaration never referenced inside the owning class draws the warning W10050.
Example.
CLASS TrafficSignal {
PRIVATE ENUM Light { RED YELLOW GREEN } // OK — scoped to TrafficSignal, unreachable outside
PRIVATE STRUCT Timing { int32 red, green } // OK — packed value-record private to the class
ENUM Mode { AUTO MANUAL } // ERROR E6039 — bare nested ENUM; add PRIVATE or move to enums.ev
}
Rationale. The construct serves the case where a class wants a closed set of states, or a packed value-record of its own. Requiring PRIVATE and scoping the name to the class keeps a type of broader audience where it belongs: at the top level of the module, named and locatable.
(b) Rule. The access modifiers that govern a class member are three, each narrowing from a public default: PRIVATE confines a member to its declaring class; INTERNAL widens that to every class in the same module while keeping the member invisible outside it; PROTECTED confines it to the declaring class and its subclasses. PRIVATE and PROTECTED are class-scoped, not instance-scoped: the declaring class reaches a PRIVATE member of any of its instances, and a subclass reaches a PROTECTED member through any instance of the declaring class, not only its own. Reaching a PRIVATE member from another class is E6009 for a field and E6088 for a method; reaching a PROTECTED member from a class that is neither the declaring class nor a subclass of it is E6095 for a field and E6096 for a method. A member that declares none of them — a field, a CONSTANT, or a method — is public, reachable by anyone with access to the class. Public is therefore the space a declaration occupies by saying nothing, and it has no keyword of its own: PUBLIC is reserved but unrecognized, and writing it is a parse error. The Appendix records that reservation. Each is judged against the class that declares the member, however it is reached: a parent's PRIVATE member is refused through a subclass instance and inside the subclass itself, and a member inherited from a class of another module keeps that module's INTERNAL. A method that fills a slot keeps the slot's access. An interface publishes its methods to everyone who holds the lens, so a method that implements one is public (E6099); an override keeps its parent method's access or widens it to public, and never narrows it (E6105) — INTERNAL and PROTECTED are not ordered, so trading one for the other narrows. Without both, a lens would reach what the class's own name refuses. The module-level consequences of INTERNAL, and the rule that it may not be applied to an interface or an abstract class, are described with the module system in I.N.
Example.
CLASS Ledger {
PRIVATE int64 secret // Ledger only
INTERNAL int32 auditTag // every class in this module, invisible outside
PROTECTED String journal // Ledger and its subclasses
int32 openingYear // anyone — no modifier is the public default
METHOD total() RETURNS int64 { ... } // anyone — likewise
}
Rationale. Three modifiers name three concentric audiences inside a public default, so the reach of a member is stated at its declaration exactly where that reach is restricted. A fourth keyword for the default would be a word that changes nothing: every declaration would carry a modifier, and the ones that actually restrict would stop standing out.
(a) Rule. An INTERFACE declares a contract: a set of full method signatures with no bodies and no data fields. An interface may extend one or more other interfaces, the parents separated by commas, and a class that implements the child must satisfy every method of every ancestor. An interface never uses IMPLEMENTS — it is a contract, so it has nothing to implement, and composing contracts is what EXTENDS is for (E6090). Where two extended interfaces declare the same method with the same parameter types and an incompatible result, the child is rejected (E6091): no call site could choose between them. The same method reached by two paths with an identical signature is one contract, not a conflict, and is kept once; a shared name with different parameters is an ordinary overload. A class adopts an interface with IMPLEMENTS, and leaving any declared method unimplemented is a compile error. An interface with no methods at all is itself an error — the construct for "a set of related types" is GROUP, not an empty interface.
Example.
INTERFACE Drawable {
METHOD draw(int32 x, int32 y) RETURNS VOID
}
INTERFACE Shape EXTENDS Drawable, Measurable { ... } // two parents, comma-separated
CLASS Circle IMPLEMENTS Drawable {
METHOD draw(int32 x, int32 y) RETURNS VOID { ... } // must satisfy every ancestor method
}
INTERFACE Empty { } // ERROR — an interface with no methods; use GROUP instead
Rationale. An interface is behavior with no state, so it carries signatures only; the empty-interface error steers "a set of related types" toward GROUP, the construct actually built for it.
(b) Rule. An ABSTRACT CLASS is a partial class. A method declared ABSTRACT METHOD has no body and is an abstract method — a subclass must implement it; a method declared with a body is concrete and inherited as written. An abstract class must declare at least one ABSTRACT METHOD, since a class with no unfilled slots is a regular CLASS (E6073). An ABSTRACT METHOD may appear only inside an abstract class (E6074). Neither an abstract method nor an abstract class may be PRIVATE — an abstract member is a contract its subclasses must implement, and PRIVATE would hide it from the very types meant to fulfil it (E6077); MODIFY composes freely, so ABSTRACT MODIFY METHOD is valid. For every interface it IMPLEMENTS it must declare a matching method, concrete or ABSTRACT METHOD, never omitting it (E6020), exactly as a concrete class would. An abstract class cannot be instantiated directly (E6029), and a class that extends one must implement every abstract method or remain abstract itself (E6006). It may EXTENDS one class and IMPLEMENTS several interfaces like any class, but it may not be a generic template (E6075).
Example.
ABSTRACT CLASS Conveyance {
ABSTRACT METHOD move() RETURNS VOID // abstract — no body; the subclass implements it
METHOD describe() RETURNS String { RETURN ("a conveyance") } // concrete — inherited as written
}
CLASS Aircraft EXTENDS Conveyance {
METHOD move() RETURNS VOID { ... } // implements the abstract method
}
Conveyance c := CREATE Aircraft() // OK — the concrete class is named (I.F.iii)
Conveyance d := CREATE Conveyance() // ERROR E6029 — an abstract class cannot be instantiated directly
Rationale. An abstract class mixes shared implementation with unfilled slots, so it can be neither instantiated nor left with an abstract method unimplemented in a concrete subclass. The explicit ABSTRACT METHOD marker makes a missing body a deliberate declaration the parser and analyzer can act on, not an accident.
(c) Rule. A SINGLETON CLASS is a single-instance actor — a class modelling a process-level service that performs behaviour, of which the kernel's System (and Process, Stdio, DateTimeFactory) are the canonical examples. Singletons are rare: a type is a singleton only when there is genuinely one of it and it acts. The construct is mutually exclusive with NAMESPACE — a stateless grouping of functions is the latter, not the former. Five rules, each with its own diagnostic, hold the construct to its purpose: SINGLETON applies only to CLASS and not to the other type kinds (E1099); in V1 a singleton declares no data fields at all (E1100), and its methods may not be MODIFY (E1101). It may neither extend nor be extended, singletons being leaves of the inheritance tree (E1102), and it may not declare INIT (E1103). One exception, the kernel's runtime state: an INTERNAL SINGLETON CLASS of the ENVZN kernel whose every data field is PRIVATE may declare fields, an INIT and MODIFY methods. The rule is structural and never a list of names: INTERNAL keeps the state out of every developer's sight, the kernel is the only module (as UNION, E6062), and all-PRIVATE is the SHARED CLASS monitor's shape (E2116), whose locking is likewise the author's responsibility in V1. Its INIT runs once, before main. A developer's singleton stays stateless until V2. A singleton's methods are called with -> (System->exit(...)) — the surface reads as sending a message to the live instance/actor.
Example.
SINGLETON CLASS System {
METHOD exit(int32 code) RETURNS VOID { ... }
}
System->exit(0) // called with -> : a message to the live actor
SINGLETON STRUCT Bad { ... } // ERROR E1099 — SINGLETON applies only to CLASS
SINGLETON CLASS Cache {
PRIVATE int32 hits // ERROR E1100 — V1 singleton declares no data fields
MODIFY METHOD reset() { ... } // ERROR E1101 — a singleton method may not be MODIFY
INIT() { ... } // ERROR E1103 — a singleton may not declare INIT
}
SINGLETON CLASS Sub EXTENDS System { ... } // ERROR E1102 — a singleton neither extends nor is extended
Rationale. A singleton is the rare "one-of, and it acts" case; the five diagnostics keep it from drifting into a stateful object or a mere function bag. Interior state is deferred to V2+ (and when admitted must be thread-safe), which is why the V1 no-fields rule holds.
(d) Rule. A NAMESPACE is a stateless host of free functions — the mirror-opposite of a STRUCT (which holds data and no functions): a NAMESPACE holds functions and only constant data. The two are perfectly complementary: NAMESPACE + STRUCT ≈ CLASS. All a CLASS adds beyond the sum of the two is inheritance (EXTENDS) and interface implementation (IMPLEMENTS), in neither of which a namespace or struct participates. Math (square root, gcd, the numeric functions and constants) is the canonical example; namespaces should be common. NAMESPACE Name { … } admits METHOD declarations at any of the three visibilities, together with CONSTANT data fields and constant arrays. It also admits FOREIGN BIND CONSTANT <type> <NAME> members: a C constant read once, by the bind mechanism of §17, into a member of the namespace — spelled _ev_fbc_<NAME> in the lowering, since the C name is a macro the preprocessor would rewrite — and qualified by the namespace at every use, NumericLimits.INT8_MIN. So a limit keeps the name C gave it, the preprocessor never sees it as a declaration, and the member belongs to its declarer: two namespaces binding the same C name are two members, never a redefinition. This is the one place a FOREIGN declaration may appear below the top of a file. The visibilities are public (the default), PRIVATE (callable only by sibling functions of the same namespace), and INTERNAL (callable anywhere in the same module). A variable (non-CONSTANT) data field is rejected (E1107), a MODIFY method is rejected (E1108), and an INIT or CLEANUP is a parse error (a namespace is stateless, with no instance lifecycle). Because a namespace has no instance, its members are reached with . — Math.PI, Math.sqrt(x) — and calling a namespace method with -> is an error (E1106). The C++/Rust scope-resolution spelling Math::sqrt(x) is likewise an error (E1109): :: qualifies a module (ALIAS mda::TextColumn, I.N.d.iv), never a namespace member, so the two sigils never overlap. Inside the namespace its own members are referenced bare (PI) or with the leading-dot self form (.PI), both resolving to the same in-scope member. A namespace name follows the PascalCase type-name convention (W10026 otherwise).
Example.
NAMESPACE Math {
CONSTANT float64 PI = 3.14159265358979
METHOD sqrt(float64 x) RETURNS float64 { RETURN (.helper(x)) } // .helper — leading-dot self form
PRIVATE METHOD helper(float64 x) RETURNS float64 { RETURN (PI * x) } // PI — bare self reference
}
float64 r := Math.sqrt(2.0) // reached with . — no instance
float64 p = Math.PI
NAMESPACE Counters {
int32 total // ERROR E1107 — a variable (non-CONSTANT) data field
MODIFY METHOD bump() { ... } // ERROR E1108 — a MODIFY method in a namespace
}
Math->sqrt(2.0) // ERROR E1106 — a namespace method is called with . , not ->
Math::sqrt(2.0) // ERROR E1109 — `::` qualifies a MODULE, not a namespace member
Rationale. Behaviour-and-constants (NAMESPACE) plus data-fields (STRUCT) is the substance of a class, so each half stands as a first-class construct. A namespace exists so that not everything need be a class, and its statelessness is what forbids variable fields, MODIFY, and a lifecycle. The kernel's character-classification, codec, and numeric-conversion families are namespaces — CharClassifier, HexCodec, Base64Codec, ByteOrderCodec, NumericUtilities — as are the numeric and formatting hosts Math, FloatFormat, UTFCodec, TextEncoding, and the hash-constant tables. The conversion families into which the former Convert singleton was broken up live here too. A NAMESPACE lowers to a C++ namespace Name { … } of inline free functions and static constexpr constants — no backing struct, no instance — and a Name.method(…) call lowers to Name::method(…).
(e) Rule. A SHARED CLASS is an interior-mutable monitor — a class built to be shared by reference across concurrent tasks while holding its own synchronization internally. It is the only class kind a SHARED MUTABLE REFERENCE (I.I.vi) may point at, sound precisely because a monitor serialises its own access. Two rules hold it to that contract. It must IMPLEMENTS Shareable — the marker interface that admits a type into a SHARED MUTABLE REFERENCE field and into the move-only OwnedList[T] collection — and a SHARED CLASS that does not is E2115. And every one of its data fields must be PRIVATE, so the only path to its state is through its synchronized methods and no holder can mutate a field bypassing the lock. An externally-visible field — one left bare, and so public by default, or marked SHARED, PROTECTED, or INTERNAL — is E2116.
Example.
SHARED CLASS Channel[T] IMPLEMENTS Shareable { // canonical SHARED CLASS
PRIVATE Lock lock // every field PRIVATE
PRIVATE Queue[T] buffer
MODIFY METHOD send(T value) RETURNS VOID {
SYNCHRONIZED (.lock) { ... } // author hand-gates the critical section
}
}
SHARED CLASS Bad { ... } // ERROR E2115 — a SHARED CLASS must IMPLEMENTS Shareable
SHARED CLASS Leaky IMPLEMENTS Shareable {
int32 count // ERROR E2116 — public by default; bypasses the lock
}
Rationale. The carve-out that lets multiple holders alias a SHARED CLASS mutably is safe only because the monitor serialises access; the two rules — Shareable and all-private fields — are exactly what guarantee that. The internal synchronization itself is the author's responsibility in V1. A SHARED CLASS typically holds a Lock and wraps its critical sections in SYNCHRONIZED blocks by hand, as Channel does with condition-variable logic that hand-gating cannot replace. The once-reserved AUTO SYNCHRONIZED CLASS form, a compiler-injected per-method SYNCHRONIZED, was declined and retired. It is redundant with — and strictly weaker than — Mutex[T], which preserves the compound-operation escape hatch an auto-monitor removes, and it would require a reentrant lock the kernel does not have. Use Mutex[T], the manual SHARED CLASS monitor, or Channel[T] / CONCURRENT instead.
(e.i) Rule. A SHARED CLASS instance is co-owned: its owner holds the first strong count and each SHARED MUTABLE REFERENCE holder holds another (I.I.vi(c)), and the instance is destroyed when the last of them drops. Every SHARED CLASS is co-owned this way, and no other class ever is. A WEAK REFERENCE may never observe a SHARED CLASS instance — WEAK and SHARED are mutually exclusive.
(e.ii) Known limitation. A SHARED CLASS cannot carry an int128, uint128, or decimal128 data field — directly, inside a STRUCT or VALUE CLASS field stored inline, or through a type parameter instantiated at one of them (E3049). A shared instance is allocated with its strong count in the 8-byte word immediately before it, and the allocation is made and freed at that word, so the instance itself may need at most 8-byte alignment; those three types need 16. Hold such a value behind a class-typed field, whose handle is an 8-byte pointer, or keep it out of the monitor.
Example.
SHARED CLASS Ledger IMPLEMENTS Shareable {
// PRIVATE decimal128 total // ERROR E3049 — a SHARED CLASS cannot hold a decimal128 inline
PRIVATE Balance total // OK — Balance is a CLASS: Ledger holds only an 8-byte
// handle; the decimal128 lives in Balance's own allocation
}
// SharedCell[int128] c // ERROR E3049 — the by-value T field is an int128 here
Rationale. Fixing the count at one offset, with one allocation start, for every shared instance keeps the strong count reachable from any pointer to the object — including one upcast to an interface — and keeps the free path free of per-class arithmetic. The price is this limitation, which no kernel SHARED CLASS meets and which has a one-line remedy, rather than a padded allocation paid by every shared object.
HIDDEN classes.
A HIDDEN class must declare a non-empty IMPLEMENTS or EXTENDS, and its name
may appear only as a CREATE target. It may not be used as a type — not in a
declaration, a parameter, a return, a template qualifier atom, or a GROUP
member:
Dictionary[K, V, H] d := CREATE ChainedHashDictionary[K, V, H]() // legal
ChainedHashDictionary[K, V, H] d := CREATE ChainedHashDictionary[K, V, H]() // E1131
The restriction spans module boundaries. It binds every consumer of the
class, not only the module that declares it — and the consumers are the
population it exists to protect, since the declaring module's author already
knows. A module's exported header therefore carries the HIDDEN marker, as it
carries FINAL, SHARED, and VALUE.
Two consequences follow for the author of a HIDDEN class, and both are
obligations rather than options:
clone() (and any method returning "one of me") must be declared as
the interface it implements, never as the concrete class — the concrete
name is unwritable in a return type.HIDDEN. Deciding to hide a
class is therefore also deciding that its interface is complete.(a) Rule. A class may extend zero or one class — single inheritance — and may implement zero or more interfaces; an abstract class may do both. A supertype is named as any type is named: bare, or qualified by its module (EXTENDS ENVZN::LinkedList[T], IMPLEMENTS ENVZN::Equatable[Point], IMPLEMENTS ENVZN::Equatable OF Point). A generic supertype is written in full, in either of two forms: the template form, whose type arguments are the subclass's own type parameters (CLASS Stack[T] EXTENDS Array[T]), or a concrete instantiation extended by an ordinary class (CLASS Names EXTENDS LinkedList[String]). A generic supertype given the wrong number of type arguments, or none, is a compile error (E2133); a type argument that is neither a declared type nor one of the subclass's own type parameters is E2103, as is a qualified supertype its module does not declare. FINAL on a class forbids subclassing it, and FINAL on a method forbids overriding it. A subclass may read a parent's data fields only where the parent declared them SHARED, and may freely add its own fields and methods.
Example.
CLASS Shape {
FINAL METHOD identity() RETURNS int32 { RETURN (.id) } // FINAL method — cannot be overridden
}
FINAL CLASS Circle EXTENDS Shape IMPLEMENTS Drawable, Measurable { // one parent, many interfaces
PRIVATE float64 radius // subclass freely adds its own fields
}
CLASS Sphere EXTENDS Circle { ... } // ERROR — Circle is FINAL and cannot be subclassed
Rationale. Single inheritance plus multiple interface implementation gives one line of shared implementation and any number of contracts; FINAL lets an author seal a class or a method against extension where subclassing would break an invariant.
(b) Rule. Envzn permits no casting, ever — a value is never reinterpreted as another type by assertion. Where a program needs to branch on a more specific type it uses a WHEN type-check, never an IF. A WHEN type-check pairs a subject with a predicate: IS names a class, an abstract class, a GROUP, an individual primitive type (e.g. int32, float64), or the PRIMITIVE category; IMPLEMENTS names an interface. On a type-parameter subject IS also names two shape categories: ARRAY, satisfied by any runtime-shape array (T[], T[N+], T[,]), and FOREIGN_TYPE, satisfied by a typed C handle declared by FOREIGN_TYPE BIND — the kernel's own opaque statics dispatch on both (I.D.v). A value has no shape to test, so either category on a value subject is E1104. ** It also names one kind category, VALUE CLASS, satisfied by a value class (never a primitive's backing class): a generic fills an array slot with T's default under it and nothing else (I.J.vi(e)). Inside its arm T is still T. ** The two keywords lower to the same test, so each must state the named type's kind honestly — IS on an interface, or IMPLEMENTS on a class, is a compile error. The one exception is a type-parameter target (WHEN held IS T, WHEN held IMPLEMENTS T): the developer cannot state the kind of a type the instance supplies, so either keyword accepts a class or an interface there, and the instance decides. The subject of either keyword is a type parameter or a value in scope — a parameter or a local; anything else is E1096. The named type is spelled as it is everywhere else: a parametric interface or class template carries its type arguments adjacent to its name (Equatable[K] / Equatable OF K), and naming it bare is E6092 (I.K.ix(f)). An enum or struct is not a valid IS target (E1104): a value typed as an enum or struct has no subtype to narrow to. Dispatch an enum with MATCH on its cases instead. The standalone form requires a mandatory ELSE, with an optional DO before the body.
Example.
WHEN shape IS Circle { shape->radius() } ELSE { … } // class — abstract parents match too
WHEN shape IS NOT Circle { … } ELSE { … } // negated
WHEN shape IMPLEMENTS Drawable { shape->draw() } ELSE { … } // interface
WHEN T IS PRIMITIVE { … } ELSE { … } // type parameter — category test
WHEN T IS Numeric { … } ELSE { … } // type parameter — GROUP membership
WHEN n IS int32 { … } ELSE { … } // individual primitive (type param or concrete-typed value)
WHEN T IS ARRAY { … } ELSE { … } // type parameter — any runtime-shape array
WHEN T IS VALUE CLASS { … } ELSE { … } // type parameter — a value class
WHEN value IS animals::Dog { … } ELSE { … } // a scoped, cross-module type name
WHEN d IS Direction { … } ELSE { … } // ERROR E1104 — an enum is not a valid IS target
Rationale. Forbidding casts and routing every type branch through WHEN means the narrowing is something the compiler proves rather than something the developer asserts (see (d)). Requiring IS/IMPLEMENTS to name the type's kind honestly keeps the check greppable and self-describing, and the enum/struct exclusion reflects that those types have no subtype to recover.
(c) Rule. The same predicate is an arm of a MATCH, with the subject left implicit (it is the match subject), and an optional DEFAULT.
Example.
MATCH shape {
WHEN IS Circle: { … }
WHEN IS Square: { … }
DEFAULT: { … } // compile-time type-check form: the else arm is mandatory
}
MATCH T { // a type-parameter subject, decided per instance
WHEN IS ARRAY: { … } // T[] / T[N+] / T[,]
WHEN IS FOREIGN_TYPE: { … } // a typed C handle (kernel-only atom, E2158)
WHEN IS int32: { … }
DEFAULT: { … }
}
Rationale. Folding the same predicate into MATCH arms lets a multi-way type dispatch read as one construct instead of a chain of standalone WHEN/ELSE checks.
(d) Rule. The narrowing inside a true arm is something the compiler has proved, not something the developer has asserted — that is the whole of the difference between a WHEN check and a cast. The subject is either a type parameter, decided per template instantiation at compile time, or a value. A value whose static type already settles the test is decided at compile time; otherwise — a polymorphic interface or abstract base whose object may or may not be the named type — the test runs at run time against the object's own class, and the true arm is entered only when it holds. Inside that arm the subject is the named type, so a recovery from it (Dot d := held, or a move into a T result) is proven by the arm itself and binds with no run-time check. (Corrected : this said the check was resolved entirely at compile time and took ELSE on a polymorphic subject. The backend has tested a value subject at run time ; the text had not followed.) A parent or interface type is a lens over the object, never a conversion: the value keeps its concrete identity, and every object carries its own class (I.K.iii(e)). Moving it to a narrower type with := or =@ — a narrowing — is therefore always checked, and never a cast. Where flow provenance proves the concrete type at compile time, the narrowing binds with no check and no cost. Where the value provably is not that type, it is a compile error (E2126). Otherwise — an interface-typed parameter, a join whose arms disagree, the residue past an erasure boundary — the narrowing is checked at run time against the object's own class: it binds when the object is that type, and otherwise raises PANIC LensMismatchError, naming both types. The check runs before the move, so the source still owns the object when the PANIC is raised. An EMPTY source stays EMPTY, with no check and no PANIC. The assignment is written the same way in every case; WHEN x IS T remains the way to ask without a PANIC. (Changed, LENS_LOWERING_DESIGN.md Q15–Q19: an unproven narrowing was refused at compile time. That diagnostic, type:recovery-not-provable, is retired; it is named by slug because a retired code must not be cited as live.)
A narrowing is written only at := and =@, where a PANIC is visible on the line that can raise it. Passing an argument to a narrower parameter is a compile error (E10096), and so is returning a value as a narrower type (E2175); widening into a parameter or a RETURN is free. A move between two lenses is legal only along one EXTENDS line — into an ancestor it is free widening, into a descendant it is a checked narrowing — and between two unrelated lenses it is a compile error (E2176), whether they are interfaces or a parent class and an interface the parent does not implement: the value is first recovered to its concrete type, then widened. (Q23)
Example.
Conveyance c := CREATE Aircraft() // flow proves the concrete type
Aircraft a := c // move recovery — statically discharged, NO cast
REFERENCE Aircraft b =@ c // reference recovery — static_cast on the borrowed pointer, no ownership transfer
Ship s := CREATE Ferry()
Aircraft bad := s // ERROR E2126 — the value provably is NOT an Aircraft
METHOD handle(Conveyance c) RETURNS VOID {
Aircraft a := c // checked at run time: PANIC LensMismatchError if c is not an Aircraft
}
METHOD sort(Cloneable c) RETURNS VOID {
Equatable e := c // ERROR E2176 — Cloneable and Equatable are unrelated lenses
Item it := c // checked narrowing to the concrete type…
Equatable e2 := it // …then free widening
}
Rationale. A narrowing is never unchecked and never a cast: it is free where the compiler proves it, a compile error where the compiler disproves it, and a run-time check against the object's own class in between. Refusing the in-between case outright sent every developer to a WHEN for a move they knew to be right; checking it keeps the program safe and the assignment readable, and the PANIC it can raise sits on the line that wrote it. Provenance is tracked flow-sensitively: a control-flow join whose arms all agree on the concrete type narrows for free; one whose arms disagree is checked. The branch-join precision is decided in the flow-sensitive verify pass over the IR, while the analyzer's straight-line fast-path fires the locally-provable-wrong case (E2126). V1 covers both the move recovery (Aircraft a := c) and the reference recovery (REFERENCE Aircraft a =@ c). The latter borrows the same object with no ownership transfer, under the same rule: free when proven, checked when not. Interprocedural provenance across method boundaries is a later increment. Group membership as a WHEN … IS test is limited in V1 to a group whose members all have one concrete representation — declared in the same module, with no parametric and no GROUP member (plus the built-in Numeric); a group without that property is E6083 there. Membership as a classifier carries no such limit: it is transitive, works across a module boundary, and admits a bare parametric head (I.J.v(a), I.K.ix(c)). Cross-module group growth (GROUP X += { … }) remains V2. An individual-primitive IS (WHEN n IS int32) resolves from the subject's static type, so it holds on a type parameter or a concretely-typed value. A value whose static type is a GROUP, a runtime variant, takes the ELSE arm in V1; narrow it through a type-parameterized context instead.
(e) Rule. The compiler's static type knowledge is reflected to the developer through the IDENTITY(subject) intrinsic, whose subject is a value, a data-field path (person.spouse), a type, or a type parameter. It yields a value of the kernel STRUCT Identity whose fields the compiler fills at compile time.
| Field | Holds |
|---|---|
name |
the short form: the type as written with its module qualifiers dropped — "Person", "int32", "int32[]", "float64[3,2]", "float64[,]", "Array[int32]". A runtime-extent array reports its rank spine (I.J.i(o)), since its extents are not part of its type. The compiler's diagnostics name a type the same way ** |
home |
the declaring module; primitives report "ENVZN" |
fullname |
the fully qualified name, parameterized — "ENVZN::Array[int32]", "app::Person", "app::Cell[float64[,]]" |
type |
the type as a developer writes it, fully qualified unless primitive — "int32", "ENVZN::String", "app::Person" |
kind |
the type kind — exactly one of Primitive, Enum, Group, Struct, Class, Value Class, Hidden Class, Shared Class, Abstract Class, Interface, View Class, or, for a scope rather than a type, Namespace or Conversions |
modifier |
the binding's declared qualifier — constant, mutable, reference, mutable reference, shared mutable reference; blank for a bare type or type-parameter subject |
generic |
boolean |
internal |
boolean |
blittable |
the property of I.J.i |
currentLens |
the static type, fully qualified, when the value is viewed through an ancestor lens — the lens of paragraph (d) made observable; blank otherwise |
lenses |
the ancestor chain in order, each fully qualified: classes, then abstract classes, then implemented interfaces |
numberOfDataFields, dataFields |
for a class, value class or struct (never for a NAMESPACE or CONVERSIONS block, whose CONSTANTs are not data), one IdentityField per data field, inherited fields first: name, type, kind, access (an IdentityAccess, PUBLIC_ACCESS when none is declared), modifier, declarationIndex, derived, inherited, declaredIn. Private and protected fields are listed with their access, because the reader is code that has to see the whole value, a codec above all. Empty, with a count of 0, for every other kind |
numberOfMethods, methods |
for a class, value class, interface, NAMESPACE or CONVERSIONS block (a struct has none), one IdentityMethod per method, INIT, CLEANUP and RESTORE included; a CONVERSIONS operator is listed under its keyword (AS or INTO), its FROM parameter in and its RETURNS slot out: name, descriptors in source order, typeParameters, access, the in and out parameters as IdentityParameters (name, type, kind, modifier, position) with their counts, pipe, inherited, declaredIn, overrides (the ancestor whose method it replaces) and fills (the interfaces whose slot it implements). An overridden ancestor method appears once, as the override |
fieldNameBytes, fieldNameStarts |
every data-field name as UTF-8, back to back in dataFields order (binary[]), and where each starts (int64[]), with one final entry holding the total, so field k's name is fieldNameBytes[fieldNameStarts[k], fieldNameStarts[k + 1]); both empty when there are no data fields. Encoded once, at compile time, for a byte-level reader (a JSON key matcher) to compare raw bytes against |
cases |
for an Enum subject, an EnumKind[] carrying one {name, value} pair per case in declaration order — the enum's "instances"; empty for every non-enum |
The subject is never a method: IDENTITY(Helpers.twice) is E2141, because IDENTITY(…) always yields an Identity, and a method is reached through IDENTITY(T).methods. A NAMESPACE or CONVERSIONS name is a label on the members it scopes, so its Identity lists those methods and no data fields.
Reading IDENTITY(…) costs nothing. Every member is a compile-time constant, so the compiler builds each distinct value once and every IDENTITY(…) refers to that one read-only instance. Write it where it is needed, inside a loop included: IDENTITY(Person).dataFields[i].name allocates nothing and needs no local. Identity id := IDENTITY(Person) makes an owned copy, which is legal and costs what a copy costs. REFERENCE Identity id =@ IDENTITY(Person) is legal but saves nothing over the direct read.
Rationale. An interface is a lens, not erasure (paragraph (d)); IDENTITY makes that identity legible without a cast — the developer reads a type's kind, structure, and provenance as ordinary data. Keeping Identity a real value, rather than compiler magic bolted onto a .field, means one type serves both the compile-time answer today and the runtime answer later. The reflected value is first-class: storable, returnable, an Identity[] element.
(a) Rule. Operator overloading exists in Envzn only through implementing reserved interfaces, and never through a direct overloading syntax. A type that wishes to support an operator implements the interface the operator is derived from, and the compiler derives the operator from the interface's named methods. Every overloaded operator therefore stays traceable to a greppable method declaration. The four operator interfaces, each generic over the implementing type, are:
| Interface | Required methods | Derived operators |
|---|---|---|
Equatable[T] |
isEqualTo |
==, != |
Comparable[T] |
isLessThan |
<, >, <=, >= |
Arithmetic[T] |
add, subtract, negate |
+, - |
Multiplier[T] |
multiply, divide |
*, / |
Example.
CLASS Temperature IMPLEMENTS Arithmetic[Temperature] {
METHOD add(Temperature other) RETURNS Temperature { ... } // derives +
METHOD subtract(Temperature other) RETURNS Temperature { ... } // derives -
METHOD negate() RETURNS Temperature { ... }
}
Temperature t3 := t1 + t2 // the + is derived from add
Rationale. Routing every overloaded operator through a named interface method keeps the operator's meaning discoverable by grep and forbids the opaque free-floating operator definitions that make overloading hard to read.
(b) Rule. Comparable[T] extends Equatable[T], since an ordering implies an equality. Every numeric primitive satisfies all four automatically, and String satisfies Equatable and Comparable; a user-defined type satisfies the Numeric constraint only by implementing all four with itself as the type argument. The compiler checks that the type argument matches the implementing class — a Temperature implementing Arithmetic declares add(Temperature other), not add of some other type.
Example.
CLASS Money IMPLEMENTS Arithmetic[Money], Multiplier[Money], Comparable[Money] {
METHOD add(Money other) RETURNS Money { ... } // NOT add(int64 other) — type argument must match
METHOD isLessThan(Money other) RETURNS boolean { ... } // Comparable extends Equatable ⇒ also isEqualTo
METHOD isEqualTo(Money other) RETURNS boolean { ... }
// ... plus subtract, negate, multiply, divide to fully satisfy Numeric
}
Rationale. Because Comparable extends Equatable, an ordered type must also define equality; requiring the type argument to be the implementing class prevents an Arithmetic that secretly adds some other type, keeping the derived operators well-typed.
(c) Rule. A separate reserved interface, Cloneable, governs deep copying. Several operations need a genuine copy of an instance: a := of a class-typed value, or the *Copy collection methods of I.J. Envzn makes cloneability an explicit opt-in rather than a universal default — a class is cloneable only when it declares IMPLEMENTS Cloneable and provides a clone(). The implementing class names its own concrete type as the return type, and the interface-satisfaction rule accepts a return type that itself implements Cloneable, which yields covariant return without exposing variance modifiers. A child class does not inherit cloneability — if it needs to be cloneable it declares so itself and provides its own clone(), so that the clone covers the child's own fields and not merely the inherited ones.
Example.
CLASS Node IMPLEMENTS Cloneable {
METHOD clone() RETURNS Node { ... } // names its own concrete type — covariant return
}
CLASS TaggedNode EXTENDS Node IMPLEMENTS Cloneable { // cloneability is NOT inherited — re-declare
PRIVATE String tag
METHOD clone() RETURNS TaggedNode { ... } // own clone() so the copy covers .tag too
}
Rationale. Making cloning opt-in avoids a silent universal deep-copy default. Requiring the child to re-declare Cloneable guarantees a clone actually covers the child's own fields rather than slicing them away, and covariant return keeps clone() typed to the concrete class without variance syntax.
What Comparable and Equatable oblige.
Comparable[T].isLessThan must be a strict total order: irreflexive,
antisymmetric, transitive, and trichotomous with Equatable[T].equals — for
every pair exactly one of a < b, b < a, a == b holds. A relation that is
merely consistent is not sufficient, because a sort, a SortedList, and a
RedBlackTreeDictionary all rely on trichotomy to place a value at all.
Two consequences are normative rather than advisory:
[9] below [1, 1] — and substituting it silently
reorders every ordered container keyed by that type.Equatable only.
complex is the standing example: an order may follow the real axis or the
imaginary axis but not both consistently, so complex is Equatable and is
excluded from ordered containers. A hash-based dictionary is the same case for
a different reason — hashing destroys the canonical enumeration that ordering
would need — and so is Equatable and not Comparable.Equality is structural, and empty is equal. For a container, equals holds
when the two hold the same elements — for a dictionary, the same keys each
mapping to an equal value, not merely the same key set. Two empty
containers of the same type are equal; a definition that reports them unequal is
wrong.
Rationale. Equality must be substitutable: if two values are equal, no
subsequent query may distinguish them. Key-set equality would rank {a: 1} equal
to {a: 2}, so two "equal" dictionaries would answer lookup(a) differently.
Comparing domains is a legitimate relation, but it is not equality of the
dictionary and needs its own name.
A mutable container with structural equality is a hazard as a key. Mutating it after insertion changes what it equals, and the entry becomes unreachable.
(a) Rule. INIT is the constructor. Primitive fields, and String or ByteBuffer fields, are auto-initialized to their defaults before INIT runs, so INIT need not assign them, though it may override them — the two containers because they are the always-present exceptions of I.D.vii and can never be EMPTY (I.E.e.i). Class-typed fields are not auto-initialized: the compiler verifies that every one is assigned on every path through INIT, and an unassigned class field is a compile error. A class with only primitive, String and ByteBuffer fields and no INIT receives a generated no-argument one. Multiple INIT blocks are permitted, overloaded by parameter signature exactly as methods are, and CREATE resolves which to call from the argument types. An INIT parameter may not carry a default value, under the rule of I.E — an omitted argument is expressed as a second INIT overload.
Example.
CLASS Point {
PRIVATE int32 x, y
PRIVATE Label tag // class-typed field — must be assigned on every INIT path
INIT(int32 px, int32 py) {
.x = px // primitives auto-init to defaults; assignment optional here
.y = py
.tag := CREATE Label("origin") // class-typed field — construct with :=
}
INIT(int32 px, int32 py, int32 scale) { ... } // a second overload — resolved by argument count
}
Point p := CREATE(3, 4) // CREATE resolves the INIT from the argument types
Rationale. Auto-initializing primitives and String, while forcing class-typed fields to be assigned on every path, guarantees no field is silently left absent. Overloading INIT by signature is what lets one class offer several construction shapes, and it is the whole mechanism: with no default parameter values (I.E(g)), a second shape is a second overload rather than an omitted argument.
(b) Rule. SUPER(args) calls the parent's INIT, and when present it must be the first statement in the child INIT — any statement before it is a compile error. It is required when the parent has only a parameterized INIT, and optional (called implicitly) when the parent has a no-argument one. SUPER names the immediate parent: its arguments are resolved against that parent's own INITs, never a grandparent's, exactly as a CREATE's are resolved against its class's. Arguments that fit none of them, or more than one, are a compile error (E6098). An INIT that writes no SUPER calls the parent's no-argument INIT, and the compiler states that call as surely as a written one.
Example.
CLASS ColoredPoint EXTENDS Point {
PRIVATE String color
INIT(int32 px, int32 py, String c) {
SUPER(px, py) // must be the FIRST statement — anything before it is a compile error
.color := c
}
}
Rationale. Requiring SUPER first guarantees the parent is fully constructed before the child touches any inherited state; it is mandatory exactly when the parent offers no no-argument INIT to call implicitly.
(a) Rule. A method returning a single value writes its return type bare or parenthesized with a label, the two being equivalent. A method returning several values writes the parenthesized, every-type-labelled form, and the unparenthesized or unlabelled variants are compile errors. RETURNS VOID may be written or omitted for a method that returns nothing. When a method declares a return, every code path must end in a RETURN (...) carrying the values in declaration order, and the compiler rejects any non-void path that does not. A single-value return of a class type may legitimately yield EMPTY, for which the caller establishes presence in the usual way. A method whose result may fail uses the pipe-XOR shape of I.M, rather than encoding the failure in the value. A variadic method takes a final ... parameter of an array type, into which the compiler packs the trailing call arguments. A local variable may not shadow any field, parameter, return variable, or enclosing local, per I.E.
Example.
METHOD area() RETURNS float64 { RETURN (3.14 * .r * .r) } // single value — bare or labelled equivalent
METHOD divmod(int32 a, int32 b) RETURNS (int32 quotient, int32 remainder) {
RETURN (a / b, a % b) // multi-value — parenthesized, every type labelled, declaration order
}
METHOD reset() RETURNS VOID { ... } // VOID may be written or omitted
METHOD sum(int32... nums) RETURNS int32 { ... } // variadic — final ... parameter of array type
Rationale. The bare-versus-labelled equivalence keeps a single return terse, while the strict labelled form on multi-returns keeps each slot named. Requiring a RETURN on every non-void path makes definite-return a compile-time guarantee, and steering failure into the pipe-XOR shape of I.M keeps "absent" (EMPTY) distinct from "failed."
(b) Rule. A method is read-only by default, and a method that writes the receiver's state must declare itself MODIFY. A method must be MODIFY when its body writes a receiver field, calls a MODIFY sibling method, or calls a MODIFY method through a chain of receiver-rooted fields. It is read-only when it only reads, calls non-MODIFY methods, or returns a REFERENCE to a field for read-only use. MODIFY is part of a method's public signature — it rides in the module's generated headers so that cross-module callers see the contract — and a violation is diagnostic E1098, reported at the offending statement. Because it is part of the signature, a method that implements an interface method or overrides a parent-class method carries the same mode as the slot it fills, neither adding nor dropping MODIFY; a mismatch is E6094, reported at the method. MODIFY does not apply to INIT or CLEANUP, which write fields by definition. An AUTO method carries its slot's mode like any other implementing method, written out: AUTO MODIFY METHOD reconstruct(…).
Example.
METHOD balance() RETURNS int64 { RETURN (.amount) } // read-only default — only reads
MODIFY METHOD deposit(int64 n) RETURNS VOID { .amount = .amount + n } // writes a field → must be MODIFY
METHOD withdraw(int64 n) RETURNS VOID {
.amount = .amount - n // ERROR E1098 — writes a receiver field without MODIFY
}
Rationale. The polarity is deliberately the opposite of C++'s default-mutating, opt-out-with-const arrangement, and matches Swift's mutating. The motivation is const-correctness that cannot be retrofitted away. Every method's effect on its receiver is visible in its declaration from the day it is written, and because MODIFY rides in the generated headers, cross-module callers see the contract too. INIT/CLEANUP are exempt because they write fields by definition. An AUTO method is not: it fills an interface slot, so it carries that slot's mode, and a reader sees from the declaration alone that AUTO MODIFY METHOD reconstruct writes the receiver.
(c) Rule. OVERRIDE marks the reimplementation of a concrete parent method, and is required there. Its absence on a matched concrete signature is a warning, because a reimplementation that was intended but unmarked is a latent bug. Implementing an abstract parent method, by contrast, fulfils a contract rather than replacing an implementation, and OVERRIDE there is forbidden. SUPER->method() calls the parent's concrete implementation — a qualified static call that reaches the parent's version even from a child that overrides it. SUPER is only for SUPER(args) and SUPER->method(...); a parent data field is reached with plain .field (field shadowing is forbidden, so a class has exactly one field of each name), and SUPER.field is a compile error.
Example.
CLASS Square EXTENDS Shape {
OVERRIDE METHOD describe() RETURNS String { // concrete-parent reimpl — OVERRIDE required
RETURN ("a square, not " + SUPER->describe()) // SUPER->method() calls the parent's concrete body
}
METHOD move() RETURNS VOID { ... } // abstract-parent impl — OVERRIDE FORBIDDEN
}
Rationale. Reimplementing a concrete method silently is a common source of bugs, so OVERRIDE is required to make the intent explicit. Filling an abstract slot is fulfilling a contract rather than replacing a body, so OVERRIDE there would misdescribe the relationship and is forbidden.
(d) Rule. AUTO is a method modifier that asks the compiler to generate the body deterministically from the class structure; the developer writes the signature with AUTO and leaves the braces empty. AUTO fills the body of a method of an interface the class implements, when that method is on the compiler's synthesizable list; the signature is written exactly as the interface declares it, so the ordinary conformance check is the signature check. The V1 list is Cloneable.clone, Serializable.serialize and Reconstructable.reconstruct (the last two are I.P). AUTO on any other method is E1180. The generated clone() deep-copies every field: primitives and value types by value copy, class-typed and Box fields by a recursive clone(), collection fields by a cascading :=. If any field's type is not itself Cloneable, the generation fails at compile time with a diagnostic naming the offending field.
Example.
CLASS Record IMPLEMENTS Cloneable {
PRIVATE int32 id // primitive — value copy
PRIVATE Label tag // class-typed — recursive clone(); Label must be Cloneable
AUTO METHOD clone() { } // empty body — the compiler generates the deep copy
}
Rationale. Deriving clone() from the class structure removes a mechanical, error-prone body while keeping the deep-copy contract honest — the Cloneable-of-every-field check makes an un-cloneable field a compile-time error naming exactly which field blocks generation.
(e) Rule. DEPRECATED marks a class or a method as obsolete without removing it. A call to a deprecated method, and a construction of a deprecated class, continue to compile and run exactly as before. DEPRECATED is advisory: it never changes runtime behaviour and never blocks a build. Every such use site draws a build-time warning, so callers can plan a migration. It is written either bare or with a single string-literal message carried into each warning. DEPRECATED may appear on a CLASS or a METHOD declaration, and it composes in any order with the other modifiers valid there — ABSTRACT, FINAL, OVERRIDE. It is not yet supported on an interface, an enum, a struct, an INIT, a field, or a local variable.
Example.
DEPRECATED CLASS OldShape { ... } // bare
DEPRECATED("use NewShape instead") CLASS OldShape { ... } // message carried into each warning
DEPRECATED METHOD legacyDraw() RETURNS VOID { ... } // on a METHOD
DEPRECATED FINAL METHOD render() RETURNS VOID { ... } // composes with FINAL, any order
Rationale. Deprecation must guide migration without breaking builds, so it is warning-only and runtime-inert. The optional message points the reader at the replacement API or a removal deadline, and limiting it to CLASS and METHOD reflects where the warning is currently wired.
(f) Rule. A method may declare type parameters of its own, independent of any its enclosing class carries. The type parameters are written in brackets after the method name, and — exactly as for a templated class (I.K.ix.b) — the declaration is preceded by a mandatory TEMPLATE: GIVEN …: qualifier line constraining every one of them: there is no unconstrained generic anywhere in the language, on a class or on a method. A generic method declared without a qualifier is diagnostic E2110, the same code a templated class draws.
Example.
TEMPLATE: GIVEN TYPE T IS Serializable:
METHOD parse[T](String text) RETURNS (T value | STATUS status) // a generic NAMESPACE method
TEMPLATE: GIVEN TYPE T IS Cloneable:
METHOD echo[T](T v) RETURNS T { RETURN (v) } // a generic CLASS method
METHOD echo[T](T v) RETURNS T { ... } // ERROR E2110 — no qualifier
Rationale. Method genericity is bounded genericity like every other kind (I.A, I.K.ix). The qualifier is what the method promises about the types its body will see, and the only thing a caller must read to know whether a candidate type fits. Putting the brackets after the name keeps the declaration and the call site the same shape, so a reader matches parse[T] to parse[Person] by eye.
(f.i) Rule. A method call may carry explicit type arguments in brackets between the method name and the argument list. These bind the method's own type parameters at the call site, distinct from the class-level type arguments the receiver already carries. Both member-access sigils admit the form: receiver->method[T](args) on an instance, and Namespace.method[T](args) on a namespace (I.F.i — a namespace has no instance, so it is reached with .). The form is unambiguous because Envzn has no first-class functions, so name[…](…) after either sigil is always type-arguments-then-call, never index-then-call. Three diagnostics guard it. Supplying type arguments to a method that declares none is E2129, and supplying the wrong number of them is E2133. A type argument that does not satisfy the method's qualifier is E2114 — the same code, and the same satisfaction rule, a class instantiation draws.
Example.
receiver->method[T](args) // instance receiver — the `->` form
Json::Codec.parse[Person](text) // NAMESPACE receiver — the `.` form
CREATE Foo[T](args) // the mirrored construction form
plain->reset[int32]() // ERROR E2129 — reset declares no type parameters
Codec.parse[Person, Order](text) // ERROR E2133 — parse declares ONE type parameter
Codec.parse[Plain](text) // ERROR E2114 — Plain is not Serializable
Rationale. The two sigils are not interchangeable (I.F.i), so restricting call-site type arguments to -> would have put the whole namespace surface — including the serialization façade Codec.parse[T] — out of reach of method genericity for no reason. Enforcing the qualifier at the call site (E2114) is what keeps the constraint binding rather than decorative: without it, TEMPLATE: GIVEN …: on a method would be a comment.
(a) Rule. An interface-typed reference is dynamically dispatched, with no keyword required. A collection typed to an interface holds any concrete type that implements it, and a method call through the interface reaches the correct concrete implementation. The mechanism is an ordinary vtable — one per implementing class, one pointer indirection per call — and ENVZN_IR_SPEC.md C.iv describes how it is emitted. The element interface must satisfy the collection's template qualifier like any other type argument (I.K.ix). For a Cloneable-bounded collection such as Array, that means the element interface EXTENDS Cloneable, whose clone() the compiler auto-narrows to that interface — see the heterogeneous-element note in I.K.ix.
Example.
Drawable[] shapes
shapes->append(CREATE Circle(5.0) AS handle)
FOR shape IN shapes {
shape->draw(0, 0) // dynamic dispatch — the right method for each concrete type
}
Rationale. Interface-typed dispatch needs no keyword because the interface handle is itself the signal; the vtable gives one indirection per call, so a collection can hold a heterogeneous mix of implementers and still reach each one's own method. The qualifier-satisfaction requirement is what ties this to the generic machinery of I.K.ix.
(a) Rule. An enum declares a closed set of named cases, in three forms chosen by the data each case carries. A simple enum has cases with no associated data, for flags, directions, and states. A raw-value enum gives each case a primitive value of one shared type, read through .value. An associated-value enum lets each case carry typed data of its own shape, extracted by binding in a WHEN arm, and its cases may be mixed — some carrying values, some not.
Example.
ENUM Direction { NORTH SOUTH EAST WEST } // simple
ENUM HttpStatus { OK = 200 NOT_FOUND = 404 } // raw-value — read through .value
ENUM Shape { // associated-value
CIRCLE(float64 radius)
RECTANGLE(float64 width, float64 height)
POINT // cases may be mixed — POINT carries no data
}
Rationale. Three forms cover the three real shapes of a closed set — bare states, states tagged with one primitive, and states each carrying their own record — without forcing an author to model one as another.
(b) Rule. The integer value that backs each case follows one set of rules across all three forms. An implicit first case takes the value 1, and each subsequent implicit case takes the previous case's value plus one. An explicit = N may appear at any position, and the next implicit case after an explicit one continues from N + 1. Duplicate values are permitted — the cases remain distinct names regardless of whether their backing integers collide, and equality across enum values is by case identity rather than by raw value. The mixing of explicit and implicit cases inside a single enum carries no warning — the earlier warning W10041 against mixed-raw enums is retired.
Example.
ENUM Level { // backing integers:
LOW // 1 (implicit first case)
MEDIUM // 2 (previous + 1)
HIGH = 10 // 10 (explicit)
CRITICAL // 11 (continues from N + 1)
}
Rationale. Case identity, not the backing integer, defines an enum value's equality, so duplicate backing values are harmless and mixing explicit with implicit needs no warning — which is why W10041 was retired.
(c) Rule. An enum has no methods. It is a named, ordered list of cases with numbers attached to them, and that is the whole of it: an enum body admits cases and nothing else. It may use neither IMPLEMENTS nor EXTENDS (E6019) — with no methods there is no contract to adopt and nothing to inherit. Behaviour that varies by case belongs on a class or a namespace that takes the enum as a value, where it is visible as ordinary dispatch. Simple and raw-value enums automatically satisfy Equatable; associated-value enums do not, because their cases carry varying data and equality is not automatically well-defined.
Example.
ENUM Direction { NORTH SOUTH EAST WEST }
ENUM Bad IMPLEMENTS Describable { // ERROR — an enum adopts no contract
A B
METHOD f() RETURNS VOID { ... } // ERROR — an enum has no methods
}
Rationale. An enum names a closed set of alternatives; it is data, not a type with behaviour. Keeping it that way means a reader who finds an enum knows there is nothing hidden in it — no dispatch, no state, no contract — and that describing a case is the job of whatever consumes the enum. Article III's grammar has always said as much: enum_decl admits cases alone. Automatic Equatable is safe for simple and raw-value enums but not for associated-value ones, whose per-case data makes equality something the author must define.
(a) Rule. A type parameter is the tool for a homogeneous abstraction: a container or algorithm that works over one type at a time, uniformly, without inspecting or branching on which type it was handed. The payoff is that it preserves that type exactly across its surface. An Array[T] yields a T rather than a common supertype to be cast back down, and stores it without the boxing or dynamic dispatch a "collection of the shared base type" would impose. Where an abstraction must instead hold a mix of differing concrete types, or stay open to implementers written later, the right instrument is an interface and subtype dispatch (I.K.i–I.K.iv), not a type parameter. Two boundaries follow, both fixed: first, there is no unconstrained generic — every type parameter states the contract its arguments must satisfy, and the language rejects an ANY escape hatch; second, generics are not a compile-time programming language — Envzn has, and will have, no type-level computation, no substitution-driven overload selection, and no expression templates or recursive instantiation pressed into service as a metaprogramming engine.
Rationale. A generic parameterizes a type or an algorithm over types; it does not compute on them, dispatch on them, or reflect over them. This second boundary is drawn from experience rather than theory. The mechanism that began as the type-safe container — an unambiguous good — became, once allowed to grow into a metalanguage, the largest single source of unreadability in the language Envzn most resembles. Envzn keeps the container and refuses the metalanguage, permanently, not as a limitation awaiting a later release (this is the bounded genericity principle of I.A). The heterogeneous-element note in (e) is precisely the seam at which a generic container borrows the interface mechanism rather than competing with it.
(b) Rule. Every templated class — every CLASS declared with one or more type parameters — must carry a qualifier expression naming the inclusive set of types the template will accept. The qualifier sits on the line immediately above the class header and is mandatory: a templated CLASS without one is a compile error at the definition site. There is no implicit "anything goes" constraint; the language deliberately rejects an ANY escape hatch.
Example.
TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT boolean):
FINAL CLASS Array[T] IMPLEMENTS Cloneable { … }
FINAL CLASS Bag[T] { … } // ERROR — a templated CLASS with no TEMPLATE: qualifier line above it
Rationale. The intent is contractual rather than mechanical. The qualifier is what the template author promises about the shape of types its body will see, and the only thing a downstream developer needs to read to know whether a candidate type fits.
(c) Rule. The single-type form names one type parameter and one constraint; the multi-type form names several and binds a constraint to each. A constraint is an inclusive list of atoms separated by commas, where comma reads as or. An alternative may be wrapped in parentheses with the keyword AND to require every atom in the group, and that parenthesized form is the only way to express and at the constraint level. An atom is the name of a class, an abstract class, an interface, or a GROUP, or one of the reserved names PRIMITIVE, CLASS, BLITTABLE and FOREIGN_TYPE — built-in meta-categories rather than user-definable groups. PRIMITIVE means "any primitive type"; CLASS means "any reference type": a class, an abstract class or an interface, never a primitive, STRUCT or enum; BLITTABLE means "any value-copyable, true-POD type" (the computed closure of I.J); FOREIGN_TYPE means "any typed C handle declared by FOREIGN_TYPE BIND". FOREIGN_TYPE is reserved to the kernel, where only the opaque statics of I.D.v write it; a user qualifier naming it is a compile error (E2158), because a template over a typed handle could hold the raw pointer in a field that I.I.viii (c.i) forbids. After an atom that is a GROUP, PRIMITIVE or BLITTABLE, an (EXCEPT a, b, …) clause may narrow the membership by removing specific members; EXCEPT is not legal after a class, abstract class, or interface atom, since those name a single membership rather than an enumerable set. A ground type argument on an IMPLEMENTS or EXTENDS edge is a use of the template like any other and is checked against its qualifier (E2114). A candidate type T satisfies the constraint when it satisfies at least one alternative, and an alternative is satisfied when every atom in it is satisfied. A class atom is matched by an identical class or a transitive subclass. An abstract or interface atom is matched by any concrete implementer, and also by the interface or abstract type itself and by any sub-interface that transitively EXTENDS it — so a template may be instantiated over an interface element type, as (e) describes. A GROUP atom is matched by any transitive member not removed by the carve-out — a type belonging to a member group satisfies the enclosing group — and PRIMITIVE by any primitive name not removed. Where a group member is a bare parametric head (Array), the atom is matched by every instantiation of it (Array[int32], Array[String]), since the head is what the group names. An EXCEPT name that is itself a GROUP removes that group's members, not merely the name: Collectable (EXCEPT Text) removes String and its siblings, because a group name means its members on the exclude side exactly as it does on the include side. A type argument may be any runtime-shape array — T[], the pre-sized T[N+] (the same heap array, N only its starting capacity) and the N-D T[,] — but not a fixed-size array (T[N], T[3,4]): its extent is part of its type and inline in its storage, so the developer converts it first (INTO T[], INTO T[,]). A fixed-size argument is a compile error (E2171). (before it, no instance was made and the use reached clang as an undeclared identifier.)
Example.
TEMPLATE: GIVEN TYPE T IS Cloneable, PRIMITIVE (EXCEPT boolean):
FINAL CLASS Array[T] IMPLEMENTS Cloneable { … }
TEMPLATE: GIVEN TYPES K, V; K IS PRIMITIVE (EXCEPT boolean), String;
V IS Cloneable, PRIMITIVE (EXCEPT boolean):
FINAL CLASS Dictionary[K, V, H] IMPLEMENTS Cloneable { … }
TEMPLATE: GIVEN TYPE T IS Printable, (Readable AND Writeable): // parenthesized AND — every atom required
FINAL CLASS Stream[T] { … }
Rationale. Comma-as-or with a parenthesized-AND group gives exactly the two combinators a bounded constraint needs, and no more. The EXCEPT carve-out is allowed only where the atom names an enumerable set — GROUP, PRIMITIVE — since removing a member from a single class or interface would be meaningless. Admitting the interface/abstract type itself as a match is what lets a container be instantiated over an interface element type.
(d) Rule. The qualifier is parser-and-analyzer surface only; the emitter is unaffected. A doc-comment written above the TEMPLATE: block attaches to the class that follows, not to the qualifier — the qualifier is part of the class's contract, not a separate documented entity. Constraint enforcement at an instantiation site happens whenever a Foo[X] reference is reachable through a field, parameter, return type, or local. Each type argument is checked against the matching constraint, and a failure surfaces a single general code rather than a per-template special case. Type-parameter references inside the template's own body (e.g. Array[T] written within Array.ev's methods) skip the satisfaction check, since T is a type variable bound by the enclosing template rather than a concrete type; the constraint propagates at the outer instantiation site.
Example.
Array[Point] pts // instantiation site — Point checked against T IS Cloneable, PRIMITIVE …
Array[boolean] flags // ERROR — boolean is EXCEPTed from the qualifier
// inside Array.ev's own methods:
METHOD first() RETURNS T { ... } // T is a bound type variable here — no satisfaction check
Rationale. Because T inside the body is a bound variable rather than a concrete type, checking it there would be meaningless. The check belongs at the outer Foo[X] reference, where X is concrete, and a single general diagnostic keeps the failure uniform across every template.
(e) Rule — Heterogeneous interface-element collections. Because an interface atom is satisfied by the interface itself, and by any sub-interface that EXTENDS it, a collection may be instantiated over an interface element type. That holds a heterogeneous mix of implementers dispatched through the interface contract: Array[Cloneable], or more usefully Array[LogDestination] where INTERFACE LogDestination EXTENDS Cloneable. Each element is stored by owning handle to the interface and method calls dispatch virtually to the concrete implementer; append (an owning parameter) and read/dispatch require nothing beyond this rule. When the element interface is Cloneable, directly or transitively — as it must be to satisfy a Cloneable-bounded collection such as Array — its clone() must statically return the element interface, not the base clone() RETURNS Cloneable. Otherwise the collection's deep-copy path cannot store the clone back into an interface-typed slot. The compiler supplies this narrowing automatically: any interface that EXTENDS Cloneable (directly or transitively) is emitted with a covariant clone() returning that interface, so Array[LogDestination]->clone() works with nothing more than the EXTENDS Cloneable declaration. Writing the narrowing by hand (METHOD clone() RETURNS LogDestination) remains legal and, where present, takes precedence over the auto-generated form; it is no longer required.
Example.
INTERFACE LogDestination EXTENDS Cloneable { // compiler auto-narrows clone() RETURNS LogDestination
METHOD emit(String line)
}
Array[LogDestination] sinks // heterogeneous mix of implementers, dispatched through the interface
Rationale. This is the same covariant-return-via-subtype rule of I.K.iv, and it carries real weight here. The collection's own deep-copy path stores the clone back into an interface-typed slot, so clone() must statically return the element interface rather than the Cloneable root. The compiler supplies that covariant narrowing automatically for every Cloneable-extending interface (rather than diagnosing its absence), keeping the readable surface free of the boilerplate the mechanism requires — cost relocated inward. This admits element polymorphism — a container of differing implementers — and is distinct from container variance: an Array[ConsoleDestination] is still not assignable to an Array[LogDestination] parameter, as Envzn has no variance over type parameters.
(f) Rule — Type-parameter syntax, OF versus brackets. Envzn writes a type parameter in one of two forms, fixed by what is being parameterized so that a generic's parameter list is never confused with the array-type suffix T[]. A class is parameterized with brackets everywhere it appears — at its declaration, at every CREATE, and in every type position (field, parameter, return, local). An interface with a single type parameter is parameterized with OF, both at its declaration and wherever it is referenced. An interface with more than one type parameter uses brackets, because OF binds a single argument and has no multi-argument form. A parametric type is never named bare, in any position (E6092): a template qualifier atom names a parametric interface with its argument (T IS (Cloneable AND Equatable OF T), or Equatable[T]), and a WHEN type-test names a parametric interface after IMPLEMENTS, or a class template after IS, with its arguments adjacent to the name — WHEN T IMPLEMENTS Comparable[T] or WHEN T IMPLEMENTS Comparable OF T, WHEN T IS OrderedArray[int32] or WHEN T IS OrderedArray OF int32. A bare parametric head leaves its parameter unbound for everything that has to check it, and in a WHEN it lowers to a test the C++ backend cannot even state. (the WHEN predicate, and the OF spelling there)
Example.
FINAL CLASS Array[T] // class — brackets at declaration
CREATE Array[T]() // … at CREATE
Array[T] xs // … in a type position
INTERFACE Iterator OF T // single-param interface — OF
IMPLEMENTS Comparable OF T
EXTENDS ReferenceIterator OF T
ReferenceIterator OF T cursor
INTERFACE Dictionary[K, V, H] // multi-param interface — brackets (OF has no multi-arg form)
IMPLEMENTS Dictionary[K, V, H]
WHEN T IMPLEMENTS Comparable[T] { … } ELSE { … } // type-test — bracket form …
WHEN T IMPLEMENTS Comparable OF T { … } ELSE { … } // … or OF; never bare `Comparable` (E6092)
Rationale. The single guiding distinction is that OF is the unambiguous interface-parameterization keyword, while brackets carry both class generics and the array suffix. The two are told apart by content: a bracket holding a type name is a generic argument list, and one that is empty or holds a size ([512+]) is an array. Fixing each construct to one form keeps a generic's parameter list from ever being read as T[].
(g) Rule. GROUPs named in a qualifier belong to the module that defines them. A module wanting to use its own enum or struct as an atom defines a GROUP containing it, because enums and structs are not meta-categories of their own.
Example.
GROUP Numeric { int32, int64, float64, Money } // a module-local GROUP wrapping the desired atoms
TEMPLATE: GIVEN TYPE T IS Numeric:
FINAL CLASS Accumulator[T] { … }
Rationale. This keeps the closed-membership story honest: the set of types satisfying a constraint must always be reachable through one of the listed buckets. The buckets themselves can still grow — a new class implementing an interface, or a new member added to a group, automatically satisfies any constraint naming that interface or group.
(h) Rule. A template may name itself, directly or through other templates, only with arguments that are a bare type parameter (T) or a ground type (int32, Widget). An argument built from a type parameter in a self-instantiating position (Grow[Array[T]] inside Grow[T]) is a compile error at the declaration (E2155). Such a template asks for a new, larger type at every instantiation and never stops.
Example.
TEMPLATE: GIVEN TYPE T IS PRIMITIVE:
CLASS Grow[T] {
Grow[Array[T]] next // ERROR E2155: each Grow[X] needs a Grow[Array[X]]
}
Rationale. Instantiation produces one class per distinct argument. A self-reference through a constructed argument makes that set infinite, so it is refused where the reader can see it: at the declaration, not as a compiler that never finishes.
(i) Rule. Each instantiation of a template is analyzed as concrete code, with its arguments in place of its parameters. A name in the body that resolves for the template but not for an instantiation is a compile error (E2156). It is reported once, at the template line, with a note naming the instantiation and the use that required it.
Rationale. The qualifier is the template's promise. This rule is the check that the body keeps it for every argument the qualifier admits, rather than finding out from a failure inside generated code.
(j) Rule. A template declared in another module is instantiated from the declaration that module publishes in its headers file, bodies included. A module may instantiate a dependency's template only if that dependency published it. Using one that a dependency's headers file does not carry is a compile error (E9062): the dependency was built by an older compiler, and rebuilding it is the remedy. A direct FOREIGN:: call in such a body resolves against the dependency's headers file first and, failing that, against its .evir, which records every FOREIGN BIND the module declares.
Forwarding a type parameter into another parametric type.
When a class names another parametric type with one of its own type parameters in a slot, its qualifier for that parameter must be at least as tight as the receiving slot requires. There are two such places and both bind:
IMPLEMENTS / EXTENDS clause, where the class is the other type.TEMPLATE: GIVEN TYPES K, V, H; V IS Cloneable: // too weak …
CLASS MyDict[K, V, H] IMPLEMENTS Dictionary[K, V, H] { // … Dictionary's V slot
// requires Equatable[V]
The obligation is checked at the declaration, which is the earliest point it
exists and the point a reader can act on: the forwarding class's own qualifier is
what must change, not the use site that eventually instantiates it. Absent this,
a CREATE resolves against the looser class qualifier and the violation
surfaces far away — as a failure inside a generated method, in terms of the
target language rather than of Envzn.
Three facts the comparison honours, because the language already owns them and a name-by-name reading does not:
GROUP nesting. GROUP HashKey { WordKey, decimal128 } means K IS
WordKey satisfies a slot requiring HashKey.PRIMITIVE is satisfied by a qualifier constraining to
primitive type names or a primitive group. CLASS and BLITTABLE are decided
by the language, never granted by a qualifier, so a forwarder is never required
to restate them.Cloneable class"; each alternative of the caller must be covered by
some alternative of the callee.An interface's qualifier may demand only what its own methods use. A contract
the interface never exercises excludes implementors for no reason — and the
exclusion is invisible until some type that satisfies every method is refused
at the qualifier. An iterator that hands back references never clones, so it may
not require Cloneable; a Collection whose surface is size, isEmpty and
iterator asks nothing of its element and its qualifier must say so.
Envzn's structured-concurrency model: a developer writes tasks inside a scope rather than raw threads, and the channel and switchboard communication, the capture rules, and the synchronization surface all follow from that one decision.
(a) Rule. A developer who writes concurrent code in Envzn does not write threads — they write tasks inside a scope. The unit of concurrent work is a Task; the lifetime of every task is bound to a CONCURRENT { … } block, which is its scope. The everyday patterns live in the standard library as named, typed classes (I.L.vi), not as primitives the developer assembles by hand: a pool of workers draining a queue of jobs, a pipeline of stages, a broker fanning a typed message to a set of subscribers. The lower primitives those patterns are built on — Channel, Future, Mutex, Atomic — remain in the kernel for the library implementer and for the rare case the standard pattern doesn't fit.
Example.
CONCURRENT {
WorkerPool[Job] pool := CREATE WorkerPool[Job](4) // reach for the named pattern, not raw threads
FOR job IN incoming {
pool->submit(DUPLICATE job) // job is a FOR-IN borrow; submit owns, so hand it a copy
}
} // block does not exit until every worker has joined
Rationale. Threads are meant to be out-of-mind and the pattern the natural reach — the tutorials and examples do not lead with the raw primitives because ordinary code does not spend its time there. Every supporting decision in this section falls out of the one named idea: tasks live inside a scope.
CONCURRENT)(a) Rule. A CONCURRENT { … } block opens a structured scope. Its body executes on the calling thread, and the tasks launched within it — each through a PARALLEL block (I.L.ii) — are bound to it. The block does not exit until every task it launched has joined or been cancelled. The scope owns the lifetime of every Channel, Future, and cancellation token created inside it.
Example.
CONCURRENT {
Channel[int32] work := CREATE Channel[int32](16) // owned by this scope — closed on exit
PARALLEL { producer(work) } // launched task, bound to this block
PARALLEL { consumer(work) }
} // both tasks joined here before control returns
Rationale. This is structured programming applied to concurrent work. The essential guarantee is that a function call cannot leave background work running after it returns — the scope's brace is a join point, not just a lexical boundary.
(b) Rule. The first task to fail cancels its siblings, and the failure propagates to the block's enclosing scope.
Example.
CONCURRENT {
PARALLEL { stageA() } // if stageA fails …
PARALLEL { stageB() } // … stageB is cancelled, and the failure re-raises past this block
}
Rationale. Sibling cancellation on first failure keeps a scope from lingering while one task has already lost — the scope is all-or-nothing, and the caller sees the failure rather than a silently half-finished result.
(c) Rule. A task that genuinely needs to outlive its enclosing scope is written with the deliberately ugly DETACHED CONCURRENT { … } form, the language's explicit escape hatch. In V1 that form is reserved and rejected — the keyword is held against the namespace and the parser refuses its use — so every V1 task is bound to a structured scope; the escape hatch arrives in V2.
Example.
DETACHED CONCURRENT { … } // ERROR in V1 — DETACHED reserved, parser rejects; arrives V2
Rationale. Holding the keyword against the namespace now means no V1 code can spawn unstructured background work, and no future code has to fight for the name when the escape hatch ships.
(d) Rule. Cancellation is cooperative throughout: the enclosing scope's cancellation token is implicit, channel operations and explicit yield points observe it, and a tight CPU loop that ignores cancellation is a smell the analyzer warns on.
Example.
CONCURRENT {
PARALLEL {
WHILE NOT currentTask->isCancelled() DO { // observes the implicit token
grind()
}
}
PARALLEL {
WHILE work->receive() DO { // receive() is an implicit yield/cancel point
Job job := $RETURNED
process(job)
}
}
}
Rationale. Making the token implicit keeps the cancellation plumbing off the developer's surface, cost relocated inward. The analyzer warning catches the one case where cooperation breaks down: a CPU loop with no yield point, which could never notice it was cancelled.
PARALLEL)(a) Rule. A task is launched by a PARALLEL { … } block. PARALLEL is legal only inside a — transitively — enclosing CONCURRENT scope; a PARALLEL block with no enclosing CONCURRENT is a compile error.
Example.
CONCURRENT {
PARALLEL { doWork() } // OK — scope to join is right here
}
PARALLEL { doWork() } // ERROR — no enclosing CONCURRENT, nothing to join it
Rationale. A task with no scope to join is exactly the unstructured background work the whole model exists to forbid — so the compiler refuses it at the source.
(b) Rule. Each PARALLEL body runs as a task — on its own OS thread in the V1 runtime — and registers with the innermost enclosing CONCURRENT scope, which is the scope responsible for joining it. The join model is therefore flat rather than tree-shaped: every task joins the nearest scope directly, and nesting blocks does not nest the joins.
Example.
CONCURRENT { // outer scope
PARALLEL { outerTask() } // joins the OUTER scope
CONCURRENT { // inner scope
PARALLEL { innerTask() } // joins the INNER scope — the nearest one
} // innerTask joined here, not deferred to the outer brace
}
Rationale. Registering with the innermost scope makes the join site predictable from the code's brace structure alone — you read where a task ends by finding the nearest enclosing CONCURRENT, with no tree-walk to reason about.
(c) Rule. currentTask is a compiler-injected reference to the executing task — the task equivalent of SELF, reachable inside a PARALLEL body and nowhere else. The only operations valid on it are sleep, isCancelled, and reading the task's name; it cannot be stored, assigned, or passed.
Example.
CONCURRENT {
PARALLEL {
currentTask->sleep(100) // OK — sleep
IF currentTask->isCancelled() THEN { RETURN } // OK — isCancelled
String name := currentTask->name() // OK — read the name
Task t := currentTask // ERROR — currentTask cannot be stored, assigned, or passed
}
}
currentTask->sleep(1) // ERROR — currentTask reachable only inside a PARALLEL body
Rationale. Locking currentTask to three read-only operations, and forbidding it from escaping, keeps a task handle from leaking into shared state. There it would reintroduce exactly the unstructured lifetimes the scope model removes — the same discipline SELF gets, applied to tasks.
Channel[T](a) Rule. Point-to-point communication between tasks passes through a Channel[T] — typed, bounded by default, and the V1 primitive over which Producer-Consumer is expressed without a separate library. A Channel[T] is constructed with an explicit capacity; there is no zero-argument constructor.
Example.
Channel[int32] c := CREATE Channel[int32](32) // capacity 32 — required
Channel[int32] bad := CREATE Channel[int32]() // ERROR — no zero-argument constructor
Rationale. Forcing an explicit capacity makes the backpressure decision visible at the construction site rather than defaulted silently — a bounded channel is the safe default, and choosing its size is a choice the reader can see.
(b) Rule. When the capacity fills, a send() either blocks, drops the oldest, drops the newest, or conflates with the most recent — by a policy declared at construction. The unbounded form is the separately-named UnboundedChannel[T], for the case where the developer can prove from local information that the channel cannot grow without bound. Using it is a deliberate, named choice, and the analyzer surfaces every use as a review point. (UnboundedChannel[T] is reserved for V2 and is not available in V1.)
Example.
Channel[Reading] c := CREATE Channel[Reading](8, ChannelFull.CONFLATE) // full-policy at construction
// UnboundedChannel[Log] u := CREATE UnboundedChannel[Log]() // V2 — named, deliberate; every use a review point
Rationale. Naming the unbounded channel differently, rather than expressing it as a capacity flag, makes unbounded growth a word a reviewer can grep for — the risky choice is spelled out, not hidden in an argument.
(c) Rule. Ownership transfers on a send, and the sender may not touch the value after. A receiver takes a value through the channel's iterator — which blocks per item and exits cleanly on close — or through an explicit receive() call, which returns the pipe-XOR shape of I.M.i.
Example.
// sender — ownership moves out on send
c->send(reading) // send(T value) owns — reading is consumed
use(reading) // ERROR — reading was moved into the channel
// receiver A — receive() in a WHILE (blocks per item, ends cleanly when the channel closes)
WHILE c->receive() DO {
Reading r := $RETURNED
process(r)
}
// receiver B — explicit receive(), consumed as the pipe-XOR of I.M.i
IF c->receive() THEN { Reading r := $= } // $= = the received value
ELSE { printline($!) } // $! = fail message (channel closed / drained)
Rationale. Move-on-send means the value is never aliased across the boundary — no data race is even expressible — and reusing the pipe-XOR result shape (I.M.i) means a receive reads exactly like every other fallible read in the language.
(d) Rule. A channel closes automatically when its variable goes out of scope, signalling the end of the stream to receivers; closure is the channel's own concern and does not pass through a separate routing layer.
Example.
CONCURRENT {
Channel[int32] c := CREATE Channel[int32](4)
PARALLEL { FOR i = 0 TO 9 DO { c->send(i) } }
PARALLEL {
WHILE c->receive() DO { // exits cleanly when c closes
int32 v = $RETURNED
handle(v)
}
}
} // c goes out of scope → closes → receiver's WHILE ends
Rationale. Tying closure to scope exit means the end-of-stream signal is automatic — no close() for a producer to forget — and keeping it the channel's own concern avoids a routing layer between producer and consumer.
Broker[T](a) Rule. Broadcast — one publisher delivering a typed message to many subscribers — is a separate primitive, the Broker[T], and it replaces every earlier sketch of a routing-singleton design. A Broker[T] carries values of exactly one type; the topic is the type. There are no string-keyed topics, no untyped messages, and no broker-side state outliving the subscriber that put it there.
Example.
Broker[PriceTick] ticks := CREATE Broker[PriceTick]() // the topic is the type PriceTick
ticks->publish(tick) // publish owns tick
Rationale. Making the type the topic removes the whole class of string-typo and untyped-payload bugs a keyed pub/sub carries — the compiler already knows what flows through this broker.
(b) Rule. A subscriber subscribes through its enclosing CONCURRENT scope, declaring its own bounded buffer capacity and backpressure policy at subscribe time; the subscription's lifetime ends when the scope ends. There is no manual unsubscribe, no leaked subscription, and no broker-owned reference that outlives the subscriber.
Example.
CONCURRENT {
PARALLEL {
Channel[Tick] feed := ticks->subscribe(16, BackpressurePolicy.DROP_OLDEST) // own buffer + policy
WHILE feed->receive() DO {
Tick t := $RETURNED
render(t)
}
}
} // scope ends → subscription ends, nothing to unsubscribe
Rationale. Binding the subscription's lifetime to the scope is the same structured guarantee as the tasks themselves — a subscription cannot leak past the code that owns it, so the broker never holds a dangling reference.
(c) Rule. The hot path is lock-free: an atomic publish-index on the broker, a per-subscriber ring buffer for the queued backlog, and a single compare-and-swap on multi-publisher publish. Observable counters per subscriber report delivered, dropped, and high-water-mark for diagnostics. Subscribers do not see each other, and a slow subscriber does not starve a fast one — its own buffer fills and its declared policy decides what happens next.
Rationale. Per-subscriber ring buffers isolate consumers from one another, so throughput is set by each subscriber's own policy rather than by the slowest in the set. The lock-free publish path and the diagnostic counters are cost relocated inward: fast machinery under a readable surface.
Mutex, Atomic, and SYNCHRONIZED(a) Rule. Shared mutable state, where it is unavoidable, is reached through Mutex[T] — a wrapper whose data lives inside the lock and is reachable only inside a SYNCHRONIZED(mutex) { … } block bound to that mutex. The bare lock() / unlock() API is not exposed: a value protected by a mutex is touched only inside the block, and the block's exit releases it.
Example.
Mutex[int32] counter := CREATE Mutex[int32](0) // the data lives inside the lock
SYNCHRONIZED(counter) { // the only way to reach the protected data
counter.data := counter.data + 1 // `.` — data is a field, not a method
}
counter->lock() // ERROR — bare lock()/unlock() is not exposed
Rationale. Putting the data inside the lock makes it structurally impossible to touch the value without holding the lock — you cannot forget to acquire a lock you can only reach through a SYNCHRONIZED block.
(b) Rule. For lock-free single-word state, Atomic[T] over the primitive widths provides a load / store / compareExchange surface.
Example.
AtomicInt64 seq := CREATE AtomicInt64(0) // concrete AtomicX — the parametric Atomic[T] is V2
int64 now := seq->load()
seq->store(now + 1)
IF seq->compareExchange(now, now + 1) THEN { … } // CAS
Rationale. A single-word atomic needs no critical section — exposing exactly load/store/compareExchange gives the lock-free path its three operations and nothing that would tempt a developer to build a fragile ad-hoc lock out of them.
(c) Rule. Beneath both sits the SYNCHRONIZED(lock) { … } block, the language's explicit critical section. It acquires the named lock for the duration of its body and releases it automatically on every exit path — ordinary fall-through, RETURN, BREAK, or a PANIC unwinding through it. No path can leave the lock held. A Mutex[T]'s access block is precisely a SYNCHRONIZED block bound to that mutex, and a SHARED CLASS monitor (I.K.ii) wraps its own critical sections in SYNCHRONIZED by hand.
Example.
SYNCHRONIZED(lock) { // acquires lock for the body
IF done THEN { RETURN } // released on RETURN
IF skip THEN { BREAK } // released on BREAK
risky() // released even if this PANICs and unwinds through the block
} // released on ordinary fall-through
Rationale. Releasing on every exit path, including a PANIC unwind, is the whole point of a scoped critical section. No code path, ordinary or exceptional, can leave the lock held — which is the failure mode manual lock/unlock invites.
Future and the pattern library(a) Rule. Future[T] is the eventually-ready cell that WorkerPool and the V2 patterns return for submitted work, sharing its construction and consumption shape with the pipe-XOR result of I.M.i.
Example.
CONCURRENT {
Future[int32] f := pool->submit(job) // submit owns job; returns an eventually-ready cell
IF f->await() THEN { int32 result := $= } // consumed as the pipe-XOR shape of I.M.i
ELSE { printline($!) }
}
Rationale. Reusing the pipe-XOR shape (I.M.i) means a future's result reads like every other fallible value in the language — nothing new to learn to consume asynchronous work.
(b) Rule. The standard concurrent patterns ship as named stdlib classes built atop the primitives of the parts above, and they are what idiomatic Envzn code reaches for. V1 ships the foundation: Task, CONCURRENT, PARALLEL, Channel[T], Future[T], Mutex[T], the concrete AtomicX classes, and Broker[T]. It ships one canonical pattern with them — WorkerPool[T], the language's worker-pool and producer-consumer implementation in a single named class, constructed inside a CONCURRENT block and parameterised by pool depth. (UnboundedChannel[T] and the parametric Atomic[T] sugar are reserved for V2; see the Appendix.)
Example.
CONCURRENT { // WorkerPool is constructed inside a CONCURRENT block
WorkerPool[Request] pool := CREATE WorkerPool[Request](8) // parameterised by pool depth
FOR req IN requests { pool->submit(DUPLICATE req) } // req is a FOR-IN borrow
} // pool drains and joins at the brace
Rationale. One named class for the worker-pool/producer-consumer case is the pattern-is-the-reach stance made concrete: ordinary V1 code names WorkerPool rather than wiring Channel + PARALLEL by hand.
(c) Rule. (V2 reserved — pattern library.) V2 fills out the pattern library: Pipeline[In, Out] for chained-stage processing, ScatterGather for parallel-map over a typed input collection, and ForkJoin for divide-and-conquer over a work-stealing scheduler. Actor[State, Message] for isolated stateful entities, and Supervisor for restart-strategy fault tolerance. RateLimiter, CircuitBreaker, and Bulkhead for the resilience family, and Flow[T] for cold, demand-driven streams with backpressure operators.
Rationale. The V2 set is named and reserved now so the pattern vocabulary is planned as a whole rather than accreted ad hoc — each name is a slot already accounted for in the design.
(d) Rule. (V3 reserved — long tail and scheduler graduation.) V3 adds the long tail: Reactive Streams spec interop, Saga coordination, specialized channel variants. It is also where the runtime's task scheduler graduates from OS threads to a tuned virtual-thread M:N implementation. The V1 surface deliberately looks the same on either runtime so the V3 schedule swap does not change the code a developer wrote.
Rationale. Fixing the surface now and swapping the scheduler later is cost relocated inward at the largest scale: the V1 developer writes against tasks-in-a-scope, and the M:N virtual-thread runtime arrives in V3 without a single source change.
(a) Rule. Because a PARALLEL task body must be self-contained, its captures are restricted: the body may reference channels, brokers, futures, compile-time constants, and values it owns outright because they were moved into it before the CONCURRENT block. It may not call an instance method of the enclosing class, since that implicitly captures the instance, and it may not read shared mutable state of an enclosing scope.
Example.
Channel[int32] c := CREATE Channel[int32](8)
CONCURRENT {
PARALLEL {
c->send(1) // OK — channel reference is permitted
int32 n := MAX_BATCH // OK — compile-time constant
.helper() // ERROR — instance method implicitly captures the enclosing instance
n := .sharedCounter // ERROR — reading shared mutable state of an enclosing scope
}
}
Rationale. Restricting captures to things that are immutable, uniquely owned, or a communication primitive is what makes a task body safe to run on another thread without a lock. An implicit-SELF call, or a read of enclosing mutable state, would smuggle a shared, unsynchronized alias into the task.
(b) Rule. The compiler distinguishes a permitted local call from a forbidden implicit-SELF call by ordinary name resolution: a bare call resolves either to a local or to a method, and only the first is allowed inside a task body.
Example.
CONCURRENT {
LAMBDA transform: worker(transform) // a bare call resolving to a local — OK inside a task body
PARALLEL {
worker(x) // OK — resolves to a local
process(x) // ERROR — resolves to an instance method (implicit SELF capture)
}
}
Rationale. Reusing ordinary name resolution means the rule needs no new capture-annotation syntax — whether a bare call is legal in a task body is already decided by the same lookup that decides what the call means.
The two deliberately separated failure mechanisms — recoverable failure through STATUS and the return shapes, and unrecoverable failure through PANIC and RECOVER — and why conflating them is forbidden.
(a) Rule. Envzn separates two kinds of failure and gives each its own mechanism. A recoverable failure is an ordinary outcome a caller is expected to handle — a parse that did not succeed, a key that was not present — and it is communicated through return values (STATUS and the return shapes). An unrecoverable failure is a defect or a genuinely exceptional condition, and it is communicated by unwinding the stack (PANIC/RECOVER).
Example.
IF parser->scan(source) THEN { ... } ELSE { ... } // recoverable — handled through the return shape
PANIC FileNotFoundError("no config", path) // unrecoverable — unwinds the stack
Rationale. Conflating the two is a reliable way to make error handling either too noisy or too easy to ignore. Routing every ordinary miss through the stack-unwinding path buries expected outcomes in exception machinery; routing genuine defects through return values invites callers to drop them silently. Keeping the vocabularies apart forces each failure to travel the channel that matches how it must be handled.
(a) Rule. STATUS is the built-in type for recoverable outcomes. It carries one of three literals — SUCCESS, PARTIAL_SUCCESS(message), and FAILURE(message). Both FAILURE and PARTIAL_SUCCESS may carry a second argument, an int32 code, for a machine-readable error number alongside the human-readable message. The one-argument forms remain valid and mean a code of 0 — the value reserved for no numeric code, not for a meaningful zero. A STATUS is treated like a boolean literal and assigned with =.
Example.
STATUS ok = SUCCESS
STATUS f2 = FAILURE("open failed", 2) // message + int32 code
STATUS p2 = PARTIAL_SUCCESS("3 of 5 written", 3) // two-argument form
STATUS f1 = FAILURE("open failed") // one-arg — code is 0 (no code)
STATUS p1 = PARTIAL_SUCCESS("wrote most of it") // one-arg — code is 0
Rationale. The int32 code is where a numeric outcome from outside the program is carried: an errno from a SETS_ERRNO foreign binding, an HTTP status, a C-library result code. It rides alongside the message rather than being smuggled into it. Reserving 0 for no code keeps the one-argument form honest: a caller reading a 0 knows no external number was supplied rather than mistaking a meaningful zero.
(a.i) Rule. A STATUS literal is valid in exactly three places — the right side of a STATUS assignment, a WHEN arm of a MATCH, and the right side of an IS check in a plain IF. Writing one anywhere else is a compile error. A MATCH arm binds the code alongside the message, WHEN FAILURE(msg, code), and a pipe-XOR caller reads the code through the $# token described below.
Example.
STATUS s = readConfig(path) // (1) right side of a STATUS assignment
MATCH s {
WHEN SUCCESS: { ... }
WHEN PARTIAL_SUCCESS(msg, code): { ... } // (2) WHEN arm — binds message and code
WHEN FAILURE(msg, code): { ... }
}
IF s IS FAILURE THEN { ... } // (3) right side of an IS check in a plain IF
int32 n = SUCCESS // ERROR — STATUS literal outside its three places
Rationale. Confining the literals to three syntactic positions keeps STATUS out of general expression contexts, where it would read like an ordinary value. The only ways to inspect a STATUS are the guard (IS) and the exhaustive binder (MATCH).
(a.ii) Rule. An IF s IS FAILURE is a guard, suitable for early-exit propagation. Attaching an ELSE to a STATUS IS check is a compile error, because handling more than one variant is the job of MATCH, which is also the only way to bind the variant's message and code.
Example.
IF s IS FAILURE THEN { RETURN (s) } // guard — early-exit propagation
IF s IS FAILURE THEN { ... } ELSE { ... } // ERROR — no ELSE on a STATUS IS check
Rationale. A bare guard tests one variant and gets out of the way. The moment you want to branch on which variant, and to read its message and code, you are doing the work MATCH exists for. The language pushes you there rather than letting an IF/ELSE grow into a half-exhaustive match without binding.
(a.iii) Rule. PARTIAL_SUCCESS means the operation completed with caveats whose meaning is developer-defined and carried in the message; the caller decides whether, in its context, that counts as success or failure.
Example.
MATCH writeAll(records) {
WHEN SUCCESS: { done() }
WHEN PARTIAL_SUCCESS(msg, code): { retryRemainder(msg) } // caller decides this context's meaning
WHEN FAILURE(msg, code): { abort(msg) }
}
Rationale. Some operations genuinely land between clean success and outright failure. Rather than force the producer to pick one, PARTIAL_SUCCESS names that middle outcome and hands the interpretation to the caller, who alone knows whether a partial write is tolerable.
(b) Rule. A method communicates a value alongside an outcome through one of two return shapes. The comma shape, RETURNS (T a, STATUS s), populates every slot on every call: the value slot is meaningful even on failure. The pipe-XOR shape places a | separator in the clause and populates exactly one side — the success side or the failure side, never both. Its success side is a tuple of one or more typed slots, all populated together when the call succeeds. The shape is therefore either a success tuple — RETURNS (T t | STATUS s), RETURNS (A a, B b | STATUS s) — or the degenerate sole-STATUS RETURNS (STATUS s).
Example.
METHOD parse(String src) RETURNS (int32 pos, STATUS s) // comma — both slots always meaningful
METHOD dequeue() RETURNS (T t | STATUS s) // pipe-XOR — one side only
METHOD scan(String src) RETURNS (Token tok, int32 next | STATUS s) // pipe-XOR, multi-slot success tuple
METHOD flush() RETURNS (STATUS s) // degenerate — sole STATUS
Rationale. The comma shape suits a function such as a parser that returns the position it reached even when it did not fully succeed — the value is real regardless of outcome. The pipe-XOR shape suits everything where the value is meaningful only on success: it makes "there is no value on the failure side" a fact of the type rather than a convention the caller must remember.
(b.i) Rule. Three rules fix the pipe-XOR shape: the | appears at most once and is the last separator in the clause; STATUS is never a comma-member of a success tuple: it appears only as the post-| slot or as the sole slot, never alongside the values. An N-way union — (A a | B b | C c) — is not a V1 shape. It is reserved, and deferred to V3. The pipe-XOR shape is required for a reference-returning method that may fail (a reference has no meaningful default) and recommended for any value-returning method that should force the caller to confront failure.
Example.
METHOD lookupRef(K k) RETURNS (REFERENCE V v | STATUS s) // required — a reference has no default
METHOD at(int32 i) RETURNS (T t, STATUS s | STATUS s2) // ERROR — STATUS as a comma-member of success
METHOD choose() RETURNS (A a | B b | C c) // ERROR — N-way union reserved to V3
METHOD odd() RETURNS (T t | STATUS s | int32 n) // ERROR — `|` appears more than once
Rationale. One |, appearing last, keeps the split between "the values" and "the outcome" unambiguous — there is always exactly one success side and one failure side. Forbidding STATUS among the values prevents the two channels from bleeding together. The N-way union is genuinely useful but a much larger design, so it is parked to V3 rather than half-built in V1.
(c) Rule. A pipe-XOR call is consumed by an IF or a WHILE whose condition is the call. The IF's truth is the call's status — SUCCESS takes the THEN; FAILURE and PARTIAL_SUCCESS take the ELSE. Inside the success branch, $=[i] reads the i-th success slot ($=[0] first, $=[1] second), and bare $= is shorthand for $=[0]; the index must be a compile-time integer literal. Inside the failure branch, $! reads the failure STATUS's message (a String) and $# reads its int32 error code. Using a success or failure token outside its qualifying branch is diagnostic E6053.
Example.
IF scores->at(99) THEN {
REFERENCE int32 r =@ $= // $= is $=[0]
printline((r INTO String))
}
ELSE {
printline($!) // failure message (String)
printline(($# INTO String)) // failure code (int32)
}
IF parser->scan(source) THEN {
Token tok := $=[0]
int32 next := $=[1]
}
IF q->dequeue() THEN { ... } ELSE {
printline($=) // ERROR E6053 — success token in the failure branch
}
Rationale. Because the value exists only on success, the success tokens are reachable only inside the THEN, and the failure tokens only inside the ELSE. The compiler, not the reader, guarantees you cannot read a slot that was never populated. The index must be a compile-time literal because the slots are heterogeneously typed — the type of $=[i] is fixed only when i is known at compile time.
(c.i) Rule. Each of the three tokens has a verbose alias: $RETURNED for $=, $ERR_MESSAGE for $!, and $ERR_CODE for $#. Each alias shares token kind, scope rules, and lowering with its short form, so the two spellings are interchangeable and a call site may use whichever reads better.
Example.
IF parser->scan(source) THEN {
Token tok := $RETURNED[0] // $RETURNED ≡ $=
}
ELSE {
printline($ERR_MESSAGE) // $ERR_MESSAGE ≡ $!
printline(($ERR_CODE INTO String)) // $ERR_CODE ≡ $#
}
Rationale. The short forms keep dense call sites terse; the verbose aliases let a spelled-out call site read as prose. They lower identically, so choosing one is purely a readability call with no semantic cost.
(c.ii) Rule. The producer side is enforced so consumers need not re-check: E2081 for a pipe-XOR producer and E2082 for a single-return one guarantee every success slot is populated on the success branch, so a $=[i] consumer need not re-verify. A WHILE-pipe re-evaluates the call each iteration and exits on the first failure. Indexed access participates too: arr[i] on a collection whose subscript is pipe-XOR is itself a qualifying pipe-call condition.
Example.
WHILE q->dequeue() DO { Token t := $= } // re-evaluated each iteration; exits on first failure
IF arr[i] THEN { T v := $= } // arr[i] subscript is itself a qualifying pipe-call
Rationale. Enforcing full population at the producer (E2081/E2082) is what makes the consumer's job safe. Once the compiler proves every success slot is set on the success branch, reading $=[i] there can never see a hole, so the caller writes no defensive re-check. The WHILE-pipe turns "consume until it fails" into a loop header, and subscript-as-condition lets a fallible lookup drive a branch with no separate call.
(c.iii) Rule. $= (with $=[i] and $RETURNED) is typeless until it is bound. The only thing a success branch may do with it is bind it. It may move or copy it into a local, declared there (T v := $=, T v = $=) or already in scope (v := $=); store it into a data field (.f := $=); or, when the slot is a REFERENCE, bind a local REFERENCE to it (REFERENCE T r =@ $=). Every other use is diagnostic E6109. That includes a method call or field access on it ($=->m(), $=.f), passing it as an argument (f($=)), returning it (RETURN ($=)), using it as an operand or a condition ($= == 3, IF NOT $= THEN), and storing it into an array cell (xs[i] = $=). $! and $# are already typed (String, int32) and are unaffected.
An owned $= behaves as a local declared at the top of the success branch. If the branch does not move it, it is dropped when the branch ends, on every exit, as a local would be. A REFERENCE may never bind an owned $=, wherever that REFERENCE is declared: the value is moved into a local first, and the local is borrowed. The failure branch drops nothing, because its value slot is EMPTY.
Example.
IF hay->find(ndl) THEN { int64 at = $= } // bound by a declaration: legal
IF r->next() THEN { last = $= } // bound into a local already in scope
IF dict->lookupRef(k) THEN { REFERENCE V v =@ $= } // a REFERENCE slot, bound to a local REFERENCE
IF make(n) THEN { RETURN (1) } // an owned $= left unbound: dropped here
IF (s INTO int32) THEN { process($=) } // ERROR E6109 — an argument
IF re->find(t) THEN { printline($=->text()) } // ERROR E6109 — a member access
IF rd->readBool() THEN { IF NOT $= THEN { … } } // ERROR E6109 — an operand
IF make(n) THEN { REFERENCE String r =@ $= } // ERROR E6109 — a REFERENCE to an owned $=
Rationale. $= names a slot of a tuple whose types the reader has to look up in another method's signature. Binding it first puts the type on the page, where the reader is, and gives the value a name and an owner with an ordinary scope; every later action is an action on a typed local, under the usual rules. Refusing a REFERENCE to an owned slot keeps the branch's implicit owner from being outlived by a borrow, so the escape check needs nothing of its own. It also keeps the lowering simple: the value arrives in a register, and the only things that ever happen to it are one store or one drop.
(d) Rule. The multi-assign caller form generalizes to the multi-value success tuple: a destructuring assignment binds the success slots in order and then the STATUS.
Example.
Token tok, int32 next, STATUS s := parser->scan(source) // names every slot at once
Rationale. A caller may want all the slots as named locals, rather than reading them through $=[i] inside a branch. The destructuring form gives the same tuple its own names in one line, in slot order with the STATUS last.
(e) Rule. A return value is discarded deliberately and visibly with the marker $?: $? := call() drops a single return, and a $? slot drops one position of a multi-value return. Because $? marks an outbound value, it is a compile error as a call argument (E1136) or a parameter name (E1137). (Mandatory consumption — rejecting an ignored non-void return outright — is reserved and not yet enforced.)
Example.
$? := call() // drops a single return, on purpose and visibly
String data, $? := readFile(path) // keeps `data`, discards the STATUS deliberately
foo($?) // ERROR E1136 — $? as a call argument
METHOD m($? x) { ... } // ERROR E1137 — $? as a parameter name
Rationale. Discarding a result should be a decision the reader can see, not a silent drop: $? says "I looked at this and chose to ignore it." It is outbound-only because it marks a value leaving a call. Using it where a value is supplied — an argument or a parameter — is meaningless, so both are rejected.
( rename: the surface keywords are PANIC (raise) and RECOVER (the TRY handler clause) — same mechanism, more fitting tone. TRY and FINALLY are unchanged. THROW/CATCH are retired keywords that now produce a "renamed to PANIC/RECOVER" compile error. This sits below the non-catchable assertion family: a PANIC is handleable and unwinds; an assertion failure aborts.)
(a) Rule. Error is a reserved abstract class, and every error type extends it. Error cannot be instantiated or raised directly, and it implements no interface. (an interface the kernel no longer declares, and Readable, which Error never implemented.) It carries a message, set by the subclass through SUPER(msg); a cause, holding the message of a triggering error or EMPTY; and an int32 code. Three further fields are injected by the compiler at the panic site: filename, line_number, and threadName — the thread's variable name, or the absence value for an as-yet-unnamed context. A handler reads the text through String accessors — message(), cause(), filename(), threadName() — because the text is held as char[] storage, which is never public (E2064); code and line_number are public int32 fields. A developer-defined error subclass extends Error, may add its own fields, sets message through SUPER, and assigns its other fields in INIT.
Example.
CLASS FileNotFoundError EXTENDS Error {
String path
INIT(String msg, String filePath) {
SUPER(msg) // sets the inherited `message`
path = filePath // own field set in INIT
}
}
Error e := CREATE Error("x") // ERROR — Error is abstract; extend it, don't instantiate
Rationale. Making Error abstract forces every raised error to be a named subclass carrying its own context, so a handler can match on type. The three injected site fields (filename, line_number, threadName) come free at the PANIC site because the compiler knows where the panic is — the developer never threads them through by hand.
(b) Rule. PANIC takes the error type and its developer-defined INIT arguments, and the compiler injects the site fields. Handling is structured as TRY { … } RECOVER (Type bind) { … } FINALLY { … }. The TRY block guards the risky work, and each RECOVER clause names one error type together with a binding for the caught instance. The parentheses around (Type bind) are required, and there is no as keyword. The named type must resolve to a known type — an unresolved name is E2103, not a downstream C++ error — and it must be an Error subclass; catching a class that does not extend Error is rejected (E4027). An error type declared in a dependency module is caught by its qualified Module::Type name (the same qualifier that names any other cross-module type), and the emitted catch is qualified to that module. The raise side is symmetric: PANIC Module::Type(...) accepts the same qualifier — a dependency's error type is raised by its qualified name, and the emitted construction and panic are qualified to that module.
Example.
TRY {
openConfig(path) // may PANIC FileNotFoundError
}
RECOVER (FileNotFoundError e) { // parens required; no `as`
printlineErr(e->message())
printlineErr(e->filename()) // compiler-injected site field
}
Rationale. The (Type bind) form binds the caught instance to a name of the handler's choosing without borrowing a keyword like as; the required parentheses keep the type-plus-binding unit visually distinct from the block that follows.
(b.i) Rule. A TRY may carry several RECOVER clauses, matched top to bottom, so a subclass clause must precede its superclass to remain reachable. Catching the abstract base Error directly — RECOVER (Error e) — is rejected (E4016, catch-too-broad); every RECOVER clause must name a concrete Error subclass, and there is no catch-all.
Example.
TRY {
risky()
}
RECOVER (FileNotFoundError e) { // matched top to bottom by type
handleMissing(e)
}
RECOVER (NetworkError e) { // a different concrete Error subclass
handleNetwork(e)
}
Rationale. Top-to-bottom matching means an earlier, broader clause would shadow a later, narrower one; ordering subclass-before-superclass keeps every clause reachable. Catching the abstract base Error is rejected so a handler cannot silently swallow every failure type — each clause must name the concrete errors it is prepared to handle.
(b.ii) Rule. The trailing FINALLY { … } block — and the FINALLY keyword itself — is optional; when present it runs on every exit path, whether the TRY/RECOVER completes normally or a PANIC unwinds through it. Informative: catch errors as close to the problem as possible — the narrowest scope that can actually recover or add useful context — rather than a blanket handler far up the stack, where the originating context has already been lost.
Example.
TRY {
openConfig(path)
}
RECOVER (FileNotFoundError e) {
printlineErr(e->message())
}
FINALLY { // optional — omit the whole clause if unused
releaseHandle() // runs on normal exit AND on unwind
}
Rationale. FINALLY is the place for cleanup that must happen regardless of outcome, so it fires on both the normal and the unwinding path. Catching close to the problem preserves the context that a far-up blanket handler would already have lost.
(b.iii) Rule. On a PANIC, the runtime unwinds the stack between the panic and the matching RECOVER, running CLEANUP on every owned heap object in reverse order; non-owning handles are skipped, as ever, because the owner is responsible. Every error inherits two methods from Error: ->hasCause() reports whether cause is present, and ->getErrorCode() returns the code. (Corrected : this also listed ->stackTrace, which Error does not declare, and ->toJson and ->toString "from the two interfaces Error implements"; it implements none, and JSON_Serializer is retired.) Errors are chained by passing a triggering error's message as the cause of a new one.
Example.
TRY {
parseAll(source)
}
RECOVER (ParseError e) {
IF e->hasCause() THEN { logCause(e) }
int32 c = e->getErrorCode()
PANIC ConfigError("bad config", e->message()) // chain — triggering message becomes the new `cause`
}
Rationale. Unwinding in reverse and running CLEANUP on owned objects is what keeps PANIC memory-safe: every owner releases its heap on the way out, while non-owning handles are skipped because their owner already accounts for them. The inherited method set gives handlers a uniform way to inspect any error, and threading a message into cause builds the chain that explains what triggered what.
(b.iv) Rule — resource exhaustion. Running out of a finite resource is not a defect in the program, so it has its own branch of the hierarchy: ResourceExhaustedError extends Error, and OutOfMemoryError extends ResourceExhaustedError. Every block the runtime owns comes from one allocator, which never hands back an empty result for a non-zero size: when memory runs out it raises OutOfMemoryError with the message out of memory allocating <n> bytes, so no CREATE is ever followed by a null check. Whether that raise is catchable depends on the backend, and is fixed when the kernel is built. Under the LLVM backend it is an ordinary tier-2 PANIC: it unwinds, CLEANUP runs, and a RECOVER can shut down gracefully. Under the C++ backend it is not raised: the runtime prints the same uncaught-PANIC report, envzn: uncaught PANIC ENVZN:OutOfMemoryError: out of memory allocating <n> bytes — no handler, and aborts. (, kernel-runtime-natives M1. The split is the kernel's EV_OOM_RAISE build flag: the C++ backend never lets a C-runtime exception unwind through C++ frames, and that report is written without allocating.)
Example.
TRY {
buildIndex(corpus)
}
RECOVER (ResourceExhaustedError e) { // OutOfMemoryError lands here (LLVM backend)
printlineErr("index too large for this machine: " + e->message())
}
Rationale. One allocator that never returns an empty result moves the null check out of every caller and into one place (relocate the cost inward), and an empty result that nobody checks is a memory-safety breach. Giving exhaustion its own parent lets a handler say "I can recover from running out" without also catching the defects it cannot recover from.
(b.v) Rule — the entry frames' catch-all. Exactly two frames may handle every unwinding failure: the compiler-synthesized entry frames around Main::start() (the program's entry) and around ThreadEntry::run() (a thread's entry). Each carries, after its TRY, a RECOVER (Error e) that reports the uncaught Envzn error, followed by an implicit catch-all that reports any exception that is not an Envzn Error (a foreign one, raised in C or C++ code the program calls). Both handlers are the compiler's, not the developer's: no source can write either one. In every other frame, RECOVER names a concrete Error subclass (base Error is E4016), and there is no catch-all. A backend lowers the catch-all only in these two entry frames: in C++ a trailing catch (...), in LLVM a catch-all landing-pad clause after the Error clause.
Example. (what the compiler synthesizes, not source a developer writes)
// around ThreadEntry::run(id) — and, alike, around Main::start()
TRY {
ThreadEntry.run(id)
}
RECOVER (Error e) { // the entry frame only: base Error is E4016 anywhere else
// report "uncaught Envzn error: " + e, then end the thread (the program)
}
// implicit catch-all: report "uncaught non-Envzn exception", then end it
Rationale. An exception that escapes a thread's or the program's outermost frame has nowhere left to go. Without a handler there, the C runtime terminates the process with no report, and an unhandled foreign exception is undefined behaviour across the C boundary. A handler at exactly those two frames guarantees every failure is reported, and keeping it in the compiler's hands, and nowhere else, preserves the rule that a developer's RECOVER names what it can recover from (I.M, E4016).
The module as a filesystem folder: its manifest, its dependency and visibility rules, the name-resolution order, and how compiled modules link.
(a) Rule. A module is the unit of compilation, dependency, and visibility, and in Envzn it is a folder. There is no separate module declaration that the filesystem layout merely echoes: the folder is the module.
Example.
Networking/ // the folder IS the module "Networking"
Networking.json // the manifest (stem matches the module name)
src/
Socket.ev
HttpResponse.ev
interfaces.ev
enums.ev
Rationale. Making the folder the module means there is no import-resolution algorithm and no search path to learn: a module's structure is exactly what ls shows. This is one of the language's fixed principles.
(b) Rule. A module folder contains one manifest and one or more Envzn source files. The manifest is a JSON file named for the module: a module named Networking is described by Networking.json. It is the single source of truth for the module's identity, its build target, its Envzn dependencies, and any native dependencies. The compiler identifies the manifest by finding the *.json file whose stem matches its own name field. A dependency entry names the module it needs and, for one in the project, the path to it. It names a version only when the dependency is fetched from outside the project, where several versions exist and the version is a SemVer range; a dependency in the project is built from the same commit as the module that uses it, so it is always exactly the version that is there, and it carries none. A module's own version is a SemVer version whose build metadata (after +) is ignored when versions are compared.
Example.
{
"name": "Networking",
"version": "1.0.0",
"target": "shared_library",
"dependencies": [
{ "name": "AdvancedMath", "path": "../AdvancedMath" }
]
}
Rationale. The compiler keys on the name field rather than the filename, so the folder name itself carries no load. The identity lives in one authoritative place. A version on an in-project dependency would be a second copy of the dependency's own version, kept by hand in every module that uses it: bumping one module's version would mean editing every manifest naming it, and a copy that lagged would refuse a build that is correct (when computed versions replaced the placeholder 1.0.0s and 395 such copies went stale at once). A range earns its place only where it chooses between versions, which happens only for a package fetched from outside.
(b.i) Rule. Every file the compiler reads on a module's behalf lies inside the module folder — anything the manifest names, and anything the module's source directories contain. A path is canonicalized before use; if it resolves outside the module folder the compilation is rejected. The rule is about the resolved location, not the spelling: an upward ../ that lands back inside the folder is fine, and a plain-looking name that is a symlink out of it is not.
Example.
{ "name": "myLib", "version": "1.0.0", "target": "executable",
"nativeSources": ["../../../secret.cpp"] } // rejected: resolves outside myLib/
Rationale. The folder is the module (a), so a manifest deciding which files the compiler opens is bounded by that same folder — otherwise a manifest could steer a read anywhere on disk and route the contents into the translation unit or into a diagnostic. Canonicalizing first is what lets one rule cover both an upward escape and a planted symlink, without banning ../, which legitimate sibling layouts rely on. Paths that legitimately reach outside a module — a system library's headers, a system library to link — are the business of the build flags of (c.i), which are gated by provenance rather than by location.
(b.ii) Rule. A dependency declared with a path is bounded one level wider than (b.i), because a dependency legitimately lives outside the module that uses it. Its path is canonicalized and must resolve inside the consuming module, the library directory the build resolves against, or the project that library directory belongs to. Those roots are fixed by the build, never inferred from where the module happens to sit on disk. A dependency outside all three is not named by a path: it is installed, and resolves by name.
Example.
{ "name": "evTest", "path": "../../evTest" } // fine: a sibling in the project
{ "name": "Other", "path": "/etc" } // rejected: outside every root
Rationale. A dependency's path is the one manifest field whose whole purpose is to point outside the module, so (b.i)'s root cannot apply — but unbounded is not the alternative. Everything downstream of a resolved dependency path is a read: the dependency's manifest, its generated headers, its IR sidecar, and the include directories handed to the C++ toolchain. Bounding it to the project keeps the declaration a statement about the project rather than about the filesystem, and the package manager needs nothing wider: every location it searches for a dependency, the package cache included, lies within the project.
(c) Rule. The name follows the identifier rules of I.C and may not collide with a reserved kernel name. The target is either executable, which produces a binary and requires the entry-point arrangement of ENVZN_IR_SPEC.md C.vii, or shared_library, which produces a linkable library and a generated headers file.
Example.
{ "name": "Networking", "version": "1.0.0", "target": "shared_library" }
{ "name": "MyApp", "version": "1.0.0", "target": "executable" }
Rationale. The two targets split the two things a build can produce — a runnable binary versus a linkable library plus its public-surface headers — and each carries the arrangement its consumers need.
(c.i) Rule. The dependencies array names other modules, each by name, version, and an optional path; allows-foreign gates the foreign-function mechanisms; and a foreign block records native headers and libraries.
Example.
{
"name": "Networking",
"version": "1.0.0",
"target": "shared_library",
"allows-foreign": true,
"dependencies": [
{ "name": "AdvancedMath", "path": "../AdvancedMath" }
],
"foreign": {
"headers": ["sys/socket.h", "netdb.h", "openssl/ssl.h"]
}
}
Rationale. Every fact the build needs about a module's environment is declared in one place: what it depends on, whether it may reach across the foreign boundary, and which native headers and libraries it pulls in. The source files stay free of build metadata.
(c.ii) Rule. Every .ev source file begins with a MODULE declaration, directly below its header comment and before any other declaration — in a module of any target, and in a file compiled on its own. Where the file belongs to a module folder, the name must match the manifest. A missing line is an error (E9049); a name that disagrees with the manifest is an error (E9050).
Example.
MODULE Networking // first line of every Networking/src/*.ev
CLASS Socket {
...
}
Rationale. The MODULE line ties each source file back to the folder that owns it, so a file cannot be mis-filed into the wrong module. It is also where every type the file declares gets its identity: a type is its name and the module that declares it, which is what keeps two same-named types from different modules apart. A file without the line would declare types that belong to no module, so the line is never optional — not even for a single-folder executable or a lone file.
(c.iii) Rule. Dependency resolution locates each dependency's library and headers in a fixed order: the declared path, then a project lib/ directory, then a compiler-supplied search path. It resolves transitive dependencies topologically, and rejects a circular dependency or a version mismatch as an error.
Example.
"dependencies": [
{ "name": "AdvancedMath", "path": "../AdvancedMath" },
{ "name": "evTest", "path": "../evTest" }
]
// resolution order per entry: declared path -> project lib/ -> compiler search path
// a cycle A->B->A, or a version that does not match, is a compile error
Rationale. A fixed three-step lookup and a topological ordering make linkage deterministic and reproducible. Cycles and version mismatches are surfaced as errors rather than resolved silently, because either signals a broken dependency graph.
(c.iv) Rule — thread stack size. An executable manifest may set "thread-stack-size", written <n>K or <n>M: between 512K and 32M, and a multiple of 16K (one page on Apple silicon; a thread's stack is a whole number of pages). It sizes every thread the program's tasks run on (CONCURRENT/PARALLEL, the thread and worker-pool classes) and, on macOS, the main thread too, through the link; on Linux the main thread's size is the shell's ulimit -s. The default is 8M. Any other value, or the key in a shared_library manifest, is E9060: a library starts no program and has no threads of its own to size. (, kernel-runtime-natives M5.D. The size bounds how deep a correct program may recurse before the stack-exhaustion abort of I.A.ii(f).)
Example.
{ "name": "MyApp", "version": "1.0.0", "target": "executable", "thread-stack-size": "16M" }
(c.v) Rule — the program entry. An executable names its entry class in the manifest's entrypoint key, and that class implements one of two kernel interfaces. TaskStarter has METHOD start() RETURNS STATUS, for a program that takes no arguments. TaskStarterWithOptions OF T has METHOD start(REFERENCE T options) RETURNS STATUS, for one that does: T is a class of the same module that IMPLEMENTS TaskStarterOptions, and the key becomes an object whose options block describes T's fields (Appendix, "Manifest keys: the entrypoint block"). The compiler writes the parsing — describe, load and forwarded on T, which are implied by the interface and never written by hand — so start receives typed, validated values, and --help, usage errors (exit 2) and the usage text come from the same declarations. An options field is boolean, an integer up to uint32, a float, String, an enum, a blittable struct of those (flattened to --outer.inner), or a positional String[] that takes the rest of the words (E9070); the manifest and the class must agree (E9071). The entry class declares no INIT (E9069): the runtime constructs it, so nothing runs before start but the parsing the program declared. A program never reads argv itself; its own executable's path is System->programPath(). entrypoint.json is retired.
Example.
CLASS GreetOptions IMPLEMENTS TaskStarterOptions {
String name
int64 times
INIT() { .name = "World" .times = 1 }
}
CLASS Greet IMPLEMENTS TaskStarterWithOptions OF GreetOptions {
METHOD start(REFERENCE GreetOptions options) RETURNS STATUS {
REPEAT options.times { Stdio->printline(("Hello, $1!")->format(options.name)) }
RETURN (SUCCESS)
}
}
"entrypoint": { "start": "greet::Greet::start",
"options": { "name": { "type": "String", "alias": "n", "help": "who to greet" },
"times": { "type": "int64", "help": "how many times" } } }
Rationale. Reading arguments is among the first things a new developer does, and a hand-rolled loop over argv is where defaults drift from the help text and a typo becomes a silent wrong value. Declaring the options once, as typed fields and one manifest block, relocates that cost inward: the compiler writes the parsing and the usage from the same source, so they cannot disagree, and start sees only checked values. Banning the entry INIT keeps start the first line of the program's own logic.
(d) Rule. Every declared type has a canonical fully-qualified name, modulename::TypeName. The :: operator is legal only between a module name and a type name, exactly one level deep; further access uses . or ->.
Example.
AdvancedMath::Matrix m := CREATE AdvancedMath::Matrix(3, 3)
m->transpose() // further access uses -> (or . )
AdvancedMath::Matrix::Row r // ERROR — :: is one level deep only
Rationale. Restricting :: to a single module-to-type hop keeps qualification unambiguous: it names where a type comes from, and nothing more. Member and method access is left entirely to . and ->.
(d.i) Rule. A bare, unqualified type name resolves in a fixed order: first a type in the current module, then a type in ENVZN. Otherwise it is a compile error, directing the developer to declare the source module and qualify the name. Bare lookup never consults a dependency, even a declared one: if two dependencies both expose a Foo, the developer always writes depA::Foo or depB::Foo.
Example.
String s = "hi" // bare: current module, else ENVZN (kernel)
Matrix m := CREATE Matrix(3, 3) // ERROR if Matrix lives in a dependency
AdvancedMath::Matrix m := CREATE AdvancedMath::Matrix(3, 3) // qualify the source
Rationale. Keeping bare lookup off dependencies means ambiguity — two dependencies each exposing Foo — is resolved at the source, by the developer writing depA::Foo or depB::Foo. No precedence rule is left for the reader to reconstruct.
(d.ii) Rule. ENVZN::X is always legal and reaches the kernel; because a module may not declare a type that shadows a kernel name (see (e)), the bare name and the qualified form never disagree.
Example.
Array[int32] a := CREATE Array[int32]() // bare Array == ENVZN::Array
ENVZN::Array[int32] b := CREATE ENVZN::Array[int32]() // same type, explicit
Rationale. Since kernel names cannot be shadowed, ENVZN::Array and bare Array are guaranteed to name the same type. The explicit form is available for clarity, but can never mean something different from the bare one.
(d.iii) Rule. A qualified name module::Type resolves in exactly one place: the named module. If that module declares no such type, it is a compile error — the compiler never falls back to searching the current module, the kernel, or another dependency for the bare Type. Qualification is a precise instruction about where the type comes from, and the compiler obeys it literally.
Example.
mda::TextColumn c := CREATE mda::TextColumn(vs) // resolves only in mda
mda::Widget w // ERROR — mda declares no Widget (no fallback to a local/kernel Widget)
Rationale. A qualified name that silently resolved elsewhere would defeat the purpose of qualifying. The developer wrote mda:: to pin the source, so an absent member must fail loudly rather than drift to a same-named type in another scope. This is the mirror of (d.i): a bare name never reaches a dependency, and a dependency-qualified name never reaches anything but that dependency. Together they make a module's own type win its bare name, while every cross-module reference stays explicit. A module may legitimately declare a TextColumn alongside a dependency's mda::TextColumn: the bare form is the module's, the qualified form the dependency's.
(d.iv) Rule. ALIAS — a file-scoped short name for a qualified entity. Repeating a module qualifier at every mention is noise when a file leans on one dependency type or namespace function; ALIAS removes it for the span of a single file. An ALIAS declaration sits at the very top of a .ev file, after the MODULE line and before any CLASS, INTERFACE, or NAMESPACE. It binds a short name to a fully-qualified target for that file only; another file in the same module is unaffected. Three forms are recognised, by their qualifier:
- ALIAS module::Type (::) binds the dependency type module::Type to the bare name Type; every bare Type in the file — in a declaration, a CREATE, a MATCH ... WHEN, a PANIC — resolves to module::Type.
- ALIAS Namespace.function (.) binds a single namespace function; a bare function(args) in the file becomes the namespace call Namespace.function(args), so the Namespace. qualifier is no longer written.
- ALIAS Namespace (a bare namespace name) imports every function of the namespace: each becomes bare-callable in the file (cubeRoot(x) for Math.cubeRoot(x)).
Resolution is a pure rewrite performed before the module's files are merged: each aliased mention is replaced by its fully-qualified form, so nothing downstream treats an aliased name specially. ALIAS never widens visibility or changes linkage — it is only shorthand for a name that the developer could have written in full, and it is subject to two guards. The target must be real: a module::Type that names no exported type, or a namespace/function that does not exist, is E2107. And the short name must be unambiguous. An ALIAS whose short name also names a type declared in the file, a method of the file's class, or another alias is E2108 — as is a whole-namespace import that brings in such a colliding name. A bare use could otherwise mean two things. ALIAS does not shadow; where a collision is possible the program is rejected rather than silently resolved.
Example.
MODULE report
ALIAS mda::TextColumn // a dependency type
ALIAS Math.cubeRoot // one namespace function
// ALIAS Math // (alt.) every Math function, bare-callable
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
TextColumn c := CREATE TextColumn(vs) // resolves to mda::TextColumn
float64 r = cubeRoot(27.0) // resolves to Math.cubeRoot(27.0)
RETURN (SUCCESS)
}
}
Rationale. The qualifier exists to pin a name's source (d.iii); ALIAS keeps that pinning while paying for it once, at the top of the file, instead of at every use. Confining it to the file and forbidding any collision preserves the guarantees of (d.i)–(d.iii): a reader still sees exactly one meaning for each bare name. The alias table sits where the file's external dependencies are already declared, so what a file imports stays legible in one place. Because the alias is resolved by rewriting to the fully-qualified form before analysis, it introduces no new resolution scope and no runtime construct. It is a source convenience the compiler erases early.
(e) Rule. Type naming against the kernel is governed by one rule: no kernel type name may be shadowed. Every type the kernel (ENVZN) declares at top level is reserved: the utility gateways System, Stdio, Process, Math, File, Path, and the retired-but-still-reserved Convert, together with the collection and value types String, Array, Set, Dictionary, Stack, Queue, Box, DynamicString, and the rest. A module that declares a class, struct, interface, group, or enum with one of those names is a compile error.
Example.
CLASS Set { ... } // ERROR — Set is a reserved kernel top-level name
CLASS Path { ... } // ERROR — Path is a reserved kernel gateway name
CLASS Convert { ... } // ERROR — retired but still reserved
CLASS SocketPool { ... } // OK — not a kernel name
Rationale. An earlier design split these — gateways were reserved but collection and value types were shadowable (a module's own Set bound bare Set locally while ENVZN::Set reached the kernel). Shadowing is unsafe because it silently corrupts type resolution. A concrete field in a shadowing class can be mis-typed as the shadowed kernel generic's type parameter T, so the emitter lowers it as the generic (_ev_ref_of(...)) instead of the concrete form (&this->field). The distinction was removed; all kernel names are now reserved alike.
(e.i) Rule. The check keys on the kernel's top-level types only. A class-nested type, such as the GROUP StatusKind inside _EvStatus, does not reserve its bare name, so a module may still declare its own top-level StatusKind.
Example.
STRUCT StatusKind { int32 x } // OK — _EvStatus.StatusKind is nested, not top-level
Note. The name is StatusKind rather than the broader Kind, which is plausible enough as a user type that a module declaring one would collide with the nested kernel group. Narrowing the kernel name removed that reachable collision.
Rationale. Reserving only top-level kernel names keeps the reserved set small and predictable. A name buried inside a kernel class was never reachable bare, so reserving it would cost developers names for no safety gain.
(f) Rule. Visibility is public by default: every type a module declares is visible to any module that depends on it. The generated headers file is the authoritative record of that public surface. INTERNAL marks a declaration module-private: the headers file records it with its marker, so a dependent can instantiate a template that uses it, but it is not part of the public surface and dependents may not name it. Naming another module's INTERNAL type is a compile error (E2157), wherever the name appears: a field, a parameter, a return type, a local, a CREATE or a type argument. Code that is instantiated from a template is judged as belonging to the template's own module, so a library template may use that library's INTERNAL types in its body. INTERNAL applies to concrete classes, namespaces, enums, structs, fields, and methods. On a field or method it widens the audience to every class in the same module while keeping it out of the public surface, and it is mutually exclusive with PRIVATE. An INTERNAL NAMESPACE is a set of free functions callable anywhere in its module and from nowhere else (E6034).
Example.
INTERNAL CLASS JsonFrame IMPLEMENTS Cloneable { // module-private, not in headers
INTERNAL int32 depth // visible to same-module classes
INTERNAL METHOD push() RETURNS STATUS { ... }
}
INTERNAL NAMESPACE RawMutex { // module-private free functions
METHOD lock(UNSAFE.MUTEX h) { FOREIGN::ev_mutex_lock(h) }
}
Rationale. Public-by-default matches the folder-is-the-module model: a module's declared surface is its interface. INTERNAL gives a bounded relaxation, opening a member to the rest of the module without ever leaking it into the headers. PRIVATE (class-only) and INTERNAL (module-wide) are genuinely distinct audiences, and cannot be combined.
(f.i) Rule. Applying INTERNAL to an interface, an abstract class, or a local variable is a compile error.
Example.
INTERNAL INTERFACE Hasher { ... } // ERROR — an interface exists to be implemented
INTERNAL ABSTRACT CLASS Shape { ... } // ERROR — an abstract class exists to be extended
METHOD run() {
INTERNAL int32 count = 0 // ERROR — a local has no module-level visibility
}
Rationale. An interface and an abstract class exist precisely to be implemented or extended by a consumer, so hiding them from consumers is contradictory. A local variable has no module-level visibility to adjust, so the modifier is meaningless there.
(g) Rule. A module's source files follow a strict naming rule. Every file other than the grouping files holds exactly one top-level declaration, and its filename stem matches that declaration's name. The declaration is a class, an interface, a primitive, a conversions block, or a single STRUCT. The grouping files are interfaces.ev, which holds the module's INTERFACE and GROUP declarations; enums.ev, which holds its ENUM declarations; and structs.ev, which holds module-level STRUCT declarations.
Example.
Networking/src/
Socket.ev // one top-level: CLASS Socket
HttpResponse.ev // one top-level: CLASS HttpResponse
interfaces.ev // all INTERFACE + GROUP declarations
enums.ev // all ENUM declarations
structs.ev // module-level STRUCT declarations
Rationale. Keeping one declaration per file with a matching stem keeps a module's file inventory in close correspondence with its declared surface: the file list is the type list. The three grouping files pool the small declarations that would otherwise scatter across many one-line files.
(g.i) Rule. A STRUCT is the one supporting type with two valid homes. The structs.ev pool is the natural place for small, shared, or owner-less records; its own StructName.ev file reads better when a struct is closely tied to a single type and meant to live beside it. A STRUCT may not share a file with another top-level declaration (E9008); ENUM and GROUP have no own-file form and always live in their grouping file.
Example.
// AddrInfo.ev — own-file form, sits beside the type that uses it
STRUCT AddrInfo { int32 family, int32 socktype, int32 protocol }
// structs.ev — the pooled form for small shared records
STRUCT Point { int32 x, int32 y }
STRUCT Range { int32 lo, int32 hi }
// Socket.ev
CLASS Socket { ... }
STRUCT Handle { int32 fd } // ERROR E9008 — a STRUCT may not share a file
Rationale. A STRUCT earns two homes because both readings are legitimate: pooled when it is a small shared record, own-file when it is bound to one type. It may never share a file (E9008), which would break the one-declaration-per-file correspondence. ENUM/GROUP have no own-file form and always live in their grouping file.
(h) Rule. Envzn reaches a C function or C library through FOREIGN BIND: a forward declaration of an external function, written entirely in Envzn types. From it the compiler emits a direct call and synthesizes every conversion at the boundary, so .ev source contains no inline C++ and the foreign surface stays type-checked in Envzn terms. A module uses any foreign mechanism only if its manifest sets allows-foreign.
Example.
FOREIGN BIND CONSTANT int32 SOCK_STREAM
FOREIGN BIND gai_strerror(int32 errcode) RETURNS String
FOREIGN BIND freeaddrinfo(AddrInfo res) // (LOAD out-parameters are covered in (h.i))
{ "name": "Networking", "allows-foreign": true, "foreign": { "headers": ["netdb.h"] } }
Rationale. Writing the foreign surface entirely in Envzn types keeps .ev source free of inline C++, and lets the type checker cover the boundary. The allows-foreign manifest gate keeps the foreign-function boundary out of ordinary application code. The full account of how FOREIGN BIND and its relatives lower to C is given in ENVZN_IR_SPEC.md C.vi, and inline FOREIGN { } blocks are removed (h.ii). What remains pending is the deprecation of the legacy FOREIGN declaration form, and the _cxx* retirement.
(h.i) Rule. The LOAD parameter modifier — out-parameters the C call fills. LOAD marks a FOREIGN BIND parameter the C function writes through rather than reads. It lowers to &handle uniformly, and the parameter's storage shape alone sets the pointer depth. Three shapes cover the cases. A LOAD char8[], or any value-array, is a caller-sized fill buffer: it lowers to a pointer to its element's C type (T *, (h.vi)) that the C call writes into directly, its length parameter is checked against the array's capacity (h.vi), and its length after the call is the fill count of (h.iii). A LOAD of a FOREIGN_TYPE value handle is a caller-allocated struct, passed as &value → X *, its fields reached with .. A LOAD of a FOREIGN_TYPE pointer handle is a callee-allocated struct, passed as &pointer → X **, its fields reached with ->. LOAD is legal only on a FOREIGN BIND parameter; on an ordinary method parameter it is E2100. It is legal only on an eligible mutable storage type, so a LOAD of an immutable String is E2101. The three shapes LOAD accepts are given in (h.iii); their lowering is ENVZN_IR_SPEC.md C.vi.
Example.
FOREIGN BIND read(int32 fd, LOAD char8[] data, int32 n) RETURNS int32 // fill-buffer: void*, C writes, returns count
FOREIGN BIND stat(String path, LOAD FileStat buf) RETURNS (int32 result | STATUS status) SETS_ERRNO(-1) // caller-allocated struct: &value -> X*
FOREIGN BIND getaddrinfo(String node, String service,
AddrInfo hints, LOAD AddrInfo res) RETURNS int32 // callee-allocated: &pointer -> X**
// METHOD take(LOAD int32 x) // ERROR E2100 — LOAD outside a FOREIGN BIND
// FOREIGN BIND f(LOAD String s) // ERROR E2101 — immutable String ineligible
Rationale. LOAD is the boundary's answer to a C out-parameter — a value the callee fills — without ever exposing a raw pointer to Envzn code. The compiler takes the address, and the storage shape alone decides whether that is a void * fill buffer, an X * to a caller-allocated struct, or an X ** for a callee-allocated one. No separate OUT or OUT STRUCT keyword is needed. It is the write-through half of the FFI surface that the UNSAFE / opaque carriers of I.I.viii complete on the handle-holding side.
(h.ii) Rule. No inline FOREIGN { } blocks. An inline FOREIGN { <raw C++> } block embedded in .ev source is not a valid construct. Native code is reached only through FOREIGN BIND, against a separately-compiled shim. A block in any module — the ENVZN kernel included — is diagnostic E3041. The prohibition is universal (there is no allows-foreign escape — allows-foreign gates the FOREIGN BIND family, never a raw-C++ block) and is enforced in the analyzer, so it holds under every backend. The kernel's own Process singleton reaches fork / execvp / waitpid this way, over the C shim EV_process_native.c.
Example.
// METHOD m() { FOREIGN { ::some_c_call(); } } // ERROR E3041 — inline raw-C++ block removed
FOREIGN BIND some_c_call(...) RETURNS ... // reach native code through a bound shim
Rationale. An inline block was the one native passthrough that bypassed the allows-foreign opt-in — any .ev could inject arbitrary C++ (or machine code) with no manifest flag and no diagnostic. Removing it rather than gating it closes that hole completely, and makes (h)'s "no inline C++" a genuine guarantee rather than an aspiration. The native escape remains available, typed and greppable, through FOREIGN BIND. (Shipped V1)
(h.iii) Rule. The LOAD shape table. LOAD accepts exactly three parameter shapes. The presence or absence of a * in the bound C type distinguishes the second from the third: a caller-allocated value from a callee-allocated pointer.
| Form | C shape | What the compiler passes | Field access |
|---|---|---|---|
LOAD char8[] |
void *buf — a caller-sized fill buffer |
the raw element pointer; the C call writes into the Envzn-owned array's own storage, and the array's length is then the fill count below | — |
LOAD <FOREIGN_TYPE value> — bound as (struct X) |
struct X *buf — caller allocates |
the handle is a stack value; LOAD passes &value, giving X* |
. |
LOAD <FOREIGN_TYPE pointer> — bound as (struct X *) |
struct X **out — callee allocates |
the handle is a pointer; LOAD passes &pointer, giving X** |
-> |
Example.
FOREIGN_TYPE BIND (struct stat) FileStat { int64 st_size int32 st_mode int64 st_mtime }
FOREIGN BIND stat(String path, LOAD FileStat buf) RETURNS (int32 result | STATUS status) SETS_ERRNO(-1) // value form — buf becomes X*
FOREIGN_TYPE BIND (struct addrinfo *) AddrInfo // pointer form — the callee allocates the list node
The fill count. After the call, a LOAD array's length is the number of elements C wrote, and the binding says where that number comes from. A return named count, in a binding with exactly one LOAD array, is that array's fill count: the length becomes the return, clamped to [0, bound], so a -1 error return leaves it empty and an end-of-file 0 leaves no stale elements. Any other binding — a void, pointer or status return, or an integer return under another name — fills exactly its bound, so before C runs an array shorter than the bound grows to it, the added elements zeroed; an array already longer is never shrunk, and its elements past the bound keep their values. The count and the bound are in one unit, the unit of (h.vi): a bound that counts bytes makes the count bytes, which is divided by the element's size, so a recv of 6 bytes into an int16[] leaves 3 elements. The value the call returns is passed through unchanged. A count return beside two or more LOAD arrays names no one array and is E2159; a count return that is not an integer, in a binding with a LOAD array, is E2160. Without a LOAD array count is an ordinary name (pwrite returns one).
FOREIGN BIND read(int32 fd, LOAD binary[] data, C.size_t nbyte) RETURNS (C.ssize_t count) // length = what read() returned
FOREIGN BIND getentropy(LOAD binary[] buf, C.size_t length) RETURNS int32 // length = length; the int32 is a status
Rationale. Reading the value-versus-pointer distinction off the bound C type means both POSIX families are expressible without a separate OUT modifier: the caller-allocated stat and its relatives, and the callee-allocated getaddrinfo. The declaration stays a transcription of the C signature rather than a second thing to learn.
(h.iv) Rule. The CALLED_BY_EMITTER marker — a binding whose caller is generated code. A FOREIGN BIND whose only call sites are written by the compiler, not by any .ev source, is marked CALLED_BY_EMITTER. It is a trailing marker on the declaration, in the same position and of the same kind as SETS_ERRNO, may appear at most once, and — like the other markers — is valid only on a FOREIGN BIND, never on the legacy FOREIGN form (E1169; a repeat is E1170). It changes no lowering: the binding is emitted, typed, and called exactly as an unmarked one. Its sole effect is to exempt the declaration from the unused-FOREIGN warning, which counts FOREIGN::name(...) call sites in the declaring file and therefore cannot observe a caller the compiler synthesizes. The marker is kernel-facing in practice; an ordinary module has no emitter-reached bindings.
Example.
// The emitter writes this call into every synthesized bounds check;
// no .ev line names it.
FOREIGN BIND _value_array_throw_oob(int32 idx, int32 bound) CALLED_BY_EMITTER
Rationale. Without the marker the compiler reports a still-needed declaration as dead and advises removing it — advice that breaks the build, because the emitted C++ still calls the symbol. The alternative, teaching the analyzer the set of names the emitter happens to synthesize, moves a fact about the kernel into the compiler and covers new cases silently. Declaring the intent where the binding is written keeps the analyzer honest about everything else in the file: the warning stays live for every unmarked declaration, which is how the redundant ev_datetime_from_broken_down in DateTime.ev was found.
(h.v) Rule. The owned-return markers $* and $(freer) — a C result the caller must free. A FOREIGN BIND whose C function returns memory the caller owns says so with a trailing marker, in the same position as SETS_ERRNO. $* frees the result with free() once it has been copied into the Envzn value; $(name) names the freer instead ($(sqlite3_free), and $(sqlite3_free()) is accepted). The binding lowers to a translation-unit-local wrapper that copies the result, for a String return into a fresh String with a null result becoming EMPTY, and then frees the original. The marker also applies to the two returns that arrive as a NULL-terminated const char**, String[] and Dictionary[String, String, H]: every element is copied, and then each element string and the array itself are freed. A marker on any other return is E2093. At most one marker is allowed per declaration (E1170), and like the other markers it is valid only on a FOREIGN BIND (E1169). An opaque handle never takes one: its lifetime is managed by the wrapping class.
(h.vi) Rule. A native array at the boundary — an element pointer, and the length that keeps C inside it. A native array (T[], T[N], T[N+], or a dense T[,]) of a boundary element type crosses a FOREIGN BIND as a pointer to its element's C type: const T* for a plain (read) parameter and T* for a LOAD (written) one. The constness follows the parameter's mode, never the C prototype, so it is decided by the binding alone. The C element type is the primitive's own lowering (int32_t, double, char32_t), except where that lowering has no C spelling: char8 crosses as char and binary as uint8_t, each layout-identical. A C.* element crosses as its C type (C.size_t[] as size_t *), and an UNSAFE.HANDLE[] as an array of C pointers (void **, void * const * for a read parameter). A pointer carries no length, so every one-dimensional native array argument must be bounded by something in the binding, and the binding alone decides how. An integer-typed scalar parameter is a length when its name says so: one of length, len, count, cnt, n, num, nbyte(s), bytes, size, sz, cap, capacity, max, maxlen, nmemb, nelem(s), elems, bufsize, buflen; or a name ending in len, length, size, count, cap, capacity, nbyte(s), bytes, nmemb or nelem(s); or a name of two or more camelCase/underscore words whose first is n, num or max. Reading the parameters left to right, a length bounds the arrays declared since the previous length that its name refers to (the array's name occurs in it, or the two share a word), or all of them when it refers to none. A length whose name contains byte or size counts bytes; any other counts elements. Each array is then exactly one of four classes, the first that applies: bounded — before the call the compiler checks 0 ≤ length ≤ count (elements) or 0 ≤ length ≤ count × size of the element (bytes), where count is the array's length for a read parameter and its capacity for a LOAD; integer buffer — an array of integers, which C reads as a fixed-shape count or out-cell, is checked to hold at least one element; C string — a read char8[] or binary[] is checked to contain a 0 element within its length; length elsewhere — any other array, in a binding that carries some other integer parameter or integer array through which C learns the extent, crosses unchecked. A failed check raises IndexOutOfBoundsError (I.M.ii) before C runs — except a negative length bound as an unsigned C-ABI type (C.size_t), which keeps the MathError of I.D.x — and each argument is still evaluated exactly once. An array that falls in none of the four classes is E2154: nothing in the binding can tell C where it ends. String[] and N-dimensional arrays are not classified; they carry their own extent.
Example.
FOREIGN BIND write(int32 fd, binary[] data, C.size_t nbyte) RETURNS C.ssize_t // bounded: nbyte ≤ data.length bytes
FOREIGN BIND read(int32 fd, LOAD binary[] data, C.size_t nbyte) RETURNS C.ssize_t // bounded: nbyte ≤ data.capacity bytes
FOREIGN BIND puts(char8[] s) RETURNS int32 // C string: a '\0' must occur in s
FOREIGN BIND pipe(LOAD int32[] fds) RETURNS int32 // integer buffer: capacity ≥ 1
// FOREIGN BIND strcpy(LOAD char8[] dst, char8[] src) // ERROR E2154 — dst has no length
Rationale. Memory safety is the floor (I.A), and an element pointer is exactly the shape that lets a C function walk off the end of an Envzn array. The compiler cannot see the C prototype, but it can see the binding, and a binding written as a transcription of the C signature nearly always names its lengths. Reading those names makes the common case — write, read, recv, memcpy, snprintf — checked with no extra syntax, which relocates the cost inward; the residue that names no length is rejected rather than trusted. Constness from the mode, not the prototype, keeps the rule checkable without C.
(h.vii) Rule. A FOREIGN BIND matches the C it names. Every module build reads the module's C signature catalog, build/c-catalog.json, made from the system headers and the module's own C before the compiler runs; a build that finds none, or one of an older schema, stops with E9064. Each FOREIGN BIND is then compared with the C declaration of its name, so the binding names the type its C declaration names. Values compare by ABI, width and signedness, so int64 matches C's long on an LP64 target; where no fixed-width primitive matches on every target, the binding names a C-ABI type of I.D.x. Pointers compare by exact type, with one exception: a byte array (binary[], int8[], uint8[], char8[]) and any single-level handle may cross as void *. A C enumeration is a value of the width and sign the compiler gives it, and a C function pointer matches only a FOREIGN_TYPE naming that type. A variadic function binds its fixed parameters as declared, and the binding's further parameters are its variadic arguments. The failures are: a name absent from the catalog, which predates the binding (E2161); a parameter count that differs, or a return where C returns nothing (E2162); a value of the wrong width or sign (E2163); a pointer of the wrong type (E2164); an array wider than bytes passed as void * (E2165); a variadic argument C would promote, an integer narrower than int or a float (E2166); and a FOREIGN BIND CONSTANT missing from the catalog or not fitting its declared type (E2167). A name the catalog records as unresolved is a C++ function, which the catalog does not read; it is not checked.
Example.
FOREIGN BIND read(int32 fd, LOAD binary[] data, C.size_t nbyte) RETURNS (C.ssize_t count) // ssize_t read(int, void *, size_t)
FOREIGN BIND chmod(String path, C.mode_t mode) RETURNS int32 // mode_t: 16 bits on Darwin, 32 on Linux
FOREIGN BIND open(String path, int32 flags, int32 mode) RETURNS int32 // open(const char *, int, ...): mode is variadic
// FOREIGN BIND read(int32 fd, LOAD binary[] data, int32 nbyte) RETURNS int32 // ERROR E2163 — C takes size_t
// FOREIGN BIND memset(LOAD int32[] b, int32 c, C.size_t nbytes) // ERROR E2165 — only bytes cross as void *
Rationale. A binding is written by hand, and before the catalog nothing compared it with C. Reading the C declaration once, before the compiler runs, keeps the compiler free of a C frontend and moves the check to the binding's own line.
The surface of the kernel module that every Envzn program may use without declaring a dependency — a catalog that points at where each member is specified.
(h.viii) Rule. SETS_ERRNO(<sentinel>) — a C failure reported through errno. A FOREIGN BIND whose C function signals failure by returning a sentinel value and setting errno says so with SETS_ERRNO(<sentinel>), and its RETURNS list spells the pipe: RETURNS (T value | STATUS status) (E2094 otherwise). After the call, a result equal to the sentinel becomes FAILURE carrying errno as its code and strerror(errno) as its message; any other result is the value. The sentinel is an integer literal (-1, 0) for an integer return, or EMPTY for a pointer return — an UNSAFE.HANDLE or a FOREIGN TYPE handle — whose failure is NULL (fopen, dlopen); EMPTY on any other return is E2094. Where errno lives is the platform's (__error() on Darwin, __errno_location() on glibc); the module's C catalog names it, so no backend spells it.
Example.
FOREIGN BIND open(String path, int32 flags, int32 mode) RETURNS (int32 fd | STATUS status) SETS_ERRNO(-1)
FOREIGN BIND dlopen(String path, int32 mode) RETURNS (UNSAFE.HANDLE lib | STATUS status) SETS_ERRNO(EMPTY)
// FOREIGN BIND getpid() RETURNS (int32 pid | STATUS status) SETS_ERRNO(EMPTY) // ERROR E2094 — an int32 is never NULL
(a) Rule. The standard library is the surface of the kernel — the ENVZN module — that an Envzn program may use without declaring a dependency. Some of its members are specified elsewhere in the type system: String in I.D.vii, the AS/INTO conversion operators' governing principle in I.D.viii, and the array and collection family in I.J; this section catalogues the remainder — the system gateways and the kernel type hierarchy. The precise, current method signatures of these classes live in the kernel source files. Where this section and a kernel .ev file disagree about a signature, the kernel file is the authority.
Example.
printline("no import needed") // ENVZN surface — no dependency declared
String s := "hello" // String — specified in I.D.vii
int32 n := small INTO int64 // AS/INTO conversion — governed by I.D.viii
Rationale. The intent is to fix what surface exists and what shape it has, not to duplicate a signature list that a later kernel change would silently make stale. The kernel .ev file, not this prose, is the tie-breaker on any exact signature.
(b) Rule. File and Path cover filesystem work. A File is constructed from a path and works in either of two modes without the caller choosing between two types: adaptive, where each operation opens, acts and closes, or persistent, where an explicit open holds a handle across many operations until an explicit close. It carries a text surface that reads and writes whole-file String content, a byte surface that is the Readable/Writable contract, positioned reads and writes that act at an offset without disturbing the cursor, and advisory whole-file locking for cooperating processes. It deliberately carries no metadata — whether a path names a directory, its modification time — because that belongs to Path (b.i), and a File and a Path over the same string are two views of one thing rather than a hierarchy. A file operation can always fail for reasons outside the program — a missing file, a permission denied — so its reads and writes report failure through the recoverable-error vocabulary of I.M rather than returning a bare value.
Example.
File f := CREATE File("notes.txt")
IF f->readText() THEN { String contents := $= } // pipe-XOR read (I.M)
ELSE { printlineErr($!) } // $! = failure message
Rationale. External failure is not a defect in the program, so it belongs in the recoverable STATUS/pipe-XOR vocabulary of I.M rather than a PANIC. A caller must handle a missing file inline rather than unwind.
(b.i) Rule. A Path constructed from a path string answers structural questions about it: whether it exists, and whether it names a directory or a file. It derives related paths — the parent, the basename, the stem, the extension, a path with a replaced extension, a joined segment, a resolved absolute form — and lists a directory's contents.
Example.
Path p := CREATE Path("/tmp/data.csv")
IF p->exists() THEN { ... }
String ext := p->extension() // "csv" — no leading dot
String parent := p->parent()
Path joined := p->join("sub")
Rationale. Path answers questions and derives new paths as pure structural operations; the extension is returned dot-free ("csv", not ".csv") so callers compare and rebuild extensions without stripping punctuation.
(b.ii) Rule. Process runs an external program and returns its exit code together with its captured standard output and error. It also answers the running program's own process ID, which is unique among the processes alive at the same moment but reused once a process exits.
Example.
ProcessResult r = Process->run("ls", args)
String tmp := ("$1.$2.tmp")->format(dest, Process->id()) // no two concurrent runs share it
Rationale. Exit code plus captured stdout/stderr is the complete result of running a child process; bundling all three means the caller never re-reads the process's streams separately. The process ID is what keeps two concurrent runs of one program from colliding on a name they both derive — a temporary file beside its destination is the common case.
(c) Rule. Math is a NAMESPACE of numeric functions and constants — a stateless free-function host, not an actor. Its constants and functions are both reached with .: Math.PI, Math.E, Math.sqrt(x), Math.floor(y). The surface covers absolute value and sign across the numeric types. It covers square root, cube root, and the power, exponential, and logarithm family, together with the trigonometric and hyperbolic functions, taking angles in radians. It covers the rounding family of floor, ceiling, round, and truncate; minimum, maximum, and clamp; and radian-to-degree conversion. And it covers the overflow-aware arithmetic forms — wrapping, saturating, and a checked form returning a STATUS — together with the distance function hypot.
Example.
float64 c := Math.PI // constant — reached with '.'
float64 e := Math.E
float64 r := Math.sqrt(2.0) // function — also '.', never Math->sqrt
float64 f := Math.floor(y)
float64 d := Math.hypot(3.0, 4.0) // distance function
float64 m := Math.clamp(v, 0.0, 1.0)
Rationale. Math holds no state and reaches nothing, so it is a NAMESPACE, reached with ., rather than a SINGLETON actor reached with ->. Writing Math->sqrt(x) is the E1106 error of the six reflexes.
(c.i) Rule. A Math function whose mathematical domain a runtime argument can violate — a square root of a negative, a logarithm of a non-positive — panics with MathError. A domain violation the compiler can detect statically is a compile error.
Example.
TRY { float64 r := Math.sqrt(x) } // x from runtime — may panic
RECOVER (MathError e) { printlineErr("domain error") }
Math.sqrt(-1.0) // ERROR — negative literal, domain violation caught statically
Rationale. A domain violation the compiler can prove is a programmer error surfaced early; one that depends on runtime data is a recoverable defect, so it is the catchable MathError (PANIC/RECOVER tier), letting the caller recover close to the failure.
(d) Rule. Type conversion is not a singleton but the AS/INTO operator surface of I.D.viii, under that same principle. A widening conversion is total and lossless (INTO); a narrowing or sign-crossing one is lossy and range-checked (AS); and a parse, which can always fail, is the fallible INTO from a String.
Example.
int64 wide := small INTO int64 // widening — total, lossless
IF big AS int32 THEN { int32 n := $= } // narrowing — fallible, range-checked
IF "42" INTO int32 THEN { int32 v := $= } // parse from String — fallible INTO
ELSE { printlineErr("not a number") }
Rationale. The operator is the guarantee: INTO promises no loss, AS admits loss and forces a range check, and a parse rides the fallible INTO because a String may not name a value. The reader knows the safety of a conversion from the operator alone.
(d.i) Rule. The conversion families the retired Convert singleton once carried are now CONVERSIONS hosts of operators: value-to-String rendering on NumberConverter / FloatConverter / CharConverter, numeric widen/narrow on PrimitiveConversions, char-width crossing on CharWidthConverter, and the String↔ByteBuffer bridge on TextConverter.
Example.
String s := 42 INTO String // rendered via NumberConverter
String t := 3.14 INTO String // via FloatConverter
ByteBuffer bb := s INTO ByteBuffer // String -> ByteBuffer bridge (TextConverter)
Rationale. Grouping each conversion family on a CONVERSIONS host keeps the developer surface a single pair of operators (AS/INTO) while relocating the per-family machinery inward — the cost lives in the host, not on the reader's line.
(d.ii) Rule. The operations that are deliberately not checked conversions remain ordinary NAMESPACE method calls: the bit-exact truncating/reinterpreting casts on NumericUtilities, the HexCodec and Base64Codec codecs, the ByteOrderCodec endian serialization, and the CharClassifier character predicates.
Example.
String hex := HexCodec.toHex(bb) // codec — NAMESPACE call with '.'
IF Base64Codec.fromBase64(s) THEN { ByteBuffer back := $= } // fallible — pipe-XOR
boolean isDigit := CharClassifier.isDigit(c)
Rationale. A bit-exact reinterpret or a hex/base64 round-trip is not a value-preservation question the AS/INTO safety contract speaks to, so those stay plain NAMESPACE calls (.) rather than pretending to be checked conversions.
(d.iii) Rule. System is the SINGLETON CLASS of process-level services — getenv for reading the environment, and exit for terminating with a chosen code; inheriting from System is forbidden, since it is a singleton.
Example.
IF System->getenv("HOME") THEN { String home := $= }
System->exit(0) // message send — '->', not '.'
Rationale. Process-level services are a single shared actor, so System is a SINGLETON reached with ->; a singleton has exactly one instance, which is why subclassing it is rejected.
(d.iv) Rule. The standard-input/standard-output surface is the separate Stdio singleton, and its text-writing methods are the one part of the kernel callable unqualified: print, printline, printErr, printlineErr, formatPrint, and formatPrintline are written bare — printline("ready"), not Stdio->printline("ready") — because printing is frequent enough that the receiver is noise. The rest of the surface is reached through Stdio-> in the ordinary way. print and printline write a String to stdout (printline appending a newline); formatPrint and formatPrintline take a template and arguments under the rules of I.F.vi; printBytes writes a ByteBuffer verbatim; and the printErr family — printErr, printlineErr, formatPrintErr, formatPrintlineErr, printBytesErr — writes the same shapes to stderr. The input side is Stdio->read(length) for raw bytes paired with an end-of-file boolean, and Stdio->readline() for a single line paired with the same boolean.
Example.
print("no newline")
printline("with newline")
formatPrintline("x=$1 y=$2", x, y) // template — rules of I.F.vi
Stdio->printBytes(bb) // ByteBuffer written verbatim
printlineErr("to stderr") // printErr family -> stderr
ByteBuffer chunk, boolean eof := Stdio->read(1024)
String line, boolean eof2 := Stdio->readline()
Rationale. stdin/stdout is a distinct concern from process control, so it is its own Stdio singleton; pairing each read with an end-of-file boolean lets the caller detect stream end without a sentinel value.
(d.v) Rule. Every Stdio output method returns the pipe-XOR shape of I.M.i — int32 written | STATUS status — because a write to a terminal or a redirected stream can fail. Text composition itself is the Formatter class of I.F.vi.
Example.
IF printline("hi") THEN { int32 written := $= } // int32 written | STATUS status
ELSE { printlineErr($!) } // write failed — report on stderr
Rationale. A pipe to a closed terminal or a full disk can reject a write, so an output cannot promise a bare value. The pipe-XOR of I.M.i forces the caller to acknowledge either the byte count or the failure, never to ignore it silently.
(e) Rule. The kernel type hierarchy for failure is rooted at Error, the reserved abstract class of I.M, with the concrete subclasses the kernel itself raises — among them CompileError, EmptyHandleError, FileError, MathError, IndexOutOfBoundsError, and NetworkError. STATUS, with its SUCCESS, PARTIAL_SUCCESS, and FAILURE variants, is the recoverable-failure type.
Example.
TRY { ... }
RECOVER (FileError e) { ... } // concrete subclass of Error
RECOVER (NetworkError e) { ... } // another concrete subclass (base Error is E4016)
STATUS s = FAILURE("bad input") // recoverable — assigned with '='
IF s IS FAILURE { ... }
Rationale. Two separate failure vocabularies (I.M): Error and its subclasses are the handleable-defect (PANIC/RECOVER) tier, while STATUS is the recoverable tier — keeping "external failure I recover from" distinct from "defect I unwind on."
(e.i) Rule. Two interfaces support hashing: Hashable, which a type implements to produce its own hash and so become usable as a Dictionary key or a Set element. And Hasher, the pluggable hashing strategy a Dictionary[K, V, H] or Set[V, H] is parameterized over; the shipped default is DefaultHasher.
Example.
Dictionary[String, int32, DefaultHasher[String]]
m := CREATE ChainedHashDictionary[String, int32, DefaultHasher[String]]() // H stated explicitly
Set[String] seen := CREATE Set[String]()
Rationale. Separating Hashable (a type hashes itself) from Hasher (a strategy the collection is parameterized over) lets one keyed type serve many hashing policies — the DoS-resistant SipHash strategy plugs into the H slot without changing the key type.
(e.ii) Rule. The kernel's interfaces complete the surface: Cloneable, the two iterator interfaces, the four operator interfaces of I.K.iv, Hashable, Readable, Printable, Serializable, Reconstructable, ThreadStarter, and the program-entry trio TaskStarter, TaskStarterWithOptions OF T and TaskStarterOptions (I.N(c.v)). Its enums include DeliveryMode, Severity, Build, Encoding, and Endianness. The Appendix catalogues them in full.
Rationale. This is the full interface/enum roster of the kernel surface; the exhaustive catalogue lives in the Appendix, so this paragraph names the members and defers their detail rather than duplicating the list.
(f) Rule. Several kernel subsystems shipped after the survey above was first written and carry their own surface; rather than restate them, this section names them and fixes what surface exists; their exact signatures are governed by (a). They are: the date-and-time ring — DateTime, TimeDuration, and the TimeComparison enum, with DateTimeFactory as the construction singleton and the ring's own formatting and parsing; MeasuringTimer for elapsed-time measurement; and the Random family — the Random, Shuffler, and Shuffleable interfaces over the Xoshiro256 engine, with the CasualRandom, SeededRandom, and SecureRandom generators and RandomError. Logger, once sketched as a kernel member, is now the standalone Logger module and is no longer part of this surface. Each named here is a shipped V1 member.
Example.
DateTime d := DateTimeFactory->newDateTime(2026, 7, 28, 9, 0, 0) // construction singleton
MeasuringTimer t := CREATE MeasuringTimer()
Random r := CREATE CasualRandom()
Rationale. Naming the subsystems keeps this catalog complete without duplicating a signature list that a later kernel change would silently make stale — the same policy (a) states for the rest of the section.
(g) Rule. BuildInfo is the kernel NAMESPACE through which a program reads its own build provenance at runtime — the data a --version line would print. Its members are reached with ., and the text-valued ones return the byte-array type rather than String: BuildInfo.version() yields the full version line (the MAJOR.MINOR.PATCH+⟨counter⟩ of paragraph (h)), BuildInfo.gitDescribe() the git describe of the build commit, BuildInfo.commit() and BuildInfo.branch() the commit identifier and branch, and BuildInfo.builtAt() the ISO-8601 build timestamp — each a char8[] of UTF-8 bytes. The two non-text members are BuildInfo.isDirty(), a boolean true when the build was taken from a working tree carrying uncommitted changes, and BuildInfo.buildCounter(), the uint64 build counter.
Example.
char8[] v := BuildInfo.version() // "MAJOR.MINOR.PATCH+⟨counter⟩" as UTF-8 bytes
char8[] gd := BuildInfo.gitDescribe()
char8[] br := BuildInfo.branch()
boolean dirty := BuildInfo.isDirty() // uncommitted working tree?
uint64 cnt := BuildInfo.buildCounter()
printline(BuildInfo.version() INTO String) // char8[] -> String bridge (I.D.viii)
Rationale. The byte-array choice is deliberate and structural. The provenance surface is wired into the kernel build ahead of String, so it deals in char8[] and leaves the conversion to text to the caller, through the bridge of I.D.viii. None of these values is authored in source; they are computed at build time and surfaced to the namespace through a compiler-generated header, under the model of paragraph (h).
(h) Rule. Build provenance follows one model across every component — the kernel, the compiler, and each module. A component's version is MAJOR.MINOR.PATCH+⟨build⟩, SemVer 2.0 with build metadata, and it is written, not derived: the manifest states it (the compiler's lives in bin/compiler.version), and a build stamps it exactly as written. Every component starts at 0.0.0. MAJOR moves for a rewrite or a major update, MINOR for additions or changes, and PATCH for a fix; a MINOR bump resets PATCH, and a MAJOR bump resets both. ⟨build⟩ counts every commit that touches the component, in lowercase hexadecimal without padding, and is never reset. A commit that changes a component's source declares its bump, and work spread over several commits takes one bump when it completes. A build's own counter (from EV_BUILD_NUMBER, then GITHUB_RUN_NUMBER, then a local per-checkout count) is recorded beside the version and is never part of it.
Example.
8.1.4+264 // MAJOR.MINOR.PATCH+⟨build⟩, as the manifest states it
// 264 (hex) = commits that have touched the component; a build's counter is reported separately
Rationale. A version a build computes is a version that differs between two machines building the same commit, and one that disagrees with the manifest a reader opens. Writing it whole, in the commit that changes the component, makes the version a statement about the component's history, which is what a reader of it wants, and leaves the per-build facts where they belong, beside it. (a PATCH counted from version control since the nearest v⟨MAJOR⟩.⟨MINOR⟩ tag, and the build counter, so 8.1.4 was stamped 8.1.74+000001.)
(h.i) Rule. A manifest may declare a groups map: named sets of the component's source files that work together, such as the kernel's concurrency or collections families. Provenance then reports each subgroup's and each file's activity — the commits that touched it since the last tag, and the most recent one. A subgroup has no version of its own; the component does.
Rationale. A groups map lets a large component show where its changes landed — the whole kernel, its collections family, or a single file — without a second set of version numbers that nothing would bump.
(h.ii) Rule. The full provenance is written on every successful build to the emitted output: the version, the git describe, the commit, the branch, the dirty flag, the counter, and the build timestamp. It lands as a buildinfo.json beside the artifacts, and as a generated header the kernel build links in to back the BuildInfo surface of paragraph (g). It is never written back into tracked source. (Shipped V1)
Rationale. That boundary is the governing principle. A source tree records what a program is, not the circumstances of any one build of it, so build identity lives on the output side — buildinfo.json and the generated header — where it cannot churn the source.
How a value crosses the boundary between a program and a document. The format-neutral value model, the codec a type asks the compiler to generate with AUTO, the RESTORE hook that seals a reconstructed class, and the DERIVED field that never travels.
(a) Rule. A type takes part in serialization by asking for it: it implements Serializable (it can write itself) and/or Reconstructable (it can be rebuilt), and declares the method with AUTO and an empty body (I.K.vi(d)). The compiler then writes the body: one line per field per direction, using only field access and the typed events of (b). There is no runtime type table and no field-walking loop at run time, and the generated method is an ordinary public method of the type, emitted in the type's own module, so a dependency's type travels like any other. A type that wants a different shape writes the method itself; the façade cannot tell the two apart. Reconstruct is a pull: the type's reconstruct asks a Reconstructor for each key and value in turn. The format's façade is ordinary module code — Json::Codec.serialize(value), and Json::Codec.parse[T](text) for any T IS Reconstructable, Array[E] included whenever E is.
Example.
CLASS Person IMPLEMENTS Serializable, Reconstructable {
String name
int64 age
AUTO METHOD serialize(MUTABLE REFERENCE Serializer s) RETURNS STATUS { }
AUTO MODIFY METHOD reconstruct(MUTABLE REFERENCE Reconstructor source, ParseMode mode) RETURNS STATUS { }
MODIFY METHOD RESTORE() RETURNS STATUS { RETURN (SUCCESS) }
}
IF Json::Codec.serialize(person) THEN { String text := $= } // write
IF Json::Codec.parse[Person](text) THEN { Person p := $= } // read — the same codec, in reverse
Rationale. This is the "relocate the cost inward" tiebreak of I.A applied to the most tedious, most error-prone code a developer writes, with the opt-in made visible. Reflection would move the cost to runtime — a per-object tax, and errors a developer meets only by hitting them. Generating at compile time gives the same one-line surface with none of the cost: the errors are diagnostics at the AUTO declaration, and the codec is ordinary code the memory-safety proof of I.I covers like any other. Asking explicitly, rather than having a codec derived wherever a type is used, means a type's codec is part of its declared surface, written once in its own module rather than once per use site. (serde-explicit-codecs: this rule described a derive-by-use codec with "no opt-in marker", synthesized at each parse site.)
(b) Rule. The value model is format-neutral and lives in the kernel; a format lives in a module. DataValue is the neutral tree: the shape shared by JSON, BSON, CBOR, and a database row. Four interfaces are the contract: a format implements Serializer, a write sink receiving a flat event stream of typed events (putInt64, putFloat64, putString, a key as its UTF-8 bytes, …), and Reconstructor, a source a type pulls from (beginObject, nextField, readString, …) that can also re-emit its whole content into a sink (read(sink)); a type implements Serializable, describing itself to a sink, and Reconstructable, rebuilding itself from a source under a ParseMode (LENIENT or STRICT, (k.i)). nextField names a key by its slot in IDENTITY(T).dataFields (I.K.iii(e)).
Rationale. Putting the value model in the zero-dependency kernel, while keeping the text of JSON in its own module, lets one derived codec serve JSON, a database row, and any later format. The kernel never learns a format.
(c) Rule. A STRUCT is pure data and is reconstructed by direct field injection. A CLASS may carry an invariant or a computed field, so it is reconstructed by injecting the persisted fields and then calling RESTORE — an ordinary MODIFY METHOD RESTORE() RETURNS STATUS, declared by the class itself. RESTORE runs on the freshly-injected, not-yet-sealed instance: it computes the DERIVED fields and validates the type's invariants. It is fallible — a broken invariant arriving from a document is an expected boundary failure, not a defect — so it returns a FAILURE which the synthesized parse propagates into its | STATUS arm, and it never PANICs. A CLASS that declares AUTO reconstruct and no RESTORE is diagnostic E6100, reported at the AUTO declaration.
Example.
CLASS Person {
PRIVATE String name
PRIVATE number age
DERIVED String display // computed, never in the document
MODIFY METHOD RESTORE() RETURNS STATUS { // the reconstruct hook
IF (.age < 0) { RETURN (FAILURE("Person: age must be >= 0")) }
.display := ("$1 ($2)")->format(.name, .age)
RETURN (SUCCESS)
}
}
Rationale. The STRUCT/CLASS distinction already means data versus data and behavior, and reconstruction is exactly where that distinction earns its keep: a record can be poured, an object must be sealed. Making RESTORE mandatory for a reconstructed class is the point rather than a burden: "this type crosses a deserialization boundary" becomes a contract the compiler enforces. And because RESTORE is an ordinary method, INIT calls the same one — so validation cannot be written twice, or forgotten once.
(d) Rule. A DERIVED field is a computed field — a memoized hash, a name assembled from two others — and it is the one place a field-level annotation is unavoidable. It is used symmetrically: skipped on serialize, and computed by RESTORE on reconstruct. It is writable during the injection-and-RESTORE window and frozen after. DERIVED on a STRUCT field, or on a CLASS that declares no RESTORE, is diagnostic E6106 — in either case there is nothing to compute it.
Rationale. A computed field is not data; round-tripping it would persist a value the type can always rebuild, and a stale one would then override the truth on the way back in. Marking it once, and having the one hook that computes it also be the one hook that validates, keeps the two halves from drifting apart.
(e) Rule. Reconstruct is post-order: a nested object field is rebuilt by calling the child's own reconstruct in place, so a nested value is RESTOREd — and therefore valid — before its owner's RESTORE runs. A field whose type cannot be serialized is diagnostic E6101, reported at the AUTO declaration and naming the offending field; every such field is reported, not only the first. The codes of (f)–(h) are reported there the same way.
Rationale. Post-order is what makes the hook's contract honest: when a type validates its invariants, everything it owns has already validated its own.
(f) Rule. Two shapes are deferred in V1 and are diagnosed rather than half-supported. A nested field of interface or abstract type is open polymorphism, which needs a discriminator and a runtime registry (E6102). A REFERENCE field is a back-pointer into an object graph, and a hook cannot repair a graph it cannot see (E6104). (The third shape, a parse[T] whose T is declared in a dependency, was a diagnosed refusal. It is retired, and its code with it: a type's codec is generated in its own module as public methods, so a dependency's type parses like any other.)
Rationale. Each of these is a real capability with a real design behind it, and each is a diagnostic rather than a silent miscompile. Per I.A(g), a shipped feature is world-class or it is diagnosed, and a limitation met only by colliding with it is a defect.
(g) Rule. A Dictionary becomes a document object, so its key type must have a canonical, lossless, reversible text form: String, the integer types, char8/char32, a plain ENUM (by case name), and boolean qualify. A float, a float-valued number, and any composite key do not, and are diagnostic E6103. The hasher and the comparator are type-level properties and are never serialized — reconstruct re-hashes with the target type's declared hasher, which is statically known because parse[Dictionary[String, Person, DefaultHasher[String]]] names it.
Rationale. Document keys are text; a key whose text form is not reversible cannot survive the round trip, and a float's is not. Re-applying the hasher rather than round-tripping it removes the whole class of "wrong hasher" bug by construction — the data never gets a say in it.
(h) Rule. The one collection whose codec is synthesized in V1 is Array[E] — a document array, its element serialized by the same rules as any other reachable value, so an Array of nested objects reconstructs each element through its own codec. Every other collection-typed reachable field is diagnostic E6107: Set, Queue, Stack, Deque, LinkedList, SortedList, a native T[], an Array of Array, and — for now — Dictionary. The key rule of I.P.g states what a Dictionary key must satisfy when Dictionary synthesis lands; until it does, a Dictionary-typed field is E6107 like the rest.
Rationale. Array is the shape a document array actually has, and it is the one that carries its own growth — the others each need a decision the codec cannot make for itself. Dictionary is the sharpest case: it is an interface over several concrete implementations, so "reconstruct a Dictionary" has no answer until the type carries enough identity for the codec to know which one to build. That is a language question, not a codec question, and a diagnostic is the honest place to leave it (I.A.g — a shipped feature is world-class or it is diagnosed).
(i) Rule. A document has four scalar shapes — string, number, boolean, null — and Envzn has more scalar-ish types than that. A type without a native document shape therefore travels encoded: its wire form is one of the four, and the codec applies a total, reversible encode on serialize and a fallible decode on reconstruct. A ByteBuffer is a base64 string; a decimal128 is its canonical decimal text; a DateTime is an RFC-3339 string; a TimeDuration is an ISO-8601 duration; a char8 is a number, a char32 a one-code-point string. The encode never fails, since every value of the type has a text form. The decode is fallible: a malformed base64 string, a non-canonical decimal, or a bad date is a decode FAILURE, and that failure propagates out of parse exactly as a RESTORE failure does. A value never round-trips to something silently wrong.
Rationale. The document formats Envzn targets are text, and text has only a handful of primitive shapes; the language's richer scalars have to be carried inside those shapes without loss. Making the encode total keeps serialize infallible: a value can always be written. Making the decode fallible keeps reconstruct honest — the document is untrusted input, and a shape that does not parse is a boundary failure rather than a corrupt value. This is the same relocate-the-cost-inward move as the rest of I.P: the developer writes a ByteBuffer field and the compiler carries the base64 both ways.
(j) Rule. A plain ENUM does not travel as a single scalar, because either half of a case's identity can drift independently: a case can be renamed (its name changes) or renumbered/reordered (its ordinal changes, and ordinals are dev-assignable and optional). So an enum serializes as a two-field object carrying both — {"name": <case name>, "value": <ordinal>}. Reconstruct resolves name-first-then-value: the name is looked up against the enum's case table, and only if it names no live case is the ordinal tried; a pair that matches on neither is a decode FAILURE. A document therefore survives a case rename (it recovers by value) or a reorder (it recovers by name). The per-enum case table is compile-time data the compiler emits: the IDENTITY(Enum).cases reflection model (I.K.iii.e). The generic name↔value logic lives once in the kernel EnumReflection namespace, as name, valueForName, and checkValue. The codec emits only the per-enum data and calls that shared logic, never a lookup of its own.
Rationale. A case's name and its ordinal are two independent names for the same thing, and a long-lived document outlives both — a rename here, a renumber there. Persisting only one loses to the other's drift; persisting the pair, and preferring the human-meaningful name, keeps the common edit (reordering cases) lossless while still recovering from a rename. Capturing both is exactly why the enum is an object and not an encoded scalar like (i): neither half alone is a stable key. This mirrors how a complex or a GROUP case travels — a small object whose parts reconstruct together — so the enum's pair reuses the same object-cell machinery those cells do.
(k.i) Rule. The reconstruct façade has two entry points that differ only in how they treat a document that does not exactly match the type. Codec.parse[T] is lenient: a key the type does not declare is skipped, a declared key the document omits is left at its compiler-default (and RESTORE then validates), and only a type mismatch on a present key is a hard FAILURE. Codec.parseStrict[T] is strict — serde's deny_unknown_fields plus required-field checking — so an unknown key or a missing declared key is itself a FAILURE. Strictness applies to the whole reconstructed tree: a nested object, an array element, and a GROUP member are held to the same rule as the root. A DERIVED field never travels, so it is never counted "missing". Both entry points return the clean (T | STATUS) shape — there is no second success slot and no drift-report object.
Rationale. Two documents can disagree with a type in two directions — carrying more than the type expects, or less — and which of those is an error is a policy the caller owns, not the codec. Lenient is the forgiving default that tolerates a producer that added a field or a consumer that dropped one; strict is the contract-enforcing mode for a closed schema. Keeping both on the same (T | STATUS) return keeps the surface one obvious shape, and pushing the flag down the whole tree makes "strict" mean the same thing at every depth rather than only at the root.
Envzn compiles through its own intermediate representation, the EvIR: a fully-analyzed program is built into typed EvIR nodes, and those nodes are lowered to C++20. This article specifies the EvIR in fourteen logical groups, one per Section, stating what each group's nodes are and the essence of how they lower. It is deliberately not exhaustive. The complete node inventory, every traced C++ mapping, and the lowering model live in the companion ENVZN_IR_SPEC.md, generated from the compiler's own spec-trace and held in sync with this constitution.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
(a) The compilation pipeline tokenizes and parses source into an abstract syntax tree, analyzes it, builds the analyzed tree into EvIR, lowers the EvIR to C++20, and invokes clang++. The lowering model the per-node mappings sit inside is recorded in ENVZN_IR_SPEC.md Section C: the pipeline in full, the ownership-handle representation, concurrency, the foreign-function boundary, the generated entry point, diagnostics, and kernel-build notes. The Sections below specify the node groups themselves; each names the spec parts (A.⟨n⟩ for the node set, B.⟨n⟩ for the lowering) that catalogue it in full. Where this article and the generated specification disagree, the specification — anchored to the compiler's own trace — is the authority on lowering, exactly as Article I is the authority on language semantics.
The leaf value nodes — the constants a program writes directly.
(a) Each literal node carries its resolved type and lowers to the matching C++ literal or kernel value. An integer, float, boolean, or char literal takes its C++ form, a char literal becoming a UTF-32 literal; a string literal becomes an interned immutable String; an array literal becomes an EvArray initialization; and a STATUS literal becomes an _EvStatus. The two absence leaves carry no payload — one stands for an unoccupied class-typed slot, the other for an empty pipe slot. The full node list and every traced lowering are in ENVZN_IR_SPEC.md A.i / B.i.
The nodes that name an existing value rather than compute a new one.
(a) A reference node names a place: a local or parameter read, the receiver SELF, a data-field read through ., or an indexed element coll[i]. Each lowers according to the place's form: an owning handle, a borrow (a raw pointer), or a value-array slot. The same surface syntax therefore compiles to different C++ depending on the binding it resolves to. See ENVZN_IR_SPEC.md A.ii / B.ii.
Computation over values, and the explicit conversions between types.
(a) The arithmetic, comparison, bitwise, and shift operators lower to their C++ equivalents. A derived operator — one a type gained by implementing an operator interface (I.K.iv) — lowers to a call of the interface method it was derived from. The AS / INTO conversions lower through the per-type CONVERSIONS host, a C++ namespace of free-function operators, and an opaque wrap/unwrap lowers to a call of its instance of Opaque's generic wrap[T] / unwrap[T] (I.D.v), an ordinary call in both backends. Conversions are always explicit and checked; there is no implicit cast. See ENVZN_IR_SPEC.md A.iii / B.iii.
The nodes that invoke behaviour or build instances.
(a) A call node is overload-resolved before lowering, so it already names its concrete target — a self-call lowers to a bare member call, a static call to Owner::m(...). A CREATE lowers to a heap allocation through _ev_unique<T> followed by the matching INIT constructor, with SUPER(...) emitted in the constructor's initializer list. A lambda lowers to a C++ callable under the non-escaping capture rules of I.F.v. See ENVZN_IR_SPEC.md A.iv / B.iv.
(b) The IDENTITY(subject) intrinsic (I.K.iii(e)) lowers to an IrStaticValue: a value built once and read by reference. Its value is a synthesized construction of the kernel STRUCT Identity, an IrCreate whose arguments are compile-time literals the analyzer has already computed from the subject's static type and binding (String, bool and int literals, a String[] literal for the ancestor lenses, and nested IdentityField, IdentityMethod and IdentityParameter constructions for the member lists). Its key is derived from those facts alone, so equal values share one instance wherever they are written. The expression is a read-only borrow of that instance: := from it copies. In C++ the instance is a function-local static inside an inline accessor, merged by the linker; under LLVM it is a linkonce_odr constant. Because the analyzer has proven the subject legal and the field values are fixed, the emit phase only builds it and never decides anything. (A non-empty String[] literal is an array of move-only owning handles that cannot form a C++ initializer_list, so it lowers through the _ev_object_array_of(...) factory rather than a brace-init; see ENVZN_IR_SPEC.md.)
(c) Every method, INIT and call names its target by one symbol, stamped by the compiler on the definition and on every call that resolves to it, carried into .headers for the modules that call across, and emitted verbatim by a backend that has no overloading of its own. A developer never writes it; it is the name a linker, a debugger or a backtrace shows, so it is built to be read:
symbol := type-symbol "." member "(" params ")" "->" "(" returns ")"
params := "void" | param { "," param }
param := [ mark ] typearg (* bare = the parameter owns its argument *)
mark := "&" (* REFERENCE *)
| "*" (* MUTABLE REFERENCE *)
| "~" (* WEAK REFERENCE *)
| "^" (* SHARED MUTABLE REFERENCE *)
returns := "void" | typearg { "," typearg } [ "|STATUS" ] (* a STATUS in the final slot of a multi-slot return *)
member := ident | "_" ident (* "_" = compiler-synthesized: _init, _drop *)
ENVZN:StringView.contains(&ENVZN:EvArray[char32])->(boolean)
ENVZN:StringView.contains(&ENVZN:EvArray[char32],boolean)->(boolean)
ENVZN:Error._init(&ENVZN:String)->(void)
app:Counter.reset(void)->(void)
app:Main.take(ENVZN:String)->(int64)
app:Main.take(&ENVZN:String)->(int64)
ENVZN:Dictionary[ENVZN:String,int32,ENVZN:SIPHasher].remove(ENVZN:String)->(ENVZN:String,int32|STATUS)
The type-symbol and every typearg are the type symbols of the template-monomorphization design (§9): a declared type is qualified by its module (ENVZN:String), a primitive is bare, a native array is named as the NativeArray / NativeNdArray instance it is (ENVZN:NativeArray[char32]), and an instantiation's owner is its own symbol, whose module is the template's home. The whole signature is in the name — every parameter's mode and type, and every return slot, |STATUS marking the failure alternative of a pipe return — and void stands for an empty list, so every symbol has both lists. The symbol names the class that defines the method: a call through a subclass to an inherited method carries its ancestor's symbol, and an override carries its own. A call on an array is a call of NativeArray[T]'s or NativeNdArray[T]'s own method and carries that method's symbol: the instance's in a concrete body (ENVZN:NativeArray[binary].clear(void)->(void)), the template's in a generic one (ENVZN:NativeArray.swap(int64,int64)->(void)), so no call is a hidden intrinsic. A call through a type parameter (a->isLessThan(b) with a a T) carries no symbol: no class defines it until an instance does, and the instance's own call carries that one. That has three consequences, each intended. Overloads, including two that differ only in a parameter's mode (I.E.g), never share a symbol. Adding an overload never renames an existing one, so a module compiled against the old set still links. And changing a method's parameters or its return type changes its symbol, so every caller compiled against the old function fails to link until it is rebuilt against the new one, rather than calling it with the wrong shape.
The nodes that introduce or update storage.
(a) A binding carries its operator, and the operator decides the lowering: = to a value copy or direct initialization, := to a C++ move of the handle, and =@ to taking the address of a place expression. An assignment to an existing local, field, indexed element, or reference lowers to the corresponding C++ store, applying a clone or move where the form requires it. See ENVZN_IR_SPEC.md A.v / B.v.
The structured-control nodes.
(a) Blocks, conditionals, and loops lower to their C++ structured-control equivalents. A MATCH lowers by subject: a switch or std::variant visitation for an enum or group, a presence test for a possibly-EMPTY value, an if/else if chain for a condition-form match. FOR IN lowers by iterable: a class collection or user Iterator OF T drives an owned iterator through hasNext() / next(), while a raw array (T[], T[N], T[N+]) is driven by INDEX over the array buffer, binding the loop variable to a borrow pointer into that buffer — a value array's by-value next() cannot hand back the stable pointer the lowered body dereferences. A compile-time WHEN ... IMPLEMENTS block lowers to an if constexpr. See ENVZN_IR_SPEC.md A.vi / B.vi.
How a method hands values back, and how an expression runs for its effect.
(a) A single-value return lowers to a C++ return, applying any required clone or move as the value leaves the callee. A comma-shaped multi-return and a pipe-XOR return both lower to a std::tuple of the slots, the pipe-XOR shape carrying a trailing _EvStatus. An expression statement lowers to its expression evaluated for effect. See ENVZN_IR_SPEC.md A.vii / B.vii.
The STATUS / pipe-XOR machinery and the presence tests.
(a) A pipe-XOR call consumed by an IF or WHILE lowers to a test of the result tuple's trailing _EvStatus, with the $=, $=[i], $!, and $# slot reads lowering to std::get accesses of that temporary. The presence tests lower to ordinary checks — IS VALID to a non-empty handle test, and IS SUCCESS / IS FAILURE / IS PARTIAL_SUCCESS to an _EvStatus outcome test. See ENVZN_IR_SPEC.md A.viii / B.viii.
The PANIC / RECOVER path and the assertion family, distinct from recoverable failure.
(a) A PANIC lowers to a C++ throw of an Error subclass and a TRY to a try whose RECOVER arms become catch blocks and whose FINALLY runs on every exit path. An ASSERT lowers to a guarded halt — an abort() on failure — which a production build may elide. See ENVZN_IR_SPEC.md A.ix / B.ix.
The structured-concurrency nodes.
(a) A CONCURRENT scope lowers to an _ev_task_scope RAII object that joins before it unwinds. A PARALLEL block lowers to a task launched on a std::thread registered with that scope, and a SYNCHRONIZED(lock) block to an _ev_lock_guard released on every exit path. The EvIR states that release itself rather than leaving it to the guard: the block names its target's acquire() and release(), and an IrSynchRelease naming the block stands at its end, before each exit that leaves it, and in every cleanup pad raised inside it, so a backend without destructors places nothing. The channel, broker, mutex, future, atomic, and worker-pool primitives lower onto the kernel's concurrency runtime. See ENVZN_IR_SPEC.md A.x / B.x and the concurrency model of I.L.
The declaration nodes that give a module its shape.
(a) A class lowers to a C++ class: fields to members, methods to member functions, the MODIFY/read-only distinction to the C++ const qualifier, INIT and CLEANUP to constructor and destructor, and FINAL to the final specifier. An interface lowers to an abstract class of pure-virtual signatures, a struct to a public-field record, a group to a std::variant, and an enum to a C++ enum class. See ENVZN_IR_SPEC.md A.xi / B.xi.
The typed foreign-function boundary and the UNSAFE gate.
(a) A FOREIGN BIND lowers to a direct call of the bare C symbol with no wrapper, the SETS_ERRNO and owned-return markers adding a thin translation. The call is parenthesised, (::name)(args), so that a C function-like macro of the same name cannot intercept it and the call reaches the function. A FOREIGN BIND CONSTANT lowers to a link-time macro-shim symbol, and a FOREIGN_TYPE BIND to a void* newtype for the opaque form or a ⟨cpp-type⟩ * for the concrete form. An inline FOREIGN { } block never reaches lowering — it is rejected in the analyzer as E3041 (I.N(h.ii)); an UNSAFE { } block lowers to a plain C++ scope gating raw-handle access. See ENVZN_IR_SPEC.md A.xii / B.xii and the boundary tables of C.vi.
The debug-only capture nodes.
(a) SNAPSHOT and STACKTRACE lower to debug-build capture calls and are elided otherwise; neither changes the meaning of the program it observes. See ENVZN_IR_SPEC.md A.xiii / B.xiii.
The type representation every node carries, and the scope-exit destruction marker.
(a) ResolvedType is the resolved type the analyzer gives each node: a primitive, class handle, value-array, or collection. It drives every lowering decision, from the C++ type a binding emits to the owning-handle shape (_ev_unique<T> versus _ev_shared<T>) a class field takes. The scope-exit drop marker records where an owned value's life ends; the C++ destructor emits the actual release. See ENVZN_IR_SPEC.md A.xiv / B.xiv and the ownership-handle model of C.ii.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This article gives the concrete grammar of Envzn in EBNF. It is a consolidation of the rules stated in prose across Article I, not a new authority. Where a production here and the normative prose of Article I disagree, Article I wins, and this article is the bug to fix. The productions are grounded section by section, and each group cites the section it formalizes: lexical forms in I.C, types in I.D (array forms in I.J), declarations in I.E, expressions in I.F, control flow in I.H.
Coverage. The grammar is now complete across all three tranches. Tranche 1: the lexical grammar, module/declaration skeletons, binding/assignment forms, and control flow (with the I.H.i condition sub-grammar). Tranche 2: the type grammar of I.D (III.3) and the expression grammar of I.F (III.5). Tranche 3: the MATCH pattern language and the WHEN / TRY / PANIC statement forms (III.4), and the class, interface, struct, enum, group, namespace, method, and conversion-host declarations of I.K / I.M.ii / I.D.viii (III.6). One production remains deliberately informal and is flagged inline where it occurs: the platform arm of conditional compilation (I.H.vi). Everything else is fully derivable.
The metasyntax is EBNF with the following conventions.
rule = definition ; (* a production; terminated by ; *)
a | b (* alternation: a or b *)
[ a ] (* optional: zero or one a *)
{ a } (* repetition: zero or more a *)
( a b ) (* grouping *)
"IF" (* a terminal — a literal keyword or symbol *)
'a' (* a terminal character *)
? description ? (* a terminal defined informally in prose *)
(* ... *) (* a comment, not part of the grammar *)
lower_case (* a non-terminal *)
Uppercase quoted terminals ("IF", "THEN") are reserved keywords; the full keyword set is the Reserved Identifiers Catalog above. Two lexical terminals recur and are named once here: NEWLINE is one or more line terminators, and INDENT/whitespace between tokens is insignificant except that NEWLINE terminates a statement (III.1).
(* — comments (I.C.b): removed before parsing, may appear wherever whitespace may *)
line_comment = "//" , { ? any character except a line terminator ? } ;
block_comment = "/*" , { ? any character, including line terminators ? } , "*/" ;
doc_comment = "///" , [ " " ] , { ? any character except a line terminator ? } ;
(* — statement termination (I.C.c): the newline IS the terminator; no semicolon,
save the single C-style FOR header of III.4 *)
statement_end = NEWLINE ; (* a NEWLINE terminates only at bracket depth 0 — inside an
unclosed "(" or "[" it is insignificant whitespace; block
braces never suppress (I.C.c) *)
(* — identifiers (I.C.d) *)
letter = 'A'..'Z' | 'a'..'z' ;
digit = '0'..'9' ;
identifier = letter , { letter | digit | "_" } ; (* no leading "_"; not a keyword *)
(* — numeric literals (I.C.e): three bases, underscores between digits only *)
digit_sep = "_" ;
dec_digits = digit , { [ digit_sep ] , digit } ;
hex_digit = digit | 'a'..'f' | 'A'..'F' ;
hex_digits = hex_digit , { [ digit_sep ] , hex_digit } ;
bin_digits = ( "0" | "1" ) , { [ digit_sep ] , ( "0" | "1" ) } ;
int_literal = dec_digits | ( "0x" , hex_digits ) | ( "0b" , bin_digits ) ;
float_literal = dec_digits , "." , dec_digits , [ exponent ]
| dec_digits , exponent ;
exponent = ( "e" | "E" ) , [ "+" | "-" ] , dec_digits ;
(* — imaginary term (I.C.f): a coefficient juxtaposed with the constant "im" *)
imaginary = ( int_literal | float_literal | identifier ) , "im" ;
numeric_literal = int_literal | float_literal | imaginary ;
(* — character and string literals (I.C.g) *)
escape = "\\n" | "\\t" | "\\r" | "\\\\" | "\\'" | "\\\"" | "\\0"
| "\\v" | "\\f"
| "\\x" , hex_digit , hex_digit
| "\\u" , 4 * hex_digit
| "\\U" , 8 * hex_digit ;
char_literal = "'" , ( ? one Unicode scalar ? | escape ) , "'" ;
string_literal = '"' , { ? any char except '"' or a line terminator ? | escape } , '"' ;
multiline_str = '/"' , { ? any character, including line terminators ? } , '"/' ;
A module is a directory (I.N); the grammar is per file. One class per .ev file; supporting types are grouped into interfaces.ev, enums.ev, structs.ev (I.A.i.b).
source_file = { NEWLINE } , { alias_decl , { NEWLINE } } ,
{ top_level_decl , { NEWLINE } } ;
alias_decl = "ALIAS" , identifier , ( "::" , identifier | "." , identifier ) ;
(* file-scoped dependency import — ALIAS Mod::Type / ALIAS Ns.func
(Appendix). The FOREIGN /
BIND FFI declaration surface remains outside this grammar for now. *)
top_level_decl = class_decl
| interface_decl
| struct_decl
| enum_decl
| group_decl
| namespace_decl
| conversions_decl (* CONVERSIONS host, I.D.viii *)
| primitive_decl ; (* a kernel PRIMITIVE's backing type, I.D *)
(* ── the type grammar (formalizes I.D; array forms from I.J) ────────── *)
type = core_type , [ array_suffix ] ; (* at most ONE suffix — chained T[N][M] is retired, E2124 *)
core_type = primitive_type
| generic_type
| qualified_name ; (* a CLASS / INTERFACE / STRUCT / ENUM / GROUP type, including
the built-in value types String, ByteBuffer, DynamicString,
DynamicByteBuffer, StringView, ByteBufferView *)
qualified_name = [ identifier , "::" ] , identifier ; (* module-qualified name, I.N *)
primitive_type = signed_int | unsigned_int | float_type
| "boolean" | "binary"
| "char" | "char8" | "char16" | "char32"
| "opaque" | "number" | "complex" | "decimal128" ; (* opaque is BARE in type position;
opaque[T] is call-site only, I.D.v *)
signed_int = "int8" | "int16" | "int32" | "int" | "int64" | "int128" | "i128" ;
unsigned_int = "uint8" | "uint16" | "uint32" | "uint" | "uint64" | "uint128" | "u128" ;
float_type = "float16" | "float32" | "float" | "float64" | "double" ;
(* generic / parametric types — the I.J collections: Array[T], Set[V, H], Queue[T], Box[T], … *)
generic_type = "Dictionary" , "[" , dict_args , "]" (* the map type — two spellings, see NOTE *)
| identifier , "[" , type_arg_list , "]" (* Array[T], Set[V,H], LinkedList[T], … *)
| identifier , "OF" , type ; (* the OF constraint form: Iterator OF T, Hasher OF K (I.J) *)
dict_args = type , ":" , type (* colon sugar: Dictionary[K : V] — I.D.v *)
| type , "," , type , [ "," , type ] ; (* full form: Dictionary[K, V] / [K, V, H] — I.J *)
type_arg_list = type , { "," , type } ;
(* NOTE: Article I shows the map type under TWO spellings — the colon sugar Dictionary[K : V] (I.D.v)
and the comma list Dictionary[K, V, H] (I.J). Both are admitted here and FLAGGED for reconciliation. *)
(* array + dense N-D forms (I.J.i(a–t)) *)
array_suffix = "[" , "]" (* T[] unbounded value- or object-array (I.J.i(a–c)) *)
| "[" , extent , "]" (* T[N] fixed-capacity, no growth (I.J.i(b)) *)
| "[" , extent , "+" , "]" (* T[N+] pre-sized growable (I.J.i(l)) *)
| "[" , nd_spine , "]" (* T[,] T[,,] N-D rank spine (I.J.i(o)) *)
| "[" , extent , { "," , extent } , "]" ; (* T[m,n] runtime / T[3,4] fixed N-D extents (I.J.i(o)) *)
(* AMBIGUITY — `generic_type` vs the N-D extent form of `array_suffix`. Since the N-D element type
may be an OBJECT (I.J.i(p)), `Foo[A,B]` is TOKEN-IDENTICAL under both productions: a parametric
instantiation (type-args A,B) and a rank-2 N-D array of Foo with runtime extents A,B. The grammar
alone cannot separate them; the rule is:
- Any slot that a type-argument list could never hold decides it as N-D IMMEDIATELY:
an EMPTY slot (`Foo[,]`), an integer literal (`Foo[3,4]`), or any other expression (`Foo[n+1,m]`).
- An ALL-IDENTIFIER slot list (`Foo[A,B]`) is decided AFTER name resolution, on the HEAD:
if Foo takes type parameters it is a parametric instantiation; if Foo is a non-generic type
(String, a CLASS, …) it can only be an N-D array, and the identifiers are extents.
This mirrors the single-bracket `T[X]` rule, where X is resolved to a class-scope CONSTANT before
the fixed-array reading is chosen. Extents are VALUES; type-args are TYPES. *)
extent = int_literal | identifier ; (* a literal, a CONSTANT, or a run-time extent expr *)
nd_spine = "," , { "," } ; (* all-empty; one comma per extra axis, rank ≤ 15 *)
(* — a binding: at most ONE new typed variable per assignment line (I.E.c) *)
local_decl = [ handle_qual ] , type , identifier , [ binding_init ] ;
handle_qual = "REFERENCE" | "MUTABLE" , "REFERENCE" ; (* non-owning / mutable-non-owning local binding (I.I) *)
binding_init = assign_op , expression ;
assign_op = "=" | ":=" | "=@" ; (* bind value | own (construct/clone/move) | reference (I.G) *)
(* — a field carries modifiers (I.E); REFERENCE decides ownership (I.D.iv(f), I.I) *)
field_decl = { field_modifier } , type , identifier , [ binding_init ] ;
field_modifier = "REFERENCE" | "MUTABLE" | "PRIVATE" | "PROTECTED"
| "CONSTANT" | "SHARED" | "VOLATILE" | "FINAL" ;
(* — a comma-shape multi-value receive declares the extra names on prior lines (I.E.c) *)
multi_receive = type , multi_slot , { "," , multi_slot } , ":=" , expression ;
multi_slot = identifier | "$?" ; (* $? discards that slot (I.M.i; AMB-021) *)
statement = local_decl
| assignment
| if_stmt
| while_stmt | until_stmt | do_loop
| for_in_stmt | for_coord_stmt | for_range_stmt | for_c_stmt | hotloop_stmt
| repeat_stmt | loop_stmt
| match_stmt
| when_typecheck_stmt | conditional_compile_stmt
| try_stmt | assert_stmt
| postfix_stmt
| jump_stmt
| anon_block | unsafe_stmt | synchronized_stmt | parallel_stmt
| expr_stmt ;
block = "{" , { NEWLINE } ,
[ statement , { statement_end , { NEWLINE } , statement } ,
[ statement_end ] , { NEWLINE } ] , "}" ;
(* "}" may close the final statement without a newline, so the
one-line form IF (c) THEN { one-statement } is legal — but a
one-line block admits EXACTLY ONE statement: two statements
with only a space between them are underivable here and are
the I.C.c two-statements-one-line compile error.
Blocks nest to a maximum depth of fifteen (I.A.i(d)); the
grammar itself is unbounded, so the limit is a static check
the analyzer applies rather than a derivable property. *)
jump_stmt = ( "BREAK" , [ identifier ] ) | ( "CONTINUE" , [ identifier ] )
| return_stmt | panic_stmt ; (* the identifier names a LABEL — I.H.iii(e) *)
anon_block = block ; (* anonymous scoping block — bounds a lifetime (I.G.e; AMB-030) *)
unsafe_stmt = "UNSAFE" , block ; (* I.I.viii *)
synchronized_stmt = "SYNCHRONIZED" , block ; (* I.L *)
parallel_stmt = "PARALLEL" , block ; (* I.L *)
(* ── I.K.iii — WHEN type-check (narrowing; mandatory ELSE, optional DO) ── *)
when_typecheck_stmt
= "WHEN" , expression , type_predicate , [ "DO" ] , block , "ELSE" , block ;
type_predicate = "IS" , [ "NOT" ] , ( type | "PRIMITIVE" ) | "IMPLEMENTS" , type ;
(* a PARAMETRIC type here must be the generic_type form —
`X[args]` or `X OF arg`; a bare parametric qualified_name
is E6092 (checked by the analyzer, which knows the arity) *)
(* ── I.H.vi — conditional compilation (build-time; mandatory ELSE) ── *)
conditional_compile_stmt
= "WHEN" , ( "Build" , "IS" , ( "DEBUG" | "RELEASE" )
| "FEATURE" , string_literal
| platform_test ) , block , "ELSE" , block ;
platform_test = ? a test against the System platform vocabulary (I.H.vi) — FLAGGED, not pinned here ? ;
(* ── I.M.ii — PANIC / TRY / RECOVER / FINALLY ── *)
panic_stmt = "PANIC" , type , "(" , [ arg_list ] , ")" ; (* PANIC ErrorType(args); site fields injected *)
try_stmt = "TRY" , block ,
{ { NEWLINE } , "RECOVER" , "(" , type , identifier , ")" , block } , (* parens required; no `as`; subclass before super *)
[ { NEWLINE } , "FINALLY" , block ] ; (* FINALLY optional; a TRY clause — the only place FINALLY is
valid. RECOVER/FINALLY follow the AMB-009 layout rule of
if_stmt: next line after a multi-line block. *)
(* ── I.M.ii — the assertion family. The message is introduced by `=>`, never by a
comma inside the parens, and it is REQUIRED on both ASSERT forms; the parser
reports `missing_message` when it is absent. The condition must fit on one
source line; only the message may continue onto the next. *)
assert_stmt = ( "ASSERT" | "ASSERT!" ) , "(" , bool_expr , ")" , "=>" , expression
| "UNREACHABLE!" , [ "=>" , expression ] ;
(* ── I.H.i — conditional headers ─────────────────────────────────────
A condition is simple or compound. A simple condition needs EXACTLY ONE
of { surrounding parentheses, trailing marker }; a bare simple condition
with neither is a compile error and is un-derivable below by construction.
A compound condition parenthesizes each clause; its outer parens and its
marker are both optional. The marker is THEN for IF, DO for WHILE/UNTIL. *)
cond_then = simple_cond_then | compound_cond_then ;
simple_cond_then
= "(" , bool_expr , ")" , [ "THEN" ] (* parenthesized: marker optional *)
| bool_expr , "THEN" ; (* marker form: parentheses omitted *)
compound_cond_then
= [ "(" ] , paren_clause ,
{ bool_op , paren_clause } , [ ")" ] , [ "THEN" ] ;
paren_clause = "(" , bool_expr , ")" ;
bool_op = "AND" | "OR" | "XOR" ;
cond_do = ? cond_then with the marker terminal "DO" substituted for "THEN" ? ;
(* ── I.H.ii — the conditional ─────────────────────────────────────── *)
if_stmt = "IF" , cond_then , block ,
{ { NEWLINE } , "ELSE" , "IF" , cond_then , block } ,
[ { NEWLINE } , "ELSE" , block ] ;
(* Continuation-keyword layout: after a
MULTI-line block the ELSE / ELSE IF must start the next line —
cuddled `} ELSE {` there is the I.C.c layout error; only after a
ONE-line block may the continuation share the line. The layout
constraint is enforced as a layout rule, not encoded in EBNF. *)
(* ── I.H.iii — loops ──────────────────────────────────────────────── *)
while_stmt = "WHILE" , cond_do , block ;
until_stmt = "UNTIL" , cond_do , block ; (* readable WHILE NOT *)
do_loop = "DO" , block , { NEWLINE } , ( "WHILE" | "UNTIL" ) , condition_tail ;
(* the tail is MANDATORY, so a next-line WHILE/UNTIL is unambiguous —
it is always this loop's tail, never a new statement (AMB-009). *)
condition_tail = "(" , bool_expr , ")" | bool_expr ; (* post-loop: no marker (I.H.i.a) *)
for_in_stmt = "FOR" , identifier , "IN" , expression , block ; (* FOREACH withdrawn; reserved *)
for_coord_stmt = "FOR" , ( "(" , coord_list , ")" | coord_list ) , "IN" , expression , block ;
(* the N-D coordinate iterator (I.J.i(q.i)); one identifier per
axis — count = rank (E2122); axis 0 runs innermost *)
coord_list = identifier , "," , identifier , { "," , identifier } ;
for_range_stmt = "FOR" , identifier , "=" , expression ,
( "TO" | "UNTIL" ) , expression ,
[ "STEP" , expression ] , block ; (* TO inclusive, UNTIL exclusive *)
for_c_stmt = "FOR" , type , identifier , "=" , expression , ";" ,
bool_expr , ";" , simple_stmt , block ; (* the ONLY semicolons; one line *)
hotloop_stmt = "HOTLOOP" , ( for_range_stmt | for_c_stmt | while_stmt | for_coord_stmt ) ;
(* I.H.iii(f) — bounds-check-HOISTING modifier; must immediately
precede a counted FOR or a WHILE (else E1149). A suggestion:
the analyzer proves the hoist, or the loop keeps its checks
silently; it never skips a check. *)
repeat_stmt = "REPEAT" , [ expression ] , block ;
(* with a count: runs the body that many times. WITHOUT one:
the bare infinite loop, exited by BREAK — I.H.iii(c). *)
(* ── I.H.iii(e) — LABEL, the block/loop naming prefix ──────────────── *)
label_stmt = "LABEL" , identifier , ( loop_stmt | for_in_stmt | for_range_stmt
| for_c_stmt | while_stmt | until_stmt
| do_loop | repeat_stmt | block ) ;
(* the name is unique within the CLASS; its extent is the block
it prefixes. BREAK <name> / CONTINUE <name> target it. *)
(* ── I.H.iii(d) — LOOP, exactly ONE form ──────────────────────────── *)
loop_stmt = "LOOP" , identifier , "IN" , expression ,
"WITH" , "INDEX" , identifier , block ;
(* element binds as REFERENCE (as FOR IN); index is a read-only
zero-based int64. BOTH clauses mandatory — see I.H.iii(d).
The iterator-handle and `LOOP $_ IN` forms are WITHDRAWN. *)
(* ── I.H.v — MATCH (statement; no fallthrough) ────────────────────── *)
match_stmt = "MATCH" , expression , "{" , { NEWLINE } ,
{ when_arm , { NEWLINE } } , [ default_arm , { NEWLINE } ] , "}" ;
when_arm = "WHEN" , when_pattern , ":" , block ;
default_arm = "DEFAULT" , ":" , block ; (* ONLY the compile-time IS/IMPLEMENTS form (I.K.iii.c) *)
when_pattern = "IS" , [ "NOT" ] , ( type | "PRIMITIVE" ) (* type-check arm (I.K.iii.c) *)
| "IMPLEMENTS" , type
| status_pattern (* STATUS variant (I.M.i) *)
| enum_case_pattern (* enum case — bare name, no payload (I.K.viii) *)
| type , identifier ; (* type binding (I.H.v) *)
(* per I.H.v(a.i): EMPTY arm, DEFAULT arm, IF guards,
compare_op / TO-range / literal-list patterns, and the subjectless
(bool_expr) condition role. The subject is now mandatory. *)
status_pattern = "SUCCESS"
| "FAILURE" , "(" , identifier , [ "," , identifier ] , ")" (* binds message[, code] *)
| "PARTIAL_SUCCESS" , "(" , identifier , ")" ;
enum_case_pattern
= [ identifier , "." ] , identifier ; (* NORTH | Direction.NORTH *)
(* A V1 enum case is a BARE NAME. There is no syntax to declare an associated
value on an ENUM case (I.K.viii), so no arm can bind one; STATUS is the only
closed set whose alternatives carry a payload, and status_pattern above is
its dedicated production. *)
(* NOTE: several arms share a surface shape — an identifier may begin a type binding, an
enum case, or an expression — and which arm applies is resolved by the MATCH subject's
type, not by syntax alone. `labeled_slot` is defined with the return shapes in III.6. *)
(* ── I.H.iii(e) — postfix single-statement forms ──────────────────── *)
postfix_stmt = simple_stmt , "FOR" , identifier , "IN" , expression
| simple_stmt , "WHILE" , condition_tail ;
simple_stmt = assignment | expr_stmt ;
Envzn fixes an explicit precedence order only for the arithmetic symbols (I.F.ii). The keyword operators — bitwise, shift, boolean — are written as words precisely to keep them out of a precedence tower, and I.H.i requires each clause of a compound boolean condition to be parenthesized. The tiers below encode the orders I.F.ii states and lean on explicit grouping everywhere I.F.ii declines to fix one; any tier whose relative precedence Article I does not pin down is flagged inline.
(* deepest = highest-binding; `expression` is the loosest form *)
expression = logical_expr ;
logical_expr = convert_expr , { ( "AND" | "OR" | "XOR" ) , convert_expr } ;
(* NOTE: in a condition header, I.H.i additionally requires each
boolean clause to be parenthesized — see the cond grammar in III.4 *)
convert_expr = compare_expr , { ( "AS" | "INTO" ) , type } ; (* x AS int32, userInput INTO int32 (I.D.viii) *)
compare_expr = bitwise_expr , [ compare_op , bitwise_expr ] (* non-associative: at most one comparison *)
| bitwise_expr , presence_test ;
compare_op = "==" | "!=" | ">" | "<" | ">=" | "<="
| "≈" | "≉" (* number-only; same precedence as == (I.F.ii(c)) *)
| "BEQUALS" | "BNEQUALS" ; (* bit-pattern equality (I.F.ii(c)) *)
presence_test = "IS" , [ "NOT" ] , "VALID" (* presence test (I.D.iv/e); the SUBJECT must be a
type with an EMPTY state — not a String/ByteBuffer
(always present, E6068), a REFERENCE (E6041), a
primitive (E6042), a STATUS (E6043), an enum
(E6044) or a STRUCT (E6045) — see I.I.iii *)
| "IS" , ( "SUCCESS" | "FAILURE" | "PARTIAL_SUCCESS" ) ; (* STATUS test (I.M) *)
(* NOTE: Article I does not fix the relative precedence of the keyword bitwise and shift operators and
steers authors to parenthesize (I.F.ii); the two tiers below are a conservative reading — arithmetic
binds tighter than shifts, shifts tighter than the BAND/BOR/BXOR family — and are FLAGGED. *)
bitwise_expr = shift_expr , { ( "BAND" | "BOR" | "BXOR" ) , shift_expr } ;
shift_expr = additive_expr ,
{ ( "LSHIFT" | "RSHIFT" | "ASHIFT" | "LROTATE" | "RROTATE" ) , additive_expr } ;
additive_expr = mult_expr , { ( "+" | "-" | "&+" | "&-" | "|+|" | "|-|" ) , mult_expr } ;
(* &+ &- wrapping (I.F.ii(a.iv)); |+| |-| set union / difference (I.J.ii(c.i)) *)
mult_expr = unary_expr , { ( "*" | "/" | "~/" | "%" | "#" | "&*" | "|&|" ) , unary_expr } ;
(* # = hash-combine (I.F.ii(a)); &* wrapping (I.F.ii(a.iv)); |&| set intersection (I.J.ii(c.i)) *)
unary_expr = ( "NOT" | "BNOT" | "-" | "#" | "++" | "--" ) , unary_expr (* prefix (I.F.ii(a,b)); "#" is the hash word (I.F.ii(a)) *)
| power_expr ;
power_expr = postfix_expr , [ "^" , unary_expr ] ;
(* ^ left operand is postfix-only, so a prefix minus is never captured
under it: -2 ^ 2 derives as -(2 ^ 2), per I.F.ii(a). The right
operand admits unary (2 ^ -1 parses) and re-enters unary→power,
keeping ^ right-associative. (Corrected — the earlier
power_expr = unary_expr ["^" power_expr] derived (-2)^2, contradicting
I.F.ii(a); found by the GOLDEN clean-room probe, AMB-012.) *)
postfix_expr = primary , { postfix_op } ;
postfix_op = "." , identifier (* field / NAMESPACE member (I.F.i) *)
| "." , identifier , [ "[" , type_arg_list , "]" ] ,
"(" , [ arg_list ] , ")" (* NAMESPACE method call, optional call-site type args (I.K.vi.f.i) *)
| "->" , identifier , [ "[" , type_arg_list , "]" ] ,
"(" , [ arg_list ] , ")" (* method call, optional call-site type args (I.F.iv, I.K.vi) *)
| "[" , expression , { "," , expression } , "]" (* index; multi-coordinate for an N-D array (I.J) *)
| "!" (* factorial — binds tighter than ^ (I.F.ii(a)) *)
| "++" | "--" ; (* postfix increment / decrement (I.F.ii(b)) *)
primary = literal
| "SELF" | "SUPER"
| "." , identifier (* implicit-SELF field read, .field (I.G.d) *)
| dollar_token
| construct_expr
| identity_expr
| opaque_static
| format_call
| lambda_expr
| identifier
| "(" , expression , ")" ;
literal = numeric_literal | char_literal | string_literal | multiline_str
| "TRUE" | "FALSE" | "EMPTY" | array_literal ;
array_literal = "[" , [ expression , { "," , expression } ] , "]" ; (* e.g. [2, 3, 5, 7, 11] (I.J) *)
construct_expr = "CREATE" , [ qualified_name ] , [ "[" , type_arg_list , "]" ] ,
"(" , [ arg_list ] , ")" ; (* class name inferred when concrete, required for interface/abstract (I.F.iii) *)
identity_expr = "IDENTITY" , "(" , identity_subject , ")" ; (* compile-time reflection intrinsic (I.K.iii(e)) *)
identity_subject = qualified_name , [ "[" , type_arg_list , "]" ] (* a type / type-parameter, optionally parameterized *)
| identifier , { "." , identifier } ; (* a value variable or a data-field path *)
opaque_static = "opaque" , "[" , type , "]" , "->" , identifier ,
"(" , [ arg_list ] , ")" ; (* opaque[T]->wrap/unwrap — the two call-site statics (I.D.v) *)
format_call = ( string_literal | multiline_str ) , "->" , "format" ,
"(" , [ arg_list ] , ")" ; (* positional composition over $1..$9 (I.F.vi) *)
arg_list = arg , { "," , arg } ;
arg = expression ; (* $? is NOT an argument — E1136; its legal homes are the
discard-bind and multi-receive slots of III.3/III.5 (I.M.i).
*)
dollar_token = "$=" , [ "[" , int_literal , "]" ] | "$RETURNED" (* success-slot reads (I.M.i) *)
| "$!" | "$ERR_MESSAGE" | "$#" | "$ERR_CODE" ; (* failure-side reads (I.M.i) *)
(* ── lambdas (I.F.v) — four forms; the body decides which ──────────── *)
lambda_expr = "LAMBDA" , lambda_params , ":" , expression (* expression form: LAMBDA x: x + 1 *)
| "LAMBDA" , "(" , [ name_list ] , ")" , block (* block form: parenthesized params + brace body *)
| "LAMBDA" , ":" , block (* no-param colon-block *)
| "LAMBDA" , "(" , ")" ; (* no-param empty form *)
lambda_params = name_list | "(" , name_list , ")" ; (* expression-form params, optionally parenthesized *)
name_list = identifier , { "," , identifier } ;
(* ── lvalues, assignment, returns (the entry points III.3 and III.4 depend on) ── *)
assignment = place , assign_op , expression
| identifier , compound_op , expression (* x += e ≡ x = x + e (I.F.ii(b.i)) *)
| "$?" , ":=" , expression (* explicit whole-return discard (I.M.i) *)
| multi_receive ;
compound_op = "+=" | "-=" | "*=" | "/=" | "%=" ;
place = ( identifier | "SELF" | "." , identifier )
, { place_suffix } ; (* an assignable location — never a method call;
the leading-dot head is implicit-SELF field
access, .field (I.G.d) *)
place_suffix = "." , identifier
| "[" , expression , { "," , expression } , "]" ;
bool_expr = expression ; (* an expression of boolean type; a compound boolean *condition* parenthesizes per I.H.i *)
return_stmt = "RETURN" , [ "(" , expression , { "," , expression } , ")" ] ;
expr_stmt = expression ; (* e.g. a method call evaluated for effect *)
These expand the top_level_decl alternatives named in III.2. A user-defined error type (I.M.ii) is an ordinary class_decl that EXTENDS Error — it needs no production of its own.
(* ── templated types (I.K.ix) — the qualifier sits on the line above the class header ── *)
template_decl = "TEMPLATE" , ":" , "GIVEN" , type_params_spec , ":" ;
type_params_spec = "TYPE" , identifier , "IS" , constraint
| "TYPES" , name_list , ";" ,
param_constraint , { ";" , param_constraint } ;
param_constraint = identifier , "IS" , constraint ;
constraint = alternative , { "," , alternative } ; (* comma reads as OR *)
alternative = atom | "(" , atom , { "AND" , atom } , ")" ; (* the parenthesized form is the only AND *)
atom = ( type | "PRIMITIVE" ) , [ "(" , "EXCEPT" , name_list , ")" ] ; (* EXCEPT only after GROUP / PRIMITIVE *)
(* ── classes (I.K.i–iii, v–vii) ── *)
class_decl = [ template_decl ] , { class_mod } , class_kind , identifier ,
[ class_type_params ] ,
[ "EXTENDS" , type ] ,
[ "IMPLEMENTS" , type , { "," , type } ] ,
"{" , { class_member } , "}" ;
class_kind = [ "HIDDEN" ] ,
( "CLASS" | "ABSTRACT" , "CLASS" | "SINGLETON" , "CLASS"
| "SHARED" , "CLASS" | "VALUE" , "CLASS" ) ;
(* VALUE = the value-semantics kind of I.J; HIDDEN = the
implementation-hiding prefix of I.K (E1130/E1131); which
combinations are legal is semantic, not grammatical.
*)
class_mod = "FINAL" | deprecated ;
class_type_params = "[" , name_list , "]" ; (* [T] / [K, V, H]; the colon form [K: V] is retired *)
deprecated = "DEPRECATED" , [ "(" , string_literal , ")" ] ;
class_member = field_decl (* III.3 *)
| method_decl
| operator_member
| init_decl
| cleanup_decl
| operator_decl (* a conversion hosted on its class (I.D.viii.d) *)
| nested_type ;
primitive_decl = [ template_decl ] , "PRIMITIVE" , identifier , [ class_type_params ] ,
"{" , { class_member } , "}" ; (* a CLASS body; a PRIMITIVE takes no EXTENDS / IMPLEMENTS *)
nested_type = "PRIVATE" , ( enum_decl | struct_decl ) ; (* only a PRIVATE enum / struct may nest (I.K.i) *)
(* ── methods, INIT, CLEANUP (I.K.v–vi) ── *)
method_decl = [ template_decl ] , (* mandatory when type params are declared — I.K.vi.f *)
{ method_mod } , "METHOD" , identifier , [ "[" , name_list , "]" ] ,
"(" , [ param_list ] , ")" , [ return_clause ] , block ;
method_mod = "PRIVATE" | "PROTECTED" | "INTERNAL" (* absent = public — I.K.iii.b *)
| "MODIFY" | "OVERRIDE" | "FINAL" | "AUTO" | deprecated ;
operator_member = [ template_decl ] , { method_mod } , "OPERATOR" , operator_symbol ,
"(" , [ param_list ] , ")" , [ return_clause ] , block ; (* no METHOD: a member the language calls (I.F) *)
operator_symbol = "+" | "-" | "*" | "/" | "~/" | "^" | "<" | ">" | "<=" | ">=" | "[]" | "[]=" ;
init_decl = "INIT" , "(" , [ param_list ] , ")" , block ; (* SUPER(args), if present, is the first statement *)
cleanup_decl = "CLEANUP" , block ;
param_list = param , { "," , param } ;
param = [ param_mod ] , param_type , [ "..." ] , identifier , [ "=" , expression ] ;
param_mod = "REFERENCE" | "MUTABLE" , "REFERENCE" ; (* the three modes of I.I.vi: none = own; MOVE is reserved and is not a mode (I.I.vi(b)); LOAD is a FOREIGN-BIND-only modifier (I.N(h.i)) *)
param_type = type | "LAMBDA" ; (* a lambda-typed parameter (I.F.v) *)
(* ── return shapes (I.K.vi, I.M.i): comma fills every slot; a single trailing `|` is pipe-XOR ── *)
return_clause = "RETURNS" , ( "VOID" | type | return_tuple ) ;
return_tuple = "(" , labeled_slot , { "," , labeled_slot } ,
[ "|" , labeled_slot ] , ")" ; (* the `|` appears at most once and last (I.M.i) *)
labeled_slot = type , identifier ;
(* ── interfaces (I.K.ii, ix.f) ── *)
interface_decl = "INTERFACE" , identifier , [ iface_type_params ] ,
[ "EXTENDS" , iface_ref , { "," , iface_ref } ] ,
"{" , method_sig , { method_sig } , "}" ; (* >= 1 method; an empty interface is an error *)
iface_type_params = "OF" , identifier | "[" , name_list , "]" ; (* single param uses OF; multi uses brackets *)
iface_ref = identifier , [ "OF" , type | "[" , type_arg_list , "]" ] ;
method_sig = "METHOD" , identifier , [ "[" , name_list , "]" ] ,
"(" , [ param_list ] , ")" , [ return_clause ] ; (* signature only, no body *)
(* ── structs, enums, groups, namespaces (I.K.viii, ix.g; I.N) ── *)
struct_decl = "STRUCT" , identifier , "{" , { field_decl } , "}" ;
enum_decl = "ENUM" , identifier , "{" , enum_case , { sep , enum_case } , "}" ;
enum_case = identifier , [ "=" , expression ] (* simple / raw-value *)
| identifier , "(" , labeled_slot , { "," , labeled_slot } , ")" ; (* associated-value *)
group_decl = "GROUP" , identifier , "{" , [ group_member , { sep , group_member } ] , "}" ;
group_member = qualified_name ; (* primitive / class / struct / interface / GROUP;
a parametric class appears as its BARE HEAD,
no type arguments (I.J.v.a) *)
namespace_decl = [ "INTERNAL" ] , "NAMESPACE" , identifier , "{" , (* INTERNAL: module-private, I.N(f) *)
{ method_decl | constant_field | foreign_constant_decl } , "}" ; (* free functions, CONSTANT data, bound C constants (I.K.ii.d) *)
constant_field = { "PRIVATE" | "INTERNAL" } , "CONSTANT" , type , identifier , [ "=" , expression ] ;
(* absent = public — I.E.f *)
foreign_constant_decl = "FOREIGN" , "BIND" , "CONSTANT" , type , identifier ; (* §17; also legal inside namespace_decl *)
sep = "," | NEWLINE ; (* enum / group members: comma or newline *)
(* ── conversion hosts (I.D.viii) ── *)
conversions_decl = "CONVERSIONS" , identifier , "{" , { operator_decl | method_decl | constant_field } , "}" ; (* operators, PRIVATE helpers, CONSTANT data — I.D.viii.d *)
operator_decl = "OPERATOR" , ( "AS" | "INTO" ) ,
"(" , "FROM" , type , identifier , ")" ,
"RETURNS" , ( type | return_tuple ) , block ; (* RETURNS mandatory; also legal as a class member *)
| Group | Section | Status |
|---|---|---|
| Lexical grammar | I.C | specified (III.1) |
| Source file / module skeleton | I.A.i, I.N | specified (III.2) |
| Declarations & bindings | I.E | specified (III.3) |
| Control flow (all forms) | I.H | specified (III.4) |
| Condition sub-grammar | I.H.i | specified (III.4) |
| Type grammar (primitives, generics, arrays, N-D) | I.D, I.J | specified (III.3) |
Expression grammar (operators, calls, lambdas, $-tokens) |
I.F | specified (III.5) |
MATCH pattern language |
I.H.v | specified (III.4) |
WHEN type-check / conditional compilation |
I.K.iii, I.H.vi | specified (III.4) |
| Class / interface / struct / enum / group / namespace | I.K | specified (III.6) |
Methods, INIT, params, RETURNS shapes |
I.K.vi, I.M.i | specified (III.6) |
Error handling — pipe-XOR RETURNS, PANIC/TRY/RECOVER |
I.M | specified (III.4, III.6) |
CONVERSIONS / OPERATOR AS/INTO hosts |
I.D.viii | specified (III.6) |
| Conditional-compilation platform arm | I.H.vi | informal (flagged inline) |
End of the Envzn Language Constitution, Version 2.0.
This document was restructured into the articles described in the opening section: a normative language specification, a lowering reference, a developer guide, and a roadmap. The ?-type-suffix and the optional-type model were swept out in the same pass, leaving the bare-type-with-EMPTY absence model of I.D.iv as the single account of absence. Article I is authoritative where the articles disagree.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This catalog is the single reference for the reserved keywords, the primitive type names, the kernel classes, and the identifiers reserved against a future version. It is a catalog rather than prose by intent — it exists to be scanned. The authority for it is the live compiler: bin/compiler/parse/tokens.py, bin/compiler/primitives.py, the reserved-name set in bin/compiler/module_driver.py, and the kernel source under kernel/. This appendix mirrors that state and adds the V2 and V3 reservations the parser refuses today; any change to the compiler sources named above is reflected here in the same commit.
Sourced from bin/compiler/parse/tokens.py.
CLASS NAMESPACE EXTENDS IMPLEMENTS INTERFACE STRUCT ENUM GROUP METHOD INIT CLEANUP MODULE VERSION INTERNAL ALIAS FOREIGN FOREIGN_TYPE BIND SETS_ERRNO LOAD CALLED_BY_EMITTER UNSAFE TEMPLATE GIVEN. (ALIAS is the file-scoped dependency import — ALIAS Mod::Type; BIND/SETS_ERRNO/CALLED_BY_EMITTER are the FOREIGN BIND FFI surface of I.N.h.)ABSTRACT FINAL OVERRIDE PRIVATE PROTECTED SHARED VOLATILE VALUE HIDDEN REFERENCE MUTABLE MOVE DUPLICATE CONSTANT MODIFY AUTO DERIVED BLITTABLE DEPRECATED. (MOVE is reserved and is not a parameter marker — I.I.vi(b); VALUE marks the value-semantics class kind of I.J; HIDDEN is the implementation-hiding class prefix of I.K; DUPLICATE is the explicit deep-copy value operator, family of MOVE/CREATE; DERIVED marks the computed serialization field of I.P; BLITTABLE is a template-qualifier atom (V1 Part I), reserved so it reads as a qualifier, never a user type name.)RETURNS RETURN VOID LAMBDA OF IS CREATE SELF SUPERIF THEN ELSE WHILE DO FOR LOOP REPEAT UNTIL TO STEP IN BREAK CONTINUE MATCH WHEN DEFAULT WITH INDEX LABEL (FOREACH is reserved-only — see the Reserved-only bullet below)TRY RECOVER FINALLY PANIC ASSERT ASSERT! UNREACHABLE! SNAPSHOT STACKTRACE SUCCESS FAILURE PARTIAL_SUCCESS OK PARTIAL VALID. (PANIC/RECOVER rename THROW/CATCH, ; THROW/CATCH stay reserved only to emit a "renamed" error. ASSERT!/UNREACHABLE! shipped V1; bare UNREACHABLE is likewise reserved, only so the parser can hint "did you mean UNREACHABLE!". Reserved-with-no-semantics: NO_RETURN (V3), FREEZE, POISON, FENCE.)AND OR NOT XOR TRUE FALSE EMPTY. (NONE, the old absence spelling, is reserved and is not a value: writing it — NONE as a value, or IS NONE — is E1164 with the fix (EMPTY, IS NOT VALID). Absence has one spelling, bare-type EMPTY, I.D.iv.)BAND BOR BXOR BNOT LSHIFT RSHIFT ASHIFT LROTATE RROTATEBEQUALS BNEQUALSSYNCHRONIZEDCONVERSIONS OPERATOR AS INTO FROMNO_RETURN (verified-divergence method modifier, V3) · FREEZE POISON FENCE (low-level LLVM vocabulary) · FOREACH (reserved for a possible strided form in V3). These are claimed so no program can bind them as identifiers.$-prefixed tokensThe dollar-prefixed family is small and consequential — each token names a slot the compiler synthesizes for the developer to read, and each is recognized only in a specific syntactic position. The tokenizer treats each as a single token (bin/compiler/tokens.py), not as $ followed by a separate punctuation character; mixing them outside their position is a parse error.
| Token | Purpose | Where it's valid | Spec |
|---|---|---|---|
$= (alias: $RETURNED) |
reads slot 0 of a pipe-XOR call's success tuple — shorthand for $=[0] |
the success (THEN) branch of an IF/WHILE pipe-call only, and only to be bound (I.M.i(c.iii)) |
I.M.i |
$=[i] (alias: $RETURNED[i]) |
reads slot i of the success tuple, where i is a compile-time integer literal |
same as $= |
I.M.i |
$! (alias: $ERR_MESSAGE) |
reads the failure STATUS's message — a String; pairs with $# as the two failure-side accessors |
the failure (ELSE) branch of an IF/WHILE pipe-call only |
I.M.i |
$# (alias: $ERR_CODE) |
reads the failure STATUS's int32 error code (FAILURE("...", code)); paired with $! |
the failure (ELSE) branch of an IF/WHILE pipe-call only |
I.M.i |
$? |
explicit discard of a return value — "I know I'm dropping this and I mean to" | single-return discard $? := call(), or a slot in a multi-value return destructure; never a call argument (E1136) or a parameter name (E1137) |
I.J.i, I.M.i |
$* |
a foreign BIND return marker meaning the returned C string is heap-owned and the compiler must ::free it after copying |
trailing the RETURNS String clause of a FOREIGN BIND declaration |
I.N, ENVZN_IR_SPEC.md C.vi |
$(freer()) |
the named-freer variant of $* — the freer to call instead of ::free |
same as $* |
ENVZN_IR_SPEC.md C.vi |
$_ |
RESERVED, no live form. Was the anonymous loop variable of LOOP $_ IN …; that form was **withdrawn ** with the rest of the old LOOP surface (I.H.iii(d)). The token stays claimed so it is not reused for something else. |
nowhere — the form it belonged to no longer exists | I.H.iii(d) |
Two policy notes. $? and $_ are distinct tokens with distinct meanings — $? discards a return-slot value, $_ is the anonymous loop variable; one does not substitute for the other, and the lexer does not accept either form in the other's position. $_ is WITHDRAWN, not deferred. It was previously described here as "deferred in the tokenizer", which read as a gap waiting to be closed; it is not. The LOOP $_ IN form it belonged to never tokenized and has been withdrawn along with the rest of the old LOOP surface, so there is no deferral left to clear and no examples to reach for. Collection iteration is FOR … IN; iteration that needs the element's position is LOOP … WITH INDEX (I.H.iii(d)). The token itself stays reserved so a future feature does not silently inherit a spelling readers may still associate with loops.
The value-array of I.J.i admits exactly the blittable element types — those whose value can be transferred between storage locations by a flat byte-copy, without aliasing, ownership transfer, or any other lifetime concern. The set is closed under the following rules, applied transitively:
| Rule | Type | Blittable? |
|---|---|---|
| 1 | Any primitive listed above (int*, uint*, float*, boolean, char, binary, and the value-class numeric primitives number / complex) |
yes |
| 2 | Any String-family type (String, DynamicString, ByteBuffer, DynamicByteBuffer) |
no — a String is stored as an owning handle (_ev_unique<String>), so row 5 applies. (it contradicted row 5 and mis-routed a String-bearing STRUCT to the value-array backing, where it could not compile at all.) |
| 3 | A STRUCT whose every field is blittable |
yes |
| 4 | A VALUE CLASS whose every data field is blittable and that declares no EXTENDS — its methods and any IMPLEMENTS do not affect blittability, since a value class's value lives entirely in its stored fields. (A plain heap CLASS is never a value-array element: its instances are owning handles, so a CLASS[] is always the object-array.) |
yes |
| 5 | A handle field, a REFERENCE field, or a field of a parametric type carrying handles |
no |
| 6 | A Box[T], Array[T], Dictionary[K, V, H], or any other heap-with-handles collection |
no |
| 7 | A value-array — T[] or T[N] — as a field of a STRUCT or CLASS whose other fields are blittable |
yes (transitive) |
The blittability of a type is computed once by the analyzer (blittability_diagnostics.py) and cached against the type's symbol; no source-side annotation is required, and the developer never writes "blittable" or any equivalent keyword. A T[] is legal for every element type T (I.J.i (a), (c)): a non-blittable element simply selects the object-array backing rather than the value-array, so there is nothing to reject. (the code stays reserved.)
A blittable type carries no requirement on how its bytes are laid out, beyond what the underlying C++ compiler chooses. The "blit" of "blittable" is the bulk byte transfer, not a guarantee of trivial layout — the four String-family types are blittable because their copy semantics are well-defined deep copies of their internal storage, even though that storage is heap-backed. The value-array's lowering carries the same per-element copy through every slot.
Sourced from bin/compiler/primitives.py.
| Canonical | C++ lowering | Aliases |
|---|---|---|
int8 / int16 / int32 / int64 |
int8_t … int64_t |
i8 / i16 / i32, int, integer / i64 |
uint8 / uint16 / uint32 / uint64 |
uint8_t … uint64_t |
u8 / u16 / u32, uint / u64 |
int128 |
__int128 (compiler built-in; no header) |
i128 |
uint128 |
unsigned __int128 (compiler built-in; no header) |
u128 |
float32 / float64 |
float / double |
f32 / float, double, f64 |
boolean |
bool |
none — the abbreviated bool is not an alias |
char8 / char16 / char32 |
char8_t / char16_t / char32_t |
c8 / c16 / char, character, c32 — char and character alias the code-point width char32 (the three-width family of I.D.i(d)) |
binary |
uint8_t |
none — the sole octet type, distinct from uint8 because an octet is not a number |
decimal128 |
Decimal128 value-class ({ int128 coefficient; int32 exponent }) |
decimal |
opaque |
Opaque (the backing PRIMITIVE, I.D.v) |
none |
C.size_t |
size_t (verbatim) |
none — boundary-only, see I.D.x |
C.ssize_t |
ssize_t (verbatim) |
none — boundary-only, see I.D.x |
C.long |
long (verbatim) |
none — boundary-only, see I.D.x |
C.unsignedLong |
unsigned long (verbatim) |
none — boundary-only, see I.D.x |
C.mode_t |
mode_t (verbatim) |
none — boundary-only, see I.D.x |
The V1 design adds two special value-type primitives — number (an int64-or-float64 tagged value) and complex (a pair of numbers; imaginary unit im) — backed by compiler-known Number / Complex special classes and never instantiated directly (Number.ev/Complex.ev + their conversion hosts). This supersedes the earlier fixed complex_float32 / complex_float64 primitives (and their i literal suffix): the old complex_float* / complex_int* names are retired in favour of the single complex. decimal128 (alias decimal) is also a live V1 primitive (primitives.py state="active"): an IEEE 754-2008 exact base-10 numeric backed by the compiler-known Decimal128 value-class ({ int128 coefficient; int32 exponent }, value = coefficient × 10^exponent), never dev-instantiated. Context-typed literals (decimal128 price = 19.99 — no d suffix), exact + − * / with round-half-even, cohort-preserving so it is Comparable + Hashable (a valid Dictionary/Set key + SortedList element), the RoundingMode rounding-context surface (roundTo, add/subtract/multiply/divide), AS/INTO conversions including the IEEE BID 16-byte wire codec (decimal128 INTO ByteBuffer / ByteBuffer INTO decimal128), and ≈/≉ relative approximate-equality. Reserved against use in V1, each a compile error: the arbitrary-precision bigint and rational; and the sub-byte bit. The wider integers int128 / uint128 are live V1 primitives (primitives.py state="active", lowering to the __int128 / unsigned __int128 built-ins) — see the Primitive types table above. They support + - * / %, comparison, and the keyword bitwise operators; the INTO String operators (on NumberConverter), the String INTO int128 / uint128 parses, and Format render them via hand-rolled 128-bit decimal/base conversion (no libc path). The power operator ^ and the postfix factorial ! are available on the numeric types. Distinct from all of the above are the four C-ABI boundary types — C.size_t, C.ssize_t, C.long, and C.unsignedLong (primitives.py kind="c_abi", state="active") — which lower verbatim to the C spelling they name and exist solely to type a foreign-function boundary. Each is a single reserved word that contains a dot; C is not a namespace and reserves no identifier, so a class or module named C stays legal. They are admissible only inside a FOREIGN/FOREIGN BIND declaration, carry no arithmetic and no ordering, are not members of Numeric, and have no guaranteed width — that absence is their contract, since a fixed-width primitive cannot express a pointer to size_t (size_t is unsigned long where uint64_t is unsigned long long, and which of them matches differs by platform). See Part I.D.x.
ENVZNAuthored as roughly one hundred ten .ev source files; the compiler emits a per-class header for each, alongside a hand-written floor and its native glue. The // AUTO-GENERATED first-line marker, not any fixed count, distinguishes an emitted header from a hand-written one.
Array Dictionary Set Box Stack Queue Deque LinkedList SortedList OwnedListChainedHashDictionary RedBlackTreeDictionary ProHashDictionary — pure-Envzn, behind the Dictionary interfaceArrayIterator DictionaryIterator LinkedListIterator LinkedListNode SetIteratorString DynamicString ByteBuffer DynamicByteBufferSystem Stdio File Path Math Formatter — and Convert (name still reserved)Convert): NumberConverter FloatConverter CharConverter CharWidthConverter PrimitiveConversions TextConverter (AS/INTO hosts); NumericUtilities HexCodec Base64Codec UTFCodec TextEncoding ByteOrderCodec CharClassifier (NAMESPACE method hosts); DateTimeFactory (construction singleton)Hasher OF K (the pluggable strategy interface) with the shipped hashers DefaultHasher, StringHasher, and SipHasherDateTime TimeDuration MeasuringTimer — constructed through DateTimeFactory; the ring's own formatting and parsing (see I.O)CasualRandom SeededRandom SecureRandom Xoshiro256 (engine) RandomErrorError (parent) CompileError EmptyHandleError FileError IndexOutOfBoundsError MathError NetworkErrorCloneable Iterator OF T BidirectionalIterator OF T Hashable Equatable[T] Comparable[T] Arithmetic[T] Multiplier[T] Readable Writable Printable Serializable Reconstructable ThreadStarter TaskStarter TaskStarterWithOptions OF T TaskStarterOptions Shareable Shuffler Random ShuffleableDeliveryMode Severity Build Encoding Endianness TimeComparisonA module manifest's name field may not equal any of: System Stdio Process Math Convert File Path.
entrypoint blockEvery word with a meaning in a manifest's entrypoint block (I.N(c.v)). The compiler holds the same
table in one place, bin/compiler/driver/manifests.py ENTRYPOINT_WORDS, and a test keeps the two
in agreement. Manifest keys are spelled with hyphens between words, never underscores.
| Word | Where | Value | Default | Meaning |
|---|---|---|---|---|
entrypoint |
manifest | string, or object | — | the entry class: a string for a simple program, an object for one with options |
start |
entrypoint object | string | — | the entry class, " |
options |
entrypoint object, command entry | object; a list in a command entry | none | one entry per options field, keyed by its name; in a command entry, the fields that command takes |
after-double-dash |
entrypoint object | string | none | the program that receives the words after -- |
commands |
entrypoint object | object | none | the program's command words, each with its help and the fields it takes |
type |
option entry | string, required | — | the field's declared type, as the source spells it |
help |
option entry, command entry | string | "" | the line --help prints |
alias |
option entry | string, one letter | none | the short name: -n for --name |
required |
option entry | true / false | false | the program does not start without it |
positional |
option entry | true / false | false | the value is a bare word in order, not text after the option's name |
forward |
option entry | string | none | the program this option is also handed to |
command |
option entry | true / false | false | the enum field that receives the chosen command |
Inside the block: start is the only method name "<module>::<Class>::start" accepts; an option's
key is its field's name, and the command line spells it in kebab case (noInline is --no-inline,
snake_case is --snake-case); a . in an option's key joins a struct field to its member
("window.width"); a type is a primitive's name,
String, or an enum's or struct's name as declared. The command line reserves --help and -h,
so no option is named help and no alias is h, and --, which ends the options.
A key of commands is a command word: lower-case letters, digits and -, starting with a letter.
The one option with "command": true is an enum field, and its cases are the command words: each
case drops its leading lower-case prefix, is lower-cased, and turns _ into - (epmBUILD is
build, epmEXTERNAL_DEPS is external-deps). An option no command lists is global; one a command
lists belongs to that command alone. With commands, every positional belongs to a command, and a
String[] field, a positional only, takes the rest of the words and comes last.
Recognized by the parser and rejected with a "not yet implemented" diagnostic, so that V1 code cannot shadow a name a later version needs.
CONCURRENT PARALLEL SYNCHRONIZED; classes Task Channel[T] Future[T] Mutex[T] Broker[T] Subscription[T] WorkerPool + the concrete AtomicX family; injected reference currentTask. Reserved for V2 (not yet live): keywords DETACHED (DETACHED CONCURRENT), ATTACHED / LONG_LIVED / TEMPORARY (pool/scope modifiers); classes UnboundedChannel[T], the parametric Atomic[T] sugar; AUTO SYNCHRONIZED CLASSPipeline[In, Out] ScatterGather ForkJoin Actor[State, Message] Supervisor RateLimiter CircuitBreaker Bulkhead Flow[T]Cursor[T] · Format · Pair · PriorityQueue · LoggerBUTTON CHECKBOX COLUMN DROPDOWN HSTACK IMAGE LABEL LIST SCROLL SEPARATOR SPACER TABLE TEXTFIELD VSTACK WINDOW, and the V2-reserved-only CHART DATEPICKER MENUBAR MODAL PROGRESSBAR SLIDER SPLITVIEW TABS TOOLBARTCPConnection TCPServer WebSocket STREAM GPU_Operation, and the GPU keyword family GPU GPU_ASYNC GPU_RECEIVE GPU_SENDDIRTY SECRET ENCRYPTED — already reserved in the tokenizer (alongside live UNSAFE) so user code cannot bind them; their semantics ship with the Adjectives featurePUBLIC — reserved, and deliberately unrecognized. The token is in bin/compiler/parse/tokens.py, so PUBLIC may not be bound as an identifier, but no declaration parser accepts it: it is absent from the field-modifier set (parse/parser/decl_class.py) and from the method-modifier set (parse/parser/decl_method.py), so writing it is a parse error (E1008 in a class body) rather than the "not yet implemented" diagnostic the rest of this section describes. That is by design, not an omission. Public is the space a declaration occupies by saying nothing (I.K.iii(b)) — a field, CONSTANT, or method carrying none of PRIVATE / INTERNAL / PROTECTED is already public — so a keyword for it would change no program's meaning while putting a modifier on every declaration and burying the ones that restrict. The reservation is kept so the word cannot be bound to something else, and so a later version keeps the option of giving it a meaning that is not merely the default spelled out. Until then this Constitution writes public visibility as the absence of a modifier and shows PUBLIC in no example.Recognized by the parser and rejected with a diagnostic that names the replacement, so that pre-redesign code surfaces its migration site clearly.
ThreadSwitchboard (→ Broker[T]), Thread as user-facing class (→ CONCURRENT { … } block + Task runtime reference), ThreadInbox (→ Channel[T] + scope-bound subscription)->send_message(value, mode) (→ Channel.send / Broker.publish), ThreadSwitchboard->register (→ Broker.subscribe inside a CONCURRENT scope), currentThread (→ currentTask)DeliveryMode and its cases POINT_TO_POINT / BROADCAST (→ Channel is point-to-point by type; Broker is broadcast by type)WAIT block against a registered channel (→ Channel iteration or Broker.subscribe block)The ~/ floor-division operator is implemented. TAINTED and Sanitiser[T] were **dropped ** (Part C is now the Adjectives feature); the Part C identifiers queued for V1 are ADJECTIVES, CARRIES, MARK, CLEAR, not yet in the tokenizer.
━━━━
(b) Rule. Every WHEN arm names one alternative of the subject's closed set and binds what that alternative carries, for that arm only. A MATCH whose arms do not cover every alternative — an uncovered GROUP member, ENUM case, or STATUS kind — is a warning: for a GROUP the alternatives are its written members, which is also its transitive set, because only a group whose members all have one concrete representation can type a value at all (I.J.v(a.i)) — the set is closed, so a gap is usually an oversight, but leaving one deliberately unhandled is a legitimate choice the compiler flags rather than refuses. A possibly-EMPTY subject is not matched at all — absence is IS VALID per I.D.iv, and dereferencing an unproven value is E2080 wherever it occurs.
Example.
MATCH shape { // GROUP Shape { Circle, Square, Triangle }
WHEN Circle c: { ... }
WHEN Square s: { ... }
} // WARNING — Triangle uncovered
MATCH direction { // ENUM Direction { NORTH, SOUTH, EAST, WEST }
WHEN NORTH: { ... }
WHEN SOUTH: { ... }
} // WARNING — EAST, WEST uncovered
Rationale. The binding arm is the reason the construct exists: it yields a value — narrowed instance, associated payload, status message — that the analyzer can then trust. Coverage over any closed set is checkable, so the compiler reports the gap; it warns rather than errors because deliberate partial handling is a real pattern and the fallthrough is silent, not unsafe.
(b.i) Rule. A MATCH is a statement and does not itself yield a value; its arms read as ordinary bodies. A WHEN carries no guard — a runtime test that further refines an arm is an ordinary IF inside that arm's body.
Example.
MATCH request {
WHEN Order o: {
IF o->isPaid() THEN { ship(o) } ELSE { hold(o) } // the guard, written plainly
}
}
Rationale. Guards were part of the value role removed in (a.i) and share its fate: a guard is an IF folded into the arm header, where it reads as part of the pattern rather than as the branch it is. Written inside the body it is the same code, one construct fewer, and the arm's binding is already in scope.
Generated — do not edit by hand. This document is produced by a generator from the compiler's own spec-trace, which it emits as it traces every construct. Regenerate after any trace change; the companion ENVZN_CONSTITUTION.md (Article II) summarises it and must stay in sync.
Envzn compiles through its own intermediate representation, the EvIR. The front end tokenizes and parses source into an AST and analyzes it; the analyzed tree is then built into EvIR nodes (build_ir), and the EvIR is lowered to C++20 (compiler/evir/emitter.py), which clang++ turns into a native executable. Section A specifies the EvIR node set in fourteen logical groups; Section B records how each node lowers to C++, covering all 532 traced mappings.
The node set of the Envzn intermediate representation, grouped by role. Every concrete node defined in compiler/evir/nodes.py appears in exactly one group; the abstract roots IrExpr and IrStmt are category framing, not elements.
The leaf value nodes — the constants a program writes directly. Each carries its resolved type and lowers to the corresponding C++ literal or kernel value; the absence leaves (EMPTY, none) carry no payload and stand for an unoccupied class or pipe slot.
IrIntLit — an integer literal, typed by the analyzer (the context-free default is int64)IrBinaryLit — a literal WRITTEN as a bit pattern (0xC3, 0b1100); a subclass of IrIntLit by value, typed binary for an octet and by written width beyond it — the node, not a field, says it is a bit pattern (I.D(b))IrFloatLit — a floating-point literal (default float64)IrBoolLit — a boolean literal — TRUE or FALSEIrCharLit — a char32 code-point literalIrStringLit — an interned immutable String literalIrArrayLit — an array literal, [a, b, c]IrStatusLit — a STATUS literal — SUCCESS, PARTIAL_SUCCESS, or FAILURE(message, code)IrEmpty — the EMPTY absence value of a class-typed slotIrNone — the none value of an unoccupied pipe / optional slotThe nodes that name an existing value rather than compute a new one — reads of locals, the receiver, data fields, and indexed elements. Each resolves to a place the surrounding node reads from or writes to, and the access form (owning handle, borrow, value-array slot) decides how it lowers.
IrVarRef — a read of a local, parameter, or constantIrSelf — the receiver SELF inside a methodIrFieldRead — a data-field read through . (owning, reference, or chain receiver)IrIndex — an indexed access coll[i] over an array, value-array, or collectionIrMultiIndex — a dense N-D subscript a[i, j, …] — fused column-major access on the EvNdArray companion; the element may be an OBJECT, whose cell is an owning handleIrArrayCell — slot index of a native array's store (EvArr / EvNdArr) as an element: get borrows it, set moves a value in (dropping what was there), take moves it out and leaves the slot all-zero. The index is already in range: the kernel body that reaches one checks itIrIndexGuard — a subscript coordinate, checked (#19, native-array-primitive-design §19.13): it yields index when 0 <= index < extent (IN_RANGE) or 0 <= index (NON_NEGATIVE, the growing write), else raises IndexOutOfBoundsError through the backend's own raiser (_value_array_throw_oob in C++, ev_panic_oob in LLVM). With no extent it is checked against its own access's extent on axis, so the array is evaluated once; with one it stands alone, a hoisted check ahead of a loopIrProvenReadAt — a native or fixed array's cell that loop elision proved in range, read or overwritten in place with no bounds branch; lowered to the §2.2 proven access, which re-checks and counts under -DEV_VERIFY_ELISIONIrProvenWriteAt — the C3-fill cell — slot index of storage CREATE(n) reserved, proven in [length, capacity) — written with no grow; the loop's fill_after sets the length onceComputation over values: the arithmetic, comparison, bitwise, and logical operators, and the explicit AS / INTO conversions together with the CONVERSIONS hosts that define them. Conversions are always explicit and checked; there is no implicit cast.
IrBinary — a binary operator — arithmetic, comparison, bitwise, shift, or BEQUALSIrUnary — a unary operator — negate, NOT, BNOT, factorial, increment/decrementIrConvert — an AS / INTO conversion at a use siteIrPrimCast — a primitive numeric cast (static_cast<T>) — the int/float-arm coercion behind number construction and wideningIrCoerce — an IMPLICIT scalar conversion the analyzer admitted, stated on the IR (Phase 4d.1) — kind (compiler.common.coercion.CoerceKind) names WHICH clause (widen, reinterpret, a provably-safe narrow, an octet range check or offset shim, a folded constant) admitted the crossing with no explicit AS/INTOIrDuplicate — a DUPLICATE value deep copy. The value-vs-reference SHAPE decision is made in build_ir, not the emitter: a BORROW operand (a =@ REFERENCE local, a handle-ABI borrow param, or the IrElementRef transition build_ir inserts for a DUPLICATE arr[i] storage cell) lowers to ENVZN::_ev_duplicate_ref<T>(operand); every other operand (owning handle / value / primitive) binds the by-value ENVZN::_ev_duplicate(value) (owning handle deep-clones, value/primitive value-copies).IrConversions — a CONVERSIONS host declaring the AS/INTO operators for a typeIrConversionOp — a single AS or INTO operator definitionIrOpaqueOp — an opaque[T]->wrap / ->unwrap static-dispatch operationIrGetPointee — a representation-shape bridge: OWNING → BORROW, lowering inner.get()IrAddressOf — a representation-shape bridge: VALUE_REF → BORROW, lowering &innerIrArrayView — a fixed array's cells seen as a native array (native-array-primitive-design §3, §19.2): a T[N] as a REFERENCE NativeArray[T], a T[M,N] as a REFERENCE NativeNdArray[T]. build_ir places one wherever a fixed array meets a method, an operator, a whole-array copy or a REFERENCE T[] / REFERENCE T[,] slot; a backend builds a descriptor over cells with the extents of their type, which owns nothing and never growsIrDeref — a representation-shape bridge: BORROW → VALUE, lowering (*inner)IrShared — a new strong count on a SHARED CLASS object held through a borrow: the =@ bind of a SHARED MUTABLE REFERENCE field. Lowers to ENVZN::_ev_share(inner) (C++) / an atomic add on the count at obj − 8 (LLVM)IrElementRef — a representation-shape bridge: a storage-array cell → BORROW referent pointer, lowering _ev_ref_of(recv.data()[index]). The mutable subscript yields a non-copyable _Ref write proxy, so the element is reached through .data()[index]; _ev_ref_of splits shape (&elem value / .get() referent owning). build_ir inserts it for DUPLICATE arr[i] (the inline form of REFERENCE r =@ arr[i]; DUPLICATE r).IrLayoutOf — SIZE OF T / ALIGNMENT OF T, a compile-time C.size_t: each backend asks its own layout authority for one stored value of the type (C++ sizeof / alignof, LLVM its data layout)IrRefOf — a reference-source bridge: a value → BORROW referent pointer via _ev_ref_of(inner). The =@ bind of a generic TYPE_PARAM source (resolves per-instantiation — .get() for a class T, & for a primitive T) and the general reference-source fallback.IrPipeSlotRef — a reference-source bridge: an Array[T] wrapper subscript success-slot → BORROW pointer via _EvGet<0>(inner). The wrapper arr[i] yields the pipe-XOR (REFERENCE T | STATUS) tuple; =@ binds the success-slot reference pointer directly.IrMutRefCast — a reference-source bridge: a VALUE_REF (const T& value-reference) → BORROW pointer, const-stripped so a MUTABLE REFERENCE T* field slot also accepts it, via const_cast<...>(&inner).IrWeakLock — the FALLIBLE deref of a WEAK REFERENCE handle: weak handle → (REFERENCE T | EMPTY), lowering to _ev_weak<T>::lock() plus a validity test (C++) or an is_alive load and branch on the referent preamble (LLVM). RESERVED, PENDING IMPLEMENTATION — not yet constructed and WEAK REFERENCE has no token, but it has a committed consumer in the nullable foreign key of ORMapping; the node exists so the lock operation has an IR anchor rather than being re-derived in the emitter from MatchSubject.WEAK.The nodes that invoke behaviour or build instances — resolved method and static calls, heap construction through INIT and SUPER, and lambdas. Overload resolution is settled before lowering, so each call node already names its concrete target.
IrCall — a method or namespace/static call, overload resolved by argument typesIrCreate — a heap-class CREATE — allocation reached through an owning handleIrFormatObject — the FormatArgument of a handle argument to a format call — a class or interface object, a FOREIGN_TYPE pointer, an array or EMPTY: ABSENT when null, FORMATTABLE when the object implements Formattable (tested on the object), else UNKNOWN (format-argument-design §4)IrStaticValue — a compile-time-constant value built once and read by reference — IDENTITY(…) (A13)IrIdentityThroughLens — IDENTITY(x) of an object held through a class lens — the lens's static record, re-named from the object's tag at run time (Q20)IrNdAlloc — an implicit dense N-D construction float64[m,n] / float64[3,4] — ENVZN::EvNdArray<elem, RANK>(dims…), a selector resolving to _NdArray (blittable) or _NdObjectArray (object)IrNdWiden — a fixed→spine N-D widening — a compile-time fixed-shape array (EvNdArrayFixed) materialized as a runtime spine EvNdArray<elem, RANK> when it flows into a float64[,] binding; total, one-directionalIrInit — an INIT constructor — its initializer list and bodyIrSuperInit — a SUPER(...) base-constructor call, emitted in the initializer list (sub-node)IrLambda — a lambda — expression form, block form, or no-parameter task bodyThe nodes that introduce or update storage. The binding operator carried by each one — copy, move, or non-owning reference — is part of its meaning and decides whether the right-hand value is copied, moved, or borrowed as it lowers.
IrLet — a local declaration with its binding operator (=, :=, =@)IrAssign — an assignment to an existing local, field, or referenceIrMultiAssign — a multi-value assignment from a comma- or pipe-shaped returnIrIndexAssign — an indexed write coll[i] = v (move or clone, per form)The structured-control nodes — blocks, conditionals, loops, MATCH, and compile-time type narrowing — together with the clause and arm components they are built from. Control flow is always reducible; there is no arbitrary jump.
IrBlock — a brace-delimited statement sequence and its scopeIrIf — a conditional with its then / else-if / else clausesIrClause — a single condition-and-body clause within an IF or WHEN chain (sub-node)IrLoop — a loop — counted FOR, range FOR IN, WHILE, or LOOPIrNdForEach — a dense N-D coordinate walk FOR (i, j) IN grid — nested loops, contiguous axis innermost. No producer : build_ir writes the walk as nested IrLoops over the array's own extentsIrBreak — a BREAK out of the enclosing loopIrContinue — a CONTINUE to the next iterationIrMatch — a MATCH over a class, STATUS, or enum with exhaustive armsIrMatchArm — a single WHEN arm of a MATCH, with its binding (sub-node)IrWhenImplements — a compile-time WHEN ... IMPLEMENTS type-narrowing blockHow a method hands values back and how an expression runs for its effect. The return nodes carry the single-, comma-, and pipe-XOR-shaped results, applying any required clone or move as the value leaves the callee.
IrReturn — a RETURN, applying any required clone or move to the value as it leavesIrMultiReturn — a return populating several slots (comma or pipe-XOR shape)IrMultiSlot — a single named slot within a multi-value return (sub-node)IrExprStmt — an expression evaluated for its effect as a statementThe STATUS / pipe-XOR machinery and the presence tests. These nodes express the language's recoverable-failure vocabulary — consuming a pipe-XOR call in an IF or WHILE, reading its success or failure slots, and testing STATUS or class-value presence — kept strictly apart from the unrecoverable path.
IrPipeIf — an IF whose condition is a fallible pipe-XOR producer (a pipe-returning call, a fallible AS/INTO, a SETS_ERRNO FOREIGN call, or a collection/__op_index__ mirror subscript), narrowing $= / $! in its branches. A bare value-array T[]/T[N]/T[N+] subscript is NOT a producer — it is a direct bounds-checked read — so IF arr[i] THEN over a value array is an ordinary boolean IrIf, not this nodeIrPipeWhile — a WHILE driven by a pipe-XOR callIrPipeRead — a read of a pipe result slot — $=, $=[i], $!, $#IrIsStatus — an IS SUCCESS / IS FAILURE / IS PARTIAL_SUCCESS testIrIsValid — an IS VALID / IS NOT VALID presence test on a class valueThe PANIC / RECOVER path for unrecoverable error, and the ASSERT family for programmer-error checks that halt. Distinct from the recoverable STATUS vocabulary of the previous group: these unwind or abort rather than return a value.
IrPanic — a PANIC of an Error subclassIrTry — a TRY with its RECOVER and FINALLY clausesIrRecover — a single RECOVER clause binding a caught Error type; bind_read says whether its body reads the binding (sub-node)IrReportUncaught — the program entry's stderr report of a failure nothing caught (uncaught Envzn error: <message> / uncaught non-Envzn exception), built only in the handlers of IrMain and IrThreadEntryIrAssert — an ASSERT / ASSERT! programmer-error check (halts on failure)IrUnreachable — an UNREACHABLE! always-on unconditional halt — diverging (satisfies definite-return)The structured-concurrency nodes: the CONCURRENT scope that joins before it unwinds, the PARALLEL task launched within it, and the SYNCHRONIZED critical section. Each lowers onto the C++ threading runtime with its lifetime guarantees intact.
IrConcurrent — a CONCURRENT structured-scope block (RAII join-before-unwind)IrParallel — a PARALLEL task launch within a CONCURRENT scopeIrSynchronized — a SYNCHRONIZED(lock) critical sectionThe declaration nodes that give a module its shape — classes, namespaces, interfaces, structs, groups, enums — and the members within them: methods, signatures, parameters, and fields. These are the top-level nodes a module is a sequence of.
IrClass — a CLASS declaration — fields, methods, layout, and destructorIrNamespace — a NAMESPACE — a stateless host of free functions plus CONSTANT data; lowers to a C++ namespaceIrInterface — an INTERFACE declaration — pure-virtual method signaturesIrStruct — a STRUCT — a public-field data record with generated constructionIrUnion — a kernel-internal UNION raw-storage block (one typed arm live, no discriminant) lowering to a C++ union — backs the number value-classIrGroup — a GROUP — a tagged set of named constantsIrEnum — an ENUM declaration and its casesIrMethod — a method definition — signature, body, MODIFY/const, OVERRIDEIrMethodSig — a method signature without a body (interface or abstract) (sub-node)IrParam — a parameter — plain (owns), REFERENCE, MUTABLE REFERENCE, or variadicIrField — a data field — owning, REFERENCE, SHARED MUTABLE REFERENCE, or CONSTANTIrMain — the program entry, on IrModule.main for an executable only: the stack size, then one IrTry of ordinary sentences — CREATE <entry>() (the entry class declares no INIT) and either start() with STATUS to exit code, or, for a TaskStarterWithOptions entry (takes_options), the argument array and RETURN entry->entryRun(argv) — with an Error handler and a catch-all that report and exit 1IrMainArgv — the process arguments as an owned String[], one UTF-8-decoded String per C argument — where argc/argv enter the IRIrThreadEntry — the C entry of a raw thread, on IrModule.thread_entry for the kernel only (when it declares ThreadEntry.run): ev_thread_entry(int64 id), one IrTry around ThreadEntry.run(id) with IrMain's Error handler and catch-all, each reporting and then exiting the process with 1 — the only Envzn function C names (native-array-primitive-design §12.3)The typed foreign-function boundary and the UNSAFE gate around raw-handle access. The FOREIGN and BIND nodes reach genuine C symbols with their types stated; UNSAFE marks the only scope in which a raw foreign handle may be read.
IrForeignExpr — an inline FOREIGN expression blockIrForeignStmt — an inline FOREIGN statement blockIrForeignBind — a FOREIGN BIND to a C function — a typed FFI callIrForeignConstant — a FOREIGN BIND to a C constantIrForeignTypeBind — a FOREIGN_TYPE BIND to a C struct or opaque handleIrUnsafe — an UNSAFE { } block gating raw-handle accessThe debug-only capture nodes. They are present in the IR under a debug build and elided otherwise, and never change the meaning of the program they observe.
IrSnapshot — a SNAPSHOT debug capture of a valueIrStacktrace — a STACKTRACE debug statementIrBinding — one in-scope name (scope-capture unit consumed by IrSnapshot) (sub-node)The type representation every node carries, and the scope-exit destruction markers that drive deterministic cleanup. ResolvedType is the resolved type a node was given by the analyzer; IrDrop records where an owned value's life ends on the NORMAL path, and IrCleanupPad records the same for the EXCEPTIONAL one.
ResolvedType — the resolved type a node carries — primitive, class handle, value-array, or collectionIrDrop — a scope-exit destruction marker (RAII; the C++ destructor emits it implicitly) (sub-node)IrSynchRelease — the release of a SYNCHRONIZED block's lock, naming the block (sync_id) and the target's release() — placed where a drop for leaving the block is placed: its end, an exit that leaves it, and a row of every pad inside it (translate request synchronized_release) (sub-node)IrCleanupPad — the drops an EXCEPTION passing through a point must run — one row per DISTINCT live set (deduplicated, so the count matches a landing-pad count rather than a call count), innermost-first in reverse declaration order. Carried as a method-level table (cleanup_pads on IrMethod/IrInit/IrClass/IrConversionOp) plus a per-statement pad_id stamp, because the live set changes at every declaration rather than per lexical scope and an IF arm is a bare statement tuple with no node to hang a field on. Produced by drop_insertion as the fifth row of the _frames_to_unwind computation that already answers this for four other exit kinds: the walk stops at a TRY region (the backend chains to the pad stamped on the IrTry itself) and at a lambda/PARALLEL barrier, and dedup keys on the declaration, never the name. strip_module_drops clears it beside the drops, so golden does not move. (sub-node)IrCatchClause — one RECOVER a catch pad tests: its type, its TRY, its index, and name_hash (FNV-1a 64 of module:Class) (sub-node)How each EvIR node lowers to C++20, organised by the same fourteen groups. Each row is one traced mapping from that spec-trace: the node, the variant or concept that distinguishes it, the C++ shape it emits, and the governing constitution reference. Structural sub-nodes (clauses, arms, slots) carry no standalone lowering and are noted inline under their parent group.
IrIntLit — an integer literal, typed by the analyzer (the context-free default is int64)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| integer literal | 5 |
I.D.ii |
| int literal 128bit | (((unsigned __int128)68719476736ull << 64) \| (unsigned __int128)0ull) |
— |
| int literal plain | 1234 |
— |
| int literal unsigned ull | 9223372036854775808ull |
— |
IrFloatLit — a floating-point literal (default float64)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| float literal | 3.5 |
I.D.ii |
| float literal | 1.41 |
— |
IrBoolLit — a boolean literal — TRUE or FALSE
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| boolean literal | true |
I.D.i, I.C |
| bool literal false | U'\n' |
— |
| bool literal true | true |
— |
IrCharLit — a char32 code-point literal
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| char literal | U'x' |
I.D.i, I.C |
| char literal escape | U'z' |
— |
| char literal printable | U'A' |
— |
| char literal universal | U'A' |
— |
IrStringLit — an interned immutable String literal
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| string literal | ENVZN::_ValueArray<char32_t>{0x68, 0x69} |
I.D.vii, I.C |
| string literal | make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0xA}) |
— |
| string literal empty | make_ev_unique<String>(ENVZN::_ValueArray<char32_t>()) |
— |
IrArrayLit — an array literal, [a, b, c]
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| array literal | ENVZN::_ValueArray<T>{ <e0>, <e1>, ... } |
— |
IrStatusLit — a STATUS literal — SUCCESS, PARTIAL_SUCCESS, or FAILURE(message, code)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| cstring literal | "boom" |
— |
| status message | _STATUS_FAILURE("oops") |
— |
| status msg encode | ENVZN::_utf8_from_string(this->failReason) |
— |
| status msg pipe move | std::move(std::get<1>(__pipe_1).message) |
— |
| status success | _STATUS_SUCCESS() |
— |
| status with code | _STATUS_FAILURE("boom", 42) |
— |
| status empty message | _STATUS_SUCCESS() |
— |
IrEmpty — the EMPTY absence value of a class-typed slot
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| empty literal | {} |
— |
IrNone — the none value of an unoccupied pipe / optional slot
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| none literal | nullptr |
— |
Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrBinaryLit.
IrVarRef — a read of a local, parameter, or constant
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| rvalue read of var | n |
I.F, I.F.i |
| constant field scalar | static constexpr double ZERO = 0.0; |
— |
| constant field string | static const String& GREETING() { static const String v{ENVZN::_ValueArray<char32_t>{0x68, 0x65, 0x6C, 0x6C, 0x6F}, 5}; return v; } |
— |
| constant field value array | static constexpr ENVZN::_ValueArrayConst<uint8_t, 6> masks = {{ 255, 127, 63, 31, 15, 7 }}; |
— |
| constant value float32 suffix | 3.14f |
— |
| constant value float64 int promote | 0.0 |
— |
| constant value string codepoints | 0x68, 0x65, 0x6C, 0x6C, 0x6F |
— |
| constant value struct braceinit | {4, Stage::END} |
— |
| field enum case | State::END |
— |
| kernel foreign constant | const int32_t _ev_fbc_F_OK = F_OK; |
— |
| varref constant qualified | Math::PI |
— |
| varref narrowed handle | joined |
— |
| varref plain | pDay |
— |
| constant value float32 int promote | result |
— |
| constant value string empty | result |
— |
| enum bare | result |
— |
| struct nested enum | result |
— |
| varref narrowed optional class | result |
— |
| varref narrowed value optional | result |
— |
IrSelf — the receiver SELF inside a method
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| self ref | this |
— |
IrFieldRead — a data-field read through . (owning, reference, or chain receiver)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| chain receiver owning field | (*this->left) |
— |
| chain receiver reference field | (*this->src) |
— |
| field array capacity | (scratch.capacity()) |
— |
| field array length | (f.length()) |
— |
| field constant qualified | Constants::ANSWER |
— |
| field foreign constant | _ev_fbc_SOCK_STREAM |
— |
| field foreign handle | (p)->ai_next |
— |
| field recv pointer deref strip | this->inner->v |
— |
| field self | this->s |
— |
| field text length | (url->length()) |
— |
| field value | q.key |
— |
| field var pointer | h->key |
— |
IrIndex — an indexed access coll[i] over an array, value-array, or collection
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| chain receiver handle storage | (*got) |
— |
| index default | s[t] |
— |
| index fixed array | sbo[0] |
— |
| index op index | b->__op_index__(i) |
— |
| assign from index move | this->data[index] |
— |
| index array subscript | this->data[index] |
— |
| index pipe slot error | this->data[index] |
— |
| index text op index | this->data[index] |
— |
IrMultiIndex — a dense N-D subscript a[i, j, …] — fused column-major access on the EvNdArray companion; the element may be an OBJECT, whose cell is an owning handle
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| ndarray | a(i, j) |
I.J |
Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrArrayCell,IrIndexGuard,IrProvenReadAt,IrProvenWriteAt.
IrBinary — a binary operator — arithmetic, comparison, bitwise, shift, or BEQUALS
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| binary bit equals float64 | (std::bit_cast<uint64_t>(a) == std::bit_cast<uint64_t>(c)) |
— |
| binary bitwise shift | (a & b) |
— |
| binary default | (i + a) |
— |
| binary floordiv | ENVZN::_ev_floordiv<int32_t>(7, 2) |
— |
| binary lrotate | std::rotl(x, k) |
— |
| binary operator method dispatch | _ev_unique<ENVZN::TimeDuration>(a->__op_plus__(b)) |
— |
| binary set algebra rewrap | _ev_unique<Set<int32_t, _ev_unique<DefaultHasher<int32_t>>>>(a->unionWith(b)) |
— |
| power float pow | std::pow(static_cast<double>(2), static_cast<double>((-1))) |
— |
| power integer ipow | ev_ipow(static_cast<int32_t>(3), static_cast<int32_t>(2)) |
— |
| value operand handle deref | (*x) |
— |
| value operand subscript cast | static_cast<double>(f[0]) |
— |
| binary bit equals float32 | (this->length + 1) |
— |
| binary bit equals int | (this->length + 1) |
— |
| binary coalesce | (this->length + 1) |
— |
| binary coalesce empty | (this->length + 1) |
— |
| binary hash combine | ev_hash_combine(static_cast<uint64_t>(a), static_cast<uint64_t>(b)) |
I.F.ii(a) |
| binary rrotate | (this->length + 1) |
— |
| binary set algebra | (this->length + 1) |
— |
| binary wrapping | ev_wrapmul_u64(a, b) |
I.F.ii(a.iv) |
IrUnary — a unary operator — negate, NOT, BNOT, factorial, increment/decrement
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| unary bitwise not | (~a) |
— |
| unary default | (-7) |
— |
| unary factorial | ev_factorial(5) |
— |
| unary postdecrement | (i--) |
— |
| unary postincrement | (i++) |
— |
| unary preincrement | (++i) |
— |
| unary predecrement | (!(i == j)) |
— |
| unary hash word | static_cast<uint64_t>(key) |
I.F.ii(a) |
IrConvert — an AS / INTO conversion at a use site
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| conv fn pipe slot | bool value{}; |
— |
| convert class wrap | _ev_unique<String>(CharConverter::_cv_into__char8__String(c8)) |
— |
| enum to int cast | static_cast<int32_t>(cat) |
— |
| convert no conversion | _ev_unique<String>(NumberConverter::_cv_into__int32__String(index)) |
— |
| complex | ComplexConversions::_cv_into__complex__float64(realC) |
I.D.viii, I.D.i(g) |
| complex | _ev_unique<String>(ComplexConversions::_cv_into__complex__String(pc)) |
I.D.viii |
| number | NumberConversions::_cv_as__number__int32(n7) |
I.D.viii |
IrPrimCast — a primitive numeric cast (static_cast<T>) — the int/float-arm coercion behind number construction and widening
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| number int | static_cast<int64_t>(3) |
I.D.i(g) |
IrCoerce — an IMPLICIT scalar conversion the analyzer admitted, stated on the IR (Phase 4d.1) — kind (compiler.common.coercion.CoerceKind) names WHICH clause (widen, reinterpret, a provably-safe narrow, an octet range check or offset shim, a folded constant) admitted the crossing with no explicit AS/INTO
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| widen | {value} (WIDEN/REINTERPRET/NARROW_*/CONST_FITS into a non-binary dest, bare — 4d.1 identity lowering); a binary dest: static_cast<binary>(… |
I.F / I.D.i(b.i) / §28.3 |
IrConversions — a CONVERSIONS host declaring the AS/INTO operators for a type
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| conversions host | namespace ProbeConv { /* AS/INTO operator free functions */ } |
I.D.viii |
IrConversionOp — a single AS or INTO operator definition
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| conversion operator | String into_String(Color v) { ... } // free fn in host namespace |
I.D.viii |
IrOpaqueOp — an opaque[T]->wrap / ->unwrap static-dispatch operation
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| opaque wrap | _opq_wrap<int32_t>(n) // payload boxed behind void* |
I.D.v |
Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrDuplicate,IrGetPointee,IrAddressOf,IrArrayView,IrDeref,IrShared,IrElementRef,IrLayoutOf,IrRefOf,IrPipeSlotRef,IrMutRefCast,IrWeakLock.
IrCall — a method or namespace/static call, overload resolved by argument types
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| call arg handle deref | *pk2 |
— |
| class return wrap | _ev_unique<String>(clone()) |
— |
| foreign arg opaque array | (void*)((sniHost).data()) |
— |
| foreign arg passthrough | R_OK |
— |
| foreign arg string | reinterpret_cast<const char*>(ENVZN::_utf8_from_string(s).data()) |
— |
| foreign arg unsafe handle | static_cast<void*>(this->native) |
— |
| foreign arg value array | (hay).data() |
— |
| foreign bind arg load outparam | &res |
— |
| foreign bind arg opaque peek | _opq_peek<SSL*>(this->ssl) |
— |
| foreign bind call load buffer | ([&]() -> int32_t { int32_t _tmp_0_cap = (slot).capacity(); char8_t* _tmp_0 = new char8_t[_tmp_0_cap]; int32_t _r = (::read)(0, _tmp_0, 1)… |
— |
| foreign bind call plain | (::cos)(x) |
— |
| foreign bind call string callee owned | ([&]() -> _ev_unique<String> { const char* _r = (::gai_strerror)(rc); return _r ? ENVZN::_string_from_utf8(_r) : _ev_unique<String>(); }()) |
— |
| foreign bind call string caller owned | ([&]() -> _ev_unique<String> { const char* _r = (::ev_path_canonical)(reinterpret_cast<const char*>(ENVZN::_utf8_from_string(this->value).… |
— |
| method inline splice | ({ auto&& _inl_101_recv = (data); (_inl_101_recv->_data); }) |
— |
| method inline trailing move | (std::move(_inl_3_v)); |
— |
| method inline void guard | (void)0; |
— |
| methodcall arg adopt clone | _ev_adopt_clone<_ev_unique<HttpHeader>>(hc->clone()) |
— |
| methodcall arg constref clone | _ev_unique<Person>(p->clone()) |
— |
| methodcall arg move | std::move(a) |
— |
| methodcall arg template move | std::move(w) |
— |
| methodcall array clear | this->data.clear() |
— |
| methodcall array length | (r6.length()) |
— |
| methodcall array remove | arr.remove(0) |
— |
| methodcall conversion helper | isDigit(c) |
— |
| methodcall conversion helper class wrap | _ev_unique<String>(decimalDigits(v)) |
— |
| methodcall cxx member | this->native.join() |
— |
| methodcall format arg class tostring | _ev_unique<String>((bob) ? (bob)->toString() : ENVZN::_string_from_utf8("EMPTY").release()) |
— |
| methodcall format arg dynbytebuffer | _ev_unique<ByteBuffer>((dbb).toByteBuffer()) |
— |
| methodcall format arg dynstring | _ev_unique<String>((name).toString()) |
— |
| methodcall format arg unrenderable | ENVZN::_string_from_utf8("[??]") |
— |
| methodcall namespace | IntUtil::square(7) |
— |
| methodcall namespace class wrap | _ev_unique<String>(IntUtil::label(42)) |
— |
| methodcall opaque deepcopy | _opq_clone(args[idx]) |
— |
| methodcall opaque loaded | value.loaded() |
— |
| methodcall opaque unwrap | _opq_unwrap<bool>(value) |
— |
| methodcall opaque unwrap class | _opq_unwrap_class<String>(value) |
— |
| methodcall self implicit | burn() |
— |
| methodcall string format formatter | _ev_unique<String>(Formatter().format(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x24, 0x31}), _opq_pack(cv))) |
— |
| methodcall string format wrap | _ev_unique<String>(tmpl->formatWith(BinaryMode::HEX_SPACED, args)) |
— |
| methodcall string isempty | (em->isEmpty()) |
— |
| methodcall variadic opaque pack | ds.at(4) |
— |
| string arg handle deref | *e |
— |
| call arg opaque move | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| foreign arg bytebuffer | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall arg interface upcast | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall array capacity | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall array iterator synth | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall foreign legacy | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall generic | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall opaque wrap | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| methodcall super | _ev_unique<ArrayIterator<T>>(iterator()) |
— |
| complex | Complex(Number(static_cast<int64_t>(3)), Number(static_cast<int64_t>(4))).__op_plus__(Complex(Number(static_cast<int64_t>(5)), Number(stat… |
I.D.i(g) |
| complex | Complex(Number(static_cast<int64_t>(3)), Number(static_cast<int64_t>(4))).__op_minus__(Complex(Number(static_cast<int64_t>(1)), Number(sta… |
I.D.i(g) |
| complex | Complex(Number(static_cast<int64_t>(1)), Number(static_cast<int64_t>(2))).__op_times__(Complex(Number(static_cast<int64_t>(3)), Number(sta… |
I.D.i(g) |
| complex | Complex(Number(static_cast<int64_t>(1)), Number(static_cast<int64_t>(0))).__op_divide__(Complex(Number(static_cast<int64_t>(0)), Number(st… |
I.D.i(g) |
| complex | Complex(Number(static_cast<int64_t>(3)), Number(static_cast<int64_t>(4))).negate() |
I.D.i(g) |
| complex | sum.equals(Complex(Number(static_cast<int64_t>(8)), Number(static_cast<int64_t>(6)))) |
I.D.i(g), I.F.ii.c |
| complex | c.real() |
I.D.i(g) |
| complex | c.imaginary() |
I.D.i(g) |
| complex | c.conjugate() |
I.D.i(g) |
| complex | c.magnitude() |
I.D.i(g) |
| complex | Complex(Number(static_cast<int64_t>(1)), Number(static_cast<int64_t>(0))).phase() |
I.D.i(g) |
| number | drift.isClose(Number(static_cast<double>(0.3)), 1.5e-08, 1e-12) |
I.F.ii.c |
| number | sum.equals(Number(static_cast<int64_t>(7))) |
I.D.i(g), I.F.ii.c |
| number | n.kind() |
I.D.i(g) |
IrCreate — a heap-class CREATE — allocation reached through an owning handle
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| construct heap class | make_ev_unique<Widget>(5) |
I.F.iii, I.K.v, II.D |
| call arg byref local | nums |
— |
| call arg move | std::move(r) |
— |
| create class | make_ev_unique<Box>() |
— |
| create qualified class | make_ev_unique<Logger::NullSink>() |
— |
| create struct | FloatingDecimal64() |
— |
| create value class | DynamicString() |
— |
| create arg struct constref clone | make_ev_unique<ArrayIterator<T>>(this->data) |
— |
| create arg struct move | make_ev_unique<ArrayIterator<T>>(this->data) |
— |
| create qualified struct | make_ev_unique<ArrayIterator<T>>(this->data) |
— |
| create qualified struct pod | make_ev_unique<ArrayIterator<T>>(this->data) |
— |
| create struct pod | make_ev_unique<ArrayIterator<T>>(this->data) |
— |
| complex | Complex(Number(static_cast<int64_t>(5)), Number(static_cast<int64_t>(2))) |
I.C(f), I.D.i(g) |
| number int | Number(static_cast<int64_t>(3)) |
I.D.i(g) |
| number float | Number(static_cast<double>(3.14)) |
I.D.i(g) |
IrNdAlloc — an implicit dense N-D construction float64[m,n] / float64[3,4] — ENVZN::EvNdArray<elem, RANK>(dims…), a selector resolving to _NdArray (blittable) or _NdObjectArray (object)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| ndarray | ENVZN::EvNdArray<double, 2, ENVZN::EvArrayMode::_GROWABLE>(m, n) |
I.J |
IrNdWiden — a fixed→spine N-D widening — a compile-time fixed-shape array (EvNdArrayFixed) materialized as a runtime spine EvNdArray<elem, RANK> when it flows into a float64[,] binding; total, one-directional
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| ndarray | ENVZN::EvNdArray<elem, RANK, _GROWABLE>(<fixed>) — kernel converting ctor, element-wise (clone for object cells); NOT a memcpy |
I.J.i |
IrInit — an INIT constructor — its initializer list and body
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| constructor (INIT) | Probe(const ENVZN::EvArray<_ev_unique<String>>& argv) { } |
I.K.v |
IrLambda — a lambda — expression form, block form, or no-parameter task body
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| lambda block | [&](<params>) { /* body */ } |
— |
| lambda expr | [&](<params>) { /* body */ } |
— |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrSuperInit— aSUPER(...)call, emitted in theIrInitinitializer list.Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrFormatObject,IrStaticValue,IrIdentityThroughLens.
IrLet — a local declaration with its binding operator (=, :=, =@)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| local var, no init | int32_t n = 5; |
I.E, II.N |
| primitive copy var->var | int32_t m = n; |
I.G, I.J.ii |
| move-init local | <owner><<Class>> w = <init>; |
I.G, I.I.i, I.J.ii |
| refsource array cell | const String* piece0 = _ev_ref_of(r9[0]); |
— |
| refsource field class | m->left.get() |
— |
| refsource field param | _ev_ref_of(e->key) |
— |
| refsource pipe slot | const ENVZN::EvArray<char8_t>* got = &std::get<0>(__pipe_2); |
— |
| refsource self param | _ev_ref_of(this->key) |
— |
| refsource self reference field | this->active |
— |
| refsource var storage refvar | const_cast<std::remove_const_t<std::remove_reference_t<decltype(source)>>*>(&source) |
— |
| vardecl constant scalar | static constexpr uint64_t n_div_5 = 3689348814741910323; |
— |
| vardecl default | _ev_unique<Person> noOne = {}; |
— |
| vardecl fixed array nogrow | ENVZN::EvArray<DynamicString> fixed(12, true); |
— |
| vardecl foreign handle default | struct addrinfo * res = nullptr; |
— |
| vardecl from field move | _ev_unique<RBNode<K, V>> x = std::move(h->left); |
— |
| vardecl from var move | _ev_unique<Payload> second = std::move(first); |
— |
| vardecl general | Pair q = p; |
— |
| vardecl handle mode | const int32_t* v = box->value(); |
— |
| vardecl interface upcast call | _ev_unique<Cloneable> c = _ev_unique<Cloneable>(original->clone()); |
— |
| vardecl interface upcast create | _ev_unique<Dictionary<__int128, int32_t, _ev_unique<DefaultHasher<__int128>>>> d = _ev_unique<Dictionary<__int128, int32_t, _ev_unique<Def… |
— |
| vardecl parametric adopt clone | K k2 = _ev_adopt_clone<K>(key->clone()); |
— |
| vardecl reference deref | int32_t v = *(b->value()); |
— |
| vardecl storage capacity | ENVZN::EvArray<char32_t> b = char32(16); |
— |
| vardecl value class init | DynamicString a = DynamicString(); |
— |
| refsource array element | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource field storage | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource field value | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource iter ref | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource none | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource self | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource var param | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource var storage | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| refsource var value | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl constant array | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl constant string | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl from cell clone | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl from cell move | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl from index value | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl from refvar clone | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl group deref | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl optional field clone | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
| vardecl value class default | _ev_unique<ArrayIterator<T>> result = make_ev_unique<ArrayIterator<T>>(this->data); |
— |
IrAssign — an assignment to an existing local, field, or reference
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| reassign primitive | n = 5; |
I.G, I.I.i, I.J.ii |
| assign chain default | spec.width = 0; |
— |
| assign chain field move | h->right = std::move(x->left); |
— |
| assign chain var move | x->left = std::move(h); |
— |
| assign default | ok = false; |
— |
| assign from cell move | value = std::move(this->data.mutable_data()[0]); |
— |
| assign from field move | value = std::move(popped->value); |
— |
| assign handle deref | v = *(r); |
— |
| assign handle flip | local = holder->storedRef(); |
— |
| assign handle rebind | handle = this->guarded.get(); |
— |
| assign interface upcast call | it = _ev_unique<ReferenceIterator<V>>((({ auto&& _inl_87_recv = (other); (std::move(_ev_unique<ReferenceIterator<V>>(_inl_87_recv->data->i… |
— |
| assign mutref writethrough | m = 99; |
— |
| assign parametric adopt clone | k2 = _ev_adopt_clone<K>(this->key->clone()); |
— |
| assign string field clone | result = _ev_unique<String>((this->source)->clone()); |
— |
| assign uptr move | result = std::move(paths); |
— |
| class init field default | this->id = i; |
— |
| init param scalar | this->inner = make_ev_unique<Inner>(7); |
— |
| refsource self storage | &this->data |
— |
| refsource var class | this->src = s.get(); |
— |
| self assign chain default | this->holder->node->isRed = true; |
— |
| self assign chain field move | this->head->next = std::move(taken->next); |
— |
| self assign chain var move | this->head->next = std::move(newNode); |
— |
| self assign constref clone | this->label = _ev_unique<String>(label->clone()); |
— |
| self assign default | this->i = 0; |
— |
| self assign move | this->head = h; |
— |
| self assign opaque wrap | this->ctx = _opq_wrap<SSL_CTX*>(::SSL_CTX_new(::TLS_client_method())); |
— |
| self assign reference | this->src = s.get(); |
— |
| self assign string constref clone | this->name = n; |
— |
| self assign strong smr | this->core = core; |
— |
| assign chain reference | this->length = (this->length + 1); |
— |
| assign chain string move | this->length = (this->length + 1); |
— |
| assign copy construct | this->length = (this->length + 1); |
— |
| assign deref copy | this->length = (this->length + 1); |
— |
| assign parametric move | this->length = (this->length + 1); |
— |
| self assign array | this->length = (this->length + 1); |
— |
| self assign chain reference | this->length = (this->length + 1); |
— |
| self assign parametric adopt clone | this->length = (this->length + 1); |
— |
| self assign string move | this->length = (this->length + 1); |
— |
IrMultiAssign — a multi-value assignment from a comma- or pipe-shaped return
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| multiassign extra existing | p0 = std::get<1>(_ret_5); |
— |
| multiassign extra typed | auto _ret_1 = d->lookup(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x6F, 0x70, 0x65})); int32_t v = std::get<0>(_ret_1); _E… |
— |
| multiassign first existing | prodHi = std::get<0>(_ret_4); |
— |
| multiassign first typed | auto _ret_1 = d->lookup(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x6F, 0x70, 0x65})); int32_t v = std::get<0>(_ret_1); _E… |
— |
| multiassign slot get | auto _ret_0 = labels->lookup(alpha); int32_t va = std::get<0>(_ret_0); _EvStatus sa = std::get<1>(_ret_0); |
— |
| multiassign slot move get | auto _ret_0 = _ev_unique<ENVZN::String>(d->remove(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x61}))); _ev_unique<String> rk = st… |
— |
| multiassign tuple temp | auto _ret_0 = d->lookup(b); int32_t got = std::get<0>(_ret_0); _EvStatus gs = std::get<1>(_ret_0); |
— |
| multiassign extra ref | auto _ret_4 = umul128(a, b); |
— |
| multiassign first ref | auto _ret_4 = umul128(a, b); |
— |
IrIndexAssign — an indexed write coll[i] = v (move or clone, per form)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| indexed assign class clone | result[rlen] = _ev_unique<String>(tail->clone()); |
— |
| indexed assign default | ab[0] = 65; |
— |
| indexed assign parametric move | this->data[(j + 1)] = std::move(key); |
— |
| indexed assign none | this->data[(this->data.length())] = b; |
— |
IrBlock — a brace-delimited statement sequence and its scope
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| block stmt | { _ev_unique<ArrayIterator<int32_t>> iter = _ev_unique<ENVZN::ArrayIterator<int32_t>>(scores->iterator()); while (iter->next()) { const in… |
— |
IrIf — a conditional with its then / else-if / else clauses
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| if stmt | if (s) { if (d) { if (v) { if (i) { Stdio.printline(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x73, 0x74, 0x72, 0x69, 0x6E, 0x67… |
— |
IrLoop — a loop — counted FOR, range FOR IN, WHILE, or LOOP
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| for counted | for (int32_t i = 1; i < 6; ++i) { _EvStatus s = pool->submit(make_ev_unique<SquareJob>(i, results)); } |
— |
| forin concrete iterator | [' {', ' auto _ev_iter = src.iterator();', ' while (_ev_iter->hasNext()) {'] |
— |
| repeat loop | [' for (int32_t _rep_6 = 0; _rep_6 < (18); ++_rep_6) {'] |
— |
| while loop | while (m > 0) { char32_t d = (48 + (m % 10)); tmp.prepend(d); m = (m / 10); } |
— |
| cstyle for | while ((i + 3) <= n) { |
— |
| dowhile loop | while ((i + 3) <= n) { |
— |
| foreach range for | while ((i + 3) <= n) { |
— |
| forin range for | while ((i + 3) <= n) { |
— |
| forin virtual iterator | while ((i + 3) <= n) { |
— |
| loop iter | while ((i + 3) <= n) { |
— |
| until loop | while ((i + 3) <= n) { |
— |
IrNdForEach — a dense N-D coordinate walk FOR (i, j) IN grid — nested loops, contiguous axis innermost. No producer : build_ir writes the walk as nested IrLoops over the array's own extents
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| ndarray | nested for-loops, axis 0 innermost (column-major) |
I.J |
IrBreak — a BREAK out of the enclosing loop
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| break stmt | break; |
— |
IrContinue — a CONTINUE to the next iteration
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| continue stmt | (emits — first-gen C++ not captured for this row) |
— |
IrMatch — a MATCH over a class, STATUS, or enum with exhaustive arms
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| status match bind | _ev_unique<String> msg = ENVZN::_string_from_utf8(s.message); |
— |
| status match cond | s.kind == _EvStatus::StatusKind::SUCCESS |
— |
| valuematch enum qualify | if (d == Direction::NORTH) { ok = false; } else if (d == Direction::EAST) { } else if (d == Direction::SOUTH) { ok = false; } else if (d =… |
— |
| valuematch equality | if (d == Direction::NORTH) { ok = false; } else if (d == Direction::EAST) { } else if (d == Direction::SOUTH) { ok = false; } else if (d =… |
— |
| match group bind | (emits — first-gen C++ not captured for this row) |
— |
| match group when | (emits — first-gen C++ not captured for this row) |
— |
| match optional bind | (emits — first-gen C++ not captured for this row) |
— |
| match optional none | (emits — first-gen C++ not captured for this row) |
— |
| match optional when | (emits — first-gen C++ not captured for this row) |
— |
| match weak bind | (emits — first-gen C++ not captured for this row) |
— |
| match weak none | (emits — first-gen C++ not captured for this row) |
— |
| match weak when | (emits — first-gen C++ not captured for this row) |
— |
| valuematch condition | (emits — first-gen C++ not captured for this row) |
— |
IrWhenImplements — a compile-time WHEN ... IMPLEMENTS type-narrowing block
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| when implements block | if constexpr (std::is_base_of_v<Cloneable, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond class | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond group | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond implements | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond inoperative | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond primitive | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
| when implements cond primitive set | if constexpr (std::is_base_of_v<I, T>) {\n /* then arm */\n} else {\n /* else arm */\n} |
— |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrClause— a condition-and-body clause, lowered within itsIrIf/IrWhenImplements;IrMatchArm— aWHENarm, lowered within itsIrMatch.
IrReturn — a RETURN, applying any required clone or move to the value as it leaves
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| auto clone class field | return _STATUS_SUCCESS(); |
— |
| auto clone header | return _STATUS_SUCCESS(); |
— |
| auto clone return | return _STATUS_SUCCESS(); |
— |
| auto clone value | return _STATUS_SUCCESS(); |
— |
| class default ctor | return _STATUS_SUCCESS(); |
— |
| class field plain | return combine(sh, sr); |
— |
| class field reference | return _STATUS_FAILURE("WorkerPool round-trip produced the wrong sum"); |
— |
| class header bare | return _STATUS_SUCCESS(); |
— |
| class header bases | return _STATUS_FAILURE("cloneInheritanceSmoke step 1"); |
— |
| class init ctor | return _STATUS_FAILURE("bug103Smoke: inlined bare-name CallStmt lost receiver"); |
— |
| class init ctor empty | return _STATUS_SUCCESS(); |
— |
| class init super | return _STATUS_FAILURE("cloneInheritanceSmoke step 1"); |
— |
| conversions namespace | return _STATUS_SUCCESS(); |
— |
| cpp name method keyword | return _STATUS_SUCCESS(); |
— |
| init param array | return _STATUS_FAILURE("subscription did not outlive its broker"); |
— |
| init param heap | return _STATUS_FAILURE("at least one assertion failed"); |
— |
| init param heap mutable | return _STATUS_FAILURE("refSmoke step 1"); |
— |
| interface destructor | return combine(sh, sr); |
— |
| interface header | return combine(sh, sr); |
— |
| interface method pure virtual | return combine(sh, sr); |
— |
| interface ret class pointer | return combine(sh, sr); |
— |
| method return slot class | _ev_unique<String> result; |
— |
| method return slot reference | return this->guarded; |
— |
| method return slot value | return true; |
— |
| method sig class pointer | return _STATUS_SUCCESS(); |
— |
| method sig multireturn tuple | return true; |
— |
| method signature | return _STATUS_FAILURE("bug103Smoke: inlined bare-name CallStmt lost receiver"); |
— |
| pipe return tuple | return std::make_tuple(v, s); |
— |
| refsource self class | return this->stored; |
— |
| refsource self value | return this->inner; |
— |
| return clone field | return make_ev_unique<String>(*this->name).release(); |
— |
| return clone release | return e.release(); |
— |
| return clone value class | return new DynamicString(std::move(result)); |
— |
| return plain | return i; |
— |
| return reference | return this->inner; |
— |
| return void | return; |
— |
| struct copy assign | return pr.key->equals(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x61, 0x6D, 0x65})); |
— |
| struct copy ctor | return pr.key->equals(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x61, 0x6D, 0x65})); |
— |
| struct default ctor | return pr.key->equals(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x61, 0x6D, 0x65})); |
— |
| struct field | return _STATUS_SUCCESS(); |
— |
| struct header | return pr.key->equals(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x61, 0x6D, 0x65})); |
— |
| struct move defaults | return pr.key->equals(make_ev_unique<String>(ENVZN::_ValueArray<char32_t>{0x6E, 0x61, 0x6D, 0x65})); |
— |
| struct nested group | return _STATUS_SUCCESS(); |
— |
| struct value ctor | return _STATUS_SUCCESS(); |
— |
| auto clone array | return result; |
— |
| return clone field optional | return result; |
— |
| return clone local optional | return result; |
— |
IrMultiReturn — a return populating several slots (comma or pipe-XOR shape)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| interface ret multireturn | return std::make_tuple(<v1>, <v2>, ...); |
— |
| multireturn tuple | return std::make_tuple(<v1>, <v2>, ...); |
— |
IrExprStmt — an expression evaluated for its effect as a statement
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| call arg class passthrough | testValueAccess(r); |
— |
| expr stmt | (i++); |
— |
| stmt call | bump(); |
— |
| string arg move | pass(label); |
— |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrMultiSlot— a return slot, lowered within itsIrMultiReturntuple.
IrPipeIf — an IF whose condition is a fallible pipe-XOR producer (a pipe-returning call, a fallible AS/INTO, a SETS_ERRNO FOREIGN call, or a collection/__op_index__ mirror subscript), narrowing $= / $! in its branches. A bare value-array T[]/T[N]/T[N+] subscript is NOT a producer — it is a direct bounds-checked read — so IF arr[i] THEN over a value array is an ordinary boolean IrIf, not this node
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| call arg reference return deref | {\n auto __pipe_1 = v->find(needle->data);\n if (std::get<1>(__pipe_1).kind == _EvStatus::StatusKind::SUCCESS) {\n /* then: $RETURNED = st… |
— |
| convert call | { auto __pipe_3 = NumberConverter::_cv_into__String__int64(n64); if (std::get<1>(__pipe_3).kind == _EvStatus::StatusKind::SUCCESS) { v64 =… |
— |
| foreign bind call sets errno | ([&]() -> std::tuple<int32_t, _EvStatus> { auto _r = (::fsync)(this->fd); if (_r == -1) { int _e = errno; return {_r, _STATUS_FAILURE(std:… |
— |
| if pipe | { auto __pipe_1 = s->pop(); if (std::get<1>(__pipe_1).kind == _EvStatus::StatusKind::SUCCESS) { int32_t v = std::get<0>(__pipe_1); r->expe… |
— |
| if pipe convert | { auto __pipe_3 = NumberConverter::_cv_into__String__int64(n64); if (std::get<1>(__pipe_3).kind == _EvStatus::StatusKind::SUCCESS) { v64 =… |
— |
| pipe call variadic pack | { auto __pipe_1 = s->pop(); if (std::get<1>(__pipe_1).kind == _EvStatus::StatusKind::SUCCESS) { int32_t v = std::get<0>(__pipe_1); r->expe… |
— |
IrPipeWhile — a WHILE driven by a pipe-XOR call
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| while pipe | while (true) {\n auto __pipe_1 = it->next();\n if (!(std::get<1>(__pipe_1).kind == _EvStatus::StatusKind::SUCCESS)) break;\n const _ev_und… |
— |
| while pipe fallback | while (true) { |
— |
IrPipeRead — a read of a pipe result slot — $=, $=[i], $!, $#
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| pipe result errcode | std::get<1>(__pipe_5).code |
— |
| pipe result status | ENVZN::_string_from_utf8(std::get<1>(__pipe_1).message) |
— |
| pipe slot move | std::move(std::get<0>(__pipe_3)) |
— |
| pipe slot reference | std::get<0>(__pipe_7) |
— |
| pipe slot value | std::get<0>(__pipe_7) |
— |
| pipe call bare | std::get<0>(__pipe_1) |
— |
| pipe result error | std::get<0>(__pipe_1) |
— |
IrIsStatus — an IS SUCCESS / IS FAILURE / IS PARTIAL_SUCCESS test
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| is status | (s.kind == _EvStatus::StatusKind::FAILURE) |
— |
IrIsValid — an IS VALID / IS NOT VALID presence test on a class value
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| isvalid class optional | (h == nullptr) |
— |
| isvalid foreign handle | (p != nullptr) |
— |
| isvalid param present | (!_ev_is_present(value)) |
— |
| isvalid handle or ref | (this->head->next == nullptr) |
— |
| isvalid value optional | (this->head->next == nullptr) |
— |
IrPanic — a PANIC of an Error subclass
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| throw stmt | throw <Class>(<args>); |
— |
IrTry — a TRY with its RECOVER and FINALLY clauses
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| entry main | try {\n /* body */\n} catch (const <E>& <name>) {\n /* catch */\n} |
— |
| try catch | try {\n /* body */\n} catch (const <E>& <name>) {\n /* catch */\n} |
— |
| try catch clause | try {\n /* body */\n} catch (const <E>& <name>) {\n /* catch */\n} |
— |
| try catch finally | try {\n /* body */\n} catch (const <E>& <name>) {\n /* catch */\n} |
— |
| try finally | try {\n /* body */\n} catch (const <E>& <name>) {\n /* catch */\n} |
— |
IrAssert — an ASSERT / ASSERT! programmer-error check (halts on failure)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| assert statement | if (!(n == 5)) { std::abort(); } // message elided |
I.M |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrRecover— aRECOVERclause, lowered within itsIrTry.Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrReportUncaught,IrUnreachable.
IrConcurrent — a CONCURRENT structured-scope block (RAII join-before-unwind)
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| concurrent scope | {\n ENVZN::_ev_scope __ev_scope_N;\n /* body (PARALLEL → __ev_scope_N.spawn) */\n} |
— |
IrParallel — a PARALLEL task launch within a CONCURRENT scope
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| parallel spawn | __ev_scope_N.spawn([&]() {\n /* task body */\n}); |
— |
| parallel unreachable | __ev_scope_N.spawn([&]() {\n /* task body */\n}); |
— |
IrSynchronized — a SYNCHRONIZED(lock) critical section
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| sync target owned | {\n std::lock_guard<std::mutex> __ev_sync_1(this->lock->_native);\n /* body */\n} |
— |
| sync target self | {\n std::lock_guard<std::mutex> __ev_sync_N(<mutex>._native);\n /* body */\n} |
— |
| synchronized block | {\n std::lock_guard<std::mutex> __ev_sync_N(<mutex>._native);\n /* body */\n} |
— |
| sync target expr | {\n std::lock_guard<std::mutex> __ev_sync_N(<mutex>._native);\n /* body */\n} |
— |
| sync target handle | {\n std::lock_guard<std::mutex> __ev_sync_N(<mutex>._native);\n /* body */\n} |
— |
| sync target param | {\n std::lock_guard<std::mutex> __ev_sync_N(<mutex>._native);\n /* body */\n} |
— |
IrClass — a CLASS declaration — fields, methods, layout, and destructor
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| kernel fwd class | class String; |
— |
| namespace block | ['namespace IntUtil {'] |
— |
| namespace forward decl | inline bool isUpper(char32_t c); |
— |
| parent base lowered | Hasher<K> |
— |
| singleton instance decl | inline _Math Math; |
— |
IrNamespace — a NAMESPACE — a stateless host of free functions plus CONSTANT data; lowers to a C++ namespace
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| namespace | namespace Math { inline float64 sqrt(...); ... } |
I.J.ii.d |
IrInterface — an INTERFACE declaration — pure-virtual method signatures
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| interface ret reference | (emits — first-gen C++ not captured for this row) |
— |
IrStruct — a STRUCT — a public-field data record with generated construction
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| class destructor | ~File() { |
— |
| kernel fwd struct | struct STATUS; |
— |
| struct pod alias | using DateTimeFields = ::_EV_ENVZN_DateTimeFields; |
— |
| struct pod global | ['struct _EV_ENVZN_DateTimeFields {'] |
— |
| class destructor call | (emits — first-gen C++ not captured for this row) |
— |
IrGroup — a GROUP — a tagged set of named constants
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| decls group forward | (emits — first-gen C++ not captured for this row) |
— |
| group decl | (emits — first-gen C++ not captured for this row) |
— |
IrEnum — an ENUM declaration and its cases
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| enum declaration | enum class Color : int32_t { RED, GREEN, BLUE }; |
I.K.viii |
IrMethod — a method definition — signature, body, MODIFY/const, OVERRIDE
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| method sig reference | (emits — first-gen C++ not captured for this row) |
— |
IrParam — a parameter — plain (owns), REFERENCE, MUTABLE REFERENCE, or variadic
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| variadic opaque | ENVZN::EvArray<<elem>> <name> |
I.I.vi, II.N |
| variadic | std::initializer_list<<elem>> <name> |
I.I.vi, II.N |
| value class, REFERENCE | const <Class>* <name> |
I.I.vi, II.N |
| blittable struct, plain | <type> <name> |
I.I.vi, II.N |
| value class, plain | <Class> <name> |
I.I.vi, II.N |
| value class, MUTABLE REFERENCE | <Class>& <name> |
I.I.vi, II.N |
| brace, MUTABLE REFERENCE | <type>* <name> |
I.I.vi, II.N |
| brace, REFERENCE | const <type>* <name> |
I.I.vi, II.N |
| heap class, plain | <owner><<Class>> <name> |
I.I.vi, II.N |
| heap class, MUTABLE REFERENCE | <Class>* <name> |
I.I.vi, II.N |
| heap class, REFERENCE | const <Class>* <name> |
I.I.vi, II.N |
| cxx reserved | <type>& <name> |
I.I.vi, II.N |
| array, MUTABLE REFERENCE | <type>* <name> |
I.J.i, II.N |
| array, REFERENCE | const <type>* <name> |
I.J.i, II.N |
| primitive scalar, plain | <type> <name> |
I.I.vi, II.N |
| call arg parametric adopt clone | _ev_adopt_clone<T>(value->clone()) |
— |
| call arg parametric move | std::move(key) |
— |
| interface param template | const K& key |
— |
| arg deref into ref param | (emits — first-gen C++ not captured for this row) |
— |
| call arg parametric constref clone | (emits — first-gen C++ not captured for this row) |
— |
| init param array mutable | (emits — first-gen C++ not captured for this row) |
— |
| init param brace | (emits — first-gen C++ not captured for this row) |
— |
| init param brace mutable | (emits — first-gen C++ not captured for this row) |
— |
IrField — a data field — owning, REFERENCE, SHARED MUTABLE REFERENCE, or CONSTANT
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| class field strong smr | _ev_shared<WorkerPoolCore> core{}; |
— |
| cpp name field rename | start |
— |
| field recv pointer | h.left->left |
— |
| field var refvar | n.key |
— |
| struct pod field | int32_t day; |
— |
| auto clone optional field | (emits — first-gen C++ not captured for this row) |
— |
| call arg byref self field | (emits — first-gen C++ not captured for this row) |
— |
| class field foreign | (emits — first-gen C++ not captured for this row) |
— |
| class init field fixed array | (emits — first-gen C++ not captured for this row) |
— |
| field self narrowed handle | (emits — first-gen C++ not captured for this row) |
— |
| field self narrowed optional class | (emits — first-gen C++ not captured for this row) |
— |
| field self narrowed value optional | (emits — first-gen C++ not captured for this row) |
— |
| string arg field clone | (emits — first-gen C++ not captured for this row) |
— |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrMethodSig— a pure-virtual signature, lowered within itsIrInterface.Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrUnion,IrMain,IrMainArgv,IrThreadEntry.
IrForeignExpr — an inline FOREIGN expression block
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| inline foreign block (expr) | 42 // inline FOREIGN block: cpp_text emitted verbatim into the expression |
I.N |
IrForeignStmt — an inline FOREIGN statement block
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| foreign block stmt | // <verbatim C++ from the FOREIGN { ... } block, emitted unchanged>\nENVZN::_throw_string_oob("ByteBufferView: range out of bounds"); |
— |
IrForeignBind — a FOREIGN BIND to a C function — a typed FFI call
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| foreign bind (C function) | // no decl emitted; use sites lower to a direct (::ev_probe_fn)(args) call |
I.N |
IrForeignConstant — a FOREIGN BIND to a C constant
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| foreign bind constant | PROBE_CONST // bound int32; resolved via a generated link-time macro-shim symbol |
I.N |
IrForeignTypeBind — a FOREIGN_TYPE BIND to a C struct or opaque handle
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| foreign type bind (opaque handle) | using ProbeHandle = void*; // newtype over opaque; concrete form -> <cpp_type> * |
I.N |
IrUnsafe — an UNSAFE { } block gating raw-handle access
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| unsafe block | {\n /* UNSAFE body — no runtime guard */\n} |
— |
IrSnapshot — a SNAPSHOT debug capture of a value
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| snapshot array | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot block | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot class recurse | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot collection | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot handle | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot primitive | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
| snapshot text | ENVZN::_ev_snapshot(<var>); // -debug only |
— |
IrStacktrace — a STACKTRACE debug statement
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| stacktrace stmt | ENVZN::_ev_stacktrace(); // -debug only |
— |
Defined in the IR, lowering not yet spec-traced (node present in
compiler/evir/nodes.py; seecompiler/evir/emitter.pyfor current emission):IrBinding.
ResolvedType — the resolved type a node carries — primitive, class handle, value-array, or collection
| Variant / concept | C++ lowering | Const. |
|---|---|---|
| scalar | int8_t |
I.D.i, II.N |
| scalar | int32_t |
I.D.i, II.N |
| scalar | int64_t |
I.D.i, II.N |
| scalar | double |
I.D.i, II.N |
| scalar | bool |
I.D.i, II.N |
| scalar | char32_t |
I.D.i, II.N |
| scalar | uint8_t |
I.D.i, II.N |
| numeric group | EvNumeric |
I.J.v, II.N |
| named group | EvGroup_<Name> |
I.J.v, II.N |
| fixed dim, int literal | <N> |
I.J.i, II.N |
| fixed dim, named const | <DIM_NAME> |
I.J.i, II.N |
| SHARED CLASS owner | _ev_shared |
I.I.ii, II.N |
| default owner | _ev_unique |
I.I.ii, II.N |
| UNSAFE.HANDLE/MUTEX/CONDVAR | <_UnsafeHandle<T>> |
I.I.viii, I.D.v, II.N |
| SBO inline array | ENVZN::EvArray<<elem>, <N>> |
I.J.i, II.N |
| fixed single-dim array | ENVZN::EvArray<<elem>> |
I.J.i, II.N |
| multi-dim fixed array | std::array<<elem>, <N>> |
I.J.i, II.N |
| qualified array | ENVZN::EvArray<<ns::Name>> |
I.J.i, II.N |
| optional module class | <owner><<ns::Name>> |
I.K.i, I.N, II.N |
| optional module struct | std::optional<<ns::Name>> |
I.J.iv, II.N |
| module struct | <ns::Name> |
I.J.iv, I.N, II.N |
| module class | <owner><<ns::Name>> |
I.K.i, I.N, II.N |
| set iterator | ENVZN::_cxx_setiter<<inner>> |
— |
| map iterator | ENVZN::_cxx_mapiter<<K>, <V>> |
— |
| reserved type | <CXX_RESERVED_TYPES[name]> |
— |
| void | void |
I.K.vi, II.N |
| unbounded array | ENVZN::EvArray<<elem>> |
I.J.i, II.N |
| optional class | <owner><<Class>> |
I.D.iv |
| optional interface | <owner><<Interface>> |
I.D.iv |
| optional template param | _ev_optional_t<<T>> |
I.D.iv |
| optional primitive | std::optional<<inner>> |
I.D.iv |
| status | _EvStatus |
I.M.i, II.N |
| value class | DynamicString |
I.D.vi, I.K.i, II.N |
| heap class | <owner><<Class>> |
I.I.i, I.I.ii, I.K.i, II.N |
| fallback | <name> |
I.D.ix |
| class name, parametric | <Base><<args>> |
I.I.i, I.I.ii, I.K.i, II.N |
| class name | <Base> |
I.I.i, I.I.ii, I.K.i, II.N |
| array elem, parametric class | <Name><<args>> |
I.J.i, II.N |
| array elem, class | <Name> |
I.J.i, II.N |
| reference to class | const <Class>* <name> = <src>.get() |
I.I.iv, I.I.v, II.N |
| reference to T | <const? >_ev_underlying_t<<T>>* |
I.I.iv, I.I.v, II.N |
| reference generic | <const? ><lowered>* |
I.I.iv, II.N |
| ndarray | ENVZN::EvNdArray<elem, RANK, MODE, Dims…> (one selector: ev_is_blittable_v<elem> picks _NdArray vs _NdObjectArray; the Dims pack picks fix… |
I.J |
Sub-nodes (structural components, lowered as part of their parent — no standalone form):
IrDrop— a scope-exit drop, emitted implicitly by the C++ destructor (RAII);IrSynchRelease— a lock release, emitted implicitly by_ev_lock_guard; a// IrSynchRelease <id>comment, as IrDrop is;IrCleanupPad— an unwind-path drop set, cleared before emit alongside IrDrop;IrCatchClause— a catch test on a pad row, lowered within itsIrCleanupPad.
Curated narrative — not generated from the TSV. Section A specifies the EvIR node set and Section B records the per-node C++ mappings. This section explains the lowering model those mappings sit inside: the compilation pipeline, the ownership-handle representation, the statement and abstraction lowering, concurrency, the foreign-function boundary, the generated entry point, diagnostics, and kernel-build facts. It carries the narrative that was Article II of the constitution before the EvIR specification was split into this document.
The canonical compiler is a linear pipeline from Envzn source to a native executable. Source text is first tokenized into a stream of tokens carrying position information. The token stream is then parsed, by recursive descent, into an abstract syntax tree. The tree is then analyzed — the analyzer resolves types, checks the move and lock and reference rules, and verifies interface satisfaction, and it is the analyzer's passes, rather than any separate tool, that serve as the language's lint layer. The analyzed tree is then built into EvIR (build_ir) and the EvIR is emitted as C++20 (compiler/evir/emitter.py). The emitted C++ is finally handed to the backend, which invokes clang++ with -std=c++20 to produce the executable.
Around that per-translation-unit pipeline sits the module driver, which performs the work C.vi describes. It loads manifests, resolves dependencies in topological order, merges a module's source files into one compilation unit, emits the combined C++, and invokes the backend with the dependent libraries linked. All diagnostics are reported before C++ emission is attempted, so that a downstream C++ error never obscures an Envzn one. The canonical compiler is the Python implementation under bin/; a second, trimmer compiler and an in-progress self-hosted compiler exist, and where they diverge from the canonical one the divergence is treated as catching-up work, not as a second opinion.
The primitive types lower to fixed-width C++ types. The signed and unsigned integers from 8 to 64 bits become the <cstdint> exact-width types. The 128-bit int128 and uint128 lower to the compiler built-ins __int128 and unsigned __int128, which need no header. No libc path renders or parses a 128-bit integer, so the kernel does both through a hand-rolled decimal-and-base conversion. float32 and float64 become float and double, boolean becomes bool, and byte and binary become uint8_t. The char family lowers as three distinct C++ types, deliberately not C++'s 8-bit char — char8 becomes char8_t, char16 becomes char16_t, and char32 (the canonical name char resolves to) becomes char32_t. A character literal lowers to a UTF-32 literal, so 'a' emits as U'a'. These aliases are emitted at global scope rather than inside the kernel namespace, because they are language-level primitives and a developer expects int32 to mean the same thing in every module.
A class type lowers to a heap allocation reached through an owning handle. The default owning handle is _ev_unique<T>, a non-copyable smart handle: its non-copyability at the C++ type level is what makes an accidental second owner a compile error in the emitted code, not merely in the analyzer. The allocation is split in two — a separate T allocation and a small separate control block, _ev_ctrl<T>, of roughly a dozen bytes. The control block carries an atomic alive flag, an atomic weak_count, and an atomic strong_count. The alive flag records whether the T is still valid. The weak_count counts the _ev_weak<T> observers, each incrementing it on construction or copy and decrementing it on destruction. The control block is freed only when that count reaches zero, which guarantees no observer ever reads a deallocated control block. Every class owner is a _ev_unique<T> except the owner of a SHARED CLASS instance, which is the first strong count of an intrusive _ev_shared<T>: a one-word handle to the object, with the atomic strong count in the 8-byte word at obj − 8 and the allocation made and freed at obj − 8 (so a SHARED layout may need at most 8-byte alignment — E3049). It is copyable: a copy or an IrShared bind adds a count, a drop removes one, and the last drop destroys the object. Only a declared SHARED CLASS is ever shared, and nothing is promoted: the count keeps the referent alive as a runtime backstop, while its lifetime is still proven at every construction site (E3048, I.I.i(b)). Primitives, String, STATUS, enum cases, and STRUCT fields are value types and are emitted inline. Stack-frame exit releases owned heap objects in reverse declaration order through the ordinary RAII chain.
A REFERENCE T and a MUTABLE REFERENCE T lower to raw C++ pointers — T const* and T* respectively — and carry no control block and no reference count. This is sound precisely because the reference checker of I.I.v has already proved, at compile time, that the reference cannot outlive its referent and cannot alias a conflicting access. The runtime therefore needs no check, and a reference costs exactly a pointer. The exception is the SHARED MUTABLE REFERENCE field, which lowers to a strong _ev_shared<T> that co-owns its SHARED CLASS referent; its =@ bind lowers through IrShared, a new strong count taken on the borrowed object. Reference parameters never escape, so they are always borrows. The three parameter modes of I.I.vi lower as follows:
plain T — own |
REFERENCE T — read |
MUTABLE REFERENCE T — write |
|
|---|---|---|---|
blittable non-class — primitive (including the class-backed binary, complex, number, decimal128), enum, STATUS, blittable STRUCT |
T by value |
const T& |
T& |
heap class, interface, String, ByteBuffer |
_ev_unique<T> by value (call site emits std::move) |
const T* |
T* |
array — T[], T[N], T[N+], N-D |
the container by value, moved | const EvArray<…>* (resolves _ValueArray or _ObjectArray per element) |
EvArray<…>* |
| value class, blittable or not | T by value, moved |
const T* |
T* |
type parameter T |
T by value — at a class instantiation T is _ev_unique<X> |
_ev_borrow_t<T> |
_ev_mut_borrow_t<T> |
A LAMBDA-typed parameter is plain only. A FOREIGN parameter follows the C ABI (I.N) and a conversion's FROM source is a read (I.D.viii); neither takes a mode.
Owning is a sink parameter. The own column hands the callee the value itself: a unique handle, a container, or a blittable copy, all by value. A raw T* would hide ownership from C++ and leak if a PANIC unwinds before the callee stores it; T&& would bind the object, but a heap object lives behind its handle. The unique handle by value is C++'s idiomatic sink: its destructor covers every exit, unwind included. For a blittable type ownership is a copy, which by value carries in registers.
A borrow is a raw pointer, not an owning handle. An earlier ABI passed a class parameter as const _ev_unique<T>& — an owning handle by const reference — which is a category error: a borrow does not own what it observes. It made legal programs uncompilable, because the only upcast on an owning handle is a move, which a borrow must not perform. A raw pointer upcasts implicitly, binds a borrowed referent, and keeps EMPTY representable as nullptr, so IS VALID still works and the memory-safety floor of I.A is not traded away. Every class borrows by pointer, a value class included; only a non-class blittable borrows by C++ reference, because it has no EMPTY state to represent and a reference needs no address-taking at the call. The rule keys on whether the type is a C++ class, which is decidable on an incomplete type — and an interface slot is instantiated inside its implementer's own base clause (Money IMPLEMENTS Equatable OF Money), where the implementer is incomplete.
The mode decides const-ness, not the type. A REFERENCE is const and a MUTABLE REFERENCE is not, for every type. _ev_borrow_t<T> and _ev_mut_borrow_t<T> resolve the type-parameter row per instantiation — const X* / X* for an owning handle _ev_unique<X> or any other class, const T& / T& for a non-class or a class-backed primitive — which is exactly what the concrete rows give. So an interface slot and its implementation, declaring the same mode (I.I.vi(a.iii)), spell the same C++ type by construction.
Most expressions lower directly. The arithmetic and comparison operators become their C++ equivalents, as do the keyword bitwise, shift, and boolean operators. A derived operator — one a type gained by implementing an operator interface of I.K.iv — lowers to a call of the interface method the compiler derived it from. A CREATE lowers to a heap allocation through _ev_unique<T>, followed by the matching INIT call. A := move lowers to a C++ move of the handle; a = value copy to direct initialization, or to the explicit CREATE or clone() the source contained; and a =@ reference to taking the address of the place expression.
A STATUS lowers to the _EvStatus struct, which carries the outcome, a message String, and an int32_t code defaulting to 0. The pipe-XOR shape of I.M lowers to a C++ std::tuple of the success slots followed by the trailing _EvStatus — RETURNS (A a, B b | STATUS s) becomes a std::tuple<A, B, _EvStatus>. The consumption form lowers to an if whose condition tests the tuple's _EvStatus slot, with the result tokens resolving to std::get reads of that temporary: $=[i] is std::get<i>(temp), $# is std::get<status_idx>(temp).code, and $! is std::get<status_idx>(temp).message. MATCH lowers according to its subject — an enum or GROUP to a switch or std::variant visitation, a possibly-EMPTY value to a presence test over its two arms, and a condition-form MATCH to an if/else if chain.
FOR IN lowers by the shape of the iterable, in two forms that share one surface. A class collection or a user class implementing Iterator OF T takes the iterator form: a loop FOR T x IN coll { body } becomes, in effect, an owned iterator obtained from coll->iterator(), a WHILE over hasNext(), and a per-iteration next() whose pipe-XOR result binds x as a non-owning reference into the collection:
{
Iterator OF T _it := coll->iterator()
WHILE _it->hasNext() {
IF _it->next() THEN {
REFERENCE T x =@ $=
body
} ELSE {
PANIC Error("FOR/IN invariant: next() yielded a failure after hasNext() was true")
}
}
}
A raw array — T[], T[N], or T[N+], as distinct from the Array[T] wrapper class — takes the index form instead. The loop is driven by an index over the array buffer, with the loop variable bound to a borrow pointer into that buffer, and the iterable expression evaluated exactly once (it may be side-effecting). The reason is that the shared loop body is lowered for a REFERENCE variable it dereferences, for every element kind including value elements, and a value array's by-value next() cannot hand back a stable pointer to dereference. The two forms are not observably different to a program: both visit every element in order and bind a non-owning reference to it.
The implicit iterator of the first form is owned by the loop and dropped at loop exit, and that lowering serves a kernel collection and a user class that implements Iterator OF T alike. As an optimization with no observable effect, the compiler may inline the iterator's method bodies in place of virtual dispatch when the static type of the implicit iterator resolves to a FINAL CLASS. A program may not depend on whether the inlining fires.
The IDENTITY(subject) reflection intrinsic (I.K.iii(e)) lowers to an IrStaticValue: a compile-time-constant value built once and read by reference (serde design §4.2 A13). The analyzer computes the Identity field values from the subject's static type and binding. The IR builder synthesizes an IrCreate of the kernel STRUCT Identity, whose arguments are those values as literal nodes — IrStringLit, IrBoolLit, IrIntLit, IrArrayLits of the nested IdentityField / IdentityMethod / IdentityParameter constructions — and wraps it as the IrStaticValue's value. Its key is a hash of the facts alone (no span, no node id, no file), so equal values written at two sites or in two modules name one instance. The expression is a read-only borrow of that instance: an owning edge (Identity id := IDENTITY(P), String n := IDENTITY(P).name) is given an IrDuplicate by the IR builder, exactly as a CONSTANT read is, so no backend ever moves out of it. The C++ backend emits one guarded inline accessor holding a function-local static per key and file; the LLVM form is a linkonce_odr constant.
A format call's arguments (I.F.vi) are FormatArguments. Before the full analysis runs, the analyzer rewrites each argument of a FormatArgument... parameter into CREATE FormatArgument(arg), and a String or DynamicString format/formatWith call into Formatter.format(text, …). Ordinary overload resolution then picks each INIT, so a scalar or text argument is an IrCreate carrying its init_symbol. A literal resolves by its type alone (an int64, a float64). A value class is decided there too: its toString() text if it implements Formattable, else FormatKind.UNKNOWN. The IR builder packs the tail into one IrArrayLit typed FormatArgument[]. A HANDLE argument (a class or interface object, a FOREIGN_TYPE pointer, an array, EMPTY) has no INIT; it lowers to an IrFormatObject, whose outcome — ABSENT, FORMATTABLE or UNKNOWN — is decided at run time. tests_object is false when no object can implement Formattable (a FOREIGN_TYPE pointer), so only the null test is made and the pointer is never borrowed.
A class lowers to a C++ class. Its data fields become members and its methods become member functions. The MODIFY distinction of I.K.vi lowers to the C++ const qualifier: a read-only Envzn method emits as a const member function, a MODIFY method as a non-const one. The const-correctness Envzn enforces at its own level is thereby carried into the emitted code. INIT becomes a constructor and CLEANUP, together with the field-destruction chain, becomes the destructor. FINAL emits the C++ final specifier, which both forbids subclassing and lets the C++ compiler devirtualize and inline calls — the mechanism behind the optional iterator inlining of C.iii.
An interface lowers to an abstract C++ class of pure virtual functions, and a class that implements one gains a vtable. A call through an interface-typed reference is an ordinary virtual call — one pointer indirection — and that is the whole runtime cost of the polymorphic collections of I.K.vii. A GROUP lowers to a std::variant over its member types; a group member that recurses through Box lowers that Box to a _ev_unique indirection, which is what breaks the otherwise self-referential variant. An enum lowers by form: a simple enum to a C++ enumeration, a raw-value enum to one carrying its primitive values, and an associated-value enum to a tagged representation that a MATCH destructures.
The library aggregates are implemented internally with C++ templates, which is how Envzn offers parameterized collections without exposing user-defined generics. Array[T] backs onto the T[] storage primitive — its INTERNAL T[] data field lowers to EvArray<T>, which resolves the _ValueArray<T> value-array for a blittable T and the _ObjectArray<_ev_unique<T>> object-array for a class T. An array literal lowers to a C++ brace-init {…} for a value-element array, since _ValueArray has an initializer_list constructor. A non-empty object-element array literal cannot: an array of move-only owning handles has no initializer_list form. It lowers instead through the free factory _ev_object_array_of(e0, e1, …), which move-appends each element onto a fresh _ObjectArray through its existing grow-assign. An empty literal is a plain {} for either backing. Dictionary is a pure INTERFACE Dictionary[K, V, H] with pure-Envzn implementations behind it (ChainedHashDictionary, RedBlackTreeDictionary, ProHashDictionary); the compiler no longer special-cases it, and hashing is pluggable through the H (Hasher) type parameter rather than a C++ functor. Set[V, H] is likewise a pure-Envzn class wrapping a Dictionary, so neither Set nor Dictionary backs onto a C++ unordered container. The iterators the collections hand out are concrete FINAL classes, one per collection, and their FINAL-ness is what permits the loop-body inlining of C.iii.
CONCURRENT { … } lowers to a structured task scope — an _ev_task_scope RAII object over the block body that joins every task it launched before it unwinds. A PARALLEL { … } block lowers to a task launched on a std::thread registered with the innermost enclosing scope, and the task body emits as the callable the thread runs. The capture restrictions of I.L.vii are enforced in the analyzer before emission, so the emitted lambda captures only what the model permits. SYNCHRONIZED(lock) { … } lowers to a std::lock_guard over the lock's native mutex, held for the body and released automatically on every exit path — fall-through, RETURN, BREAK, or a PANIC unwinding through it.
Channel[T] lowers to a typed, bounded message queue with its synchronization state; MessageBroker[T] to the lock-free publish-index-and-per-subscriber-ring structure of I.L.iv; Mutex[T] to a mutex guarding interior storage reachable only inside its SYNCHRONIZED block; Future[T] to an eventually-ready cell sharing the pipe-XOR consumption shape; Atomic[T] to a std::atomic over the primitive width; and WorkerPool[T] to the kernel's pool class built over those primitives. The low-level synchronization primitives the kernel needs — a mutex, a condition variable, an atomic, a raw thread handle — are not expressible as ordinary Envzn classes, because the underlying C++ standard-library types delete their copy and move operations. The kernel reaches them through the FOREIGN_TYPE BIND mechanism of C.vi, as a small family of _cxx-prefixed types: _cxxmutex, _cxxcondvar, _cxxatomic[T], _cxxrawthread. Each binds the corresponding C++ standard type by value, and each emits its parameters by reference rather than by value, precisely because those C++ types cannot be copied.
Each module's emitted C++ is wrapped in a namespace. A non-kernel module emits as namespace modulename { using namespace ENVZN; … }, and the using directive is what lets kernel types keep their bare names inside the module's emitted code. The kernel itself emits inside namespace ENVZN, with the one exception of the primitive numeric aliases, which stay at global scope as C.ii records. The module driver compiles a module in five steps. It loads the manifest for identity, target, dependencies, and foreign metadata. It resolves and recursively compiles the dependencies in topological order. It merges the source files into one compilation unit, where a duplicate type name across two files is an error. It emits the combined C++, and invokes clang++ -std=c++20 with the dependent libraries linked. An executable target produces a binary, and the compiler appends a generated int main() under the rules of C.vii. A shared_library target produces a .dylib together with a generated .headers file that lists every public, non-INTERNAL declaration and so forms the authoritative public surface a dependent compiles against.
The foreign-function boundary lowers as follows. A FOREIGN BIND declaration of a C function is type-checked against its Envzn signature alone; the compiler never reads C header content. In the ordinary case it lowers to a direct call of the bare C symbol, so a binding named open lowers FOREIGN::open(...) to (::open)(...). The parentheses are there so that a C function-like macro of the same name — macOS defines sigaddset both ways — cannot intercept the call: a macro expands only when its name is followed directly by (. The compiler synthesizes the conversion at each boundary type. Three markers change the lowering. The LOAD parameter modifier declares a value-array parameter write-through, so the C function writes through the storage pointer. A binding marked SETS_ERRNO(sentinel) emits a wrapper that turns an errno into a STATUS FAILURE, making it a pipe-XOR producer. A return marked $*, or $(freer()), emits a wrapper that copies the returned C string and frees the raw pointer, so the free is compiler-generated and inseparable from the call. FOREIGN is an Envzn-side greppability marker only — no FOREIGN C++ namespace is emitted. Every type at the boundary is an Envzn type mapped to the C ABI by a fixed table:
| Envzn type | C ABI type | Boundary behavior |
|---|---|---|
int8 … int64, uint8 … uint64 |
int8_t … uint64_t |
direct |
float32 / float64 |
float / double |
direct |
boolean |
bool |
direct |
byte |
uint8_t |
direct; a single C char binds as byte |
String (parameter) |
const char* |
a scoped, NUL-terminated buffer that lives exactly as long as the call |
String (return) |
const char* |
copied into a fresh String; a null result becomes EMPTY |
ByteBuffer (parameter) |
element pointer + a separate uint64 length |
Envzn-owned; the C side borrows it for the call |
opaque |
void* |
an opaque handle the Envzn side stores and passes back but never dereferences |
an Envzn STRUCT |
the compiler-emitted struct, by value | every field must transitively be a boundary type |
ByteBuffer is parameter-only: RETURNS ByteBuffer is a compile error, because a single C return value cannot carry both a pointer and a length. A C library struct — struct stat, struct sockaddr — has a layout fixed by system headers, and never crosses the boundary. A C function that needs one is reached through a module-supplied native shim, which speaks only boundary types in its own signature. FOREIGN BIND CONSTANT binds a single integer macro (e.g. O_RDONLY) through a small C shim that re-exports it as a named symbol. The LOAD shape table and the boundary rules are Article I.N(h) of the Constitution; the manifest conventions and the V2 boundary extensions are outside this spec.
Every executable module names one entry class, and the compiler generates the main() that runs it. The manifest names it in its entrypoint key, written in full as <module>::<Class>::start: the module part must be the manifest's own name, and the method is always start. A shorter <Class> or <Class>::start is accepted with a warning. For a program that takes arguments the key is an object, { "start": …, "options": { … } }, optionally with commands and after-double-dash (Constitution, "Manifest keys: the entrypoint block"). entrypoint.json is retired and never read. Each of the following is a compile error: an executable module without the key, a shared-library module with it, a malformed key, a method other than start, a module part that is not this module, or a named class that does not exist, implements neither starter interface, or declares an INIT.
"entrypoint": "hello::Hello::start"
The entry class implements one of two interfaces. TaskStarter is the single-method interface — METHOD start() RETURNS STATUS — that the program's main thread and every spawned worker thread share; a program in this form ignores its command line. TaskStarterWithOptions OF T has METHOD start(REFERENCE T options) RETURNS STATUS, where T IMPLEMENTS TaskStarterOptions. For it, the compiler writes three members on T from the manifest's options block — describe, load and forwarded — and one on the entry class, entryRun(REFERENCE String[] argv) RETURNS int32. That member creates T, fills it through the kernel's EntryOptions[T].fill, and calls start. They are ordinary Envzn source, analyzed and lowered like any method. The entry class declares no INIT: the runtime constructs it, so nothing runs before start() except argument parsing the program declared.
The IrMain node carries one flag, takes_options. Without it, the generated int main() constructs the entry class, calls start(), and translates the returned STATUS to a POSIX exit code: SUCCESS to 0, PARTIAL_SUCCESS and FAILURE to 1. With it, main() builds a String[] from the operating system's argv, constructs the entry class, and returns entryRun(&argv): 0 after --help, 2 for a command line the options reject (the problem and the usage on standard error), and otherwise start()'s STATUS mapped as above. The whole sequence is wrapped in a C++ try with three narrowing catch arms: Envzn's Error first, then std::exception, then a catch-all. Each writes a diagnostic to standard error and exits 1, so an uncaught exception produces a message rather than a silent std::terminate.
The compiler detects errors at every stage of the pipeline, and the stage at which an error is found determines both its category and how the compiler recovers from it well enough to keep finding more.
| Stage | Category | Recovery |
|---|---|---|
| Tokenization | lexical errors — an unterminated quote, an invalid escape | skip to the next line |
| Parsing | structural errors — an unexpected token, a malformed header | panic-mode resynchronization to the next statement boundary |
| Analysis | type errors — a mismatch, an undefined name, an unimplemented interface | report and continue with the other declarations |
| Analysis | move, lock, and reference errors — a use after move, a mutation under an iterator lock | report, and suggest a clone() or a lock scope where one is clear |
| Emission | code-generation errors — an unsupported construct | report; emit a stub where possible |
Every diagnostic carries four things: a source location of file, line, and column; an error level, either error, which blocks compilation, or warning, which does not; a quoted snippet of the offending line with a caret beneath the span; and, where the fix is clear, a suggestion. A diagnostic is identified by a stable E#### code, and the codes named throughout Article I are those identifiers. All errors are reported before C++ emission is attempted, so that a downstream clang++ error cannot mask the Envzn error that caused it.
A location is a range, not a point: start_line/start_col and end_line/end_col, 1-based and counted in Unicode code points. A point is the degenerate range whose end equals its start, so a diagnostic that knows only where a problem begins is expressible without a second shape. The frame is drawn only where the source is readable and the column is known; where either is missing the diagnostic prints its location line alone rather than a partial frame, because a diagnostic must never fail while reporting a failure. The caret is placed by display column — a tab advances to the next multiple of eight, and an East-Asian Wide or emoji glyph occupies two cells — which is not the stored column on any line containing either.
Where a single literal edit resolves the diagnostic, it is offered as a help: line beneath the remedy, and the same edit is machine-applicable. Most diagnostics have none, and that is the expected outcome: the remedy for a type error or a missing contract is a decision, not a substitution.
error [E1174] parse:numeric-literal-malformed: `0x` must be followed by hex digits
╭─ examples/hello.ev:6:19
6 │ int32 h = 0x
│ ^
╰─
at examples/hello.ev:6:19
help: replace with `0x1F`
The same diagnostics are available as machine-readable records under --diagnostics=json, shaped as LSP Diagnostic objects — 0-based lines and UTF-16 character offsets, with any fix carried as a TextEdit. Everything Envzn-specific is namespaced under evzn. in the record's data field, which LSP defines as opaque passthrough, so an editor consumes the stream without a translation layer. The document is always emitted, even when empty, so a consumer can distinguish a clean build from a compiler that stopped before it could report.
The kernel — the ENVZN module — is compiled as a shared library that every Envzn program links against. It publishes a single canonical header, which the generated C++ of every module includes.
The kernel is authored as Envzn source — roughly one hundred ten .ev files — and the compiler emits from them a per-class header apiece, alongside the hand-written floor and its native glue, all of which the canonical header includes. This is the result of the demagic effort, a staged project to replace hand-written C++ kernel class bodies with emitted ones. A collection or utility that was once a block of C++ in the kernel header is now an ordinary .ev file the compiler lowers like any other. The canonical header retains only the host runtime glue that genuinely cannot be authored in Envzn — the formatting and hashing helpers, the four-form String and Binary primitive machinery, and the low-level _cxx* concurrency types of C.v. The kernel holds to one hard rule: it has no dependency on any external package, and an optional system dependency — OpenSSL, SQLite, a regex library — belongs in the module that consumes it, never in the kernel.
End of specification. Section A specifies 108 EvIR nodes in 14 groups; Section B records 519 TSV-traced lowering rows; Section C is curated narrative. Regenerate Sections A and B with the spec-spec generator.
Envzn 0.8
Run evc --version for the compiler's version; the tables below list every component's.
0.8 names the language package as a whole: the compiler,
the intermediate representation, the kernel and the standard library, shipped
together and tested together. Every component inside carries its own version and
they move independently, because they are developed independently: a fix to the
JSON parser is not a new compiler.
The compiler, the EvIR and the kernel can each change on their own, but they are fundamentally in sync: the compiler emits an EvIR the kernel's headers expect, and a mismatch between any two of them is a defect rather than a configuration. They are versioned separately so a change can be described precisely, not so they can drift apart.
| Component | Version | What it is |
|---|---|---|
Compiler (evc) |
6.3.0+56e | The canonical compiler. Its own lineage, independent of the release number. |
| EvIR | f4bd86e2f3cb3904 (schema hash) |
The serialized intermediate-representation format, named by its schema hash, which moves exactly when the format does. |
Kernel (ENVZN) |
8.1.4+264 | Text, collections, math, time and I/O — what every Envzn program rests on. |
Each module is versioned by its own manifest and released with the package.
| Module | Version |
|---|---|
Data |
2.1.4+5d |
Json |
3.0.2+2c |
Logger |
0.2.5+1a |
Networking |
2.0.8+45 |
Regex |
1.0.3+1e |
diagnostics |
2.11.0+1a |
epm |
3.8.1+8b |
evTest |
0.1.6+12 |
mda |
0.2.0+e |
Module manifests also carry a language_version — currently 2.0. That is an
edition marker, in the sense Rust means by edition = "2021": it states which
level of the language a module is written against, so the compiler knows how to read
it. It is not a maturity claim and is unrelated to the release number above.
Copyright © 2026 The Data Science Group, LLC.
A new systems programming language
By Brian Haughton
Oct 12, 2026
Envzn (https://envzn-lang.org) has been recently released in beta as a new modern systems programming language; at the time of this writing, it is still in development. It was designed to be memory safe from the start.
Much has been written about memory safety lately1 and it seems the volume has been turned up since many large companies decided to publicize that they are writing systems and programs in Rust. For example, Microsoft2 and Chromium3 each found that about 70% of their serious security bugs were memory-safety errors, and Google reports that Android’s share fell from 76% to 24% as new code moved to Rust.4
In designing Envzn, I considered the memory model for Java5, Go6, Rust7, C++8, and many other mainstream languages. I felt that Rust’s borrow checker was a definite step forward and found it inspiring. Rust’s hybrid model of proving lifetimes at compile time, but checking most boundaries at run time9, seems to be the honest path forward.
Many languages were designed under the assumption that memory safety was something that can only be achieved at run-time. Programs can become too complicated and developers are too brilliant for a language team to anticipate fully how the language would be used. Much research has been done on this topic, and many believe that while compile-time analysis is helpful, run-time checking is the only viable option for true memory safety.10
Envzn is also a hybrid model. I took the approach that compile time analysis is sufficient for everything the code text decides, like lifetimes, ownership, leaks, and initialization, because the compiler walks the whole program and can follow every reference through its call graph and control-flow graphs.11 For variables that depend upon input, like an array index, math calculation, or call depth, these are checked at run time, but cheaply because the proof has already covered everything else. Any pattern the compiler cannot prove safe is not admitted; it is refused and the developer has to redesign that code.12
“A correct Envzn program neither leaks nor crashes on a memory fault. Every allocation is owned, destruction happens at a point the source determines, and the patterns ownership cannot prove safe are refused at compile time rather than admitted and hoped over.”13
I divided the general hazards of memory safety into 8 categories that could create unsafe conditions for memory access, and addressed each either within the compiler, the language structure, or the run time:
For those of you that are curious about other definitions, Microsoft’s four recurring root causes related to memory safety are out-of-bounds, use-after-free, type confusion, and uninitialized use.14 Type confusion cannot occur in Envzn code, and the other three are on the list.
Envzn is an ahead-of-time compiled, strongly-typed language with 25 primitive types, plus classes, enums, structs, groups and interfaces, where casting is forbidden, but conversions are common. Pointers do not exist (outside of UNSAFE blocks) and there’s a single owner for each owning handle, and conversions to and from handles are not allowed.
Further, I disregarded the asymmetry of create/destroy, so I kept the “create” function, but specifically saw an opportunity for a language without the need for a “destroy”, “delete”, or “free” that also didn’t carry the burden of garbage collection. The “delete” function does not exist. Cleanup happens in a deterministic manner when an object falls out of scope at a closing brace ‘}’ boundary similar to C++.
With every library created in Envzn code, the compiler produces 3 files, the library, the library .headers file, and the library .evir file. The library is linked into your executable just like a C++ library, the .headers file contains all class public data fields and method declarations for the developer to read method signatures, and the .evir file contains the pre-compiled bytecode of the library.
For every REFERENCE variable (types 3-5 above), the compiler analyzer traces that handle from its beginning to its end, walking its use from the time it is assigned to when it falls out of scope. If the REFERENCE variable is used by another module (in a library or in an executable), the analyzer opens that .evir file for the library and includes that in its reference walk.
The reference walk that may include multiple .evir files detects instances of hazards 1 and 3 described above; the other 6 are handled by the analyzer, the language structure, or the runtime. Any module with even one REFERENCE that cannot be proven safe fails the build of that module. This means that sometimes good code may fail because the analyzer cannot prove that a REFERENCE is clean.
How Envzn handles each type:
For those that believe that with any access into another language that isn’t safe, like C, then the whole program is unsafe15, Envzn does allow access to C code but only in a sandbox or via a special direct call. By this definition, Envzn is therefore memory safe as long as you stay within the Envzn code.
For the sandbox approach, Envzn has a keyword UNSAFE that refers to a block of code with braces, written like UNSAFE{…}. The UNSAFE block allows unchecked access to C structures and data fields that would otherwise be forbidden. The guarantee is confinement; a raw C pointer cannot escape the block.
For the direct call, Envzn has a keyword phrase FOREIGN BIND to map C functions directly into Envzn code. C functions may be declared at the top of the .ev file in Envzn format, and then called directly from Envzn code.
MODULE ffiExample
// The module's manifest must opt in to the foreign boundary: "allows_foreign": true
// Bind a libc function with its real C signature (unistd.h):
// ssize_t write(int fd, const void *buf, size_t count);
FOREIGN BIND write(int32 fd, binary[] data, C.size_t count) RETURNS C.ssize_t
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
ByteBuffer payload := "hello from C\n" INTO ByteBuffer
binary[] bytes := payload->view(0, payload->size())->copy()
// Every call across the boundary sits inside an UNSAFE block.
int64 written = 0
UNSAFE { written = FOREIGN::write(1, bytes, payload->size()) }
// A negative length never reaches C as a huge size_t:
// the conversion raises MathError before the call is made.
int64 negative = -1
TRY {
int64 ignored = 0
UNSAFE { ignored = FOREIGN::write(1, bytes, negative) }
}
RECOVER (MathError e) {
printline("refused: a negative length cannot become a C size_t")
}
RETURN (SUCCESS)
}
}
Envzn has two types that can hold system level C pointers, but the developer cannot invoke any memory space from those nor convert them into handles or numbers. UNSAFE.HANDLE lowers to a raw untyped C pointer, but it’s only a storage device, received from a foreign function and passed back into a foreign function. Opaque is a primitive type that can hold any typed C pointer, like one specific to SSL. Within an UNSAFE block it can be assigned, used in foreign functions, and its structures accessed. See the Envzn Constitution I.I.viii(d).
The EVIR bytecode file exists because in order to prove memory safety for any REFERENCE handle, the compiler must walk the code to check everywhere that REFERENCE is used. The machine code in the library itself doesn’t carry enough information for the walk, so the compiler generates a .evir bytecode file for each library, allowing the compiler to actually walk into the precompiled bytecode to check that REFERENCE, and to open as many .evir files as required to do so.
For those of you that may say either the walk is flawed or impossible to follow or would extend the compile time to something unreasonable, I’d say two things: first I will acknowledge that the compiler evir walk is not perfect and may miss something. In those cases the rule is that if the compiler cannot prove the REFERENCE is safe, then the build fails. Even so, it may still miss16. Second, timings have shown that even a complex three-hop .evir walk adds an average of about 2 secs to any build, a timeframe that I felt was reasonable.
The current size of compiler is over 120k lines of code across ~300 python files with about 3300 test cases with diagnostic, adversarial, and probing tests; the standard library and adjacent modules are over 60k lines of code across ~280 Envzn files with about 3600 test cases. Every error found has contributed to our test suite. I have frequently used clang sanitizers for identifying errors. Also I have frequently asked AI to help find defects and log them.
The Envzn language today compiles and runs on macOS and Linux. It lowers to C++ but is on-path to lower to LLVM soon.
1. CISA, NSA, FBI and international partners, “The Case for Memory Safe Roadmaps,” December 2023, https://www.cisa.gov/case-memory-safe-roadmaps; and The White House, Office of the National Cyber Director, “Back to the Building Blocks: A Path Toward Secure and Measurable Software,” February 2024, https://bidenwhitehouse.archives.gov/oncd/briefing-room/2024/02/26/press-release-technical-report. ↩
2. M. Miller, “Trends, Challenges, and Strategic Shifts in the Software Vulnerability Mitigation Landscape,” BlueHat IL, February 2019; and Microsoft Security Response Center, “We Need a Safer Systems Programming Language,” July 2019, https://www.microsoft.com/en-us/msrc/blog/2019/07/we-need-a-safer-systems-programming-language. About 70% of the CVEs Microsoft patched over twelve years were memory-safety issues. ↩
3. The Chromium Projects, “Memory Safety,” https://www.chromium.org/Home/chromium-security/memory-safety. About 70% of 912 high- or critical-severity security bugs since 2015 were memory-safety bugs; half were use-after-free. ↩
4. J. Vander Stoep and A. Rebert, “Eliminating Memory Safety Vulnerabilities at the Source,” Google Security Blog, September 2024, https://security.googleblog.com/2024/09/eliminating-memory-safety-vulnerabilities-Android.html. Memory-safety vulnerabilities fell from 76% of Android’s total in 2019 to 24% in 2024. ↩
5. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, §15.10.4: every array access is checked at run time and raises ArrayIndexOutOfBoundsException, https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.10.4. ↩
6. The Go Authors, “The Go Memory Model,” https://go.dev/ref/mem; see also R. Cox, “Off to the Races,” https://research.swtch.com/gorace. A data race on a multi-word value, such as a slice or an interface, can break Go’s memory safety. ↩
7. R. Jung, J.-H. Jourdan, R. Krebbers and D. Dreyer, “RustBelt: Securing the Foundations of the Rust Programming Language,” POPL 2018, https://plv.mpi-sws.org/rustbelt/popl18/. The first machine-checked safety proof for a realistic subset of Rust’s ownership type system. ↩
8. C and C++ are the memory-unsafe languages the guidance in note 1 recommends moving away from; see CISA et al., “The Case for Memory Safe Roadmaps” (note 1). ↩
9. S. Klabnik and C. Nichols, The Rust Programming Language, ch. 8.1, “Storing Lists of Values with Vectors,” https://doc.rust-lang.org/book/ch08-01-vectors.html. Indexing past the end of a vector panics at run time. ↩
10. L. Szekeres, M. Payer, T. Wei and D. Song, “SoK: Eternal War in Memory,” IEEE Symposium on Security and Privacy, 2013. A survey of run-time defences for C and C++, the setting in which run-time checking is treated as the only option. ↩
11. P. Cousot et al., the Astrée static analyzer, https://www.astree.ens.fr/. In 2003 it proved the absence of run-time errors in the Airbus A340 primary flight-control software (132,000 lines of C) with zero false alarms, in a subset of C that excludes recursion and dynamic allocation. ↩
12. H. G. Rice, “Classes of Recursively Enumerable Sets and Their Decision Problems,” Transactions of the American Mathematical Society 74 (1953); and P. Cousot and R. Cousot, “Abstract Interpretation: A Unified Lattice Model for Static Analysis of Programs by Construction or Approximation of Fixpoints,” POPL 1977. No analysis can decide every behaviour of every program, so a sound analysis must over-approximate, and some correct programs are refused. ↩
13. The Envzn Constitution, Article I.A, “Memory safe,” https://envzn-lang.org/constitution.html. ↩
14. M. Miller, BlueHat IL 2019 (note 2). The recurring root causes of Microsoft’s memory-safety CVEs were heap out-of-bounds access, use-after-free, type confusion and uninitialized use. ↩
15. H. Xu, Z. Chen, M. Sun, Y. Zhou and M. R. Lyu, “Memory-Safety Challenge Considered Solved? An In-Depth Study with All Rust CVEs,” ACM Transactions on Software Engineering and Methodology, https://arxiv.org/abs/2003.03296. Every memory-safety CVE in Rust studied (up to 2020) required unsafe code. ↩
16. This is why it is still a work in progress. ↩
Four unusual design choices, and eleven trouble spots it closes
Most of what a systems language does is settled practice, and Envzn follows it. This page covers the rest: places where Envzn made a choice few other languages have made, and places where a familiar language lets a defect through silently and Envzn refuses it. Every example below is checked by the documentation build. A block marked as failing must fail to compile with the error shown, so a claim here cannot drift from the compiler without the build noticing.
The features that make Envzn safe and exact by default (memory safety, checked overflow, no casts, diagnostics that cite the Constitution, numbers for money and data, N-D arrays, calling C) have their own page: Features of Envzn.
1. Leak-freedom proven at compile time. Every object is owned, and the graph of owning and counted references must contain no cycle, so a leak is a compile error (E3033). Swift's ARC and Rust's Rc leak a cycle silently (I.I.i(b.i)).
2. Parameter modes spelled as words. A plain parameter owns its argument, REFERENCE reads it, and MUTABLE REFERENCE writes it, exclusively (I.I.vi). The same three meanings are sigils in Rust and drift between &, const& and && in C++.
3. Bounds-check removal you ask for, and that is proven. HOTLOOP asks the compiler to replace a loop's per-element bounds checks with one check up front. If it cannot prove that one check covers every access, the build fails (E5027) rather than run unchecked (I.H.iii(f)).
4. Three assignment operators, one per meaning. = copies a value, := takes ownership (constructing, cloning or moving), and =@ binds a reference. A move is visible at the point it happens (I.F).
Where it bites: C and C++, where the result is undefined.
Envzn: a shift count must lie in [0, width), and a constant that breaks the rule is a compile error (I.F.ii(c.iv)).
int32 a = 5
int32 b = a LSHIFT 40
Where it bites: C, C++, Java and JavaScript, where x & mask == 0 means x & (mask == 0).
Envzn: mixing a bitwise operator with a comparison requires parentheses.
int64 x = 6
int64 mask = 4
IF x BAND mask == 0 THEN { printline("clear") }
Where it bites: C, C++ and Java, where 0755 is 493.
Envzn: octal literals are refused; write decimal, 0x or 0b (I.C(e)).
int32 mode = 0755
== on strings comparing referencesWhere it bites: Java, and C's char*, where two equal strings can compare unequal.
Envzn: == on a String is a compile error; content equality is ->equals() (I.F.ii(c.i)).
String a = "hello"
String b := a->clone()
IF a == b THEN { printline("same") }
Where it bites: C, C++, Java, Go and C#.
Envzn: there is no null. A class-typed value may be EMPTY, and the compiler refuses any use it cannot prove is
present; IF w IS VALID is the proof (I.D.iv).
MODULE nullExample
CLASS Widget {
PRIVATE int32 id
INIT(int32 i) { .id = i }
METHOD ident() RETURNS int32 { RETURN (.id) }
}
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
Widget w = EMPTY
printline(("id $1")->format(w->ident()))
RETURN (SUCCESS)
}
}
Where it bites: C, C++, Python and JavaScript, where if (count) and if (ptr) hide a comparison.
Envzn: a condition must be a boolean (I.D.i(b.iii)).
int64 count = 3
IF count THEN { printline("some") }
Where it bites: C++, where it is undefined behaviour, and Java, where it throws at run time. Envzn: a live loop or view locks its source against change, at compile time (I.D.vi(d.ii)).
int64[] items := CREATE()
items->append(1)
FOR x IN items { items->append(x) }
Where it bites: C and Go, where an error code can be stored and forgotten.
Envzn: a STATUS kept in a variable must be checked before it goes out of scope. Dropping a result on purpose is
written visibly, as $? := call() (I.F.iv).
MODULE statusExample
CLASS Main IMPLEMENTS TaskStarter {
METHOD save() RETURNS STATUS {
RETURN (SUCCESS)
}
METHOD start() RETURNS STATUS {
STATUS s = save()
RETURN (SUCCESS)
}
}
Where it bites: Java, C# and Python (except:), where one handler silently swallows every failure.
Envzn: recovering from the base Error class is refused; name the errors you handle (I.M.ii).
TRY { printline("work") }
RECOVER (Error e) { printline("swallowed") }
Where it bites: C, C++ and Java, where a forgotten break runs the next case.
Envzn: MATCH never falls through, and it dispatches only over closed sets (an enum, a GROUP of types, or a
STATUS). Matching on arbitrary values is an IF chain (I.H.v).
int32 n = 5
MATCH n {
WHEN 5: { printline("five") }
}
Where it bites: npm install scripts, Cargo's build.rs, CMake: a dependency can run code on your machine at build
time.
Envzn: manifest build flags that could run code are refused, inline C blocks are not part of the language, and a
module may call C only after opting in with "allows_foreign": true (I.N).
{ "name": "netio", "version": "1.0.0", "target": "library", "allows_foreign": true, "sources": ["Socket.ev"] }
Readability. Not a goal that most languages pursue. After having put code into production in over a dozen languages, and seeing the direction that some languages were taking (C++ has gotten quite complex compared with its past versions), I saw an opportunity to build a systems language that would have readability as a goal.
The problem with readability as a goal is that no one has ever created a standard for what this means. Some standards committees have considered it; ISO 25010 and ISO 5055 define maintainability and have stopped short of defining readability1. Python's motto is "readability counts"2, and Go considered it in its design3; they seem to be the exceptions. SonarQube, a code-analysis tool, even had to withdraw some guidelines about the ratio of comments to code lines, worried that future developers would add garbage comments just to “game the ratio” to satisfy their tool4.
Every experienced developer knows what “bad” code looks like: an alphabet soup of abbreviations, unexplained magic numbers, cryptic, unhelpful, or misleading names of elements, a lack of meaningful comments, “dense” and “packed” code accomplishing multiple tasks on one line, and sigils used often instead of their longer equivalents. Some languages are more susceptible to this than others - Perl is a great language but the competition among developers to accomplish in one line what a paragraph of lines would do was insane. Some lint programs guide developers to avoid these, but there’s no language that refuses unreadable code5.
So, I started with a simple and straightforward definition: readability means that a junior software engineer should be able to cold-read the code and adjacent comments, and understand what the code is doing.
This “simple” definition is much harder to measure than one would guess. Starting with the “junior software engineer” terminology; it’s a vague label implying “not much” experience in the field, and further, the “comprehension” expectation that this less-experienced software person could pick up code they’ve never seen before and understand it sounds a bit crazy.
However, in order to set readability as a goal, it needs to be measured. After many iterations, I’ve arrived at this for a readability rubric:
While the above rubric is helpful, I needed to be able to score my code to improve it. The problem I then encountered was how to create a positive score when everything is done well. I found it much easier to generate a score based on the negative, when the presence of these “bad things” exists. Even so, it was not enough, so I began to think about how the junior software engineer would respond to poorly written code, which led me to my next idea. I decided to use a readability score based on the reader’s response and actions while reading, with the understanding that it’s very subjective15:
The scoring for readability doesn’t judge readability directly. It looks for specific problems in the code based on the above bullet points to generate a grade16.
As part of this exercise, my first iterations were too biased toward Envzn, giving it scores above what it deserved. Envzn did too well. As readable as I think it is, I felt that these early scores were too generous. I asked AI to critique it to seek out the biases to make the scoring more balanced. It found three specific bias points:
Once these were fixed, our Envzn code landed in the middle of the pack, with specific, fixable problems: lines doing two jobs and names too short to say what they hold. After each adjustment, I asked AI for another round of critiques. After many revisions, I shaped the current readability rubric into what it is now. While Envzn isn't going to win any awards for readability, the scoring provided a clear work-list of possible improvements.
Even with this rubric, scoring a language remains difficult. Code samples vary greatly across languages and developers, so the goal here is not precision or accuracy. Instead, it is to create rough tiers of separation—based on limited samples—that shows how well a language encourages developers to write readable code, and whether they actually do so in publicly available projects.
Envzn's guiding idea is to move the hard parts into the compiler and the library so the code a developer writes is readable. This rubric highlights where that hasn't happened yet: every construct the language forces on an author, and every habit in our own library that makes a reader stop. A truly readable language is one where the most readable approach is also the easiest. Envzn isn't there yet, but I now have a list of exactly where it falls short, and a clear way to track our progress.
Disclaimer: These are judgements grounded in research where research exists, and stated as choices where it doesn’t17. The methodology is open for inspection and improvement. If you are a researcher in this field, please reach out.
i carry meaning by convention (Gal Beniamini, Sarah Gingichashvili, Alon Klein Orbach and Dror G. Feitelson, "Meaningful Identifier Names: The Case of Single-Letter Variables," ICPC 2017). ↩ifs were no harder than one compound condition, though flat code was slightly easier than deep nesting (Shulamyt Ajami, Yonatan Woodbridge and Dror G. Feitelson, "Syntax, Predicates, Idioms — What Really Affects Code Complexity?", EMSE 2019). ↩?: throw and early returns. https://kotlinlang.org/docs/idioms.html ↩The contracts every other family is built on: copying, equality, ordering, hashing, iteration, views, and reading and writing text.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
BidirectionalIteratorBidirectionalIterator OF T — extends ReferenceIterator OF T with reverse traversal. Used by Array, LinkedList, SortedList, Deque per spec L763-768.
kernel/src/interfaces.ev:458
Methods
METHOD hasPrevious() RETURNS boolean
MODIFY METHOD previous() RETURNS | REFERENCE T
MODIFY METHOD skipBack(uint64 n) RETURNS | REFERENCE T
Collectablekernel/src/interfaces.ev:175
CollectionThe minimum definition of a Collection container — what every container in the standard library can answer, so that membership of this interface is what marks a type AS a collection.
3 METHODS: iterator() declared here size() and isEmpty() inherited from Countable
contains() is deliberately NOT here, and the reason is the whole shape of
the interface. Containment needs EQUALITY on T, and Array[T] requires only
Cloneable of its elements — so putting contains in the minimum would force
Equatable onto every element type in the language the moment Array joined.
That is the split the industry already divides on: where equality is
UNIVERSAL (Java's Object.equals, Python's eq) a Collection can require
contains, and where equality is OPT-IN (Rust, Swift, C++) it cannot —
Swift's Collection requires iteration and offers contains only as an
extension where Element: Equatable. Envzn is the second kind. Containment
belongs with Searchable OF T, whose find needs exactly the same equality
and of which contains is the boolean shadow.
ITERATION is also the more primitive notion: contains is DERIVABLE from
iterating and comparing, while iteration cannot be derived from containment.
A minimum should be the irreducible core.
The qualifier is deliberately the WIDEST of any container's: iterator(),
size() and isEmpty() ask NOTHING of T, so nothing here should either.
Shareable is listed beside Cloneable because the OwnedList family
constrains its element that way, and refusing it would exclude a container
from the interface over a contract the interface never uses.
kernel/src/interfaces.ev:521
Methods
METHOD iterator() RETURNS ReferenceIterator[T]
Collectorskernel/src/interfaces.ev:163
CountableCountable is an opt-in interface for any class that enumerates how many elements it holds.
kernel/src/interfaces.ev:250
Methods
METHOD size() RETURNS int64
METHOD isEmpty() RETURNS boolean
IteratorIterator OF T — forward-traversal cursor over a collection. Per spec §Iterator (L730+).
hasNext() uses it not at all — the
qualifier said T IS Countable, which asked the ELEMENT to have a size.
So it admits every element any of its sub-interfaces admits (I.K.ix: an
interface's qualifier may demand only what its own methods use): a plain
CLASS (ObjectIterator OF Row — Cloneable/Shareable alone refused it at
the kernel's own EXTENDS edge), any BLITTABLE value
(ValueIterator), and the Cloneable/Shareable/primitive elements
ReferenceIterator hands out.kernel/src/interfaces.ev:291
Methods
METHOD hasNext() RETURNS boolean
ObjectIteratorObjectIterator OF T — extends Iterator with by-reference navigation
over a HEAP-CLASS element type. The object peer of ReferenceIterator:
where ReferenceIterator's bound admits only Cloneable primitives,
ObjectIterator admits any class, so a collection whose logical
element is a synthesized class instance (a per-position VIEW — e.g.
a DataFrame yielding a Row built from its stored columns) can be
FOR e IN coll-iterable. Because the source may not STORE the
element (it synthesizes it), the concrete iterator OWNS the current
element in an internal slot and hands back a non-owning REFERENCE
into that slot; the reference is valid until the next advance, on
which the slot is refreshed. The FOR-IN loop borrows it for the
iteration exactly as it borrows a ReferenceIterator's referent —
so next() lowers to REFERENCE T (a T*) on both this interface
and its implementers, with none of the value-form covariance seam.
kernel/src/interfaces.ev:434
Methods
MODIFY METHOD next() RETURNS | REFERENCE T
2.0 pipe-XOR shape: a successful navigation refreshes the
iterator's owned slot and populates value with a non-owning
reference into it; end-of-iteration populates s with FAILURE.
METHOD peek() RETURNS | REFERENCE T
peek is non-consuming: the reference to the current slot without advancing. Same pipe-XOR shape as next().
ReferenceIteratorReferenceIterator OF T — extends Iterator with by-reference
navigation. Implemented by the collection iterators, whose backing
storage is referenceable: next() / peek() / skip() hand back a
non-owning reference into the source rather than a copy. Buffer
iterators (over by-value _cxx* storage) implement only the
value-form Iterator.
next/peek/skip hand back a REFERENCE and never clone, so Cloneable
was never used; Shareable joins it so the OwnedList family qualifies.
kernel/src/interfaces.ev:384
Methods
MODIFY METHOD next() RETURNS | REFERENCE T
2.0 pipe-XOR shape: a successful navigation populates value
with a non-owning reference into the source; end-of-iteration
or invariant violation populates s with FAILURE. The caller's
IF iter->next() THEN { binding REFERENCE T v =@ $RETURNED } ELSE { ... } binds the
populated slot.
METHOD peek() RETURNS | REFERENCE T
peek is non-PANICing and non-consuming: returns the reference at the current cursor without advancing. Same pipe-XOR shape as next().
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE T
SearchableSearchable OF T — contents can be searched for a needle of the same
Text kind. find returns the match position; pipe-XOR FAILURE means
no match. Implemented by String and StringView — the view holds the
one canonical scan, and String forwards through a full-span view.
kernel/src/interfaces.ev:328
Methods
METHOD find(REFERENCE T needle) RETURNS | int64
ValueIteratorValueIterator OF T — extends Iterator OF T with by-value navigation. Implemented by the buffer iterators, whose backing storage yields elements by value, not by reference: nextValue() / peekValue() / skipValue() hand back a copy of the element. The value-form mirror of ReferenceIterator.
kernel/src/interfaces.ev:406
Methods
MODIFY METHOD nextValue() RETURNS | T
2.0 pipe-XOR shape: a successful navigation populates value
with a copy of the element at the new cursor; end-of-iteration
populates s with FAILURE.
METHOD peekValue() RETURNS | T
peekValue is non-consuming: the value at the current cursor without advancing. Same pipe-XOR shape as nextValue().
MODIFY METHOD skipValue(uint64 n) RETURNS | T
CloneableCloneable — per. A class implementing Cloneable opts in to deep-copy semantics: := on instances calls clone(); the *Copy family of collection methods clones each class-typed element through this interface.
Implementations declare their own concrete return type — Envzn's interface satisfaction rule accepts any return type that itself implements Cloneable (covariant-return-via-subtype), so:
CLASS Person IMPLEMENTS Cloneable { METHOD clone() RETURNS Person { Person p := CREATE Person(.age) RETURN (p) } }
...satisfies the contract without any cast.
An AUTO clone is the other form, and it declares NO return type: the
compiler supplies the body AND the concrete return type, so writing
RETURNS on one is E7029 (auto-clone-with-returns).
CLASS Point IMPLEMENTS Cloneable {
AUTO METHOD clone() { } // generated; never RETURNS Point
}
kernel/src/interfaces.ev:205
Methods
METHOD clone() RETURNS Cloneable
InoperativeGROUP Inoperative — the types whose values generic code may not
operate on: no clone, no copy, no iteration over the payload. Today's
sole member is opaque (I.D.v), whose payload type is erased, so no
method dispatch on it is well-defined. A generic kernel container
(Box, Array, ...) tests membership on its type parameter:
WHEN T IS Inoperative { /* opt out */ } ELSE { /* the general path */ }
A GROUP, not an interface: it states its members by name, it needs no method (Envzn forbids an empty interface, E6001), and membership is a compile-time fact read off this declaration, so every backend decides it the same way.
kernel/src/interfaces.ev:368
ComparableComparable[T] — type defines a strict less-than ordering. Extends Equatable[T]: a type that is comparable is necessarily equatable (otherwise sorted-and-equal-to checks can't compose).
Required for any T used in:
- SortedList[T] (insert position determined by isLessThan)
- Array[T]->sort() (insertion-sort or quicksort comparator)
- any future ordered collection
The implementation MUST satisfy a strict total order:
- Irreflexive — a.isLessThan(a) is always FALSE.
- Antisymmetric — if a.isLessThan(b) then NOT b.isLessThan(a).
- Transitive — if a.isLessThan(b) and b.isLessThan(c),
then a.isLessThan(c).
- Trichotomous (consistent with Equatable) — for every
pair, exactly one of a.isLessThan(b), b.isLessThan(a),
or a.isEqualTo(b) is TRUE.
The kernel provides built-in Comparable behaviour for primitive
numerics (int8..int64, uint8..uint64, float32, float64,
byte, char) and String (lexicographic). boolean is also
comparable (FALSE < TRUE). Class types must declare
IMPLEMENTS Comparable[K] and provide isLessThan(K) and
isEqualTo(K) methods explicitly.
isLessThanOrEqual, isGreaterThan, isGreaterThanOrEqual are
derivable and not part of this interface; the canonical method
is isLessThan. Callers compose: NOT a.isLessThan(b) is
"a >= b", b.isLessThan(a) is "a > b", etc.
kernel/src/interfaces.ev:557
Methods
METHOD isLessThan(REFERENCE T other) RETURNS boolean
EquatableEquatable[T] — type can compare itself to another instance of the same type for value equality. Parameterised over T to pin the comparison type at the implementation site:
CLASS Token IMPLEMENTS Equatable[Token] {
METHOD isEqualTo(Token other) RETURNS boolean { ... }
}
Equatable is the contract Dictionary uses to resolve hash collisions and Set uses for membership. Required alongside Hashable for any class type used as a Dictionary key.
Implementations must be:
- Reflexive — a.isEqualTo(a) is always TRUE.
- Symmetric — a.isEqualTo(b) iff b.isEqualTo(a).
- Transitive — if a.isEqualTo(b) and b.isEqualTo(c),
then a.isEqualTo(c).
- Consistent with Hashable — if a.isEqualTo(b), then
a.hash() == b.hash(). (The reverse need not hold; hash
collisions on equal-by-isEqualTo objects break Dictionary.)
Built-in for primitives and String, same as Hashable.
kernel/src/interfaces.ev:319
Methods
METHOD equals(REFERENCE T other) RETURNS boolean
HashKeykernel/src/interfaces.ev:158
HashableHashable — type can produce a stable hash code of itself.
Returned value is uint64 per spec §Hashable and KeyHasher
(CONSTITUTION L3611). Implementing classes are eligible for use
as Dictionary[K: V] keys (paired with Equatable[K], below) and
Set[T] elements.
The hash MUST be: - Deterministic — equal objects (per Equatable.isEqualTo) must produce equal hashes. Calling hash() on the same value twice must yield the same result. - Pure — no observable side effects, no I/O, no mutation of SELF or any reachable state.
The kernel provides built-in Hashable behaviour for primitives
(int8..int64, uint8..uint64, float32, float64, byte,
char, boolean) and String — those types do not need to
declare IMPLEMENTS Hashable explicitly. Dictionary[K: V] uses
the built-in path automatically when K is one of those.
kernel/src/interfaces.ev:484
Methods
METHOD hash() RETURNS uint64
IncomparableGROUP Incomparable — the primitives with no equality: opaque (move-only, a
tagged payload), and the UNSAFE.* handles, whose == would compare
addresses, which says nothing about what they hold. Comparing two arrays of
one is a compile error (E5026), never a runtime answer.
kernel/src/interfaces.ev:112
OperatorEquatableGROUP OperatorEquatable — the primitives that compare with == / !=, and
only that way. A kernel body comparing elements of a type parameter picks its
comparison by group (NativeArray.equals): this group takes the operator,
Equatable takes ->equals(), and Incomparable has no equality at all.
decimal128 also has ==, but it is Equatable and compares through its exact equals, so it is not a member: one type, one way.
kernel/src/interfaces.ev:98
WordKeyGROUP WordKey — a primitive whose value IS an integer bit-pattern, so a
hasher body may reduce it to its hash word with uint64 v = #key (I.F.ii(a):
the value mod 2^64) and nothing about the value domain changes. It is
exactly the operand set # accepts (E2153).
FastIntHasher and InlineIntHasher were qualified PRIMITIVE(EXCEPT
opaque, boolean, number, complex) while their bodies are a bare
uint64 v = key — which TRUNCATES for float32/float64, is forbidden outright
for decimal128 (E2121 — decimal never mixes), and names a FOREIGN-only type
for the C.* four. The constraint admitted types the body could not honour.
This is the set it can.
int128/uint128 ARE members, and they are the one case where the reduction is lossy: the high 64 bits are dropped, so two keys differing only above bit 63 hash alike. That is a WEAK hash, not a wrong one — Equatable still separates them on lookup, and taking low bits is an ordinary hash fold. A float is excluded for the different reason that its bits are not a value: the same number has several encodings, so # on it would not be a fold but a reinterpretation.
kernel/src/interfaces.ev:137
PrintablePrintable — type can render itself directly to stdout.
Distinct from Readable — Readable produces a String for the caller to do something with; Printable is the convenience for types that own their own output side effects (e.g. a complex renderer that writes structured output to multiple lines).
Most types should implement Readable and let callers route the output. Printable is for cases where producing the intermediate String would be wasteful (e.g. large structured dumps).
kernel/src/interfaces.ev:644
Methods
METHOD print() RETURNS void
ReadableReadable — a byte source: the counterpart of Writable. The single
operation is read — drain the source into an storage char8[512+]
of whatever it had. File, Socket, and the Stdio stdin source
implement it, so code can ask of any of them "can I read this?"
the same way Writable answers "can I write it?".
read returns the bytes it managed to produce as a char8[512+]
storage value — empty when the source has none, populated through
to end-of-input otherwise. The FAILURE status is reserved for a
genuine read error, not for a short or empty read. The caller can
build a ByteBuffer or DynamicByteBuffer from the returned
storage when a wrapper is needed (§21).
Spec reference: stdio-spec.md §6.
kernel/src/interfaces.ev:627
Methods
MODIFY METHOD read() RETURNS | binary[]
Textkernel/src/interfaces.ev:167
WritableWritable — a byte sink. The single operation is write: hand it a
ByteBuffer and it delivers every byte or fails. Implemented by the
Stdio stdout/stderr sinks, by File, and by Socket — so a rendered
String (from a Formatter) can reach any of them through one
uniform call.
All-or-nothing: a short OS write is retried internally, so the outcome is SUCCESS — every byte written, count returned — or a FAILURE status. There is no partial write.
THE EXTENT IS THE ARRAY'S OWN LENGTH — there is deliberately no
length parameter. The old shape
write(content, length) passed the caller's integer straight to
POSIX write, which reads that many bytes from the base pointer:
write(twoByteBuffer, 65536) wrote 64 KB of live heap — including a
pointer — to disk, with no diagnostic at any phase. CWE-126, and
severity 10 against I.A's memory-safe floor.
It was also redundant. read/readAt already return a char8[]
whose .length IS the valid extent, so the class conveyed extent by
array length in one direction and by a separate integer in the other.
Three of the four call sites in the whole corpus passed a value equal
to the array's length anyway.
To write PART of a buffer, take a view (ByteBufferView is
REFERENCE char8[] source + start + length) or pass a right-sized
array. A lone length could only ever express a prefix — it has no
offset — so it was never the right tool for a slice.
Spec reference: stdio-spec.md §6.
kernel/src/interfaces.ev:866
Methods
MODIFY METHOD write(REFERENCE binary[] content) RETURNS | int64
ViewView — the non-owning window itself. Minimal base contract; the element-typed operations (operator[], iterator, find via Searchable, copy) live on the concrete view (StringView). Kept deliberately minimal so a future N-D view tier is not constrained by 1-D shape. Declared before Viewable because Viewable.view() references it.
kernel/src/interfaces.ev:337
Methods
METHOD length() RETURNS int64
ViewableViewable — a source that yields a non-owning, bounded View into its
own storage without copying. view(start, length) windows over
[start, start+length). The return type is the base View; an
implementer narrows it covariantly to its concrete view (String
returns StringView). This is the 1-D / linear tier (String now;
ArrayView / byte-buffer views later) — the N-D strided views the
Data module needs are a separate, related contract.
kernel/src/interfaces.ev:348
Methods
METHOD view(int64 start, int64 length) RETURNS View
Text and bytes: the immutable String and ByteBuffer, their mutable twins, and the views and iterators over them.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
StringIMPLEMENTS Countable, Cloneable, Hashable, Equatable
Immutable readable/printable text.
Storage is char32[] (UTF-32 code points), one entry per code point.
The compiler lowers char32[] to ENVZN::_ValueArray<char32_t> so
every positional method is O(1) by code-point index. No UTF-8
decode lives in String — those conversions live in Converter and
Codec classes.
Storage rule: STRING IS IMMUTABLE. The .data field is populated
once in INIT and never mutated. Every transformation (substring,
toUpper, trim, …) returns a fresh String. There is no concat:
build text in steps with a DynamicString.
Case fold: ASCII only. Code points >= 0x80 pass through unchanged
in toUpper / toLower / case-insensitive find / contains /
count. Full Unicode case folding waits for V2 Unicode tables.
kernel/src/String.ev:28
Constructors
INIT()
Empty String.
INIT(REFERENCE char32[] origin)
Take ownership of a pre-built code-point array. The literal-
lowering path in the emitter and every internal transformation
(substring, toUpper, trim*, …) construct their result
this way: build a fresh char32[], hand it to a new String.
From a raw code-point array, COPYING it. REFERENCE is now explicit:
it always lowered to const EvArray<char32_t>&, so this states the
borrow the signature already had rather than changing it.
INIT(char32[] origin, int64 length)
THE LITERAL CONSTRUCTOR. The emitter's, not a developer's.
It could not be hidden. INTERNAL INIT is E1141 and PRIVATE INIT is a
parse error: a constructor carries no visibility modifier in Envzn,
because "INIT and CLEANUP are lifecycle, not module surface". So this is
public, and what keeps it honest is its own signature: the array
is a plain, owning parameter — a developer who calls it sees that it is taken, and
the analyzer poisons the source so a later read is E3010. That is the
language's normal contract rather than a hidden trapdoor.
It exists to spend ONE allocation on a string literal instead of two.
String s = "bob" lowers to a _ValueArray<char32_t>(U"bob", 3)
handed to a String constructor. Through INIT(REFERENCE char32[]) above
that array is built, then COPIED into .data and destroyed — two heap
allocations and two memcpys for every literal in the program, of which
there are ~2,800. Taking it as a plain (owning) parameter makes it a by-value
EvArray<char32_t>, so C++17's guaranteed copy elision constructs the
caller's prvalue DIRECTLY into it — nothing is materialised twice — and
:= then transfers the buffer pointer into .data. Measured 2 -> 1.
length IS REDUNDANT AND MUST NOT BE REMOVED. origin.length already
carries the count; this parameter exists solely to give this INIT a
different ARITY from INIT(REFERENCE char32[]). Owning and REFERENCE of
the SAME type at the SAME arity both lower to a one-argument
constructor over EvArray<char32_t> — by value and by const reference —
and clang rejects the pair as ambiguous. Differing arity is the
established way round it; StringIterator carries both forms for
exactly this reason. Delete this parameter and the kernel stops building.
It is String-only on purpose: a character-sequence literal has exactly
one representation in the language, and it is String. The other five
text/binary classes do not get it, which
run_text_binary_consistency.sh records as an allow-listed asymmetry
rather than drift.
INIT(REFERENCE String other)
Copy-construct from another String. ByteBuffer has had
INIT(REFERENCE ByteBuffer) all along; the text axis had no equivalent,
so CREATE String(other) was rejected outright until Phase 1 added this.
This does NOT collide with the array form above: the two differ in
parameter TYPE (String against char32[]), which C++ overload
resolution separates cleanly. What it cannot separate is the same type
owned versus REFERENCE — both lower to one-argument
constructors taking EvArray<char32_t> by value and by const reference,
and clang calls that ambiguous. That is why there is no owning companion.
Methods
METHOD clone() RETURNS String
Cloneable contract — deep copy. Returns a fresh String whose
.data is an independent code-point array with the same values.
METHOD length() RETURNS int64
Code-point count. O(1).
METHOD size() RETURNS int64
UTF-8 byte count of the text — distinct from length() (the code-point count). Storage is UTF-32 code points, so size() sums each code point's UTF-8 width per RFC 3629 (the same widths UTFCodec.encodeToUTF8 emits): U+0000–007F → 1 byte, U+0080–07FF → 2, U+0800–FFFF → 3, ≥ U+10000 → 4. Mirrors DynamicString.size().
METHOD isEmpty() RETURNS boolean
True iff the String has zero code points.
METHOD __op_index__(int64 i) RETURNS char32
Code point at index i. Declared as operator [] so the
only access syntax is s[i] — there is no public at()
method on String. Raises IndexOutOfBoundsError if i is out
of range — bounds check lives in _ValueArray<char32_t>::operator[].
METHOD equals(REFERENCE String other) RETURNS boolean
Code-point-by-code-point equality. UTF-32 storage means no normalisation surprises; two Strings are equal iff their code- point sequences match exactly. Value equality, delegated to the value array's own equals. That is not merely shorter: for an element type with a unique object representation the array compares with a single length-checked memcmp (one SIMD compare) where this method used to walk element by element. Measured at 6x faster on 64 elements and 11-14x from 1K up, with identical results across an 8-cell differential matrix — including the float guard, since the array deliberately does NOT memcmp an arithmetic element type (-0.0 == +0.0, NaN != NaN would come out wrong).
METHOD isLessThan(REFERENCE String other) RETURNS boolean
Use the lexicographic comparision below
METHOD compareTo(REFERENCE String other) RETURNS int32
Lexicographic code-point comparison. Returns -1 / 0 / +1 in the usual three-way-comparison sense.
METHOD hash() RETURNS uint64
FNV-1a 64-bit hash over the code-point array. Satisfies the Hashable contract. Deterministic.
METHOD hash(uint64 seed) RETURNS uint64
FNV-1a 64-bit hash with caller-supplied seed. Each code point is mixed in as a 4-byte little-endian sequence: XOR then multiply per byte. Wrap on uint64 overflow is the algorithm.
METHOD substring(int64 start, int64 len) RETURNS String
Substring by code-point index. start is inclusive; length is
the count of code points. A bad range is a precondition violation
(programming error) — it PANICs, the same category as operator[].
Recoverable runtime outcomes (search misses) live on find/count
as the pipe-XOR (... | STATUS); a bad slice range is not one.
Also the lowering target of the s[start:length] slice sugar.
METHOD view(int64 start, int64 length) RETURNS StringView
Non-owning bounded view starting at start for length code
points. Suitable for searching / scanning without allocating a
copy. StringView's INIT validates the bounds; length == 0
yields an empty view; negative or out-of-range bounds PANIC.
METHOD find(REFERENCE String needle) RETURNS | int64
First occurrence of needle in this String (case-sensitive) — the
Searchable contract. Pipe-XOR: SUCCESS yields the absolute index
where the match begins; FAILURE means no match. To search a
sub-range, view(start, length) then search the window.
METHOD find(REFERENCE String needle, boolean caseMatch) RETURNS | int64
As find, with ASCII case-fold when caseMatch == FALSE. Forwards to
the one canonical char32 scan in StringView: a full-span view over this
String's codepoints searches for needle's codepoints.
METHOD contains(REFERENCE String needle) RETURNS boolean
True iff needle occurs at least once (case-sensitive).
METHOD contains(REFERENCE String needle, boolean caseMatch) RETURNS boolean
METHOD startsWith(REFERENCE String prefix) RETURNS boolean
True iff this String begins with prefix. Forwards to the one canonical
char32 scan in StringView, the same way find does — a full-span view
over this String's code points tests prefix's code points. An empty
prefix is a prefix of everything.
METHOD endsWith(REFERENCE String suffix) RETURNS boolean
True iff this String ends with suffix. Same delegation as startsWith.
METHOD lastIndexOf(REFERENCE String needle) RETURNS | int64
Index of the LAST occurrence of needle, pipe-XOR: SUCCESS populates
index, FAILURE when the needle does not occur. The forward search is
find; this is its mirror, and like find it forwards to StringView so
there is exactly one char32 scan in the kernel.
METHOD count(REFERENCE String needle) RETURNS int64
Non-overlapping occurrence count of needle (case-sensitive).
Empty needle returns 0.
METHOD count(REFERENCE String needle, boolean caseMatch) RETURNS int64
METHOD find_first_of(REFERENCE String set) RETURNS | int64
B1: index of the first code point that IS a member of set (the code
points of set, treated as a set). Pipe-XOR: SUCCESS = index, FAILURE =
none present. Forwards through a full-span view to the one canonical
char32 scan in StringView.
METHOD find_first_not_of(REFERENCE String set) RETURNS | int64
B1: index of the first code point that is NOT a member of set.
METHOD split(REFERENCE String delim) RETURNS String[]
Split on delim into an array of Strings. Adjacent delimiters
produce empty pieces; a trailing delimiter produces an empty
trailing piece. Empty receiver returns a single-element array
containing one empty String. Empty delim returns a single-
element array containing this String unchanged.
METHOD splitLines() RETURNS String[]
Split on any of the Unicode line-break code points: LF, CR, CRLF (one boundary), VT, FF, NEL (U+0085), LS (U+2028), PS (U+2029). The line terminators are NOT included in the pieces. A trailing terminator does NOT yield a trailing empty piece.
METHOD toUpper() RETURNS String
ASCII uppercase fold. Code points >= 0x80 unchanged.
METHOD toLower() RETURNS String
ASCII lowercase fold. Code points >= 0x80 unchanged.
METHOD trim() RETURNS String
TRIM (ASCII WHITESPACE: space, tab, LF, CR, VT, FF) -----------
METHOD trimStart() RETURNS String
METHOD trimEnd() RETURNS String
METHOD format(FormatArgument args...) RETURNS String
Format this String as a template — substitute $1..$9 with the
corresponding argument, $$ with a literal $ and $: with a literal
:; a placeholder may carry a :spec (stdio-spec.md §4). The everyday
("text $1")->format(a) form.
One renderer does every format call: Formatter. The compiler compiles a
format call on a String as Formatter.format(template, …)
(analyze/format_calls.py; format-argument-design.md §6, Q2), so the
template is read in place and this body is never reached. It names no
Formatter, which keeps String free of every kernel dependency — the
invariant the kernel's header order rests on.
METHOD formatWith(BinaryMode mode, FormatArgument args...) RETURNS String
format with an explicit rendering mode for binary / byte-buffer
arguments — compiled as Formatter(mode).format(template, …).
METHOD iterator() RETURNS ValueIterator[char32]
String concatenation. Returns a fresh String; both receivers
are unchanged.
ITERATOR — value-form (char32 is by-value). Wraps the bounded
walk in a sibling StringIterator class so the surface
matches the standard ValueIterator pipe-XOR shape (nextValue /
peekValue / skipValue). _ValueArray's raw iterator has a
different signature (no STATUS pipe-XOR), so the wrap is
necessary.
DynamicStringIMPLEMENTS Countable, Cloneable, Hashable, Equatable
Stack-resident mutable text builder.
DynamicString is one of four sibling classes in the Envzn text/binary type system:
PURPOSE The text builder. Mutate in place; snapshot to immutable String with toString() when done.
API SHAPE The non-modifying surface mirrors String exactly: length / isEmpty / at / equals / compare / hash / hash(seed) / find / contains / count / split / splitLines / concat / iterator / clone / format / formatWith / toString.
The modifying surface is DynamicString's reason for existing: MODIFY toUpper / toLower / trim / trimStart / trimEnd / substring (in-place slice) / append (String / DynamicString / char32) / prepend (String / DynamicString / char32) / replace / padStart / padEnd. Mutating methods return STATUS.
STRING ↔ DynamicString BRIDGE
Both classes now carry UTF-32 codepoint storage. Cross-class
operations (INIT(String), equals(String), find(String, …),
toString()) are direct codepoint copies — no UTF-8 encode/decode.
kernel/src/DynamicString.ev:52
Constructors
INIT()
INIT(int64 reserve)
Pre-size the builder to reserve code points, so a build of known
length performs ONE allocation instead of walking the growth schedule.
This was a NO-OP: it accepted the number and discarded it, on the
grounds that "pre-spilling to capacity N would need an storage reserve
method". reserveExact is that method — the substrate's resize already
takes INLINE and handles the spill, so the storage was never the
obstacle. Every caller that believed it was pre-sizing has been growing
from zero.
reserveExact, not reserve: this is a STATED size. reserve is the
incremental hint append uses and deliberately leaves 79% headroom.
INIT(REFERENCE String s)
Bridge ctor — start with the contents of an immutable String. Both storages are UTF-32 code points, so this is a direct copy with no encode step.
REFERENCE: the source is borrowed and survives construction. It used
to be taken by value, which handed the constructor a whole String it
only ever read from.
INIT(REFERENCE DynamicString other)
Copy-construct from another DynamicString. Every owning class in the text/binary family now has a same-type copy constructor: String, ByteBuffer, DynamicString and DynamicByteBuffer.
REFERENCE, so the source is borrowed and this instance allocates its
own storage. It does NOT collide with the other constructors here — they
differ in parameter TYPE, which C++ overload resolution separates. What
it cannot separate is one type owned against REFERENCE; that is
why there is no owning companion anywhere in this family.
INIT(REFERENCE char32[] origin)
Construct from a raw code-point array, COPYING it. REFERENCE, so the
source is borrowed and the builder allocates its own storage — the same
rule the other three owning classes in this family follow.
Methods
METHOD clone() RETURNS DynamicString
Deep copy. Returns a fresh DynamicString with the same codepoints. Implements the Cloneable contract.
METHOD isEmpty() RETURNS boolean
O(1) emptiness test.
METHOD length() RETURNS int64
Code-point count, O(1). Storage is one codepoint per slot.
METHOD size() RETURNS int64
UTF-8 byte count of the stored text — distinct from length() (the code-point count). Storage is UTF-32 code points (Phase 8.7), so size() sums each code point's UTF-8 width per RFC 3629 (the same widths UTFCodec.encodeToUTF8 emits): U+0000–007F → 1 byte, U+0080–07FF → 2, U+0800–FFFF → 3, ≥ U+10000 → 4.
METHOD __op_index__(int64 i) RETURNS char32
Code point at index i. Declared as operator [] so the
only access syntax is s[i] — there is no public at()
method on DynamicString. Raises IndexOutOfBoundsError if i is out
of range — bounds check lives in _ValueArray<char32_t>::operator[].
METHOD equals(REFERENCE DynamicString other) RETURNS boolean
Compare codepoint content against another DynamicString. Value equality, delegated to the value array's own equals. That is not merely shorter: for an element type with a unique object representation the array compares with a single length-checked memcmp (one SIMD compare) where this method used to walk element by element. Measured at 6x faster on 64 elements and 11-14x from 1K up, with identical results across an 8-cell differential matrix — including the float guard, since the array deliberately does NOT memcmp an arithmetic element type (-0.0 == +0.0, NaN != NaN would come out wrong).
METHOD equals(REFERENCE String other) RETURNS boolean
Compare codepoint content against a String. Direct compare — both storages are UTF-32 codepoints.
METHOD isLessThan(REFERENCE DynamicString other) RETURNS boolean
Lexicographic codepoint comparison against another DynamicString.
METHOD compareTo(REFERENCE String other) RETURNS int32
Lexicographic codepoint comparison against a String. Returns -1/0/+1.
METHOD compareTo(REFERENCE char32[] otherData) RETURNS int32
Lexicographic codepoint comparison against a String. Returns -1/0/+1.
METHOD hash() RETURNS uint64
FNV-1a 64-bit hash over the UTF-32 codepoints. Matches String.hash() for identical text content (both fold over the same codepoint sequence).
METHOD hash(uint64 seed) RETURNS uint64
FNV-1a 64-bit hash with caller-supplied seed.
METHOD find(REFERENCE DynamicString needle) RETURNS | int64
First occurrence of needle in this DynamicString. Pipe-XOR:
SUCCESS yields the codepoint index of the match; FAILURE means no
match. This is the Searchable contract (case-sensitive). The scan is
the one canonical char32 scan in StringView — DynamicString builds a
full-span view over its own codepoints and forwards. A String-needle
overload is provided for convenience.
METHOD find(REFERENCE DynamicString needle, boolean caseMatch) RETURNS | int64
As find, with ASCII case-fold when caseMatch == FALSE. Views both
sides in place and runs the one canonical char32 scan in StringView.
This method used to snapshot BOTH sides to immutable Strings — two full
copies per call — on the belief that a char32[128+] field could not
bind to a REFERENCE char32[] parameter. E3 disproved it:
since SBO was removed both spellings are the same EvArray<char32_t>.
METHOD find(REFERENCE String needle) RETURNS | int64
Convenience: search for a String needle.
METHOD find(REFERENCE String needle, boolean caseMatch) RETURNS | int64
As find, with ASCII case-fold when caseMatch == FALSE. Views the
storage in place — no snapshot — and forwards to the canonical scan,
which owns the native fast path and its bounds re-derivation.
METHOD contains(REFERENCE String needle) RETURNS boolean
True iff needle occurs at least once (case-sensitive).
METHOD contains(REFERENCE String needle, boolean caseMatch) RETURNS boolean
METHOD count(REFERENCE String needle) RETURNS int64
Non-overlapping occurrence count of needle (case-sensitive).
Empty needle returns 0.
METHOD count(REFERENCE String needle, boolean caseMatch) RETURNS int64
METHOD view(int64 start, int64 len) RETURNS StringView
Viewable — a non-owning, bounded window over this builder's code points
without copying. The mutable half of the family had no view() until
Phase 5, because a view into a GROWABLE buffer is only safe once the
analyzer refuses to mutate the source while the view is live.
That lock now exists: a view() on a named variable arms the same
per-source mutation lock an iterator() does (E5003), so appending to
or truncating this builder while a view over it is in scope is a
compile-time error rather than a stale window.
What the lock does NOT cover is the view outliving this object — that is, it predates this method, and it already applies to String.view.
METHOD startsWith(REFERENCE String prefix) RETURNS boolean
True iff this builder begins with prefix.
Builds a StringView directly over .data — no snapshot. E3
established that a char32[128+] field binds to a REFERENCE char32[]
parameter: both lower to EvArray<char32_t>, and have since SBO was
removed. The view is a local, consumed before this method returns, and
nothing mutates the builder in between — so it needs none of the
mutation-lock machinery that a PUBLIC view() will require, and it
costs no copy. find above uses the same shape.
METHOD endsWith(REFERENCE String suffix) RETURNS boolean
True iff this builder ends with suffix.
METHOD lastIndexOf(REFERENCE String needle) RETURNS | int64
Index of the LAST occurrence of needle, pipe-XOR.
METHOD find_first_of(REFERENCE String set) RETURNS | int64
Index of the first code point that IS a member of set, pipe-XOR.
METHOD find_first_not_of(REFERENCE String set) RETURNS | int64
Index of the first code point that is NOT a member of set, pipe-XOR.
METHOD split(REFERENCE String delim) RETURNS String[]
Split on delim into an array of Strings. Empty delim
returns a single-element array containing a snapshot of this
DynamicString. Adjacent delimiters produce empty pieces; a
trailing delimiter produces an empty trailing piece. Receiver
is not mutated.
METHOD splitLines() RETURNS String[]
Split into lines on any of the Unicode line boundaries (same set as String.splitLines): LF, VT, FF (0x0A-0x0C), FS, GS, RS (0x1C-0x1E), CR and CR-LF (one boundary), NEL (U+0085), LS (U+2028), PS (U+2029). Terminators are NOT included; a trailing terminator does not yield a trailing empty piece. Receiver not mutated.
METHOD concat(REFERENCE String other) RETURNS String
Build a fresh String from this DynamicString's content followed
by other's. Non-modifying — receiver and other are both
unchanged. (To append in place, use the modifying append(String)
below.)
METHOD iterator() RETURNS ValueIterator[char32]
Snapshot to a String first, then return its iterator. The snapshot is an O(n) codepoint copy; subsequent iteration is O(1) per codepoint against the contiguous char32[] storage.
METHOD format(FormatArgument args...) RETURNS String
Format this text as a template. Compiled as
Formatter.format(<this>->toString(), …) — the one format renderer
(analyze/format_calls.py; format-argument-design.md §6) — so this body is
never reached. It names no Formatter: the conversion hosts depend on
DynamicString, and Formatter on them.
METHOD formatWith(BinaryMode mode, FormatArgument args...) RETURNS String
METHOD toString() RETURNS String
BRIDGE OUT — explicit snapshot to immutable String ----------- Direct codepoint copy into a fresh String. No decode step.
MODIFY METHOD toUpper() RETURNS STATUS
─── MODIFYING METHODS ───────────────────────────────────────── Mutate receiver in place; return STATUS. ASCII uppercase fold, in place. Codepoints >= 0x80 pass through. Full Unicode case mapping is V2.
MODIFY METHOD toLower() RETURNS STATUS
ASCII lowercase fold, in place.
MODIFY METHOD toTitleCase() RETURNS STATUS
ASCII title-case fold, in place: the first character of each word is
uppercased and the remainder of the word lowercased. Word boundaries are
ASCII whitespace, -, and ' (see isTitleBoundary). Codepoints >= 0x80
pass through uncased but do not break a word. Full Unicode case mapping is
V2 — the same limit toUpper / toLower carry.
MODIFY METHOD trim() RETURNS STATUS
Strip ASCII whitespace at both ends, in place.
MODIFY METHOD trimStart() RETURNS STATUS
MODIFY METHOD trimEnd() RETURNS STATUS
METHOD substring(int64 start, int64 len) RETURNS String
A NEW String over [start, start+length). PURE — the receiver is
untouched. Matches String.substring, which PANICs on a bad range
rather than returning a STATUS, so this does too.
MODIFY METHOD append(REFERENCE String s) RETURNS STATUS
BUILDER MUTATIONS — append ------------------------------------
MODIFY METHOD append(DynamicString d) RETURNS STATUS
MODIFY METHOD append(char32 c) RETURNS STATUS
Append one Unicode code point. Tier-1 text check rejects a noncharacter / surrogate / control code point with FAILURE.
MODIFY METHOD setAt(int64 i, char32 c) RETURNS STATUS
Assign the code point at i. Pipe-XOR on the index, and gated by the
same Tier-1 text check append(char32) applies — a DynamicString may
not be mutated into holding a surrogate, noncharacter or control.
int64, not the uint64 DynamicByteBuffer.setAt still takes; Phase 2
normalises that split and a new method should not join the wrong side.
MODIFY METHOD clear() RETURNS STATUS
Empty the builder, keeping its capacity. The mutable text class had no way to be cleared at all, while its byte peer did.
MODIFY METHOD truncate(int64 n) RETURNS STATUS
Drop code points from the END until length() == n. FAILURE if n
exceeds the current length or is negative — this never grows.
MODIFY METHOD dropFirst(int64 n) RETURNS STATUS
Drop the first n code points. O(length - n) shift left.
MODIFY METHOD prepend(REFERENCE String s) RETURNS STATUS
BUILDER MUTATIONS — prepend -----------------------------------
MODIFY METHOD prepend(DynamicString d) RETURNS STATUS
MODIFY METHOD prepend(char32 c) RETURNS STATUS
MODIFY METHOD replace(REFERENCE String needle, REFERENCE String replacement) RETURNS STATUS
BUILDER MUTATIONS — replace -----------------------------------
Replace every occurrence of needle with replacement, in
place. Empty needle returns FAILURE (avoids infinite-substitution).
MODIFY METHOD padStart(int64 targetLength, char32 padChar) RETURNS STATUS
BUILDER MUTATIONS — padStart / padEnd -------------------------
Left-pad with padChar until the receiver is targetLength
CODE POINTS long. Already-longer receivers are left alone.
MODIFY METHOD padEnd(int64 targetLength, char32 padChar) RETURNS STATUS
Right-pad with padChar until the receiver is targetLength
CODE POINTS long.
StringViewIMPLEMENTS View, Viewable
Non-owning, bounded slice over a code-point array.
A StringView is a short-lived locals-only descriptor. It carries a
REFERENCE char32[] source plus start + length (code-point offsets
into the source array), and exposes a narrow read-only surface — find /
contains / count, length / operator[] / iterator(), plus view() (narrow
to a sub-window — composition) and copy() (materialise the window into a
fresh char32[]; wrap with CREATE String(view->copy()) for an owned
String). It IMPLEMENTS View and Viewable.
STRING-FREE BY DESIGN. StringView references only char32[] and itself —
never String. This breaks what would otherwise be a String↔StringView
dependency cycle, so String can implement Viewable with a covariant
view() returning a (complete, emitted-first) StringView. Consequences:
the search needle is a StringView (wrap a needle String with
needleStr->view(0, needleStr->length())), copy() yields char32[],
and bounds violations PANIC IndexOutOfBoundsError(...) directly (bodies
emit out-of-line).
The REFERENCE field is safe by the same reference-checker rules the rest
of the kernel relies on: the source's lifetime must enclose the view's;
the source must not be re-bound underneath a live view; the view is
non-storable into another class. An empty view (length == 0) is permitted
— find reports not-found and iterator() is immediately exhausted — so
String can route search / iteration uniformly through a full-span view.
kernel/src/StringView.ev:45
Constructors
INIT(REFERENCE char32[] source, int64 start, int64 length)
Construct a bounded view over [start, start+length) in source.
Throws (via the C-string helper) if start < 0 or length < 0 or
start + length > source.length(). A zero length is allowed.
Methods
METHOD length() RETURNS int64
Code-point count of this view.
METHOD size() RETURNS int64
Countable — View EXTENDS Countable, so the view owes size() and
isEmpty() as well as its own length(). All three are the same
number here: the count of code points the window spans.
METHOD isEmpty() RETURNS boolean
METHOD __op_index__(int64 i) RETURNS char32
Code point at index i within this view. sv[i] is the only read
syntax. Throws (C-string helper) if i is out of [0, view.length).
METHOD find(REFERENCE char32[] needle) RETURNS | int64
First occurrence of needle (itself a view) within this view's whole
code-point range. Pipe-XOR: SUCCESS yields the view-relative index of
the match; FAILURE means no match. Case-sensitive — to search a
sub-range, narrow with view(start, length) first.
METHOD find(REFERENCE char32[] needle, boolean caseMatch) RETURNS | int64
As find, with ASCII case-fold when caseMatch == FALSE.
METHOD startsWith(REFERENCE char32[] needle) RETURNS boolean
True iff this view begins with needle (case-sensitive). An empty
needle returns TRUE; a needle longer than the view returns FALSE.
METHOD endsWith(REFERENCE char32[] needle) RETURNS boolean
True iff this view ends with needle (case-sensitive). An empty
needle returns TRUE; a needle longer than the view returns FALSE.
METHOD lastIndexOf(REFERENCE char32[] needle) RETURNS | int64
Last occurrence of needle within this view (case-sensitive). Pipe-XOR:
SUCCESS yields the view-relative index of the final match; FAILURE means
no match. An empty needle yields the view length. Scans backward from the
last candidate window, so the first hit found is the last occurrence.
METHOD contains(REFERENCE char32[] needle) RETURNS boolean
True iff needle occurs at least once in this view (case-sensitive).
METHOD contains(REFERENCE char32[] needle, boolean caseMatch) RETURNS boolean
METHOD count(REFERENCE char32[] needle) RETURNS int64
Non-overlapping occurrence count of needle in this view
(case-sensitive). Empty needle returns 0.
METHOD count(REFERENCE char32[] needle, boolean caseMatch) RETURNS int64
METHOD find_first_of(REFERENCE char32[] set) RETURNS | int64
B1: index of the first code point that IS a member of set. Pipe-XOR:
SUCCESS = the index; FAILURE = no code point in this view is in set.
METHOD find_first_not_of(REFERENCE char32[] set) RETURNS | int64
B1: index of the first code point that is NOT a member of set.
METHOD view(int64 start, int64 length) RETURNS StringView
Narrow to a sub-window [start, start+length) relative to THIS view
(composition — a sub-window of a window is a window). Bounds are
checked against this view's length, so a sub-view can never escape
its parent. Satisfies Viewable.
METHOD copy() RETURNS char32[]
Materialise this window's code points into a fresh char32[] (the "keep this slice" escape hatch — the view itself never escapes). Wrap with CREATE String(view->copy()) for an owned String. DEFECT FIXED. This used .source->copyTo(piece, length), which copies from the SOURCE'S index 0 and ignores .start — so any view whose window did not begin at 0 returned the wrong code points. _ValueArray::copyTo(other, n) takes no source offset, so it cannot express a windowed copy at all; the element loop below (which was here, commented out) is the only correct form. ByteBufferView.copy() never had the bug — it always used this shape.
It stayed latent because every caller passed a FULL-SPAN view
(view(0, length())), where .start is 0 and the two agree. The first
caller with a non-zero start was DynamicString.substring, added in
Phase 2, which is what surfaced it.
METHOD iterator() RETURNS ValueIterator[char32]
Walk the view's code points in order. The iterator snapshots the
bounded slice into its own storage at construction, so it is
independent of this view and its source char32[] for its entire
lifetime (matching ByteBufferIterator's design). The snapshot is
materialised inline because the emit does not currently auto-deref a
REFERENCE self-field when passed to a value-typed ctor param.
ByteBufferIMPLEMENTS Countable, Cloneable, Hashable, Equatable
Immutable opaque binary data container.
ByteBuffer is one of four sibling classes in the Envzn text/binary type system:
PURPOSE A handle to a chunk of opaque binary data — bytes whose meaning the language does not interpret. Once constructed the contents never change; transformations like subBuffer or concat return a new ByteBuffer. Display in human-readable form goes through HexCodec.toHex(...) (default separator " ", e.g. "3F 40 6A").
STORAGE
A single INTERNAL binary[] field. This lowers
to a contiguous, growable byte buffer
governed by the value-array storage shorthand of
ENVZN_CONSTITUTION.md §10.1. All positional accessors read via
.data[i]; appends are high-water-mark assignments at
.data[.data.length].
INDEXING SEMANTICS — BYTES, NOT CODE POINTS
Every positional method indexes in bytes. length() and size()
both exist and return the same number, because a byte IS the
storage unit; they differ only on the text axis. buf[i] returns a
binary primitive, not a char. 'binary' is an opaque char, aka
'unsigned char'.
ERROR-RETURN POLICY
One policy, shared with the text axis: [] raises a PANIC
IndexOutOfBoundsError, the find family is pipe-XOR
(int64 index | STATUS) with no -1 sentinel, and everything else
is total.
kernel/src/ByteBuffer.ev:54
Constructors
INIT()
CONSTRUCTORS / CLEANUP
INIT(REFERENCE binary[] origin)
Construct from a pre-built byte array, COPYING it. Every internal
transformation (subBuffer, concat, clone) constructs its result this
way: build a fresh binary[], hand it to a new ByteBuffer.
REFERENCE, not owning: the class allocates its own storage rather
than adopting the caller's. This was the last owning constructor in the
text/binary family and the only one that adopted caller memory — every
other kernel class allocates its own, so the outlier moved rather than
the pattern. It costs one copy per construction, and buys a uniform rule:
handing an array to a constructor never takes it away from you.
INIT(binary[] origin, int64 length)
Similar to String, we have an owning binary[] for performance
length IS REDUNDANT AND MUST NOT BE REMOVED.
INIT(REFERENCE ByteBuffer other)
Copy-construct from another ByteBuffer. One allocation, one bulk copy — the element loop this replaced wrote at the high-water mark, so the storage reallocated as it filled.
Methods
METHOD clone() RETURNS ByteBuffer
CLONE — hand-written. Hands the storage straight to the copying constructor, which reserves once and bulk-copies.
It used to build an intermediate binary[] byte by byte and hand THAT
over, which cost two full copies and an extra allocation: once into the
intermediate, once out of it. That shape made sense when the constructor
took the array by ownership and adopted the array; under REFERENCE the intermediate is
pure waste, because the constructor was going to copy anyway.
METHOD isEmpty() RETURNS boolean
INSPECTION
METHOD size() RETURNS int64
METHOD length() RETURNS int64
Byte count — the same number size() returns. On the byte axis the two
coincide, because a byte IS the storage unit; on the text axis they
differ (String.length() counts code points, String.size() counts
UTF-8 bytes). Both names exist on all six text/binary classes so a
caller never has to remember which axis they are holding.
METHOD __op_index__(int64 i) RETURNS binary
Byte at index i — buf[i] yields the raw binary. THE element
accessor: a pipe-XOR at() stood beside it until Phase 3, which left
the byte axis with two ways to read one byte and the text axis with one.
The bounds check lives in the lowered form which raises an PANIC IndexOutOfBoundsError out of range, mirroring String's code-point operator []. Delegating rather than range-checking here is deliberate: the array's PANIC carries the offending index and the bound in its message, and this class sits upstream of Formatter, so a PANIC written here could only say "out of bounds" with no numbers in it.
METHOD equals(REFERENCE ByteBuffer other) RETURNS boolean
COMPARISON Value equality, delegated to the value array's own equals. That is not merely shorter: for an element type with a unique object representation the array compares with a single length-checked memcmp (one SIMD compare) where this method used to walk element by element. Measured at 6x faster on 64 elements and 11-14x from 1K up, with identical results across an 8-cell differential matrix — including the float guard, since the array deliberately does NOT memcmp an arithmetic element type (-0.0 == +0.0, NaN != NaN would come out wrong).
METHOD isLessThan(REFERENCE ByteBuffer other) RETURNS boolean
Use the lexicographic comparision below
METHOD compareTo(REFERENCE ByteBuffer other) RETURNS int32
Lexicographic byte comparison: shorter buffer orders before a longer one when prefixes match. Returns -1 / 0 / 1.
METHOD find(REFERENCE ByteBuffer needle) RETURNS | int64
Searchable — first index at which needle's bytes occur in this
buffer, else FAILURE. Forwards to the one canonical binary scan in
ByteBufferView: a full-span view over this buffer searches for
needle's bytes.
METHOD lastIndexOf(REFERENCE ByteBuffer needle) RETURNS | int64
Index of the LAST occurrence of needle, pipe-XOR. The mirror of
find, forwarded through a full-span view the same way, so there is
exactly one byte scan in the kernel.
METHOD find_first_of(REFERENCE ByteBuffer set) RETURNS | int64
B1: index of the first byte that IS a member of set (the bytes of
set, treated as a set). Forwards through a full-span view.
METHOD find_first_not_of(REFERENCE ByteBuffer set) RETURNS | int64
B1: index of the first byte that is NOT a member of set.
METHOD view(int64 start, int64 length) RETURNS ByteBufferView
Viewable — a non-owning, bounded window over this buffer's bytes
without copying. The byte-side analogue of String.view.
METHOD hash() RETURNS uint64
HASHING — same FNV-1a as String, deterministic across runs FNV-1a 64-bit hash. Matches String.hash() and DynamicString.hash() byte-for-byte for identical content, so the three classes hash to the same uint64 when carrying the same bytes.
METHOD hash(uint64 seed) RETURNS uint64
Seeded FNV-1a, the peer of String.hash(uint64 seed). Chaining a seed
lets a composite key hash its parts in sequence without materialising a
concatenation.
METHOD contains(REFERENCE ByteBuffer needle) RETURNS boolean
CONTENT LOOKUP Empty needle returns true (matches String.contains).
METHOD startsWith(REFERENCE ByteBuffer prefix) RETURNS boolean
METHOD endsWith(REFERENCE ByteBuffer suffix) RETURNS boolean
METHOD find(REFERENCE ByteBuffer needle, int64 fromIndex) RETURNS | int64
First-occurrence index at or after fromIndex. Pipe-XOR:
FAILURE on out-of-range fromIndex or when needle does not
occur from that point onward.
METHOD count(REFERENCE ByteBuffer needle) RETURNS int64
Non-overlapping occurrence count. Empty needle returns 0 (avoids infinite-match scenario).
METHOD subBuffer(int64 start, int64 length) RETURNS ByteBuffer
SLICING / CONCATENATION
Copy a contiguous slice into a fresh ByteBuffer. start is inclusive,
length is a byte count. TOTAL, and the exact peer of
String.substring: a bad range is a precondition violation — a
programming error — so it raises a PANIC, the same category as [].
length == 0 yields an empty buffer and is not an error.
This returned pipe-XOR (ByteBuffer | STATUS) until Phase 3, which made
a caller slicing a buffer write an IF where the same caller slicing a
String writes none. A recoverable outcome is a search that misses; a
caller asking for bytes that were never there is a bug in the caller.
METHOD concat(REFERENCE ByteBuffer other) RETURNS ByteBuffer
Concatenation. Returns a fresh ByteBuffer; receivers unchanged. operator + pending — see.
METHOD iterator() RETURNS ByteBufferIterator
Yield a value-iterator over the bytes. The iterator copies the bytes into its own storage at construction — it is fully independent of this buffer for its whole lifetime.
METHOD data() RETURNS REFERENCE binary[]
Non-owning REFERENCE to the underlying binary[] storage. The
receiver retains ownership; the returned reference is valid
for the receiver's lifetime per §11.6 lifetime elision. The
canonical use is at a FOREIGN BIND call site that needs to
expose the byte storage to a C function without copying.
DynamicByteBufferIMPLEMENTS Countable, Cloneable, Hashable, Equatable
Stack-resident mutable binary builder.
DynamicByteBuffer is one of four sibling classes in the Envzn text/binary type system:
PURPOSE The binary builder. Mutate in place; snapshot to immutable ByteBuffer with toByteBuffer() when done. Mutating methods return STATUS only — no chaining.
ACCESS IDIOMS
Subscript read .data[i] returns binary. Subscript write at HWM
(.data[.data.length] = v) extends; in-range write replaces.
.data.length returns int32 (current logical length). .data.clear()
resets length to 0.
kernel/src/DynamicByteBuffer.ev:39
Constructors
INIT()
CONSTRUCTORS / CLEANUP
INIT(int64 reserve)
Pre-size the builder to reserve bytes — one allocation instead of the
growth schedule. that is
reserveExact, and the substrate's resize already handles the INLINE
spill. reserveExact and not reserve because this is a STATED size,
not the incremental hint append uses.
INIT(REFERENCE binary[] origin)
Construct from a raw byte array, COPYING it. DynamicString has had a raw-array constructor all along; the byte builder had none, so the only way in was append-in-a-loop.
REFERENCE, not owning: the class allocates its own storage rather than
adopting the caller's. That is what every kernel class does — the last
owning constructor in this family, ByteBuffer's, was retired in Phase 2.
INIT(REFERENCE DynamicByteBuffer other)
Copy-construct from another DynamicByteBuffer. Every owning class in the text/binary family now has a same-type copy constructor: String, ByteBuffer, DynamicString and DynamicByteBuffer.
REFERENCE, so the source is borrowed and this instance allocates its
own storage. It does NOT collide with the other constructors here — they
differ in parameter TYPE, which C++ overload resolution separates. What
it cannot separate is one type owned against REFERENCE; that is
why there is no owning companion anywhere in this family.
INIT(REFERENCE ByteBuffer other)
Methods
METHOD clone() RETURNS DynamicByteBuffer
CLONE — hand-written. Constructs a fresh DynamicByteBuffer and re-appends every byte through the public append() method, so we stay on the same write path as ordinary growth (no cross- instance private-field access). Mirrors DynamicString.clone().
METHOD isEmpty() RETURNS boolean
INSPECTION
METHOD size() RETURNS int64
METHOD length() RETURNS int64
Byte count — the same number size() returns. On the byte axis the two
coincide, because a byte IS the storage unit; on the text axis they
differ (String.length() counts code points, String.size() counts
UTF-8 bytes). Both names exist on all six text/binary classes so a
caller never has to remember which axis they are holding.
METHOD data() RETURNS REFERENCE binary[]
Non-owning REFERENCE to the underlying binary[512+]
storage. Mirror of ByteBuffer.data() (§11.6 lifetime
elision applies); canonical use is at a FOREIGN BIND call
site that needs to expose the byte storage to a C function
without copying.
METHOD iterator() RETURNS ByteBufferIterator
Snapshot iterator over the current bytes. Returns the shared ByteBufferIterator (the value-form ValueIterator OF binary used by ByteBuffer too): it copies the bytes in at construction, so the walk stays stable even if this mutable buffer is appended to afterward.
METHOD equals(REFERENCE DynamicByteBuffer other) RETURNS boolean
COMPARISON Value equality, delegated to the value array's own equals. That is not merely shorter: for an element type with a unique object representation the array compares with a single length-checked memcmp (one SIMD compare) where this method used to walk element by element. Measured at 6x faster on 64 elements and 11-14x from 1K up, with identical results across an 8-cell differential matrix — including the float guard, since the array deliberately does NOT memcmp an arithmetic element type (-0.0 == +0.0, NaN != NaN would come out wrong).
METHOD isLessThan(REFERENCE DynamicByteBuffer other) RETURNS boolean
Use the lexicographic comparison below.
METHOD compareTo(REFERENCE DynamicByteBuffer other) RETURNS int32
Lexicographic byte comparison. Shorter buffer orders before longer when prefixes match. Returns -1 / 0 / 1.
METHOD find(REFERENCE DynamicByteBuffer needle) RETURNS | int64
Searchable — first index at which needle's bytes occur in this
buffer, else FAILURE. Snapshots both sides to immutable ByteBuffers
and forwards to ByteBuffer.find — the one canonical byte scan.
METHOD hash() RETURNS uint64
HASHING FNV-1a 64-bit hash. Matches String.hash() / DynamicString.hash() / ByteBuffer.hash() byte-for-byte for identical content.
METHOD hash(uint64 seed) RETURNS uint64
METHOD contains(REFERENCE ByteBuffer needle) RETURNS boolean
CONTENT LOOKUP
METHOD startsWith(REFERENCE ByteBuffer prefix) RETURNS boolean
METHOD endsWith(REFERENCE ByteBuffer suffix) RETURNS boolean
METHOD find(REFERENCE ByteBuffer needle, int64 fromIndex) RETURNS | int64
First-occurrence index at or after fromIndex. Pipe-XOR:
FAILURE on out-of-range fromIndex or when needle does not
occur from that point onward.
METHOD count(REFERENCE ByteBuffer needle) RETURNS int64
Non-overlapping occurrence count. Empty needle returns 0 (avoids infinite-match scenario).
MODIFY METHOD append(binary b) RETURNS STATUS
MUTATIONS — return STATUS, mutate receiver in place
MODIFY METHOD append(REFERENCE ByteBuffer bb) RETURNS STATUS
MODIFY METHOD append(DynamicByteBuffer dbb) RETURNS STATUS
MODIFY METHOD prepend(binary b) RETURNS STATUS
MODIFY METHOD prepend(REFERENCE ByteBuffer bb) RETURNS STATUS
MODIFY METHOD setAt(int64 i, binary b) RETURNS STATUS
MODIFY METHOD clear() RETURNS STATUS
MODIFY METHOD truncate(int64 n) RETURNS STATUS
Drop bytes from the END until size() == n. FAILURE if n exceeds current size or n < 0 (no-grow contract).
MODIFY METHOD dropFirst(int64 n) RETURNS STATUS
Drop the first n bytes. O(size - n) shift left.
METHOD subBuffer(int64 start, int64 length) RETURNS ByteBuffer
A NEW ByteBuffer over [start, start+length). PURE — the receiver is
untouched. Same name, same meaning and same shape as
ByteBuffer.subBuffer, which is what the vertical rule requires — TOTAL
Raising a PANIC on a bad range like String.substring does.
METHOD __op_index__(int64 i) RETURNS binary
Byte at i. Throws IndexOutOfBoundsError out of range — the bounds
check lives in the value array's own subscript, exactly as ByteBuffer's
and String's do. The mutable class had no index operator at all, so
dbb[i] did not compile while bb[i] did.
METHOD view(int64 start, int64 length) RETURNS ByteBufferView
Viewable — a non-owning, bounded window over this builder's bytes
without copying. The mutable half of the family had no view() until
Phase 5, because a view into a GROWABLE buffer is only safe once the
analyzer refuses to mutate the source while the view is live.
That lock now exists: a view() on a named variable arms the same
per-source mutation lock an iterator() does (E5003), so appending to
or truncating this builder while a view over it is in scope is a
compile-time error rather than a stale window.
What the lock does NOT cover is the view outliving this object — that is, it predates this method, and it already applies to ByteBuffer.view.
METHOD lastIndexOf(REFERENCE ByteBuffer needle) RETURNS | int64
Index of the LAST occurrence of needle, pipe-XOR. Scans in place over
the backing rather than snapshotting to a ByteBuffer first — the same
choice find already makes here, and the one DynamicString.find still
does not. Once view() reaches the mutable classes this can forward to
ByteBufferView.lastIndexOf like the immutable peer does.
METHOD find_first_of(REFERENCE ByteBuffer set) RETURNS | int64
Index of the first byte that IS a member of set, pipe-XOR.
METHOD find_first_not_of(REFERENCE ByteBuffer set) RETURNS | int64
Index of the first byte that is NOT a member of set, pipe-XOR.
METHOD concat(REFERENCE ByteBuffer other) RETURNS ByteBuffer
A NEW ByteBuffer holding this buffer's bytes followed by other's.
Pure: this buffer is unchanged. The mutating sibling is append.
MODIFY METHOD padStart(int64 targetLength, binary padByte) RETURNS STATUS
Pad the FRONT with padByte until the buffer is targetLength long.
Already at or above the target is SUCCESS and a no-op. int64 rather
than the uint64 DynamicString still uses — the sign split across these
two classes is normalised in Phase 2, and a new method should not be
born on the wrong side of it.
MODIFY METHOD padEnd(int64 targetLength, binary padByte) RETURNS STATUS
Pad the END with padByte until the buffer is targetLength long.
MODIFY METHOD replace(REFERENCE ByteBuffer needle, REFERENCE ByteBuffer replacement) RETURNS STATUS
Replace every occurrence of needle with replacement. Empty
needle returns FAILURE (avoids infinite-substitution).
METHOD toByteBuffer() RETURNS ByteBuffer
BRIDGE OUT — explicit snapshot to immutable ByteBuffer
ByteBufferViewIMPLEMENTS View, Viewable
A non-owning, bounded window over a ByteBuffer's binary[] storage.
The byte-side mirror of StringView: it holds the one canonical binary
scan (find / contains / count) that ByteBuffer — and, via a ByteBuffer
snapshot, DynamicByteBuffer — forward into. Like StringView it is
ByteBuffer-free: it knows only binary[], so it introduces no
dependency cycle with the owning buffer types.
Bytes carry no case, so there is no case-fold variant — the scans are exact-byte only (the one structural difference from StringView).
kernel/src/ByteBufferView.ev:25
Constructors
INIT(REFERENCE binary[] source, int64 start, int64 length)
Construct a bounded view over [start, start+length) in source.
Raises a PANIC (via the C-string helper) if start < 0 or length < 0 or
start + length > source.length(). A zero length is allowed.
Methods
METHOD length() RETURNS int64
Byte count of this view.
METHOD size() RETURNS int64
Countable — View EXTENDS Countable, so the view owes size() and
isEmpty() as well as its own length(). All three are the same
number here: the count of octets the window spans.
METHOD isEmpty() RETURNS boolean
METHOD __op_index__(int64 i) RETURNS binary
Byte at index i within this view. bv[i] is the only read syntax.
Raises a PANIC (C-string helper) if i is out of [0, view.length).
METHOD find(REFERENCE binary[] needle) RETURNS | int64
First occurrence of needle's bytes within this view's whole range.
Pipe-XOR: SUCCESS yields the view-relative index of the match;
FAILURE means no match. To search a sub-range, narrow with
view(start, length) first.
METHOD startsWith(REFERENCE binary[] needle) RETURNS boolean
True iff this view begins with needle. An empty needle returns TRUE;
a needle longer than the view returns FALSE.
METHOD endsWith(REFERENCE binary[] needle) RETURNS boolean
True iff this view ends with needle. An empty needle returns TRUE;
a needle longer than the view returns FALSE.
METHOD lastIndexOf(REFERENCE binary[] needle) RETURNS | int64
Last occurrence of needle within this view. Pipe-XOR: SUCCESS yields
the view-relative index of the final match; FAILURE means no match. An
empty needle yields the view length. Scans backward from the last
candidate window, so the first hit found is the last occurrence.
METHOD contains(REFERENCE binary[] needle) RETURNS boolean
True iff needle occurs at least once in this view.
METHOD count(REFERENCE binary[] needle) RETURNS int64
Non-overlapping occurrence count of needle. Empty needle returns 0.
METHOD find_first_of(REFERENCE binary[] set) RETURNS | int64
B1: index of the first byte that IS a member of set. Pipe-XOR:
SUCCESS = the index; FAILURE = no byte in this view is in set.
METHOD find_first_not_of(REFERENCE binary[] set) RETURNS | int64
B1: index of the first byte that is NOT a member of set.
METHOD view(int64 start, int64 length) RETURNS ByteBufferView
Narrow to a sub-window [start, start+length) relative to THIS view
(composition — a sub-window of a window is a window). Bounds are
checked against this view's length, so a sub-view can never escape
its parent. Satisfies Viewable.
METHOD copy() RETURNS binary[]
Materialise this window's bytes into a fresh binary[] (the "keep this
slice" escape hatch — the view itself never escapes). Wrap with
CREATE ByteBuffer(view->copy()) for an owned ByteBuffer.
METHOD iterator() RETURNS ValueIterator[binary]
Walk this window's bytes in order. Mirrors StringView.iterator(),
which the byte axis had no counterpart to until now.
The window is materialised and GIVEN to the iterator. It cannot be
lent: .source is a REFERENCE field — a pointer — and does not bind to
a REFERENCE binary[] parameter, so the only array this view can offer
is a local snapshot, and lending a local returns an iterator over freed
storage. The owning constructor takes the array, so the
referent lives exactly as long as the iterator does.
ByteBufferIteratorIMPLEMENTS ValueIterator
Value-form iterator over a ByteBuffer.
ByteBufferIterator is the value-iterator counterpart to the collection iterators (ArrayIterator and friends), and mirrors StringIterator on the text axis.
It has TWO constructors, and they differ in what they do with the
bytes. The BORROWING form takes a window [start, start+length) of
an array the caller keeps owning, and aliases it — ByteBuffer and
DynamicByteBuffer pass their own field, which outlives the
iterator. The OWNING form takes the array outright and lends itself
the borrow, which is what a view must use: a view's .source is a
REFERENCE field, so the only array it can offer is a local snapshot,
and lending a local is an error.
The header used to say the bytes were "copied in — the iterator never aliases", which the single borrowing constructor had never done. Now one form aliases, one owns, and each says which.
IMPLEMENTS ValueIterator OF binary — a ByteBuffer's storage yields bytes by value, not by reference, so the iterator advances with nextValue() / peekValue() / skipValue() rather than the by-reference forms ReferenceIterator (the collection iterators) carries.
STORAGE
Five fields: snapshot storage used only by the owning constructor,
the borrowed payload, the window offset, a cached length, and a
cursor. Every read indexes .data[.start + .cursor], so a window
that does not begin at zero walks the right bytes.
kernel/src/ByteBufferIterator.ev:50
Constructors
INIT(REFERENCE binary[] source, int64 start, int64 length)
BORROWING form — built by ByteBuffer.iterator() and
DynamicByteBuffer.iterator(), which pass their own binary[] FIELD
plus the window [start, start+length). The iterator ALIASES that
storage, so the argument must outlive the iterator. Both owners pass the
whole array (0, .data.length).
INIT(binary[] snapshot)
OWNING form — the iterator takes the array and lends itself the borrow.
.data =@ .owned is SELF-rooted, so the referent lives exactly as long
as the iterator does and the dangle cannot arise. This is the
form ByteBufferView.iterator() uses.
It is separable from the borrowing form ONLY because their arities
differ. Two one-argument constructors over the same EvArray<uint8_t>,
one owning and one REFERENCE, lower to by-value and const-reference
and clang rejects the pair as ambiguous — which is what blocked
ByteBufferView.iterator() through Phase 1.
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD nextValue() RETURNS | binary
Value-form advance — copy out the byte at the cursor, then step the cursor forward. FAILURE at end-of-iteration.
METHOD peekValue() RETURNS | binary
The byte at the cursor without advancing. FAILURE at end.
MODIFY METHOD skipValue(uint64 n) RETURNS | binary
Move the cursor forward by n and return the byte there.
FAILURE if that would pass the end. skipValue(0) == peekValue().
MODIFY METHOD nextBytes(int64 numberOfBytes) RETURNS | binary[]
Block read: copy up to numberOfBytes bytes from the cursor into
a fresh binary[] and advance the cursor past them. Returns fewer
than requested when the buffer is exhausted first (the caller
checks .length); FAILURE only when the cursor is already at the
end, or numberOfBytes is not positive. The block-oriented
counterpart to byte-at-a-time nextValue(), mirroring the
(binary[] | STATUS) shape of File.read().
Arrays, lists, queues, sets and dictionaries, with their iterators.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
ArrayIMPLEMENTS Cloneable, Collection
Opaque-size, ordered, indexable collection.
The foundation collection class. Stack, Queue, Deque, LinkedList, Set, and SortedList all compose on top of Array's storage; the hash-based collections (Dictionary) keep their own backing.
Element access is by integer index in 0..length-1. Out-of-bounds reads raise a PANIC IndexOutOfBoundsError; out-of-bounds writes raise the same. Mutation methods come in move and copy pairs:
For class-typed T, COPY routes through Cloneable.clone(); T must implement Cloneable for any *Copy method to be reachable.
Removal:
Inspection without removal:
Iteration:
Sorting and search:
Functional transforms (map / filter / reduce) are pure-Envzn loops over the element domain and return new Arrays.
The storage shorthand T[] is the same physical layout as
Array[T]; the difference is API surface. T[] exposes only the
minimal value-array surface (subscript read + HWM write proxy,
.length, .capacity, clear(), remove(i), iterator());
Array[T] does the richer work (append / insertAt / count / sort …)
on top of that surface and maintains a public length field. The
sole developer-visible difference between int32[] and an object
T[] is that object elements must relocate with := (a move),
never a plain =.
kernel/src/Array.ev:71
Constructors
INIT()
Default constructor
INIT(int64 presized)
Presized constructor to reduce the malloc activity
Methods
METHOD iterator() RETURNS ArrayIterator[T]
Returns a fresh ArrayIterator[T] at position 0 — the FINAL
concrete iterator class (covariant against the inherited
Iterable.iterator() shape). Each call returns an independent
iterator; multiple may exist concurrently on the same Array.
The concrete return type lets the emitter inline hasNext() /
next() on FOR/IN loops over Array; callers binding to
BidirectionalIterator OF T still typecheck via class-to-
interface upcast.
METHOD size() RETURNS int64
Number of elements currently stored. Read-only, O(1).
METHOD isEmpty() RETURNS boolean
Countable — the other half of size(). Array carries the whole
Collection contract now (size, isEmpty, iterator), and none of
the three asks anything of T: that is what lets Array join Collection
while keeping its qualifier at Cloneable-or-primitive.
METHOD clone() RETURNS Array[T]
Deep copy. Each element is cloned via T->clone(); T must
implement Cloneable when T is a class type.
For T IS Inoperative (opaque only today): returns
an empty Array — Inoperative values are opaque so we can't
preserve them on clone.
MODIFY METHOD append(T value) RETURNS STATUS
Append value to the end. Per §10.2 the bare-named form
consumes the source — value is moved into the array and
the caller's source is poisoned (post-call use is a compile
error). For a deep-copy variant that leaves the caller's source
valid, use appendCopy. O(1) amortised.
EMPTY-reject (class-typed T only): an EMPTY class-handle
value is refused with FAILURE before any state change — the
collection only ever holds real owned objects, so every
subsequent peek/pop/at sees a populated slot. Per §9.3 IS VALID
is meaningful only on class handles; the check is gated via
WHEN T IMPLEMENTS Cloneable (the kernel's proxy for
"class-shaped T") and elided for primitive / struct T.
MODIFY METHOD appendCopy(REFERENCE T value) RETURNS STATUS
Append a deep copy of value to the end. value stays fully
valid for the caller after the call. For class-typed T, the
copy goes through T->clone(); T must implement Cloneable. For
primitive/struct T, value-copy. O(1) amortised. Returns SUCCESS,
or FAILURE if backing storage rejected the insert.
METHOD __op_index__(int64 index) RETURNS MUTABLE REFERENCE T
Reference to element at index i. Throws IndexOutOfBoundsError if i is out
of range — bounds check lives in _EvArray<char32_t>::operator[]. A
borrow-propagating ("mirror") accessor: the result mirrors the receiver's
mutability (mutable array -> MUTABLE REFERENCE, const -> read-only REFERENCE).
METHOD subscript(int64 index) RETURNS | MUTABLE REFERENCE T
Bounds-checked reference into the element at index — the lowering
target for arr[idx] syntax on Array[T] receivers, and a borrow-
propagating ("mirror") accessor: SUCCESS populates result with a
reference that mirrors the receiver's mutability (a mutable array
yields a MUTABLE REFERENCE for in-place modification, a const array a
read-only REFERENCE); out-of-bounds populates s with FAILURE. Caller
pattern: IF arr[i] THEN { binding REFERENCE T r =@ $RETURNED, then using r,
} ELSE { log($!) }. The
reference is valid only while the Array is not mutated (mutation lock).
Replaces the former at / subscript / mutableAt accessor set.
MODIFY METHOD setAt(int64 index, T value) RETURNS STATUS
Replace the element at index. Per §10.2 the bare-named form
consumes the source — value is moved into the array and
the caller's source is poisoned. The previous element is
destroyed. Returns FAILURE on out-of-bounds.
MODIFY METHOD setAtCopy(int64 index, REFERENCE T value) RETURNS STATUS
Replace the element at index with a deep copy of value.
value stays valid for the caller. Throws IndexOutOfBoundsError
on bad index.
MODIFY METHOD insertAt(int64 index, T value) RETURNS STATUS
Insert value at index, shifting subsequent elements right
by one. Per §10.2 the bare-named form consumes the source —
value is moved into the array and the caller's source is
poisoned. Valid index is 0..length inclusive (index == length
appends). Returns FAILURE on out-of-bounds. O(n) — shifts
everything to the right of the insertion point.
MODIFY METHOD insertAtCopy(int64 index, REFERENCE T value) RETURNS STATUS
Insert a deep copy of value at index. value stays valid.
Same index rules and complexity as insertAt.
MODIFY METHOD swap(int64 i, int64 j) RETURNS STATUS
Exchange the elements at i and j in place. Nothing is copied and no
slot is ever empty — this is how an element moves WITHIN an array, since
arr[k] := arr[j] is E6040 (a subscript is a reference to a slot the
array keeps owning). Returns FAILURE if either index is out of bounds.
MODIFY METHOD replace(int64 index, T value) RETURNS | T
Put value at index and hand back the element it displaced. Per
§10.2 value is consumed. Unlike setAt, which destroys the previous
element, this returns it — the owned counterpart of reading arr[i].
Pipe-XOR: FAILURE on out-of-bounds. O(1): the new element is parked at
the tail, swapped into place, and the old one is removed from the tail,
where removal shifts nothing.
MODIFY METHOD remove(int64 index) RETURNS | T
Remove the element at index and return it. Pipe-XOR:
SUCCESS populates removed with the value moved out of the
array; FAILURE populates status with the bounds violation.
Subsequent elements shift down. O(n). index is int64.
MODIFY METHOD clear() RETURNS void
Remove all elements; the array becomes empty.
METHOD map(LAMBDA func) RETURNS Array[T]
Apply func to every element; return a new Array with the
transformed values, in the same order.
METHOD filter(LAMBDA pred) RETURNS Array[T]
Return a new Array containing only the elements for which
pred(elem) is TRUE, in their original order.
MODIFY METHOD reduce(REFERENCE T initial, LAMBDA acc) RETURNS T
Fold left: starting with initial, repeatedly apply
acc(accumulator, elem) for each element in order. Returns
the final accumulator value.
MODIFY METHOD shuffle(MUTABLE REFERENCE Shuffler rng) RETURNS void
Shuffleable OF T — in-place Fisher-Yates.
Lives on Array, not OrderedArray, so every subclass inherits it. It
costs Array nothing: the storage's swap works for every T Array's
qualifier admits, so no interface requirement is added by its being here. It
was also the one method whose presence on OrderedArray contradicted
that class: shuffling destroys exactly the ordering the name promises. Walks from the last index
down, swapping each element with a uniformly-chosen earlier-or-equal
slot drawn from rng. The exchange is the storage's own swap: no
clones, one form for every T. (It used to clone both elements of a
class T and move the clones back in — two deep copies per step.)
ArrayIteratorIMPLEMENTS BidirectionalIterator
Concrete BidirectionalIterator OF T for Array[T].
An Array[T]'s ->iterator() method yields a fresh ArrayIterator[T]
at position 0. Multiple iterators on the same Array are independent
(each has its own cursor); the source Array is locked against
mutation while any iterator is held (per §Iterator's mutation-lock
rule).
Notable:
The iterator holds a REFERENCE T[] source directly into
the source Array's data storage (collection storage shorthand) — validated under §REFERENCE structural condition 2
(mutation-locked at INIT). All element access goes through the
T[] implicit methods (->size(), [i]).
kernel/src/ArrayIterator.ev:35
Constructors
INIT(REFERENCE T[] source)
constructor that requires a REFERENCE
The iterator never owns the vector — .source is a
REFERENCE field, not
an owning copy — so a const reference is the correct shape
and accepts both const-source (Array's iterator() is non-
mutating) and non-const-source call sites.
Methods
METHOD hasNext() RETURNS boolean
returns TRUE if we've not reached the end
MODIFY METHOD next() RETURNS | REFERENCE T
Pipe-XOR: SUCCESS populates the value slot with a non-owning
reference; end-of-iteration populates STATUS with FAILURE.
a REFERENCE is non-owning, so referencing it is
harmless; only the by-value lift (popFirst/popLast) rejects opaque.
This matches Array.at, which has never guarded opaque.
METHOD peek() RETURNS | REFERENCE T
peek at the next item without advancing the iterator
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE T
skip(n) — moves cursor forward by n positions. Parameter is unsigned per spec §Iterator (forward-only contract). Pipe-XOR: SUCCESS with the element at the new position, or FAILURE if out of bounds. skip(0) is equivalent to peek().
METHOD hasPrevious() RETURNS boolean
returns TRUE if the iterator is not at the first element
MODIFY METHOD previous() RETURNS | REFERENCE T
mirror of next: on SUCCESS, it returns a REFERENCE to the value and decrements the iterator's cursor; on FAILURE it returns only the status message
MODIFY METHOD skipBack(uint64 n) RETURNS | REFERENCE T
skipBack(n) — moves cursor backward by n positions. Symmetric counterpart to skip(n) on BidirectionalIterator. Pipe-XOR: SUCCESS with the element at the new position, or FAILURE if start is reached. skipBack(0) is equivalent to peek().
OrderedArrayEXTENDS Array
Opaque-size, ordered, indexable collection.
The foundation collection class. Stack, Queue, Deque, LinkedList, Set, and SortedList all compose on top of Array's storage; the hash-based collections (Dictionary) keep their own backing.
Element access is by integer index in 0..length-1. Out-of-bounds reads raise IndexOutOfBoundsError; out-of-bounds writes raise the same. Mutation methods come in move and copy pairs:
For class-typed T, COPY routes through Cloneable.clone(); T must implement Cloneable for any *Copy method to be reachable.
Removal:
Inspection without removal:
Iteration:
Sorting and search:
Functional transforms (map / filter / reduce) are pure-Envzn loops over the element domain and return new Arrays.
The storage shorthand T[] is the same physical layout as
Array[T]; the difference is API surface. T[] exposes only the
minimal value-array surface (subscript read + HWM write proxy,
.length, .capacity, clear(), remove(i), iterator());
Array[T] does the richer work (append / insertAt / count / sort …)
on top of that surface and maintains a public length field. The
sole developer-visible difference between int32[] and an object
T[] is that object elements must relocate with := (a move),
never a plain =.
kernel/src/OrderedArray.ev:71
Constructors
INIT()
Default constructor
INIT(int64 presized)
for presized Stack allocation
Methods
OVERRIDE METHOD clone() RETURNS OrderedArray[T]
Deep copy. Each element is cloned via T->clone(); T must
implement Cloneable when T is a class type.
For T IS Inoperative (opaque only today): returns
an empty Array — Inoperative values are opaque so we can't
preserve them on clone.
MODIFY METHOD sort() RETURNS void
In-place insertion sort using T->isLessThan(other). T must
implement Comparable[T] — the compiler emits a clear "T does
not implement Comparable" diagnostic at instantiation otherwise.
Each element is walked down by swapping it with its left neighbour
while it is strictly smaller, so equal elements keep their order
(stable). No element is copied and no slot is ever empty: the old
form lifted the element out with T key := .data[i], which is a move
from a reference (E6040) and silently deep-cloned every key.
O(n^2) worst case; acceptable for the small-N collections this
V1 kernel typically holds. A heap-or-merge-sort upgrade is a
V2 candidate if profiling demands it.
METHOD contains(REFERENCE T value) RETURNS boolean
Linear scan for an element equal to value. T must implement
Equatable[T] for class T. O(n).
METHOD equals(REFERENCE OrderedArray[T] other) RETURNS boolean
Element-wise equality. Two arrays are equal when they are the same
length and every element at the same index is equal — which makes two
EMPTY arrays equal, the case the previous form got wrong: it seeded
result = FALSE and only ever set it TRUE from inside the element
loop, so a pair of empty arrays passed the length test, never entered
the loop, and were reported UNEQUAL.
METHOD isLessThan(REFERENCE OrderedArray[T] other) RETURNS boolean
LEXICOGRAPHIC, the same order String.isLessThan settled on and for the
same reason. The first differing element decides; if neither array
differs through the shorter one's length, the shorter is less — so a
prefix sorts before what extends it.
This returned .length < other.length. Length-first is a different
total order, not a cheaper route to this one: it ranks [9] below
[1,1] and calls every pair of same-length arrays equal-or-greater
regardless of content, which silently reorders any OrderedArray-keyed
RedBlackTreeDictionary and makes sort() over arrays-of-arrays wrong.
NativeArrayNativeArray — what T[] and T[N+] are.
A developer writes T[], never NativeArray: this is the primitive's backing
class, as Number is number's. Its store is the floor's EvArr.
Every element is reached through the floor: ev_arr_at (a borrow of a cell),
ev_arr_put (moves a value into a cell) and ev_arr_take (moves a cell out).
C moves bytes; what a value means — its drop, its clone, its equality — is
written here, so the loops below are ordinary Envzn.
The array owns its block and its elements. INIT allocates, CLEANUP is the one
place either is released, and the array is moved, never byte-copied: a copy
is clone().
kernel/src/NativeArray.ev:58
Constructors
INIT()
CREATE(): room for four elements.
INIT(int64 n)
CREATE(n): room for n elements, with length 0.
Methods
METHOD length() RETURNS int64
The live elements.
METHOD capacity() RETURNS int64
The allocated slots.
MODIFY METHOD reserve(int64 n) RETURNS void
Room for at least n elements, keeping the 79% growth trigger: the
incremental hint a caller appending in a loop gives.
MODIFY METHOD reserveExact(int64 n) RETURNS boolean
Room for exactly the n elements the caller names: no growth heuristic.
FALSE, with the array unchanged, when the block cannot be allocated.
MODIFY METHOD clear() RETURNS void
Drop every element; length becomes 0 and the block is kept.
METHOD __op_index__(int64 i) RETURNS MUTABLE REFERENCE T
a[i] — a checked read: the cell, borrowed.
MODIFY METHOD __op_set_index__(int64 i, T value) RETURNS void
a[i] = v — the high-water write (I.J.i): grows to i + 1 if needed, then the value moves in. A gap it opens reads as EMPTY / zero, or a value class's default (E1159).
MODIFY METHOD append(T value) RETURNS void
The value moves in at the end: the write []= makes at index .length,
where there is no old value to take out.
MODIFY METHOD appendRange(REFERENCE NativeArray[T] other) RETURNS void
Append a copy of every element of other, which may be this array.
MODIFY METHOD remove(int64 i) RETURNS T
Move element i out, sliding the tail down one slot.
MODIFY METHOD swap(int64 i, int64 j) RETURNS void
Exchange elements i and j.
METHOD copyTo(MUTABLE REFERENCE NativeArray[T] dst, int64 n) RETURNS void
dst becomes a copy of this array's first n elements; its old ones are dropped.
MODIFY METHOD convertFrom(REFERENCE U[] src, int64 n) RETURNS void
METHOD equals(REFERENCE NativeArray[T] other) RETURNS boolean
The same length and every element equal.
METHOD clone() RETURNS NativeArray[T]
A deep copy: each element's own copy.
NativeNdArrayNativeNdArray — what T[,] (any rank, runtime extents) is.
A developer writes T[,], never NativeNdArray: this is the primitive's
backing class. Its store is the floor's EvNdArr, column-major: cell c of
coordinates p is c = p[0] * strides[0] + … + p[rank - 1] * strides[rank - 1].
Every cell is reached by that flat index through the floor, as NativeArray
reaches its elements: ev_ndarr_at (a borrow of a cell), ev_ndarr_put (moves a
value in) and ev_ndarr_take (moves a cell out). C moves bytes; a cell's drop,
clone and equality are written here.
The array owns its block and its cells. INIT allocates, CLEANUP is the one
place either is released, and the array is moved, never byte-copied: a copy
is clone(). Its extents are fixed at INIT; reshapeTo re-extents without
moving a cell, and nothing grows it.
kernel/src/NativeNdArray.ev:51
Constructors
INIT(REFERENCE int64[] extents)
T[m, n, …]: one extent per axis (1 to 15), every cell EMPTY / zero, or a
value class's default (its INIT(), E1159). An
extent is int64 in the language and int32 in the store; a negative one, or one
past int32, is a MathError, never an empty axis (§11).
Methods
METHOD count() RETURNS int64
The cells: the extents multiplied out.
METHOD rank() RETURNS int64
The axes.
METHOD dim(int64 k) RETURNS int64
The extent of axis k.
METHOD stride(int64 k) RETURNS int64
The column-major stride of axis k: the product of every extent below it.
METHOD isContiguous() RETURNS boolean
A native N-D array is one dense column-major block.
MODIFY METHOD fill(REFERENCE T v) RETURNS void
Every cell becomes a copy of v; the caller keeps v.
MODIFY METHOD swap(int64 coords...) RETURNS void
Exchange two cells, given as the full coordinates of both: rank for the
first, then rank for the second (grid->swap(i0, j0, i1, j1)).
MODIFY METHOD reshapeTo(int64 extents...) RETURNS boolean
Re-extent to extents, one per axis, when the cell count is unchanged; no
cell moves. FALSE, with the array unchanged, when the count differs (a
negative extent counts as zero).
METHOD equals(REFERENCE NativeNdArray[T] other) RETURNS boolean
The same extents and every cell equal.
METHOD clone() RETURNS NativeNdArray[T]
A deep copy: the same extents, and each cell's own copy.
METHOD copyInto(MUTABLE REFERENCE NativeNdArray[T] dest) RETURNS void
Copy every cell into dest, which has as many: each cell dest held is dropped
and replaced by its own copy of this array's cell, and an EMPTY cell stays EMPTY
(§7). It is how a whole-array value reaches a fixed T[M,N], which is C's cells
and has no copy of its own: float64[2,2] fp := p * q copies the product into
a view of fp (native-array-primitive-design §19.13, Brian).
METHOD __op_plus__(REFERENCE NativeNdArray[T] other) RETURNS NativeNdArray[T]
a + b, a - b, a * b: element by element over two arrays of one shape (a
Hadamard product, not a matrix one — linear algebra is AdvancedMath's). The
analyzer refuses unequal ranks (E2125) and a non-numeric element (E2132).
METHOD __op_minus__(REFERENCE NativeNdArray[T] other) RETURNS NativeNdArray[T]
METHOD __op_times__(REFERENCE NativeNdArray[T] other) RETURNS NativeNdArray[T]
DequeIMPLEMENTS Cloneable, Collection
Defines the Deque[T] class per ENVZN_CONSTITUTION §Deque (L659–680).
Deque[T] is a double-ended queue: O(1) push and pop at either end, no random-access indexing, no mid-list operations. The contract is intentionally narrower than LinkedList[T] — Deque is a LinkedList with a constrained API surface that names the ends as "front" and "back" rather than "first" and "last."
Composes on LinkedList[T], which provides exactly Deque's contract:
- O(1) at both ends (LinkedList.prepend / append / popFirst /
popLast / peekFirst / peekLast).
- BidirectionalIterator OF T.
- Cascading clone() via Cloneable.
So Deque is pure delegation — no new storage, no new iterator,
just a renamed-and-narrowed view over LinkedList.
kernel/src/Deque.ev:29
Constructors
INIT()
Methods
METHOD clone() RETURNS Deque[T]
Hand-written clone() — AUTO refused for the same cascade reason as Queue / Stack / LinkedList: the synthesis walker can't see T's Cloneable status from this instantiation site through the LinkedList[T] composition. Walk the underlying LinkedList's iterator and pushBack a deep clone of each element — ordering preserved (front-to-back).
METHOD iterator() RETURNS LinkedListIterator[T]
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of elements currently stored. Read-only, O(1).
MODIFY METHOD clear() RETURNS void
MODIFY METHOD pushFront(T value) RETURNS STATUS
FRONT-SIDE OPERATIONS — pushFront / popFront / peekFront
MODIFY METHOD pushFrontCopy(REFERENCE T value) RETURNS STATUS
MODIFY METHOD popFront() RETURNS | T
METHOD peekFront() RETURNS | REFERENCE T
MODIFY METHOD pushBack(T value) RETURNS STATUS
BACK-SIDE OPERATIONS — pushBack / popBack / peekBack
MODIFY METHOD pushBackCopy(REFERENCE T value) RETURNS STATUS
MODIFY METHOD popBack() RETURNS | T
METHOD peekBack() RETURNS | REFERENCE T
QueueEXTENDS Stack
Defines the Queue[T] class per ENVZN_CONSTITUTION §Queue.
Queue[T] is a FIFO collection implemented as a thin layer over
Array[T] (a.k.a. T[]). All storage and per-element ownership
semantics live in Array[T]; Queue contributes the FIFO discipline
and the public count field. Front is index 0, back is the last
element — enqueue appends, dequeue removes from index 0.
Performance note (Path B-pragmatic tradeoff):
- enqueue / enqueueCopy are O(1) amortised — same as Stack push
- dequeue is O(n) — removes from index 0; Array shifts elements down
- peek is O(1)
Callers who need O(1) dequeue should use Deque[T], which gets its
own std::deque backing (per Path B-pragmatic split — see
project_kernel_demagic_stage22.md memory). Queue-on-Array eats
the dequeue cost in exchange for a single backing storage shape
shared with Stack and SortedList.
kernel/src/Queue.ev:31
Constructors
INIT()
default constructor
INIT(int64 presized)
for presized Stack allocation
Methods
OVERRIDE METHOD clone() RETURNS Queue[T]
Deep copy. Each element is cloned via T->clone(); T must
implement Cloneable when T is a class type.
For T IS Inoperative (opaque only today): returns
an empty Array — Inoperative values are opaque so we can't
preserve them on clone.
MODIFY METHOD enqueue(T value) RETURNS STATUS
Add value at the back of the queue. Per §10.2 the bare-named
form consumes the source — value is moved through Array's
owning append into the queue's backing.
MODIFY METHOD enqueueCopy(REFERENCE T value) RETURNS STATUS
Deep-copy form of enqueue. value stays valid for the caller;
the clone is what the backing array stores.
OVERRIDE METHOD peek() RETURNS | REFERENCE T
Remove and return the front element. Pipe-XOR: SUCCESS populates
value; FAILURE when the queue is empty. O(n) — depends on Array
providing popFirst() with move-out semantics for class T.
FIFO peek — the FRONT element, which is NOT what Stack.peek()
returns.
Queue EXTENDS Stack, and Stack's peek() is LIFO: it forwards to
peekLast(). Inherited unchanged, a Queue reported its most recently
ENQUEUED element as its front — dequeue() (which uses popFirst) and
peek() disagreed about which end the queue's head is. queueSmoke caught
it as "expected 11, got 22".
OVERRIDE is required here (W7020): this reimplements a CONCRETE inherited method rather than fulfilling an abstract contract.
MODIFY METHOD dequeue() RETURNS | T
StackEXTENDS Array
Defines the Stack[T] class per ENVZN_CONSTITUTION §Stack.
Stack[T] is a LIFO collection implemented as a thin layer over Array[T] (a.k.a. T[]). All storage and per-element ownership semantics live in Array[T]; Stack contributes the LIFO discipline and the public count field.
Design philosophy: by building Stack on Array[T], all the FOREIGN/T-substitution/ownership questions surfaced by the original Stack.ev preview are relocated to Array[T] — exactly once, instead of once per collection. See Array.ev (forthcoming) for those questions resolved.
kernel/src/Stack.ev:25
Constructors
INIT()
default constructor
INIT(int64 presized)
for presized Stack allocation
Methods
OVERRIDE METHOD clone() RETURNS Stack[T]
Deep copy. Each element is cloned via T->clone(); T must
implement Cloneable when T is a class type.
For T IS Inoperative (opaque only today): returns
an empty Array — Inoperative values are opaque so we can't
preserve them on clone.
MODIFY METHOD push(T value) RETURNS STATUS
Push value onto the top. Per §10.2 the bare-named form
consumes the source — value is moved through Array's owning
append onto the stack's backing.
MODIFY METHOD pushCopy(REFERENCE T value) RETURNS STATUS
Deep-copy form of push. value stays valid for the caller;
the clone is what the backing array stores.
MODIFY METHOD pop() RETURNS | T
Remove and return the top element. Pipe-XOR: SUCCESS populates
value; FAILURE when the stack is empty. Depends on Array
providing popLast() with move-out semantics for class T.
METHOD peek() RETURNS | REFERENCE T
Return (without removing) the top element as a REFERENCE handle. Multi-return per the kernel peek contract — STATUS == FAILURE when empty, SUCCESS otherwise. Delegates to Array.peekLast.
MODIFY METHOD popLast() RETURNS | T
Remove and return the last element. FAILURE if empty. Ownership
of the returned element transfers to the caller. O(1).
For T IS Inoperative (opaque): always returns FAILURE —
the stored payload is opaque and can't be lifted out by-value.
MODIFY METHOD popFirst() RETURNS | T
Remove and return the first element. FAILURE if empty. O(n) — shifts every remaining element down by one. For T IS Inoperative: always returns FAILURE (see popLast).
METHOD peekLast() RETURNS | REFERENCE T
Read the last element without removing it. STATUS is FAILURE
when the array is empty (value is EMPTY); SUCCESS otherwise
with value referencing the element in place. The REFERENCE
handle is valid only while no mutation occurs on the Array.
METHOD peekFirst() RETURNS | REFERENCE T
Read the first element without removing it. Same pipe-XOR shape as peekLast.
SortedListIMPLEMENTS Cloneable, Collection
Defines the SortedList[T] class per ENVZN_CONSTITUTION §SortedList (L703–716).
SortedList[T] is a collection that maintains its elements in
ascending order (per T->isLessThan) at all times. Insertion
walks to the sort position and splices; the order is invariant
across the public API — there is no operation that produces an
out-of-order sequence.
Composes on LinkedList[T], as do Stack and Queue — one backing
store shared across the composed collections. LinkedList provides
mid-chain insert/remove via its insertAt / removeAt methods;
SortedList drives them with a Comparable-aware position search.
────────────────────────────────────────────────────────────────── ORDER INVARIANT ──────────────────────────────────────────────────────────────────
At every public-API boundary, for any two indices i < j in the
list, the element at i is isLessThan the element at j OR
isEqualTo the element at j. Duplicates (per Equatable.isEqualTo,
inherited via Comparable[T] EXTENDS Equatable[T]) are allowed and
stored adjacently.
────────────────────────────────────────────────────────────────── SHORT-CIRCUIT SEARCH ──────────────────────────────────────────────────────────────────
Because the list is always sorted, contains and remove walk
from the front and stop early when they cross the value's
expected position:
contains(v): scan from the head; if v->isLessThan(elem)
becomes TRUE, the value is not present (any further elements
are >= elem > v).remove(v): same short-circuit; the first match is the
one removed (matches duplicates' adjacent-storage rule).Mean-case work is O(n/2) for both; worst-case is O(n). A real production version could replace LinkedList with a balanced tree (red-black, AVL) for O(log n), but that's a much larger implementation. This V1 form trades sorted-search complexity for implementation simplicity.
kernel/src/SortedList.ev:62
Fields
int32 lengthConstructors
INIT()
Methods
METHOD clone() RETURNS SortedList[T]
Hand-written clone() — AUTO refused for the same cascade
reason as Queue / Stack / Deque / LinkedList: the synthesis
walker can't see T's Cloneable status from this instantiation
site through the LinkedList[T] composition. Walk the
underlying LinkedList's iterator and append a deep clone of
each element. Sort order is preserved because the source list
is already sorted and we visit front-to-back; we use
data->append (which adds to tail) rather than going through
SortedList.add's per-insert binary scan.
METHOD iterator() RETURNS LinkedListIterator[T]
ITERATOR — delegate to LinkedList's BidirectionalIterator
The element order is insertion order, which by the order
invariant is also ascending. Callers iterate front-to-back
for ascending traversal; back-to-front via previous() for
descending.
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of elements currently stored. Read-only, O(1).
MODIFY METHOD clear() RETURNS void
MODIFY METHOD insert(T value) RETURNS STATUS
INSERT
Walks the iterator to find the first position where
value->isLessThan(elem) becomes TRUE — that's where value
belongs in the sorted order. The iterator is held in a
nested block so it drops (releasing the mutation lock on
_data) before the call to _data->insertAt.
Insert value at the position that keeps the list sorted.
Per §10.2 the bare-named form consumes the source —
value is moved into the list. The walk reads value for
comparison (read-only, doesn't consume) before the final
.data->insertAt call which performs the move.
MODIFY METHOD insertCopy(REFERENCE T value) RETURNS STATUS
Deep-copy form of insert. value stays valid for the caller;
the clone is the one moved into the list.
METHOD contains(REFERENCE T value) RETURNS boolean
CONTAINS / REMOVE — short-circuit on Comparable order
MODIFY METHOD remove(REFERENCE T value) RETURNS boolean
Remove the first element equal to value. Returns TRUE if
a match was found and removed, FALSE otherwise.
METHOD peekFirst() RETURNS | REFERENCE T
FRONT / BACK ACCESS — convenience wrappers over LinkedList
peekFirst returns the smallest element; peekLast the largest. popFirst / popLast remove and return them. All four are O(1) by virtue of LinkedList's existing front/back operations.
METHOD peekLast() RETURNS | REFERENCE T
MODIFY METHOD popFirst() RETURNS | T
MODIFY METHOD popLast() RETURNS | T
SetIMPLEMENTS Cloneable, Collection
Set is a thin pure-Envzn wrapper over a Dictionary
STORAGE Set[V, H] holds Dictionary[V, int64, H] data (the interface),
backed by a ChainedHashDictionary. The element is the dictionary KEY
(collision-safe: distinct elements that hash equal land in the same
bucket and are told apart by Equatable, never merged); the value is an
unused int64 dummy (0). A boolean value is impossible — the Dictionary
qualifier bans boolean V — so a small int is the minimal placeholder.
TWO TYPE PARAMETERS Set[V, H]:
- V — element type. Hashable + Equatable (the dict's key contract).
- H — the Hasher OF V. Callers name a concrete hasher
(e.g. Set[int32, DefaultHasher[int32]]); the no-arg INIT lets the
backing dictionary CREATE a DefaultHasher[V], a hasher-taking INIT
threads a supplied one through. H is phantom in the body (the dict
stores the hasher as the Hasher OF V interface).
ITERATION yields the elements (the dict's keys), forward-only, order
unspecified. iterator() returns the backing dictionary's key iterator
directly — there is no separate SetIterator.
.length is kept in sync by hand: the Dictionary surface has no count(),
and insert() is replace-or-add (SUCCESS either way), so add/remove gate
on a prior contains to keep the count exact.
Set[V, H] — unordered set of unique elements over a Dictionary.
kernel/src/Set.ev:43
Fields
int64 lengthConstructors
INIT()
No hasher — the backing dictionary CREATEs a DefaultHasher[V].
INIT(Hasher[V] h)
Caller-supplied hasher, threaded into the backing dictionary.
INIT(GrowthHint hint, int64 initialCapacity)
Default hasher + sizing hints (forwarded to the dictionary).
INIT(Hasher[V] h, GrowthHint hint, int64 initialCapacity)
Caller hasher + sizing hints.
Methods
METHOD clone() RETURNS Set[V, H]
Deep copy — the backing dictionary clones every key.
METHOD iterator() RETURNS ReferenceIterator[V]
ITERATOR — yields the elements (the dictionary's keys).
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of elements currently stored. Read-only, O(1).
MODIFY METHOD clear() RETURNS void
MODIFY METHOD add(V value) RETURNS STATUS
ADD / REMOVE / CONTAINS
Add value (consumed). If already present, the element stays and
the moved-in value is dropped; .length is unchanged.
MODIFY METHOD addCopy(REFERENCE V value) RETURNS STATUS
Deep-copy form of add. value stays valid for the caller.
METHOD contains(REFERENCE V value) RETURNS boolean
MODIFY METHOD remove(REFERENCE V value) RETURNS STATUS
Remove value. SUCCESS if it was a member, FAILURE otherwise.
METHOD unionWith(REFERENCE Set[V, H] other) RETURNS Set[V, H]
SET ALGEBRA — |+| / |&| / |-| bind to these.
Union — every element from either input (deduped).
METHOD intersectionWith(REFERENCE Set[V, H] other) RETURNS Set[V, H]
Intersection — elements present in BOTH inputs.
METHOD differenceWith(REFERENCE Set[V, H] other) RETURNS Set[V, H]
Difference — elements in SELF but NOT in other (asymmetric).
BoxIMPLEMENTS Cloneable
Defines the Box[T] class per ENVZN_CONSTITUTION §Box.
Box[T] is a heap-allocating transparent wrapper around a single T. Its primary purpose is to break the type cycle that would otherwise make a self-recursive GROUP infinite-sized:
GROUP Expr {
Number n
BinaryExpr // contains Box[Expr] — the recursion
// through Box's heap pointer breaks
// the cycle for std::variant
}
CLASS BinaryExpr {
Box[Expr] left
Box[Expr] right
String op
}
Compiler features (transparency sugar — not in this class):
- Auto-wrap on assignment. A class field declared
Box[T] foo accepts a T-typed RHS; the compiler emits the
equivalent of .foo = CREATE Box[T](rhs) for fresh INITs and
.foo->set(rhs) for reassignments.
- Auto-unwrap on read. Reading instance.foo where
.foo is a Box[T] field yields T (specifically a REFERENCE
T handle via the equivalent of .foo->value()); the user
never sees the Box wrapper.
- MATCH transparency. When a GROUP variant arm contains a
boxed type, MATCH dispatches on the inner T, not on Box[T].
None of those three features live inside this file — they're compiler-side rewrites. They reduce every user-facing interaction with Box to an Envzn-side method call on the surface declared below.
kernel/src/Box.ev:48
Constructors
INIT(T value)
The only constructor. value is consumed (a plain parameter owns). The
compiler's auto-wrap rewrite produces CREATE Box[T](rhs)
when initialising a Box[T] field from a T-typed expression.
Methods
METHOD clone() RETURNS Box[T]
Hand-written rather than AUTO: Box has no zero-arg INIT (the
user-facing model has no "empty box" state), so the cascade
synthesis path doesn't apply. T must implement Cloneable when
T is a class type; the explicit ->clone() call below
surfaces the requirement as a compile error on the Box[T]
instantiation that triggers it.
METHOD value() RETURNS REFERENCE T
── value — return a non-owning handle ────────────────────────
The auto-unwrap rewrite for reads of a Box[T] field. Returns
a non-optional REFERENCE T into SELF's owned .inner.
.inner is always populated (set by INIT and never cleared),
so the reference is always valid; the reference checker proves
it without runtime infrastructure.
METHOD valueClone() RETURNS T
── valueClone — return an owned copy ───────────────────────── The path callers take when they need an owning T (e.g. to store elsewhere, to mutate independently). T must be Cloneable; the cascade-failure rule fires at instantiation otherwise.
MODIFY METHOD set(T value) RETURNS void
── set — replace the wrapped value ─────────────────────────── Drops the previous inner and installs value (owned). : := to a populated non-Optional owning field drops the previous owner via its destructor, then installs the new owner from the RHS. Box never enters a "moved-out" state observable to the user — the drop and the install happen as a single operator step.
GrowthHintGrowthHint — advisory sizing hint for hash-based collections (Dictionary impls, Set). Passed at construction alongside an initial capacity so an implementation can tune its backing storage.
VOLATILE is a reserved
concurrency keyword, so the churn case is named
DYNAMIC.)V1: the hint is accepted and stored but only initialCapacity
drives behavior (ChainedHashDictionary pre-sizes its bucket array).
GrowthHint-driven tuning (shrink policy, load-factor selection) is
a future performance pass.
kernel/src/enums.ev:207
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
EvArrEvArr — what a T[] holds: the C array floor's 1-D descriptor, and its ONE
definition. The compiler lowers it, as every STRUCT that crosses a FOREIGN
BIND, to the C struct _EV_ENVZN_EvArr in the emitted EV_cstructs.h;
native/EV_arr.h only names it (typedef struct _EV_ENVZN_EvArr EvArr;), so
the C floor and Envzn read the same layout (native-array-primitive-design
§19.6, 6a′). NativeArray[T] holds one by value, and every ev_arr_* binding
takes it by REFERENCE, which crosses as EvArr *. 32 bytes.
kernel/src/structs.ev:382
Fields
HANDLE dataint64 lengthint64 capacityint64 growAtEvNdArrEvNdArr — what a T[,] holds: the C array floor's N-D descriptor, and its ONE
definition (lowered, as EvArr is, to _EV_ENVZN_EvNdArr in EV_cstructs.h; the
fixed-array fields become C's inline arrays). NativeNdArray[T] holds one by
value. 200 bytes; column-major.
count cells, EMPTY when an extent is 0.rank are unused.kernel/src/structs.ev:401
Fields
HANDLE dataint64 countint32 rankint32 dimsint64 stridesLinkedListIMPLEMENTS Cloneable, Collection
Defines the LinkedList[T] class per ENVZN_CONSTITUTION §LinkedList.
LinkedList[T] is a doubly-linked list with O(1) push/pop at both
ends and O(n) traversal/lookup. The
forward chain is owning; back-pointers are explicit REFERENCE, re-bound
with =@.
LinkedList is the foundation for Deque (composes on LinkedList for O(1) both-end ops) and SortedList (composes on LinkedList; insert walks to the sort spot via Comparable[T]). Together with Array, this reduces the kernel to two backing stores.
────────────────────────────────────────────────────────────────── STRUCTURE — sentinels + chain ──────────────────────────────────────────────────────────────────
Every list always contains two sentinel nodes — a "starter" at the head and an "ender" at the tail. They exist on construction and are never removed. User nodes live strictly between them.
_head (id=0) ⇄ user1 ⇄ user2 ⇄ ... ⇄ userN ⇄ _tail_ref (id=1)
Forward arrows (→ in the diagram, next field) are owning
unique_ptrs. Backward arrows (← in the diagram, prev_ref field)
are non-owning REFERENCEs.
The list class holds:
- _head — owning non-Optional sentinel; this owns the entire
forward chain transitively through .next.
- _tail_ref — non-owning REFERENCE to the ender sentinel; needed
for O(1) end-side operations without traversing the whole
chain. The ender is itself owned (via the forward chain) by
the node that immediately precedes it.
- _nextId — counter for new user-node IDs (starts at 2).
- length — public count of user nodes (excludes sentinels).
Empty list: _head → ender (head.next owns ender; head.prev_ref
is EMPTY; ender.prev_ref REFERENCEs head; ender.next is EMPTY).
────────────────────────────────────────────────────────────────── SPLICE PATTERN ──────────────────────────────────────────────────────────────────
Each insert/remove follows a consistent shape:
(a) move owning links via := (always taking the existing
value out of an Optional owning field BEFORE overwriting
the field — otherwise the unique_ptr destructor frees the
value mid-splice);
(b) REBIND back-pointers via =@ (REFERENCE rewires;
structural conditions checked);
(c) move the new owning link into the predecessor's .next
slot last, completing the splice.
Optional unwraps use IF X IS NOT VALID { PANIC } to convert
statically-unreachable EMPTY branches (e.g. _tail_ref.prev_ref
is always set after INIT) into explicit kernel-invariant PANICs
— making "this can't happen" auditable instead of hiding behind
silent fallbacks.
kernel/src/LinkedList.ev:72
Fields
int32 lengthConstructors
INIT()
Constructs both sentinels and wires them. After this returns,
head → ender (head.next owns the ender), and the list is empty.
Methods
METHOD clone() RETURNS LinkedList[T]
Hand-written clone() — Builds a fresh empty list, walks the
current chain directly (no heap iterator), and appends a deep-clone
of each user value. The new list owns its own sentinel chain with
correctly-wired last_node_ref (set by append() on every push).
METHOD iterator() RETURNS LinkedListIterator[T]
Per spec L767, LinkedList exposes BidirectionalIterator OF T.
Concrete class is LinkedListIterator (separate file). Pass
.head by-& so the iterator's REFERENCE binding satisfies
§REFERENCE condition 2 (mutation-locked at INIT) without
moving ownership of .head out of SELF.
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of elements currently stored. Read-only, O(1).
MODIFY METHOD prepend(T value) RETURNS STATUS
FRONT-SIDE OPERATIONS (right after head sentinel)
Insert value at the front. value is cloned in via
LinkedListNode's INIT.
Splice ordering : step 1: newNode.next := .head.next (move old first into newNode.next; .head.next is now EMPTY) step 2: .head.next := newNode (move newNode into .head.next; local poisoned) step 3: bump last_node_ref if list was empty
MODIFY METHOD prependCopy(REFERENCE T value) RETURNS STATUS
Deep-copy form of prepend. value stays valid for the caller;
the clone is the one moved into the new node.
MODIFY METHOD popFirst() RETURNS | T
Remove and return the front user value. EMPTY if empty.
Splice ordering : step 1: popped := .head.next (move; .head.next now EMPTY) step 2: .head.next := popped.next (move the new-first into .head.next) step 3: if popped was the only user node, last_node_ref bumps back to .head
METHOD peekFirst() RETURNS | REFERENCE T
Read (without removing) the front user value. Pipe-XOR shape:
SUCCESS populates value with the reference; empty / invariant
violation populates s with FAILURE. Never PANICs.
METHOD at(int32 index) RETURNS | REFERENCE T
Non-owning reference to the value at index (0-based), or FAILURE
if out of bounds. O(index) forward walk from the first user node —
backs index-based external walkers that cannot hold a
LinkedListIterator field (iterator Rule A), e.g.
ChainedHashDictionaryIterator. Read-only; the source list stays
mutation-locked while the returned reference is held.
MODIFY METHOD append(T value) RETURNS STATUS
BACK-SIDE OPERATIONS (right before ender sentinel)
Insert value at the back. value is cloned in via
LinkedListNode's INIT (const-ref param-passing).
O(n) — walks .head's owning chain to find the node whose .next is
the ender (id 1), then splices newNode in front of the ender.
MODIFY METHOD appendCopy(REFERENCE T value) RETURNS STATUS
Deep-copy form of append. value stays valid for the caller;
the clone is the one moved into the new node.
MODIFY METHOD popLast() RETURNS | T
Remove and return the back user value. EMPTY if empty. O(n) walk from .head to find the second-to-last user node so we can splice the ender into its .next slot. Single-element case short-circuits to popFirst().
Splice ordering : step 1: popped := wasSecondToLast.next (move popped out of the predecessor's next slot) step 2: wasSecondToLast.next := popped.next (move ender into the predecessor's next slot)
METHOD peekLast() RETURNS | REFERENCE T
Read (without removing) the back user value. Pipe-XOR shape:
SUCCESS populates value with the reference; empty list
populates s with FAILURE. O(n) walk from .head.
MODIFY METHOD insertAt(int32 index, T value) RETURNS STATUS
MID-CHAIN OPERATIONS (insertAt / removeAt)
Used by SortedList[T] and any other consumer that needs to splice at an arbitrary position. O(index) walk to the target node, then O(1) splice via the same move-out-before-overwrite pattern as prepend/append/popFirst/popLast.
Index 0 and index .length (or .length - 1 for removeAt)
delegate to the existing front/back methods to avoid
duplicating splice logic.
Insert value at position index. Valid range is 0..length
(inclusive — index == length appends, equivalent to append).
Per §10.2 the bare-named form consumes value (poisoned
at the call site). STATUS == FAILURE on out-of-bounds index
or kernel-invariant violation; SUCCESS otherwise.
MODIFY METHOD insertAtCopy(int32 index, REFERENCE T value) RETURNS STATUS
Deep-copy form of insertAt. value stays valid for the caller;
the clone is the one moved into the new node.
MODIFY METHOD removeAt(int32 index) RETURNS | T
Remove and return the user value at position index. STATUS
== FAILURE on out-of-bounds index or kernel-invariant violation
(paired with EMPTY in the value slot); SUCCESS otherwise (paired
with the removed value).
LinkedListIteratorIMPLEMENTS ReferenceIterator
Concrete BidirectionalIterator OF T for LinkedList[T].
A LinkedList[T]'s ->iterator() method yields a fresh
LinkedListIterator[T] positioned at the first user node (or at
the ender sentinel if the list is empty). Multiple iterators on
the same list are independent (each has its own cursor REFERENCE);
the source list is locked against mutation while any iterator is
held (per §Iterator's mutation-lock rule).
────────────────────────────────────────────────────────────────── CURSOR MODEL ──────────────────────────────────────────────────────────────────
The cursor REFERENCEs the node "about to be read" by the next forward operation. Valid cursor positions:
The cursor never sits at the head sentinel (id = 0). Stepping backward stops at the first user node — going further would land at head (which has no readable value), so hasPrevious returns false there and previous/skipBack return EMPTY without moving.
For an empty list, the cursor starts at the ender; both hasNext and hasPrevious are false.
────────────────────────────────────────────────────────────────── SAFETY ──────────────────────────────────────────────────────────────────
source_head_node_ref is a REFERENCE to the source list's
head sentinel. Set in INIT from a by-& parameter; satisfies
§REFERENCE structural condition 2 (mutation-locked at INIT) —
the mutation lock prevents append/prepend/pop on the source
while any iterator exists.cursor_ref is a REFERENCE to a node owned by the source
list's _head chain. Safe under condition 1 (ownership-
reachable from SELF via the validated source-head REFERENCE).────────────────────────────────────────────────────────────────── SKIP / SKIP-BACK BOUNDS ──────────────────────────────────────────────────────────────────
skip(n) walks forward; on overshoot the cursor lands on the
ender sentinel (a valid cursor position) and EMPTY is returned.
No rollback needed — landing on the ender keeps the cursor
model intact.skipBack(n) walks backward; on underflow the cursor stops at
the first user node (the position whose _prev_ref.id == 0)
and EMPTY is returned. The check is peek-before-step so the
cursor never lands on the head sentinel — preserving the
"cursor never at head" invariant.No local REFERENCE-typed variables are used. The cursor field is the walker.
kernel/src/LinkedListIterator.ev:75
Constructors
INIT(REFERENCE LinkedListNode[T] source_head_node)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE T
METHOD peek() RETURNS | REFERENCE T
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE T
skip(n) — moves cursor forward by n positions. skip(0) is equivalent to peek(). On overshoot, the cursor lands on the ender sentinel and FAILURE is returned.
OwnedListIMPLEMENTS Collection
Owning, move-only, non-Cloneable list.
────────────────────────────────────────────────────────────────── WHAT IT IS ──────────────────────────────────────────────────────────────────
OwnedList[T] is a singly-linked list that OWNS its elements and only
ever MOVES them — it never copies or clones. Because it is not itself
Cloneable, it imposes no Cloneable requirement on T; its bound is
T IS Shareable, so it can hold non-Cloneable kernel concurrency
primitives (Channel, Mutex, Future, …) that the standard collections
(Array / Dictionary / LinkedList / Set, all IMPLEMENTS Cloneable)
reject.
It is the registry behind MessageBroker[T] (a list of per-subscriber
Channels), and is reusable for any "hold a set of owned, non-copyable
objects, walk them, add/remove by id" need.
────────────────────────────────────────────────────────────────── API (minimal) ──────────────────────────────────────────────────────────────────
Structure mirrors LinkedList: a head sentinel (id 0) and an ender
sentinel (id 1) bracket the user nodes (id ≥ 2). Splices use the
move-out-before-overwrite ordering. Singly-linked, owning-
forward; dropping .head cascade-frees the chain.
Built to back MessageBroker[T].
kernel/src/OwnedList.ev:48
Fields
int32 lengthConstructors
INIT()
Methods
MODIFY METHOD add(T value) RETURNS uint64
Take ownership of value and prepend it (right after the head
sentinel). O(1). Returns the new node's stable id, which the
caller passes to removeById later.
Splice ordering: step 1: newNode.next := .head.next (move old first into newNode.next) step 2: .head.next := newNode (move newNode into .head.next)
MODIFY METHOD removeById(uint64 id) RETURNS boolean
Remove the user node with the given id. Returns TRUE if found and
removed; FALSE if no live node carries that id. Walks from the
head sentinel tracking the predecessor, then splices the target
out (its owned element is dropped as popped leaves scope).
METHOD findById(uint64 id) RETURNS | REFERENCE T
Return a REFERENCE to the element of the node with the given id. Pipe-XOR: SUCCESS yields the reference; FAILURE if no live node carries that id. Used by MessageBroker.subscribe to hand a Subscription a non-owning handle to its just-added channel.
METHOD size() RETURNS int64
Countable — the count of user nodes (sentinels excluded). .length is
the int32 field; size() is the int64 contract, and int32 -> int64 is
a widening, so the assignment carries it with no stated conversion.
METHOD isEmpty() RETURNS boolean
METHOD iterator() RETURNS OwnedListIterator[T]
Fresh forward cursor positioned at the first user node (or the
ender if empty). Pass .head by-& so the iterator's REFERENCE
binding is mutation-locked at INIT without moving .head out.
OwnedListIteratorIMPLEMENTS ReferenceIterator
Forward cursor over OwnedList[T].
A fresh iterator from OwnedList.iterator() is positioned at the
first user node (or the ender sentinel if the list is empty). Drive
it with the pipe-XOR loop:
OwnedListIterator[T] it := list->iterator()
WHILE it->next() DO {
REFERENCE T value =@ $RETURNED
... use value in place (no copy) ...
}
Mirrors LinkedListIterator (the proven cursor model), bound to
T IS Shareable so it can walk a chain of non-Cloneable elements.
next() yields a REFERENCE to the element — the consumer operates on
it in place; the element is never copied out of the list.
Plain FINAL class (not IMPLEMENTS ReferenceIterator): OwnedList's
consumers drive next() directly, and the for-in / ReferenceIterator
protocol carries a Cloneable-shaped contract we don't want here.
kernel/src/OwnedListIterator.ev:33
Constructors
INIT(REFERENCE OwnedListNode[T] sourceHeadNode)
Methods
METHOD hasNext() RETURNS boolean
Iterator — TRUE while the cursor still sits on a user node. The ender
sentinel is id 1, which is exactly the condition next() refuses on,
so the two agree by construction.
This class implemented NO interface at all until now, which is why it
alone of the iterators could not satisfy Collection.iterator() —
ArrayIterator and the rest were already BidirectionalIterator OF T.
METHOD peek() RETURNS | REFERENCE T
ReferenceIterator — the reference at the current cursor WITHOUT
advancing. Same pipe-XOR shape as next() and the same refusal at the
ender sentinel; it simply does not move cursorRef.
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE T
ReferenceIterator — advance n positions and yield what lands under
the cursor. skip(0) is next(); running off the ender fails exactly
as next() does, so a short list refuses rather than walking past the
sentinel.
MODIFY METHOD next() RETURNS | REFERENCE T
Advance and yield the next element by REFERENCE. Pipe-XOR:
SUCCESS populates value; FAILURE once the cursor reaches the
ender sentinel (end of iteration).
DictionaryDictionary is a pure INTERFACE, not a concrete class, and is no longer special-cased by the compiler. It is an ordinary parametric interface the compiler treats like any other.
THREE TYPE PARAMETERS Dictionary[K, V, H]:
- K — key type. Hashable + Equatable (primitives, String, or a class
implementing both).
- V — value type. Cloneable / primitive (the clone()-bearing surface
requires it; see EXTENDS Cloneable below).
- H — the Hasher OF K used to hash keys. Callers name a concrete
hasher here (e.g. Dictionary[String, int32, StringHasher]); the
hidden impls store it as the Hasher OF K interface type and, when
constructed without one, CREATE a DefaultHasher[K].
IMPLEMENTATIONS (both HIDDEN, pure Envzn, no FOREIGN / std::): - ChainedHashDictionary[K,V,H] — bucket array + chaining; unordered. - SkipListDictionary[K,V,H] — skip list; sorted iteration (K also Comparable). (lands in a later #16 phase.)
Callers construct an impl and hold the interface: Dictionary[String, int32, StringHasher] scores := CREATE ChainedHashDictionaryString, int32, StringHasher
EXTENDS Cloneable — every Dictionary deep-copies.
ITERATION yields KEYS (forward-only), per spec §Iterator. Order is unspecified for the chained-hash impl; the skip-list impl iterates in sorted key order. Dictionary[K, V, H] — unordered key→value map interface. Keys are hashed by the H hasher; values are Cloneable. Construct a concrete impl (ChainedHashDictionary / SkipListDictionary) and hold this interface type.
kernel/src/Dictionary.ev:49
Methods
METHOD clone() RETURNS Dictionary[K, V, H]
Deep copy. (Cloneable contract; covariant return — an impl returns its own concrete type.)
METHOD iterator() RETURNS ReferenceIterator[K]
Forward-only iterator over the keys. FOR/IN over a Dictionary visits each key once.
METHOD keys() RETURNS LinkedList[K]
Snapshot of all keys in a fresh LinkedList (each key cloned).
METHOD isEmpty() RETURNS boolean
check if the dictionary is empty
METHOD size() RETURNS int64
Number of key→value pairs currently stored. All three impls already
provide it; declaring it here makes it callable through a Dictionary
interface handle.
MODIFY METHOD clear() RETURNS void
MODIFY METHOD insert(K key, V value) RETURNS STATUS
insert (key, value). BOTH are MOVEd in (consumed) — the dictionary
owns what it stores, so there is nothing for it to clone. Replacing an
existing key destroys the old value and leaves the count unchanged.
SUCCESS always (FAILURE only on an EMPTY key/value where the type is
Cloneable). Use insertCopy to keep your own key and value.
MODIFY METHOD insertCopy(REFERENCE K key, REFERENCE V value) RETURNS STATUS
Deep-copy insert — both key and value stay valid for the caller.
METHOD lookup(REFERENCE K key) RETURNS | MUTABLE REFERENCE V
Lookup — a reference into the stored value, or FAILURE if the key is absent. Gate on STATUS, not on the returned V. A borrow-propagating ("mirror") accessor: the returned reference mirrors the receiver's mutability — a mutable dictionary yields a MUTABLE REFERENCE (modify the value in place), a const one a read-only REFERENCE. Valid while the dictionary is not mutated (iterator mutation lock).
There is deliberately NO value-cloning lookup: borrowing is the default
and owning is explicit. To own a copy, clone the borrow; to own the
value itself, remove it.
METHOD lookupFast(REFERENCE K key) RETURNS boolean
Allocation-free lookup — found plus the value, no pipe and no STATUS.
This is not a faster lookup; it is a lookup with a different COST on
the miss. lookup builds a FAILURE("...key not found") when the key
is absent, so a loop that misses once per distinct key — a group-by, a
join, a dedupe — allocates a formatted String per miss, a cost the pipe
hides completely at the call site. Every implementation already knows
whether the key is present before it decides what to return, so making
this part of the interface costs nothing and is what lets a consumer
stay on the interface instead of reaching for the concrete class.
On a miss value is the type's absent form (EMPTY for a class V, zero
for a primitive) and MUST NOT be read: found is the only valid
discriminator. C# spells the same contract TryGetValue.
MODIFY METHOD remove(REFERENCE K key) RETURNS | K
remove — MOVES both halves out, or FAILURE if the key is absent. Nothing is cloned: the stored key and value are handed to the caller rather than copied and destroyed. The returned key is the STORED one, which is equal to — but not necessarily the same object as — the probe key, which is why it is worth returning.
METHOD contains(REFERENCE K key) RETURNS boolean
contains - like lookup() but only returns a boolean if the key-value pair is found
ChainedHashDictionaryIMPLEMENTS Dictionary
ChainedHashDictionary
STORAGE:
- buckets : HashBucket[K,V][] — a RAW value-array of lean value-class buckets,
one per slot. Each HashBucket stores its entries INLINE (2 CollisionNode slots
+ a lazy spill), so there is NO per-bucket heap object and NO per-entry heap
node — the LinkedList-per-bucket + ChainedHashEntry + per-lookup heap iterator
of the old design are gone (that iterator alloc was the measured 174 ns/lookup
S4 bug). An empty bucket is a zero-count HashBucket (no nullable-slot problem).
- In-place bucket mutation binds a MUTABLE REFERENCE into .buckets[idx] (reads
bind a plain REFERENCE); the bucket's own MODIFY methods do the work.
- count : int64; hasher : Hasher OF K (interface-typed, decision 5);
bucketLevel : int64 (power-of-two growth level); growth : GrowthHint
(advisory, stored-unused for V1).
BUCKET INDEX: hash & (bucketCount - 1) over a POWER-OF-TWO bucket count
(HashConstants.pow2CountAtLevel / indexForHash) — replaces the old prime %.
RESIZE: load factor > 0.79 (count100 > bucketCount79) → double the bucket count
(one pow2 level) and rehash every entry by its CACHED hash (no key re-hash).
IMPLEMENTS Dictionary[K, V, H] — Cloneable comes transitively (Dictionary EXTENDS
Cloneable); a redundant explicit Cloneable would create an ambiguous C++ double
base and break clone() covariance. H is phantom in the body; the stored hasher is
the Hasher OF K interface (no-arg INIT CREATEs the DefaultHasher).
ChainedHashDictionary[K, V, H] — separate-chaining hash table over lean inline
value-class buckets. HIDDEN: constructed via CREATE, held through the Dictionary
interface.
kernel/src/ChainedHashDictionary.ev:45
Constructors
INIT()
No hasher, default sizing — CREATE a DefaultHasher[K].
INIT(Hasher[K] h)
Caller-supplied hasher, default sizing.
INIT(GrowthHint hint, int64 initialCapacity)
Default hasher + sizing hints (initialCapacity ignored for V1 — the pow2 ladder governs bucket count; GrowthHint stored, unused).
INIT(Hasher[K] h, GrowthHint hint, int64 initialCapacity)
Caller hasher + sizing hints.
Methods
METHOD clone() RETURNS Dictionary[K, V, H]
METHOD iterator() RETURNS ReferenceIterator[K]
METHOD keys() RETURNS LinkedList[K]
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of key-value pairs currently stored. Read-only, O(1).
MODIFY METHOD clear() RETURNS void
MODIFY METHOD insert(K key, V value) RETURNS STATUS
MODIFY METHOD insertCopy(REFERENCE K key, REFERENCE V value) RETURNS STATUS
METHOD lookup(REFERENCE K key) RETURNS | MUTABLE REFERENCE V
METHOD lookupFast(REFERENCE K key) RETURNS boolean
Dictionary.lookupFast — same probe as lookup, without the STATUS that
lookup must allocate on a miss.
MODIFY METHOD remove(REFERENCE K key) RETURNS | K
METHOD contains(REFERENCE K key) RETURNS boolean
METHOD equals(REFERENCE Dictionary[K, V, H] other) RETURNS boolean
Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
HashBucketIMPLEMENTS Cloneable, Comparable
PARAMETERISED OVER HASH: uint64 for ChainedHashDictionary (FNV), uint128 for
ProHashDictionary (SipHash-2-4-128). Every scan rejects on the cached HASH before the
key compare (CollisionNode.matches). Equal cached hashes form a contiguous run the
scans walk for the key match.
The lookup returns a TRIVIAL (boolean found, V value) multi-return — NOT a
(V|STATUS) pipe-XOR — so the hot path never constructs an _EvStatus (whose
_ValueArray member is non-trivially destructible). The dictionary builds the
interface-mandated (V|STATUS) once at its public boundary.
A method may not be chained off an indexed SELF field (.data[i]->m() is a parse
error), so an element is bound to a local reference before the call; counted
iteration uses WHILE.
See: CollisionNode.ev, HashConstants.ev, ChainedHashDictionary.ev / ProHashDictionary.ev, ENVZN_CONSTITUTION.md §I.J.vi (VALUE CLASS). HashBucket[K, V, HASH] — one sorted array of CollisionNodes (2 inline).
kernel/src/HashBucket.ev:35
Constructors
INIT()
Methods
METHOD size() RETURNS int64
Number of entries in this bucket.
MODIFY METHOD insert(K key, V value, HASH hash) RETURNS boolean
Insert key→value (with cached hash). TRUE if a new entry was added,
FALSE if an existing key's value was replaced in place.
METHOD lookup(HASH hash, REFERENCE K key) RETURNS boolean
Look up key (with cached hash) — TRIVIAL (found, value) multi-return, so
the hot path never builds an _EvStatus. value is the type default on a miss.
HYBRID (measured crossover at depth ~24): the common shallow bucket
(≤ LINEAR_SCAN_MAX entries) is a plain linear scan from 0 — no lowerBound
binary search, and one matches() per node (no redundant outer hash pre-check).
Only a deep/flooded bucket (> LINEAR_SCAN_MAX) pays the O(log n) sorted path.
The sorted invariant is kept by insert, so the deep path stays valid.
METHOD lookupRef(HASH hash, REFERENCE K key) RETURNS | MUTABLE REFERENCE V
Look up key — a non-owning reference into the stored value, or FAILURE.
A borrow-propagating ("mirror") accessor: the returned reference mirrors
the receiver's mutability (a mutable bucket yields a MUTABLE REFERENCE, a
const bucket a read-only REFERENCE). Binds directly to the matched node's
INTERNAL value field.
METHOD containsKey(HASH hash, REFERENCE K key) RETURNS boolean
TRUE if key is present.
METHOD keyCloneAt(int64 i) RETURNS K
A clone of the i-th node's key.
METHOD valueCloneAt(int64 i) RETURNS V
A clone of the i-th node's value.
METHOD hashAt(int64 i) RETURNS HASH
The cached hash of the i-th node — backs growAndRehash re-bucketing.
MODIFY METHOD removeEntry(HASH hash, REFERENCE K key) RETURNS | K
Remove key — returns the cloned-out key, or FAILURE. Shift-removes from the
sorted live region (the tail slides left, count--; the physical array is not
shrunk — the freed tail slot is reused by the next insert).
Evict the entry for key and hand BOTH halves back, moved — never
cloned. Replaces the former removeKey, which was written as
read-then-delete (keyCloneAt(pos) followed by the shift) and so
deep-copied the very key it was about to destroy — the Array.popLast
defect shape fixed in 3003ed5f, in its dictionary form.
The survivors still shift down and data's physical length is left
alone: it is a non-shrinking high-water mark and the vacated tail slot
is reused by the next insert (see the header note).
MODIFY METHOD placeNew(K key, V value, HASH hash) RETURNS void
Build a node from (key, value, hash) and sorted shift-insert it. No update scan; the caller guarantees the key is new (rehash re-place / known-fresh).
METHOD clone() RETURNS HashBucket[K, V, HASH]
Deep copy — every live node cloned, in sorted order (so the clone stays sorted).
METHOD equals(REFERENCE HashBucket[K, V, HASH] other) RETURNS boolean
METHOD isLessThan(REFERENCE HashBucket[K, V, HASH] other) RETURNS boolean
HashBucketIteratorIMPLEMENTS ReferenceIterator
HashBucketIterator walks the dictionary's HashBucket[K,V,HASH][] buckets (a raw value-array of inline
buckets) in bucket order, yielding a non-owning REFERENCE to each entry's key. Holds
a mutation-locked REFERENCE to the buckets array (set in INIT from a by-reference
parameter — §REFERENCE condition 2); the lock pins the source dictionary against
mutation for the iterator's declaring-block lifetime.
CURSOR MODEL: (bi, ei) is the NEXT position to read — bucket bi, entry ei
within that bucket (0→slot0, 1→slot1, k≥2→spill[k-2]). advanceToValid() normalises
the pair so it either names a live entry (bi < nbuckets, ei < bucket.size()) or
sits at end (bi >= nbuckets). hasNext is bi < nbuckets. Iteration order is
unspecified (bucket order, and within a bucket the 2 slots then the hash-sorted
spill) — the Dictionary interface promises no order for the hash impls.
The per-entry key is reached by binding directly to the bucket's / node's INTERNAL
fields (same ENVZN module) — =@ node.key — rather than via a value-class accessor
method, whose inlining into a =@ bind would drop the reference and copy the
move-only key (the long-standing key-bind gotcha). The bucket count is read through
size().
Parameterised over [K, V, HASH] — the dictionary's hasher type is not needed here (the iterator never hashes), so it is left off the iterator's contract; HASH is carried only to name the bucket/node types. HashBucketIterator[K, V, HASH] — forward-only key iterator over a bucket array.
kernel/src/HashBucketIterator.ev:43
Constructors
INIT(REFERENCE HashBucket[K, V, HASH][] buckets)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE K
METHOD peek() RETURNS | REFERENCE K
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE K
CollisionNodeIMPLEMENTS Cloneable, Comparable
CollisionNode.ev — one (key, value, cachedHash) cell, as a VALUE CLASS so the
hash bucket stores it INLINE (no per-entry heap node). This is the Phase-1 dict-
rebuild substrate replacing the heap-allocated ChainedHashEntry: a HashBucket
holds CollisionNodes by value (two inline slots + a contiguous spill), and an
Array[CollisionNode[K,V]] lowers to inline storage — _ValueArray when K,V are
primitive (the trivially-copyable C-class path), _ObjectArray-by-value when K is
a class (e.g. a String key → owning handle field, the managed value-class form
the compiler deep-copies).
The key's hash is cached at insert (idea from libdict): a resize re-buckets via the cached hash without re-hashing keys, and a lookup rejects on the uint64 hash before the (possibly expensive) key compare.
K IS (Hashable AND Equatable); V is Cloneable / primitive. IMPLEMENTS Cloneable so
a node can be an Array[CollisionNode] element (whose clone() the bucket needs).
See: HashBucket.ev (the holder), ChainedHashDictionary.ev (the consumer),
ENVZN_CONSTITUTION.md §I.J.vi (VALUE CLASS). (Replaces the old heap-class
ChainedHashEntry, removed in the Phase-2 dict rebuild.)
CollisionNode[K, V, HASH] — a (key, value, cachedHash) bucket cell, value-typed.
HASH is the cached-hash width: uint64 for ChainedHashDictionary (FNV), uint128
for ProHashDictionary (SipHash-2-4-128). Parameterising the width keeps the common
int-key node tight (16 B at uint64 — 4 nodes/cache line) while letting the Pro
table keep its full 128-bit digest for the cheap pre-compare reject.
kernel/src/CollisionNode.ev:41
Constructors
INIT()
An empty node: key and value at their types' defaults, and not valid. What
an array slot holds before a node is written to it (I.J.vi, E1159); .valid
is what says it holds nothing.
INIT(K k, V v, HASH h)
Methods
METHOD hashValue() RETURNS HASH
The cached hash of this node's key (used by resize re-bucketing and the pre-compare reject in lookup).
METHOD matches(HASH h, REFERENCE K other) RETURNS boolean
TRUE if this node matches both the query hash and the query key. The cached
HASH is checked first (cheap reject); only on a hash hit is identity confirmed
via Equatable (class keys) or == (primitive keys) — the design doc's "compare
hash first, confirm key" step. Backs every lookup/insert/remove scan.
MODIFY METHOD setValue(V v) RETURNS void
Replace the stored value in place — backs insert-over-existing-key (the key and cached hash are unchanged).
METHOD valueClone() RETURNS V
A clone of the stored value — backs by-value lookup.
METHOD keyClone() RETURNS K
A clone of the stored key — backs keys().
METHOD clone() RETURNS CollisionNode[K, V, HASH]
Deep copy — key and value cloned, cached hash carried across.
METHOD equals(REFERENCE CollisionNode[K, V, HASH] other) RETURNS boolean
METHOD isLessThan(REFERENCE CollisionNode[K, V, HASH] other) RETURNS boolean
IntKeyedDictionaryIMPLEMENTS Dictionary
HIDDEN concrete Dictionary impl specialised for INTEGER keys: linear-probe open-addressing over a STRUCT-OF-ARRAYS (K[] keys + V[] vals), with a hash & mask home index. The TRUSTED-KEY FAST TIER. Pure Envzn, zero-dep.
WHY it is fast (the s04 envzn_oa prototype — ~1.1x C for int32->int64, the fastest
s04 result; verified by benchmarks/s04_dict/envzn_intkeyed):
- STRUCT-OF-ARRAYS, not chained buckets: one flat array level, so the hot probe
is a direct keys[s] read (C's own layout) — no bucket->node indirection, no
per-node binary search, no redundant hash+key re-compare.
- hash & mask index (the LOW bits): with an identity hasher on dense/sequential
integer keys this maps sequential keys to SEQUENTIAL slots — cache-line locality
+ prefetch, the effect that made envzn_oa (1.04x C) beat multiply-shift's
scatter (envzn_lpint, 1.38x). Distribution is the pluggable HASHER's job:
identity for trusted/dense keys (fastest), a mixing hasher (DefaultHasher/
SipHasher) for adversarial keys. The key-set-aware multiply-shift + prime
fallback for the robust general case lives in ShallowDictionary, NOT here.
- A non-pipe-XOR fast read: operator[] (d[key]) and lookupFast return by
value / (found,value), skipping the (V | STATUS) tuple the interface lookup
builds per call — the s04 IntDict lever ("no pipe-XOR on the hot path"). Held
CONCRETELY (not behind the Dictionary interface) the whole lookup inlines to
C-class code (~1.1x C vs ~3x through the interface + pipe-XOR).
- ONE compare per probe: keys[s] == key (a primitive ==), then a field read of
vals[s]. No cached-hash pre-check (integer keys are their own cheap hash).
STORAGE — three parallel value-arrays: keys[], vals[], and states[], whose
SlotState marks each slot VACANT (probe stops), LIVE, or TOMBSTONE (probe
continues; slot reusable). keys[]/vals[] in a non-LIVE slot hold 0 and are never
read. No key value is reserved: every value of every admitted K, signed or
unsigned, can be stored (and silently forbade those two keys for a signed one).
KEY DOMAIN: any integer key. IntKeyedDictionary is the fast opt-in tier for TRUSTED keys (as FastIntHasher is the fast opt-in hasher) because its identity-style hashing is not DoS-resistant; untrusted keys → ProHashDictionary or ChainedHashDictionary.
HASHER — stored CONCRETELY as the type parameter H hasher (a VALUE-CLASS hasher such as InlineIntHasher lives inline, no _ev_unique handle), so .hasher->hash(key) can inline.
IMPLEMENTS Dictionary[K, V, H] — Cloneable comes transitively (Dictionary EXTENDS
Cloneable). Full interface surface (rehash / tombstones / iterator / clone) PLUS the
concrete fast path (operator[] / lookupFast) for callers holding the concrete type.
kernel/src/IntKeyedDictionary.ev:62
Fields
int64 countint64 tombstonesint64 capuint64 maskConstructors
INIT(H h)
Methods
MODIFY METHOD insert(K key, V value) RETURNS STATUS
MODIFY METHOD insertCopy(REFERENCE K key, REFERENCE V value) RETURNS STATUS
METHOD lookup(REFERENCE K key) RETURNS | MUTABLE REFERENCE V
METHOD __op_index__(REFERENCE K key) RETURNS V
Direct value read — d[key]. Returns the stored value on a hit, or the V
default (0) on a miss. NO pipe-XOR (V | STATUS) tuple on the hot path: the
s04 experiments (IntDict) showed the pipe-XOR construction is a real per-lookup
cost, and operator[] returns V by value like ByteBuffer/String subscript.
Use contains/lookup when a miss must be distinguished from a stored 0.
METHOD lookupFast(REFERENCE K key) RETURNS boolean
Comma-return lookup — boolean f, V v := d->lookupFast(key). No pipe-XOR
(V | STATUS) tuple; the trivial (found, value) return the s04 prototypes
(IntDict/OADict) used to stay C-class. found distinguishes a miss from a
stored default.
METHOD contains(REFERENCE K key) RETURNS boolean
MODIFY METHOD remove(REFERENCE K key) RETURNS | K
Remove — hands back the stored key and value.
NOTE: unlike ChainedHashDictionary, this cannot move the halves out. The
storage is a struct-of-arrays open-addressed table, and reading a slot
(.vals[s]) is a subscript READ, which by rule clones rather than moves
(cxx_emit stmt_assign.py:149 — "the subscript is a read accessor, never
a move-out"). HashBucket escapes this because it can evict a whole
CollisionNode and take its fields; an SoA table has no move-out-at-index
primitive to call. So this pays one DUPLICATE per half, and the census
pins it at that rather than at 0. K is an integer here, so the key half
is a bit copy; only a class-typed V costs a real clone.
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
MODIFY METHOD clear() RETURNS void
METHOD iterator() RETURNS ReferenceIterator[K]
METHOD keys() RETURNS LinkedList[K]
METHOD clone() RETURNS Dictionary[K, V, H]
METHOD equals(REFERENCE Dictionary[K, V, H] other) RETURNS boolean
for Equatable Interface Dictionary is equal if all keys between the two dictionaries are equal Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
IntKeyedDictionaryIteratorIMPLEMENTS ReferenceIterator
The ReferenceIterator OF K returned by IntKeyedDictionary.iterator(). Yields a REFERENCE K for each LIVE slot of the dictionary's K[] keys, in slot order.
Holds a mutation-locking REFERENCE to the dictionary's keys value-array (bound
with =@ in INIT); the lock pins the source dictionary against mutation for the
iterator's declaring-block lifetime. The dictionary hands over the indices of its
LIVE slots (liveSlots), so the iterator never reads slot state — the
dictionary's SlotState is PRIVATE to it. Cursor pos indexes
liveSlots.
Parameterised over [K, V] to match the dictionary's arity (the vals array is not
walked and V is otherwise unused, but keeping the pair mirrors ShallowDictionaryIterator
and leaves room for a key+value iterator later). The hasher H is not needed — the
iterator never hashes.
kernel/src/IntKeyedDictionaryIterator.ev:31
Constructors
INIT(REFERENCE K[] keyArr, int64[] live)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE K
METHOD peek() RETURNS | REFERENCE K
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE K
ProHashDictionaryIMPLEMENTS Dictionary
The DoS-RESISTANT dictionary, rebuilt on the byte-keyed substrate that made StringKeyedDictionary beat C. Pure Envzn, zero-dep beyond the SipHash key shim.
WHY THE REBUILD (the measurement that forced it):
The old ProHash — Dictionary[BinaryWord,V,H] over char32 String keys, interface dispatch,
pipe-XOR returns, heap-node chains — ran the s05 word-dict at 1505 ms, 32x C.
The s05 experiment envzn_strkeyed_sip then ran the SAME SipHash-2-4 over the
byte-keyed open-addressing substrate at 49 ms — a 30x speedup at IDENTICAL
DoS-resistance. So ProHash's cost was never SipHash; it was the SHAPE. This class
keeps everything that made it "Pro" and rebuilds the shape underneath it.
WHAT MAKES IT "PRO" (both properties retained): 1. SipHash-2-4 keying. A process-global 16-byte secret (OS entropy, the same FOREIGN key shim SipHasher uses), so an attacker cannot predict bucket distribution — hash-flooding DoS defence by construction. 2. ADAPTIVE deep tier: chain -> RED-BLACK TREE. A bucket starts as a linear CHAIN (optimal when shallow — the overwhelmingly common case). If a bucket's depth exceeds TREEIFY_THRESHOLD (8) it is TREEIFIED into a red-black tree ordered by (cached hash, then key bytes) — a total order — so even a bucket an attacker somehow manages to overfill degrades to O(log n), never O(n). This is the belt-and-suspenders behind the SipHash keying: SipHash makes deep buckets unforceable; the tree bounds the damage if one ever occurs anyway.
THE SPEED LEVERS (carried over from StringKeyedDictionary):
- char8[] BYTE keys, not String. String stores char32 code points and hashes /
compares them one handle-indirected, bounds-checked element at a time — that was
the dominant cost. The caller transcodes ONCE (s INTO ByteBuffer -> bytes).
(Byte keys also mean this cannot be a Dictionary[BinaryWord,V,H] impl: the interface
cannot fix a type parameter (E2103) and an array key is not PRIMITIVE. It is a
standalone CLASS, as StringKeyedDictionary is.)
- System->memoryWord absorbs the SipHash message 8 BYTES PER ROUND (one wide
load) instead of eight bounds-checked byte reads.
- HOTLOOP hoists the per-byte bounds check out of the tail/compare loops.
- System->memoryCompare confirms a key with one std::memcmp, not a per-byte loop.
- No pipe-XOR on the hot path: lookupFast returns a trivial (found, value) and
operator[] returns V by value — neither builds the (V | STATUS) tuple. The
pipe-XOR lookup remains for the kernel idiom, off the hot path.
STORAGE — a flat byte pool + a flat ENTRY ARENA (SoA), no per-entry heap node:
- keyPool : char8[] — every key's bytes, contiguous.
- per-bucket: bucketList (the member CHAIN head — kept intact in BOTH modes, so
enumeration is always a chain walk), bucketRoot (the red-black index root when
treeified; -1 otherwise), bucketMode (0 chain / 1 tree), bucketDepth. The tree
is an ADDITIONAL lookup index over the same entries, never the sole structure —
that is what keeps rehash/remove/clone simple.
- per-entry: entHash, entOff/entLen (slice into keyPool), entVal,
entNext (chain link, doubles as the free-list link), entLeft/entRight/
entParent/entRed (red-black links, tree mode), entLive.
Freed entries are recycled through freeHead.
REMOVE — a deliberate, bounded simplification (labelled, not hidden): removing from a TREEIFIED bucket does not run the CLRS red-black delete-fixup. It collects the bucket's live entries, drops the target, and REBUILDS the bucket (re-chained if the remaining depth <= UNTREEIFY_THRESHOLD, else re-treeified). That is O(depth) — bounded, correct, and it keeps ~150 lines of the most bug-prone code in a red-black tree out of the kernel. Lookup and insert — the hot paths — use the real red-black tree.
kernel/src/ProHashDictionary.ev:78
Constructors
INIT()
Methods
MODIFY METHOD insertSlice(REFERENCE binary[] buf, int64 off, int64 len, V value) RETURNS STATUS
METHOD lookupFastSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
Comma-return lookup — no pipe-XOR (V | STATUS) tuple on the hot path.
METHOD containsSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
MODIFY METHOD removeSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
Remove. Unlinks the entry from the bucket's member chain, then RE-INDEXES the bucket: a treeified bucket that has fallen to the untreeify threshold drops its red-black index and reverts to a plain chain (hysteresis: treeify at >8, untreeify at <=6, so churn around the boundary cannot thrash); one still above it rebuilds the index. Rebuilding rather than running the CLRS red-black delete-fixup is a deliberate, bounded simplification (O(depth)) — labelled, not hidden. It keeps the single most bug-prone routine in a red-black tree out of the kernel, and remove is not the hot path; lookup and insert use the real tree.
MODIFY METHOD insert(REFERENCE binary[] key, V value) RETURNS STATUS
METHOD lookupFast(REFERENCE binary[] key) RETURNS boolean
METHOD __op_index__(REFERENCE binary[] key) RETURNS V
Direct value read — d[key]. V default (0) on a miss. No pipe-XOR.
METHOD lookup(REFERENCE binary[] key) RETURNS | V
Pipe-XOR lookup — the kernel idiom, kept OFF the hot path.
METHOD lookupRef(REFERENCE binary[] key) RETURNS | MUTABLE REFERENCE V
METHOD contains(REFERENCE binary[] key) RETURNS boolean
MODIFY METHOD remove(REFERENCE binary[] key) RETURNS boolean
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
MODIFY METHOD clear() RETURNS void
METHOD bucketIndexOf(REFERENCE binary[] key) RETURNS int64
The bucket a key currently maps to.
Exposed for TESTABILITY of the adaptive tier. SipHash keying means an attacker cannot force colliding keys — which also means a TEST cannot, so the chain->tree escalation would otherwise be unreachable, untested kernel code. This lets a test group keys that share a bucket and drive the escalation deterministically.
It does NOT weaken the DoS guarantee: hash-flooding's threat model is "the attacker supplies KEYS (data) that the victim hashes", not "the attacker calls methods on the victim's dictionary". Anyone able to invoke this already has code execution in-process, at which point the hash is not the weak link. Do not, however, echo the result across a trust boundary — that WOULD hand out a collision oracle.
METHOD maxBucketDepth() RETURNS int64
Deepest bucket in the table — the clustering metric the adaptive tier bounds.
METHOD treeifiedBuckets() RETURNS int64
How many buckets have escalated to a red-black tree. Zero under normal load — non-zero means collisions got deep (the adaptive tier is doing its job). Exposed so the escalation is TESTABLE and observable, not a silent internal.
METHOD iterator() RETURNS ReferenceIterator[BinaryWord]
One BinaryWord per live entry, borrowed from this dictionary's key
pool. Valid only while the dictionary is unmodified: an insert may grow
the pool and a rehash may move it.
METHOD keys() RETURNS LinkedList[BinaryWord]
MODIFY METHOD insertCopy(REFERENCE BinaryWord key, REFERENCE V value) RETURNS STATUS
MODIFY METHOD insert(BinaryWord key, V value) RETURNS STATUS
METHOD lookupFast(REFERENCE BinaryWord key) RETURNS boolean
Dictionary.lookupFast — the interface-shaped (BinaryWord-keyed) peer of
the binary[] slice form above. K is BinaryWord for this class, so this
is the overload that satisfies the interface; the slice form stays for
the zero-copy call sites that already hold a buffer and a range.
METHOD lookup(REFERENCE BinaryWord key) RETURNS | MUTABLE REFERENCE V
METHOD contains(REFERENCE BinaryWord key) RETURNS boolean
MODIFY METHOD remove(REFERENCE BinaryWord key) RETURNS | BinaryWord
The removed key is a word over this dictionary's own pool. A freed entry
is recycled through freeHead but its BYTES stay in the pool, so the
returned word reads correctly until the pool is next compacted.
METHOD equals(REFERENCE Dictionary[BinaryWord, V, H] other) RETURNS boolean
Equal when both hold the same keys mapped to the same values. Walks the smaller surface — this dictionary's entries — and asks the other by lookup, so the cost is one hash per key rather than a cross product. Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
METHOD clone() RETURNS Dictionary[BinaryWord, V, H]
Deep copy. Returns the Dictionary INTERFACE, not the concrete class —
the class is HIDDEN, so its name may appear only as a CREATE target. The
copy goes in through the interface's own insert, since insertSlice
is this class's and not the interface's.
ProHashDictionaryIteratorIMPLEMENTS ReferenceIterator
Walks the ENTRY ARENA, yielding one BinaryWord per live entry.
WHY THE ARENA AND NOT THE BUCKETS. ProHash stores entries in flat parallel arrays and threads them into buckets — a chain when shallow, a red-black tree once a bucket passes the treeify threshold. Walking the buckets would mean two traversal shapes and a recursion for the tree tier; walking the arena is one linear pass that is correct for both, and it touches each array in order rather than chasing indices. Iteration order is arena order, which is neither insertion nor hash order — a dictionary promises no order, and this one says so rather than implying one it would have to keep.
Freed entries are recycled through freeHead, so a dead slot may sit
anywhere in the arena; entLive is the only thing that decides.
Like its StringKeyed sibling, the window is one VALUE field re-assigned per step — no allocation per key.
kernel/src/ProHashDictionaryIterator.ev:32
Constructors
INIT(REFERENCE binary[] pool, REFERENCE int64[] offs, REFERENCE int64[] lens, REFERENCE int8[] live, int64 arenaSize)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE BinaryWord
METHOD peek() RETURNS | REFERENCE BinaryWord
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE BinaryWord
RedBlackTreeDictionaryIMPLEMENTS Dictionary
An ORDERED Dictionary[K, V, H] backed by a left-leaning red-black tree (Sedgewick LLRB), ARENA form. Guaranteed O(log n) lookup / insert / remove; iteration yields keys in Comparable order.
── Phase-4 arena rewrite ────────────────────────────────────────
Nodes live inline in ONE RBNode[K, V][] arena value-array; child links are
int64 arena indices (-1 = null), not owning handles. The owning-handle design's
per-node heap allocation (one _ev_unique<RBNode> per key) collapses to a
single growable array. rootIdx is a plain int64 (no RBRoot holder — index
assignment can't trip the move-out/EMPTY-consume rules that forced the holder).
A free-list (freeHead, threaded through a dead slot's left) reclaims slots
on delete. The iterator walks an explicit index stack (O(n) total), retiring
the subSize/nthKeyRef rank machinery.
THE ARENA DISCIPLINE (load-bearing — proved by kernel_probe/rbArenaProbe):
appending a node (alloc) can REALLOCATE the arena and dangle any live
reference into it. So: indices are stable, references are NOT. Every node
access is wrapped in a tiny index-helper (leftOf, setLeftAt, …) that binds
a fresh =@ .arena[i], touches the node, and drops the ref before returning —
so no reference is ever held across an alloc()/insertNode() that might grow the
arena. Insert allocs exactly one leaf at the bottom of the recursion; delete
never allocs (only frees), so the delete path is realloc-free.
(The helpers also sidestep a parser limitation: a bare { … } block whose
first statement declares a comma-bearing type — REFERENCE RBNode[K, V] n — is
misparsed as a set literal. Encapsulating each bind in a method avoids the bare
block entirely and reads better.)
K must additionally be Comparable (the tree orders by key). The hasher type H
is part of the Dictionary interface but UNUSED here — an ordered tree compares
keys, it does not hash — so no hasher is ever constructed (H bound satisfied
vacuously). Comparison goes through the WHEN K IMPLEMENTS Comparable[K] split
(the SortedList idiom): the compiler lowers built-in Comparable (primitives,
String) under that guard; a bare a->isLessThan(b) emits a literal method
clang rejects for primitives.
kernel/src/RedBlackTreeDictionary.ev:52
Fields
int64 rootIdxint64 countint64 freeHeadConstructors
INIT()
INIT(Hasher[K] h)
INIT(GrowthHint hint, int64 initialCapacity)
INIT(Hasher[K] h, GrowthHint hint, int64 initialCapacity)
Methods
MODIFY METHOD insert(K key, V value) RETURNS STATUS
MODIFY METHOD insertCopy(REFERENCE K key, REFERENCE V value) RETURNS STATUS
METHOD lookup(REFERENCE K key) RETURNS | MUTABLE REFERENCE V
METHOD lookupFast(REFERENCE K key) RETURNS boolean
Dictionary.lookupFast — the same descent as lookup, without the
STATUS that lookup must allocate on a miss.
MODIFY METHOD remove(REFERENCE K key) RETURNS | K
Remove — hands back the STORED key and value (not the probe key, which is what the old key-only remove returned).
Like the SoA dictionaries and unlike ChainedHashDictionary, the halves are cloned rather than moved: the arena node is reached by index and a subscript read clones by rule (stmt_assign.py:149), and the LLRB delete rebalances the tree, so the node cannot simply be evicted first. Census pins this at one DUPLICATE per half.
METHOD contains(REFERENCE K key) RETURNS boolean
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
Number of key-value pairs currently stored. Read-only, O(1).
MODIFY METHOD clear() RETURNS void
METHOD keys() RETURNS LinkedList[K]
METHOD iterator() RETURNS ReferenceIterator[K]
METHOD clone() RETURNS Dictionary[K, V, H]
METHOD equals(REFERENCE Dictionary[K, V, H] other) RETURNS boolean
for Equatable Interface Dictionary is equal if all keys between the two dictionaries are equal Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
RedBlackTreeDictionaryIteratorIMPLEMENTS ReferenceIterator
Forward, in-order key iterator for RedBlackTreeDictionary (ARENA form). Yields keys in Comparable order (the tree's natural order), each as a non-owning REFERENCE into the live arena.
This holds an explicit index stack of the un-visited left spine and advances ONE step per next(): pop the top (the next in-order node), then push the left spine of its right child. O(n) total, O(h) space.
Per the iterator rules it holds NEITHER an iterator-typed field (Rule A /
E1112) NOR an owning class field (Rule B / E1113); a mutation-locked REFERENCE
to the arena array plus primitive cursors and an int64[] stack (a value-typed
storage shorthand — exempt from Rule B) are all permitted. The per-node key is
bound DIRECTLY to the node's INTERNAL key field (value =@ nd.key), never via
an accessor (whose inlining into a =@ bind would copy the move-only key —
the key-bind gotcha shared with HashBucketIterator).
Parameterised over [K, V] (V needed to name RBNode[K, V]); H is irrelevant.
kernel/src/RedBlackTreeDictionaryIterator.ev:34
Constructors
INIT(REFERENCE RBNode[K, V][] arena, int64 root, int64 count)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE K
METHOD peek() RETURNS | REFERENCE K
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE K
ShallowDictionaryIMPLEMENTS Dictionary
A Dictionary[K,V,H] with a WHOLE-KEY-SET-AWARE multiply-shift index and a prime-modulus fallback tier: linear-probe open-addressing over a STRUCT-OF-ARRAYS. Pure Envzn, zero-dep.
STATUS — PARKED as a narrow, documented option, NOT the default. A measurement-driven
finding settled its role: a dictionary lookup is memory-bound, and
cache-fast access requires either an IDENTITY hash on dense keys (IntKeyedDictionary's
key & mask, ~1.1x C) or INLINE byte-dense slots (StringKeyedDictionary). A MIXING
index — FNV, SipHash, OR this class's multiply-shift — scatters adjacent keys to
random slots by design, eating a cache miss per probe, which floors any such dict at
~3-4x C. Measured here: ~4.6x C for int keys, SLOWER than ChainedHashDictionary
(~3.3x). So multiply-shift is robust-but-slow; it does NOT unify "fast + robust" (the
two are physically opposed). Its one distinct property — structural (bit-pattern)
attack resistance without a keyed hasher — is better served by ProHashDictionary
(SipHasher, which also stops hash-collision attacks). Kept correct + tested as an
explicit option; use IntKeyedDictionary / StringKeyedDictionary for speed,
ChainedHashDictionary as the general default, ProHashDictionary for DoS.
WHY "SHALLOW": at each rehash it holds the whole live key set, SEARCHES a few
candidate 64-bit multipliers, and adopts the one that keeps home-slot depth
shallowest for THIS key set — a hash chosen for the actual keys, not blind. If no
pow2 multiplier can tame a pathological set (keys whose entropy is trapped in a few
low bits — e.g. all multiples of a power of two), it falls back to a PRIME-sized
table with mod-prime indexing, which is coprime to any 2^k stride and breaks those
structural collisions. This is the robustness IntKeyedDictionary's hash & mask
deliberately trades away for cache speed — ShallowDictionary is the safe default;
IntKeyedDictionary is the trusted-key fast tier.
INDEX — two composed layers (slotFor):
- pow2 (common): slot = (mult * hash) >> shift, probe (s+1) & mask.
- prime (fallback): slot = (mult * hash) % p, probe s+1 wrap-at-p.
The multiply-shift mixes ALL bits of the hasher output, so it rescues a weak/cheap
hasher (FastIntHasher's identity) and is harmless for a strong one (FNV/SipHash is
already uniform → the search converges on the first candidate). Full hasher
pluggability AND a whole-key-set-aware low-collision index, together.
STORAGE — four parallel value-arrays (SoA, blittable → flat _ValueArray; the hot
probe touches only the dense slotState/slotHash, then one keys[s]):
- slotState : int8[] — 0 empty / 1 full / 2 tombstone. Liveness lives here, so
ANY key value is valid (no reserved sentinels — unlike IntKeyedDictionary).
- slotHash : uint64[] — cached full hash per slot; the slotHash[s]==h
fast-reject skips the key compare on almost all non-matches (crucial once String
keys land — a mismatched hash never calls equals).
- keys : K[], vals : V[] — parallel per-slot key/value.
DoS: hash-flooding resistance comes from the pluggable hasher H — construct as
ShallowDictionary[K,V,SipHasher[K]] for a keyed, attacker-proof hash; the prime
fallback additionally bounds structural (bit-pattern) attacks. Default
(DefaultHasher / FNV) is the fast general-purpose choice.
V1 SCOPE: primitive K/V (the blittable fast path — SoA _ValueArray). String keys
(the design's 5x-over-chained headline) are the next step; they need object-array
slot handling (empty-slot placeholders + the cached-hash reject to gate equals),
which the cached-hash column above is already laid out for.
IMPLEMENTS Dictionary[K, V, H] — Cloneable comes transitively (Dictionary EXTENDS
Cloneable). H is the interface hasher slot; the stored hasher is the Hasher OF K
interface (no-arg INIT CREATEs DefaultHasher). Plus the non-pipe-XOR fast path
(operator[] / lookupFast) for callers holding the concrete type.
kernel/src/ShallowDictionary.ev:76
Fields
int64 countint64 tombstonesint64 capint64 shiftAmtuint64 multint64 maskboolean primeModeuint64 primePConstructors
INIT()
INIT(Hasher[K] h)
Methods
MODIFY METHOD insert(K key, V value) RETURNS STATUS
MODIFY METHOD insertCopy(REFERENCE K key, REFERENCE V value) RETURNS STATUS
METHOD lookup(REFERENCE K key) RETURNS | MUTABLE REFERENCE V
METHOD __op_index__(REFERENCE K key) RETURNS V
Direct value read — d[key]. Returns the stored value on a hit, or the V
default (0) on a miss. No pipe-XOR (V | STATUS) tuple on the hot path.
METHOD lookupFast(REFERENCE K key) RETURNS boolean
Comma-return lookup — boolean f, V v := d->lookupFast(key). No pipe-XOR;
found distinguishes a miss from a stored default.
METHOD contains(REFERENCE K key) RETURNS boolean
MODIFY METHOD remove(REFERENCE K key) RETURNS | K
Remove — hands back the stored key and value. Like IntKeyedDictionary and unlike ChainedHashDictionary, an SoA open-addressed table has no move-out-at-index primitive, so a subscript read clones rather than moves (stmt_assign.py:149). Census pins this at one DUPLICATE per half.
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
MODIFY METHOD clear() RETURNS void
METHOD iterator() RETURNS ReferenceIterator[K]
METHOD keys() RETURNS LinkedList[K]
METHOD clone() RETURNS Dictionary[K, V, H]
METHOD equals(REFERENCE Dictionary[K, V, H] other) RETURNS boolean
for Equatable Interface Dictionary is equal if all keys between the two dictionaries are equal Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
ShallowDictionaryIteratorIMPLEMENTS ReferenceIterator
The ReferenceIterator OF K returned by ShallowDictionary.iterator(). Walks the struct-of-arrays slots, yielding a REFERENCE K per live slot (slotState[pos] == 1).
Holds mutation-locking REFERENCEs to the dictionary's keys value-array and its
slotState liveness array (bound with =@ in INIT); the lock pins the source
dictionary against mutation for the iterator's declaring-block lifetime. Cursor
pos is the next slot to examine; advanceToValid() skips empty (0) and tombstone
(2) slots.
Parameterised over [K, V] to match the dictionary's arity; V is unused (the values are not walked), the hasher H is not needed (the iterator never hashes).
kernel/src/ShallowDictionaryIterator.ev:28
Constructors
INIT(REFERENCE K[] keyArr, REFERENCE int8[] stateArr, int64 capacity)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE K
METHOD peek() RETURNS | REFERENCE K
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE K
StringKeyedDictionaryIMPLEMENTS Dictionary
A byte-keyed dictionary: linear-probe open-addressing over a STRUCT-OF-ARRAYS with BYTE-DENSE keys held in ONE FLAT binary[] pool, a byte-FNV hash, and a memcmp confirm. The STRING FAST TIER. Pure Envzn, zero-dep.
WHY the key is a byte array, NOT Dictionary[String, V, H]:
Two compiler realities, met head-on, shaped this class:
1. The Dictionary[BinaryWord,V,H] INTERFACE cannot fix one of its type parameters — an
impl must be parameterised over the SAME type variables as the interface (a
... IMPLEMENTS Dictionary[String, V, H] is rejected E2103: the interface body
still references BinaryWord, unbound in the impl's scope). So there is no way to write a
String-SPECIALISED Dictionary impl; a generic [BinaryWord,V,H] one (ChainedHashDictionary)
is the only shape, and it must hash/compare keys through the pluggable Hasher
+ Equatable == — the SLOW char32 path (String stores char32 code points; each
hash/equals iterates them through handle-indirected, bounds-checked accessors).
2. The s05 word-dict study (FINDINGS.md #5/#9/#17) proved the fast form is
BYTE-DENSE keys read by DIRECT FLAT-ARRAY INDEXING — "byte-dense IS faster; the
slowness was ByteBuffer method dispatch, not byte-density."
So this class takes the KEY AS binary[] bytes (the caller transcodes its String
once, key INTO ByteBuffer → bytes, UNTIMED — exactly the s05 benchmark's contract),
sidestepping BOTH the interface-fix wall and the per-lookup String→bytes transcode.
It is a standalone CLASS, constructed directly. The "relocate cost inward" tier for
string/byte keys.
MODELLED ON benchmarks/s05_worddict/envzn_shimopt/native/native.hpp — the shim's
open-addressing map (byte-FNV + linear probe + stored-hash reject + length reject +
memcmp confirm), REBUILT PURE: what the inline C++ shim did with libc, the new
language performance levers do in-language —
- HOTLOOP → the byte-FNV hash loop (hoists the per-byte bounds check to
one up-front range check; the constitution I.H.iii(f) example
IS this hash).
- System->memoryCompare → the key confirm (std::memcmp, one bounds-checked call per
probe instead of a per-byte Envzn loop). The HOT-path lever.
- System->memoryWord → available for a word-wise long-key hash (not exercised by the
short Shakespeare words; a length-gated follow-up).
STORAGE — a FLAT byte pool + five parallel per-slot arrays (SoA; the hot probe touches
only the dense slotState/slotHash, then the pooled key bytes):
- keyBytes : binary[] — ONE flat, append-only pool; every key's bytes live here,
contiguous — the cache-dense form the s05 study crowned (#17). A removed key's
bytes linger until clear() (no compaction in V1 — a bounded, documented cost;
memoryCopy-based compaction on high-tombstone rehash is the follow-up).
- slotOff : int32[], slotLen : int32[] — each slot's key start + length in the pool.
- slotState : int8[] — 0 empty / 1 full / 2 tombstone (liveness; any byte content
is a valid key).
- slotHash : uint64[] — cached full FNV hash; the slotHash[s]==h fast-reject skips
the length + memcmp on almost every non-match (the crucial gate for byte keys).
- vals : V[] — parallel per-slot value.
INDEX — hash & mask (pow2), probe (s+1) & mask — native.hpp's index exactly. FNV
is a MIXING hash so this scatters, but for arbitrary string keys there is no dense-key
structure to exploit; the byte-dense pool + cached-hash reject is the cache lever here,
not index locality (the s05 finding, distinct from IntKeyedDictionary's key & mask).
SURFACE — a byte-array analogue of the Dictionary fast tier: insert/lookupFast/
lookup (pipe-XOR)/lookupRef/contains/remove/size/isEmpty/clear/clone.
Each comes in a whole-array form (insert(binary[] key, ...), key IS the array) and a
zero-copy SLICE form (insertSlice(buf, off, len, ...)) for the s05 flat-query loop
that never allocates per lookup. Iteration over pooled keys is a deferred follow-up.
kernel/src/StringKeyedDictionary.ev:73
Fields
uint64 primeuint64 h_maskint64 countint64 tombstonesint64 capuint64 maskConstructors
INIT()
Methods
MODIFY METHOD insertSlice(REFERENCE binary[] buf, int64 off, int64 len, V value) RETURNS STATUS
Insert the key slice buf[off .. off+len) → value (value MOVEd in). New keys
are interned into the flat pool. Replacing an existing key leaves count unchanged.
METHOD lookupFastSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
Comma-return lookup over a slice — boolean f, V v := d->lookupFastSlice(buf,off,len).
No pipe-XOR tuple on the hot path.
METHOD lookupSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS | V
METHOD containsSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
MODIFY METHOD removeSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS boolean
MODIFY METHOD insert(REFERENCE binary[] key, V value) RETURNS STATUS
METHOD lookupFast(REFERENCE binary[] key) RETURNS boolean
METHOD lookup(REFERENCE binary[] key) RETURNS | V
METHOD lookupRef(REFERENCE binary[] key) RETURNS | MUTABLE REFERENCE V
METHOD contains(REFERENCE binary[] key) RETURNS boolean
MODIFY METHOD remove(REFERENCE binary[] key) RETURNS boolean
METHOD isEmpty() RETURNS boolean
METHOD size() RETURNS int64
MODIFY METHOD clear() RETURNS void
MODIFY METHOD insert(BinaryWord key, V value) RETURNS STATUS
METHOD lookupFast(REFERENCE BinaryWord key) RETURNS boolean
Dictionary.lookupFast — the interface-shaped (BinaryWord-keyed) peer of
the binary[] slice form above. K is BinaryWord for this class, so this
is the overload that satisfies the interface; the slice form stays for
the zero-copy call sites that already hold a buffer and a range.
METHOD lookup(REFERENCE BinaryWord key) RETURNS | MUTABLE REFERENCE V
METHOD contains(REFERENCE BinaryWord key) RETURNS boolean
MODIFY METHOD remove(REFERENCE BinaryWord key) RETURNS | BinaryWord
The removed key is returned as a word over THIS dictionary's pool, and the pool outlives the slot — a tombstone does not reclaim the bytes — so the returned word stays readable until the next rehash compacts them.
METHOD iterator() RETURNS ReferenceIterator[BinaryWord]
One BinaryWord per live key, borrowed from this dictionary's pool.
Valid only while the dictionary is: the words point INTO its storage,
and a rehash moves that storage.
METHOD keys() RETURNS LinkedList[BinaryWord]
Every live key, as borrowed words. Same lifetime caveat as iterator().
MODIFY METHOD insertCopy(REFERENCE BinaryWord key, REFERENCE V value) RETURNS STATUS
METHOD clone() RETURNS Dictionary[BinaryWord, V, H]
Returns the Dictionary INTERFACE, not the concrete class — the class
is HIDDEN, so its name may appear only as a CREATE target, and this is
the shape ProHashDictionary.clone() already had. The copy goes in
through the interface's own insert, since insertSlice is this
class's and not the interface's.
METHOD equals(REFERENCE Dictionary[BinaryWord, V, H] other) RETURNS boolean
for Equatable Interface Dictionary is equal if all keys between the two dictionaries are equal Two dictionaries are equal when they hold the SAME ASSOCIATIONS: the same keys, each mapping to an EQUAL VALUE.
Not merely the same KEYSET. That would rank {a:1} equal to {a:2}, so
two "equal" dictionaries would answer lookup(a) differently and neither
could stand in for the other — which is the whole point of an equivalence.
Keys-AND-values is what C++ (map and unordered_map), Rust, Swift,
Julia, Python and Java all specify. Keyset equality is a perfectly good
relation, but it is equality of the DOMAIN rather than of the dictionary,
and it deserves its own name (hasSameKeys) rather than this one.
Equal sizes plus a one-way walk is sufficient: with the counts already
equal, other cannot carry a key this one lacks unless this one also
carries a key other lacks — and the walk would have found that.
StringKeyedDictionaryIteratorIMPLEMENTS ReferenceIterator
Walks the open-addressed slot table, yielding one BinaryWord per OCCUPIED
slot — a borrowed window onto that key's bytes in the shared pool.
NO ALLOCATION PER KEY, and that is the whole reason this class exists rather
than materialising keys. The window is a VALUE class held in one field,
.cur, re-assigned at each step; next() hands back a reference to that
field. So a walk of a million keys performs one assignment per key and no
heap traffic at all — which is what keeps the dictionary's measured
advantage intact while it satisfies the Dictionary contract.
Slot states match the dictionary's own encoding: 0 empty, 1 occupied, 2 tombstone. Only 1 is yielded.
kernel/src/StringKeyedDictionaryIterator.ev:28
Constructors
INIT(REFERENCE binary[] pool, REFERENCE int64[] offs, REFERENCE int64[] lens, REFERENCE int8[] states, int64 capacity)
Methods
METHOD hasNext() RETURNS boolean
MODIFY METHOD next() RETURNS | REFERENCE BinaryWord
METHOD peek() RETURNS | REFERENCE BinaryWord
MODIFY METHOD skip(uint64 n) RETURNS | REFERENCE BinaryWord
BinaryWordIMPLEMENTS Cloneable, Hashable, Equatable
A BORROWED window onto a run of bytes: the array, where the run starts, and
how long it is. Value-copied and inline — copying a BinaryWord copies three
machine words, never the bytes.
WHY IT EXISTS. A byte-keyed dictionary stores every key end-to-end in one
pool and remembers each key as an (offset, length) pair, because that is what
makes it fast: one allocation for all the keys instead of one per key. But a
key so stored is not a value the language can hand back — binary is a
single byte, and an iterator yielding bytes cannot say where one key ends and
the next begins. BinaryWord is that missing value: the pair the dictionary
already holds, given a type.
It BORROWS. The bytes belong to whatever pool the window was opened on, and
a BinaryWord is valid exactly as long as that pool is. It is the byte-axis
sibling of StringView/ByteBufferView, and differs from them in being a
VALUE class: a view is an object reached through a handle, while a word is
copied inline, which is what lets an iterator yield one per step without
allocating.
kernel/src/BinaryWord.ev:30
Constructors
INIT(REFERENCE binary[] src, int64 off, int64 len)
Methods
METHOD length() RETURNS int64
Bytes in the window.
METHOD offset() RETURNS int64
Where the window opens in the underlying pool. A caller holding the pool
can use this with length() to reach the bytes directly — which is how
the slice fast paths avoid going through the window at all.
METHOD at(int64 i) RETURNS | binary
The byte at i within the window, or FAILURE when i is outside it.
METHOD clone() RETURNS BinaryWord
METHOD hash() RETURNS uint64
METHOD equals(REFERENCE BinaryWord other) RETURNS boolean
Equal when the windows hold the same bytes — not when they name the same place. Two words over different pools are equal if their bytes match.
METHOD isLessThan(REFERENCE BinaryWord other) RETURNS boolean
Lexicographic by bytes, shorter-is-less on a shared prefix — the order a byte-keyed tree needs to stay total.
The class-backed numeric primitives and the math that works on every number type.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
NumStorenumber is an ergonomic unified numeric — an integer XOR a float, never
both and never neither — backed by this compiler-known value-class. It is
NEVER dev-instantiated (there is no CREATE Number); it is driven entirely
by the number primitive surface and by literals. It is copy-by-value (a
value-class, NOT opaque's move-only model).
Storage is a NumberKind tag (INTEGER | UNSIGNED | FLOAT) selecting one arm of
a raw NumStore UNION (int64 XOR uint64 XOR float64). The tag makes every access
safe — the unsafe union read is encapsulated entirely behind this value-class
surface (the north-star "relocate the cost inward" tiebreak). The UNSIGNED arm
(number-unsigned-arm-design.md, #38) is value-classified, not surface-typed: it
is reached only when an integer overflows the int64 arm into (int64_max,
uint64_max], giving full [int64_min, uint64_max] integer fidelity.
See number-and-complex-design.md and ENVZN_CONSTITUTION.md I.D.i(g). NumberKind (the INTEGER|FLOAT subtype tag) lives in enums.ev per the kernel convention that all ENUMs are declared there (E9031).
kernel/src/Number.ev:34
Fields
int64 iuint64 ufloat64 fNumberkernel/src/Number.ev:41
Fields
NumberKind tagNumStore storeConstructors
INIT()
Default-initialize to zero, INTEGER subtype (constitution I.D.i(b): every
numeric primitive default-inits to zero). Without this the synthesized
zero-init would leave tag at 0 — not the INTEGER case — since kernel
enums start at 1.
INIT(int64 v)
INIT(uint64 v)
Widen-in from an unsigned 64-bit value. Value-classified by the ladder:
a magnitude that still fits the signed arm (v ≤ int64_max) is stored as
INTEGER so it compares/prints identically to the same int literal; only a
value in (int64_max, uint64_max] takes the UNSIGNED arm. This is the total
uint64 INTO number edge (no fallible AS needed — every uint64 fits).
INIT(float64 v)
Methods
METHOD kind() RETURNS NumberKind
The subtype this number currently holds — INTEGER, UNSIGNED, or FLOAT. The
V1 introspection surface (the typed, MATCH-able stand-in for V2 runtime
WHEN n IS int64). A pure tag read; never touches the union arm.
METHOD equals(number other) RETURNS boolean
Value-equality across subtypes (the Equatable surface a == b lowers to).
Any float-subtype operand compares by IEEE value (the integer arm promoted
to double) — so number(3) == number(3.0) is TRUE, number(0.1+0.2) ==
number(0.3) is FALSE. Two integer-kind operands are equal only when they
share an arm: INTEGER (≤ int64_max) and UNSIGNED ((int64_max, uint64_max])
hold DISJOINT value ranges, so a cross-arm compare is FALSE without ever
comparing signed to unsigned bits (no UB). Tolerance is ≈; bit-exact is
BEQUALS.
METHOD isLessThan(number other) RETURNS boolean
Ordering by mathematical value across arms (the a < b surface). Mirrors
equals: any float-subtype operand compares by IEEE value, so
number(2) < number(2.5) is TRUE. Two integer-kind operands compare in
the int128 domain, which unifies the INTEGER and UNSIGNED arms into one
signed-wide value — so a cross-arm compare is ORDERED (unlike equality,
where the disjoint ranges make it simply FALSE) and never compares signed
to unsigned bits.
NaN: the float path delegates to float64's own <, so every comparison
against a NaN is FALSE — the same answer float64 gives. That is why the
four operators derive by SWAPPING operands and never by negating: NOT (b
< a) would make NaN <= x TRUE. (I.D.g.v)
METHOD isLessThanOrEqual(number other) RETURNS boolean
a <= b. A separate method rather than NOT isLessThan(b, a) for the
NaN reason in isLessThan above: negation flips NaN's correct FALSE into
a wrong TRUE. > and >= are the operand-swapped forms of these two.
METHOD __op_plus__(number other) RETURNS number
Arithmetic. Any float-subtype operand → float result (the integer arm
promoted to double — the common float path, unchanged). Otherwise both are
integer-kind: compute in int128 so int64 overflow is seen, then classify
down the ladder — so number overflow promotes (INTEGER→UNSIGNED→FLOAT)
instead of wrapping. */^ whose result exceeds int128 drop to FLOAT.
METHOD __op_minus__(number other) RETURNS number
METHOD negate() RETURNS number
Negation — -n lowers to this (number has no C++ unary operator-).
A FLOAT negates in float64, so -0.0 stays a signed zero; an integer kind
negates in int128 and classifies back down the ladder, so negating a
uint64 past int64's range promotes instead of wrapping — the same rule
0 - n follows.
METHOD __op_times__(number other) RETURNS number
Multiply. Integer-kind operands compute in int128; the one integer op whose
product can exceed int128 (near-uint64_max × near-uint64_max ≈ 2^128), so a
recover-and-check (a≠0 ∧ p/a≠b ⇒ the multiply wrapped) drops to FLOAT.
METHOD __op_divide__(number other) RETURNS number
METHOD __op_floordiv__(number other) RETURNS number
Floor division (~/) — floors toward negative infinity (vs / which
truncates). Integer-kind → int128 floor then classify; any float → float
floor. Division shrinks magnitude so it never overflows the int128 domain
(int64_min ~/ -1 lands at 2^63, which the ladder classifies UNSIGNED).
METHOD __op_power__(number other) RETURNS number
Power (^). Any float operand → float result. Integer-kind: a negative
exponent is fractional → FLOAT; otherwise iterate in int128, dropping to
FLOAT the moment a multiply would exceed int128. Bases 0/1/−1 are handled
directly so a huge exponent can't spin the loop (|base|≥2 overflows within
~127 steps).
METHOD isClose(number other, float64 rtol, float64 atol) RETURNS boolean
Approximate equality (the ≈ / ≉ operator lowers to this). Two
int-subtype operands compare EXACTLY — integers carry no representation
error, so ≈ adds nothing there. Otherwise (any float involved) the
principled tolerance applies: |a − b| ≤ max(rtol·max(|a|,|b|), atol).
The atol floor is what makes comparison to zero work. Operator defaults
come from the desugar; this method is also the explicit-tolerance surface.
ComplexThe complex primitive's backing value-class.
complex is one complex-number type, backed by this compiler-known value-class
and NEVER dev-instantiated (no CREATE Complex); it is driven entirely by the
complex primitive surface and the real + coeff im literal form. Copy-by-value.
Internally it is a pair of numbers — the real and imaginary components — each
keeping its own int/float subtype, so a single complex spans both Gaussian-
integer complexes (3 + 4im, integer components) and float complexes
(3.0 + 4.0im), and even mixed ones (3 + 4.0im). Per-component arithmetic is
just number arithmetic, which is why complex is built ON number.
The field is named imag (not im) because im is the reserved imaginary-unit
token; the public accessors are .real / .imaginary (each a number), added
in a later cycle alongside .conjugate / .magnitude / .phase.
See number-and-complex-design.md Part 2 and ENVZN_CONSTITUTION.md I.D.i(g).
kernel/src/Complex.ev:38
Fields
number renumber imagConstructors
INIT(number re, number imag)
Methods
METHOD equals(complex other) RETURNS boolean
Component-wise value-equality (the Equatable surface a == b lowers to).
Two complexes are equal iff both components are equal as numbers — so
(3 + 4im) == (3 + 4im). There is NO ordering on complex (</> are a
compile error): the complex field is not ordered.
METHOD __op_plus__(complex other) RETURNS complex
Addition / subtraction — component-wise, the reals with the reals and the
imaginaries with the imaginaries: (8 + 6im) = (3 + 4im) + (5 + 2im).
Each component op is ordinary number arithmetic; the result reassembles
through the rp + ip im literal form (fused at parse time, so this does
not recurse into the very operator being defined).
METHOD __op_minus__(complex other) RETURNS complex
METHOD __op_times__(complex other) RETURNS complex
Multiplication: (a + bi)(c + di) = (ac − bd) + (ad + bc)i. The cross terms
are what make im² = −1 fall out — (0 + 1im) * (0 + 1im) = (−1 + 0im).
METHOD real() RETURNS number
The real component (a in a + bi), as a number.
METHOD imaginary() RETURNS number
The imaginary component (b in a + bi), as a number.
METHOD conjugate() RETURNS complex
The complex conjugate — flips the sign of the imaginary part:
conjugate(a + bi) = a − bi. Multiplying a value by its conjugate gives a
real ((a+bi)(a−bi) = a² + b²), which is why division scales by it.
METHOD magnitude() RETURNS number
Magnitude (modulus) |a + bi| = √(a² + b²) — the distance from the origin,
always a non-negative real. Computed in float64 via Math.sqrt, so the
result is a float-subtype number. (Complex depends on Math here.)
METHOD phase() RETURNS number
Phase (argument) of a + bi = atan2(b, a) — the angle in radians from the
positive real axis, in (−π, π]. A float-subtype number.
METHOD negate() RETURNS complex
Negation — -c lowers to this: −(a + bi) = (−a) + (−b)i. (Unary minus on
a complex routes here; complex has no C++ unary operator-.)
METHOD __op_divide__(complex other) RETURNS complex
Division: (a + bi)/(c + di) = [(ac + bd) + (bc − ad)i] / (c² + d²).
Both components are scaled by the real denominator |other|². With integer
components this follows number's truncating integer /; float-component
complexes divide exactly — use those when an exact quotient is wanted.
Decimal128The decimal128 primitive's backing value-class (V1).
decimal128 is an IEEE 754-2008 exact base-10 numeric, backed by this
compiler-known value-class. NEVER dev-instantiated (no CREATE Decimal128 in
user code); driven by the decimal128 surface, literals, and AS/INTO. Copy-by-
value, blittable. Exact + cohort-normalized ⇒ Comparable AND Hashable.
Storage is { int128 coefficient; int32 exponent }: value = coefficient × 10^exponent. int128 holds ~38 decimal digits, ≥ the IEEE decimal128 34-significant-digit requirement. The hard decimal machinery lives here (north-star "relocate the cost inward"); the dev surface is a plain primitive.
ROUNDING CONTEXT: a RoundingMode enum + the single decideUp decision
funnel parametrize the reducers (reduced/mulReduce/divReduce) by (precision,
mode); the bare operators forward (34, HALF_EVEN) so their behavior is
unchanged. Public surface: roundTo(places[, mode]) (decimal-place rounding)
and add/subtract/multiply/divide(other, precision, mode) (explicit
significant-digit context). See decimal128-design.md.
kernel/src/Decimal128.ev:30
Fields
int128 coefficientint32 exponentConstructors
INIT()
Default-initialize to zero (constitution I.D.i(b)).
INIT(int128 coeff, int32 exp)
Construct from a (coefficient, exponent) pair: value = coefficient × 10^exponent. The form the literal/conversion/arithmetic lowering targets.
Methods
METHOD powTen(int32 n) RETURNS int128
10^n as int128, for 0 ≤ n ≤ 38 (callers keep n in range). n < 0 → 1.
METHOD digitCount(int128 v) RETURNS int32
Decimal digit count of |v| (zero counts as 1 digit). Overflow-safe (uses ~/).
METHOD decideUp(int32 cmpHalf, boolean nonzeroDropped, boolean coeffOdd, boolean neg, RoundingMode mode) RETURNS boolean
Single source of truth for "round the retained magnitude UP by one?" across all seven RoundingMode values, given a cohort-free description of what was dropped below the retained coefficient: - cmpHalf — the dropped fraction vs ½ ULP of the last retained digit: +1 above ½, 0 exactly ½ (a tie), −1 below ½. - nonzeroDropped — TRUE iff ANY nonzero digit was dropped (the directed modes UP/CEILING/FLOOR round on any remainder, not just at the half). - coeffOdd — parity of the retained coefficient (HALF_EVEN tie-break). - neg — sign of the value (CEILING/FLOOR are sign-directed). Every reducing path (reduced / mulReduce / divReduce / roundedDrop) funnels its rounding decision through here, so the bare operators' fixed (34, HALF_EVEN) behavior and the explicit-mode surface share one rule and cannot drift.
METHOD roundedDrop(boolean neg, int128 mag, int32 drop, RoundingMode mode) RETURNS int128
Drop the drop lowest decimal digits (drop ≥ 1) from an EXACT magnitude
mag, rounding per mode via decideUp, and return the rounded
magnitude. The dropped part has no sticky tail (mag is exact), so the
tie test is just remainder-vs-half. Used by roundTo (decimal-place
rounding); the sig-digit reducers compute cmpHalf inline because they
also carry a sticky direction.
METHOD reduced(boolean neg, int128 mag, int32 exp, int32 stickyDir, int32 precision, RoundingMode mode) RETURNS decimal128
Build a decimal128 from a sign + magnitude + exponent, rounding the
magnitude to ≤ precision significant digits with the given mode.
stickyDir carries information about digits below mag already dropped:
+1 = the true value is slightly ABOVE mag (round up at a tie), −1 =
slightly BELOW (round down at a tie), 0 = mag is exact (tie → per mode).
Bare +/− pass (34, HALF_EVEN) so their behavior is unchanged.
METHOD addMagnitudes(int128 ca, int32 ea, int128 cb, int32 eb, int32 precision, RoundingMode mode) RETURNS decimal128
Sum of two decimals by sign+magnitude. Aligns the larger-exponent operand UP exactly (bounded so it fits int128), rounds the smaller operand DOWN to the working exponent capturing a tri-state sticky, combines by sign, then reduces to 34 digits. Subtraction's guard-borrow is handled by the sticky sign (a rounded-off subtrahend makes the true result slightly smaller).
METHOD pairDigits(int128 hPart, int128 lPart) RETURNS int32
Product of two magnitudes (each < 10^34) at the given exponent, reduced to ≤ 34 digits with round-half-even. Avoids a 256-bit binary intermediate by splitting each coefficient at 10^17 into halves whose pairwise products all fit int128 (< 10^34 < 2^113); the exact 68-digit product is carried as a (high, low) decimal pair and reduced digit-by-digit with a sticky tail. Significant-digit count of a value carried as a (high, low) decimal pair hPart·10^34 + lPart, with lPart < 10^34. When the high part is nonzero its lowest digit sits at decimal position 34, so the pair spans digitCount(hPart) + 34 digits; otherwise the count is just lPart's. The 34 here is the structural split exponent (10^34), independent of the target precision.
METHOD mulReduce(boolean neg, int128 ma, int128 mb, int32 exp, int32 precision, RoundingMode mode) RETURNS decimal128
METHOD divReduce(boolean neg, int128 ma, int128 mb, int32 exp, int32 precision, RoundingMode mode) RETURNS decimal128
Quotient of two magnitudes (mb ≠ 0) at the given exponent, to 34
significant digits with round-half-even. Schoolbook long division: take the
integer quotient, then emit fractional digits one at a time (each step
rem*10 < 10^35 stays in int128) until 34 significant digits or an exact
remainder, then one guard digit + sticky for the final rounding.
METHOD equals(decimal128 other) RETURNS boolean
Cohort-normalized VALUE equality (the Equatable surface a == b): two
decimals are equal iff their numeric values match, regardless of cohort —
1.0 == 1.00 == 1. Computed as (a − b) having a zero coefficient (the
subtraction aligns + reduces exactly), so different representations of the
same value compare equal.
METHOD isLessThan(decimal128 other) RETURNS boolean
Strict less-than (the Comparable surface): the sign of (a − b).
METHOD hash() RETURNS uint64
Cohort-invariant hash (the Hashable surface): hashes the CANONICAL form (coefficient with trailing zeros stripped + adjusted exponent), so equal values hash equal — the invariant that makes decimal128 a sound Dictionary/ Set key. FNV-1a over the canonical (coefficient, exponent). The int128 → uint64 folds are inline unchecked narrowings (Decimal128 is a floor primitive, emitted before NumericUtilities, so it can't call it).
METHOD __op_plus__(decimal128 other) RETURNS decimal128
METHOD __op_minus__(decimal128 other) RETURNS decimal128
METHOD negate() RETURNS decimal128
Negation — -d lowers to this (decimal128 has no C++ unary operator-).
Flip the coefficient's sign and keep the exponent: exact, never rounded,
and the cohort survives — -(1.50) is -1.50, which 0 - d through
addMagnitudes would not promise.
METHOD checkedExp(int64 e) RETURNS int32
Narrow a working exponent (computed in int64 to dodge int32 overflow UB)
back to the int32 exponent field, raising a recoverable MathError when the
scale overflows int32 — decision 2's "PANIC MathError on overflow".
Reachable: d = d * d doubles the exponent each step, so ~32 squarings
overflow. Decimal128 is emitted before the MathError class, so it cannot
PANIC MathError directly — it routes through the int128 floor-division
domain trap (INT64_MIN ~/ −1 → "floor division result out of range"), the
only MathError raiser reachable from a floor primitive. (The message is
the generic floor-div one; an exponent-specific message would need the
MathError class reordered ahead of Decimal128 — see decimal128-design.md.)
METHOD __op_times__(decimal128 other) RETURNS decimal128
METHOD __op_divide__(decimal128 other) RETURNS decimal128
METHOD clampPrecision(int32 p) RETURNS int32
Clamp a caller-supplied precision to the type's valid range [1, 34]: decimal128 carries at most 34 significant digits, and a precision below 1 is meaningless. Out-of-range requests are pinned to the nearest bound rather than rejected — the result is always a well-formed decimal128.
METHOD roundTo(int32 places, RoundingMode mode) RETURNS decimal128
Round to places digits after the decimal point, ties broken per mode.
Negative places rounds to tens / hundreds / … (place −2 → nearest 100).
A value already at this granularity or coarser is returned unchanged.
This is decimal-PLACE rounding (the everyday money/measurement operation);
significant-digit control is the precision arg on the arithmetic methods.
METHOD roundTo(int32 places) RETURNS decimal128
roundTo with the default HALF_EVEN (banker's) tie-break.
METHOD add(decimal128 other, int32 precision, RoundingMode mode) RETURNS decimal128
Sum reduced to precision significant digits, ties per mode — the
explicit-context form of +.
METHOD subtract(decimal128 other, int32 precision, RoundingMode mode) RETURNS decimal128
Difference reduced to precision significant digits, ties per mode —
the explicit-context form of −.
METHOD multiply(decimal128 other, int32 precision, RoundingMode mode) RETURNS decimal128
Product reduced to precision significant digits, ties per mode — the
explicit-context form of *.
METHOD divide(decimal128 other, int32 precision, RoundingMode mode) RETURNS decimal128
Quotient to precision significant digits, ties per mode — the
explicit-context form of /. Divide-by-zero raises MathError through
divReduce's floor-division, exactly as / does.
METHOD absOf(decimal128 v) RETURNS decimal128
|v| — magnitude as a decimal128 (negate the coefficient, keep the exponent). The cohort is irrelevant to closeTo (it compares values), so no normalization is needed.
METHOD closeTo(decimal128 other) RETURNS boolean
Approximate equality — the ≈ (U+2248) / ≉ (U+2249) surface. decimal128
is EXACT and 34 significant digits wide, so the number type's √machine-eps
epsilon (1.5e-8, sized for float64) is far too coarse here. closeTo is
RELATIVE (a fraction of the larger magnitude): the default tolerance agrees
to ~30 of 34 significant digits — it absorbs a few ULP of rounding noise
from /, AS, … without calling genuinely different values close. Use
->isClose(other, rtol, atol) for a caller-chosen tolerance.
METHOD isClose(decimal128 other, decimal128 rtol, decimal128 atol) RETURNS boolean
closeTo with caller-chosen relative + absolute tolerances (the principled-
tolerance companion, parallel to number->isClose): TRUE iff
|a − b| ≤ max(rtol·max(|a|,|b|), atol). rtol scales with the larger
operand magnitude (the relative term); atol is the absolute floor near
zero (where a relative test alone never matches a non-zero value).
DecimalTextkernel/src/DecimalText.ev:17
Methods
METHOD parseDecimalParts(REFERENCE String s) RETURNS | DecimalParts
Scan EXACT decimal text into its (coefficient, exponent) parts — an optional sign, integer digits, and an optional '.' with fractional digits ("19.99", "-0.01", "100", "+5.0"). The coefficient is every digit as a signed int128; the exponent is −(fractional digit count), so the text's scale is preserved ("1.00" → coefficient 100, exponent −2). Fallible: empty input, a stray character, a second '.', no digits, or int128-overflow of the coefficient.
MathNAMESPACE of standard math functions and constants.
Math is a stateless NAMESPACE (the mirror of a STRUCT: functions +
CONSTANT data, no instance), accessed via Math.methodName(args)
and Math.PI. The namespace declares the float64 constants
(PI, E, …) plus a wide method surface
covering absolute value, roots/exponentiation, logarithms,
trigonometry, rounding, sign, min/max/clamp, angle conversion,
overflow-aware integer arithmetic, and geometry helpers.
The standard math functions are bound to their C symbols in
<math.h> (and abs in <stdlib.h>) via FOREIGN BIND (V1
Part E) — see the bind block below. Domain validation (negative
roots, non-positive logarithms, out-of-range inverse-trig
arguments) stays in Envzn; each bind performs only the raw
computation.
────────────────────────────────────────────────────────────────── OVERLOAD CONVENTIONS ──────────────────────────────────────────────────────────────────
Envzn has no user generics, so methods that the spec describes
generically over a numeric T (min(T, T), wrappingAdd(T, T),
etc.) appear here as one concrete overload per primitive type:
min / max / clamp: int32, int64, float32, float64
overloads (4 per method).saturatingAdd / checkedAdd: every integer primitive —
int8..int64, uint8..uint64 (16 per method). Float overflow follows
IEEE 754 semantics; no checked variant. (WRAPPING arithmetic is not
a method — it is the operators &+ &- &* of I.F.ii(a.iv).)abs / sign: int32, int64, float32, float64 overloads.To keep this design preview reasonable in length, only the int32 and float64 overloads are spelled out below for the multi-overload families; production Math.ev expands every primitive variant. The expansion is mechanical.
────────────────────────────────────────────────────────────────── ERROR HANDLING ──────────────────────────────────────────────────────────────────
Domain errors PANIC MathError:
- sqrt, cbrt of a negative real
- log, log2, log10 of a non-positive value
- asin, acos of a value outside [-1, 1]
- pow(0, x) for x < 0
Integer overflow on plain + / - / * PANICs (MathError,
I.F.ii(a.iii)) — it never silently wraps. The explicit alternatives
are the wrapping operators &+ &- &* (modular), and the
saturating / checked method variants below.
kernel/src/Math.ev:96
Fields
float64 PIfloat64 TAUfloat64 Efloat64 PHIfloat64 EMfloat64 SQRT2float64 LN2Methods
METHOD abs(int32 x) RETURNS int32
ABSOLUTE VALUE — overloads per primitive
METHOD abs(float64 x) RETURNS float64
METHOD isNaN(float64 x) RETURNS boolean
TRUE iff x is NaN — the only value not equal to itself. The language
forbids authoring NaN as a literal (a NaN/Infinity is a computation
RESULT, never developer-assignable, I.C), so this is how a value that
can ARISE is TESTED — retiring the hand-rolled v != v idiom.
METHOD isNaN(float32 x) RETURNS boolean
METHOD isFinite(float64 x) RETURNS boolean
TRUE iff x is finite (neither ±infinity nor NaN). x - x is 0 for any
finite x and NaN for ±inf/NaN, so (x - x) == 0 is the finiteness test —
retiring the hand-rolled (f - f) == 0 idiom.
METHOD isFinite(float32 x) RETURNS boolean
METHOD squareRoot(float64 x) RETURNS complex
Square root over the reals AND into the complex plane — RETURNS complex
so a negative argument yields a pure-imaginary result instead of failing:
squareRoot(9) = (3 + 0im) (x ≥ 0 → real component)
squareRoot(-4) = (0 + 2im) (x < 0 → imaginary component)
This is the Math↔complex integration: complex c = Math.squareRoot(-4)
is a plain complex assignment. (Math depends on the complex type here; the
edge is one-way — Complex's own magnitude/phase use the bare FOREIGN math
binds, not this namespace, so there is no Math↔Complex cycle.)
METHOD cubeRoot(float64 x) RETURNS float64
METHOD exponent(float64 base, float64 exp) RETURNS | float64
METHOD eulersExponent(float64 x) RETURNS float64
METHOD loge(float64 x) RETURNS | float64
LOGARITHMS — x must be > 0; FAILURE STATUS otherwise.
METHOD log2(float64 x) RETURNS | float64
METHOD log10(float64 x) RETURNS | float64
METHOD sin(float64 x) RETURNS float64
TRIGONOMETRY — radians; asin/acos domain-checked.
METHOD cos(float64 x) RETURNS float64
METHOD tan(float64 x) RETURNS float64
METHOD asin(float64 x) RETURNS | float64
METHOD acos(float64 x) RETURNS | float64
METHOD atan(float64 x) RETURNS float64
METHOD atan2(float64 y, float64 x) RETURNS float64
METHOD sinh(float64 x) RETURNS float64
METHOD cosh(float64 x) RETURNS float64
METHOD tanh(float64 x) RETURNS float64
METHOD floor(float64 x) RETURNS float64
ROUNDING — float64 in, float64 out
METHOD ceiling(float64 x) RETURNS float64
METHOD round(float64 x) RETURNS float64
METHOD truncate(float64 x) RETURNS float64
METHOD sign(int32 x) RETURNS int32
SIGN — returns -1, 0, or 1 as int32 regardless of input type
METHOD sign(float64 x) RETURNS int32
METHOD min(int32 a, int32 b) RETURNS int32
MIN / MAX / CLAMP — overloads per numeric primitive
Spelled out for int32 + float64 in this preview; production Math.ev expands int64 / float32 variants identically.
METHOD min(float64 a, float64 b) RETURNS float64
METHOD max(int32 a, int32 b) RETURNS int32
METHOD max(float64 a, float64 b) RETURNS float64
METHOD clamp(int32 v, int32 lo, int32 hi) RETURNS int32
METHOD clamp(float64 v, float64 lo, float64 hi) RETURNS float64
METHOD toRadians(float64 deg) RETURNS float64
ANGLE CONVERSION
METHOD toDegrees(float64 rad) RETURNS float64
METHOD saturatingAdd(int32 a, int32 b) RETURNS int32
OVERFLOW-AWARE INTEGER ARITHMETIC
Two flavors per integer primitive (the WRAPPING flavor is now the
operators &+ &- & of I.F.ii(a.iv), lowered to the ev_wrap_
int32 overloads spelled out; production Math.ev expands all 8 integer primitives.
METHOD checkedAdd(int32 a, int32 b) RETURNS | int32
METHOD hypotenuseLength(float64 x, float64 y) RETURNS float64
GEOMETRY
NumericLimitsNAMESPACE of the numeric limits and the layout constants the conversion hosts read.
A conversion body used to spell its bounds as literals — v > 127,
v > 0x7F, iv > 9223372036854775807 — and a literal's type was decided
twice, once by the analyzer and once by the emitter's magnitude ladder
. A CONSTANT has one declared type, so a bound read from here
arrives typed exactly once. The four conversion hosts
(PrimitiveConversions, NumberConversions, DecimalConversions,
ComplexConversions) contain no numeric literal at all; every value they
compare against or count with is a member of this namespace, reached as
NumericLimits.INT8_MAX.
The <stdint.h> limits keep the names C gave them and are BOUND, not
declared: INT8_MIN is a macro, so a member of that name would be
rewritten by the preprocessor before clang saw a declaration. The bind
mechanism of §17 reads each macro once into a member of this namespace
(I.K.ii.d). Everything else here is an ordinary CONSTANT, typed as the
site that reads it needs — a binary mask for a byte extraction, an
int32 bias for an int32 exponent, a float64 bound for a float
range check — so no site casts.
kernel/src/NumericLimits.ev:33
Fields
int8 INT8_MINint8 INT8_MAXint16 INT16_MINint16 INT16_MAXint32 INT32_MINint32 INT32_MAXint64 INT64_MINint64 INT64_MAXuint8 UINT8_MAXuint16 UINT16_MAXuint32 UINT32_MAXuint64 UINT64_MAXint128 INT128_MINint128 INT128_MAXuint32 CODE_POINT_MAXuint16 SURROGATE_FIRSTuint16 SURROGATE_LASTfloat64 INT32_MIN_F64float64 INT32_MAX_F64float64 UINT8_MAX_F64float64 UINT16_MAX_F64float64 CODE_POINT_MAX_F64int32 INT32_ZEROint32 INT32_ONEint64 INT64_ZEROint64 INT64_ONEuint64 UINT64_ZEROuint64 UINT64_ONEint128 INT128_ZEROint128 INT128_ONEint128 INT128_TENfloat64 FLOAT64_ZEROfloat64 FLOAT64_TENbinary BYTE_MASKint64 BITS_PER_BYTEint64 BYTES_PER_HALFint64 LAST_BYTE_INDEXint64 HALF_WIDTH_BITSint32 DECIMAL128_EXPONENT_BIASint64 DECIMAL128_EXPONENT_SHIFTint64 DECIMAL128_SIGN_SHIFTchar32 DIGIT_ZEROchar32 DECIMAL_POINTchar32 MINUS_SIGNNumericUtilitieskernel/src/NumericUtilities.ev:30
Methods
METHOD floatHashBits(float64 v) RETURNS uint64
The hash-stable bit pattern of a float — the value's IEEE-754 binary64 encoding, with one canonicalisation.
A hasher may not simply widen a float into a word: that truncates the mantissa, so two distinct values collide. It takes the BITS instead, which is exact and injective — a float32 key widens into binary64 losslessly first, so both widths share this one path.
-0.0 is the single case where bits and equality disagree: IEEE says
-0.0 == 0.0, so the two MUST hash alike or a dictionary loses a key it
was handed. Both encodings therefore map to 0.
NaN needs no special case and gets none: it is equal to nothing, itself included, so no equal pair can hash differently. The consequence is worth stating plainly — a NaN inserted as a key can never be looked up again. That is IEEE's rule, not this function's.
METHOD toInt32(uint32 v) RETURNS int32
Saturating cast uint32 -> int32 (clamps anything above INT32_MAX).
METHOD truncateToUint64(uint128 v) RETURNS uint64
Low 64 bits of a 128-bit unsigned value.
METHOD truncateToUint64(int128 v) RETURNS uint64
Low 64 bits of a 128-bit SIGNED value (bit-reinterpret; no range check).
The signed sibling of the uint128 form — used by decimal128's cohort hash
and by number's int64↔uint64 reinterpret paths.
METHOD toUint64(int64 v) RETURNS uint64
Reinterpret a signed int64 as uint64 (value-preserving for the non-negative
inputs callers guarantee; bit-reinterpret otherwise). The int64 sibling of
toUint64(int32) — number AS uint64 uses it instead of an inline narrow.
METHOD truncateToUint32(uint64 v) RETURNS uint32
Low 32 bits of a 64-bit unsigned value.
METHOD truncateToInt32(int64 v) RETURNS int32
Low 32 bits of a 64-bit signed value, WRAPPING into int32's range.
Spelled out rather than cast. BAND states which bits are
kept and narrows the type to uint32; the sign is then applied by
arithmetic, because the top half of uint32 has no int32 counterpart and
AS correctly refuses it. Masking the sign bit off first makes the AS
total — it can never fail — and subtracting the bias reproduces two's
complement exactly, in Envzn, with nothing reinterpreted behind the
developer's back.
METHOD truncateToInt32(uint64 v) RETURNS int32
Low 32 bits of a 64-bit unsigned value, WRAPPING into int32's range. The unsigned-source sibling of the int64 form above; same construction.
METHOD truncateToInt32(float32 v) RETURNS int32
Truncate a float toward zero into int32 (no NaN / range check — the caller is responsible for validating the value first).
There is no total float->int spelling in the language and this host cannot reach the one fallible form: NumericUtilities is emitted BEFORE PrimitiveConversions, so AS/INTO are undeclared identifiers here. TRUNCATE refuses a float source correctly — round-toward-zero is not a bit chop. The shim sits beside ev_convert_f64_to_bits, which this file already binds, so the pattern is the file's own.
METHOD truncateToInt32(float64 v) RETURNS int32
METHOD toUint64(int32 v) RETURNS uint64
A signed int32 read as uint64 — value-preserving for the non-negative inputs callers guarantee. A NEGATIVE input does not survive: it maps into the top of the unsigned range (-1 becomes 18446744073709551615), so the sign is lost rather than the bits reinterpreted.
METHOD toInt64(uint64 v) RETURNS int64
A uint64 read as int64 — value-preserving for values <= INT64_MAX, which
callers guarantee. Above that the value wraps negative. The inverse of
toUint64(int64). It also underpins the uint64 INTO int128 conversion
(PrimitiveConversions), which splits the magnitude across two toInt64 calls
to widen positively — the direct cross-sign assign is not itself a widen.
METHOD exactScaledInt128(int128 mantissa, int32 power) RETURNS | int128
Exact integer value of mantissa × 10^power as int128, or FAILURE when the
result is not an exact integer (power < 0 leaving a remainder) or its
magnitude exceeds int128. The shared extraction behind every decimal128 AS
int*/uint*; each caller range-checks the int128 against its own width.
FloatFormatShortest-round-trippable float -> decimal string.
Portions derive from Ryu (Copyright 2018 Ulf Adams), used under the Boost Software License 1.0 — see LICENSE.md, Third-Party Notices.
Kernel-internal numeric formatter. Users never touch it directly;
FloatConverter's float→String operators delegate
here. Modelled on UTFCodec.ev — a self-contained numeric algorithm
in its own file behind a clean interface.
ALGORITHM
Implements the Ryu algorithm (Ulf Adams, "Ryū: fast float-to-string
conversion", PLDI 2018) — the shortest decimal string that round-
trips back to the exact input float. Pure Envzn: no FOREIGN, no
native shim. This replaces an earlier lossy std::to_string shim
(which gave a fixed 6 decimal places).
Re-implemented from the published algorithm rather than transcribed
from the reference C — with one exception: the precomputed constant
tables are copied verbatim, and carry per-table provenance notes in
the body. The portable RYU_OPTIMIZE_SIZE variant is the
model: it computes the pow5 / inverse-pow5 magic values at runtime
from a tiny base table rather than carrying ~1300 uint64 table
constants, and uses a hand-rolled 64x64->128 multiply (no uint128).
Upstream: github.com/ulfjack/ryu, offered under Apache-2.0 or Boost-1.0.
Envzn elects Boost-1.0 — see LICENSE.md, Third-Party Notices.
INTERFACE — bits in, String out
formatF64(uint64 bits) / formatF32(uint32 bits) take the raw
IEEE-754 bits of the float, never a float value. The float<->bits
reinterpret is the caller's job. Consequence: FloatFormat
is pure integer code with zero dependency on a float type or any
bitcast primitive.
kernel/src/FloatFormat.ev:56
Fields
uint32 LOG2_OF_5_MULTuint32 LOG2_OF_5_SHIFTint32 LOG2_POW5_MAX_Euint32 LOG10_OF_2_MULTuint32 LOG10_OF_2_SHIFTint32 LOG10_POW2_MAX_Euint32 LOG10_OF_5_MULTuint32 LOG10_OF_5_SHIFTint32 LOG10_POW5_MAX_Eint32 DOUBLE_MANTISSA_BITSint32 DOUBLE_EXPONENT_BITSint32 DOUBLE_BIASint32 FLOAT_MANTISSA_BITSint32 FLOAT_EXPONENT_BITSint32 FLOAT_BIASint32 DOUBLE_POW5_INV_BITCOUNTint32 DOUBLE_POW5_BITCOUNTint32 FLOAT_POW5_INV_BITCOUNTint32 FLOAT_POW5_BITCOUNTint32 POW5_TABLE_SIZEMethods
METHOD float64toDecimal(uint64 bits) RETURNS FloatingDecimal64
Render the IEEE-754 double whose raw bits are bits as its
shortest round-trippable decimal String.
METHOD floatingDecimalToString(FloatingDecimal64 fd, boolean isNegative) RETURNS String
Turn a FloatingDecimal64 carrier into its final String, per the Phase 4 format-policy (floatformat-ryu-plan.md): Python-style threshold (sciExp < -4 OR >= 16), compact exponent (no '+', no leading zero), no trailing '.0', sign of zero dropped, special-case spellings "NaN"/"infinity"/"-infinity". MIRRORED by floatingDecimalToBytes — the two MUST stay byte-identical.
METHOD formatF64(uint64 bits) RETURNS String
One-shot: bits → FloatingDecimal64 → String. Convenience wrapper that chains float64toDecimal + floatingDecimalToString, extracting the sign bit from the raw bits.
METHOD floatingDecimalToBytes(MUTABLE REFERENCE binary[] out, FloatingDecimal64 fd, boolean isNegative) RETURNS void
MIRROR of floatingDecimalToString — appends the bytes to out.
METHOD appendF64Bits(MUTABLE REFERENCE binary[] out, uint64 bits) RETURNS void
MIRROR of formatF64 — appends the bytes for the float whose raw
bits are bits.
METHOD appendF64(MUTABLE REFERENCE binary[] out, float64 v) RETURNS void
appendF64Bits from a float64 value — the serializer's entry point.
METHOD decimalF64(float64 v) RETURNS uint64
The Ryu decomposition of a float64 value, without formatting: v == (isNegative ? -1 : 1) * mantissa * 10^exponent, the mantissa the shortest that round-trips. Specials keep float64toDecimal's sentinel exponents (0x7FFFFFFC..0x7FFFFFFF).
METHOD float32toDecimal(uint32 bits) RETURNS FloatingDecimal32
Render the IEEE-754 float whose raw bits are bits as its
shortest round-trippable decimal. Same structural shape as
float64toDecimal above — re-read its STEP 1..5 comments
for the algorithm narrative; this body only flags the f32
specifics (narrower mantissa, narrower magic constants,
32-bit arithmetic throughout).
METHOD floatingDecimal32ToString(FloatingDecimal32 fd, boolean isNegative) RETURNS String
f32 sibling of floatingDecimalToString — identical logic; only the carrier type differs (FloatingDecimal32 vs FloatingDecimal64, uint32 vs uint64 mantissa). The shared digit-walking helpers (appendDigits, appendMantissaWithPoint, appendChars) take uint64 — uint32 mantissas widen at the call site.
METHOD formatF32(uint32 bits) RETURNS String
One-shot: bits → FloatingDecimal32 → String.
ArithmeticArithmetic[T] — the contract that T is additive: an add(T),
subtract(T), and negate(), each closed over T. It is a named
constraint (e.g. for generic bounds), NOT an operator-derivation
mechanism.
The binary OPERATORS are a separate, explicit surface: a class
overloads + / - by declaring OPERATOR +(T) RETURNS T /
OPERATOR -(T) RETURNS T (mangled __op_plus__ /
__op_minus__), exactly as number and decimal128 do. Declaring
IMPLEMENTS Arithmetic[T] does NOT by itself make a + b compile —
the operator method is what the compiler dispatches. There is no
unary operator -; expose negation as the named negate().
Implementations should be closed (add(b) returns a T),
associative, and have subtraction undo add. Built-in for the
primitive numerics. A fully-numeric custom type typically declares
both this contract and the matching operator methods, and pairs
with Comparable[T] / Multiplier[T].
kernel/src/interfaces.ev:582
Methods
METHOD add(REFERENCE T other) RETURNS T
METHOD subtract(REFERENCE T other) RETURNS T
METHOD negate() RETURNS T
FloatingGROUP HashKey — the primitives admissible as a hash key: every WordKey,
plus decimal128.
decimal128 is NOT a WordKey — #key is forbidden for it (E2153) — but it
does not need to be. It carries its own exact
hash() (Decimal128.ev), so it takes a hasher's WHEN K IMPLEMENTS Hashable
arm and never reaches the widening. That is why the general hashers admit it
and FastIntHasher/InlineIntHasher, whose bodies ARE the widening, do not.
kernel/src/interfaces.ev:153
MultiplierMultiplier[T] — the contract that T supports multiply(T) and
divide(T). Sister to Arithmetic[T]; separated because not every
additive type multiplies (e.g. Date types add a Duration but have no
meaningful multiplication). Like Arithmetic, this is a constraint,
NOT operator-derivation.
The * / / OPERATORS are declared explicitly: OPERATOR
*(T) RETURNS T / OPERATOR /(T) RETURNS T (mangled
__op_times__ / __op_divide__). A class may overload *// this
way (e.g. Matrix * Matrix); % is not overloadable.
Division by a zero-equivalent value should PANIC MathError if
undefined. Built-in for the primitive numerics. Arithmetic[T] +
Multiplier[T] + Comparable[T] is what makes a custom type satisfy
the implicit Numeric constraint.
kernel/src/interfaces.ev:606
Methods
METHOD multiply(REFERENCE T other) RETURNS T
METHOD divide(REFERENCE T other) RETURNS T
NumericPer the ENVZN module convention, this file contains INTERFACEs (and may contain GROUPs / STRUCTs). Each interface here is "reserved" — recognized by the compiler for built-in cascade rules, operator dispatch, or similar.
This file currently contains the interfaces needed to support String, Array, Stack, and ArrayIterator. Expansion as more kernel collections land (Hashable for Set/Dictionary, Equatable / Comparable fully spec'd alongside the existing Operator Overloading interfaces, etc.) — out of scope for this initial draft. GROUP Numeric — sum type spanning every primitive numeric kind.
The constitution's reserved numeric category. Used by:
- Methods that accept "any number" without committing to a
specific width (Math.isLessThan(Numeric a, Numeric b)).
- Generic numeric algorithms expressed at the kernel layer.
- Operator dispatch on Numeric-typed variables (the four
arithmetic operators are spec-defined on Numeric; the
compiler dispatches to the underlying primitive at runtime).
Includes byte because byte is structurally an unsigned 8-bit
integer and participates in numeric arithmetic in the kernel
(e.g. byte arrays for binary protocols). Excludes char
because char represents a Unicode code point — comparison /
ordering apply, but arithmetic does not.
kernel/src/interfaces.ev:37
ValuePrimitiveGROUP Collections — sum type spanning every kernel collection class.
The compiler recognises this group as the canonical "is this a
collection?" check. Every member is parametric (Foo[T] or
Dictionary[K: V]) and is guaranteed by the kernel to:
EMPTY or CREATE():= ownership transfer (per the canonical move semantics)Drives 's AUTO clone synthesis when a class has a collection- typed field: the body emits field->clone without requiring the element type to itself be Cloneable when the collection's clone internally handles its own elements.
Used by template qualifier expressions as the constraint for "this
type param accepts any kernel collection" (e.g. Dictionary's V).
GROUP ValuePrimitive — the POSITIVE form of PRIMITIVE(EXCEPT opaque,
boolean, number, complex). A negative list has to be remembered; a positive
one cannot be forgotten. The EXCEPT form was also silently WRONG: it still
admitted the four C.* boundary types, legal only inside a FOREIGN
declaration (I.D.x).
⚠ IT IS NOT A DROP-IN FOR THE ATOM, and the reason is structural. A comma in
a template qualifier is a UNION, not an intersection: V IS Cloneable,
PRIMITIVE(EXCEPT boolean) means "a Cloneable class OR such a primitive".
Writing V IS Cloneable, ValuePrimitive therefore ADDS an arm rather than
narrowing one, and PRIMITIVE is a reserved meta-category atom carrying
value semantics the analyzer reads — dropping it changed ownership analysis
and raised E3023 on CollisionNode. So this group replaces an EXCEPT list
only where the primitive constraint stands ALONE (GIVEN TYPE K IS
PRIMITIVE(EXCEPT …)), which is the hasher shape. Narrowing an atom BY a
group at a union site needs compiler support that does not exist yet.
kernel/src/interfaces.ev:79
NumberKindNumberKind — the subtype tag carried by a number primitive: a signed
integer (int64) XOR an unsigned integer (uint64, reached only when a value
overflows the int64 arm into (int64_max, uint64_max]) XOR a float (float64).
number->kind() returns this (a typed, MATCH-able surface). Backs the
Number value-class (Number.ev, V1 Part D). UNSIGNED is appended last so the
shipped INTEGER/FLOAT ordinals are unchanged. See number-and-complex-design.md,
number-unsigned-arm-design.md / ENVZN_CONSTITUTION I.D.i(g).
kernel/src/enums.ev:245
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
RoundingModeRoundingMode — how a decimal128 operation breaks at the boundary where
it must drop digits. The bare operators + - * / always round to 34
significant digits with HALF_EVEN; the explicit-context methods
(roundTo, and add/subtract/multiply/divide with an explicit
precision) take a mode. There is NO ambient/global rounding context —
every mode-taking call names its choice (the readable north-star).
The set is Java's RoundingMode minus UNNECESSARY; a superset of
IEEE 754's five rounding-direction attributes. HALF_EVEN is the
zero-default (it is listed first), matching the bare-operator behavior.
Backs the Decimal128 value-class (Decimal128.ev, V1 Part #40).
kernel/src/enums.ev:292
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
DecimalPartsDecimalParts — the (coefficient, exponent) a decimal text scans into, before
the compiler assembles them into a decimal128. Returned by
NumericUtilities.parseDecimalParts so the String INTO decimal128 lowering can
build Decimal128(coeff, exp) — the same construction the literal path emits —
without the kernel ever constructing a value-class primitive itself.
kernel/src/structs.ev:67
Fields
int128 coefficientint32 exponentInstants, durations, and timing.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
DateTimeIMPLEMENTS Comparable
UTC wall-clock instant, millisecond precision.
Storage shape (LOCKED): canonical int64 epochMs —
milliseconds since the Unix epoch — is the single source of truth.
The seven broken-down fields (year/month/day/hour/minute/second/
millisecond) are public read-only and derived once at construction
by Calendar.epochMsToFields (Calendar.ev).
Construction (LOCKED, ISO 8601 range [year 1, year 9999]): - CREATE DateTime() — wall-clock now (always valid) - DateTimeFactory->newDateTime(...) — explicit components, pipe-XOR FAILURE on out-of-range. The factory lives on the DateTimeFactory singleton because fallible INIT isn't a V1 surface (parser has no INIT-RETURNS form; revisit when it does).
kernel/src/DateTime.ev:37
Fields
int32 yearint32 monthint32 dayint32 hourint32 minuteint32 secondint32 millisecondConstructors
INIT()
Construct from the current wall-clock instant (UTC). Always valid — system time cannot be outside the representable range.
INIT(int64 epochMs)
Construct from a raw Unix epoch ms value. Primarily used by DateTimeFactory.newDateTime after it has validated components and computed epochMs via Calendar.fieldsToEpochMs — that is the supported path for explicit construction, because it surfaces a pipe-XOR FAILURE on out-of-range. Direct use is also fine if you already hold a known-valid epoch (e.g. from another DateTime, from a database column). An epoch outside [year 1, year 9999] splits into proleptic-Gregorian fields outside that range; no FAILURE is raised here, so prefer DateTimeFactory.newDateTime for untrusted input.
Methods
METHOD getEpochMs() RETURNS int64
Wall-clock instant as milliseconds since the Unix epoch (UTC).
METHOD isLessThan(REFERENCE DateTime other) RETURNS boolean
Comparable[DateTime] — strict less-than on epochMs (UTC). The
ordering operators (<, <=, >, >=) are derived by the
compiler from this single method per Comparable's convention.
METHOD equals(REFERENCE DateTime other) RETURNS boolean
Equatable[DateTime] — Comparable's parent. Two DateTimes are equal iff their epochMs match; broken-down field equality is a derived consequence (both split by Calendar from the same ms).
METHOD compareTo(REFERENCE DateTime other) RETURNS TimeComparison
Explicit three-way comparison — for callers that want the named
TimeComparison enum (BEFORE / EQUAL / AFTER) rather than
composing the Comparable primitives. Both surfaces are
intentional per Phase 0 #3 LOCKED.
METHOD __op_plus__(REFERENCE TimeDuration d) RETURNS DateTime
dt + td — shift forward by d. UTC.
METHOD __op_minus__(REFERENCE TimeDuration d) RETURNS DateTime
dt - td — shift back by d. UTC.
METHOD __op_minus__(REFERENCE DateTime other) RETURNS TimeDuration
dt - dt' — the TimeDuration FROM other TO self. Sign
follows the convention later - earlier > 0.
METHOD format(REFERENCE String pattern) RETURNS String
Render this DateTime against pattern, substituting each
recognised token with its zero-padded field value and copying
every other character verbatim.
METHOD hash() RETURNS uint64
FNV-1a 64-bit hash of epochMs, mixed as 8 little-endian bytes. epochMs is the canonical state — two DateTimes with equal epochMs are Equatable-equal and must hash identically.
METHOD clone() RETURNS DateTime
Field copy. Routes through INIT(int64) so the broken-down decomposition runs once on the clone; epochMs is the source of truth, the seven public fields are derived.
DateTimeFactoryFallible DateTime construction surface.
Envzn has no static-method facility and fallible INIT is not a V1
parser surface, so the two DateTime factories that validate their
components and return pipe-XOR (DateTime | STATUS) live on a
dedicated stateless singleton rather than on the DateTime class
itself.
Both delegate range / calendar validation to Calendar.fieldsToEpochMs,
which answers NumericLimits.INT64_MIN for components out of range.
kernel/src/DateTimeFactory.ev:25
Methods
METHOD parseDateTime(REFERENCE String text, REFERENCE String pattern) RETURNS | DateTime
Strict-parse a DateTime from text against a pattern using
the Phase 5 token grammar: YYYY (4-digit year), MM/DD/HH/
mm/ss (2-digit), SSS (3-digit milliseconds). Each token
consumes exactly its width in decimal digits; every other
pattern character must match the next text character exactly.
On any mismatch (width / non-digit / literal mismatch / trailing
text / out-of-range components / invalid calendar date such as
Feb 30), returns FAILURE rather than a partial DateTime.
METHOD newDateTime(int32 year, int32 month, int32 day, int32 hour, int32 minute, int32 second, int32 millisecond) RETURNS | DateTime
Construct a DateTime from explicit year-through-millisecond components. UTC. Pipe-XOR FAILURE on out-of-range per Phase 0 #5: year must lie in [1, 9999] (ISO 8601 range), month in [1, 12], day in [1, 31] (and a day the month has — Feb 30 is a FAILURE), hour in [0, 23], minute in [0, 59], second in [0, 60] (leap-second permissible), millisecond in [0, 999].
TimeDurationIMPLEMENTS Cloneable, Hashable, Equatable
Signed wall-clock duration with millisecond precision.
Storage: canonical int64 totalMs (signed) — single source of truth.
The five broken-down accessor fields (days/hours/minutes/seconds/millis)
are public read-only and decomposed once at construction; for negative
totalMs each carries the same sign as totalMs (mirrors java.time.Duration's
sign convention).
Construction: - CREATE TimeDuration() — zero duration - CREATE TimeDuration(d, h, m, s, ms) — explicit components; the INIT composes totalMs and re-decomposes the fields, so callers reading .days / .hours / ... always see the normalised values (1 day 25 hours → 2 days 1 hour). - CREATE TimeDuration(int64 totalMs) — direct totalMs (used by arithmetic operator results — e.g., DateTime operator -(DateTime)).
Arithmetic / comparison: TimeDuration implements Comparable (and the
parent Equatable), Hashable, Cloneable, plus operator + / operator -
over TimeDuration → TimeDuration and a named negate() (V1 leaves
unary - on classes out of scope per Phase 0 #6 LOCKED).
kernel/src/TimeDuration.ev:43
Fields
int64 daysint64 hoursint64 minutesint64 secondsint64 millisConstructors
INIT()
Zero duration.
INIT(int32 days, int32 hours, int32 minutes, int32 seconds, int32 millis)
Explicit-component constructor. Each parameter contributes
linearly to totalMs (1 day = 86_400_000 ms; 1 hour = 3_600_000 ms;
1 minute = 60_000 ms; 1 second = 1_000 ms; 1 ms = 1 ms). The
broken-down fields below are then derived from totalMs, so
(1 day, 25 hours, 0, 0, 0) yields .days = 2, .hours = 1.
INIT(int64 totalMs)
Direct totalMs constructor. Used by arithmetic-operator results (DateTime->operator-(DateTime), TimeDuration±TimeDuration) where the int64 difference is already known and re-running the component composition would just round-trip.
Methods
METHOD getTotalMs() RETURNS int64
Signed milliseconds — the canonical underlying value.
METHOD __op_plus__(REFERENCE TimeDuration other) RETURNS TimeDuration
td1 + td2 lowering. Returns a new TimeDuration whose totalMs
is the int64 sum; no overflow check (int64 ms range is ~±292M
years, well past anything practical).
METHOD __op_minus__(REFERENCE TimeDuration other) RETURNS TimeDuration
td1 - td2 lowering.
METHOD negate() RETURNS TimeDuration
Named unary negation. Unary - on classes is out of V1 scope
(Phase 0 #6 LOCKED); callers compose td->negate() instead.
METHOD isLessThan(REFERENCE TimeDuration other) RETURNS boolean
Strict less-than on totalMs. Drives derived </<=/>/>=.
METHOD equals(REFERENCE TimeDuration other) RETURNS boolean
Two TimeDurations are equal iff their totalMs match.
METHOD hash() RETURNS uint64
FNV-1a 64-bit hash of totalMs, mixed as 8 little-endian bytes. Mirrors the per-byte mixing String.hash() uses; equal totalMs → equal hash, the Equatable contract.
METHOD clone() RETURNS TimeDuration
Field copy. Routes through INIT(int64) so the decomposition runs once on the clone; totalMs is the source of truth, the public fields are derived.
METHOD format() RETURNS String
ISO-8601 duration text — [-]P[nD]T[nH][nM][nS[.mmm]], millisecond
precision: PT0S for zero, a leading - for a negative duration, and
fractional seconds (PT1.500S) only when there are sub-second millis.
TOTAL — every duration has a text form. The inverse is
DurationText.parse (DurationText.ev); serde carries a TimeDuration
field through this pair (I.P.i).
DurationTextISO-8601 duration PARSE, the inverse of TimeDuration.format.
Reads [-]P[nD]T[nH][nM][nS[.mmm]] (millisecond precision) back into a
TimeDuration. Fallible: a malformed string is a FAILURE, never a silent zero —
which is exactly what serde's reconstruct needs at the untrusted document
boundary (I.P.i). A NAMESPACE (not a method on TimeDuration) because it is a
fallible construction with no receiver, mirroring DateTimeFactory.parseDateTime.
Bounds are checked explicitly before every index (the scan advances by a
variable amount), so the walk never indexes past the end regardless of AND
evaluation order.
kernel/src/DurationText.ev:22
Methods
METHOD parse(REFERENCE String text) RETURNS | TimeDuration
Parse an ISO-8601 duration string into a TimeDuration, or FAILURE.
MeasuringTimerA stack-scoped RAII elapsed-time probe.
Construct one as a local; it captures a monotonic start instant. When it leaves scope its CLEANUP (destructor) reports the elapsed time — so the measured region is simply the local's lexical scope:
{
MeasuringTimer t := CREATE MeasuringTimer("parse phase")
... work to measure ...
} // → prints "parse phase: 1.234 ms"
Read the elapsed value mid-scope with elapsedNanos() / report(), or call silence() to suppress the automatic print (record-only).
Clock: a monotonic, nanosecond-resolution counter (ev_monotonic_nanos, EV_timer_native.hpp) — excludes system sleep, immune to wall-clock adjustments. The right source for timing code regions. (A direct FOREIGN BIND to libc's clock_gettime_nsec_np was rejected by the emitted C++: its clockid_t enum parameter won't implicitly construct from an Envzn uint32, so the one-line extern "C" wrapper takes the enum and exposes int64 nanos — and stays portable.)
kernel/src/MeasuringTimer.ev:37
Fields
int64 startNanosString labelboolean reportOnExitConstructors
INIT(REFERENCE String label)
Start a labelled timer.
INIT()
Start an unlabelled timer (reports under "timer").
Methods
METHOD elapsedNanos() RETURNS int64
Elapsed monotonic nanoseconds since construction.
METHOD report() RETURNS String
Human-readable elapsed time, auto-scaled to ns / us / ms / s, prefixed with the label: e.g. "parse phase: 1.234 ms".
METHOD show() RETURNS void
Print the elapsed-time report line to stdout now. (Kept a normal method, not inlined into CLEANUP: the kernel's header-ordering scanner doesn't walk destructor bodies, so the Stdio dependency must surface from a scanned method to order EV_stdio.hpp ahead of this class.)
MODIFY METHOD silence() RETURNS void
Suppress the automatic CLEANUP print — use elapsedNanos()/report() to read the value yourself.
MODIFY METHOD unsilence() RETURNS void
Re-enable the automatic CLEANUP print.
TimeConstantsThe fixed factors between time units, in one place.
These are not arbitrary tuning numbers — every one is a definition, fixed by
the units themselves and unchanging. They lived as bare literals in
TimeDuration, DurationText and MeasuringTimer, which meant the same
86400000 appeared in two files with nothing connecting them and nothing
saying which unit pair it converted. A reader met mag / 86400000 and had to
count the zeroes to learn it was days.
Sibling of HashConstants and NumericLimits — a namespace whose whole
content is named constants, reached as TimeConstants.MS_PER_DAY.
kernel/src/TimeConstants.ev:23
Fields
int64 MS_PER_SECOND — 1_000 — milliseconds in a second.int64 MS_PER_MINUTE — 60_000 — milliseconds in a minute (60 x MS_PER_SECOND).int64 MS_PER_HOUR — 3_600_000 — milliseconds in an hour (60 x MS_PER_MINUTE).int64 MS_PER_DAY — 86_400_000 — milliseconds in a day (24 x MS_PER_HOUR). A NOMINAL day: this is duration arithmetic, which knows nothing of leap seconds or of the 23- and 25-hour days a DST transition produces. Calendar-aware arithmetic belongs to DateTime, not here.int64 NS_PER_MICROSECOND — 1_000 — nanoseconds in a microsecond.int64 NS_PER_MILLISECOND — 1_000_000 — nanoseconds in a millisecond.int64 NS_PER_SECOND — 1_000_000_000 — nanoseconds in a second.TimeComparisonThree-way comparison result for DateTime->compareTo. Co-exists with Comparable[DateTime]'s isLessThan / equals — both surfaces are intentional per the constitution §28.5 reservation. Comparable derives the ordering operators (<, <=, >, >=); compareTo names the result for callers that want the explicit enum.
kernel/src/enums.ev:183
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
DateTimeFieldsDateTimeFields — the seven UTC calendar fields Calendar.epochMsToFields fills for DateTime's INITs. All int32. Not part of the public DateTime surface — callers read the public fields on the DateTime instance. (ev_time_to_fields, and its C layout was pinned at 28 bytes, Calendar.ev is Envzn now.)
kernel/src/structs.ev:89
Fields
int32 yearint32 monthint32 dayint32 hourint32 minuteint32 secondint32 millisecondThreads, tasks, channels, locks, worker pools and atomics.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
TaskUser-visible handle for a CONCURRENT-spawned task.
────────────────────────────────────────────────────────────────── USER-FACING API ──────────────────────────────────────────────────────────────────
Task is the per-task handle carried as the currentTask reference
inside a CONCURRENT block. User code can only obtain a Task through
the compiler-injected currentTask identifier — Tasks cannot be
stored in fields, assigned to variables, or passed as arguments
(analyzer-enforced; see concurrent_scope_diagnostics.py rules R1–
R5, with R6 rejecting bare CREATE Task(...)).
────────────────────────────────────────────────────────────────── NOT USER-CONSTRUCTIBLE ──────────────────────────────────────────────────────────────────
Task has no public INIT. The only constructor is INTERNAL and is
invoked by the CONCURRENT-block lowering (_ev_task_scope::spawn
in EV_task_native.hpp): one Task per spawned child, installed
as the new OS thread's thread_local _ev_current_task slot before
the body runs and cleared on body exit.
────────────────────────────────────────────────────────────────── CANCELLATION ──────────────────────────────────────────────────────────────────
Cancellation is cooperative (Decision #2, threads-research §6.8).
The enclosing CONCURRENT scope calls task->cancel() (INTERNAL) on
every spawned Task whenever any sibling PANICs or the parent scope
cancels. Body code polls currentTask->isCancelled() in long-
running loops and returns at its own pace. There is no async tear-
down at V1; the _ev_task_scope destructor still joins each spawned
OS thread before unwinding.
────────────────────────────────────────────────────────────────── LIFETIME ──────────────────────────────────────────────────────────────────
The Task instance is heap-allocated by _ev_task_scope::spawn and
lives until the enclosing scope's destructor runs. Task does NOT
own its RawThread — the scope guard does, so the join order is
driven by scope unwinding, not by Task CLEANUP.
kernel/src/Task.ev:62
Constructors
INIT(REFERENCE String name)
Methods
METHOD name() RETURNS String
PUBLIC API
METHOD isCancelled() RETURNS boolean
Returns TRUE once the enclosing CONCURRENT scope has flipped this task's cancellation flag. Body code is expected to call this in any long-running loop and exit cooperatively.
METHOD sleep(int64 millis) RETURNS void
Sleep the calling OS thread for millis milliseconds. Lowers
to FOREIGN::ev_thread_sleep_ms(millis) → POSIX nanosleep in
EV_unsafe_concurrency_native.cpp.
The receiver MUST be the current task: the analyzer rules
against storing/passing Task handles ensure currentTask is
the only reachable receiver. sleep does NOT observe the
cancellation flag — callers that want cancellable sleep check
isCancelled() before and after the call.
FutureEventually-ready cell holding a worker's result.
────────────────────────────────────────────────────────────────── USER-FACING API ──────────────────────────────────────────────────────────────────
Future[T] is the handle returned by WorkerPool[J, R].submit(...)
. The pool spawns a Task that runs the supplied
function on the job; when the function returns, the kernel calls
future->resolve(result). The submitter holds the Future and
reads the result by calling future->await().
────────────────────────────────────────────────────────────────── NOT USER-CONSTRUCTIBLE ──────────────────────────────────────────────────────────────────
Future has no user-callable constructor. The only legitimate
construction site is the kernel: WorkerPool.submit allocates one
Future per submitted job, hands it to the worker Task, and returns
it to the submitter. The analyzer rejects bare CREATE Future[T](...)
in user .ev source (concurrent_scope_diagnostics.py R7, H.2.3
follow-up); the kernel construction path bypasses the analyzer via
emit-time new ENVZN::Future<T>(...) and isn't constrained by R7.
────────────────────────────────────────────────────────────────── CROSS-THREAD SAFETY ──────────────────────────────────────────────────────────────────
Future is one of the kernel-managed exceptions to Envzn's "user code cannot share instances across threads" rule (sibling to Mutex / Channel / MessageBroker). The worker thread mutates the Future via resolve() / fail(); the submitter thread reads via isReady() / await(). All access goes through the internal Mutex, which provides the happens- before ordering, and the partner-locked ThreadCondition handles the blocking wait without busy-polling.
The kernel guarantees exactly one resolve() OR fail() call per Future — the WorkerPool / scope-guard pairs the construction with a single completion path. The Future itself doesn't enforce this; a second resolve() silently overwrites (harmless since notifyAll already fired on the first call). T-aliasing across threads is avoided because resolve() takes T by value (move at the C++ level) and await() returns a fresh clone (see "Value semantics" below).
────────────────────────────────────────────────────────────────── VALUE SEMANTICS ──────────────────────────────────────────────────────────────────
Future[T] retains the resolved value across multiple await() calls.
For class-T, await() returns a .value->clone() so the submitter
thread never aliases the worker's payload. For primitive T (int32
etc.), the := value-copy is sufficient and the WHEN T IMPLEMENTS
Cloneable split picks the ELSE branch automatically.
Per Constitution §12 paragraph 5: a resolved Future retains its
value if the enclosing CONCURRENT scope is later cancelled — only
unresolved Futures resolve to FAILURE("scope cancelled") on
cancellation. The scope guard arranges this by calling fail() only
on Futures whose isResolved field is still FALSE at cancel time.
────────────────────────────────────────────────────────────────── STATUS ──────────────────────────────────────────────────────────────────
Mutex + ThreadCondition substrate via the existing UNSAFE.MUTEX /
UNSAFE.CONDVAR FFI; no new _cxx* reserved types.
kernel/src/Future.ev:86
Constructors
INIT()
Methods
METHOD isReady() RETURNS boolean
PUBLIC API
Non-blocking check. Returns TRUE if the Future has been
resolved (with a value) OR failed (with a STATUS reason);
FALSE while the worker is still in flight. Takes the mutex
briefly to avoid a torn read of .isResolved.
MODIFY METHOD await() RETURNS | T
Blocking await. Returns the resolved value on success; returns a FAILURE STATUS if the worker threw or the enclosing CONCURRENT scope cancelled before resolution.
Pipe-XOR per Constitution §13.1: the caller MATCHes on the
return to dispatch the SUCCESS / FAILURE branches. Spurious
wakeups from pthread are tolerated by the WHILE-not-IF loop
around readyCond->wait().
Multiple await() calls on the same Future are safe — the value is preserved (cloned out for class T, value-copied for primitive T) and subsequent awaits return the same result without re-blocking.
ChannelIMPLEMENTS Shareable
Typed, bounded, point-to-point message channel.
────────────────────────────────────────────────────────────────── USER-FACING API ──────────────────────────────────────────────────────────────────
It is bounded by default — the constructor demands an explicit capacity and a BackpressurePolicy, so "what happens when the consumer falls behind" is a decision the author makes, never a silent unbounded-growth default.
Channel[int32] work := CREATE Channel[int32](4, BackpressurePolicy.BLOCK)
CONCURRENT {
PARALLEL { // producer
work->send(1)
work->send(2)
work->close()
}
PARALLEL { // consumer
WHILE work->receive() DO {
int32 job = $RETURNED
printline((job INTO String))
}
}
}
────────────────────────────────────────────────────────────────── BACKPRESSURE ──────────────────────────────────────────────────────────────────
When the buffer is at capacity, send() consults the policy fixed at construction:
────────────────────────────────────────────────────────────────── CROSS-THREAD SAFETY ──────────────────────────────────────────────────────────────────
Channel[T] is one of the kernel-managed exceptions to Envzn's
"user code cannot share instances across threads" rule (sibling to
Mutex / MessageBroker / Future). Sharing IS the point — a producer task and
a consumer task hold the same Channel and coordinate through it. The
internal Lock serialises every queue mutation and provides the
happens-before ordering; the two partner-locked ThreadConditions
(notEmpty / notFull) handle the blocking waits without busy-polling.
────────────────────────────────────────────────────────────────── CLOSE SEMANTICS ──────────────────────────────────────────────────────────────────
close() is sticky. After close:
- receive() drains any buffered values (still SUCCESS), then returns
FAILURE once empty — so a WHILE ch->receive() DO { … } consumer
loop exits cleanly.
- send() returns FAILURE immediately.
A Channel also closes implicitly when its owning variable goes out of
scope (CLEANUP closes before tearing down the buffer).
────────────────────────────────────────────────────────────────── STATUS ──────────────────────────────────────────────────────────────────
Composes Queue[T] storage + Lock + ThreadCondition substrate. capacity is a count; callers pass a positive value.
kernel/src/Channel.ev:97
Constructors
INIT(int64 capacity, BackpressurePolicy policy)
Methods
MODIFY METHOD send(T value) RETURNS STATUS
PUBLIC API
Enqueue value. Pipe-XOR STATUS. The bare-named (owning) form
consumes the source — the value is moved into the buffer. At
capacity, behaviour follows the BackpressurePolicy. Returns
FAILURE if the channel is closed.
MODIFY METHOD receive() RETURNS | T
Remove and return the front value. Pipe-XOR: SUCCESS populates
value; blocks while the buffer is empty and the channel is
open. Returns FAILURE once the channel is closed AND drained, so
a WHILE ch->receive() DO { … } loop terminates on close.
MODIFY METHOD tryReceive() RETURNS | T
Non-blocking receive. Pipe-XOR: SUCCESS returns the front value if
one is buffered; FAILURE immediately if the buffer is empty (never
blocks). A WHILE ch->tryReceive() DO { … } loop drains whatever
is currently buffered and then exits.
MODIFY METHOD close() RETURNS void
Sticky shutdown. Wakes every blocked sender and receiver so they re-test their predicate and exit. Idempotent.
METHOD shareableKind() RETURNS String
Shareable marker — short type tag for debug printers / logs.
METHOD isClosed() RETURNS boolean
Non-blocking state read. TRUE once close() (or scope-exit CLEANUP) has run.
METHOD size() RETURNS int64
Current buffered count. Snapshot under the lock — advisory only (the value may change the instant the lock is released).
MessageBrokerTyped broadcast pub/sub.
────────────────────────────────────────────────────────────────── USER-FACING API ──────────────────────────────────────────────────────────────────
MessageBroker[T] fans a published value out to every current subscriber.
One MessageBroker per typed message. Each subscriber gets its own buffered
Channel[T], so a slow subscriber is governed by its own
BackpressurePolicy and does not block a fast one.
MessageBroker[Match] broker := CREATE MessageBroker[Match]()
CONCURRENT {
PARALLEL { // a subscriber task
Subscription[Match] sub := broker->subscribe(16, BackpressurePolicy.DROP_OLDEST)
WHILE sub->receive() DO {
Match got := $RETURNED
handle(got)
}
}
PARALLEL { broker->publish(m) } // a publisher task
}
────────────────────────────────────────────────────────────────── OWNERSHIP / LIFETIME ──────────────────────────────────────────────────────────────────
Each subscriber's Channel is co-owned: the MessageBroker holds one strong
(reference-counted) handle in an OwnedList[Channel[T]] (the move-only,
non-Cloneable collection — standard collections reject a non-Cloneable
Channel), and the returned Subscription holds a SHARED MUTABLE
REFERENCE that, because Channel is shared-eligible (§9.1), is a strong
handle too. Unsubscribe is lazy: the Subscription's CLEANUP closes its
channel, and publish skips closed channels. A channel is freed when its
last owner drops — so a Subscription may safely outlive the MessageBroker (it
keeps its channel alive and can still drain it), and the MessageBroker need not
outlive its subscriptions. This is the ARC guarantee that closes the
prior write-after-free.
The MessageBroker is itself shared across tasks by PARALLEL capture (like any
channel/mutex), not by a SHARED MUTABLE REFERENCE field — so it is an
ordinary class, internally synchronized by .lock.
kernel/src/MessageBroker.ev:60
Constructors
INIT()
Methods
MODIFY METHOD publish(REFERENCE T value) RETURNS void
Fan value out to every live subscriber. Each subscriber gets its
own clone (class T) or copy (primitive T); a closed (unsubscribed)
channel is skipped. Walks the owned registry with a MUTABLE
REFERENCE local cursor — ownership grants mutable access, so no
SHARED carve-out is needed on the MessageBroker side.
MODIFY METHOD subscribe(int32 capacity, BackpressurePolicy policy) RETURNS Subscription[T]
Register a new subscriber with its own buffered channel. Returns a scope-bound Subscription holding a SHARED MUTABLE REFERENCE to the channel. The Subscription is created from the channel handle BEFORE the handle is moved into the registry — the heap channel object is not moved by the handle transfer, so the reference stays valid.
SubscriptionA scope-bound handle to a MessageBroker subscription.
Returned by MessageBroker[T].subscribe(...). It holds a SHARED MUTABLE
REFERENCE to its Channel[T] — the carve-out (§9.6) that lets the
subscription drive the channel's MODIFY methods (receive/tryReceive),
sound because Channel is a SHARED CLASS monitor. Because Channel
is shared-eligible (§9.1) the reference is a strong (reference-counted)
handle: the subscription co-owns the channel with the MessageBroker's registry.
Lifecycle: scope-bound. When the subscription's declaring scope ends, CLEANUP closes the channel; the MessageBroker skips closed channels on future publishes (lazy unsubscribe). The channel is freed when its last owner drops — so a subscription may outlive the MessageBroker and still drain its (closed) channel safely; there is no dangling reference.
kernel/src/Subscription.ev:27
Fields
MUTABLE REFERENCE Channel[T] channelRefConstructors
INIT(MUTABLE REFERENCE Channel[T] channel)
Methods
MODIFY METHOD receive() RETURNS | T
Blocking receive of the next published value. Pipe-XOR: SUCCESS yields the value; FAILURE once the channel is closed and drained.
MODIFY METHOD tryReceive() RETURNS | T
Non-blocking receive. Pipe-XOR: SUCCESS if a value is buffered;
FAILURE immediately otherwise. A WHILE sub->tryReceive() DO { … }
loop drains whatever is currently buffered and exits.
Mutexkernel/src/Mutex.ev:80
Fields
T dataConstructors
INIT(REFERENCE T initial)
Methods
MODIFY METHOD acquire() RETURNS void
Block until the lock is acquired. Mirrors Lock.acquire().
Use through SYNCHRONIZED in user code — manual acquire is
the C-mutex anti-pattern (forget release, leak the lock).
MODIFY METHOD release() RETURNS void
Release the lock. Mirrors Lock.release(). Pairs with a
previous acquire() on the same Mutex from the same thread.
MODIFY METHOD tryAcquire() RETURNS boolean
Non-blocking attempt to acquire. Mirrors Lock.tryAcquire().
Returns TRUE if the caller now holds the lock (and is
responsible for calling release() exactly once); FALSE if
another thread currently holds it.
LockKernel mutual-exclusion primitive.
────────────────────────────────────────────────────────────────── PURE SYNCHRONIZATION ──────────────────────────────────────────────────────────────────
Lock is the bare OS-level mutual-exclusion primitive — a thin
Envzn wrapper over UNSAFE.MUTEX + pthread shims. It synchronises
access; it does not bundle protected data. The user-facing
Mutex[T] (see Mutex.ev) composes a Lock with a typed data
field for the "lock + protected state" pattern; kernel-internal
sites that need pure synchronisation (Channel's buffer lock,
Future.value, ThreadCondition partner) hold a Lock directly.
────────────────────────────────────────────────────────────────── USAGE ──────────────────────────────────────────────────────────────────
Use through the SYNCHRONIZED block. The block guarantees the lock is released when control leaves the block — even via RETURN, BREAK, or PANIC from inside:
SYNCHRONIZED .myLock {
// critical section
IF .someCondition THEN {
RETURN // lock still released — guaranteed by block scope
}
.field = newValue
}
The compiler emits an ENVZN::_ev_lock_guard (defined in
EV_unsafe_concurrency_native.hpp) over the Lock's .native
handle; release happens in the guard's destructor on every exit
path.
────────────────────────────────────────────────────────────────── RAW ACQUIRE / RELEASE — narrow uses only ──────────────────────────────────────────────────────────────────
The acquire() / release() / tryAcquire() methods are exposed for the rare cases where the lock-and-unlock paths can't be expressed as a single scope:
Outside those cases: prefer SYNCHRONIZED. Manual acquire/release is the C-mutex anti-pattern (forget release, leak the lock).
kernel/src/Lock.ev:70
Constructors
INIT()
Methods
MODIFY METHOD acquire() RETURNS void
Block until the lock is acquired. Used directly by ThreadCondition (and similar primitives that need explicit acquire/release pairing); everywhere else, prefer the SYNCHRONIZED block which guarantees release on every exit path.
MODIFY METHOD release() RETURNS void
Release the lock. Pairs with a previous acquire() on the same Lock from the same thread. Calling release() without first holding the lock is undefined behaviour at the OS level — pthread does not require the implementation to detect or report this misuse.
MODIFY METHOD tryAcquire() RETURNS boolean
Non-blocking attempt to acquire the lock. Returns TRUE if the caller now holds the lock (and is responsible for calling release() exactly once); FALSE if another thread currently holds it. Useful for optimistic-locking patterns where the caller would rather bail than wait.
WorkerPoolV1 Part H.4.1: a pool of worker threads that run submitted jobs.
────────────────────────────────────────────────────────────────── USER-FACING API ──────────────────────────────────────────────────────────────────
A WorkerPool owns a fixed set of worker threads that drain a shared,
bounded job queue. A job is any TaskStarter — a self-contained unit of
work whose start() runs on a worker thread. Jobs are moved in (the pool
takes ownership), so a job carries its inputs as value fields and reports
results by writing to an output destination it holds — typically a
SHARED MUTABLE REFERENCE Channel[R] the caller owns and drains. The
pool is non-parametric: it is polymorphic over TaskStarter, not
WorkerPool[T].
WorkerPool pool := CREATE WorkerPool(4, 64, BackpressurePolicy.BLOCK)
pool->submit(CREATE RenderJob(tile, resultChannel))
pool->submit(CREATE RenderJob(tile2, resultChannel))
pool->awaitIdle() // block until both jobs have finished
pool->shutdown() // stop the workers (also runs at scope exit)
────────────────────────────────────────────────────────────────── STRUCTURE ──────────────────────────────────────────────────────────────────
The pool owns a WorkerPoolCore (the thread-safe engine + job queue) and
one shared WorkerBody (the drain loop), and spawns N OS threads via
RawThread. Each thread owns its own body, which loops on the shared core.
The threads are OS-detached at spawn; clean shutdown is driven by the
core's live-worker count and exitCond, not by joining std::thread
handles — so the pool keeps no RawThread handles after spawning.
The body holds a SHARED MUTABLE REFERENCE to the core (not to the pool), which is why the engine is a separate owned sub-object: the pool hands out a reference to something it owns, never to itself.
────────────────────────────────────────────────────────────────── V1 SCOPE (DETACHED + LONG_LIVED) ──────────────────────────────────────────────────────────────────
STATUS: V1 Part H.4.1. First real client of RawThread.
kernel/src/WorkerPool.ev:75
Constructors
INIT(int32 workerCount, int32 capacity, BackpressurePolicy policy)
Methods
MODIFY METHOD submit(TaskStarter job) RETURNS STATUS
Enqueue a job for a worker to run. Pipe-XOR STATUS. The bare-named (owning) form consumes the source — the pool takes ownership of the job. At queue capacity, behaviour follows the BackpressurePolicy fixed at construction. Returns FAILURE if the pool has been shut down.
MODIFY METHOD awaitIdle() RETURNS void
Block until the pool is idle — the queue is empty and no job is running. Does not stop the pool; the workers stay alive for more work. Useful as a batch barrier between submit waves.
MODIFY METHOD shutdown() RETURNS void
Sticky shutdown. Queued-but-unstarted jobs still drain; once the queue empties, every worker leaves its loop and this returns. Idempotent — a second call is a no-op.
METHOD size() RETURNS int64
Number of worker threads in this pool.
WorkerPoolCoreIMPLEMENTS Shareable
WorkerPoolCore is the thread-safe heart of a WorkerPool: a bounded,
move-only job queue plus the synchronisation that lets N worker threads
drain it concurrently while submitters hand work in. It is a
SHARED CLASS (monitor) — the carve-out (§9.6) that lets the worker
threads and the submitting thread drive its MODIFY methods through
shared references without owning it.
The public WorkerPool façade owns one WorkerPoolCore and hands a
SHARED MUTABLE REFERENCE to it to the worker bodies. Splitting the
engine out of the façade is what avoids a self-reference: the façade
passes a reference to an owned sub-object (the same idiom Channel uses
to hand its bufferLock to its ThreadConditions), never to itself.
THE JOB QUEUE
Jobs are TaskStarter instances, moved in (never cloned), so the queue
cannot be Channel[T] (which requires T IS Cloneable). It is a
singly-linked chain of WorkerJobNodes behind a head sentinel: submit
appends at the tail, processNext splices off the front (FIFO). Append is
O(n) in queue depth — acceptable for a bounded pool; see the perf note
in WorkerPool.ev.
LIFECYCLE COUNTERS
idleCond fires when count == 0 AND
active == 0 — the signal awaitIdle() waits on.exitCond fires when it hits 0 —
the signal awaitWorkersExit() waits on for clean teardown.STATUS: V1 Part H.4.1. Composes WorkerJobNode storage + Lock + ThreadCondition substrate. DETACHED + LONG_LIVED behaviour.
kernel/src/WorkerPoolCore.ev:49
Constructors
INIT(int32 capacity, BackpressurePolicy policy)
Methods
MODIFY METHOD registerWorker() RETURNS void
Register a worker about to be spawned. Called synchronously from WorkerPool.INIT, once per worker, BEFORE any shutdown can be requested — so liveWorkers is exactly the worker count before the first awaitWorkersExit() can observe it.
MODIFY METHOD workerExited() RETURNS void
A worker has left its drain loop. Decrements liveWorkers and, when the last worker exits, wakes awaitWorkersExit().
MODIFY METHOD submit(TaskStarter job) RETURNS STATUS
Submit a job. Pipe-XOR STATUS. The bare-named (owning) form consumes the source — the job is moved into the queue. At capacity, behaviour follows the BackpressurePolicy. Returns FAILURE if the pool is shut down.
MODIFY METHOD processNext() RETURNS boolean
Run one job, blocking until work is available. Returns TRUE after running a job (the caller should loop and call again); FALSE once the pool is shut down AND the queue is drained (the worker should leave its loop). The job runs OUTSIDE the lock so other workers can dequeue and submit() does not stall behind a long-running job.
MODIFY METHOD beginShutdown() RETURNS void
Begin a sticky shutdown. Wakes every blocked worker and submitter so they re-test their predicate; queued-but-unstarted jobs still drain (workers exit only once the queue is empty). Idempotent.
MODIFY METHOD awaitWorkersExit() RETURNS void
Block until every worker has left its drain loop. Called by WorkerPool teardown after beginShutdown(), so the worker bodies and this core are guaranteed untouched by any thread before they are destroyed.
MODIFY METHOD awaitIdle() RETURNS void
Block until the pool is idle — no queued jobs and none running. Does NOT shut the pool down; the workers stay alive for more work.
METHOD shareableKind() RETURNS String
Shareable marker — short type tag for debug printers / logs.
AtomicBooleanINTERNAL kernel class wrapping a single lock-free atomic boolean.
Storage: UNSAFE.HANDLE native — a heap-allocated _Atomic bool
owned across the FFI boundary. Lock-free on every platform Envzn
supports (bool is the simplest lock-free atomic type).
Surface (all three lock-free patterns): - load() single-step indivisible read - store(v) single-step indivisible write - compareExchange(expected, desired) test-and-set; returns TRUE on successful swap
KERNEL-ONLY (INTERNAL). User code reaches atomics through higher- level patterns (Switchboard, Channel, future Future[T] / Pool / etc.) — never directly.
kernel/src/AtomicBoolean.ev:35
Constructors
INIT(boolean initialValue)
Methods
METHOD load() RETURNS boolean
METHOD store(boolean newValue) RETURNS void
METHOD compareExchange(boolean expected, boolean desired) RETURNS boolean
AtomicBinaryINTERNAL kernel class wrapping a single lock-free atomic octet.
Holds a binary — an opaque octet, NOT a number. AtomicUint8 is the
numeric counterpart; the two are distinct Envzn types over the same
underlying C shim, which is why the C entry points still spell
themselves ev_atomic_byte_*.
kernel/src/AtomicBinary.ev:26
Constructors
INIT(binary initialValue)
Methods
METHOD load() RETURNS binary
METHOD store(binary newValue) RETURNS void
METHOD compareExchange(binary expected, binary desired) RETURNS boolean
AtomicChar8INTERNAL kernel class wrapping a single lock-free atomic char8 (UTF-8 code unit).
FFI signatures use uint8 (E2090 forbids char8 at the C
boundary); the AtomicChar8 method surface uses char8 and the
conversion is a free bit-cast since char8 ≡ uint8 at storage.
kernel/src/AtomicChar8.ev:27
Constructors
INIT(char8 initialValue)
Methods
METHOD load() RETURNS char8
METHOD store(char8 newValue) RETURNS void
METHOD compareExchange(char8 expected, char8 desired) RETURNS boolean
AtomicChar16INTERNAL kernel class wrapping a single lock-free atomic char16 (UTF-16 code unit).
FFI signatures use uint16 (E2090 forbids char16 at the C
boundary); the AtomicChar16 method surface uses char16 and the
conversion is a free bit-cast since char16 ≡ uint16 at storage.
kernel/src/AtomicChar16.ev:27
Constructors
INIT(char16 initialValue)
Methods
METHOD load() RETURNS char16
METHOD store(char16 newValue) RETURNS void
METHOD compareExchange(char16 expected, char16 desired) RETURNS boolean
AtomicChar32INTERNAL kernel class wrapping a single lock-free atomic char32 (UTF-32 code point).
FFI signatures use uint32 (E2090 forbids char32 at the C
boundary); the AtomicChar32 method surface uses char32 and the
conversion is a free bit-cast since char32 ≡ uint32 at storage.
kernel/src/AtomicChar32.ev:27
Constructors
INIT(char32 initialValue)
Methods
METHOD load() RETURNS char32
METHOD store(char32 newValue) RETURNS void
METHOD compareExchange(char32 expected, char32 desired) RETURNS boolean
AtomicInt8kernel/src/AtomicInt8.ev:21
Constructors
INIT(int8 initialValue)
Methods
METHOD load() RETURNS int8
METHOD store(int8 newValue) RETURNS void
METHOD compareExchange(int8 expected, int8 desired) RETURNS boolean
AtomicInt16kernel/src/AtomicInt16.ev:21
Constructors
INIT(int16 initialValue)
Methods
METHOD load() RETURNS int16
METHOD store(int16 newValue) RETURNS void
METHOD compareExchange(int16 expected, int16 desired) RETURNS boolean
AtomicInt32kernel/src/AtomicInt32.ev:21
Constructors
INIT(int32 initialValue)
Methods
METHOD load() RETURNS int32
METHOD store(int32 newValue) RETURNS void
METHOD compareExchange(int32 expected, int32 desired) RETURNS boolean
AtomicInt64kernel/src/AtomicInt64.ev:21
Constructors
INIT(int64 initialValue)
Methods
METHOD load() RETURNS int64
METHOD store(int64 newValue) RETURNS void
METHOD compareExchange(int64 expected, int64 desired) RETURNS boolean
AtomicUint8INTERNAL kernel class wrapping a single lock-free atomic uint8.
The NUMERIC octet. AtomicBinary is the opaque-octet counterpart; the two are distinct Envzn types over the same underlying C shim.
kernel/src/AtomicUint8.ev:25
Constructors
INIT(uint8 initialValue)
Methods
METHOD load() RETURNS uint8
METHOD store(uint8 newValue) RETURNS void
METHOD compareExchange(uint8 expected, uint8 desired) RETURNS boolean
AtomicUint16kernel/src/AtomicUint16.ev:21
Constructors
INIT(uint16 initialValue)
Methods
METHOD load() RETURNS uint16
METHOD store(uint16 newValue) RETURNS void
METHOD compareExchange(uint16 expected, uint16 desired) RETURNS boolean
AtomicUint32INTERNAL kernel class wrapping a single lock-free atomic uint32.
Shares the C ev_atomic_u32_* machinery with AtomicChar (char ≡
uint32 code point) — separate Envzn types, same underlying C shim.
kernel/src/AtomicUint32.ev:25
Constructors
INIT(uint32 initialValue)
Methods
METHOD load() RETURNS uint32
METHOD store(uint32 newValue) RETURNS void
METHOD compareExchange(uint32 expected, uint32 desired) RETURNS boolean
AtomicUint64kernel/src/AtomicUint64.ev:21
Constructors
INIT(uint64 initialValue)
Methods
METHOD load() RETURNS uint64
METHOD store(uint64 newValue) RETURNS void
METHOD compareExchange(uint64 expected, uint64 desired) RETURNS boolean
Concurrencykernel/src/interfaces.ev:171
ShareableShareable — the marker interface for a SHARED CLASS monitor: an
interior-mutable, self-synchronizing object that may be aliased by
reference across concurrent tasks. Per Constitution §771, a
SHARED CLASS MUST IMPLEMENTS Shareable (omitting it is E2115),
and Shareable is the marker that admits a type into the two places
the borrow model otherwise forbids aliasing:
- a SHARED MUTABLE REFERENCE field (§9.6), and
- the move-only OwnedList[T] collection (owned and moved, never
cloned — so it needs no Cloneable bound; Shareable is the
explicit constraint atom that admits the non-Cloneable monitor).
The kernel's SHARED CLASS monitors are Channel[T] (the canonical
one) and WorkerPoolCore. These are the only kernel types that
implement Shareable, and the only element type used in an
OwnedList is Channel (the MessageBroker's subscriber registry).
NOT Shareable — the other concurrency types are ordinary classes,
not monitors, and deliberately do NOT implement this marker:
- MessageBroker / Mutex — shared across tasks by PARALLEL capture
plus an internal Lock, not by a SHARED MUTABLE REFERENCE
field, so they need no carve-out.
- Subscription — a scope-bound handle that merely HOLDS a
SHARED MUTABLE REFERENCE Channel; it rides on Channel's
shareability rather than being a monitor itself.
- Future — an ordinary result cell, not aliased mutably.
A type opts in via IMPLEMENTS Shareable. Envzn forbids empty
interfaces (E6001), so the marker carries one descriptive method —
shareableKind() returns a short human-readable tag for the
concrete type (used by debug printers / kernel logs). OwnedList itself never
calls it; the interface exists for the type-bound.
kernel/src/interfaces.ev:242
Methods
METHOD shareableKind() RETURNS String
TaskStarterTaskStarter — body interface for spawnable threads.
A class that IMPLEMENTS TaskStarter can be passed to
CREATE Thread(...). When the user calls Thread.start() (the outer
kickoff), the runtime spawns an OS thread, sets up that thread's
Channel and current-thread accessors, and then invokes
body->start() (this interface's method) on the new thread. The
dev never calls TaskStarter.start() directly — the symmetric
naming mirrors CREATE → INIT.
Example:
CLASS Worker IMPLEMENTS TaskStarter { PRIVATE int32 jobId INIT(int32 jobId) { .jobId = jobId } METHOD start() RETURNS STATUS { Channel->current()->subscribe("jobs") // ... body runs on the spawned OS thread ... RETURN (SUCCESS) } }
Thread t := CREATE Thread("worker", CREATE Worker(42)) t->start() // outer kickoff — runtime calls Worker.start() inside
V1 ban: CREATE Thread(LAMBDA { ... }) is a parse error; thread bodies must be a TaskStarter class. V2 will add the LAMBDA shortcut as a strict superset (move-semantic captures only, REFERENCE captures rejected); existing V1 TaskStarter code continues to work unchanged.
kernel/src/interfaces.ev:792
Methods
METHOD start() RETURNS STATUS
TaskStarterOptionsTaskStarterOptions — the options class of a program that takes arguments
. The developer
declares plain fields, blittable or String, and sets their defaults in
INIT; the compiler writes all three methods from those fields and the
manifest's entrypoint.options block, and the developer never writes or
calls them. EntryOptions[T].fill calls describe and load; the program
calls forwarded when it hands options on to another program.
kernel/src/interfaces.ev:804
Methods
METHOD describe(MUTABLE REFERENCE CommandLineArguments args) RETURNS void
Declare one option per field to args, with the manifest's help, alias,
required and positional settings and INIT's value as the default.
MODIFY METHOD load(REFERENCE CommandLineArguments args) RETURNS STATUS
Copy each parsed value into its field. FAILURE when a value breaks a rule the field's type carries (an enum's case names), which is a usage error.
METHOD forwarded(REFERENCE String destination) RETURNS String[]
The command-line words to hand to destination: every option the manifest
marks "forward": destination that the user gave, as given, then the words
after -- when "after-double-dash" names it (§3a). Empty otherwise.
TaskStarterWithOptionsTaskStarterWithOptions — the entry of a program that takes arguments: the
runtime fills a T from the command line and passes it to start. A
program that takes none implements the plain TaskStarter.
kernel/src/interfaces.ev:824
Methods
METHOD start(REFERENCE T options) RETURNS STATUS
BackpressurePolicyBackpressurePolicy — what a Channel[T] / MessageBroker[T] subscriber does when its bounded buffer is full at send/publish time. V1 Part H (ENVZN_CONSTITUTION.md §12). The Channel constructor and the MessageBroker.subscribe call both take an explicit policy; there is no default — every site declares its choice so the failure mode is visible.
kernel/src/enums.ev:152
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
The runtime and the outside world: processes, files, paths and standard I/O, plus the codecs, the conversions between types, and randomness.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
SystemThe running program's own services: its environment, its exit, where its
executable lives (programPath), and the process-level runtime around them.
System is a singleton — code calls System->getenv(name), System->exit(code)
— and is not the entry point. A program's entry class implements one of two
interfaces, and the manifest's entrypoint key names it (Constitution I.N):
CLASS Hello IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
Stdio->printline("Hello, world!")
RETURN (SUCCESS)
}
}
or, for a program that takes arguments, TaskStarterWithOptions OF T, whose
start(REFERENCE T options) receives the command line already parsed into the
fields of T, as the manifest's entrypoint.options block describes them. The
entry class declares no INIT; the compiler generates the main() that creates
it, fills the options, and maps the returned STATUS to the exit code.
kernel/src/System.ev:67
Methods
METHOD getenv(REFERENCE String key) RETURNS | String
Look up an environment variable. Pipe-XOR: SUCCESS populates
value with the variable's value (empty String if set to the
empty value); FAILURE if the variable is unset.
METHOD programPath() RETURNS | String
The running program's own executable, as the absolute, symlink-free path the operating system reports. Not argv[0]: a shell passes whatever the user typed, often a bare name found on PATH. FAILURE when the system cannot say.
METHOD exit(int32 code) RETURNS void
Exit the process immediately with the given code. Does NOT
return. CLEANUP on stack frames is skipped — call only when
the program genuinely cannot continue. For normal termination,
RETURN from start() instead and let the entry-point shim
propagate the exit code.
METHOD cloneCount() RETURNS int64
Deep copies performed so far. See the note above on enabling.
METHOD resetCloneCount() RETURNS void
Zero the counter, so a test can bracket one sequence.
METHOD memoryCompare(REFERENCE binary[] a, int64 aOff, REFERENCE binary[] b, int64 bOff, int64 n) RETURNS int32
Lexicographic byte comparison of the n-byte run a[aOff .. aOff+n)
against b[bOff .. bOff+n). Returns a negative int32 when the first
differing byte is smaller in a, positive when larger, and 0 when the
two runs are byte-equal — the std::memcmp result contract, so one
primitive serves both equality (== 0) and ordering. Each offset+run
is bounds-checked once against its array's length.
METHOD memoryCopy(MUTABLE REFERENCE binary[] dst, int64 dstOff, REFERENCE binary[] src, int64 srcOff, int64 n) RETURNS void
Copy the n-byte run src[srcOff .. srcOff+n) into dst[dstOff ..
dstOff+n) in place. PRECONDITION: both ranges are live — dstOff+n
must not exceed dst.length (this is an in-place copy into existing
slots, never a growing append) and srcOff+n must not exceed
src.length; the compiler enforces both with one bounds check per run
(IndexOutOfBoundsError on violation). The source and destination runs
must not overlap. The compiler lowers each call site to one std::memcpy.
METHOD memoryWord(REFERENCE binary[] a, int64 off) RETURNS uint64
Read the 8 consecutive bytes a[off .. off+8) as one uint64 — a WIDE
load, for word-wise hashing/scanning that processes eight bytes per
operation instead of one. PRECONDITION: off+8 must not exceed
a.length (the compiler checks it once and raises IndexOutOfBoundsError
otherwise). The compiler lowers each call site to a single native-endian
8-byte load; this body is the readable little-endian spec, which
coincides with the load on the little-endian V1 targets. Byte order is an
internal detail — a word-wise hash only needs the same bytes to map to
the same word, which both forms guarantee.
StdioThe console: standard output, standard error, standard input. stdio-spec.md §2.
Stdio is a singleton. Twelve methods in three groups:
stdout — print · printline · formatPrint · formatPrintline · printBytes
stderr — the same five, each with an Err suffix
stdin — read(int32 length) · readline()
print writes its text verbatim; printline appends a newline.
The formatPrint* pair render a $1..$9 template (stdio-spec.md
§4) before writing. printBytes* write raw bytes with no formatting.
Writes return the pipe-XOR shape (int64 written | STATUS status) —
written is the byte count. Reads return the comma shape
(value, boolean atEof) — both slots are always populated, so an
end-of-input read still delivers the bytes it managed to read.
The I/O layer is pure Envzn: write / read are bound directly
from libc via FOREIGN BIND (no inline C++). <unistd.h> is listed
in the ENVZN manifest's foreign block. A ByteBuffer argument
crosses the boundary as a (pointer, length) pair (bind-spec §4); the
C side of read writes through it.
V1 scope: a write is a single write(2) call (a rare short write
under-reports the count, never corrupts); read / readline go
one byte at a time, and a line ends at \n (0x0A). Buffered I/O,
the full splitLines delimiter set, and EPIPE→FAILURE are V2.
kernel/src/Stdio.ev:50
Methods
METHOD print(REFERENCE String text) RETURNS | int64
Write text to stdout verbatim — no trailing newline.
METHOD printline(REFERENCE String text) RETURNS | int64
Write text to stdout followed by a newline.
METHOD formatPrint(REFERENCE String tmpl, FormatArgument args...) RETURNS | int64
Render tmpl against args (stdio-spec.md §4) and write the
result to stdout — no trailing newline.
METHOD formatPrintline(REFERENCE String tmpl, FormatArgument args...) RETURNS | int64
Render tmpl against args and write the result to stdout
followed by a newline.
METHOD printBytes(REFERENCE ByteBuffer data) RETURNS | int64
Write the raw bytes of data to stdout — no formatting.
METHOD printErr(REFERENCE String text) RETURNS | int64
Write text to stderr verbatim — no trailing newline.
METHOD printlineErr(REFERENCE String text) RETURNS | int64
Write text to stderr followed by a newline.
METHOD formatPrintErr(REFERENCE String tmpl, FormatArgument args...) RETURNS | int64
Render tmpl against args and write the result to stderr.
METHOD formatPrintlineErr(REFERENCE String tmpl, FormatArgument args...) RETURNS | int64
Render tmpl against args and write the result to stderr
followed by a newline.
METHOD printBytesErr(REFERENCE ByteBuffer data) RETURNS | int64
Write the raw bytes of data to stderr — no formatting.
METHOD read(int32 length) RETURNS ByteBuffer
Read from stdin. length > 0 reads up to that many bytes;
length == 0 reads one line, the \n delimiter included.
Comma shape: loaded always holds what was read; atEof is
TRUE when end-of-input was reached before the request was met.
METHOD readline() RETURNS String
Read one line from stdin, the trailing \n stripped. Comma
shape: at end-of-input line is empty and atEof is TRUE,
distinguishing EOF from a genuine blank line.
CommandLineArgumentsDeclare, parse and read a program's command-line arguments.
The input-side counterpart of Formatter: where format turns values into
text on the way out, CommandLineArguments turns the argv a program was
launched with into typed, validated values on the way in. It is the standard
way to read arguments, so no program has to hand-roll its own loop. A program
whose entry implements TaskStarterWithOptions never calls it directly: the
compiler declares its options from the options class and the manifest, and
EntryOptions[T] parses.
A program declares what it accepts, parses once, then reads typed values:
CommandLineArguments args := CREATE CommandLineArguments(argv)
args->addFlag("verbose", "v", "print each step")
args->addIntegerOption("jobs", "j", 1, "how many builds to run at once")
args->addTextOption("output", "o", "", "where to write the result")
args->require("output")
args->addPositional("input", "the file to read")
IF args->parse() THEN { ... read the values ... } ELSE { ... print $! and args->usage() ... }
IF args->helpRequested() THEN { Stdio->printline(args->usage()) ... }
int64 jobs = args->integerValue("jobs")
String input := args->positional("input")
Accepted spellings: --name value, --name=value, -n value (a declared
short name), a bare flag --verbose / -v, and --, after which every word
is positional (or, with collectAfterDoubleDash, kept apart untouched).
--help and -h are reserved: they set helpRequested().
COMMANDS (git-style: epm build --all a b). addCommand(word, help) declares a
command; forCommand(word) makes the declarations that follow belong to it;
declarations made before any forCommand are global. Then:
* the first bare word chooses the command; an undeclared word is a FAILURE;
* global options are accepted anywhere, a command's only after its word, and
an option of another command is a FAILURE that names where it belongs;
* positionals, remaining words and required options are the chosen command's
(a program with commands declares no global positionals);
* every read looks in the chosen command first, then the globals, so one
name may belong to several commands;
* usage() lists the commands when none was chosen, else that command's.
Rules:
* Required positionals are filled first, in declaration order, then the
optional ones (addOptionalPositional); any further word goes to
remaining() if addRemainingPositionals was declared, and is
otherwise a parse FAILURE, as is an undeclared option.
* parse() returns (boolean ok | STATUS s): consume it as an IF condition and read the failure message as $!.
* An option's value is checked against its kind at parse(): --jobs abc
fails there, so the typed getters never have to.
* Reading a name that was never declared is a programmer error, not a
runtime condition, and halts with UNREACHABLE!.
Storage is index-aligned parallel arrays rather than an option record: one
slot per declared option in names, shortNames, helps, kinds, scopes,
required, seen, texts, defaults, integers and floats, and one per
declared positional in the positional* arrays. A scope is a command's index,
or GLOBAL.
kernel/src/CommandLineArguments.ev:68
Constructors
INIT(REFERENCE String[] argv)
argv exactly as the program received it: argv[0] is the program
itself (used in usage()), the rest are the words to parse.
Methods
MODIFY METHOD addFlag(REFERENCE String name, REFERENCE String shortName, REFERENCE String help) RETURNS void
A switch that is either present or absent: --verbose / -v.
shortName is one letter, or "" for none.
MODIFY METHOD addTextOption(REFERENCE String name, REFERENCE String shortName, REFERENCE String defaultValue, REFERENCE String help) RETURNS void
An option carrying text: --output out.csv.
MODIFY METHOD addIntegerOption(REFERENCE String name, REFERENCE String shortName, int64 defaultValue, REFERENCE String help) RETURNS void
An option carrying a whole number: --jobs 8.
MODIFY METHOD addFloatOption(REFERENCE String name, REFERENCE String shortName, float64 defaultValue, REFERENCE String help) RETURNS void
An option carrying a floating-point number: --rate 0.25.
MODIFY METHOD require(REFERENCE String name) RETURNS void
Make a declared option mandatory: parse() fails if it is absent. With
commands, the option of the scope being declared.
MODIFY METHOD addPositional(REFERENCE String name, REFERENCE String help) RETURNS void
A required word that is not an option, filled in declaration order.
MODIFY METHOD addOptionalPositional(REFERENCE String name, REFERENCE String help) RETURNS void
A word that may be absent, filled after every required positional.
positional(name) returns "" when it was not given.
MODIFY METHOD addRemainingPositionals(REFERENCE String name, REFERENCE String help) RETURNS void
Zero or more trailing words, collected by remaining(). At most one
declaration per scope, and only after every other positional of it.
MODIFY METHOD addCommand(REFERENCE String name, REFERENCE String help) RETURNS void
A command word: epm build. The first bare word on the command line
chooses one; every word after it is read against that command.
MODIFY METHOD forCommand(REFERENCE String name) RETURNS void
Make the declarations that follow belong to the command name.
MODIFY METHOD forAllCommands() RETURNS void
Make the declarations that follow global again.
MODIFY METHOD collectAfterDoubleDash() RETURNS void
Keep every word after -- apart and untouched, for afterDoubleDash(),
instead of reading them as positionals. A program that hands those words on
to another program asks for this (program-entry design §3a); without it,
-- keeps its standard meaning: everything after it is positional.
MODIFY METHOD parse() RETURNS | boolean
Read every word against the declarations. TRUE when every value is
present and has the right kind; FAILURE's message ($!) names the first problem.
After --help, parsing succeeds without enforcing required values.
METHOD command() RETURNS String
The command word the command line chose; "" when the program has no
commands, or none was given (only possible after --help).
METHOD afterDoubleDash() RETURNS String[]
The words after --, untouched, when collectAfterDoubleDash was asked for.
METHOD spelledAsGiven(REFERENCE String[] names) RETURNS String[]
The options among names that the user actually gave, as command-line words
in the order given: each by its long name (-q is written --quiet), then its
value unless it is a flag. An option left at its default is not spelled, so a
program forwarding these never passes on a default as if it had been asked for.
METHOD helpRequested() RETURNS boolean
TRUE if --help or -h was given.
METHOD isSet(REFERENCE String name) RETURNS boolean
TRUE if the flag or option appeared on the command line.
METHOD textValue(REFERENCE String name) RETURNS String
The option's text: what was given, or its default.
METHOD integerValue(REFERENCE String name) RETURNS int64
An integer option's value: what was given, or its default.
METHOD floatValue(REFERENCE String name) RETURNS float64
A float option's value: what was given, or its default.
METHOD positional(REFERENCE String name) RETURNS String
A positional argument's word, by its declared name; "" for an optional one that was not given, or one of a command that was not chosen.
METHOD remaining() RETURNS String[]
The words collected by addRemainingPositionals, in order; empty if none
were given, or they belong to a command that was not chosen.
METHOD usage() RETURNS String
The help text, generated from the declarations so it cannot drift from them. A program with commands gets the list of commands until one is chosen, then that command's own usage.
ProcessProcess — kernel singleton for synchronous shell-out.
Stateless; never instantiated by user code. Always accessed
via Process->run(...).
kernel/src/Process.ev:50
Methods
METHOD run(REFERENCE String command, REFERENCE String[] args) RETURNS ProcessResult
Run command with args, capturing stdout, stderr, and
the exit code into a ProcessResult.
Blocks until the child process exits. PATH lookup follows
the standard execvp rules — passing a bare program name
(e.g. "tar") searches $PATH; an absolute or
directory-relative path (e.g. "/bin/sh", "./build") is
used directly.
Failure surfaces as exitCode == -1 (signal-killed); a
pipe() / fork() / waitpid() failure PANICs an Error.
execvp failure inside the child writes "execvp failed:
..." to stderr and exits with code 127.
METHOD id() RETURNS int32
The ID of the running process — unique among the processes alive at the same moment, so it names a temporary file two concurrent runs of the same program will not share (epm's staging does exactly this). Not unique over time: the operating system reuses an ID once its process has exited.
FileIMPLEMENTS Readable, Writable
Full file-interaction class over the POSIX byte-I/O surface.
Pure Envzn making C system calls (no C++ shim). Two fd lifecycle modes on
ONE class via an optional fd field:
• Persistent — open() (or a named opener) stores the fd; subsequent reads/writes/append/seek reuse it; close() releases it (CLEANUP closes any still-open fd on scope exit). • Per-operation — never call open(): the convenience methods open their own fd, do the op, and close. They are ADAPTIVE: if a persistent fd is open they use it, otherwise they open-and-close.
Thread safety: a per-File Lock (gate) guards the shared OS fd offset in
persistent mode via raw acquire/release around the critical section
(SYNCHRONIZED cannot be used inside pipe-shaped methods — E6051). Positioned
I/O (readAt/writeAt → pread/pwrite) is offset-stable and needs no lock.
Failure model: open and every File-UNIQUE syscall carry SETS_ERRNO(-1), so
failures return a STATUS with the real strerror message + errno code.
read/write are co-bound (identically) in Stdio.ev, so they keep the plain
signature — their errors are detected by the (<0) return.
Pipe-XOR idioms (kernel-first use of SETS_ERRNO): a pipe-shaped
(X | STATUS status) method returns via the NAMED slot (status = FAILURE(…)
RETURN (status); slot = local RETURN (slot)), binds $RETURNED to a LOCAL
in the THEN arm (never slot = $RETURNED), and uses $!/$# only inside the
ELSE arm.
Text I/O is UTF-8: String is the decoded char32 form; bytes on disk are UTF-8, transcoded at the boundary via TextConverter (String↔ByteBuffer). Byte I/O is binary[] (Readable/Writable contract).
kernel/src/File.ev:85
Fields
String pathint32 fdLock gateConstructors
INIT(REFERENCE String path)
Methods
MODIFY METHOD openRead() RETURNS STATUS
Open read-only (O_RDONLY).
MODIFY METHOD openWrite() RETURNS STATUS
Open for writing, creating + truncating (O_WRONLY|O_CREAT|O_TRUNC, 0644).
MODIFY METHOD openAppend() RETURNS STATUS
Open for appending, creating if absent (O_WRONLY|O_CREAT|O_APPEND, 0644).
MODIFY METHOD openReadWrite() RETURNS STATUS
Open for reading + writing, creating if absent (O_RDWR|O_CREAT, 0644).
MODIFY METHOD openExclusive() RETURNS STATUS
Open exclusively — fails if the file exists (O_WRONLY|O_CREAT|O_EXCL).
METHOD isOpen() RETURNS boolean
TRUE while a persistent fd is open.
MODIFY METHOD close() RETURNS STATUS
Close the persistent fd (no-op if not open).
MODIFY METHOD read() RETURNS | binary[]
Read the entire file's bytes (Readable). Adaptive: persistent fd (gate-guarded) if open, else opens O_RDONLY, drains, closes.
MODIFY METHOD write(REFERENCE binary[] content) RETURNS | int64
Write every byte of content, replacing contents (Writable). Adaptive.
The extent is content.length — see the Writable contract.
MODIFY METHOD appendBytes(REFERENCE binary[] content) RETURNS | int64
Append length bytes to the end (creating if absent). Adaptive.
METHOD readAt(int64 offset, int32 max) RETURNS | binary[]
Read up to max bytes at absolute offset (pread). Persistent fd.
MODIFY METHOD writeAt(int64 offset, REFERENCE binary[] content) RETURNS | int64
Write length bytes at absolute offset (pwrite). Persistent fd.
MODIFY METHOD readText() RETURNS | String
Read the whole file as UTF-8 text. Invalid UTF-8 → FAILURE.
MODIFY METHOD writeText(REFERENCE String content) RETURNS STATUS
Write content as UTF-8 text, replacing the file's contents.
MODIFY METHOD appendText(REFERENCE String content) RETURNS STATUS
Append content as UTF-8 text to the end of the file.
MODIFY METHOD seekFromStart(int64 offset) RETURNS | int64
Move the cursor to offset bytes from the START of the file.
Returns the resulting absolute position.
MODIFY METHOD seekFromCurrent(int64 offset) RETURNS | int64
Move the cursor offset bytes from where it currently sits — negative
moves backward. Returns the resulting absolute position.
MODIFY METHOD seekFromEnd(int64 offset) RETURNS | int64
Move the cursor offset bytes from the END of the file — 0 is the end
itself and negative moves back into the content. Returns the resulting
absolute position. (A POSITIVE offset here is legal and seeks PAST the
end; writing there creates a hole. That is lseek's behaviour and this
wrapper does not change it.)
MODIFY METHOD tell() RETURNS | int64
Current cursor position (lseek SEEK_CUR, no move).
MODIFY METHOD size() RETURNS | int64
File size in bytes — seek to end then restore the cursor (no stat). Nested so no top-level statement follows a pipe consume.
MODIFY METHOD truncateTo(int64 length) RETURNS STATUS
Truncate (or extend) the file to length bytes (ftruncate).
MODIFY METHOD flush() RETURNS STATUS
Flush buffered writes to disk (fsync).
MODIFY METHOD lockExclusive(boolean blocking) RETURNS STATUS
Acquire an exclusive advisory lock. blocking FALSE → non-blocking.
MODIFY METHOD lockShared(boolean blocking) RETURNS STATUS
Acquire a shared advisory lock.
MODIFY METHOD unlockFile() RETURNS STATUS
Release any advisory lock held on the file (LOCK_UN).
METHOD exists() RETURNS boolean
TRUE if the path exists (access F_OK).
METHOD isReadable() RETURNS boolean
TRUE if readable by the caller (access R_OK).
METHOD isWritable() RETURNS boolean
TRUE if writable by the caller (access W_OK).
METHOD isExecutable() RETURNS boolean
TRUE if executable by the caller (access X_OK).
MODIFY METHOD deleteFile() RETURNS STATUS
Delete the file (unlink). Named deleteFile — delete is a C++ keyword.
MODIFY METHOD renameTo(REFERENCE String dest) RETURNS STATUS
Rename / move the file to dest (rename).
MODIFY METHOD setPermissions(int32 mode) RETURNS STATUS
Change the file's permission bits (chmod); mode is an octal value.
PathIMPLEMENTS Cloneable, Comparable
Instance class wrapping a filesystem path with rich operations.
Path is the comprehensive filesystem-path API in the kernel. Where File (File.ev) is minimal — just a path String + read/write — Path layers existence checks, directory operations, manipulation (parent, basename, stem, extension, join, withExtension, resolve), and tree traversal (listFiles, makeDir, remove).
Internally a Path is a value-type wrapper around a String. Path instances are cheap to construct and hand around; they don't hold OS resources beyond the String itself.
The filesystem-touching methods (exists / isDirectory / isFile / resolve / listFiles / makeDir / remove) are backed by the C natives in EV_fs_native.c via FOREIGN BIND. The manipulation methods (parent / basename / stem / extension / join / withExtension / toString) are pure Envzn — they never touch the filesystem.
────────────────────────────────────────────────────────────────── ERROR HANDLING ──────────────────────────────────────────────────────────────────
FAILURE STATUS in the method's multi-return — never PANIC. Per
the kernel-wide error-handling convention, callers inspect the
STATUS slot (IF p->resolve() THEN { ... $RETURNED ... } ELSE { ... $! }).kernel/src/Path.ev:69
Fields
String valueConstructors
INIT(REFERENCE String value)
Methods
METHOD clone() RETURNS Cloneable
METHOD exists() RETURNS boolean
EXISTENCE CHECKS — never fail TRUE iff something exists at this path (file, directory, or other).
METHOD isDirectory() RETURNS boolean
TRUE iff this path exists and is a directory.
METHOD isFile() RETURNS boolean
TRUE iff this path exists and is a regular file.
METHOD parent() RETURNS Path
PURE-ENVZN PATH MANIPULATION
The six methods below — parent / basename / stem / extension /
withExtension / join — perform byte-level string manipulation
around the / separator. The filesystem is never touched, so
they are pure Envzn: cross-platform-consistent semantics
(forward-slash only), demagic-plan-aligned scrutability, and one
fewer dependency for the future LLVM-IR self-host.
Paths are treated as code-point strings: / is 0x2F and . is
0x2E (both ASCII, one code point each). Multi-byte codepoints
inside path segments pass through unchanged.
Returns the parent directory. For "/a/b/c" returns "/a/b".
For "/a/b/c/" returns "/a/b/c" (the trailing slash makes the
filename empty). For a relative single-segment path ("a"),
returns the empty path. For "/" returns "/" (root's own
parent — fixed point).
METHOD basename() RETURNS String
Filename including extension. For "/a/b/file.txt" returns "file.txt". For a path ending in "/" returns the empty String.
METHOD stem() RETURNS String
Filename without extension. For "/a/b/file.txt" returns "file". For "file.tar.gz" returns "file.tar" (only the last extension is stripped). For dotfiles like ".bashrc" returns ".bashrc" (no leading-dot extension stripped).
METHOD extension() RETURNS String
The file's extension including the leading dot. For "file.txt" returns ".txt". For an extensionless filename returns the empty String. For a leading-dot dotfile (".bashrc") returns the empty String — the leading dot is part of the stem, not an extension.
METHOD withExtension(REFERENCE String ext) RETURNS Path
Returns a new Path with the extension replaced. ext may
include or omit the leading dot. For withExtension(".cpp")
on "file.txt" returns Path "file.cpp". For withExtension("")
strips the extension entirely (returning the stem-form path).
METHOD join(REFERENCE String segment) RETURNS Path
Append segment as a child path component. The result is
value + "/" + segment, normalised so a trailing slash on
value or a leading slash on segment doesn't produce a
double "//". If segment is absolute (starts with '/') it
replaces value entirely — matches std::filesystem::path's
operator/ semantics.
METHOD resolve() RETURNS | Path
Resolve the path: if relative, prepend CWD; resolve any symbolic links; canonicalise '.' and '..' segments. Canonical resolution requires existence, so a missing path is FAILURE. Pipe-XOR: SUCCESS populates the resolved Path; FAILURE the STATUS.
METHOD listFiles() RETURNS | Array[Path]
DIRECTORY OPERATIONS — STATUS multi-return on failure
List the immediate children of this directory as Paths. Each
child is this joined with the entry's filename (forward-slash
semantics via join()). FAILURE if this path is not an existing
directory. An empty directory yields an empty Array (SUCCESS).
METHOD makeDir() RETURNS STATUS
Create the directory (and any missing parents). No-op if it already exists. FAILURE when something that is not a directory is in the way, on a permission error, and for the empty path.
The walk over the parents is here; C makes one directory at a time
(ev_fs_make_dir). parent() is strictly shorter than its path for
every path but "/", which is always a directory, so the recursion
ends; a relative path's walk ends at "", whose parent is the current
directory and needs no making.
METHOD remove() RETURNS STATUS
Remove the file or directory tree. FAILURE on permission error or unreachable entries during traversal.
METHOD readText() RETURNS String
I/O — delegates to File
Convenience wrappers — for callers that already have a Path, it's natural to read/write directly without constructing a separate File instance. These are equivalent to: File f := CREATE File(.value); f->readText() / writeText
METHOD writeText(REFERENCE String content) RETURNS STATUS
METHOD modifiedAt() RETURNS | int64
Last modification time, in NANOSECONDS since the Unix epoch. FAILURE when the path cannot be stat'd — it does not exist, or a component of it is not searchable.
Nanoseconds rather than whole seconds because the caller is a build tool: a source edited in the same second as the build that consumed it must still read as newer, or the rebuild is silently skipped. An int64 of nanoseconds since the epoch runs to the year 2262.
IF p->modifiedAt() THEN { int64 ns := $= }
METHOD toString() RETURNS String
STRING REPRESENTATION
METHOD equals(REFERENCE Path other) RETURNS boolean
METHOD isLessThan(REFERENCE Path other) RETURNS boolean
BuildInfoBuild-provenance runtime API.
Surfaces the AUTO-GENERATED C++ EV_buildinfo_data.hpp constants (version,
git describe / commit / branch, build counter, dirty flag, build timestamp)
to an Envzn program. The data is computed at build time by the compiler
(compiler/buildinfo.py) and written to the OUTPUT side every build — never to
source — so a program can report its own provenance.
char8[], not String: the data header is C++ #included early (global scope, before
namespace ENVZN), so this surface deliberately deals in char8[] byte
arrays (UTF-8) and primitives, and never touches String — a caller that
wants text converts the bytes itself (bytes INTO String, once String is in
scope) at the call site. A NAMESPACE (not a SINGLETON): BuildInfo is a
stateless provider of constants, it performs no behaviour.
The strings cross the FFI via the LOAD fill-buffer idiom — RETURNS char8[]
is not a legal FFI return (bind-spec), so each accessor fills a caller-owned
char8[] and returns the byte count.
kernel/src/BuildInfo.ev:37
Methods
METHOD version() RETURNS char8[]
METHOD gitDescribe() RETURNS char8[]
METHOD commit() RETURNS char8[]
METHOD branch() RETURNS char8[]
METHOD builtAt() RETURNS char8[]
METHOD isDirty() RETURNS boolean
METHOD buildCounter() RETURNS uint64
EnumReflectionThe generic enum name<->value capability.
An enum's case names are per-enum compile-time data the compiler alone knows, so
the compiler emits them: IDENTITY(SomeEnum).cases yields an EnumKind[], one
pair per case (the "cases as instances" model). This namespace is the generic
LOGIC over that table — written once, reused by anything that needs an enum's
name<->value mapping (serde, logging, config/UI, round-tripping through any
format). No feature synthesizes its own per-enum lookups; they all call here.
EnumKind (a case's name + value) lives in structs.ev next to Identity: it is
referenced by both Identity.cases and this namespace, and a STRUCT may not
share a file with a NAMESPACE (E9008) — so the ">1 consumer -> structs.ev" rule
applies.
The lookups walk cases by index (FOR i = 0 UNTIL cases.length): FOR/IN over a
T[] value-array PARAM mis-emits cases->iterator() (arrow on a value) today, so
the index form is the working idiom here.
kernel/src/EnumReflection.ev:28
Methods
METHOD name(REFERENCE EnumKind[] cases, int32 value) RETURNS String
value -> case name; the empty String when no case has that value.
METHOD valueForName(REFERENCE EnumKind[] cases, REFERENCE String target) RETURNS | int32
case name -> value; FAILURE when no case carries that name.
METHOD checkValue(REFERENCE EnumKind[] cases, int32 candidate) RETURNS | int32
Validate a value names a live case; echoes it back, else FAILURE.
FormatterAuto-conversion text formatter (stdio-spec.md §4).
Formatter is the kernel surface that powers the user-facing
("...$1")->format(args) form. The compiler rewrites that call to
Formatter->format(template, args) whenever at least one arg's
static type is not String — see stdio-spec.md §4.3.
A Formatter carries one piece of configuration: how it renders a
binary / ByteBuffer / DynamicByteBuffer placeholder. Construct
a Formatter once and reuse it — as a local, a CONSTANT field, or
held by a Writable for consistent output. The compiler's default
rewrite uses Formatter() (HEX_SPACED); call Formatter explicitly
to choose a different BinaryMode.
Architecture note: the template-walking + type cascade live here,
not on String. String is upstream of every renderable type's
conversion (the Converter and Codec classes, FloatFormat) in the kernel
.hpp DAG; placing
the cascade on String would create a cycle. Formatter is downstream
of both and can freely call into them. The compiler-rewrite from
stringExpr->format(args) to Formatter->format(stringExpr, args)
is what lets users keep the natural call shape while preserving
the topological invariant.
Format specifiers: a placeholder may carry a Python-style :spec
suffix (stdio-spec.md §4.4). The spec governs width / fill / align
and — for select types — base override and sign. The spec grammar
lives in parseSpec below; the rendering side dispatches in
renderArg / applyWidth.
kernel/src/Formatter.ev:47
Fields
BinaryMode binaryModeConstructors
INIT()
Default Formatter — binary args render as spaced hex.
INIT(BinaryMode mode)
Formatter with an explicit binary-rendering mode.
Methods
METHOD format(REFERENCE String tmpl, FormatArgument args...) RETURNS String
Render tmpl against args, substituting $1..$9, $$ (a
literal $) per stdio-spec.md §4.1, and $: (a literal :). A placeholder may carry a
format spec :<spec> (§4.4) — width / fill / align /
sign / type-letter — that is parsed and applied to the
rendered value.
FormatArgumentkernel/src/FormatArgument.ev:50
Constructors
INIT()
INIT(FormatKind k)
ABSENT (an EMPTY handle) or UNKNOWN (nothing a format call can print).
INIT(int8 v)
INIT(int16 v)
INIT(int32 v)
INIT(int64 v)
INIT(uint8 v)
INIT(uint16 v)
INIT(uint32 v)
INIT(uint64 v)
INIT(int128 v)
INIT(uint128 v)
INIT(float32 v)
A float32 keeps its own arm: it renders by its own shortest round-trip
(3.1415927), which the same value read as a float64 does not.
INIT(float64 v)
INIT(boolean v)
INIT(char32 v)
INIT(binary v)
INIT(number v)
INIT(complex v)
INIT(decimal128 v)
INIT(REFERENCE String v)
INIT(REFERENCE DynamicString v)
INIT(REFERENCE ByteBuffer v)
INIT(REFERENCE DynamicByteBuffer v)
INIT(REFERENCE Formattable v)
Methods
METHOD kindOf() RETURNS FormatKind
METHOD widthOf() RETURNS int32
The source width in bits of an INT, UINT or FLOAT (8, 16, 32, 64; 128 for the 128-bit kinds); 0 for every other kind.
METHOD asInt() RETURNS int64
METHOD asUint() RETURNS uint64
METHOD asInt128() RETURNS int128
METHOD asUint128() RETURNS uint128
METHOD asFloat() RETURNS float64
METHOD asFloat32() RETURNS float32
METHOD asBoolean() RETURNS boolean
METHOD asChar() RETURNS char32
METHOD asBinary() RETURNS binary
METHOD asNumber() RETURNS number
METHOD asComplex() RETURNS complex
METHOD asDecimal128() RETURNS decimal128
METHOD asString() RETURNS REFERENCE String
METHOD asDynamicString() RETURNS REFERENCE DynamicString
METHOD asByteBuffer() RETURNS REFERENCE ByteBuffer
METHOD asDynamicByteBuffer() RETURNS REFERENCE DynamicByteBuffer
METHOD asFormattable() RETURNS REFERENCE Formattable
FormatValueA format call (("$1 of $2")->format(a, b), Stdio->formatPrint, …) takes
its arguments as FormatArgument.... A developer never names this type: the
compiler builds one per argument at the call site, inside the call's own
expression, so each borrow it holds outlives the call (format-argument-
design.md). It copies a scalar or a 16-byte value and BORROWS anything wider —
a String, a byte buffer, a Formattable object — so a format call copies no
argument and allocates nothing per argument.
It is confined: a FormatArgument may be the element of a FormatArgument...
parameter or a REFERENCE FormatArgument[] renderer parameter, and nothing
else, because a borrow in one would dangle the moment it outlived its call.
Integers and floats are WIDENED to one kind each (FormatKind), and width
keeps the source width in bits so the renderer prints the value as written.
kernel/src/FormatArgument.ev:29
Fields
int64 iuint64 uint128 i128uint128 u128float64 ffloat32 gboolean bchar32 cbinary onumber ncomplex zdecimal128 dREFERENCE String sREFERENCE DynamicString dsREFERENCE ByteBuffer bbREFERENCE DynamicByteBuffer dbbREFERENCE Formattable fmEntryOptionsFills a program's options object from the command line, for a program whose
entry class implements TaskStarterWithOptions OF T
. It is written once,
here, so neither backend renders the parsing, --help or the usage error: the
entry the compiler generates creates the options object, calls fill, and
passes the object to start only when fill says to go on.
The answer is the exit code the program should end with, or -1 to go on:
-1 the options are loaded; call start(options)
0 --help or -h: the usage was printed
2 the command line was wrong: the problem and the usage went to stderr
kernel/src/EntryOptions.ev:23
Constructors
INIT()
Methods
MODIFY METHOD fill(REFERENCE String[] argv, MUTABLE REFERENCE T options) RETURNS int32
FormattableFormattable — a class that renders itself in a format string. A format
argument whose object implements it prints toString(); any other object
prints [??] (format-argument-design.md §5). The test is made on the OBJECT,
at run time, so an interface-typed argument whose object implements
Formattable still renders.
kernel/src/interfaces.ev:654
Methods
METHOD toString() RETURNS String
BinaryModeBinaryMode — how a Formatter renders a binary placeholder
argument. Selected at Formatter construction; the default
Formatter uses HEX_SPACED.
= padding: "3q2+7w==".Spec reference: stdio-spec.md §4.
kernel/src/enums.ev:171
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
BuildBuild — compile-time build flavor. Available to user code via
the WHEN Build IS DEBUG/RELEASE conditional-compilation construct
(analogous to #ifdef DEBUG in C/C++, never emitted):
WHEN Build IS DEBUG {
log("debug-only state: $1")->format(detail)
} ELSE {
// release path
}
Spec reference: §Control Flow > Conditional Compilation.
kernel/src/enums.ev:64
| Case | Description |
|---|---|
? |
— |
? |
— |
EncodingEncoding — text-encoding tag used by Convert text↔bytes bridges. Consumed by the four-form String/ByteBuffer type system.
Used by: - Convert.toBytes(String, Encoding) → ByteBuffer - Convert.toString(ByteBuffer, Encoding) → (String, STATUS)
V1 implementation: UTF-8 round-trip is end-to-end; the other four variants are stubbed as STATUS-FAILURE returns until needed.
kernel/src/enums.ev:91
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
EndiannessEndianness — byte-order tag used by Convert numeric↔binary bridges. Consumed by the four-form String/ByteBuffer type system.
Used by: - Convert.toBytes(int32, Endianness) → ByteBuffer - Convert.toInt32(ByteBuffer, Endianness) → (int32, STATUS) - …and every other Convert numeric↔binary bridge.
kernel/src/enums.ev:119
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
FormatKindFormatKind — what one FormatArgument holds (format-argument-design.md §3).
The integer and float kinds are WIDENED: INT holds every signed width up to
64 bits as an int64, UINT every unsigned one as a uint64, FLOAT both floats
as a float64, and the argument's width remembers the source width so it
renders as written (a negative int8 in hex is two digits; a float32 keeps its
own shortest round-trip). INT128/UINT128 cannot widen to 64 bits and are
their own kinds. The text kinds and FORMATTABLE are borrowed; ABSENT is an
EMPTY handle (renders "EMPTY"); UNKNOWN is anything else (renders "[??]").
kernel/src/enums.ev:327
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
IdentityAccessIdentityAccess — the declared access of a member, as IDENTITY(subject) reports
it on IdentityField.access and IdentityMethod.access. PUBLIC_ACCESS when
the member declares no access modifier.
kernel/src/enums.ev:305
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
EnumKindIdentity — the compile-time reflection / RTTI carrier produced by the IDENTITY(subject) keyword intrinsic. Every field is computed by the compiler from static type + binding knowledge; the developer cannot construct an Identity directly (the keyword is the only producer). See for the field semantics and the closed class / modifier vocabularies.
EnumKind — one enum case as a (name, value) pair; the element type of
Identity.cases. Referenced by both Identity and EnumReflection, so it lives
here per the ">1 consumer -> structs.ev" rule. Declared before Identity because
Identity holds an EnumKind[].
kernel/src/structs.ev:150
Fields
String name — The case name — "HIGH".int32 value — The case value — the ordinal (Envzn enums are ordinal).FormatSpecFormatSpec — parsed $N:<spec> directive carried into Formatter's
per-arg renderer. See stdio-spec.md §4.4 for the grammar and per-
type semantics. Default-constructed values mean "absent" — align
of 0x0 means "type default" (right for numbers, left for everything
else); typeLetter of 0x0 means "render via the type's default";
width of 0 means "no minimum width".
kernel/src/structs.ev:106
Fields
boolean present — Has anything been parsed? When FALSE, Formatter.renderArg uses its default-rendering path; when TRUE, the spec fields drive the formatted output.char32 fill — Single fill char. ASCII space (0x20) by default.char32 align — Alignment marker: '<' / '>' / '^', or 0x0 for "type default".char32 sign — Sign marker: '+' (force on positives) / '-' (default — only on negatives), or 0x0 (treated as '-').uint32 width — Minimum render width in code points. 0 means "no minimum".char32 typeLetter — Type letter: 'd' / 'x' / 'X' / 'o' / 'b' / 's', or 0x0 for "no type override (use the arg's default render)".IdentityField order is load-bearing: it is the synthesized-constructor argument order the IDENTITY lowering emits.
kernel/src/structs.ev:260
Fields
String name — Bare head of the type name — "Person", "Array", "int32".String home — Declaring module; primitives report "ENVZN".String fullname — Fully-parameterized spelling, module-qualified unless primitive — "ENVZN::Array[surface::Person]", "int32".String type — The subject's type, fully qualified unless primitive — "int32", "ENVZN::String", "surface::Person", "ENVZN::Array[surface::Person]".String modifier — The binding's declared qualifier — constant / mutable / reference / mutable reference / shared mutable reference; blank for a type subject.String kind — The type kind — Primitive / Enum / Group / Struct / Class / Value Class / Hidden Class / Shared Class / Abstract Class / Interface / View Class.boolean generic — True when the type has type-parameters (Array[T], Comparable[T]).boolean internal — True when the type is declared INTERNAL (module-private, §17).String currentLens — The subject's static/declared type when viewed through an ancestor lens (differs from the concrete type); blank otherwise.String[] lenses — Ancestors in order: classes -> abstract classes, then implemented interfaces.boolean blittable — True when a flat byte-copy DUPLICATES the value — both copies then live, both destroyed (C++ trivially-copyable). FALSE for anything owning a heap buffer or handle: String, ByteBuffer, every container.boolean relocatable — True when a flat byte-copy MOVES the value — the source is abandoned with NO destructor run, so only one copy is ever live (trivially-relocatable). The WEAKER and far more common property: an owning handle is not blittable (two owners would double-free) but IS relocatable, which is why a growing container may memcpy its slots yet must clone() when copied. The one shape that is neither is a SELF-REFERENTIAL value — the value-array T[N+], whose backing points into its own inline buffer, so byte-moving it would dangle: DynamicString, DynamicByteBuffer.EnumKind[] cases — For an ENUM type subject: one EnumKind (name + value) per case, in declaration order — the enum's "instances". Empty for every non-enum subject. The generic name<->value logic over this table lives in EnumReflection (EnumReflection.ev).int32 numberOfDataFields — The number of data fields (== dataFields.length); 0 for a primitive, enum, group or interface.IdentityField[] dataFields — A class's, value class's or struct's data fields, inherited ones first.int32 numberOfMethods — The number of methods (== methods.length); 0 for a primitive, enum or group.IdentityMethod[] methods — A class's, value class's, struct's or interface's methods, inherited ones first; an overridden ancestor method appears once, as the override.binary[] fieldNameBytes — The data-field names as UTF-8, back to back in dataFields order — the bytes a byte-level reader (a JSON key) is compared against, encoded once at compile time instead of from each name's code points on every compare.int64[] fieldNameStarts — Where each name starts in fieldNameBytes, plus one final entry, the total: field k's name is fieldNameBytes[fieldNameStarts[k], fieldNameStarts[k + 1]). Empty when there are no data fields.IdentityFieldIdentityField — one data field of a class, value class or struct, as IDENTITY(subject).dataFields lists it. Field order is load-bearing: it is the synthesized-constructor argument order the IDENTITY lowering emits.
kernel/src/structs.ev:162
Fields
String name — The field's name — "width".String type — The field's type, fully qualified unless primitive: "int32", "ENVZN::String".String kind — The field type's kind, in Identity's kind vocabulary: "Primitive", "Class", "Value Class", "Struct", ...IdentityAccess access — The declared access; PUBLIC_ACCESS when no access modifier is declared.String modifier — "", "CONSTANT", "REFERENCE", "SHARED MUTABLE REFERENCE", ...int32 declarationIndex — Declaration order across the effective field list, base first.boolean derived — True for a DERIVED field (I.P.d).boolean inherited — True when the field is declared in an ancestor, not in the subject.String declaredIn — The declaring type's fullname, with type arguments.IdentityMethodIdentityMethod — one method of a class, value class, struct or interface, as IDENTITY(subject).methods lists it ("INIT", "CLEANUP" and "RESTORE" included). Field order is load-bearing (the IDENTITY lowering's constructor argument order).
kernel/src/structs.ev:216
Fields
String name — The method's name; "INIT", "CLEANUP" and "RESTORE" included.String[] descriptors — The declared descriptors in source order: "AUTO", "MODIFY", "FINAL", "OVERRIDE", ...String typeParameters — "[T]" for a generic method, "" otherwise.IdentityAccess access — The declared access; PUBLIC_ACCESS when no access modifier is declared.int32 numberOfInParameters — The number of in parameters (== inParameters.length).IdentityParameter[] inParameters — The in parameters, in order.int32 numberOfOutParameters — The number of out parameters (== outParameters.length); 0 for no RETURNS.IdentityParameter[] outParameters — The out parameters (the RETURNS slots), in order.boolean pipe — True for RETURNS (... | STATUS s) rather than a comma list.boolean inherited — True when the method is declared in an ancestor, not in the subject.String declaredIn — The declaring type's fullname, with type arguments.String overrides — The ancestor whose method this replaces, "" if none.String[] fills — The interfaces whose slot this method implements.IdentityParameterIdentityParameter — one in or out parameter of an IdentityMethod. Field order is load-bearing (the IDENTITY lowering's constructor argument order).
kernel/src/structs.ev:195
Fields
String name — The parameter's name; "" for an unnamed return slot.String type — The parameter's type, fully qualified unless primitive.String kind — The parameter type's kind, in Identity's kind vocabulary.String modifier — The parameter mode: "", "REFERENCE", "MUTABLE REFERENCE".int32 position — The parameter's position in its list, from 0.ProcessResultMirrors enums.ev / interfaces.ev: a single file collecting the
small reserved STRUCTs that the constitution recognises as
part of the kernel surface but that don't merit their own per-
class file.
ProcessResult — the output of a Process->run(...) call.
exit(N) otherwise,
or -1 if the process was killed by a signal).out.kernel/src/structs.ev:40
Fields
int32 exitCodeString outString errBase64CodecBase64Codec.ev — base64 text<->bytes encoding (RFC 4648 standard alphabet).
Parameterized, multi-form transforms — NOT AS/INTO operators — hosted in a
NAMESPACE of free functions (no instance), called as Base64Codec.toBase64(bb).
kernel/src/Base64Codec.ev:14
Methods
METHOD toBase64(REFERENCE ByteBuffer bb) RETURNS String
ByteBuffer -> base64 String (RFC 4648 standard alphabet). Padding ('=') is included so the output is always a multiple of 4 characters. No line wrapping.
METHOD fromBase64(REFERENCE String s) RETURNS | ByteBuffer
Base64 String -> ByteBuffer (RFC 4648 standard alphabet). Standard '+/' alphabet only (no URL-safe variant in V1). Padding required. Skips ASCII whitespace. Pipe-XOR — FAILURE on any invalid character or wrong padding.
ByteOrderCodeckernel/src/ByteOrderCodec.ev:32
Methods
METHOD toBytes(int32 n, Endianness endian) RETURNS ByteBuffer
METHOD toBytes(int64 n, Endianness endian) RETURNS ByteBuffer
METHOD toBytes(uint32 n, Endianness endian) RETURNS ByteBuffer
METHOD toBytes(uint64 n, Endianness endian) RETURNS ByteBuffer
METHOD toBytes(float32 n, Endianness endian) RETURNS ByteBuffer
Float -> bytes: IEEE-754 bit pattern via a bound shim, then packed by the same pure-Envzn endian helper the integer overloads use.
METHOD toBytes(float64 n, Endianness endian) RETURNS ByteBuffer
METHOD toInt32(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | int32
METHOD toInt64(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | int64
METHOD toUInt32(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | uint32
METHOD toUInt64(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | uint64
METHOD toFloat32(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | float32
Bytes -> float: integer bit pattern assembled in pure Envzn, then a bound shim reinterprets it as IEEE-754.
METHOD toFloat64(REFERENCE ByteBuffer bb, Endianness endian) RETURNS | float64
DecimalCodecThe inbound half of the decimal128 IEEE 754-2008 BID (Binary Integer Decimal) 128-bit wire codec.
bidToParts decodes 16 big-endian BID bytes into a (coefficient, exponent)
DecimalParts — it returns only the PARTS, never a decimal128: the kernel
cannot construct a value-class-backed primitive, so the compiler's
ByteBuffer INTO decimal128 lowering calls this helper and assembles
Decimal128(coeff, exp) on success (the same parts→value pattern as
DecimalText.parseDecimalParts for String INTO decimal128). The outbound
encode is decimal128 INTO ByteBuffer (DecimalConversions, a plain total
OPERATOR INTO).
Simple form only: a canonical decimal128 holds ≤ 34 digits (< 10^34 < 2^113), so the coefficient always fits the 113-bit field and the "11" combination branch (large coefficient / Infinity / NaN) is never PRODUCED — but a hostile or foreign 16 bytes can present it, so decode REJECTS it (and any out-of-range exponent or > 34-digit coefficient) with a FAILURE: that is the fallible path.
Layout (big-endian): bit 127 = sign, bits 126..113 = biased exponent (exponent + 6176), bits 112..0 = the unsigned coefficient.
Pure Envzn, zero deps beyond ByteBuffer / DecimalParts / NumericUtilities. See decimal128-design.md §"IEEE BID wire codec".
kernel/src/DecimalCodec.ev:34
Methods
METHOD bidToParts(REFERENCE ByteBuffer bb) RETURNS | DecimalParts
Decode 16 big-endian IEEE BID bytes into (coefficient, exponent). Fallible: wrong length, the non-canonical "11" combination form, an out-of-range biased exponent, or a coefficient of more than 34 digits.
HexCodeckernel/src/HexCodec.ev:13
Methods
METHOD toHex(REFERENCE ByteBuffer bb) RETURNS String
ByteBuffer -> hex string with " " between bytes. Empty buffer returns "". Each byte becomes two uppercase hex digits.
METHOD toHex(REFERENCE ByteBuffer bb, REFERENCE String separator) RETURNS String
ByteBuffer -> hex string with caller-chosen separator. Pass "" for compact ("3F406A"), " " for canonical ("3F 40 6A"), ":" for MAC-style.
METHOD toHex(binary b) RETURNS String
Single-byte hex form. Used by the kernel print/stringify dispatch as the
default formatter for the binary primitive. Returns exactly
two uppercase characters (e.g. "3F" for 0x3F, "00" for zero).
METHOD fromHex(REFERENCE String s) RETURNS | ByteBuffer
Hex string -> ByteBuffer. Accepts upper/lowercase hex digits; ignores ASCII whitespace and standard separators (" ", ":", "-") so canonical / MAC / UUID formats round-trip. Pipe-XOR — FAILURE on any non-hex non-separator character or an odd digit count.
UTFCodecUnicode Transformation Format codec + scalar validity.
UTFCodec is a stateless NAMESPACE: never instantiated, reached via
UTFCodec.methodName(args). It hosts free functions plus the private
CONSTANT lookup tables (and the CharClass / State enums + FirstUnitInfo
struct they are built from) the transcoders walk.
PURPOSE
The single home for transcoding between the three UTF encodings
(UTF-8 / UTF-16 / UTF-32), plus the predicates that decide whether
a code point is a legal Unicode scalar and whether it is admissible
as text. The Converter and Codec classes and DynamicString (via
DynamicString.append) are the user-facing bridges to the String / ByteBuffer types; they
marshal char[] arrays in/out and call UTFCodec for the actual
transcoding. UTFCodec itself has no dependency on String,
DynamicString, ByteBuffer, or DynamicByteBuffer — it works
purely in terms of char8[] / char16[] / char32[] and the two
scalar-validity predicates over char. That keeps UTFCodec below
every text/byte class in the kernel dependency order.
The class is named for the UTF family (UTF-8 / UTF-16 / UTF-32).
Every transcoder is named encodeTo<TARGET>(<SOURCE>[] source) ->
(<TARGET>[] | STATUS) — the destination encoding is in the method
name; the source is in the argument width. The full 3×3 matrix
minus the identity diagonal is implemented (6 methods).
CODE POINT vs CODE UNIT
char32 is a Unicode code point (U+0000..U+10FFFF, lowering to
char32_t). char8 is a UTF-8 code unit (8-bit, char8_t). char16
is a UTF-16 code unit (16-bit, char16_t). Code-unit arrays in
char8[] / char16[] form may need multi-unit grouping to recover a
code point — UTF-8 lead+continuation bytes for encodeToUTF32(char8[]),
surrogate pairs for encodeToUTF32(char16[]).
LOOKUP TABLES (utf_utils-style DFA)
Four PRIVATE CONSTANT tables back a single-table DFA decoder
(currently dormant — the linear decode below is what runs today).
The DFA shape follows Bob Steagall's utf_utils paper:
firstUnitTable[256] — for each possible first byte, the masked code-point bits + the next DFA state. octetCategory[256] — CharClass tag for every byte value, used by continuation-byte transition lookup. transitions[108] — 9 states × 12 CharClass categories → next State. Index = (state + category). firstOctetMask[12] — per-CharClass mask of the first byte's code-point bits (e.g. 0x1F for the 5-bit lead in a 2-byte sequence).
VALIDITY — TWO PREDICATES
- isValid(char) — is the code point a legal Unicode
scalar value (<= U+10FFFF, not a
UTF-16 surrogate).
- isStringSafeCodePoint(char) — stricter: a scalar that is also
admissible as text. Rejects the 66
noncharacters and the non-whitespace
C0/C1 control bytes. This is the
invariant DynamicString enforces on
every append, so a text value can
never accumulate non-text content.
STATUS: first version, written as part of the four-form text/binary dig-out. Carries the UTF-8 encode/decode that previously lived on Convert (encodeUtf8 / decodeUtf8), now with the scalar- validity checks (overlong / surrogate / out-of-range) folded into decode. The DFA lookup tables — they are dormant storage until a DFA-based decode rewrite replaces the current linear form.
kernel/src/UTFCodec.ev:90
Methods
METHOD encodeToUTF32(REFERENCE char8[] source) RETURNS | char32[]
DFA-BASED BULK DECODE — UTF-8 code units -> UTF-32 code points Decode a full UTF-8 buffer (char8[] code units) into a char32[] of code points using the four LOOKUP TABLES above (utf_utils- style single-DFA decoder). Pipe-XOR: SUCCESS yields the codepoints buffer; FAILURE on the first malformed lead unit, truncated sequence, bad continuation unit, or DFA-detected illegal form (overlong, surrogate, beyond U+10FFFF — all baked into the transitions[] mapping).
Input / output are both bare value-array storage shorthand — no String / ByteBuffer / DynamicString / Array[T] dependency. UTFCodec sits below the String family in the kernel dependency order.
Algorithm:
1. firstUnitTable[u] -> (firstOctet bits, nextState).
ASCII units (0x00..0x7F) return nextState=BEGIN with
cp == u, so the ASCII path is one table read + one write.
2. For multi-unit leads, nextState moves into a CONTINUEn /
PARTIAL_SEQUENCE state. The continuation loop reads
successive code units, accumulates 6 bits per unit into
cp, and advances state via
transitions[currentState + octetCategory[contUnit]].
Loop exits when state returns to BEGIN/END (= 0; code
point complete) or ERROR (malformed).
3. Result built via the value-array HWM-write proxy —
result[outCount] = cp grows the buffer when outCount
equals result.length.
METHOD appendUTF8(MUTABLE REFERENCE binary[] dst, REFERENCE char32[] src, int64 off, int64 n) RETURNS void
UTF-8 ENCODE — the one encoder. Every UTF-8 encoder in the kernel and its
modules ends here: appendUTF8 for a window of code points, appendScalarUTF8
for one. String windows arrive through TextEncoding (this namespace orders
before String and cannot name it). Both append to a binary[], the buffer every
caller writes into. PRECONDITION: every code point is a Unicode scalar, as a
String's are by construction; encodeToUTF8 checks a raw array before calling.
The widths follow RFC 3629:
< 0x80 → 1 byte (0xxxxxxx)
< 0x800 → 2 bytes (110xxxxx 10xxxxxx)
< 0x10000 → 3 bytes (1110xxxx 10xxxxxx 10xxxxxx)
else → 4 bytes (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
METHOD fillUTF8(MUTABLE REFERENCE binary[] dst, REFERENCE char32[] src, int64 off, int64 n) RETURNS STATUS
The same UTF-8 as appendUTF8, through simdutf, for a caller that starts from
an EMPTY buffer — dst is filled from index 0, never appended to. The length is
measured first so dst is sized exactly. FAILURE on a non-empty dst, a window
out of range, or a code point that is not a Unicode scalar.
METHOD appendScalarUTF8(MUTABLE REFERENCE binary[] dst, char32 c) RETURNS void
One code point's UTF-8 appended to dst (see appendUTF8).
METHOD encodeToUTF8(REFERENCE char32[] source) RETURNS | char8[]
BULK TRANSCODE — char32[] → char8[] (codepoints → UTF-8 bytes)
Encode an array of UTF-32 codepoints into a UTF-8 byte stream.
Pipe-XOR: SUCCESS yields the byte buffer; FAILURE on the first
codepoint that's beyond U+10FFFF or in the UTF-16 surrogate
block. The array is checked first, then encoded by appendUTF8.
METHOD decodeUTF8(REFERENCE binary[] src, int64 off, int64 n) RETURNS | char32[]
UTF-8 DECODE — a window of bytes as code points, through simdutf. One call decodes and validates (overlong, surrogate, out-of-range and truncated sequences all fail); every code point is then held to the Tier-1 text rule, so the result can be adopted as a String's storage. FAILURE on either.
METHOD encodeToUTF16(REFERENCE char32[] source) RETURNS | char16[]
BULK TRANSCODE — char32[] → char16[] (codepoints → UTF-16 units) Encode an array of UTF-32 codepoints into a UTF-16 code unit stream. BMP codepoints (< U+10000) emit one char16. Supplementary plane codepoints (U+10000..U+10FFFF) emit a surrogate pair — high in [0xD800, 0xDBFF], low in [0xDC00, 0xDFFF]. Pipe-XOR: FAILURE on a codepoint that's beyond U+10FFFF or in the surrogate block (raw surrogate codepoints are not legal scalar values).
METHOD encodeToUTF32(REFERENCE char16[] source) RETURNS | char32[]
BULK TRANSCODE — char16[] → char32[] (UTF-16 units → codepoints) Decode a UTF-16 code unit stream into UTF-32 codepoints, pairing surrogate halves into supplementary-plane codepoints. Pipe-XOR: FAILURE on an unpaired surrogate (low surrogate without a preceding high, or high surrogate without a following low).
METHOD encodeToUTF8(REFERENCE char16[] source) RETURNS | char8[]
BULK TRANSCODE — char16[] → char8[] (UTF-16 → UTF-8)
Composition: decode UTF-16 → codepoints → encode codepoints as UTF-8. The chain propagates STATUS from either step.
METHOD encodeToUTF16(REFERENCE char8[] source) RETURNS | char16[]
BULK TRANSCODE — char8[] → char16[] (UTF-8 → UTF-16)
Composition: decode UTF-8 → codepoints → encode codepoints as UTF-16. The chain propagates STATUS from either step.
METHOD isValid(char32 c) RETURNS boolean
VALIDITY PREDICATES
TRUE when c is a legal Unicode scalar value: in range
U+0000..U+10FFFF and not a UTF-16 surrogate half.
METHOD isStringSafeCodePoint(char32 c) RETURNS boolean
TRUE when c is admissible as text — a legal scalar value that
is also not a noncharacter and not a junk control byte. This is
the Tier-1 text rule: DynamicString.append(char) rejects
every code point that fails it, so no text value can carry
non-text content.
Allowed control bytes are the text whitespace set only — tab (U+0009), LF (U+000A), VT (U+000B), FF (U+000C), CR (U+000D), and NEL (U+0085); every other C0/C1 control and U+007F (DEL) is rejected. VT/FF/NEL are kept because they are line separators (see splitLines).
TextEncodingUTFCodec holds the one UTF-8 encoder, over char32[]. It orders before
String in the kernel's C++ and cannot name it, and a String's code points
are kernel-internal, so code outside the kernel (a JSON writer, a builder)
reaches the encoder here. Nothing is allocated: the String's storage is
handed to the encoder as it is. An empty dst is filled by simdutf
(UTFCodec.fillUTF8); a non-empty one is appended to by the kernel encoder.
kernel/src/TextEncoding.ev:25
Methods
METHOD appendUTF8(MUTABLE REFERENCE binary[] dst, REFERENCE String s, int64 off, int64 n) RETURNS void
Append the UTF-8 of s's code points [off, off + n) to dst.
The window is bounds-checked; a String's code points are always
Unicode scalars, so this cannot fail.
METHOD stringFromCString(HANDLE s) RETURNS String
The String a C string's UTF-8 spells: a FOREIGN result, a main argument.
A null pointer is the empty String. Bytes that are not UTF-8 give the empty
String too, as the decoder reports them.
METHOD stringFromBytes(HANDLE p, int64 n) RETURNS String
The String of the n UTF-8 bytes at p, which is C memory the caller keeps.
METHOD utf8Of(REFERENCE String s) RETURNS char8[]
The UTF-8 of s. A String's code points are scalars, so this cannot fail.
PrimitiveConversionsCONVERSIONS host for primitive↔primitive numeric and character conversions. The AS/INTO surface over the number/char conversion matrix.
widening → OPERATOR INTO (lossless, total) e.g. int32 INTO int64 narrowing / → OPERATOR AS (lossy, fallible) e.g. int64 AS int32 sign-cross (range-checked → STATUS)
No class dependencies (only primitives + STATUS), so this host orders early in the kernel include topology and is reachable from every kernel class.
NOT here (they live on NumericUtilities): the deliberate UNCHECKED bit operations
(truncateTo*, the saturating toInt32(uint32), the reinterpreting
toUint64(int32)) — they would collide with the checked AS for the same
type pair; the char-transcoding narrowings (char16/char32 → char8,
char32 → char16) — they route through UTFCodec; and the character
classifiers (isAlpha/isDigit/…) — predicates, not conversions.
kernel/src/PrimitiveConversions.ev:28
NumberConversionsCONVERSIONS host for the number primitive's narrow-OUT surface. Widening INTO number (int / float -> number) is the implicit lattice edge handled by the compiler; this host owns the explicit, fallible extraction back to a fixed scalar.
number AS int8/16/32/64, uint8/16/32, uint64, char8 — lossy, fallible (T | STATUS)
Per CONVERSIONS.md: AS is lossy and RANGE-CHECKED at runtime — it fails
into the IF/ELSE pipe-XOR, it is NOT a silent truncation. Succeeds IFF the
number holds an integer subtype (INTEGER or the overflow-arm UNSIGNED, #38)
whose value fits the target (in range, ≥ 0 for unsigned). The UNSIGNED arm
is exactly a uint64, so AS uint64 on it is total; but UNSIGNED > int64_max,
so AS int64 (and any narrower signed/unsigned) FAILS its range check. A
float-subtype number always FAILS an integer extraction.
number INTO float64 — lossless-ish, total Every subtype lowers to float64 by the widening model (INTEGER via int64, UNSIGNED via uint64, both registered edges; float64 is identity), so this is a plain-value INTO, not a fallible AS (large magnitudes round, as any float).
The held value is read off the tagged union behind the value-class surface
(v.tag / v.store.i / v.store.u / v.store.f). The range-checked assignment to
the value slot is the sanctioned narrowing site (mirrors the int64 AS int32
row in PrimitiveConversions). number AS float32 is deferred (see its note
below — blocked on a writable float32-max bound).
kernel/src/NumberConversions.ev:35
ComplexConversionskernel/src/ComplexConversions.ev:13
DecimalConversionsThe AS/INTO conversion host for decimal128. Mirrors NumberConversions / ComplexConversions.
Surface (decimal128-design.md §Conversions): - decimal128 INTO String — EXACT decimal text (total). The headline display feature: a decimal128 renders the precise value it holds, no float artifacts. - decimal128 AS int8…int64 / uint8…uint64 — fallible (non-integral or out-of-range → FAILURE). - decimal128 AS float32 / float64 — lossy, fallible. String → decimal128 (parse) and number ↔ decimal128 land alongside.
Widening INTO decimal128 (int* → decimal128) is implicit (no operator) — the compiler lowers it at the widen-in site (build_ir).
kernel/src/DecimalConversions.ev:25
TextConverterCONVERSIONS host for the String ↔ ByteBuffer hard line. The AS/INTO surface over the kernel's text/binary boundary, and its implementation — the UTF-8 encode/decode logic lives here in the operators (and the shared encoder helper), not delegated elsewhere.
Asymmetry (by design): String INTO ByteBuffer — lossless, total (every code point UTF-8 encodes) ByteBuffer INTO String — lossless, fallible (arbitrary bytes may not be valid UTF-8 → FAILURE; each decoded code point also passes the Tier-1 text check)
INTO here assumes UTF-8 — the canonical text encoding. Other encodings, and
the hex/base64 transforms, are parameterized and stay as named functions on
the Converter and Codec classes (out of scope for single-source/single-target AS/INTO operators).
kernel/src/TextConverter.ev:26
CharConverterCONVERSIONS host for char→String.
A single code point rendered as a one-character String. char8/char16 widen to a char32 code point (via PrimitiveConversions) before encoding; char32 is already a code point. DynamicString.append(char32) UTF-8-encodes it and runs the Tier-1 text check — a non-text code point yields an empty String (the append FAILURE is benign here, matching the legacy behavior).
char8/char16/char32 INTO String — lossless, total char32[] INTO String — lossless, total String INTO char32 — exact-or-FAILURE (one code point)
Depends only on String + DynamicString, so it orders early. The char32[]→String
operator backs the compiler-inserted error-message auto-conversion (args.py
wraps a char[]-typed print/format argument as arg INTO String); the
conversion registry is array-aware so it coexists with the scalar char32→String
above rather than colliding on the key.
kernel/src/CharConverter.ev:28
CharWidthConverterCONVERSIONS host for cross-char-width NARROWING. The AS surface over char16/char32 → a narrower char, and its implementation — the single-code-unit narrowing decision lives here, delegating only to UTFCodec's bulk transcoders (the UTF authority).
char16/char32 AS char8 — lossy, fallible (multi-byte UTF-8 → FAILURE) char32 AS char16 — lossy, fallible (UTF-16 surrogate pair → FAILURE)
UTFCodec emits the full encoded sequence; the narrowing succeeds only when the result is exactly one code unit. UTF validation (scalar range, surrogate rejection) is owned by UTFCodec — an invalid source scalar surfaces as STATUS.
Char-width WIDENING (char8 INTO char16/char32, char16 INTO char32) is lossless and lives in PrimitiveConversions; only the fallible narrowing direction needs UTFCodec, so this host depends on UTFCodec and orders AFTER it (later than the early PrimitiveConversions / CharConverter hosts).
kernel/src/CharWidthConverter.ev:27
NumberConverterCONVERSIONS host for number↔text conversions The AS/INTO surface over the kernel's numeric conversions, and their implementation — the digit/parse logic lives here in the operators (and their shared helpers), not delegated elsewhere.
integer/boolean INTO String — lossless, total (every value has a text form) String INTO number — lossless, fallible (parse; bad text → FAILURE)
Scoped to depend on only String + DynamicString (NOT FloatFormat), so this
host orders EARLY — before foundational classes like Array — letting them use
x INTO String. The float→String path is the one piece that needs the Ryu
engine (FloatFormat); it lives in the separate FloatConverter host, which
orders later. Float PARSING (String→float) stays here — it uses the strtod/
strtof native shim, not FloatFormat (FOREIGN scope is per-file, §17, so the
parse binds are redeclared below).
kernel/src/NumberConverter.ev:26
FloatConverterCONVERSIONS host for float→String (V1 Part F piece 4).
Split out of NumberConverter so that NumberConverter (integer/boolean→String +
all String→number parsing) depends only on String/DynamicString and can be
ordered EARLY — before foundational classes like Array — letting them use
x INTO String. The float→decimal path is the one piece that needs the Ryu
engine (FloatFormat), so it lives here and orders after FloatFormat; its users
(Formatter, Math, MeasuringTimer) are all later classes.
float32 INTO String — lossless, total float64 INTO String — lossless, total
The float→bits reinterpret crosses the FOREIGN boundary (no pure-Envzn expression); everything past that is integer-only arithmetic in FloatFormat.
kernel/src/FloatConverter.ev:28
FloatParseConverterkernel/src/FloatParseConverter.ev:21
FloatParsekernel/src/FloatParse.ev:14
Methods
METHOD parseF64(REFERENCE String s) RETURNS | float64
METHOD parseF32(REFERENCE String s) RETURNS | float32
FloatParseResultkernel/src/FloatParseResult.ev:27
Fields
int32 MAX_DIGITSConstructors
INIT()
Methods
MODIFY METHOD pushDigit64(uint32 d) RETURNS void
Accumulate one decimal digit into the uint64 fast-path significand, flipping sig64Ovf the moment sig64·10+d would exceed uint64.
METHOD isValid() RETURNS boolean
Whether the last parse() produced a well-formed value (the FloatParse surface reads this to choose the success vs FAILURE arm).
METHOD charEqCI(char32 c, char32 lower) RETURNS boolean
ASCII case-insensitive char compare (lower is the lowercase letter).
METHOD isInfinityWord(REFERENCE String s, int64 start, int64 endp) RETURNS boolean
TRUE iff s[start, endp) spells "inf" or "infinity" (case-insensitive).
METHOD computeBitsN(int32 mantBits, int32 eMin, int32 biasAdd, int32 maxBiased, int32 signPos) RETURNS uint64
L4 — the exact float driver, generalized over target width. Produce the
correctly-rounded IEEE-754 bit pattern for the parsed (significand, exp10,
sign) via big-integer AlgorithmM: form V = sig·10^exp10 = N/D, scale to
[2^mantBits, 2^(mantBits+1)) tracking the binary exponent e2 (subnormal
floor at eMin), extract the mantissa by binary long-division, round-to-
nearest-even (with the truncated sticky bit), then handle rounding
overflow and the subnormal/normal/inf encodings. Parameters:
float64 → (52, -1074, 1075, 2047, 63) float32 → (23, -149, 150, 255, 31)
where biasAdd = mantBits + exponent-bias, maxBiased = 2^expBits − 1.
METHOD computeBits() RETURNS uint64
Correctly-rounded IEEE-754 binary64 / binary32 bit patterns (exact path).
METHOD computeBits32() RETURNS uint64
METHOD clingerEligible() RETURNS boolean
TRUE iff the Clinger fast path applies to the parsed value at float64.
METHOD eiselLemire64() RETURNS | uint64
Eisel-Lemire tier-2 fast path — value = sig64 · 10^exp10 with sig64 known exact (fits uint64). Returns the float64 MAGNITUDE bit pattern on a confidently-correct rounding, or FAILURE to fall back to the exact path. A faithful port of Rust dec2flt lemire.rs, validated in Python (0 mismatches over ~200k cases). It NEVER commits a wrong result — the only outcomes are the correctly-rounded value or a fall-back signal.
METHOD toFloat64() RETURNS float64
The parsed value as a real float64. Tiered: (L8) Clinger for the common exactly-representable case; then Eisel-Lemire for the wider fits-in-uint64 case; then the exact bignum computeBits() for everything else / EL fall-back.
METHOD clingerEligible32() RETURNS boolean
Clinger applies at float32 when sig ≤ 2^24 and |exp10| ≤ 10 (10^10 = 5^10· 2^10, 5^10 < 2^24, so it is an exact float32).
METHOD toFloat32() RETURNS float32
MODIFY METHOD parse(REFERENCE String s) RETURNS void
Parse s into this result's fields. Sets valid = FALSE (and stops) on any
character outside the strict finite-number grammar or on non-consumption.
FloatBigIntkernel/src/FloatBigInt.ev:25
Fields
int32 MAX_LIMBSConstructors
INIT()
Methods
METHOD isZero() RETURNS boolean
MODIFY METHOD setSmall(uint64 v) RETURNS void
Set to a value that fits in 64 bits.
MODIFY METHOD mulAddSmall(uint32 mul, uint32 add) RETURNS void
self := self * mul + add (mul, add each fit in 32 bits; mul >= 1).
METHOD pow10Small(int32 e) RETURNS uint32
10^e for e in 0..8 (fits uint32; e<=8 keeps it under 10^9 < 2^32).
MODIFY METHOD mulPow10(int32 k) RETURNS void
self := self * 10^k (k >= 0). Chunked by 10^9 per pass (the largest power of ten a uint32 multiplier holds), then a final <10^9 remainder.
MODIFY METHOD setPow10(int32 k) RETURNS void
self := 10^k (k >= 0). The denominator-construction path.
MODIFY METHOD shiftLeftBits(int32 n) RETURNS void
self := self * 2^n
MODIFY METHOD appendLimbHi(uint32 v) RETURNS void
Append a limb as the new most-significant limb (internal builder for cloning self into a scratch value without passing SELF).
METHOD bitLength() RETURNS int32
Number of significant bits (0 for zero). floor(log2(self)) + 1.
METHOD cloneBig() RETURNS FloatBigInt
A fresh independent copy of self (reads own limbs, builds the copy through its own appendLimbHi — never passes SELF).
METHOD cmp(REFERENCE FloatBigInt other) RETURNS int32
Ordering vs another big int: -1 (self < other), 0 (equal), 1 (self > other).
MODIFY METHOD addBig(REFERENCE FloatBigInt other) RETURNS void
self := self + other
MODIFY METHOD subBig(REFERENCE FloatBigInt other) RETURNS void
self := self - other (precondition: self >= other)
FloatToDecimalkernel/src/FloatToDecimal.ev:22
Methods
METHOD float64Parts(float64 v) RETURNS | DecimalParts
METHOD float32Parts(float32 v) RETURNS | DecimalParts
NumberToDecimalkernel/src/NumberToDecimal.ev:15
Methods
METHOD numberParts(number v) RETURNS | DecimalParts
number → decimal parts. An INTEGER subtype is exact (coefficient = store.i, exponent 0); a FLOAT subtype takes the Ryu shortest-decimal route (and so inherits its only failure mode — a non-finite float).
METHOD int128Parts(int128 v) RETURNS | DecimalParts
int128 → decimal parts. Exact when the value fits decimal128's
34 significant digits (|v| < 10^34); a wider value FAILS rather than
silently rounding — the exact-or-fail INTO contract that keeps decimal128
from ever losing precision. coefficient = v directly (int128 → int128).
METHOD uint128Parts(uint128 v) RETURNS | DecimalParts
uint128 → decimal parts. Exact when < 10^34; wider FAILS. The magnitude (< 2^113, so it fits a positive int128) is reassembled into the signed coefficient from its 64-bit halves — there is no uint128→int128 operator, and the low half is halved-then-doubled so the int64 reinterpret never goes negative (the DecimalCodec.bidToParts shape).
METHOD complexParts(complex v) RETURNS | DecimalParts
complex → decimal parts. A complex projects onto a real decimal128 only
when its imaginary part is zero (there is no ordering or real embedding of
a genuinely-complex value); otherwise FAILURE. The real part is a number,
so it routes through numberParts.
CharClassifierkernel/src/CharClassifier.ev:17
Methods
METHOD isAlpha(char32 c) RETURNS boolean
METHOD isDigit(char32 c) RETURNS boolean
METHOD isAlnum(char32 c) RETURNS boolean
METHOD isSpace(char32 c) RETURNS boolean
METHOD isUpper(char32 c) RETURNS boolean
METHOD isLower(char32 c) RETURNS boolean
FloatingDecimal32kernel/src/structs.ev:57
Fields
uint32 mantissaint32 exponentFloatingDecimal64FloatingDecimal64 / FloatingDecimal32 — the shortest-decimal carriers
produced by FloatFormat's d2d / f2d core methods. Each holds the
decimal mantissa as an unsigned integer plus the decimal exponent
(so the represented value is mantissa * 10^exponent). Reserved
exponent sentinels in the 0x7FFFxxxx range encode IEEE-754 special
cases (nan / ±inf / -0) — see FloatFormat.float64toDecimal.
kernel/src/structs.ev:52
Fields
uint64 mantissaint32 exponentPow5EntryPow5Entry — one 128-bit fixed-point pow5 magic constant, split into
its low and high 64-bit halves. Used by FloatFormat's small-table
Ryu path: DOUBLE_POW5_SPLIT2 and DOUBLE_POW5_INV_SPLIT2 are sequences
of these, and double_computePow5 / double_computeInvPow5 build one
on demand for arbitrary indices. Order matches Ryu's uint64_t mul[2]
convention — .lo is the low half, .hi is the high half.
kernel/src/structs.ev:78
Fields
uint64 louint64 hiCasualRandomIMPLEMENTS Random
A fast, OS-seeded Random for games, sampling, jitter, and other non-reproducible, non-security uses. Seeds an xoshiro256** engine once at construction from operating-system entropy; thereafter it is a pure (fast) PRNG. NOT reproducible (the seed is fresh each time) and NOT for secrets — use SecureRandom for tokens/keys.
Thread-affine (see the Random interface note): not a SHARED CLASS.
kernel/src/CasualRandom.ev:26
Constructors
INIT()
Methods
MODIFY METHOD nextInt(int64 bound) RETURNS int64
MODIFY METHOD nextUInt128() RETURNS uint128
MODIFY METHOD nextFloat() RETURNS float64
MODIFY METHOD nextBoolean() RETURNS boolean
SecureRandomIMPLEMENTS Random
A cryptographically-secure Random drawing fresh operating-system entropy on every call (getentropy via the native shim). For tokens, session identifiers, salts, and keys. Not a PRNG: there is no seed and no reproducibility. INIT raises RandomError if the OS entropy source is unavailable.
Thread-affine (see the Random interface note): not a SHARED CLASS.
kernel/src/SecureRandom.ev:26
Constructors
INIT()
Methods
METHOD boundedSecure(uint64 bound) RETURNS uint64
Uniform unsigned in [0, bound) over fresh entropy — the same 128-bit Lemire rejection as the PRNG path, but each draw pulls new OS entropy rather than advancing a seeded engine. Assumes bound >= 1.
MODIFY METHOD nextInt(int64 bound) RETURNS int64
Uniform in [0, bound) over fresh entropy. bound <= 0 PANICs.
The former nextLong; see Xoshiro256.nextInt for why the two collapsed.
A checked r AS int64 was tried here and its ELSE branch had nothing to
put in it, because the draw cannot reach the upper half of uint64:
bound > 0 by the guard, so b <= INT64_MAX, and boundedSecure returns
Lemire-uniform in [0, b) — the value is bounded BY an int64 and is
therefore always one. An UNREACHABLE! in that branch would be honest but
would still be a branch written for a statically-impossible case, which is
what the unchecked, NAMED helper exists to avoid. toInt64 states the
crossing in one line and is exact for every value this can produce.
MODIFY METHOD nextUInt128() RETURNS uint128
MODIFY METHOD nextFloat() RETURNS float64
MODIFY METHOD nextBoolean() RETURNS boolean
SeededRandomIMPLEMENTS Random
A deterministic Random seeded from a developer-supplied int64. Same seed → same sequence, across runs and platforms (xoshiro256** + splitmix64 are fixed algorithms). For reproducible simulations, tests, and property-based testing.
Thread-affine (see the Random interface note): not a SHARED CLASS, so it
cannot be shared across threads; move it if a task needs sole ownership.
kernel/src/SeededRandom.ev:19
Constructors
INIT(int64 seed)
Methods
MODIFY METHOD nextInt(int64 bound) RETURNS int64
MODIFY METHOD nextUInt128() RETURNS uint128
MODIFY METHOD nextFloat() RETURNS float64
MODIFY METHOD nextBoolean() RETURNS boolean
ShuffleableThe interface a shuffleable collection implements. shuffle(rng) reorders the collection in place into a uniformly-random permutation, drawing index choices from the supplied Shuffler. Array[T] implements it (Fisher-Yates); any future ordered collection can too.
Same element bound as Array: T is a Cloneable class or a non-boolean primitive (the swap clones / moves elements through the backing storage).
kernel/src/Shuffleable.ev:20
Methods
MODIFY METHOD shuffle(MUTABLE REFERENCE Shuffler rng) RETURNS void
Reorder in place into a uniformly-random permutation, drawing from
rng. MODIFY — mutates the collection; rng is a MUTABLE REFERENCE
because every draw advances its state.
RandomRandom — the full random / pseudo-random surface, extending
Shuffler with wider-range, 128-bit, float, and boolean draws.
Implemented by CasualRandom (fast, OS-seeded), SeededRandom
(deterministic from a developer seed), and SecureRandom (OS
entropy). A Random instance is thread-affine: it is not a
SHARED CLASS, so it cannot be shared across a thread boundary — a
non-owning capture into a PARALLEL body is rejected, while a
sole-ownership move is permitted and data-race-safe.
kernel/src/interfaces.ev:890
Methods
MODIFY METHOD nextUInt128() RETURNS uint128
A full-width 128-bit random value (two engine draws).
MODIFY METHOD nextFloat() RETURNS float64
Uniform random float64 in [0, 1) (53-bit mantissa).
MODIFY METHOD nextBoolean() RETURNS boolean
Uniform random boolean (the engine's top bit).
ShufflerShuffler — the narrow random-source capability: a single bounded
integer draw. Consumers that only need to pick an index (e.g.
Array.shuffle) depend on this, not the full Random surface.
kernel/src/interfaces.ev:874
Methods
MODIFY METHOD nextInt(int64 bound) RETURNS int64
Uniform random integer in [0, bound). bound <= 0 raises
RandomError. MODIFY because drawing advances generator state.
The hashers behind the dictionaries and sets.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
HasherHasher
Distinct in shape from Hashable: Hashable is "this type knows how
to hash itself" (hash() on SELF); Hasher OF K is "this object
knows how to hash values of type K" (hash(K key) on a separate
hasher instance). The latter is the contract for pluggable hashing —
a Dictionary / Set may be constructed with a custom Hasher, and when
none is supplied the impl constructs a kernel default that delegates
to the key's own Hashable.hash().
Implementations should be:
- Deterministic: equal K values per Equatable[K] produce
equal hashes. Calling hash() twice with the same key yields
the same result. The reference checker relies on this: it accepts
a remove(k) as releasing what insert(k, …) stored (I.I.v(e)),
which holds only if the same key finds the same entry.
- Pure: no observable side effects, no I/O, no mutation of
SELF or any reachable state.
- Well-distributed for the K-set actually used as keys.
See: interfaces.ev → Hashable; HashConstants.ev → FNV-1a constants.
Hasher OF K — pluggable hash-function interface for Dictionary
keys and Set elements. Supply a custom implementation at
construction to override the default (which hashes via the key's
own Hashable.hash()).
EXTENDS Cloneable — a dictionary's copy must hash with the same hasher,
so every clone DUPLICATEs it (a keyed SipHasher re-seeded in the copy
would lose the caller's DoS protection). Implementations name
only Hasher OF K: a redundant explicit Cloneable would be a second
C++ base.
kernel/src/Hasher.ev:46
Methods
METHOD clone() RETURNS Hasher[K]
METHOD hash(REFERENCE K key) RETURNS uint64
The key is BORROWED, not taken. A bare K key parameter is a
type-parameter param, which emits by value — so every call site
materialises an owned K (_ev_duplicate) just to compute a hash.
Hashing only reads, so it borrows.
DefaultHasherIMPLEMENTS Hasher
DefaultHasher implements Hasher OF K (Hasher.ev) for every legal key type in one
class. A Dictionary / Set constructed without an explicit hasher
CREATEs one of these.
TWO HASHING PATHS, selected at compile time on K's kind:
K IMPLEMENTS Hashable (String + user classes that declare it):
delegate to the key's own hash(). The WHEN K IMPLEMENTS Hashable
gate narrows K to a class, so key->hash() reaches THROUGH the
_ev_unique<K> handle to the real method. (A bare ELSE would not
narrow, and key->hash() would hit the handle, which has no
hash() member — this is why the class path MUST be guarded.)
everything else (numeric primitives + char): FNV-1a mix of the
value reduced to a uint64, then FNV-1a mixed. That reduction is a
WIDENING for integers and char (exact — a char widens its code
point) but it must NOT be one for a float: widening truncates the
mantissa, so distinct values would collide. A float therefore takes
its own arm and is hashed over its exact binary64 BITS, with -0.0
folded onto 0.0 so that IEEE-equal keys hash alike
(NumericUtilities.floatHashBits).
Primitives are NOT IMPLEMENTS Hashable (they are Hashable at the
type level only — there is no callable .hash()), so they fall to
this branch correctly.
Note: a specific-width gate like WHEN K IS float64 is illegal —
E1104 only admits IS PRIMITIVE / IS Numeric / IS <class> /
IS <group> as kinds, not individual primitive widths. Hence
WHEN K IS Floating, a GROUP over both float widths (interfaces.ev),
which is admitted where a bare width is not.
See: Hasher.ev (the interface), HashConstants.ev (FNV-1a constants),
interfaces.ev → Hashable.
DefaultHasher OF K — universal kernel hasher. Delegates to the key's
own hash() when K is Hashable (String, user classes); FNV-mixes the
widened value for numeric / char keys.
kernel/src/DefaultHasher.ev:49
Constructors
INIT()
Methods
METHOD clone() RETURNS DefaultHasher[K]
Hasher EXTENDS Cloneable — every dictionary DUPLICATEs its hasher when cloned. Stateless, so a fresh instance is an exact copy.
METHOD hash(REFERENCE K key) RETURNS uint64
StringHasherIMPLEMENTS Hasher
A non-parametric Hasher OF String. Functionally identical to DefaultHasher[String] (both delegate to String.hash()), but provided as a concrete named type so the canonical spelling
Dictionary[String, V, StringHasher]
reads naturally and the docs have a concrete hasher to point at.
See: Hasher.ev (the interface), DefaultHasher.ev (the universal hasher),
String.ev → hash().
StringHasher — Hasher OF String delegating to String's own FNV-1a
hash(). The default hasher for String-keyed Dictionary / Set.
kernel/src/StringHasher.ev:25
Constructors
INIT()
Methods
METHOD clone() RETURNS StringHasher
Stateless, so a fresh instance is an exact copy.
METHOD hash(REFERENCE String key) RETURNS uint64
SipHasherIMPLEMENTS Hasher
A DoS-resistant Hasher OF K backed by SipHash-2-4-64. Keyed by a process-global 16-byte secret (EV_siphash_native.hpp, seeded once from OS entropy), so an attacker cannot predict bucket distribution (hash-flooding defense). The default hasher inside ProHashDictionary; opt-in elsewhere as Dictionary[K, V, SipHasher[K]] / Set[V, SipHasher[V]].
hash() — the 64-bit SipHash-2-4 digest. (Formerly this class also exposed a 128-bit digest; the 128-bit half was removed because nothing consumed it — ProHashDictionary stores and keys on the low 64 bits — so computing it was pure waste. See benchmarks/s04_dict/envzn_siphash_opt for the measurement.)
A String key is absorbed as its raw UTF-8 bytes (via a ByteBuffer). A primitive key is absorbed as the eight bytes of its widened value, mirroring DefaultHasher's primitive path.
kernel/src/SipHasher.ev:31
Constructors
INIT()
The DEFAULT — canonical SipHash-2-4, keyed from OS entropy.
INIT(SipVariant v)
Opt in to the SipHash-1-3 round schedule (a third fewer rounds; the schedule Rust ships). Still keyed from OS entropy. 1-3 is a WEAKER PRF than 2-4 — choosing it is a security decision, not a performance one. See SipVariant.
INIT(uint64 key0, uint64 key1)
Adopt an explicit key — used by clone(), and available when a caller needs a REPRODUCIBLE digest (a fixed key hashes deterministically across runs).
INIT(uint64 key0, uint64 key1, SipVariant v)
Methods
METHOD clone() RETURNS SipHasher[K]
Hasher EXTENDS Cloneable — every dictionary DUPLICATEs its hasher when cloned. The clone MUST carry the SAME key AND the same variant: re-seeding (or re-scheduling) here would make the clone disagree with the entries the cloned dictionary copied over, and every lookup in the copy would miss.
METHOD roundSchedule() RETURNS SipVariant
Which round schedule this hasher runs.
METHOD hashSlice(REFERENCE binary[] buf, int64 off, int64 len) RETURNS uint64
SipHash-64 over a RAW BYTE SLICE buf[off .. off+len) — the fast byte path, and
the one byte-keyed callers (StringKeyedDictionary / ProHashDictionary) should use.
This is what hashBuffer below cannot be. It absorbs each 64-bit message word with
ONE System->memoryWord wide load instead of assembling it from eight
bounds-checked per-byte accessor calls, and HOTLOOP hoists the trailing bytes'
per-element bounds check into a single up-front range check. Neither skips a check
— both move it — so the memory-safety floor is unchanged.
METHOD hashBuffer(REFERENCE ByteBuffer bytes) RETURNS uint64
SipHash-64 over a ByteBuffer — the byte-sequence core for the generic Hasher OF K
String path.
This used to assemble each 64-bit word from EIGHT bounds-checked, handle-indirected
bytes[i] accessor calls — the per-element dispatch the s05 study named as the real
bottleneck. It no longer does: ByteBuffer.data() hands back a non-owning REFERENCE
to the raw binary[] storage (zero copy — the buffer keeps ownership), which is
exactly the handle the bulk primitives need. So this now simply delegates to
hashSlice, and the ByteBuffer path gets System->memoryWord + HOTLOOP for free.
One implementation of SipHash over bytes, not two.
METHOD hashWord(uint64 m) RETURNS uint64
SipHash-64 over a single 8-byte word (primitive keys). No byte loop, so none of the bulk-memory levers apply here — this path is pure round arithmetic, and the only lever on it is the round SCHEDULE (SipVariant).
METHOD hash(REFERENCE K key) RETURNS uint64
Hasher OF K — the 64-bit SipHash-2-4 digest.
SipStateThe SipHash-2-4 compression/finalization state: four 64-bit words mixed by the SipRound. INTERNAL engine driven by SipHasher; one transient instance per hash call.
A VALUE CLASS (§I.J.vi): value identity + inline storage, so a
SipState st := CREATE SipState(...) local lives on the stack with no
_ev_unique heap handle — no per-hash malloc/free. (It was formerly an
INTERNAL heap class, which cost a heap allocation on every hash call — the
dominant hasher overhead; see benchmarks/s04_dict/envzn_siphash_opt.)
Runs in 64-bit-output mode: SipHash-2-4-64 (the digest a Hasher.hash()
needs). The 128-bit second-half machinery was removed — nothing consumed it
(ProHashDictionary stores and keys on the low 64 bits), so computing it was
pure waste.
Reference: Aumasson & Bernstein, "SipHash: a fast short-input PRF" (2012), SipHash-2-4 (c = 2 compression rounds, d = 4 finalization rounds).
kernel/src/SipState.ev:29
Fields
uint64 v0uint64 v1uint64 v2uint64 v3Constructors
INIT(uint64 k0, uint64 k1)
Methods
METHOD rotl(uint64 x, int32 b) RETURNS uint64
MODIFY METHOD round() RETURNS void
One SipRound.
MODIFY METHOD absorb(uint64 m) RETURNS void
Absorb one 64-bit message word (c = 2 compression rounds).
MODIFY METHOD finalize64() RETURNS uint64
The 64-bit digest (d = 4 finalization rounds), canonical SipHash-2-4-64.
MODIFY METHOD absorbFast(uint64 m) RETURNS void
Absorb one message word with c = 1 (SipHash-1-3).
MODIFY METHOD finalizeFast64() RETURNS uint64
The 64-bit digest with d = 3 (SipHash-1-3).
FastIntHasherIMPLEMENTS Hasher
FastIntHasher implements Hasher OF K (Hasher.ev) with an IDENTITY hash: the key widened into
a uint64, no mixing. For integer keys this maps the benchmark's sequential keys
(0..N-1) to sequential slots under the pow2 & mask index, so every probe is a
cache-friendly prefetch — the ~1.5 ns/lookup path that C and C++ take (their
std::hash<int> is also identity). char widens its code point. The WordKey
qualifier admits no float, so nothing is reinterpreted here; a 128-bit key keeps
its low half, which collides only above bit 63 and is separated on lookup by
Equatable.
The tradeoff is adversarial weakness: an attacker who controls the keys can force
collisions (which is why Rust/Swift default to a slow keyed SipHash). FastIntHasher
is therefore OPT-IN — the default stays DefaultHasher (FNV), and untrusted keys
use SipHasher / ProHashDictionary. It slots into the existing H type
parameter, so it is zero dictionary-API change: a caller writes
Dictionary[int32, V, FastIntHasher[int32]] when the keys are trusted integers.
Constrained to WordKey — the primitives whose value IS an integer bit pattern
(identity on a class key is meaningless, and a float's bits are not its value): a
primitive is Hashable at the type level, so it satisfies the Hasher OF K bound
without the IMPLEMENTS Hashable class path that DefaultHasher needs.
See: Hasher.ev (the interface), DefaultHasher.ev (the FNV default), SipHasher.ev
(the keyed DoS-resistant hasher).
FastIntHasher OF K — identity hasher (widened key) for trusted primitive keys.
The ~1.5 ns C-class path; opt in via the dictionary's H slot.
kernel/src/FastIntHasher.ev:38
Constructors
INIT()
Methods
METHOD hash(REFERENCE K key) RETURNS uint64
METHOD clone() RETURNS FastIntHasher[K]
Stateless — a fresh instance behaves identically. Cloneable so a dictionary
that stores the hasher CONCRETELY (H hasher, monomorphised) can deep-copy
itself (clone()) by cloning its hasher.
InlineIntHasherIMPLEMENTS Hasher
Identical hash to FastIntHasher (the key widened into uint64, no mixing), but a VALUE CLASS rather than a regular CLASS. A VALUE CLASS stored as the concrete type parameter H hasher lives INLINE in the dictionary, so -O3 inlines the identity hash and the whole lookup chain collapses to C-class code.
Because a value class cannot be boxed behind a Hasher OF K interface handle in V1
(E1133), InlineIntHasher is used ONLY where the hasher is stored concretely (the H
type parameter) — i.e. IntKeyedDictionary. The interface-handle dictionaries
(ChainedHashDictionary / ProHashDictionary) keep using the regular-class FastIntHasher.
InlineIntHasher OF K — VALUE-CLASS identity hasher (widened key). Stored inline as
a concrete H, so the hash inlines. The monomorphised C-class path for trusted
integer keys; opt in via IntKeyedDictionary's H slot. The K IS BLITTABLE
qualifier forces every instantiation blittable, so the value class earns its
ev_is_blittable partial-spec and lowers to inline (value-array) storage — the
blittable-qualifier rule (ENVZN_CONSTITUTION I.J: a generic value class whose
TEMPLATE qualifier forces every type param blittable earns the trait).
kernel/src/InlineIntHasher.ev:36
Constructors
INIT()
Methods
METHOD clone() RETURNS void
METHOD hash(REFERENCE K key) RETURNS uint64
HashConstantsA stateless utility namespace (like Math) holding the
FNV-1a magic numbers that the Hashable kernel types reach into when
building their hash() implementations.
Lives in its own file because interfaces.ev may only hold INTERFACE
/ GROUP / STRUCT declarations (E9003), and a SINGLETON CLASS is
neither — so it cannot be co-located with the Hashable / Hasher
contracts it serves.
CONSUMERS
String, ByteBuffer, DynamicString, DynamicByteBuffer, DateTime,
TimeDuration — all reference these from their own hash() /
the 32-bit hash bodies that use them.
The 32-bit offset basis is stored in signed form because Envzn
int64 cannot hold the unsigned 0x811C9DC5. Callers BXOR with
byte values, so the bit pattern is what matters; the signed
interpretation is incidental.
See: http://www.isthe.com/chongo/tech/comp/fnv/
HashConstants — a NAMESPACE holding the FNV-1a hash-algorithm constants (offset basis + prime, in 64-bit and 32-bit forms) and the prime bucket-count ladder the chained hash dictionary grows through. Merged from the former HashConstants (FNV) + HashPrimes (ladder).
kernel/src/HashConstants.ev:39
Fields
uint64 FNV_OFFSET_BASIS_64uint64 FNV_PRIME_64int32 FNV_OFFSET_BASIS_32int32 FNV_PRIME_32int64 SIZES_LENint64 SIZESint64 POW2_MAX_LEVELint64 SHALLOW_PRIMES_LENint64 SHALLOW_PRIMESMethods
METHOD initialBucketCount() RETURNS int64
Bucket count for growth level 0 (the initial table size).
METHOD bucketCountAtLevel(int64 level) RETURNS int64
Bucket count at level, clamped to the ends of the ladder. Past
the top prime the table stops growing (V1 cap ~196k buckets).
METHOD canGrow(int64 level) RETURNS boolean
TRUE while there is a larger prime to grow into.
METHOD pow2CountAtLevel(int64 level) RETURNS int64
Power-of-two bucket count at level — 16 << level, clamped to the cap.
METHOD indexForHash(uint64 hash, int64 count) RETURNS int64
Bucket index for hash given a power-of-two count: hash & (count - 1).
The low bits carry the masked index, so truncating the uint64 hash to int64
first (the mask < 2^31 keeps the result in [0, count)) avoids an int→uint
sign-cross while preserving every bit the mask reads.
METHOD mulShiftIndex(uint64 hash, uint64 mult, int64 shift) RETURNS int64
(mult * hash) >> shift — the top 64-shift bits of the product mix ALL
input bits (unlike the low-bit mask above), so it distributes a
well-mixed hash without a mod. mult is an odd 64-bit constant chosen
key-set-aware; shift = 64 - log2(capacity).
METHOD primeAtLeast(int64 target) RETURNS int64
Smallest ladder prime >= target (clamped to the top prime).
METHOD primeModIndex(uint64 hash, uint64 mult, uint64 p) RETURNS int64
(mult * hash) % p — the prime-mode index (fallback tier).
SipVariantSipVariant — which SipHash round schedule a SipHasher runs.
STRONG_2_4 (the DEFAULT) is canonical SipHash-2-4: two compression rounds per message word, four finalization rounds. It is the conservative choice and what SipHash's authors specify for general keyed hashing.
FAST_1_3 is SipHash-1-3: one compression round, three finalization — a third fewer rounds, and the schedule Rust ships in its default HashMap. It is still considered adequate against hash-flooding, but it IS a weaker PRF than 2-4, so it is opt-in and never the default: choosing it is a security decision, not a performance one.
kernel/src/enums.ev:224
| Case | Description |
|---|---|
? |
— |
? |
— |
The error classes the kernel throws.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
ErrorAbstract base class for the kernel error hierarchy.
Every kernel error class extends Error (directly or
transitively). User-defined error classes in consumer modules
also extend Error to participate in RECOVER dispatch. The base
class carries a single message field; subclasses add their own
fields as needed (see ErrorTypes.ev for the kernel-shipped
concrete classes).
────────────────────────────────────────────────────────────────── PANIC / RECOVER semantics ──────────────────────────────────────────────────────────────────
Every Error instance can be raised in a PANIC. RECOVER clauses match by class type (and any subclass of the matched type — covariant). The base class will recover from any panic:
TRY {
doWork()
} RECOVER (FileError fe) {
logError(fe->message())
} RECOVER (Error e) {
// any error not handled above
logError("unhandled: $1")->format(e->message())
}
The matching order is top-to-bottom; subclass clauses must precede their superclasses to be reachable.
────────────────────────────────────────────────────────────────── C++ INTEROP ──────────────────────────────────────────────────────────────────
At the C++ layer, Error extends std::exception so kernel
errors propagate cleanly through any C++ stack frame the runtime
traverses (FOREIGN-call-raising, runtime panics, etc.).
kernel/src/Error.ev:49
Fields
int32 codeint32 line_numberConstructors
INIT()
INIT(char32[] message)
INIT(REFERENCE String message)
Bridge from a String arg — copy the source's code points
into this .msg. The per-subclass INIT(String message)
pattern uses SUPER(message) which routes here.
INIT(REFERENCE String message, REFERENCE String cause)
Chaining INIT — set both the message and the triggering error's
message as the cause. Errors are chained by passing a triggering
error's message as the cause of a new one (I.M.ii). A subclass that
wants to expose chaining declares its own INIT(String, String) and
routes here with SUPER(message, cause).
INIT(REFERENCE String message, REFERENCE String cause, int32 code)
Chaining INIT with an explicit numeric code.
Methods
METHOD hasCause() RETURNS boolean
Whether a triggering cause is attached (I.M.ii).
METHOD getErrorCode() RETURNS int32
The numeric error code; 0 means "no code" (I.M.ii).
METHOD message() RETURNS String
What went wrong, as the PANIC site's INIT set it.
METHOD cause() RETURNS String
The triggering error's message, or empty when there is none (I.M.ii).
METHOD filename() RETURNS String
The source file of the PANIC site, injected by the compiler.
METHOD threadName() RETURNS String
The raising thread's name, or empty for an unnamed context.
CompileErrorEXTENDS Error
Kernel error class. Raised by tooling that performs compilation at runtime (the self-hosted Envzn compiler, opaque-evaluation helpers). Not expected to be raised by ordinary application code, but reserved as a kernel type so compiler-using modules don't have to invent their own.
Subclass of Error; adds no new fields.
kernel/src/CompileError.ev:23
Constructors
INIT(REFERENCE String message)
FileErrorEXTENDS Error
Kernel error class. Thrown by File / Path methods on I/O failure. Examples: file not found, permission denied, disk full, directory creation failed, recursive remove encountered an undeletable entry.
Subclass of Error; adds no new fields — the type name itself is the discriminant for RECOVER dispatch.
kernel/src/FileError.ev:19
Constructors
INIT(REFERENCE String message)
IndexOutOfBoundsErrorEXTENDS Error
Kernel error class. Raised by every collection's bounds check
(Array.at / Array.setAt / Array.insertAt / Array.remove, LinkedList.insertAt,
removeAt, etc.). The message field typically encodes the offending index
and the collection's length at PANIC time; format follows the pattern
"index $1 out of bounds for length $2".
Subclass of Error; adds no new fields.
kernel/src/IndexOutOfBoundsError.ev:24
Constructors
INIT(REFERENCE String message)
MathErrorEXTENDS Error
Kernel error class. Thrown by Math singleton methods on domain errors and by the checked-arithmetic helpers (Math.checkedAdd, etc.) on overflow. Examples: square root of a negative real, log of a non-positive value, integer-overflow on a checked op.
Subclass of Error; adds no new fields.
kernel/src/MathError.ev:19
Constructors
INIT(REFERENCE String message)
NetworkErrorEXTENDS Error
Historical kernel-side placeholder. The production NetworkError class lives in the Networking module (Networking/NetworkError.ev) where it belongs alongside the rest of the network-protocol error surface. This kernel-side declaration exists for C++ ABI symmetry with ENVZN.hpp.
Subclass of Error; adds no new fields.
kernel/src/NetworkError.ev:19
Constructors
INIT(REFERENCE String message)
EmptyHandleErrorEXTENDS Error
Raised when a handle is used while it holds nothing.
Two places raise it. The _UnsafeHandle<T>::operator->() and get()
safety wrapper raises it (no message) when an UNSAFE.* handle is
dereferenced while null. Kernel code raises it (with a message) from a
guard that refuses to read a value it knows was moved out — CollisionNode's
valid flag. Recover from the PANIC in user code via
TRY { ... } RECOVER (EmptyHandleError e) { ... }, like any kernel Error.
Subclass of Error; adds no new fields. The probe at
kernel_probe/unsafe_safety_wrapper/ validated that the raised PANIC
unwinds across the FFI boundary and Envzn TRY/RECOVER recovers by
class identity.
kernel/src/EmptyHandleError.ev:25
Constructors
INIT()
INIT(REFERENCE String message)
With a message naming the handle that was empty.
RandomErrorEXTENDS Error
Kernel error class for the Random surface. Thrown by SecureRandom when OS entropy is unavailable, and by the generators on a non-positive bound (nextInt(bound <= 0)).
Subclass of Error; adds no new fields.
kernel/src/RandomError.ev:17
Constructors
INIT(REFERENCE String message)
OutOfMemoryErrorEXTENDS ResourceExhaustedError
Kernel error class. Raised when the runtime allocator cannot get a block; the message
is "out of memory allocating
Subclass of ResourceExhaustedError; adds no new fields.
kernel/src/OutOfMemoryError.ev:24
Constructors
INIT(REFERENCE String message)
ResourceExhaustedErrorEXTENDS Error
Kernel error class. The parent of every error that means the program ran
out of a finite resource (memory, the stack) rather than did something wrong.
RECOVER (ResourceExhaustedError e) handles all of them.
Subclass of Error; adds no new fields.
kernel/src/ResourceExhaustedError.ev:20
Constructors
INIT(REFERENCE String message)
CloneErrorEXTENDS Error
Raised when clone() is asked to copy a value that has no copy.
One place raises it today: clone() of an opaque that carries a C
handle (a FOREIGN_TYPE pointer such as a sqlite3_stmt*). A C object
has one owner, and copying the pointer would make two, one of which frees
it under the other (I.D.v (c)). Keep one owner and lend it with
REFERENCE. Raised from the kernel's opaque runtime, which is where the
box knows what it carries; caught like any kernel Error, with
TRY { ... } RECOVER (CloneError e) { ... }.
kernel/src/CloneError.ev:21
Constructors
INIT(REFERENCE String message)
LensMismatchErrorEXTENDS Error
Kernel error class. Raised when a checked narrowing (:= or =@ from a parent or interface type to a narrower one) finds the object's class is not the one named. The message names both types.
Subclass of Error; adds no new fields.
kernel/src/LensMismatchError.ev:19
Constructors
INIT(REFERENCE String message)
SeverityPer the ENVZN module convention, this single file holds the constitution's reserved enums. They're small (2–3 cases each) so grouping them in one file matches the pattern used for STRUCTs and INTERFACEs.
Each enum is referenced by name from the constitution and/or
standard library:
- DeliveryMode — used by CHANNEL[T]->send_message() to
specify how a message reaches subscribers.
- Severity — used by logging APIs and the constitution's
Compiler-Error-Strategy spec to grade diagnostic levels.
- Build — used by WHEN_BUILD conditional compilation
to switch on debug-vs-release at compile time.
Severity — diagnostic and logging level. Ordered (informally)
from least to most serious. Consumers can compare ordinally
via the implicit enum order.
Spec reference: §17 mentions ENVZN::Severity.WARNING for
compiler-driven diagnostics; user-side logging follows the
same enum.
kernel/src/enums.ev:39
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
DataValue, the dynamic value behind JSON serialisation, and opaque.
Generated by
bin/build_library_doc.pyfrom the kernel sources. Do not edit by hand: change the generator, or the doc comments inkernel/src/, and re-run it.
DataValueIMPLEMENTS Serializable, Cloneable
The kernel's neutral, format-independent value model — the abstract shape shared by JSON, BSON, CBOR, MessagePack and DB rows — as a whole DOCUMENT in one object (the two-layer cake, ENVZN_USER_GUIDE §2e): a storage layer of primitive arrays, and the public face composed over it. No object per node: no DataValue, String, Dictionary or frame per value. Ported from benchmarks/s09_json/envzn_newJson (serde-explicit-codecs design §6).
Storage:
nodes every node, a tagged slot (DataNode, structs.ev); a node is its
int64 index
items an array's elements, one contiguous run per array
keys / vals an object's members, one contiguous run per object: the member's
interned key id and its value node
bytes every string value, UTF-8, as (offset, length) windows
kOff / kLen / the interned keys — each distinct key stored ONCE in kBytes and
kHash / found through an open-addressed hash (slots); a member lookup
kBytes / slots compares integer ids, not bytes
Face: the reading surface, with the node as an explicit argument — a document
cannot hand out handles to itself, so the caller holds the document and passes
node indices. root() is where a walk starts (-1 for an empty document).
kind(v), isNull(v) … isObject(v) — the node's kindasBool(v), asNumber(v), asString(v) — by value, (T | STATUS)asStringBytes(v) + bytesRef() — the string as a UTF-8 windowcount(v), element(a, i), lookupReference(o, key) — containersAn object keeps every member in the order it was written, duplicate keys
included; lookupReference finds the FIRST. An integer past int64 is its own
node kind (JUINT) and reads back as an UNSIGNED number.
Built by DataValueBuilder through the INTERNAL MODIFY methods below (kernel only);
read by anyone through the face; walked into any Serializer by serialize(), or
pulled from by DataValueReader (a Reconstructor).
kernel/src/DataValue.ev:47
Constructors
INIT()
INIT(int64 sizeHint)
Methods
METHOD clone() RETURNS DataValue
METHOD root() RETURNS int64
METHOD kind(int64 v) RETURNS DataKind
METHOD isNull(int64 v) RETURNS boolean
METHOD isBool(int64 v) RETURNS boolean
METHOD isNumber(int64 v) RETURNS boolean
METHOD isString(int64 v) RETURNS boolean
METHOD isArray(int64 v) RETURNS boolean
METHOD isObject(int64 v) RETURNS boolean
METHOD asBool(int64 v) RETURNS | boolean
METHOD asNumber(int64 v) RETURNS | number
METHOD asStringBytes(int64 v) RETURNS | int64
METHOD bytesRef() RETURNS REFERENCE binary[]
METHOD asString(int64 v) RETURNS | String
METHOD count(int64 v) RETURNS | int64
METHOD element(int64 a, int64 i) RETURNS | int64
METHOD lookupReference(int64 o, REFERENCE String key) RETURNS | int64
METHOD serialize(MUTABLE REFERENCE Serializer s) RETURNS STATUS
METHOD serializeNode(int64 v, MUTABLE REFERENCE Serializer s) RETURNS STATUS
DataValueBuilderIMPLEMENTS Serializer
The document Serializer backend (ported from benchmarks/s09_json/envzn_newJson, serde-explicit-codecs design §6).
No frame object per container: one shared scratch stack. A container notes its base; its children are pushed as they arrive (array: one entry per element; object: key id, value); at its end they pop back into the document's pools — last first, so each lands at its final slot — until the scratch is back at base.
The typed events (putInt64 / putUint64 / putFloat64) store their node
directly, and the byte events (putStringBytes / putKeyBytes) copy their window
straight into the document's pools; the String forms encode to UTF-8 first.
result() hands back a copy and keeps the builder; takeResult() MOVES the
document out and leaves the builder empty.
kernel/src/DataValueBuilder.ev:29
Constructors
INIT()
INIT(int64 sizeHint)
Methods
MODIFY METHOD putInt64(int64 v) RETURNS STATUS
MODIFY METHOD putUint64(uint64 v) RETURNS STATUS
MODIFY METHOD putFloat64(float64 v) RETURNS STATUS
MODIFY METHOD putNull() RETURNS STATUS
MODIFY METHOD putBool(boolean v) RETURNS STATUS
MODIFY METHOD putNumber(number v) RETURNS STATUS
MODIFY METHOD putStringBytes(REFERENCE binary[] src, int64 off, int64 len) RETURNS STATUS
MODIFY METHOD putString(REFERENCE String v) RETURNS STATUS
MODIFY METHOD putKeyBytes(REFERENCE binary[] src, int64 off, int64 len) RETURNS STATUS
MODIFY METHOD putKey(REFERENCE String key) RETURNS STATUS
MODIFY METHOD beginArray() RETURNS STATUS
MODIFY METHOD beginObject() RETURNS STATUS
MODIFY METHOD endArray() RETURNS STATUS
MODIFY METHOD endObject() RETURNS STATUS
METHOD result() RETURNS | DataValue
MODIFY METHOD takeResult() RETURNS | DataValue
DataValueReaderIMPLEMENTS Reconstructor
The document Reconstructor backend: a non-owning reader over a DataValue document
(the two-layer-cake borrow pattern, like StringView over char32[]). It holds a
REFERENCE DataValue and a position in it, never a copy; the document's lifetime
must enclose the reader's.
Its position is a node: cur, the value the next read consumes (the root, or the
start node it was created at). Opening a container pushes it on a stack of open
containers; nextField / nextElement move cur to the next member value /
element and pop the container after its last. So a read never walks the document
and skipValue costs nothing: the next move steps over whatever cur holds.
nextField(type) matches the member's interned key against the names of type's
reconstructable fields (not DERIVED, not CONSTANT) in place — ASCII names byte for
byte, with no allocation (DataValue.keyIs).
read(sink) pushes the value at cur — the whole document for a fresh reader —
into any Serializer (the walk lives on the document, DataValue.serializeNode).
kernel/src/DataValueReader.ev:29
Constructors
INIT(REFERENCE DataValue doc)
INIT(REFERENCE DataValue doc, int64 start)
Methods
MODIFY METHOD read(MUTABLE REFERENCE Serializer sink) RETURNS STATUS
MODIFY METHOD beginObject() RETURNS STATUS
MODIFY METHOD nextField(REFERENCE Identity type) RETURNS | int32
MODIFY METHOD beginArray() RETURNS STATUS
MODIFY METHOD nextElement() RETURNS | boolean
MODIFY METHOD readNull() RETURNS boolean
MODIFY METHOD readBool() RETURNS | boolean
MODIFY METHOD readInt64() RETURNS | int64
MODIFY METHOD readUint64() RETURNS | uint64
MODIFY METHOD readFloat64() RETURNS | float64
MODIFY METHOD readNumber() RETURNS | number
MODIFY METHOD readString() RETURNS | String
MODIFY METHOD skipValue() RETURNS STATUS
FieldsThe kernel helpers that hold the serde rules (serde-explicit-codecs design §4.2-§4.4),
so a type's serialize / reconstruct is one line per field per direction and the
rules live here, not in every codec.
THE SLOT. Every method numbers a type's fields the way Reconstructor.nextField(type)
does: the field's position in type.dataFields, every field counted. Which fields
travel is the WRITER's decision, settled where the codec is written: a DERIVED or
CONSTANT field is never written (I.P.d), and a reader only matches the keys the
stream holds, so neither side asks per key. A key naming a field that never travels
reaches the codec's unknown arm. IDENTITY(T) is read in place, which costs nothing.
THE SEEN-SET. A reconstruct marks each slot it read; complete then fails in
STRICT for the first travelling field never marked (I.P k.i). Up to 64 slots the set
is one int64 (mark / complete); past that it is an int64[] (markWide /
completeWide). A negative index (UNKNOWN_FIELD) marks nothing, so a codec can
mark after every arm.
THE CELLS. A type with no native document shape travels encoded (I.P.i): a
ByteBuffer as a base64 string (Base64Codec), a DateTime as text in
DATE_TIME_PATTERN. An enum travels as the pair {"name", "value"} (I.P.j) and
reads back name first, then value, through EnumReflection. Each encode is total;
each decode is fallible.
kernel/src/Fields.ev:33
Fields
int32 END_OF_OBJECT — nextField after the object's last member: the object is closed.int32 UNKNOWN_FIELD — nextField on a key the type has no reconstructable field for.String DATE_TIME_PATTERN — The wire form of a DateTime cell.String CONSTANT_MODIFIER — The modifier prefix of a CONSTANT field, which never travels.Methods
METHOD travels(REFERENCE IdentityField field) RETURNS boolean
Does field travel on the wire? Neither DERIVED nor CONSTANT. Asked only by the
STRICT completeness check: a reader matches the keys the stream holds and never asks.
METHOD putKey(MUTABLE REFERENCE Serializer s, REFERENCE Identity type, int32 slot) RETURNS STATUS
Send the key of the field in type.dataFields[slot]. Which fields travel is the
writer's decision, made where the codec is written: the helper only names the key.
METHOD unknown(MUTABLE REFERENCE Reconstructor source, ParseMode mode) RETURNS STATUS
A key the type does not have: skipped in LENIENT, refused in STRICT.
METHOD mark(int64 seen, int32 wire) RETURNS int64
seen with wire field wire marked; a negative index marks nothing.
METHOD complete(int64 seen, REFERENCE Identity type, ParseMode mode) RETURNS STATUS
STRICT: FAILURE naming the first travelling field whose slot seen never marked.
LENIENT: SUCCESS.
METHOD mismatch(REFERENCE String typeName, REFERENCE String fieldName) RETURNS STATUS
The text of a value of the wrong shape for its field (a FAILURE in every mode).
METHOD missingText(REFERENCE String typeName, REFERENCE String fieldName) RETURNS String
"format: in a template $1: reads as a format spec and eats the colon.
METHOD labelled(REFERENCE String head, REFERENCE String message) RETURNS String
"
:METHOD markWide(MUTABLE REFERENCE int64[] seen, int32 wire) RETURNS void
Mark wire field wire in seen[wire / 64], growing seen to fit.
METHOD completeWide(REFERENCE int64[] seen, REFERENCE Identity type, ParseMode mode) RETURNS STATUS
complete over a wide seen-set: a word past the end of seen marks nothing.
METHOD putEnum(MUTABLE REFERENCE Serializer s, REFERENCE Identity enumType, int32 value) RETURNS STATUS
An enum case as the pair {"name": <case name>, "value": <backing integer>}.
METHOD readEnum(MUTABLE REFERENCE Reconstructor source, REFERENCE Identity enumType) RETURNS | int32
The pair back, keys in any order: the name resolves first, else the value;
neither matching, a half of the wrong shape, or any other key is a FAILURE.
The pair is pulled against IDENTITY(EnumKind), whose two fields are exactly
name (wire 0) and value (wire 1).
METHOD putEnumName(MUTABLE REFERENCE Serializer s, REFERENCE Identity enumType, REFERENCE String caseName) RETURNS STATUS
An enum case by NAME, as the pair putEnum writes. Generated AUTO code names
the case it holds; the value comes from IDENTITY(E).cases.
METHOD readEnumName(MUTABLE REFERENCE Reconstructor source, REFERENCE Identity enumType) RETURNS | String
readEnum, answering the resolved case's NAME.
METHOD putDuration(MUTABLE REFERENCE Serializer s, REFERENCE TimeDuration d) RETURNS STATUS
A TimeDuration as its ISO-8601 text (PT1H30M).
METHOD readDuration(MUTABLE REFERENCE Reconstructor source) RETURNS | TimeDuration
ISO-8601 duration text back to a TimeDuration; text that does not parse is a FAILURE.
METHOD putComplex(MUTABLE REFERENCE Serializer s, complex z) RETURNS STATUS
METHOD readComplex(MUTABLE REFERENCE Reconstructor source) RETURNS | complex
The pair back, keys in any order; a missing half is 0, any other key a FAILURE.
METHOD putBytes(MUTABLE REFERENCE Serializer s, REFERENCE ByteBuffer b) RETURNS STATUS
A ByteBuffer as a base64 string.
METHOD readBytes(MUTABLE REFERENCE Reconstructor source) RETURNS | ByteBuffer
A base64 string back to a ByteBuffer; malformed base64 is a FAILURE.
METHOD putDateTime(MUTABLE REFERENCE Serializer s, REFERENCE DateTime d) RETURNS STATUS
A DateTime as text in DATE_TIME_PATTERN.
METHOD readDateTime(MUTABLE REFERENCE Reconstructor source) RETURNS | DateTime
Text in DATE_TIME_PATTERN back to a DateTime; text that does not parse is a FAILURE.
ReconstructableReconstructable — the type-side read contract, the mirror of Serializable.
reconstruct fills SELF from a source: it pulls each field from the
Reconstructor (a nested object reconstructs its child in place), then calls
RESTORE. mode is LENIENT (an unknown key skipped, a missing key defaulted)
or STRICT (either is a FAILURE) — Constitution I.P(k.i). A type that is only
ever written implements Serializable alone.
kernel/src/interfaces.ev:754
Methods
MODIFY METHOD reconstruct(MUTABLE REFERENCE Reconstructor source, ParseMode mode) RETURNS STATUS
ReconstructorReconstructor — a read source, PULLED from. The type asks for its next field
and reads each value at the field's own type, so a typed read converts on the
source's own representation and never builds a number:
beginObject opens the object the reader stands on; nextField(type)
moves to its next member and answers the slot in type.dataFields of the
field the key names (every field counted), Fields.UNKNOWN_FIELD for a key
the type does not have, and
Fields.END_OF_OBJECT after the last member (the object is then closed).
The reader only matches the keys the stream holds. Which fields travel is
the writer's decision: a DERIVED or CONSTANT field is never written, and a
key naming one reaches the codec's unknown arm like any other stray key.beginArray opens an array; nextElement moves to its next element,
FALSE after the last (the array is then closed).readNull is TRUE, and consumes the value, when the value is null.readBool … readString read the value at one type; a value of the
wrong shape for its read is a FAILURE in every mode (I.P k.i): readInt64
on "abc", on 1.5 or on a value past int64.skipValue passes over one whole value, nested containers included.read(sink) is the push form, for a consumer with no type (the DOM
builder, a re-encoder): one whole value, pushed into the sink.kernel/src/interfaces.ev:731
Methods
MODIFY METHOD beginObject() RETURNS STATUS
MODIFY METHOD nextField(REFERENCE Identity type) RETURNS | int32
MODIFY METHOD beginArray() RETURNS STATUS
MODIFY METHOD nextElement() RETURNS | boolean
MODIFY METHOD readNull() RETURNS boolean
MODIFY METHOD readBool() RETURNS | boolean
MODIFY METHOD readInt64() RETURNS | int64
MODIFY METHOD readUint64() RETURNS | uint64
MODIFY METHOD readFloat64() RETURNS | float64
MODIFY METHOD readNumber() RETURNS | number
MODIFY METHOD readString() RETURNS | String
MODIFY METHOD skipValue() RETURNS STATUS
MODIFY METHOD read(MUTABLE REFERENCE Serializer sink) RETURNS STATUS
SerializableSerializable — the type-side write contract. serialize pushes the type's
shape into the serializer (read-only on SELF; the MUTABLE REFERENCE param lets
the sink's MODIFY methods be called).
kernel/src/interfaces.ev:706
Methods
METHOD serialize(MUTABLE REFERENCE Serializer s) RETURNS STATUS
SerializerThe serialization surface (serde-style, format-neutral) — four interfaces
(serde-explicit-codecs design §4.3). A TYPE opts in by implementing
Serializable (write) and/or Reconstructable (read); a FORMAT supplies the
backends — the Json module a JsonWriter (Serializer) and a JsonReader
(Reconstructor) over UTF-8 text, the kernel a DataValueBuilder (Serializer)
and a DataValueReader (Reconstructor) over the DataValue document. The
class names are irrelevant to a type: any Serializer drives the same
serialize, any Reconstructor the same reconstruct.
See Constitution I.P (Serialization and Reconstruction).
(Supersedes the earlier unused binary Serializable {encode()} /
JSON_Serializer {toJson()} stubs, and the push-only Deserializer, whose
deserialize(sink) is Reconstructor.read(sink).)
Serializer — a write sink. A serializable type describes its shape by pushing
a flat event stream into the serializer; the backend decides whether that
becomes bytes (streaming) or a DataValue document. All methods mutate the sink.
Typed number events: putInt64 / putUint64 / putFloat64 carry a number at
its own width, so a sink never builds a number for one; putNumber carries
the rest of the tower.
Byte events: putStringBytes / putKeyBytes carry a string value / key as
UTF-8 in src[off, off + len), UNESCAPED (a reader decodes escapes before the
call). The window is valid only for the duration of the call — a sink that
keeps the text copies it. The String forms stay for a type whose field IS a
String.
kernel/src/interfaces.ev:686
Methods
MODIFY METHOD putNull() RETURNS STATUS
MODIFY METHOD putBool(boolean v) RETURNS STATUS
MODIFY METHOD putInt64(int64 v) RETURNS STATUS
MODIFY METHOD putUint64(uint64 v) RETURNS STATUS
MODIFY METHOD putFloat64(float64 v) RETURNS STATUS
MODIFY METHOD putNumber(number v) RETURNS STATUS
MODIFY METHOD putString(REFERENCE String v) RETURNS STATUS
MODIFY METHOD putStringBytes(REFERENCE binary[] src, int64 off, int64 len) RETURNS STATUS
MODIFY METHOD beginObject() RETURNS STATUS
MODIFY METHOD putKey(REFERENCE String key) RETURNS STATUS
MODIFY METHOD putKeyBytes(REFERENCE binary[] src, int64 off, int64 len) RETURNS STATUS
MODIFY METHOD endObject() RETURNS STATUS
MODIFY METHOD beginArray() RETURNS STATUS
MODIFY METHOD endArray() RETURNS STATUS
DataKindDataKind — the public kind of one node of a DataValue document, the kernel's
neutral, format-independent value model (the abstract shape shared by JSON,
BSON, CBOR, MessagePack, and DB rows): DataValue.kind(v) answers it. The
storage layer's own tag, DataNodeKind, is finer (three number kinds); this is
the shape a reader asks about. Promoted from the Json module's Kind so the
value model is a kernel citizen while wire formats stay in their modules
(Json maps DataValue ↔ text).
kernel/src/enums.ev:259
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
DataNodeKindDataNodeKind — the tag of one DataNode in a DataValue document: the storage
layer's kind. It is finer than the public DataKind (three number kinds, the
width the value was written at); DataValue.kind(v) maps it onto DataKind.
JNULL · JBOOL · JINT (int64) · JUINT (a uint64 past INT64_MAX) · JFLT (float64)
· JSTR · JARR · JOBJ
kernel/src/enums.ev:317
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
ParseModeParseMode — how a Reconstructable.reconstruct treats a document that does not
match the type (I.P(k.i)): LENIENT skips an unknown key and defaults a missing
one; STRICT refuses either. A value of the wrong shape fails in both.
kernel/src/enums.ev:310
| Case | Description |
|---|---|
? |
— |
? |
— |
DataNodeDataNode — one node of a DataValue document: a tag and two integer slots, read
by the tag (a STRUCT stands in for C's union, so the arms share the slots):
k p n d
JNULL - - -
JBOOL 0 / 1 - -
JINT the value - -
JUINT a uint64 past INT64_MAX, its bits (NumericUtilities.toInt64)
JFLT - - the value
JSTR offset into the document's byte byte length -
pool
JARR first slot in items element count -
JOBJ first slot in keys / vals member count -
A node is its int64 index in DataValue.nodes.
kernel/src/structs.ev:360
Fields
DataNodeKind kint64 pint64 nfloat64 dOpaqueopaque — type-erased value primitive.
Boxes a typed value behind a runtime type-tag for heterogeneous
storage. It has exactly four methods: two statics called through the
call-site template form opaque[T]->..., and two instance methods
called on an opaque value d->....
opaque d := opaque[Esquire]->wrap(myEsquire)
IF opaque[Esquire]->unwrap(d) THEN { // pipe-XOR: moves the value out; d now empty
Esquire e := $=
String name := e->getName() // call methods on the value, never on d
}
boolean b = d->loaded() // FALSE only after a successful unwrap
opaque c := d->clone() // non-destructive deep copy
opaque is not a parametric type. The [T] only appears at the
call site of the two statics; the type position is always bare
opaque (E2070).
No other method may be called on an opaque, whatever the receiver: a
local, a parameter, a field, an opaque[] element or a call's result
(E2078). To call a method on the value inside, unwrap it into a local
or a field of the concrete type first.
opaque is move-only and bound like an object. Pass, store and return
it with := (a plain opaque parameter owns its argument), and the
source is consumed: reading it afterwards is E3010. = from another
opaque would give one value two owners and is E3023. clone() is the
only copy.
── C handles and UNSAFE (I.I.viii (c.i), (d)) ──────────────────────
A typed C pointer (FOREIGN_TYPE BIND (sqlite3 *) SQLITE3) lives only
as a local inside an UNSAFE block: it may not be a field, a method
parameter or a return type (E3037). A C handle that must persist across
calls is held in an opaque field instead, the confinement-legal
carrier. Inside an UNSAFE block the compiler converts between the
opaque and the typed handle for you:
CLASS Database {
PRIVATE opaque db // the persistent sqlite3*
MODIFY METHOD open(String path) RETURNS (int32 rc) {
UNSAFE {
SQLITE3 handle
rc = FOREIGN::sqlite3_open_v2(path, handle, flags, EMPTY)
.db = handle // wraps the typed handle into the opaque
}
RETURN (rc)
}
METHOD close() RETURNS (int32 rc) {
UNSAFE { rc = FOREIGN::sqlite3_close_v2(.db) } // unwraps at the FOREIGN call
RETURN (rc)
}
}
The same conversion holds for an opaque local, for a declaration
(opaque o = handle), for a LOAD out-parameter written straight into
an opaque field, and for the explicit opaque[H]->wrap(h) /
opaque[H]->unwrap(d), which are legal only inside UNSAFE (E3050).
Outside the block no conversion is offered.
A C object has exactly one owner, so an opaque carrying a C handle has
no copy: its clone() raises CloneError. Lend it with REFERENCE
instead. An untyped void*, or an OS mutex or condition variable,
belongs in UNSAFE.HANDLE / .MUTEX / .CONDVAR, whose field is the
bare pointer with a null check; reach for opaque when the handle is
typed and worth carrying behind a tag.
opaque is the sole member of GROUP Inoperative (interfaces.ev), which
generic kernel containers test with WHEN T IS Inoperative to opt out
of clone, copy and iteration paths over a payload they cannot see.
Runtime: PRIMITIVE Opaque below — a kind and a union, every read of the
union behind its kind (opaque-union-storage-design.md), as number is
backed by PRIMITIVE Number. A primitive or a C handle is stored in its
own arm and allocates nothing; a class or interface object, or an array
held in an OpaqueArrayCell, is the owning obj arm and carries its own
class, which is what unwrap asks: a class payload matches by IS-A, so a
wrapped Circle answers unwrap[Shape]. opaque[T]->wrap / ->unwrap are
Opaque.wrap[T] / Opaque.unwrap[T], generic members instantiated per T.
Spec reference: ENVZN_CONSTITUTION.md I.D.v ("opaque — type-erased value") and I.I.viii (c.i), (d).
kernel/src/opaque.ev:121
Constructors
INIT()
Empty: UNLOADED, nothing held.
Methods
METHOD wrap(T value) RETURNS opaque
METHOD unwrap(MUTABLE REFERENCE opaque d) RETURNS | T
METHOD peek(REFERENCE opaque d) RETURNS H
METHOD loaded() RETURNS boolean
FALSE only when empty: never wrapped, or after a successful unwrap.
METHOD clone() RETURNS opaque
A copy of what it holds: an object through its own clone(), a value by
value. A C handle has one owner and no copy (CloneError, I.D.v (c)).
OpaqueTypekernel/src/opaque.ev:12
Fields
int8 i8int16 i16int32 i32int64 i64int128 i128uint8 u8uint16 u16uint32 u32uint64 u64uint128 u128float32 f32float64 f64boolean bchar8 c8char16 c16char32 cbinary onumber ncomplex zdecimal128 dHANDLE hCloneable objOpaqueArrayCellIMPLEMENTS Cloneable
An array has no class of its own to carry, so an opaque holds it in one
of these, in its obj arm: the cell's class says what the array is
(OpaqueArrayCell[int32[]] is not OpaqueArrayCell[String[]]), and
unwrap matches it with WHEN held IS OpaqueArrayCell[A] (opaque-union-
storage-design §10 x4). A fixed-size array is never a payload (E2171).
kernel/src/OpaqueArrayCell.ev:16
Fields
A arrConstructors
INIT(A value)
Methods
METHOD clone() RETURNS OpaqueArrayCell[A]
OpaqueKindOpaqueKind — what an opaque holds (OpaqueStorage.ev). A primitive is its
own kind; a C handle is HANDLE; a class, an interface object or an array
(held in an OpaqueArrayCell) is OBJECT and carries its own class.
kernel/src/enums.ev:337
| Case | Description |
|---|---|
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |
? |
— |