[
{"slug":"compiler/architecture","index":false,"title":"Architecture","order":1,"tags":["compiler","backend","llvm","qbe","targets"],"headings":[{"depth":2,"text":"Overview","id":"overview"},{"depth":2,"text":"The Two Backends","id":"the-two-backends"},{"depth":3,"text":"Phasing","id":"phasing"},{"depth":3,"text":"Capability Differences","id":"capability-differences"},{"depth":3,"text":"Target-Specific Lowering","id":"target-specific-lowering"},{"depth":3,"text":"Differential Testing","id":"differential-testing"},{"depth":2,"text":"The LLVM Boundary","id":"the-llvm-boundary"},{"depth":2,"text":"Toolchain","id":"toolchain"},{"depth":2,"text":"Runtime Model of Cesium Programs","id":"runtime-model-of-cesium-programs"},{"depth":2,"text":"Target Platforms","id":"target-platforms"},{"depth":2,"text":"Alternatives That Were Rejected","id":"alternatives-that-were-rejected"},{"depth":2,"text":"Open Items","id":"open-items"},{"depth":2,"text":"Earlier Prototype","id":"earlier-prototype"}],"links":["compiler/bootstrap","compiler/mir","compiler/freestanding"],"text":"> [!info] Source > ADR 0001 (backend, LLVM packaging, toolchain) and ADR 0004 (two backends). Status: accepted as a plan; implementation not started. ## Overview - The compiler is written in Cesium. A small stage 0 compiler written in portable C exists only to start the bootstrap chain. - The middle IR is the core design asset. It carries shapes, aliasing facts derived from the ownership rules, fusion and explicit vector operations. Numerical optimization happens there; a backend receives already-structured code. See Middle IR. - Two backends consume the same MIR. Cesium targets QBE first and later adds LLVM. ## The Two Backends | Backend | Role | Strengths | | --- | --- | --- | | QBE (MIT, vendored and pinned) | Development, bootstrap and porting backend; correctness first | Builds in seconds with any C compiler; very fast compiles; correct C ABI including structs by value; a new architecture port is roughly 1.5 to 2 thousand lines | | LLVM (through libcsllvm) | Primary release backend | Optimization and vectorization, every Cesium target, full debug info (DWARF, CodeView/PDB), freestanding features | ### Phasing 1. Stage 0 and cesium1 use QBE. QBE's output (assembly) is assembled and linked by the pinned zig cc in CI. No LLVM build is needed to begin. 2. The real compiler starts with the QBE backend too. 3. The LLVM backend and libcsllvm are added when numerics performance, more targets, full debugging or freestanding features matter. 4. From then on, releases use LLVM. QBE remains for development iteration, the bootstrap chain and quick ports. ### Capability Differences | Feature | QBE backend | LLVM backend | | --- | --- | --- | | Targets | QBE's list (amd64 SysV, Apple and Windows; arm64 Linux and Apple; rv64) | All Cesium targets | | SIMD and vector operations | Scalarized by a MIR legalization pass | Native vector types | | Optimization | QBE's modest optimizations | Full pipeline | | Debug info | Line tables only | Full variables and types: DWARF; CodeView/PDB on Windows | | Freestanding attributes (interrupt calling conventions, naked functions, sections, no red zone, stack probes) | Not available: building a kernel requires LLVM | Available | | Output | Assembly text (needs an assembler and linker) | Object files, linked by in-process LLD | Code that needs a capability a backend lacks is legalized (for example scalarized) or rejected with a clear error naming the backend. Performance benchmarks always run on LLVM. ### Target-Specific Lowering Frontends never compute layout. MIR keeps sizeof(T), alignof(T), index and field symbolic, and each backend resolves them for the target: LLVM from its data layout, the QBE wrapper from its own implementation of the C layout rules. When a frontend needs a layout value at compile time it asks the active backend through a layout-query interface. ### Differential Testing Both backends must give every program the same meaning, so core MIR has no undefined behavior (see Middle IR), and consistency is proven by testing: 1. Corpus tests: the test corpora through QBE, LLVM -O0 and LLVM -O2; outputs must match exactly. 2. Layout tests: generated structs, arrays and nested aggregates; each backend prints sizeof, alignof and every field offset, compared with the equivalent C declaration compiled by zig cc. 3. ABI tests: generated calls between Cesium (built with each backend) and C in both directions. 4. Random programs: a generator of well-defined MIR programs with a reducer, once MIR stabilizes. 5. Floating point: exact bit comparison wherever the floating-point policy is strict. ## The LLVM Boundary - LLVM and LLD are statically linked into the compiler. - Cesium emits LLVM IR itself (textual first, bitcode later) and drives LLVM through a handful of LLVM C API calls: parse IR, run a pass pipeline, create a target machine, emit an object. - The only C++ in the compiler is a small shim for LLD and for writing Windows import libraries. - libcsllvm is one archive per host containing LLVM, "},
{"slug":"reference/overview","index":false,"title":"Overview","order":1,"tags":["overview","design","goals"],"headings":[{"depth":2,"text":"Design Goals","id":"design-goals"},{"depth":2,"text":"Basic Program Structure","id":"basic-program-structure"}],"links":[],"text":"Cesium is a compiled, statically-typed systems programming language designed for mathematical computing and linear algebra applications. It prioritizes performance, explicit memory management, and mathematical expressiveness while maintaining C ABI compatibility. The language borrows design and syntactic elements from languages as varied as Python, Fortran, Rust, Go, Odin, and C++, but ultimately derives the bulk of its original design inspiration and goals from C, Zig, and MATLAB. As such, an early placeholder name for the language was CZM for those three languages. Ultimately, the name is a reference to the atomic element cesium (American Chemical Society spelling). Since one of the primary objectives of the language is runtime performance, it seemed fitting to share a name with the primary element used for standard atomic clocks. In fact, a second in timekeeping is officially defined in SI by assuming the unperturbed ground-state hyperfine transition frequency of the cesium-133 atom to be exactly 9,192,631,770 Hz. It takes 34 bits to represent that number as an integer in binary. ## Design Goals - Math-first language with built-in mathematical operators and types - Compile-time dispatch and optimization - Memory safety through ownership tracking and explicit management - Strong typing with minimal implicit conversions - ASCII-only syntax for universal accessibility - C interoperability for existing library integration ## Basic Program Structure This simple example demonstrates the basic structure of a Cesium program: - Cesium source files use the .csm extension - Function definitions use the syntax return_type = function_name(parameters) - void indicates no return value - Built-in functions like printf are available without imports - String literals use standard C-style double quotes"},
{"slug":"compiler/bootstrap","index":false,"title":"Bootstrap Chain","order":2,"tags":["compiler","bootstrap","stage0"],"headings":[{"depth":2,"text":"The Ladder","id":"the-ladder"},{"depth":3,"text":"Rules for the Chain","id":"rules-for-the-chain"},{"depth":2,"text":"Stage 0","id":"stage-0"},{"depth":3,"text":"Why C and Not Zig","id":"why-c-and-not-zig"},{"depth":2,"text":"`cesium1`","id":"cesium1"},{"depth":2,"text":"What CI Builds","id":"what-ci-builds"},{"depth":2,"text":"What Contributors Need","id":"what-contributors-need"},{"depth":2,"text":"Bootstrap Models That Were Considered","id":"bootstrap-models-that-were-considered"},{"depth":2,"text":"Porting to a New Host","id":"porting-to-a-new-host"}],"links":["compiler/s0-subset","compiler/stage0-c-dialect"],"text":"> [!info] Source > ADR 0002 (bootstrap strategy), ADR 0004 (QBE first) and the stage 0 design. Status: accepted as a plan. The Cesium compiler is written in Cesium. Something else has to compile it the first time, and that is done by a layered chain that starts from a small compiler written in C. ## The Ladder | Layer | Written in | Compiles | Notes | | --- | --- | --- | --- | | Stage 0 | Portable C | S0 | A tiny S0 frontend plus libcsmir (QBE first); runs only in CI | | Stage 1 (cesium1) | S0 | S1 | Frontend only: parses S1, emits core MIR text, hands it to libcsmir. Verbose by design; frozen once the next layer works | | Real compiler | S1 | Full Cesium | Reimplements MIR (both levels) and both lowerings in Cesium; borrow checking, generics, math operators, freestanding support; starts on QBE and adds LLVM | - S0 is a deliberately tiny subset of Cesium; see The S0 Subset. - S1 is a comfortable language for writing the real compiler. Its feature list is a set of candidates to be confirmed when stage 1 is designed. - Convenience features (for, switch, tagged unions, strings, modules, floats) are implemented in stage 1, written in S0, not in stage 0. They are defined as rewrites into core MIR. - More layers are added only if a later compiler genuinely needs features its predecessor cannot compile. ### Rules for the Chain 1. Each subset is a strict subset of Cesium. Every S0 program is a valid Cesium program with the same meaning. 2. Every later compiler must still compile the frozen layers, so the from-source check in CI can run down the whole chain. 3. The chain ends with the full compiler rebuilding itself, checked for identical output. 4. Frozen layers keep their own libcsmir, so the real compiler's MIR can evolve freely. ## Stage 0 Stage 0 is written in portable C: the intersection of C99 and C11 that every mainstream compiler implements, with no extensions, only the ISO C standard library and a list of banned functions. See Stage 0 C Dialect. It consists of: - the S0 frontend (lexer, recursive-descent and Pratt parser, minimal type checking, the S0 to MIR mapping); - libcsmir: core MIR data structures, text parser, printer, verifier, the QBE lowering, later the LLVM lowering, and a small arena runtime; - vendored QBE, with its entry point renamed so it can be called in-process. Stage 0 does not spawn processes; assembling and linking are done by the build system. Pipeline (phase 1, QBE only): Stage 0's output does not need to be efficient, and stage 0 has no optimization design. ### Why C and Not Zig - Stability. Zig is pre-1.0 and its releases bring breaking changes. The root of the chain should not need rework on every Zig upgrade. ISO C is frozen. - Native fit with LLVM. LLVM's C API is C. - Portability of the root. Stage 0 can be built by Clang, GCC or MSVC, so Cesium can move away from zig cc later without touching it. - Zig's churn stays in build.zig, which only orchestrates. The C dialect's limits apply only to stage 0 and libcsmir. They do not affect Cesium's design or the real compiler. ## cesium1 Stage 1 is only a frontend. It emits core MIR text and calls a coarse C ABI exported by libcsmir (pointers, uword and i32 only; no by-value structs, callbacks or variadics): It becomes self-contained in two phases: first it writes assembly that build.zig assembles and links; once libcsllvm exists it assembles QBE output through LLVM's integrated assembler and links with in-process LLD, or uses the LLVM backend directly. ## What CI Builds build.zig runs only in CI pipelines. It orchestrates the LLVM build, stage 0, libcsmir, libcsllvm and the chain. 1. Devkits (cesiumlang/devkits): per-host packages containing the pinned official Zig, the Cesium LLVM build (core, the Cesium targets and LLD; no Clang) and a pinned QBE. Stage 0 builds use the Zig from the devkit. 2. Build the LLD shim and libcsllvm per host. 3. Build stage 0 and libcsmir, run the portability and banned-function checks, and run the layer chain up to the full"},
{"slug":"reference/lexical-structure","index":false,"title":"Lexical Structure","order":2,"tags":["lexical","comments","keywords","identifiers","strings"],"headings":[{"depth":2,"text":"Source Files","id":"source-files"},{"depth":2,"text":"Comments","id":"comments"},{"depth":2,"text":"Keywords","id":"keywords"},{"depth":2,"text":"Built-in Functions and Constants","id":"built-in-functions-and-constants"},{"depth":2,"text":"Identifiers","id":"identifiers"},{"depth":2,"text":"String Literals and Interpolation","id":"string-literals-and-interpolation"},{"depth":3,"text":"String Types","id":"string-types"}],"links":["reference/modules-imports","reference/memory-management","reference/builtin-functions"],"text":"## Source Files | Extension | Used for | | --- | --- | | .csm | Cesium source files | | .csi | Module interface files (see Modules and Imports) | These are the only two extensions. The earlier .cs, .czm and .cesium spellings, and .m for interface files, are no longer used (cesiumlang/cesium#14). ## Comments Cesium supports three types of comments: ## Keywords Cesium reserves the following keywords: Core Types: file, str, list, dict, slice, struct, path, uword Language Constructs: alias, catch, as, return, comptime, generic, sizeof, typeof, asm, void, enum, error, null, undefined, union Control Flow: if, while, for, else, do, with, defer, break, continue, switch, case, fallthrough, throw Function Qualifiers: operator, context, property, private, secret, static, destruct Variable Qualifiers: const, static, private, secret, volatile, atomic, register, simd C Interop: extern, export OOP Constructs: trait, impl, type, this, super Namespacing: std, namespace undefined marks a pointer that owns nothing, or a plain value that is uninitialized; see Memory Management. > [!question] Open > The keyword list is under review. import is used as a keyword on the modules page but is not listed here, and the list reserves many common identifiers: cesiumlang/cesium#50. Which built-in names are reserved and which can be shadowed, and how this list relates to the Built-in Functions page, is cesiumlang/cesium#20. ## Built-in Functions and Constants Memory Management: alloc(), free(), realloc() Debugging and I/O: printf(), debugf(), assert(), stdout, stdin, stderr Mathematical: floor(), ceil(), trunc(), round(), trueround(), abs(), min(), max(), mean(), norm(), pi ## Identifiers Identifiers follow C-style rules: start with letter or underscore, followed by letters, digits, or underscores. Valid identifiers: - variable_name - _private_var - Class2D - MAX_SIZE ## String Literals and Interpolation Cesium supports multiple string literal formats: ### String Types - Simple strings use double quotes and support escape sequences - Interpolated strings use backticks and allow expression embedding with {} - Path strings are a special type for filesystem paths with automatic normalization"},
{"slug":"spec/lexical","index":false,"title":"Lexical Structure (Draft)","order":2,"tags":["spec","lexical"],"headings":[{"depth":2,"text":"2.1 Source Files","id":"21-source-files"},{"depth":2,"text":"2.2 Whitespace and Tokens","id":"22-whitespace-and-tokens"},{"depth":2,"text":"2.3 Comments","id":"23-comments"},{"depth":2,"text":"2.4 Identifiers","id":"24-identifiers"},{"depth":2,"text":"2.5 Keywords","id":"25-keywords"},{"depth":2,"text":"2.6 Literals","id":"26-literals"},{"depth":3,"text":"Integer Literals","id":"integer-literals"},{"depth":3,"text":"Floating-Point Literals","id":"floating-point-literals"},{"depth":3,"text":"Character Literals","id":"character-literals"},{"depth":3,"text":"String Literals","id":"string-literals"},{"depth":3,"text":"Other Literals","id":"other-literals"},{"depth":2,"text":"2.7 Operators and Punctuation","id":"27-operators-and-punctuation"}],"links":["spec"],"text":"> [!warning] Draft > Chapter 2 of the language specification draft. It states only what is decided. Undecided areas are marked \"Open\" with the issue to follow. See the introduction for the status markers, the citation format and the grammar notation. ## 2.1 Source Files 1. Decided. A Cesium source file has the extension .csm. A module interface file has the extension .csi. No other extensions are used. [cesium#14] 2. Decided. The syntax of the language uses ASCII characters only. [ref: overview, \"Design Goals\"] 3. Open. The encoding of a source file, and which characters may appear in comments and string literals, are not stated. The reference says only that str values are UTF-8. See cesiumlang/cesium#39. ## 2.2 Whitespace and Tokens No decision record states how source text is divided into tokens. > [!warning] Provisional — not decided (cesiumlang/cesium#57) > This draft assumes the conventional rules, which every example in the reference is consistent with: space, horizontal tab, carriage return and line feed separate tokens and are otherwise not significant; and at each point the lexer takes the longest sequence of characters that forms a token. The second rule is what makes #= one token and not # followed by =. It also has consequences that have not been examined, for example p#++ against p #+ +1, and :: (root) against : followed by an owned type :#T; those collisions are listed in cesiumlang/cesium#57 and cesiumlang/cesium#28. ## 2.3 Comments 1. Decided. There are three forms of comment [ref: lexical-structure]: | Form | Extent | | --- | --- | | // ... | To the end of the line | | /* ... */ | To the closing */ | | /** ... */ | A documentation comment | 2. Open. Whether block comments nest is not stated anywhere. 3. Open. The tags recognized inside documentation comments (the reference shows @param and @return) are not specified. ## 2.4 Identifiers 1. Decided. An identifier starts with a letter or an underscore and continues with letters, digits or underscores. [ref: lexical-structure] 2. Decided. A keyword (2.5) is not an identifier. [ref: lexical-structure] 3. Open. Whether there is a limit on identifier length, and whether identifiers that begin with an underscore are reserved, is not stated. ## 2.5 Keywords 1. Decided. The following words are reserved [ref: lexical-structure], with undefined added by [cesium#11 r15]: | Group | Keywords | | --- | --- | | Core types | file str list dict slice struct path uword | | Language constructs | alias catch as return comptime generic sizeof typeof asm void enum error null undefined union | | Control flow | if while for else do with defer break continue switch case fallthrough throw | | Function qualifiers | operator context property private secret static destruct | | Variable qualifiers | const static private secret volatile atomic register simd | | C interop | extern export | | Object-oriented constructs | trait impl type this super | | Namespacing | std namespace | 2. Open. import is used as a keyword in the reference and in the S0 subset but is not in the list. The sized type names (u8, i32, f64 and the arbitrary-width forms such as u34) are not in the list either, and the reference does not say whether they are keywords or predefined identifiers. Which built-in names (alloc, free, printf and others) are reserved and which can be shadowed is not decided. See cesiumlang/cesium#20 and cesiumlang/cesium#50. ## 2.6 Literals ### Integer Literals 1. Decided. There are no type suffixes. A literal takes its type from context, and as forces one. [cesium#16] 2. Decided by use. Decimal integer literals are a sequence of decimal digits. They appear throughout the reference and the S0 design. [ref: type-system] [cesium#9] 3. Open. No other form is specified. The reference uses hexadecimal (0xFF) and binary (0b11110000) literals in examples, and the highlighting grammar also accepts octal (0o755); none of these has a decision behind it, and neither do digit separators. The type of a litera"},
{"slug":"compiler/mir","index":false,"title":"Middle IR (MIR)","order":3,"tags":["compiler","mir","ir"],"headings":[{"depth":2,"text":"Two Levels","id":"two-levels"},{"depth":2,"text":"Who Implements It","id":"who-implements-it"},{"depth":2,"text":"No Undefined Behavior","id":"no-undefined-behavior"},{"depth":2,"text":"Core Level Sketch","id":"core-level-sketch"},{"depth":3,"text":"Lexical Conventions","id":"lexical-conventions"},{"depth":3,"text":"Types","id":"types"},{"depth":3,"text":"Declarations","id":"declarations"},{"depth":3,"text":"Statements","id":"statements"},{"depth":3,"text":"Expressions","id":"expressions"},{"depth":3,"text":"Example","id":"example"},{"depth":3,"text":"Version 0 Restrictions","id":"version-0-restrictions"},{"depth":2,"text":"Lowering","id":"lowering"},{"depth":2,"text":"Open Questions","id":"open-questions"}],"links":["compiler/architecture","compiler/freestanding"],"text":"> [!info] Source > Design: Cesium middle IR. Status: draft sketch. The text syntax shown here is illustrative and open to change. Every Cesium frontend lowers to MIR, and MIR lowers to a backend: QBE or LLVM (see Architecture). Language features are defined by how they lower: - Core features map directly onto core MIR constructs. - Composite features are rewrites into the core: for becomes while, switch becomes if chains or jump tables, defer becomes cleanup blocks, error unions become tagged structs, methods become functions taking this. ## Two Levels 1. Core level (now). Close to \"C with structured control flow\": scalars, pointers, structs, arrays, calls, structured if / while, named mutable locals. It is not SSA: locals are stack slots that the backends promote. Stage 0 implements only this level. 2. Numerics level (later). Shapes and array descriptors, alias facts from the borrow checker, vector types and FMA, loop nests over index spaces, fusion regions, per-operation floating-point policy. These lower into the core level plus hints that only LLVM uses. Structured control flow at the core level also suits SPIR-V and WebAssembly. ## Who Implements It | Component | Language | Lifetime | | --- | --- | --- | | libcsmir: core MIR text parser, verifier, printer; the QBE lowering (first), the LLVM lowering (later); vendored QBE | Portable C, part of stage 0 | Used by stage 0 and linked into cesium1; frozen with the bootstrap chain | | The real compiler's MIR (both levels) and both lowerings | Cesium | Replaces libcsmir in the real compiler | ## No Undefined Behavior Both backends must give every core MIR program the same meaning, otherwise differential testing cannot be trusted: - Integer add, sub, mul and neg wrap (two's complement). - Shift amounts are reduced modulo the operand width, or follow another single defined rule applied by both lowerings. - Division and remainder by zero, and the signed minimum divided by -1, have one defined behavior in both lowerings. - Out-of-range float to integer conversions have one defined result. - The LLVM lowering must not add flags that produce poison or undefined behavior (nsw, nuw, exact, unproven inbounds, fast-math) unless MIR semantics or a verified fact allows it. ## Core Level Sketch ### Lexical Conventions - @name for globals and functions, %name for parameters and locals. Bare names are types and operations. - Constants carry their type: 0:u8, 1:uword, -5:i64. - ; starts a comment. A file starts with a version header: cesium-mir 0. ### Types - Integers: u8 u16 u32 u64 i8 i16 i32 i64, and uword (pointer-sized, resolved by target). Signedness lives in the type, so operations need no signed and unsigned variants. - Floats: f32 f64. - Pointers: ptr<T>. Arrays: [N x T]. Structs: struct Name { field: T, ... }. void. Layout is owned by the backend. MIR keeps sizeof(T), alignof(T), index and field symbolic. ### Declarations - func is module-internal; export func is externally visible with the C ABI; extern func declares an external C ABI function. - Function attributes are reserved for freestanding targets (callconv(...), section(...), align(...), target_features(...), noredzone, naked, probe_stack(...)). Version 0 implements callconv(c) only. - A global name used as an expression yields its address. ### Statements | Statement | Meaning | | --- | --- | | local %x: T [= expr] | Mutable local (stack slot) | | set %x = expr | Assign a local | | store ptr_expr, value_expr | Store through a pointer | | eval expr | Evaluate for side effects | | if cond { ... } [else { ... }] | Structured conditional; cond is an integer, nonzero is true | | while cond { ... } | Structured loop | | break / continue | Innermost loop | | return [expr] | Return | Any statement may carry a source location, used for debug information. ### Expressions Expressions are trees, not three-address code; the lowerings flatten them. | Expression | Meaning | | --- | --- | | %x | Value of a local or parameter | | addr(%x) | Add"},
{"slug":"reference/type-system","index":false,"title":"Type System","order":3,"tags":["types","primitives","arrays","pointers","simd"],"headings":[{"depth":2,"text":"Primitive Types","id":"primitive-types"},{"depth":3,"text":"Integer Types","id":"integer-types"},{"depth":3,"text":"Floating Point Types","id":"floating-point-types"},{"depth":2,"text":"Array Types","id":"array-types"},{"depth":3,"text":"Fixed Arrays","id":"fixed-arrays"},{"depth":3,"text":"Dynamic Arrays","id":"dynamic-arrays"},{"depth":2,"text":"SIMD Types","id":"simd-types"},{"depth":2,"text":"Pointer Types","id":"pointer-types"},{"depth":2,"text":"User-Defined Types","id":"user-defined-types"},{"depth":3,"text":"Structs","id":"structs"},{"depth":3,"text":"Enums","id":"enums"},{"depth":3,"text":"Error Types","id":"error-types"},{"depth":3,"text":"Union Types","id":"union-types"},{"depth":2,"text":"Type Conversion Rules","id":"type-conversion-rules"},{"depth":3,"text":"Implicit Promotions","id":"implicit-promotions"},{"depth":3,"text":"Explicit Conversions","id":"explicit-conversions"},{"depth":2,"text":"Arithmetic Semantics","id":"arithmetic-semantics"},{"depth":2,"text":"Rules from the Original Design","id":"rules-from-the-original-design"}],"links":["reference/memory-management"],"text":"## Primitive Types ### Integer Types ### Floating Point Types ## Array Types ### Fixed Arrays ### Dynamic Arrays ## SIMD Types ## Pointer Types The sigil says whether the data can be modified through the pointer: #T is a pointer to read-only data, ~T a pointer to read-write data. Sigils nest, reading left to right. Pointers are dereferenced by default: using a pointer in a value context reads or writes the data it points to. There is no dereference operator. The address itself is only touched by the address-context operators. Owned pointers that cross a boundary are written with a leading : — :#T or :~T — in return types, parameters and struct fields. See Memory Management. > [!question] Open > Ownership rules for multi-level pointers (##T, ~#T) are not settled (open question 11 of cesiumlang/cesium#11), and neither is how dereference-by-default resolves where the expected type is not fixed (cesiumlang/cesium#26). ## User-Defined Types ### Structs ### Enums ### Error Types ### Union Types ## Type Conversion Rules ### Implicit Promotions ### Explicit Conversions ## Arithmetic Semantics Integer arithmetic has no undefined behavior. Integer +, -, * and negation wrap (two's complement). Shifts by more than the operand width, division and remainder by zero, the signed minimum divided by -1, and out-of-range float-to-integer conversions each have one defined result on every target. This mirrors the compiler's middle IR, where both backends must give every program the same meaning (cesiumlang/cesium#7, cesiumlang/cesium#8). > [!question] Open > Which defined result applies to division by zero and over-wide shifts (a trap or a value) is open question 3 of cesiumlang/cesium#8. Integer division rounding, % on negative numbers, ^ and roots on integers, and floating-point policy are cesiumlang/cesium#35. ## Rules from the Original Design These rules were set in the September 2025 design sessions and are recorded in cesiumlang/cesium#16. They are listed here so the page is complete. Several are being re-examined by the design audit, noted next to each group. Integers and conversions (under review: cesiumlang/cesium#33, cesiumlang/cesium#34) - Mixed signed and unsigned arithmetic is allowed; the result is cast to the type of the destination (u8 k = i + j behaves as i + (j as u8)). - Mixed signed and unsigned *comparison* is mathematically correct, not a bit reinterpretation: a u32 holding 3,000,000,000 compares greater than an i32 holding 10, and any negative value is less than any unsigned value. - as is bit reinterpretation only. A #void to #T conversion is spelled q as #T. - Promotions apply to function arguments the same way as to assignments. Literals (under review: cesiumlang/cesium#56) - There are no type suffixes. A literal takes its type from context; use as to force one. Enums - Values must be qualified (Status.OK). A bare OK is an error unless aliased (alias OK = Status.OK;). - With no backing type, the smallest type that fits is used, preferring unsigned. Float-backed enums are allowed and need explicit values. - Enums decay to their numeric type, and a numeric value may be passed where an enum is expected, but one enum never converts to another. Arrays, slices and strings (under review: cesiumlang/cesium#36, cesiumlang/cesium#39, cesiumlang/cesium#44) - Arrays do not decay to pointers; a pointer must be set to an explicit element. - Arrays have a built-in .len. Primitives have no methods. - Negative indices count from the end, only for arrays and slices with known bounds. Raw pointer indexing is plain address arithmetic. - Ranges are also slices: arr[0..5], arr[0..=5], arr[0..2..=8]. - str is a built-in class, not a primitive: UTF-8, NUL-terminated internally with a tracked length, raw bytes through .u8. - list[T] and dict[K,V] own and manage their memory. - Function pointer types are written #(i32, f64) name. > [!question] Open > Not settled, and so not stated above: the type of a literal with no context and what happens w"},
{"slug":"spec/s0-grammar","index":false,"title":"S0 Grammar (Draft)","order":3,"tags":["spec","grammar","s0"],"headings":[{"depth":2,"text":"3.1 Lexical Elements","id":"31-lexical-elements"},{"depth":2,"text":"3.2 Compilation Unit","id":"32-compilation-unit"},{"depth":2,"text":"3.3 Types","id":"33-types"},{"depth":2,"text":"3.4 Declarations","id":"34-declarations"},{"depth":2,"text":"3.5 Statements","id":"35-statements"},{"depth":3,"text":"Telling a Declaration from a Statement","id":"telling-a-declaration-from-a-statement"},{"depth":2,"text":"3.6 Expressions","id":"36-expressions"},{"depth":3,"text":"Operators Without a Decided Place","id":"operators-without-a-decided-place"},{"depth":2,"text":"3.7 Constraints","id":"37-constraints"},{"depth":2,"text":"3.8 Mapping to Core MIR","id":"38-mapping-to-core-mir"},{"depth":2,"text":"3.9 Not in S0","id":"39-not-in-s0"},{"depth":2,"text":"3.10 Comparison with the Stage 0 Implementation","id":"310-comparison-with-the-stage-0-implementation"}],"links":["spec","compiler/s0-subset","reference","spec/lexical","reference/modules-imports"],"text":"> [!warning] Draft > Chapter 3 of the language specification draft. This is a first transcription of the S0 design into a grammar. It has not yet been run through a parser generator, which is on the checklist in cesiumlang/cesiumlang.org#13. Where this chapter and cesiumlang/cesium#9 disagree, the issue wins. Section 3.10 compares it with the first stage 0 implementation. S0 is the subset of Cesium that stage 0 compiles. It is described in prose in The S0 Subset. This chapter gives its grammar in EBNF and traces each production to its source. See the introduction for the notation and the citation format. Sources used in this chapter: | Tag | Source | | --- | --- | | [S0] | The \"S0 contents\" table of cesiumlang/cesium#9 | | [S0-map] | The \"S0 to core MIR mapping\" table of the same issue | | [S0-sample] | The sample program of the same issue | | [S0-amend] | The amendment comment on the same issue (2026-11-16) | | [own rN] | Rule N of the ownership design, cesiumlang/cesium#11 | | [ref: page] | A page of the language reference | ## 3.1 Lexical Elements S0 uses the lexical structure of chapter 2, restricted as follows. - Comments are as in 2.3. - Open. character includes escape sequences, whose set is not specified (2.6). The S0 sample uses '\\n'. Integer literal forms other than decimal are not specified (2.6). ## 3.2 Compilation Unit | Production | Source | | --- | --- | | unit | [S0] \"Compilation unit\": multiple files compiled as one unit with shared globals; no import of Cesium modules | | top_decl | [S0] \"Data\", \"Outside world\", \"Globals\", \"Functions\" | Several source files form one unit. The grammar above applies to each file; the declarations of all files share one scope. [S0] ## 3.3 Types | Production | Source | | --- | --- | | base_type | [S0] \"Types\": u8, i32, u32, i64, u64, uword; \"Data\": struct | | sigil, type | [S0] \"Types\": pointers #T; ~T is parsed and treated the same; pointer-to-pointer ##T | | ret_type | [S0] \"Functions\": void | | declarator | [S0] \"Types\": fixed arrays T name[N] | - Decided. #T in a declaration is a pointer to T everywhere. [S0-amend] - Decided. Stage 0 does not check borrows; it treats ~T exactly as #T. [S0] - Open. Whether the array length N may be a const global as well as an integer literal is not stated in [S0]. This draft allows only a literal. ## 3.4 Declarations | Production | Source | | --- | --- | | struct_decl, field_decl | [S0] \"Data\": struct with fields only, no methods; [S0-sample] struct Token | | extern_block, extern_func | [S0] \"Outside world\": extern name = import('lib') { ... } declaring C ABI functions; [S0-sample] | | const_decl | [S0] \"Globals\": const globals; [S0-sample] const i64 TOK_IDENT = 1; | | global_decl | [S0] \"Globals\": global variables | | func_def, params, param | [S0] \"Functions\": T = name(params) { ... }, single return value, void, recursion | | initializer | [S0-map] T name = e;; [S0-amend] and [own r4, r5]: a pointer is never initialized with plain = | - By omission. A function is defined only at the top level of a unit: [S0] lists no nested functions. So in S0 the form ret_type \"=\" ident \"(\" cannot be confused with an assignment, which occurs only inside a block. (For the full language this ambiguity is open: cesiumlang/cesium#27.) - Decided. There is a single return value. [S0] - Decided. Struct literals do not exist in S0; fields are assigned one at a time. [S0] - Decided. The entry point is i32 = main(i32 argc, ##u8 argv). [S0] - Decided. Parameters, return values and extern signatures use only scalar and pointer types; a struct is not passed or returned by value. [cesium#8], \"v0 restrictions\" - Open. Whether a const global may be an array or a pointer, and what expressions may initialize a global, are not stated in [S0]. - Open. How a function declared in an extern block is named at the call site. The sample calls write(...) without the block's name, while the reference writes windows.Sleep(ms) and uses export or as to make a name global (Modules and Im"},
{"slug":"compiler/s0-subset","index":false,"title":"The S0 Subset","order":4,"tags":["compiler","stage0","s0","bootstrap"],"headings":[{"depth":2,"text":"Rules","id":"rules"},{"depth":2,"text":"Contents","id":"contents"},{"depth":2,"text":"Pointers in S0","id":"pointers-in-s0"},{"depth":2,"text":"S0 to Core MIR","id":"s0-to-core-mir"},{"depth":2,"text":"Not in S0","id":"not-in-s0"},{"depth":2,"text":"Sample Program","id":"sample-program"},{"depth":2,"text":"Stage 0 as Implemented","id":"stage-0-as-implemented"},{"depth":3,"text":"What Stage 0 Rejects Because the Design Is Open","id":"what-stage-0-rejects-because-the-design-is-open"},{"depth":2,"text":"Stage 1 Goals (S1)","id":"stage-1-goals-s1"},{"depth":2,"text":"Testing","id":"testing"},{"depth":2,"text":"Open Questions","id":"open-questions"}],"links":["spec/s0-grammar","compiler/bootstrap","compiler/mir"],"text":"> [!info] Source > Design: stage 0 and the S0 subset, including its amendment comment of 2026-11-16, which applies the file-extension decision and the ownership design. Status: draft. The formal grammar is in the specification: S0 Grammar. S0 is the deliberately tiny subset of Cesium that stage 0 compiles. Stage 0 has one job, which is to compile stage 1 (cesium1), and stage 1 is written in S0. See Bootstrap Chain. S0 is designed together with core MIR so that it is essentially a readable notation for it: almost every S0 construct maps one-to-one onto a core MIR construct. ## Rules 1. S0 is a strict subset of Cesium. Every S0 program is a valid Cesium program with the same meaning. Later compilers must still be able to compile the frozen stage 1. 2. Features are added to S0 only when stage 1's code genuinely needs them and implementing them in stage 0 is cheaper than writing around them. 3. S0 maps (nearly) one-to-one onto core MIR. A feature that needs a nontrivial rewrite belongs in S1. 4. Stage 0's output may be naive. ## Contents | Area | S0 | | --- | --- | | Types | u8, i32, u32, i64, u64, uword; pointers #T (~T is parsed and treated the same: no borrow checking); pointer-to-pointer (##T); fixed arrays T name[N] | | Data | struct with fields only: no methods, no struct literals (assign fields one at a time) | | Control flow | if / else, while, break, continue, return | | Functions | T = name(params) { ... }, single return value, void, recursion | | Expressions | + - * / %, comparisons, && \\|\\| !, bitwise & \\| and >< (XOR), shifts << >>, indexing p[i], address-of #x, field access a.b (auto-dereferences pointers), casts as, sizeof | | Literals | integers, characters ('A'), strings as NUL-terminated #u8 | | Memory | alloc(count) only: a bump arena that never frees. The element type comes from the declared target | | Globals | global variables and const globals (constants also stand in for enums) | | Outside world | extern name = import('lib') { ... } blocks declaring C ABI functions: a few libc functions (open, read, write, close, exit) and the coarse libcsmir API | | Compilation unit | multiple files compiled as one unit with shared globals; no import of Cesium modules | | Entry point | hosted main: i32 = main(i32 argc, ##u8 argv) | | Source files | .csm | i32 and u32 are required for C ABI correctness: passing an i64 where C expects an int happens to work on x86-64 but breaks on 32-bit targets. S0's arithmetic follows core MIR's defined semantics (wrapping integers, defined shifts and division by zero), so stage 0's output means the same thing on both backends. ## Pointers in S0 Because S0 must be a strict subset of Cesium, S0 source follows the ownership *syntax* even though stage 0 does not enforce ownership: - A pointer is never initialized or re-pointed with plain =. Plain = on a pointer assigns through it. A pointer gets its address with := (ownership, as for the result of alloc) or with #= (borrow): - Dereference-by-default is confirmed. There is no dereference operator. p[i] reads or writes an element, and p.field reaches through a pointer to a struct. - #T in a declaration is a pointer (to data that cannot be modified through it) everywhere. - Stage 0 parses ~T and treats it the same as #T. > [!question] Open > The design record does not yet say how the rest of the ownership rules apply to S0 source. S0 has no free, while in full Cesium an owner that is never released is a compile error; and the record's sample program writes through #T pointers (t.kind = ..., buf[i] = ...), which the ownership design allows only through ~T. Rule 1 above (strict subset) means these have to be reconciled before stage 1 is frozen. Track in cesiumlang/cesium#9. ## S0 to Core MIR | S0 | Core MIR | | --- | --- | | T name = e; (local) | local %name: T = e | | x = e; (local) | set %x = e | | p[i] = e;, p.f = e; | store index(p, i), e, store field(p, f), e | | p[i], p.f (read) | load(index(p, i)), load(field(p, f)) | | #x | addr(%x) | | if"},
{"slug":"reference/variables-constants","index":false,"title":"Variables and Constants","order":4,"tags":["variables","constants","qualifiers","ownership"],"headings":[{"depth":2,"text":"Variable Declaration","id":"variable-declaration"},{"depth":3,"text":"Basic Declaration","id":"basic-declaration"},{"depth":3,"text":"Constant Variables","id":"constant-variables"},{"depth":3,"text":"Pointer Declaration","id":"pointer-declaration"},{"depth":3,"text":"Uninitialized Variables","id":"uninitialized-variables"},{"depth":2,"text":"Qualifiers","id":"qualifiers"},{"depth":3,"text":"Storage and Access Qualifiers","id":"storage-and-access-qualifiers"},{"depth":3,"text":"Hardware Qualifiers","id":"hardware-qualifiers"},{"depth":2,"text":"Qualifier Descriptions","id":"qualifier-descriptions"},{"depth":2,"text":"Assignment Operators","id":"assignment-operators"}],"links":["reference/memory-management"],"text":"## Variable Declaration ### Basic Declaration ### Constant Variables ### Pointer Declaration Ownership and borrowing apply to pointers only. A pointer is given its address with one of three address-context operators, never with plain =: := is only meaningful with a pointer on the left; Matrix m := create_matrix(3, 3); is a compile error. See Memory Management for the full rules. ### Uninitialized Variables > [!question] Open > Whether a pointer that owns nothing may be declared bare, as on the last line, or must be written out with undefined, and how undefined is written for a plain value, are being discussed in cesiumlang/cesium#25. undefined is a keyword. For a plain value it means truly uninitialized. For a pointer it is a defined \"owns nothing\" state, distinct from null, and there is no test for it. ## Qualifiers ### Storage and Access Qualifiers ### Hardware Qualifiers ## Qualifier Descriptions | Qualifier | Description | | --- | --- | | const | Value cannot be modified after initialization | | static | Variable persists between function calls | | private | Accessible only within the current module | | secret | Accessible only within the current class/struct | | volatile | Prevents compiler optimizations | | atomic | Ensures thread-safe operations | | register | Suggests register allocation | | simd | Enables SIMD vectorization | ## Assignment Operators | Operator | Left side | Meaning | | --- | --- | --- | | = | plain value | copies the value | | = | pointer | assigns *through* the pointer (the pointer is dereferenced) | | #= | #T pointer | immutable borrow: points the pointer at an address, read-only | | ~= | ~T pointer | mutable borrow: points the pointer at an address, read-write | | := | #T or ~T pointer | takes ownership of the memory at an address | The sigil in the type and the operator must agree: ~T p #= q; and #T p ~= q; are compile errors. > [!question] Open > What = does to a plain value that owns memory (a str, a list, or a struct with owning fields) is not decided: cesiumlang/cesium#22."},
{"slug":"compiler/stage0-c-dialect","index":false,"title":"Stage 0 C Dialect","order":5,"tags":["compiler","stage0","c"],"headings":[{"depth":2,"text":"The Rule","id":"the-rule"},{"depth":3,"text":"Allowed","id":"allowed"},{"depth":3,"text":"Not Allowed","id":"not-allowed"},{"depth":3,"text":"Banned Functions","id":"banned-functions"},{"depth":3,"text":"Undefined and Implementation-Defined Behavior","id":"undefined-and-implementation-defined-behavior"},{"depth":2,"text":"Flags","id":"flags"},{"depth":2,"text":"Enforcement in CI","id":"enforcement-in-ci"},{"depth":2,"text":"Sources","id":"sources"}],"links":[],"text":"> [!info] Source > Design: stage 0 C dialect, the portable C subset. Status: draft. Applies to stage 0 and libcsmir only. It does not constrain Cesium's language design or the real compiler, which is written in Cesium. Stage 0 and libcsmir must compile unchanged with any mainstream C compiler, and should stay small, auditable and hard to misuse. \"C11\" alone is not enough: C11 made several features optional, and some compilers never implemented parts of earlier standards. The rule is therefore the intersection that every mainstream compiler implements, plus a list of banned functions modeled on git's banned.h and the Linux kernel's list of deprecated interfaces. Reference compilers: Clang (including zig cc), GCC, MSVC, and a small independent compiler such as TinyCC or cproc as a canary. ## The Rule Write ISO C that is valid as both C99 and C11, using only features every reference compiler implements, with no compiler extensions, only the ISO C standard library, and none of the banned functions. ### Allowed - Core C89/C99 language: // comments, declarations mixed with code, for (int i = 0; ...), designated initializers, compound literals, static inline functions, flexible array members. - Headers: <stddef.h>, <stdint.h>, <inttypes.h>, <stdbool.h>, <limits.h>, <stdarg.h>, <assert.h>, <string.h>, <stdio.h>, <stdlib.h>, <errno.h>. - Fixed-width integer types, size_t, ptrdiff_t, intptr_t / uintptr_t, PRIu64-style format macros. - Bounded string and formatting functions: memcpy, memmove, memset, memcmp, strlen, strcmp, strncmp, memchr, strchr, snprintf, vsnprintf, and fprintf / printf with constant format strings. - Number parsing only with the strtol family, checking errno, the end pointer and the range. - Include guards for headers. ### Not Allowed - Optional or weakly supported standard features: variable-length arrays, _Complex, <threads.h>, <stdatomic.h> / _Atomic, _Thread_local, _Generic, _Alignas / _Alignof, _Noreturn, Annex K, Annex L. - Static assertions except through one project macro (CS_STATIC_ASSERT) defined in a single header. - Compiler extensions: __attribute__, __declspec, __builtin_*, statement expressions, typeof, computed goto, case ranges, zero-length and one-element trailing arrays, nested functions, __int128, inline assembly, alloca, #pragma (including #pragma once). - Non-ISO libraries: no POSIX or Win32 calls. File I/O uses fopen / fread / fwrite; the arena allocates large blocks with malloc. - Floating point: not needed in stage 0. - Implicit switch fall-through: every non-empty case ends in break, return, continue or goto. ### Banned Functions | Banned | Why | Use instead | | --- | --- | --- | | strcpy, strcat, strncpy, strncat, strlcpy, strlcat | Unbounded copies, or results that may not be NUL-terminated | Explicit lengths with memcpy; project string helpers | | sprintf, vsprintf | No bounds | snprintf, vsnprintf (check the return value) | | gets | No bounds | fgets / fread | | scanf, fscanf, sscanf and their v variants | Unbounded %s, weak error reporting | Hand-written lexing, the strtol family | | atoi, atol, atoll, atof | No error detection | The strtol family with checks | | strtok, strtok_r | Hidden state, modifies input | Explicit scanning | | gmtime, localtime, ctime, asctime (and _r), time, clock | Shared static buffers; time makes output nondeterministic | Not needed in stage 0 | | tmpnam, mktemp, tmpfile | Race-prone temporary files | The build system provides paths | | system, getenv, signal, raise | Shell injection, nondeterminism, async hazards | Command-line arguments | | setjmp, longjmp | Non-local control flow complicates review and cleanup | Error codes | | rand, srand | Nondeterminism | Not needed | | realloc used directly | Easy to leak or misuse on failure | Arena allocation; a checked wrapper if growth is needed | Additional rules in the same spirit: - No open-coded arithmetic in allocation sizes. Sizes go through an overflow-checked helper (cs_mul_size, cs_add_size). - No %p and n"},
{"slug":"reference/operators-expressions","index":false,"title":"Operators and Expressions","order":5,"tags":["operators","expressions","precedence","arithmetic"],"headings":[{"depth":2,"text":"Operator Precedence (highest to lowest)","id":"operator-precedence-highest-to-lowest"},{"depth":3,"text":"1. Primary Expressions","id":"1-primary-expressions"},{"depth":3,"text":"2. Custom Unary Operators","id":"2-custom-unary-operators"},{"depth":3,"text":"3. Postfix Operators","id":"3-postfix-operators"},{"depth":3,"text":"4. Unary Prefix Operators","id":"4-unary-prefix-operators"},{"depth":3,"text":"5. Binary Root Operator","id":"5-binary-root-operator"},{"depth":3,"text":"6. Exponentiation (right-associative)","id":"6-exponentiation-right-associative"},{"depth":3,"text":"7. Multiplicative","id":"7-multiplicative"},{"depth":3,"text":"8. String Concatenation","id":"8-string-concatenation"},{"depth":3,"text":"9. Additive","id":"9-additive"},{"depth":3,"text":"10. Bit Shifts","id":"10-bit-shifts"},{"depth":3,"text":"11. Comparison Operators","id":"11-comparison-operators"},{"depth":3,"text":"12. Equality Operators","id":"12-equality-operators"},{"depth":3,"text":"13. Bitwise AND","id":"13-bitwise-and"},{"depth":3,"text":"14. Bitwise XOR","id":"14-bitwise-xor"},{"depth":3,"text":"15. Bitwise OR","id":"15-bitwise-or"},{"depth":3,"text":"16. Logical AND","id":"16-logical-and"},{"depth":3,"text":"17. Logical OR","id":"17-logical-or"},{"depth":3,"text":"18. Custom Binary Operators","id":"18-custom-binary-operators"},{"depth":3,"text":"19. Assignment","id":"19-assignment"},{"depth":2,"text":"Context-Aware Multiplication","id":"context-aware-multiplication"},{"depth":2,"text":"Bitwise Operations","id":"bitwise-operations"},{"depth":2,"text":"Pointer Operations and Contexts","id":"pointer-operations-and-contexts"},{"depth":3,"text":"Decorated Operators","id":"decorated-operators"}],"links":["reference/memory-management"],"text":"## Operator Precedence (highest to lowest) ### 1. Primary Expressions ### 2. Custom Unary Operators ### 3. Postfix Operators ### 4. Unary Prefix Operators ### 5. Binary Root Operator ### 6. Exponentiation (right-associative) ### 7. Multiplicative ### 8. String Concatenation ### 9. Additive ### 10. Bit Shifts ### 11. Comparison Operators ### 12. Equality Operators ### 13. Bitwise AND ### 14. Bitwise XOR ### 15. Bitwise OR ### 16. Logical AND ### 17. Logical OR ### 18. Custom Binary Operators ### 19. Assignment #=, ~= and := are the *address-context* assignment operators. They are only meaningful with a pointer on the left. See Memory Management. > [!question] Open > This table is incomplete. Unary -, + and !, a bitwise NOT, ++ / --, the compound assignments (+= and the rest), the ternary ?:, the comma operator, elementwise multiplication and the meaning of unary .. are all used somewhere in the reference or were part of the original design, but have no agreed place in the table. They are being settled in cesiumlang/cesium#15; the clash between decorated operators and postfix ~ is cesiumlang/cesium#28. ## Context-Aware Multiplication Cesium's multiplication operator (*) behaves differently based on the types of its operands: ## Bitwise Operations Cesium uses >< for XOR to distinguish it clearly from other operations: ## Pointer Operations and Contexts Address space and data space are separate, and the rule is not to mix them. - Data context (the default). A pointer used with ordinary operators is dereferenced automatically. There is no dereference operator. a + p with a pointer p reads the value p points to and yields a number; assigning that number to a pointer-typed variable is a compile error. - Address context. The address-context assignments (#=, ~=, :=) and the *decorated* operators work on the address itself. Ordinary operators never do address arithmetic. ### Decorated Operators Address arithmetic uses operators decorated with the pointer's sigil. There are two families: #-decorated (such as #+) and ~-decorated (such as ~+), including in-place forms such as p#++. They are only valid in a pointer context; both kinds of borrow are pointer contexts. - Arrays do not decay to pointers: a pointer is set to an explicit element, and #q[i] means #(q[i]). - Advancing a mutable borrow is a request to borrow the new address. - The result of a ~-decorated operation may be assigned to an immutable (#T) pointer, because the receiver is more restrictive. > [!question] Open > The full list of decorated operators, the spelling of prefix increment, the rule that parentheses open a value context inside an address context, and addrcontext() come from the September 2025 design and have not been reconciled with the rules above. See item 6 of cesiumlang/cesium#15. Whether the result of a #-decorated operation may go into a ~T pointer was assumed to be an error but not confirmed (cesiumlang/cesium#12, round 5)."},
{"slug":"compiler/freestanding","index":false,"title":"Freestanding Targets","order":6,"tags":["compiler","freestanding","targets"],"headings":[{"depth":2,"text":"Host and Target Are Independent","id":"host-and-target-are-independent"},{"depth":2,"text":"Library Layering","id":"library-layering"},{"depth":2,"text":"Compiler-Runtime Builtins","id":"compiler-runtime-builtins"},{"depth":2,"text":"Controls for Kernel Code","id":"controls-for-kernel-code"},{"depth":2,"text":"Output Formats","id":"output-formats"},{"depth":2,"text":"Consequences","id":"consequences"}],"links":["compiler/mir"],"text":"> [!info] Source > ADR 0003: freestanding targets. Status: accepted as a plan; implementation not started. The Cesium compiler only needs to *run* on hosted platforms, but it must *produce* code for freestanding targets: Cesium must be usable to write an operating system that runs on bare metal. This is primarily a requirement on the language, the standard library and the runtime. ## Host and Target Are Independent - The target triple is a first-class compiler input; nothing about the host leaks into the output. - A freestanding target implies: no implicit startup code, no OS layer, no heap unless the program supplies one, no threads or thread-local storage unless the program supplies them. - Using an OS-dependent API from freestanding code is a compile error, not a link error. ## Library Layering The standard library is split in the style of Rust's core / alloc / std: | Layer | Contents | | --- | --- | | core | No OS, no allocation: math, linear algebra kernels, formatting into caller-provided buffers, atomics | | alloc | The allocator interface; the program provides the allocator | | os | Platform layers (Linux, Windows, macOS, WASI, UEFI, ...) | On freestanding targets the panic handler is user-provided and there is no unwinding. ## Compiler-Runtime Builtins A backend emits calls to helper functions when the target lacks an instruction, so Cesium must ship these for every target: 64-bit division on 32-bit ARM and PowerPC, all floating point on soft-float PowerPC, atomics on older cores, and memcpy, memset, memmove and memcmp. ## Controls for Kernel Code Most of these map onto LLVM IR attributes and target features, so the middle IR must carry them through: | Need | Mechanism | | --- | --- | | Inline assembly, naked functions | inline asm, naked | | Interrupt and exception handlers | special calling conventions | | Kernel code that must not touch FPU or SIMD registers | per-function target features | | No red zone in x86-64 kernel code | noredzone | | Kernel code models; static, PIC or PIE relocation models | target machine options | | Explicit sections and symbol placement | section, align | | Memory-mapped I/O and device registers | volatile loads and stores; explicit layout and packing | | Atomics with explicit memory ordering | atomic instructions | | Stack probes off or controlled | probe-stack | These attributes are available only with the LLVM backend. Building a kernel requires LLVM; the QBE lowering rejects them with a clear error. > [!question] Open > How these controls are *spelled in Cesium source* is not designed. ADR 0003 states what the compiler must be able to express, not the syntax. The layout and performance features drafted for the reference (align(), pack(), inline) were never decided: cesiumlang/cesium#56. ## Output Formats - ELF kernels with linker scripts. - PE/COFF UEFI applications. - Raw flat binaries for bootloaders and firmware. - DWARF debug information for debugging under an emulator. ## Consequences - The core layer and the compiler-runtime builtins must exist before any freestanding target works. They are also what hosted targets build on. - The middle IR needs per-function attributes (calling convention, target features, red zone, stack probes, sections) from the start. - Stage 0 does not need freestanding support, but the compiler written in Cesium should not assume a hosted target anywhere in its code generation path."},
{"slug":"reference/control-flow","index":false,"title":"Control Flow","order":6,"tags":["control-flow","conditionals","loops","pattern-matching"],"headings":[{"depth":2,"text":"Conditional Statements","id":"conditional-statements"},{"depth":3,"text":"If-Else Statements","id":"if-else-statements"},{"depth":2,"text":"Loops","id":"loops"},{"depth":3,"text":"While Loops","id":"while-loops"},{"depth":3,"text":"Do-While Loops","id":"do-while-loops"},{"depth":3,"text":"For Loops with Ranges","id":"for-loops-with-ranges"},{"depth":3,"text":"Collection Iteration","id":"collection-iteration"},{"depth":2,"text":"Pattern Matching","id":"pattern-matching"},{"depth":3,"text":"Switch Statements","id":"switch-statements"},{"depth":3,"text":"Fallthrough Behavior","id":"fallthrough-behavior"},{"depth":3,"text":"Type Matching","id":"type-matching"},{"depth":2,"text":"Loop Control","id":"loop-control"},{"depth":3,"text":"Break and Continue","id":"break-and-continue"},{"depth":2,"text":"Range Syntax","id":"range-syntax"}],"links":[],"text":"## Conditional Statements ### If-Else Statements ## Loops ### While Loops ### Do-While Loops ### For Loops with Ranges ### Collection Iteration ## Pattern Matching ### Switch Statements ### Fallthrough Behavior ### Type Matching ## Loop Control ### Break and Continue ## Range Syntax Cesium provides several range operators for convenient iteration: | Syntax | Description | Example | | --- | --- | --- | | a..b | Exclusive range | 0..10 → 0,1,2,...,9 | | a..=b | Inclusive range | 0..=10 → 0,1,2,...,10 | | a..step..=b | Stepped inclusive | 0..2..=10 → 0,2,4,6,8,10 | | a..step..b | Stepped exclusive | 0..2..10 → 0,2,4,6,8 |"},
{"slug":"reference/functions","index":false,"title":"Functions","order":7,"tags":["functions","generics","overloading","variadics"],"headings":[{"depth":2,"text":"Function Declaration","id":"function-declaration"},{"depth":3,"text":"Basic Functions","id":"basic-functions"},{"depth":3,"text":"Functions with Ownership","id":"functions-with-ownership"},{"depth":3,"text":"Read-Only Methods","id":"read-only-methods"},{"depth":2,"text":"Function Qualifiers","id":"function-qualifiers"},{"depth":2,"text":"Generic Functions","id":"generic-functions"},{"depth":3,"text":"Basic Generics","id":"basic-generics"},{"depth":3,"text":"Multiple Type Parameters","id":"multiple-type-parameters"},{"depth":2,"text":"Variadic Functions","id":"variadic-functions"},{"depth":3,"text":"Type-Safe Variadics","id":"type-safe-variadics"},{"depth":3,"text":"C-Style Variadics","id":"c-style-variadics"},{"depth":2,"text":"Operator Overloading","id":"operator-overloading"},{"depth":3,"text":"Built-in Operator Overloading","id":"built-in-operator-overloading"},{"depth":3,"text":"Custom Operators","id":"custom-operators"},{"depth":2,"text":"Rules from the Original Design","id":"rules-from-the-original-design"},{"depth":2,"text":"Function Syntax Summary","id":"function-syntax-summary"}],"links":["reference/memory-management"],"text":"## Function Declaration ### Basic Functions ### Functions with Ownership Pointer parameters and return values say whether they borrow or own. A leading : marks ownership; without it the pointer is a borrow. At the call site a pointer is passed bare, and a plain value has its address taken explicitly with # (for a #T parameter) or ~ (for a ~T parameter): Owned return values are marked one by one, so mixed returns work: :~Matrix, u8 = try_invert(#Matrix m) { ... }. See Memory Management for the full rules. ### Read-Only Methods Inside a struct, an unprefixed method takes this as a mutable borrow and so cannot be called through a # pointer. A read-only method is declared with # before its name: ## Function Qualifiers ## Generic Functions ### Basic Generics ### Multiple Type Parameters ## Variadic Functions ### Type-Safe Variadics ### C-Style Variadics ## Operator Overloading ### Built-in Operator Overloading ### Custom Operators ## Rules from the Original Design These rules were set in the September 2025 design sessions and are recorded in cesiumlang/cesium#18. Some are being re-examined by the design audit (cesiumlang/cesium#33, cesiumlang/cesium#46). - Overloading uses compile-time multiple dispatch: an exact type match first, then promotions; the most specific overload wins; ambiguity is a compile error. Operators are sugar for functions. - No prototypes or forward declarations. Declaration order does not matter. - Variadics: C-style ... is allowed only in extern import blocks and is a compile error elsewhere. A Cesium-style variadic that is exported gets a generated C-compatible wrapper. - Operator overloading is limited to the predefined operators and $name$ operators. New symbol sequences cannot be invented. - Function qualifiers: operator, context, property, static, private, secret, destruct. > [!question] Open > The form T = name(params) { cannot always be told apart from an assignment (cesiumlang/cesium#27), angle-bracket generics collide with comparison operators (cesiumlang/cesium#29), the ternary operator used on this page has no precedence level yet (cesiumlang/cesium#15), and there is no example of receiving multiple return values because that syntax has not been written down (cesiumlang/cesium#18). The generic max example on this page also shares its name with the built-in max over slices (cesiumlang/cesium#20). ## Function Syntax Summary - Return type comes before the = sign - Multiple return types are comma-separated - void indicates no return value - #T and ~T parameters borrow (read-only and read-write); :#T and :~T parameters take ownership - :#T and :~T return values hand ownership to the caller; plain #T and ~T return values are borrows - A method declared with # before its name (T = #name() { ... }) is read-only; other methods take a mutable this - Generic parameters use angle brackets: <T> - Variadic parameters use ellipsis: ...Type name"},
{"slug":"reference/memory-management","index":false,"title":"Memory Management","order":8,"tags":["memory","ownership","allocation","defer"],"headings":[{"depth":2,"text":"The Model","id":"the-model"},{"depth":2,"text":"Allocation and Deallocation","id":"allocation-and-deallocation"},{"depth":3,"text":"`free`","id":"free"},{"depth":3,"text":"`null` and `undefined`","id":"null-and-undefined"},{"depth":2,"text":"Owners","id":"owners"},{"depth":2,"text":"Ownership in Function Signatures","id":"ownership-in-function-signatures"},{"depth":2,"text":"Defer Statements","id":"defer-statements"},{"depth":2,"text":"Context Managers","id":"context-managers"},{"depth":3,"text":"Defining Context Managers","id":"defining-context-managers"},{"depth":3,"text":"Using Context Managers","id":"using-context-managers"},{"depth":2,"text":"`destruct`","id":"destruct"},{"depth":2,"text":"Memory Safety Rules","id":"memory-safety-rules"},{"depth":2,"text":"Open Questions","id":"open-questions"}],"links":["reference/object-oriented"],"text":"Cesium has no garbage collector and no reference counting. Memory is managed explicitly, and the compiler checks that every owned object is released exactly once. > [!info] Source > The rules on this page are the ownership design recorded in cesiumlang/cesium#11 (decided 2026-11-16). Questions that design leaves open are marked \"Open\" with a link to the issue where they are being discussed. ## The Model Ownership and borrowing are properties of pointers only. A plain value is just a value, and = on it copies. A pointer either *borrows* the memory it points at or *owns* it. Separately, the sigil in its type says whether the data can be modified through it: #T is read-only, ~T is read-write. | Declaration | Kind | Data through the pointer | | --- | --- | --- | | #T p #= q; | immutable borrow | read-only | | ~T p ~= q; | mutable borrow | read-write | | #T p := f(); | owner | read-only | | ~T p := f(); | owner | read-write | - #=, ~= and := are *address-context* operators: they set where the pointer points. #= borrows immutably, ~= borrows mutably, := takes ownership. - The sigil and the operator must agree. ~T p #= q; and #T p ~= q; are compile errors. - := needs a pointer on the left. Matrix m := f(); is a compile error. - Plain = on a pointer assigns *through* it (pointers are dereferenced by default), so it is never how a pointer is initialized. - A borrow may be re-pointed with a later #= or ~=. ## Allocation and Deallocation alloc(count) allocates count elements. The element type comes from the pointer being initialized, and the result is owned, so it is received with :=. ### free - Only the owner may free. A borrower never can. - free(p) runs the type's destruct function, releases the memory, and resets p to undefined. - free on a null or undefined pointer is a defined no-op. - A free that the compiler can prove is redundant, such as a second free in straight-line code, is a compile error. The no-op covers only the cases the compiler cannot decide. ### null and undefined - undefined is a keyword. For a pointer it is a defined \"owns nothing\" state: null in optimized builds, and optionally a distinct trap sentinel in debug or sanitizer builds. For a plain value it means truly uninitialized. - null is a value assigned deliberately. undefined means never assigned, or freed. The two are different. - There is no test for undefined. > [!question] Open > realloc, copy and the behavior of alloc on failure are not settled: how realloc is typed under the ownership rules (it consumes an owner and returns one), the argument list of copy, and whether allocation failure is reported as an error value or as null. See cesiumlang/cesium#17 and open question 12 of cesiumlang/cesium#11. ## Owners 1. Every owner must be released. An owner that reaches the end of its scope without being freed, moved or returned is a compile error. (This is stricter than Rust, which frees automatically at the end of the scope.) 2. Reassigning an owner that still owns is a compile error. Free or move the old memory first. 3. Moving: #T b := a; where a is an owner transfers ownership to b. Using a afterwards is a compile error. 4. Mutability on transfer: the receiver may be more restrictive than the source, never less. A ~ owner can be received as #T; a # owner cannot be received as ~T. 5. In-place modification of owned data needs a ~ owner. Taking a mutable borrow from a # owner is a compile error. ## Ownership in Function Signatures Arguments are type-checked strictly: - A pointer is passed bare: f(p). A ~T pointer may be passed to a #T parameter, but nothing that is not mutable may be passed to a ~T parameter. - A plain value needs its address taken explicitly: f(#x) for a #T parameter, f(~x) for a ~T parameter. Bare f(x) with a plain x is a compile error. Ownership that crosses a function boundary is marked with : in front of the sigil: | Spelling | Where | Meaning | | --- | --- | --- | | #T / ~T | parameter | the function borrows the argument | | :#T / :~T | pa"},
{"slug":"reference/object-oriented","index":false,"title":"Object-Oriented Programming","order":9,"tags":["oop","structs","inheritance","traits","properties"],"headings":[{"depth":2,"text":"Struct Definition and Usage","id":"struct-definition-and-usage"},{"depth":3,"text":"Basic Struct Definition","id":"basic-struct-definition"},{"depth":3,"text":"Usage","id":"usage"},{"depth":2,"text":"Inheritance","id":"inheritance"},{"depth":3,"text":"Single Inheritance","id":"single-inheritance"},{"depth":3,"text":"Multiple Inheritance","id":"multiple-inheritance"},{"depth":2,"text":"Properties","id":"properties"},{"depth":3,"text":"Property Definition","id":"property-definition"},{"depth":3,"text":"Property Usage","id":"property-usage"},{"depth":2,"text":"Traits and Implementation","id":"traits-and-implementation"},{"depth":3,"text":"Defining Traits","id":"defining-traits"},{"depth":3,"text":"Implementing Traits","id":"implementing-traits"},{"depth":3,"text":"Generic Functions with Traits","id":"generic-functions-with-traits"},{"depth":2,"text":"Access Modifiers","id":"access-modifiers"},{"depth":2,"text":"Method Types","id":"method-types"},{"depth":2,"text":"Rules from the Original Design","id":"rules-from-the-original-design"}],"links":[],"text":"## Struct Definition and Usage ### Basic Struct Definition ### Usage An unprefixed method takes this as a mutable borrow, so it cannot be called through a #Point pointer. A method declared with # before its name is read-only and can. ## Inheritance ### Single Inheritance > [!question] Open > How a destructor calls its parent's destructor has no agreed spelling. The original example used the C++-style super ~Point();, but destructors were renamed to destruct Name() because prefix ~ now means a mutable borrow. See cesiumlang/cesium#18 and, for destructors and overrides reached through a base pointer, cesiumlang/cesium#31. ### Multiple Inheritance ## Properties ### Property Definition ### Property Usage ## Traits and Implementation ### Defining Traits ### Implementing Traits ### Generic Functions with Traits ## Access Modifiers | Modifier | Visibility | | --- | --- | | (default) | Public - accessible everywhere | | private | Module-scoped - accessible within the same module | | secret | Class-scoped - accessible only within the class/struct | > [!question] Open > private is described two ways in the reference: module-scoped (this table) and \"accessible to subclasses\" (the Point example at the top of this page). Which one holds, or whether both do in different places, is being decided in cesiumlang/cesium#13. ## Method Types - Instance methods: Access this implicitly, as a mutable borrow - Read-only methods: Declared with # before the name; can be called through a #T pointer - Static methods: No this parameter, called on type - Properties: Special methods for field-like access - Constructors: Named same as struct, initialize instances - Destructors: Declared as destruct Name(). Run when a plain value goes out of scope, and as part of free for an owned pointer ## Rules from the Original Design These rules were set in the September 2025 design sessions and are recorded in cesiumlang/cesium#18. They are listed here so the page is complete; several are being re-examined by the design audit (cesiumlang/cesium#30, cesiumlang/cesium#31). - There are no virtual functions. All dispatch is static. - static is required on a method that does not use this; leaving it out is a compile error, and so is using this in a static method. - A default constructor is generated when none is written. It calls the parent constructors left to right and applies the field defaults. - With multiple inheritance, constructors run left to right. For conflicting members the rightmost parent wins; T = Parent.method; overrides that choice. - Properties can be overridden in subclasses. - Traits may contain private and secret members. > [!question] Open > Some examples on this page are known not to fit together yet and are waiting on cesiumlang/cesium#18: three different ways of constructing a struct appear in the reference (Point p1(3.0, 4.0);, Point(0.0, 0.0) and the literal Calculator { last_result = 0.0 }) with no rule for when each applies; Circle has both a field and a setter property named radius; and the trait Comparable declares compare(type other) while its implementation writes compare(Circle other)."},
{"slug":"reference/error-handling","index":false,"title":"Error Handling","order":10,"tags":["errors","exceptions","error-types","catch"],"headings":[{"depth":2,"text":"Error Type Definition","id":"error-type-definition"},{"depth":3,"text":"Defining Error Types","id":"defining-error-types"},{"depth":2,"text":"Error Propagation Methods","id":"error-propagation-methods"},{"depth":3,"text":"Returning Errors","id":"returning-errors"},{"depth":3,"text":"Throwing Errors","id":"throwing-errors"},{"depth":2,"text":"Error Handling with Catch","id":"error-handling-with-catch"},{"depth":3,"text":"Basic Error Catching","id":"basic-error-catching"},{"depth":3,"text":"Pattern Matching on Errors","id":"pattern-matching-on-errors"},{"depth":3,"text":"Multiple Error Types","id":"multiple-error-types"},{"depth":3,"text":"Catching Thrown Errors","id":"catching-thrown-errors"},{"depth":2,"text":"Error Handling with Context Managers","id":"error-handling-with-context-managers"},{"depth":2,"text":"Error Handling Strategies","id":"error-handling-strategies"}],"links":["reference/memory-management"],"text":"> [!question] Open > The examples on this page come from the first draft of the reference, and the semantics behind them are still being decided in cesiumlang/cesium#17 and cesiumlang/cesium#40. In particular: > > - Variables such as file_or_error, data and result are declared without a type, which the language does not allow; what type a value-or-error has, and whether an error union is the same construct as union, is not decided. > - The rules proposed in September 2025 for throw and catch are not yet confirmed: throw pushes onto a last-in, first-out error stack and catch loops over every error on it; catch { ... } with no case is an implied else; catch (name) { ... } binds the error to name; catch is a special case of switch; error types share struct syntax and semantics; abstract methods return a NoImpl error. > - Whether allocation failure is an error value or null is open. > > What *is* decided is how cleanup interacts with errors: defer is block-scoped and free runs destruct. See Memory Management. ## Error Type Definition ### Defining Error Types ## Error Propagation Methods ### Returning Errors ### Throwing Errors ## Error Handling with Catch ### Basic Error Catching ### Pattern Matching on Errors ### Multiple Error Types ### Catching Thrown Errors ## Error Handling with Context Managers ## Error Handling Strategies 1. Return Errors: For expected failures that should halt processing 2. Throw Errors: For recoverable errors in batch operations 3. Pattern Matching: Use case statements to handle specific error types 4. Resource Safety: Combine with with statements for automatic cleanup"},
{"slug":"reference/modules-imports","index":false,"title":"Modules and Imports","order":11,"tags":["modules","imports","namespaces","extern"],"headings":[{"depth":2,"text":"Module Structure","id":"module-structure"},{"depth":3,"text":"Basic Module Definition","id":"basic-module-definition"},{"depth":2,"text":"Import Syntax","id":"import-syntax"},{"depth":3,"text":"Basic Imports","id":"basic-imports"},{"depth":3,"text":"Selective Imports","id":"selective-imports"},{"depth":3,"text":"Using Imported Functions","id":"using-imported-functions"},{"depth":2,"text":"External Library Integration","id":"external-library-integration"},{"depth":3,"text":"C Library Imports","id":"c-library-imports"},{"depth":3,"text":"Platform-Specific Imports","id":"platform-specific-imports"},{"depth":2,"text":"Module Interface Files","id":"module-interface-files"},{"depth":3,"text":"Interface Definition","id":"interface-definition"},{"depth":2,"text":"Import Variants","id":"import-variants"},{"depth":3,"text":"Import Styles","id":"import-styles"},{"depth":2,"text":"Standard Library Modules","id":"standard-library-modules"},{"depth":3,"text":"Core Modules","id":"core-modules"},{"depth":3,"text":"Example Usage","id":"example-usage"},{"depth":2,"text":"Rules from the Original Design","id":"rules-from-the-original-design"},{"depth":2,"text":"Module Organization Best Practices","id":"module-organization-best-practices"}],"links":["reference/memory-management"],"text":"## Module Structure ### Basic Module Definition ## Import Syntax ### Basic Imports ### Selective Imports ### Using Imported Functions ## External Library Integration ### C Library Imports ### Platform-Specific Imports ## Module Interface Files Module interface files use the .csi extension. They exist so that a closed-source Cesium library can be imported without extern. ### Interface Definition ## Import Variants ### Import Styles | Syntax | Effect | Example Usage | | --- | --- | --- | | import(module) | Import with full namespace | module.function() | | import(module) as alias | Import with custom namespace | alias.function() | | import(module) { item } | Selective import | item() | | import(module) { item as name } | Selective import with rename | name() | | import(module) { export item } | Import as global | item() | ## Standard Library Modules ### Core Modules ### Example Usage ## Rules from the Original Design These rules were set in the September 2025 design sessions and are recorded in cesiumlang/cesium#19. The compilation model behind them is being re-examined in cesiumlang/cesium#47. - No transitive imports. A name is only reachable from the module that defines it. - A namespace name that collides with any other identifier is a compile error; alias the namespace to resolve it. - Namespaces are not tied to file paths. - A namespace or a sub-namespace can be imported; selective imports are preferred. - alias can be used anywhere to rename things: functions, parameters, enum values, types. - Circular dependencies are resolved by compile order across the files in a namespace. - Generating a C header for exported functions is an opt-in compiler flag. > [!question] Open > Several things on this page are not settled and are tracked in cesiumlang/cesium#19: the alias form (import(std.io) as io; here, against the assignment form io = import(std.io) in the original design), where semicolons go in import blocks, which std.* modules are available without an import, whether HashMap / ArrayList and the allocator types exist, and the single-quoted library names. Known problems in the examples: math.vector.add is called but never defined, 'unistd' is a header and not a library, and target_os is spelled TARGET_OS on the built-in functions page. The ArenaAllocator example also initializes a pointer with plain =, which the ownership rules do not allow (Memory Management); it is left as it is until the allocator types are decided. ## Module Organization Best Practices 1. Use descriptive namespaces: graphics.primitives rather than gfx.p 2. Keep interfaces minimal: Only export what's necessary 3. Group related functionality: Put related types and functions together 4. Use module interface files: For large modules, provide .csi files 5. Avoid circular dependencies: Structure modules hierarchically"},
{"slug":"reference/builtin-functions","index":false,"title":"Built-in Functions","order":12,"tags":["builtin","functions","io","math","introspection"],"headings":[{"depth":2,"text":"I/O Functions","id":"io-functions"},{"depth":3,"text":"Formatted Output","id":"formatted-output"},{"depth":2,"text":"Mathematical Functions","id":"mathematical-functions"},{"depth":3,"text":"Trigonometric Functions","id":"trigonometric-functions"},{"depth":3,"text":"Rounding Functions","id":"rounding-functions"},{"depth":3,"text":"Root Functions","id":"root-functions"},{"depth":2,"text":"Type Introspection","id":"type-introspection"},{"depth":3,"text":"Type and Size Information","id":"type-and-size-information"},{"depth":2,"text":"Assertion and Debugging","id":"assertion-and-debugging"},{"depth":3,"text":"Runtime Assertions","id":"runtime-assertions"},{"depth":3,"text":"Compile-time Assertions","id":"compile-time-assertions"},{"depth":2,"text":"Memory Management Functions","id":"memory-management-functions"},{"depth":3,"text":"Basic Allocation","id":"basic-allocation"},{"depth":3,"text":"Memory Operations","id":"memory-operations"},{"depth":2,"text":"String Functions","id":"string-functions"},{"depth":3,"text":"String Operations","id":"string-operations"},{"depth":2,"text":"Aggregate Functions","id":"aggregate-functions"},{"depth":3,"text":"Statistical Functions","id":"statistical-functions"},{"depth":2,"text":"System Functions","id":"system-functions"},{"depth":3,"text":"Environment Access","id":"environment-access"},{"depth":2,"text":"Built-in Constants","id":"built-in-constants"},{"depth":3,"text":"Mathematical Constants","id":"mathematical-constants"},{"depth":3,"text":"System Constants","id":"system-constants"}],"links":["reference/lexical-structure","reference/memory-management"],"text":"> [!question] Open > Much of this page was generated with the first draft of the reference and has no recorded decision behind it. Which of these functions and constants exist, which names are reserved and which can be shadowed, and how this page relates to the list in Lexical Structure is being decided in cesiumlang/cesium#20. Treat everything here except the allocation section as unconfirmed. Specific doubts: typeof returning a str; the C-style strlen / strcmp / strcat / strcpy (when str tracks its length and ** concatenates); move as a memory function; and copy, zero, compare, getenv, system, exit, e, sqrt2, ln2, POINTER_SIZE, TARGET_OS and TARGET_ARCH, of which only copy was ever discussed. ## I/O Functions ### Formatted Output ## Mathematical Functions ### Trigonometric Functions ### Rounding Functions ### Root Functions ## Type Introspection ### Type and Size Information ## Assertion and Debugging ### Runtime Assertions ### Compile-time Assertions ## Memory Management Functions ### Basic Allocation alloc returns ownership, so its result is received with :=. Only the owner may free; free on a null or undefined pointer is a no-op. See Memory Management. > [!question] Open > How realloc is typed under the ownership rules, and what alloc does on failure, are not decided (cesiumlang/cesium#17; open question 12 of cesiumlang/cesium#11). ### Memory Operations ## String Functions ### String Operations ## Aggregate Functions ### Statistical Functions ## System Functions ### Environment Access ## Built-in Constants ### Mathematical Constants ### System Constants"},
{"slug":"reference/assembly","index":false,"title":"Inline Assembly","order":13,"tags":["assembly"],"headings":[{"depth":2,"text":"What Is Settled","id":"what-is-settled"},{"depth":2,"text":"What the Compiler Must Support","id":"what-the-compiler-must-support"}],"links":["reference/variables-constants","compiler/freestanding"],"text":"> [!info] Status > This page records what the September 2025 design sessions settled about inline assembly, as listed in cesiumlang/cesiumlang.org#11. No syntax beyond what is stated here has been designed, so there are no examples yet. ## What Is Settled - Inline assembly is written in asm { ... } blocks. asm is a keyword. - A block contains raw, unqualified assembly in Intel syntax (the MSVC style). There are no GCC-style constraint strings. - Variables are referenced by name inside the block. - The hardware qualifiers volatile, atomic, register and simd were added in the same discussion; see Variables and Constants. Existing operators work on simd types. Inline assembly is not part of the S0 subset that the first compiler stage accepts. ## What the Compiler Must Support Freestanding targets (kernels, bootloaders, firmware) need inline assembly together with naked functions, interrupt calling conventions and control over sections. These are requirements on the compiler, recorded in ADR 0003 and summarized in Freestanding Targets. They are available only with the LLVM backend. > [!question] Open > Not designed: how a block names the registers it reads, writes and clobbers; how the same source serves more than one architecture; and how asm relates to the borrow checker, since assembly can read and write memory the checker knows nothing about (cesiumlang/cesium#45). Whether register stays in the language is part of the scope question in cesiumlang/cesium#58."},
{"slug":"reference/grammar","index":false,"title":"Grammar Reference","order":14,"tags":["grammar"],"headings":[{"depth":2,"text":"What Exists Today","id":"what-exists-today"},{"depth":2,"text":"Known Gaps","id":"known-gaps"}],"links":["spec","spec/lexical","spec/s0-grammar"],"text":"Cesium does not have a complete formal grammar yet. Writing one is tracked in cesiumlang/cesium#57, and it is being published as part of the language specification (cesiumlang/cesiumlang.org#13). ## What Exists Today | Resource | What it is | | --- | --- | | Language Specification (draft) | The formal definition, in progress | | Specification: Lexical Structure | Tokens, comments, identifiers, keywords and literals, with the undecided parts marked | | Specification: S0 Grammar | An EBNF grammar for the S0 subset, the part of the language the first compiler stage accepts | | cesiumlang/grammar | The TextMate grammar used for syntax highlighting on this site and in editors. It is regex-based and is not a definition of the language | ## Known Gaps These syntax questions have to be answered before a grammar for the full language can be written: | Question | Issue | | --- | --- | | Function definitions (T = name(...) {) cannot always be told apart from assignments | cesiumlang/cesium#27 | | Decorated operators collide with postfix transpose; bitwise NOT has no spelling | cesiumlang/cesium#28 | | Angle-bracket generics are ambiguous with comparison operators | cesiumlang/cesium#29 | | Several operators have no precedence level | cesiumlang/cesium#15 | | Numeric literal forms are not specified | cesiumlang/cesium#56 | | String and character literals, escapes | cesiumlang/cesium#39 | | The reserved-word list | cesiumlang/cesium#50 |"},
{"slug":"reference/compilation","index":false,"title":"Compilation Model","order":15,"tags":["compilation"],"headings":[{"depth":2,"text":"Source Files","id":"source-files"},{"depth":2,"text":"The Compiler","id":"the-compiler"},{"depth":2,"text":"Properties of Compiled Programs","id":"properties-of-compiled-programs"},{"depth":2,"text":"Target Platforms","id":"target-platforms"}],"links":["compiler","compiler/bootstrap","compiler/mir","reference/type-system","compiler/freestanding"],"text":"This page summarizes how Cesium programs are compiled, from the point of view of someone writing Cesium. The compiler's internals are described in Compiler and Toolchain. > [!info] Source > Decision records cesiumlang/cesium#4, #5, #6 and #7. These are accepted plans; the compiler is not yet implemented. ## Source Files - Cesium source files use the .csm extension. - Module interface files use the .csi extension. ## The Compiler - One self-contained binary. The compiler needs no separate toolchain: no C compiler, no SDK and no system libc on the user's machine. The linker is built in. - The compiler is written in Cesium and reaches its first working version through a bootstrap chain that starts from a small compiler written in portable C. - Two backends behind a middle IR. Every program is lowered to Cesium's middle IR, and from there to one of two backends: - QBE for development, bootstrapping and quick ports to new architectures; - LLVM as the release backend, for optimization, vectorization, full debug information and every supported target. QBE comes first; LLVM is added later and is what releases use. ## Properties of Compiled Programs - libc-free. Natively built Cesium programs do not depend on a C library. The standard library talks to the operating system directly. Programs that link C libraries which need libc use a hosted link mode. - C ABI compatible. Cesium functions can call and be called from C. - Static dispatch only. There are no virtual calls; overloads are resolved at compile time. - Generics are monomorphized. - No undefined behavior in arithmetic. Integer arithmetic wraps, and shifts and division by zero have defined results, the same on every backend. See Type System. ## Target Platforms | Architecture | Platforms | | --- | --- | | x86_64 | Windows, Linux, macOS 11+, UEFI, freestanding | | aarch64 | Windows, Linux, macOS 11+, UEFI, freestanding | | 32-bit ARM | freestanding | | PowerPC 750 | freestanding | | SPIR-V | Vulkan shaders | | WebAssembly | WASI and freestanding (tier 2) | Bare-metal targets are a first-class goal: see Freestanding Targets. > [!question] Open > The parts of the compilation model that a programmer sees most directly are not designed yet: how files map to namespaces, separate compilation, what an interface file contains, and symbol naming (cesiumlang/cesium#47); the accepted signatures of main (the reference shows void = main() and i32 = main(), and the S0 subset uses i32 = main(i32 argc, ##u8 argv); tracked in cesiumlang/cesiumlang.org#10); and what comptime means (cesiumlang/cesium#55). The compiler's command line has not been specified either."},
{"slug":"reference/performance","index":false,"title":"Performance Considerations","order":16,"tags":["performance"],"headings":[{"depth":2,"text":"What Is Decided","id":"what-is-decided"}],"links":["reference/memory-management","reference/type-system"],"text":"Run-time performance for numerical code is one of Cesium's primary goals. This page states what has been decided about how the language and compiler deliver it. The language-level tuning features are not decided yet and are listed at the end. > [!info] Source > ADR 0001, ADR 0004 and the middle IR design. ## What Is Decided - No run-time dispatch. All dispatch is static, and generics are monomorphized, so every call target is known at compile time. - No garbage collector and no reference counting. Ownership is checked at compile time, with no run-time bookkeeping beyond the pointer's own value; see Memory Management. - Numerical optimization happens in the compiler's middle IR, which knows array shapes and, from the ownership rules, which pointers cannot alias. The backend receives already-structured code together with those facts. - LLVM is the release backend. Release-build code quality (vectorization, FMA, aliasing, scheduling, register allocation) matters more to Cesium than compile speed. The QBE backend is for development and bootstrapping, and performance is always measured on LLVM. - Defined arithmetic. Integer arithmetic wraps and has no undefined behavior. The optimizer may only assume more (for example, that an addition does not overflow) where the compiler has proven it. - simd types work with the existing operators; see Type System. On targets or backends without SIMD, vector operations are scalarized. > [!question] Open > The first draft of the reference listed align(), pack(), inline, likely() and comptime unroll() as tuning features. None of them was ever discussed or decided, so they are not documented here. They are tracked, together with numeric literal forms, in cesiumlang/cesium#56. The floating-point policy (contraction, reassociation, reproducibility) is part of cesiumlang/cesium#35, and the array, vector and matrix types that most numerical code depends on are cesiumlang/cesium#36."},
{"slug":"compiler","index":true,"title":"Compiler and Toolchain","order":2147483647,"tags":["compiler"],"headings":[{"depth":2,"text":"Pages","id":"pages"},{"depth":2,"text":"Decision Records","id":"decision-records"}],"links":["compiler/architecture","compiler/bootstrap","compiler/mir","compiler/s0-subset","compiler/stage0-c-dialect","compiler/freestanding","spec","reference"],"text":"This section describes how the Cesium compiler is put together: its backends, how it bootstraps, the middle IR every frontend lowers to, and the small language subset the first compiler stage accepts. > [!info] Status > These pages summarize decision records kept as issues in cesiumlang/cesium. Stage 0 (cesium0) and cesium1, a compiler for S0 written in S0, are implemented and tested in CI on Linux, macOS and Windows with the QBE backend; the rest is a plan. Where a page and its decision record disagree, the decision record wins. ## Pages - Architecture - Two backends behind a middle IR, the toolchain, the runtime model and the target platforms - Bootstrap Chain - Stage 0 in portable C, cesium1 in S0, then the real compiler; what CI builds and what contributors download - Middle IR (MIR) - The core level of the IR that every frontend lowers to - The S0 Subset - The tiny subset of Cesium that stage 0 compiles - Stage 0 C Dialect - The portable C subset stage 0 is written in - Freestanding Targets - What bare-metal targets require of the language, library and compiler ## Decision Records | Record | Subject | | --- | --- | | cesiumlang/cesium#4 | ADR 0001: compiler backend, LLVM packaging and toolchain | | cesiumlang/cesium#5 | ADR 0002: bootstrap strategy and hosting the compiler | | cesiumlang/cesium#6 | ADR 0003: freestanding targets | | cesiumlang/cesium#7 | ADR 0004: two backends, QBE first and LLVM as the primary release backend | | cesiumlang/cesium#8 | Design: Cesium middle IR (MIR) | | cesiumlang/cesium#9 | Design: stage 0 and the S0 subset | | cesiumlang/cesium#10 | Design: stage 0 C dialect | | cesiumlang/cesium#11 | Design: ownership, borrowing and lifetimes | Requirements carried over from the removed C++ prototype (documentation generator, command-line interface, logging) are in cesiumlang/cesium#64. See also the language specification draft and the language reference."},
{"slug":"","index":true,"title":"Welcome to the Cesium programming language!","order":2147483647,"tags":[],"headings":[],"links":["news","reference","spec","compiler"],"text":"This is the home of the Cesium programming language! ![GitHub Badge](https://github.com/cesiumlang/cesium) ![CI Status](https://github.com/cesiumlang/cesium/actions) ![last-commit](https://github.com/cesiumlang/cesium/commits/main) * Check out the latest status updates: News * Read the language reference docs: Docs * Follow the formal definition as it is written: Language Specification (draft) * See how the compiler is being built: Compiler and Toolchain"},
{"slug":"news/2025-09-12","index":false,"title":"First post","order":2147483647,"tags":[],"headings":[],"links":[],"text":"It's an exciting time as I'm just making the first post on the new website for the Cesium language! I actually have finished fleshing out the details of the language design, but have not yet finished writing documentation for it. I got some help from Claude to write this initial draft, but it ended up corrupting a lot of things. Bear with me as I work through each page and manually fix everything. That said, just having a framework for the documentation to start with is tremendously helpful. I'll take having to correct all the hallucinations and errors over having to come up with all of this by myself from the outset! I've already gotten some feedback from a few colleagues who are interested in this project, which is encouraging to actually keep going with this and take it a little more seriously than a toy language for my projects for my home or side business. The grind continues. I'll let everyone know when the documentation seems to have settled down, and I can actually start working on code for a first-cut lexer/parser implementation. Maybe I can get Claude to do it for me...but at least then I'll have a better baseline reference documentation describing the language. Maybe there will be fewer hallucinations next time. Let's not get our hopes up. Stay tuned!"},
{"slug":"news","index":true,"title":"News","order":2147483647,"tags":["news"],"headings":[],"links":[],"text":""},
{"slug":"reference","index":true,"title":"Cesium Language Reference","order":2147483647,"tags":["reference"],"headings":[{"depth":2,"text":"Reference Sections","id":"reference-sections"},{"depth":2,"text":"Related Sections","id":"related-sections"},{"depth":2,"text":"Quick Navigation","id":"quick-navigation"}],"links":["reference/overview","reference/lexical-structure","reference/type-system","reference/variables-constants","reference/operators-expressions","reference/control-flow","reference/functions","reference/memory-management","reference/object-oriented","reference/error-handling","reference/modules-imports","reference/builtin-functions","reference/assembly","reference/grammar","reference/compilation","reference/performance","spec","compiler"],"text":"This section contains the comprehensive reference documentation for the Cesium Programming Language v0.1. ## Reference Sections - Overview - Language goals and design philosophy - Lexical Structure - Comments, keywords, and tokens - Type System - Primitive types, arrays, pointers, and user-defined types - Variables and Constants - Declaration and qualifiers - Operators and Expressions - Operator precedence and context-aware operations - Control Flow - Conditionals, loops, and pattern matching - Functions - Declaration, generics, and operator overloading - Memory Management - Allocation, ownership, and resource management - Object-Oriented Programming - Structs, inheritance, and traits - Error Handling - Error types and propagation - Modules and Imports - Module system and external libraries - Built-in Functions - Standard library and intrinsics - Inline Assembly - Assembly blocks and hardware access - Grammar Reference - Formal language grammar - Compilation Model - Build process and optimization - Performance Considerations - Optimization and memory layout ## Related Sections - Language Specification (draft) - The formal definition that the reference pages feed into - Compiler and Toolchain - Architecture, bootstrap chain, middle IR and the S0 subset ## Quick Navigation For specific topics, use the search functionality or browse the sections above. Each section includes practical examples and detailed explanations of language features."},
{"slug":"spec","index":true,"title":"Language Specification (Draft)","order":2147483647,"tags":["spec"],"headings":[{"depth":2,"text":"How to Read This Specification","id":"how-to-read-this-specification"},{"depth":3,"text":"Status Markers","id":"status-markers"},{"depth":3,"text":"Citations","id":"citations"},{"depth":3,"text":"Grammar Notation","id":"grammar-notation"},{"depth":2,"text":"Chapters","id":"chapters"},{"depth":2,"text":"Conformance Levels","id":"conformance-levels"}],"links":["reference","spec/lexical","spec/s0-grammar","reference/memory-management","compiler/mir"],"text":"> [!warning] Draft > This specification is a skeleton. Only the chapters listed as \"Draft\" below exist, and they cover only what has been decided. Nothing here is final. Progress is tracked in cesiumlang/cesiumlang.org#13. The language reference explains Cesium by example, for people learning and using the language. This specification is the more technical document derived from it: the definition a compiler or tool can be checked against. The reference pages and their code examples are its source material, together with the decision records and design issues in cesiumlang/cesium. ## How to Read This Specification ### Status Markers Every rule carries one of three statuses. | Marker | Meaning | | --- | --- | | Decided | Recorded as a decision. The rule cites the issue or page it comes from | | Provisional | A recommendation by the editors, not a decision. Always inside a \"Provisional\" callout that names the issue where it is being discussed | | Open | Not decided. The specification states no rule and links to the issue | If a rule has no citation, treat it as a defect in the specification and report it. ### Citations Rules cite their source in square brackets: - [cesium#11 r5] is rule 5 of cesiumlang/cesium#11. Other issues in that repository are cited the same way. - [ref: page] is a page of the language reference. ### Grammar Notation Grammars are written in EBNF: | Notation | Meaning | | --- | --- | | name = ... ; | A production | | \"text\" | A terminal: the literal characters | | a b | a followed by b | | a \\| b | a or b | | [ a ] | Optional a | | { a } | Zero or more a | | ( a ) | Grouping | | (* ... *) | A comment | ## Chapters | # | Chapter | Status | | --- | --- | --- | | 1 | Introduction and conventions | This page | | 2 | Lexical structure | Draft: decided parts only | | 3 | Syntactic grammar: the S0 subset | Draft | | 3 | Syntactic grammar: S1 and the full language | Not started. Blocked on cesiumlang/cesium#27, #28, #29 and #57 | | 4 | Types | Not started. Open: cesiumlang/cesium#16, #34, #36, #38 | | 5 | Expressions | Not started. Open: cesiumlang/cesium#15, #26, #33, #35 | | 6 | Statements | Not started. Open: cesiumlang/cesium#41, #49 | | 7 | Declarations | Not started. Open: cesiumlang/cesium#19, #47, #52 | | 8 | Ownership rules | Not started. The decided rules are in cesiumlang/cesium#11 and summarized in Memory Management. Open: cesiumlang/cesium#21 to #25 | | 9 | MIR mapping | Not started. The S0 mapping is in chapter 3; the IR is described in Middle IR | | 10 | Conformance levels | Outline below | ## Conformance Levels The bootstrap chain defines nested subsets of the language ([cesium#9]). Each compiler stage must accept its level, and every later compiler must keep accepting the levels below it. | Level | Defined by | Accepted by | Status | | --- | --- | --- | --- | | S0 | Chapter 3 | Stage 0 and every later compiler | Draft | | S1 | To be written | cesium1 and every later compiler | Open: the S1 feature list is a set of candidates to be confirmed (cesiumlang/cesium#9) | | Full | The whole specification | The real compiler | Open: which features are core, planned or unproven is cesiumlang/cesium#58 | Each level is a strict subset of the next: a program that conforms to a level is a valid program of every higher level, with the same meaning ([cesium#9], rule 1). A conformance test suite of valid and invalid programs for each level is planned (cesiumlang/cesium#57, step 3)."}
]
