Skip to content

Latest commit

 

History

History
2560 lines (2085 loc) · 86.9 KB

SPEC.md

File metadata and controls

2560 lines (2085 loc) · 86.9 KB

A7 Programming Language Specification

This reference describes the current compiler where source and regression tests establish behavior. Sections marked cut, reserved, parsed-only, or proposed do not promise executable programs. Cut forms (user variadics, multi-declaration / destructuring, multi-return) fail closed at parse or semantic exit; do not treat them as future runnable syntax. Approved rules that are not yet enforced are identified separately.

The project README and release checklist are the user-facing authorities. Status records implementation gaps, and the decision ledger records approvals. This document is not a release qualification report. Examples are independent fragments unless they include the imports and entry point needed to compile on their own.

Table of Contents

  1. Introduction
  2. Lexical Structure
  3. Type System
  4. Declarations and Expressions
  5. Control Flow
  6. Functions
  7. Generics
  8. Memory Management
  9. Planned Array Programming for AI
  10. Modules and Visibility
  11. Built-in Functions and Operators
  12. Tokens and AST Components
  13. Grammar Summary

1. Introduction

1.1 Language Overview

A7 is a statically typed procedural language. The Python compiler tokenizes, parses, checks, and emits Zig source. Zig is the supported native backend. The language has fixed arrays, slices, structs, tagged and untagged unions, compile-time generics, and explicit heap allocation with new and del.

1.2 Design Philosophy

Design decisions and their compatibility boundaries live in the decision ledger. File modules have separate semantic scopes and lower into one Zig output. Tensor operations and accelerator APIs are design proposals. General lifetime and aliasing proofs remain outside the current safety contract.


2. Lexical Structure

2.1 Source Encoding

A7 source files are UTF-8. A leading UTF-8 byte-order mark is stripped before tokenizing (a7/tokens.py:240-244). The standard file extension is .a7.

Identifiers, keywords, and numeric literals use ASCII characters only (see §2.3 and §2.6). String and character literal contents and comments may hold non-ASCII characters; the tokenizer passes them through and later passes validate their range. For example, "café" lexes as one string literal, while café outside a literal is rejected at the first non-ASCII character.

Whitespace Rules:

  • Spaces (U+0020) and carriage returns (U+000D) are skipped
  • Tab characters (U+0009) are not supported and cause a lexical error
  • Vertical tab (U+000B) and form feed (U+000C) are not whitespace: each is rejected as an unexpected character
  • Newlines (U+000A) and ; each produce a statement terminator token. Consecutive terminators collapse into one, so ;;, blank lines, and a ; at a line end contribute a single terminator

2.2 Comments

// Single-line comment extends to end of line

# Hash comments work the same way: to end of line

/*
   Multi-line comment
   /* Can be nested */
*/

// and # each start a line comment that runs to (but not including) the newline; the newline still produces its terminator. /* opens a block comment that may nest. An unterminated /* is a lexical error that points at the comment's start instead of silently dropping the file.

2.3 Identifiers

identifier = ("_" | letter) (letter | digit | "_")*
letter     = "a"..."z" | "A"..."Z"  ; ASCII letters only
digit      = "0"..."9"              ; ASCII digits only

Identifier Rules:

  • Identifiers are case-sensitive
  • Must start with an ASCII letter (a-z, A-Z) or underscore
  • Can contain ASCII letters, digits (0-9), and underscores
  • Unicode characters are not supported in identifiers
  • L27 approves file-private top-level _name and compiler-reserved __name. The compiler enforces these rules at file scope. Local __name bindings remain accepted. See §10.4 for the compatibility boundary
  • Maximum length: 100 characters

2.4 Keywords

Reserved words with grammar rules:

and        bool       break      case       char       continue   defer
del        else       enum       f32        f64        fall       false
fn         for        i8         i16        i32        i64        if
import     in         isize      match      new        nil        not
or         pub        ref        ret        string     struct     true
u8         u16        u32        u64        union      usize      while

Lexed as keyword tokens but consumed by no grammar rule yet:

as         where

as is reserved for a future cast spelling; today only cast(T, v) works. where opens a generic constraint clause. Only conjunctions of set memberships are current (where T: Numeric); richer predicates are rejected (see §6.1 and §7.3).

Lexed but unused (kept for future use, rejected or ignored by the parser):

let        int        uint       float

cast, const, self, size_of, type, using, and var lex as ordinary identifiers, not keywords. using import "p" and cast(T, v) match identifiers in the parser rather than keyword tokens. not is a keyword for prefix negation. See PAR-22 in docs/audits/2026-09-16/compiler/parser.md.

2.5 Operators and Punctuation

// Arithmetic
+    -    *    /    %

// Comparison
==   !=   <    >    <=   >=

// Logical
and  or   not  !

// Bitwise
&    |    ^    ~    <<   >>

// Assignment
=    +=   -=   *=   /=   %=   &=   |=   ^=   <<=  >>=

// Generics
$    // Generic type parameter prefix

// Builtins
@    // Builtin function prefix (for example `@type_set`)

// Other
::   :    ;    ,    ()   []   {}   ..

... has no token: the tokenizer rejects it with an unsupported-operator error, so 0...5 never lexes. Use .. for slice bounds. Variadic parameter spellings that reuse .. are cut (§6.6). ? likewise has no token and is rejected as an unexpected character.

Write ASCII names after @ and $. Unlike ordinary identifiers (which require an ASCII letter or _ start), $ accepts any Unicode letter after $ with Unicode alphanumeric or _ continuation, and @ accepts any Unicode alphanumeric or _ (including digits such as @123). Non-ASCII or numeric @/$ spellings have no defined meaning.

Float % is remainder with a quotient truncated toward zero. Its nonzero result has the dividend's sign. Constant folding follows the same rule as generated Zig: -5.5 % 2.0 is -1.5, and exact negative division preserves negative zero. This does not relax the existing nonzero-divisor proof requirement.

Typed integer / truncates toward zero (backend @divTrunc). Typed integer and float % take the dividend's sign (backend @rem; float % uses math.fmod). The integer edges are defined in every build profile: MIN / -1 wraps to MIN, MIN % -1 is 0, unary -MIN wraps to MIN, and math.abs(MIN) is MIN. A shift by a run-time count that is negative or at least the operand's bit width panics with "shift count out of range" in every profile.

Constant arithmetic has one evaluator (a7/exact_constants.py) and one rule, stated in §4.2.1: values are exact, and the result must fit its destination. Nothing wraps and nothing rounds per operation. A constant that does not fit its destination exits 6. Arithmetic on typed run-time values is separate and keeps the wrapping rule above. A constant integer division or remainder by zero stays for the divisor proof, which rejects it; a constant float division or remainder by zero is a constant error.

Build profiles (ZIG_OPTIMIZE_MODE in a7/backends/zig.py): debug compiles Zig with -O Debug, release with -O ReleaseSafe, and fast with -O ReleaseFast. In release and fast the backend drops the wrapping operator suffix only where the safety pass discharged a _nonwrap proof, and --no-nonwrap keeps wrapping in every profile. release keeps Zig's runtime checks. fast removes them, so an operation whose proof is wrong is undefined behavior there.

2.6 Literals

Integer Literals

42        // Decimal
0x2A      // Hexadecimal
0o52      // Octal
0b101010  // Binary
1_000_000 // With separators

Numeric Literal Limits:

  • Maximum numeric literal length: 100 characters (including separators)
  • Underscores can be used as separators for readability. Placement is validated by the number conversion itself: 1__2 is rejected as an invalid numeric literal
  • Prefixes are lowercase only: 0x, 0o, 0b. 0X2A lexes as 0 followed by the identifier X2A
  • 0x digits are 0-9 a-f A-F; 0o digits are 0-7; 0b digits are 0-1. Each prefixed literal needs at least one digit after the prefix

Floating-Point Literals

3.14159
2.71e10
.5
1.

A float exponent (e or E with an optional sign) needs at least one digit: 1e is rejected, 1e+10 is a float. A . followed by another . is not a decimal point: 1..5 lexes as 1, .., 5, while a trailing 1. before anything else is the float 1..

Character Literals

'a'
'\n'      // Newline
'\t'      // Tab
'\\'      // Backslash
'\''      // Single quote
'\x41'    // Byte escape for A

String Literals

"Hello, World!" // single line string
"Line 1\nLine 2"
"Quote: \"Hello\""
"Plain string"

Accepted escapes in character and string literals are \n, \t, \r, \\, \', \", \0, and \xHH. Any other backslash escape (\b, \f, \v, \a, and others) is a lexical error. \xHH requires two hex digits (\x4 is rejected). A character literal holds one code point from 0 through 255; a larger code point is a lexical error. test_char_literal_errors.py checks this byte range.

String literals hold at most 32,767 characters including both quote characters. Longer literals are a lexical error.

Boolean Literals

true
false

Nil Literal

nil

nil represents a null pointer and applies only to reference types (ref T). Value types (primitives, arrays, structs, unions, and enums) cannot hold nil.

// Valid: nil with reference types
ptr: ref i32 = nil
fn_ptr: ref fn() = nil
if ptr == nil { }

// Invalid: nil with value types
arr: [5]i32 = nil      // ERROR: arrays cannot be nil
x: i32 = nil           // ERROR: primitives cannot be nil
s: MyStruct = nil      // ERROR: value structs cannot be nil

Array Initialization: Arrays must be initialized with:

  • No initializer (zero-initialized, like every declaration without one): arr: [5]i32
  • Single value (all elements): arr: [5]i32 = 0
  • Array literal: arr: [5]i32 = [1, 2, 3, 4, 5]

Array literals must match the declared array length when a target type is present. Each element is checked against the declared element type, including nested array literals and literal arms selected by if or match. Generic initializers and bound callback arguments apply those checks at each concrete instantiation, including declared fixed-array types such as [2]$T and nested fixed arrays. Typed array values still require compatible element types; a typed [2]i32 does not narrow implicitly to [2]i8. In an if or match, a concrete typed numeric array arm supplies the element type for literal arms of the same shape.


3. Type System

3.1 Type Categories

A7's type system consists of:

  1. Value types: Copied by value
  2. Reference types: Point to memory locations
  3. Generic types: Parameterized types

3.2 Primitive Types

Type Size (bytes) Range/Description
bool 1 true or false
i8 1 -128 to 127
i16 2 -32,768 to 32,767
i32 4 -2^31 to 2^31-1
i64 8 -2^63 to 2^63-1
isize platform Signed pointer-sized integer
u8 1 0 to 255
u16 2 0 to 65,535
u32 4 0 to 2^32-1
u64 8 0 to 2^64-1
usize platform Unsigned pointer-sized integer
f32 4 IEEE 754 single
f64 8 IEEE 754 double
char 1 Byte character (0-255)

isize and usize match the target platform's pointer width:

  • 32-bit platforms: 4 bytes (same as i32 and u32)
  • 64-bit platforms: 8 bytes (same as i64 and u64)

Use usize for sizes, lengths, capacities, allocation byte counts, and array, slice, and string indices. It maps directly to Zig usize.

Use isize only for signed pointer-sized offsets or position differences; do not use it as a general-purpose signed integer. Use fixed-width integers (i32, i64, u32, u64) when data has a fixed width or range; counters and indices should normally use usize.

3.3 Composite Types

Arrays

// Fixed-size array
arr: [10]i32
matrix: [3][3]f64

// Element-wise addition for same-shape numeric fixed arrays
a: [4]f64 = [1.0, 2.0, 3.0, 4.0]
b: [4]f64 = [5.0, 6.0, 7.0, 8.0]
c: [4]f64
c = a + b

T.len and T.element are proposed introspection features, not implemented array properties. Slice an array to read .len; the compiler currently provides .len and .ptr on slice values, not fixed-array values.

Indexing through ref [N]T uses the declared fixed-array length and requires both a non-nil reference proof and a bounds proof:

  • Supported operations: reading primitive elements and updating them with simple or compound assignment, including nested fixed arrays and usize indices with a proven bound. The Zig backend keeps the optional pointer and unwraps it at the indexed access. Reachable nil accesses and out-of-bounds indices fail at semantic exit 6 in both executable and library modes.
  • Callee and guard sources: known direct or forwarded calls and unmodified, uncaptured local callable aliases keep their indexed access requirements. Borrowed arrays and guards that skip the access on nil remain valid. Resolved helper functions whose body is one Boolean-literal ret supply indexed guard facts across direct calls, forwarded calls, and unmodified, uncaptured local aliases (preserving call and argument evaluation while keeping optional-pointer unwraps at indexed uses). Eligible local bool variables and value parameters supply guard facts from bare or negated conditions and Boolean-literal comparisons. Early returns keep the surviving branch fact, copies keep their evaluated value, assignments replace facts, branch joins require matching values, and loop writes clear affected facts.
  • Rejections and exclusions: true or unknown guards paired with nil fail at semantic exit 6. An unguarded symbolic read(nil, b) wrapper still fails even if its only caller passes false. Conditional, effectful, and deferred helpers remain unknown, and captured, ref-exposed, field, and global booleans are excluded. Effectful index expressions, indexing through selected reference-array fields, mutable or captured callable origins, ref slicing, and general reference-element ownership remain unsupported. Access requirements do not certify that a function is pure or model all effects.

Slices

// Dynamic view into array
slice: []i32

// Slice properties
slice.ptr      // Pointer to first element
slice.len      // Number of elements (usize)

An inferred binding initialized from a slice expression has the slice type, including when the backing value is a fixed array. Reassigning a mutable slice binding can change its length without changing the backing array. A :: binding cannot be reassigned. Initializers execute once.

backing: [3]i32 = [7, 8, 9]
state := backing[0..3]
state = backing[1..2]
// state.len is 1; state[0] is 8.

These declarations do not establish that the backing storage outlives every use. General slice lifetime enforcement remains incomplete.

Strings

// UTF-8 source string literal
name: string = "Hello"

// String slicing produces a []char byte slice
part := name[1..4]

// Historical representation sketch, not a current user-defined type alias
string :: struct {
    ptr: ref u8
    len: usize
}
// `name.len` returns `usize` (read-only) and supports `if i < name.len` bounds guards.

References (Pointers)

// Single indirection
ptr: ref i32

// Multiple indirection
ptr_ptr: ref ref i32

// Function pointer
fn_ptr: ref fn(i32, i32) i32

// Ref parameters can modify caller storage through typed lowering
x := 42
set_to_100 :: fn(value: ref i32) {
    value = 100
}
set_to_100(x)

Structs

Person :: struct {
    name: string
    age: u32
    height: f32
}

// Nested structs
Employee :: struct {
    person: Person
    id: u64
    salary: f64
}

Unions

Number :: union {
    i: i32
    f: f32
    u: u32
}

value := Number{i: 42}
same_value: i32 = value.i

// Tagged union (discriminated)
Outcome :: union(tag) {
    ok: i32
    err: i32
}

Untagged unions use Type{field: value} literals with exactly one named field. The named field must exist and its value must be assignable to that field type. Field access type-checks against the declared union fields. Tagged unions match through leading-dot arms: case .tag: tests the tag and case .tag(name): binds a copy of the payload (see §5.2). Only payloads without strings can bind by value; variants that hold a string require tag-only case .tag: arms.

Enums

// Simple enumeration
Color :: enum {
    Red,    // 0
    Green,  // 1
    Blue    // 2
}

// With explicit values
StatusCode :: enum {
    Ok = 200,
    NotFound = 404,
    Error = 500
}

An enum with explicit values uses the first Zig tag type in i32, u32, i64, u64 that holds every variant. An omitted value is the previous value plus one. For example, Big :: enum { A = 4294967295, B } needs i64 because B is 4294967296. Values up to 18446744073709551615 use u64 when the whole enum fits that unsigned range. If no single supported tag type fits all variants, code generation rejects the enum. Enums without explicit values let Zig choose the tag width. See test_enum_tag_types.py for compiler/native cases and the separate backend-only rejection check.

3.4 Type Aliases

// Simple alias
Handle :: u64

// Generic alias
Vector :: [3]f32
Matrix :: [4][4]f32

An alias whose right side is a bare user-defined name (for example Handle :: MyInt) is a constant value alias, not a type alias. Only primitive, ref, generic-parameter, and bracket type spellings form type aliases.

3.5 Reference Semantics

// Ref parameters use ordinary lvalue arguments
x := 42
set_to_100 :: fn(value: ref i32) {
    value = 100  // OK: modifies the caller's storage
}
set_to_100(x)

Counter :: struct {
    value: i32
}

increment :: fn(counter: ref Counter) {
    counter.value += 1  // OK: checked field access through ref
}

Public address-of and dereference operators are not part of A7. The compiler inserts internal reference operations only where a typed construct requires them, then proves the operation safe before Zig codegen.


4. Declarations and Expressions

4.1 Variable Declarations

// Immutable binding (constant) - use ::
PI :: 3.14159

// Mutable bindings (variables) - use := or name: T
count := 0
age: i32 = 25    // Explicit type, initialized
name := "John"   // Inferred as string
buffer: [1024]u8 // Explicit type, no initializer: all zeros

// Multiple-declaration and destructuring binding are cut, not current:
// a, b, c: i32 = 1, 2, 3   // parse exit 5
// x, y := 10, 20           // parse exit 5

4.2 Declaration Rules

One rule: :: is immutable; := and name: T are mutable:

  • :: - Creates immutable bindings (constants)
  • := - Creates mutable bindings with inferred type
  • name: T [= value] - Creates mutable bindings with explicit type
// Constants (immutable) - use ::
PI :: 3.14159
MAX_BUFFER :: 1024
VERSION :: "1.0.0"
DOUBLE_PI :: PI * 2

// Variables (mutable) - use := or name: T
count := 0
name := "John"
buffer: [1024]u8

// Explicit typing is always mutable
MAX_SIZE: i32 = 1000    // Mutable with explicit type
counter: i32 = 0        // Mutable with explicit type

// Variables can be reassigned
counter = counter + 1   // OK
// PI = 3.0             // ERROR: cannot reassign constant

// Example using logical operators
valid := count > 0 and count < 100
should_process := valid or force_mode
can_exit := !running and cleanup_done

4.2.1 Untyped numeric constants

This section describes exact constant arithmetic and destination fitting. See the packet for the approved contract and Appendix C for resource limits and the remaining emission requirement.

Numeric literals and :: constants built from supported constant expressions keep their exact value until a context requires a concrete type. One use never fixes the type for other uses of the same constant. Global constants resolve before function bodies, so global declaration order does not change fitting; local declarations keep normal lexical visibility rules.

RATE :: 2.0
small: u8 = RATE
wide: i64 = RATE
runtime := RATE       // Concrete f64

Destination fitting:

  • Integer destinations: accept a constant only when its value is integral and fits the target range (usize and isize use the target pointer width). 2.0 fits i32; 2.5, 256 into u8, and -1 into usize fail. Implicit fitting never truncates or wraps.
  • Runtime float-to-integer casts: require an explicit checked cast(T, x). The safety pass accepts only a FLOAT literal that is finite, integral, and within the target range (a7/passes/safety.py:1036-1043, enforced at lines 903-904), and rejects anything else with "float-to-int cast requires finite integral range proof". The Zig backend lowers approved casts to @intFromFloat (zig.py:2047). Non-literal float-to-int proofs are future work; no program relying on them is accepted today.
  • Float destinations: round the exact value directly to f32 or f64 (round-to-nearest, ties-to-even). Signed zero, subnormals, and underflow to zero are preserved; finite values that round to infinity fail. Ordinary typed math calls still keep their concrete result types and can produce infinity or NaN (for example, INF :: math.exp(1000.0) after importing std/math as math).
  • Default concrete types: inferred runtime bindings, formatting, and unconstrained generics default to i32 (integer category) or f64 (float category). Annotate large literals explicitly (such as value: i64 = 9007199254740993) before formatting. Annotated variables, fields, parameters, returns, and aggregate elements fit directly to their declared type. Array lengths and indices require an integral value fitting usize. Numeric match patterns fit the subject type.

Wholly untyped constant arithmetic:

  • +, -, and * compute exact values without wrapping or rounding.
  • / truncates toward zero when both operands are integer-category (5 / 2 is 2, even when assigned to f64), and computes exact rational division when either operand is float-category (5.0 / 2 is 2.5).
  • % computes a - trunc(a / b) * b. Division or remainder by zero fails: float division by zero is a constant error, and integer division by zero fails the divisor proof.
  • Floating zero preserves IEEE sign (0.0 * -1.0 is -0.0).
  • Comparisons evaluate exact values (0.1 + 0.2 == 0.3 is true, and 1e400 == 1e400 is true without fitting either operand to f64).
  • Bitwise operators require integer-category operands (2.0 stays in the floating category even though its value is integral). Shifts require a nonnegative integer-category count: << multiplies by a power of two, and >> preserves sign (-3 >> 1 is -2). Bitwise ~ is typed-only and does not fold on untyped constants.
  • A float literal whose exponent exceeds 4,096 in magnitude fails at semantic exit 6 before exact-value construction. See Appendix C for component, work, retention, and dependency limits.

Mixed typed and untyped operations:

Typed values keep their concrete type. When an operation mixes a typed operand and an untyped constant, the compiler fits the untyped operand to its peer's type before applying the typed operation. This keeps typed float arithmetic and typed integer wrapping separate from exact constant arithmetic. cast(T, value) first gives an untyped operand its category default (i32 or f64), then applies the normal cast rules.

4.3 Expression Categories

Primary Expressions

  • Identifiers: x, foo
  • Literals: 42, "hello", true
  • Parenthesized: (x + y)

Postfix Expressions

  • Array subscript: arr[i]
  • Slice: arr[1..5], arr[..3], arr[2..]
  • Field access: point.x
  • Function call: max(a, b)

Method-call sugar such as vec.length() is planned syntax, not current semantic support. Use explicit functions such as length(vec).

Unary Expressions

  • Negation: -x
  • Logical NOT: !flag
  • Bitwise NOT: ~bits

Logical operators use keywords for AND and OR:

  • and for logical AND (not &&)
  • or for logical OR (not ||)
  • ! for logical NOT

Binary Expressions

Precedence (highest to lowest):

  1. *, /, %
  2. +, -
  3. <<, >>
  4. <, >, <=, >=
  5. ==, !=
  6. &
  7. ^
  8. |
  9. and
  10. or

Cast Expressions

// Explicit numeric and char <-> u8 casts
x := cast(f64, 42)
b := cast(u8, 'A')
c := cast(char, b)

// Generic cast
y := cast(T, value)

cast(Type, value) converts primitive numeric types when range-proven, char to u8, u8 to char, and integer expressions proven in 0..=255 to char.


5. Control Flow

5.1 Conditional Statements

// Simple if
if condition {
    // code
}

// If-else chain
if x < 0 {
    print("negative")
} else if x > 0 {
    print("positive")
} else {
    print("zero")
}

// Conditional expression
result := if x > 0 { x } else { -x }

// Complex conditions with and/or
if age >= 18 and age <= 65 {
    print("Working age")
}

if name == "admin" or permissions.admin {
    allow_access()
}

// Nested logical operators
if (x > 0 and x < 100) or (y > 0 and y < 100) {
    print("In bounds")
}

Bare struct literals are not parsed at the top level of an if or while condition because { opens the body. Wrap the expression in parentheses, pass it inside a call (if check(Pt{x: 1}) {}), or bind a variable first (p := Pt{x: 1}). See Status.

5.2 Pattern Matching

// Match on enum values
match color {
    case Color.Red: {
        print("Red")
    }
    case Color.Green: {
        print("Green")
        fall  // Continue into the next case body; must be final in a non-final case
    }
    case Color.Blue: {
        print("Green or Blue")
    }
}

// Match on literal values
match x {
    case 0: print("zero")
    case 1, 2, 3: print("small")
    case 4..10: print("medium")
    else: print("large")
}

// Match on tagged-union tags with leading-dot arms
r := Outcome{ok: 1}
out := match r {
    case .ok(v): v + 1    // binds a copy of the payload
    case .err(e): e
}

// A bare tag tests without binding; else opts out of exhaustiveness
match r {
    case .ok: print("ok")
    else: print("other")
}

// Wildcard covers remaining values; bind from the scrutinee in the arm body
score :: fn(x: i32) i32 {
    ret match x {
        case _: x + 1
    }
}

An identifier pattern refers to an existing visible symbol when one exists, preserving constant and value matching. If no visible symbol matches, the pattern fails at semantic exit 6 as an undefined name. Bare undefined identifiers never capture silently; use _ for a wildcard and read the scrutinee in the arm body when needed. Tagged-union payload bindings use case .tag(name):.

Leading-dot arms match a tagged union's tags: case .tag: checks the tag without binding, and case .tag(name): binds a copy of the payload to an immutable branch-local variable. .tag(_) is not supported. Omitting the dot (case tag:) on a tagged union fails at semantic exit 6. A match with uncovered tags and no else fails at semantic exit 6 and lists each missing tag. Only payloads without strings can bind by value: binding a string or string-containing payload fails at semantic exit 6, though tag-only case .tag: arms over those variants remain valid. Untagged unions and non-union scrutinees keep standard pattern rules.

In generic functions, numeric literals, named exact constants, and range endpoints fit each concrete subject type before overlap checking, using the defining scope. Float patterns round directly to the concrete float width. Runtime range endpoints require a numeric or char subject. Deferred pattern checks require a supported generic callable origin.

A statement match stores its else body as a statement list (else_case); an expression match stores one expression (else_expr). AST JSON output exposes both fields. See Status.

5.3 Loops

// Infinite loop
for {
    if should_stop() { break }
}

// While loop
while condition {
    // code
}

// C-style for loop
for i := 0; i < 10; i += 1 {
    print(i)
}

// Range loop
for value in array {
    print(value)
}

// Range with index
for i, value in array {
    printf("[{}] = {}\n", i, value)
}
// The index variable `i` has type `usize`.

// Range over slice
for ch in text[2..5] {
    print(ch)
}
// text[2..5] has type []char.

// Complex conditions using and/or
while running and not should_exit() {
    process_events()
}

for i := 0; i < 100 and valid; i += 1 {
    if check_condition(i) or force_exit {
        break
    }
}

5.4 Jump Statements

// Return from function
ret value

// Break from loop
break

// Continue to next iteration
continue

// Break/continue with loop label
@outer for i := 0; i < 10; i += 1 {
    for j := 0; j < 10; j += 1 {
        if condition {
            break outer
        }
    }
}

Loop labels use @name directly before a loop statement. The old name: for ... spelling is rejected because name: is reserved for typed bindings, fields, and case-like syntax.

Semantic validation reports unreachable statements that appear later in the same block after ret, a valid break or continue, fall, or an if/match statement whose branches all terminate.


6. Functions

6.1 Function Declarations

// Basic function
add :: fn(x: i32, y: i32) i32 {
    ret x + y
}

// Void function
print_number :: fn(n: i32) {
    printf("{}\n", n)
}

// Return struct for multiple values
DivModResult :: struct {
    quotient: i32
    remainder: i32
}

divmod :: fn(a: i32, b: i32) DivModResult {
    ret DivModResult{a / b, a % b}
}

// Named fields in return struct
sincos :: fn(angle: f64) struct { sin: f64, cos: f64 } {
    ret struct { sin: f64, cos: f64 }{
        sin: math.sin(angle),
        cos: math.cos(angle)
    }
}

// Current generic value function
identity :: fn(value: $T) $T {
    ret value
}

// Current minimal form: conjunction of set memberships
add :: fn(a: $T, b: $T) $T where T: Numeric {
    ret a + b
}

// Current: several bounds, comma-separated
first :: fn(a: $T, b: $U) $T where T: Numeric, U: Numeric {
    ret a
}

// Current: inline type set as a bound
f :: fn(a: $T) $T where T: @type_set(i32, i64) {
    ret a
}

// Rejected with exit 6: richer predicates (`where T == i32`,
// `where true`), unknown names, `$T` in the bound, bounds on value
// params, non-set bounds, and `where` on enums.

Nested functions

A function may declare and call a nested function that captures no enclosing locals or parameters. The compiler runs type and control-flow checks on each nested body, and the Zig backend emits these functions at file scope under distinct names. Reading an enclosing local or parameter fails during code generation with exit 7 and advice to pass it as a parameter. A nested function's own parameter may reuse an enclosing name.

outer :: fn(k: i32) i32 {
    helper :: fn(v: i32) i32 { ret v + 1 }
    ret helper(k)
}

Functions can also return capture-free nested functions as values. See test_nested_functions.py and test_nested_function_codegen.py.

6.2 Recursion

Recursion is not part of A7. A function may not call itself directly, and groups of functions may not call each other in a cycle. Semantic validation also rejects common indirect cycles through local function-pointer aliases and higher-order callback trampolines before backend code generation.

Use loops, explicit stacks, or index-based worklists for repeated work.

// ERROR: direct recursion is rejected
factorial :: fn(n: i32) i32 {
    if n <= 1 {
        ret 1
    }
    ret n * factorial(n - 1)
}

// ERROR: callback trampolines cannot hide recursion
call_it :: fn(f: fn(i32) i32, n: i32) i32 {
    ret f(n)
}

countdown :: fn(n: i32) i32 {
    if n <= 0 {
        ret 0
    }
    ret call_it(countdown, n - 1)
}

// OK: iterative rewrite
factorial_iter :: fn(n: i32) i32 {
    result := 1
    for i := 2; i <= n; i += 1 {
        result *= i
    }
    ret result
}

6.3 Function Parameter Immutability

All value parameters in A7 are immutable. ref parameters can mutate the caller's storage, while the reference binding itself is compiler-managed and never exposed as an assignable pointer value. The Zig backend lowers ref T to ?*T. References pass through calls without a boundary unwrap, and field access or supported mutation unwraps at each use.

Inside a function, nil comparisons are always valid. A call passing literal nil succeeds when a supported callee guard avoids reading the reference; this does not prove all nil call effects across arbitrary programs.

Writes through a concrete numeric ref follow the referent's assignment rules: exact constants fit when in range (and integral for integer types). For example, a guarded ref usize accepts n = 3 and n = 3.0, while assigning a typed i32 fails with a type mismatch. The same rules apply to compound assignments (+=, -=, and others). Reference and nil assignments keep normal binding rules (q := p, p == nil, p == q, del p, ref T arguments, and untyped io {} format arguments stay reference operations), while typed value contexts (typed bindings, arithmetic, ordered comparisons, ret, scalar call parameters, cast, and boolean conditions) automatically read non-nil primitive ref T values.

set_three :: fn(n: ref usize) {
    if n == nil { ret }
    n = 3
}
// Parameters cannot be reassigned
bad_function :: fn(x: i32) i32 {
    x += 1  // ERROR: cannot modify parameter
    ret x
}

// Ref parameters can modify caller storage
increment :: fn(x: ref i32) {
    x += 1
}

// To work with a mutable copy, create a local variable
good_function :: fn(x: i32) i32 {
    local_x := x      // Create mutable local copy using :=
    local_x += 1      // OK: modifying local variable
    ret local_x
}

// Usage example
main :: fn() {
    value := 10
    increment(value)  // Passes value by checked reference
    printf("Value: {}\n", value)  // Prints: Value: 11
}

6.4 Function Types

// Function pointer type
BinaryOp :: fn(i32, i32) i32

// Using function pointers
apply :: fn(op: BinaryOp, x: i32, y: i32) i32 {
    ret op(x, y)
}

result := apply(add, 10, 20)

An inferred binding to a concrete function retains its checked function type. A mutable binding can be reassigned or passed to a matching ref fn(...) parameter. A saved function value keeps its target when the original binding changes. Explicit type annotations take precedence.

io :: import "std/io"
first :: fn(x: i32) i32 { ret x + 1 }
second :: fn(x: i32) i32 { ret x + 2 }
main :: fn() {
    f := first
    saved := f
    f = second
    io.println("{} {}", saved(40), f(40)) // Prints: 41 42
}

Generic declaration aliases remain compile-time aliases, not runtime generic dispatch. These declarations do not implement capturing closures or establish a new callable-versus-argument evaluation-order guarantee.

6.5 Methods

Current implementation is limited. The examples in this section describe the intended receiver model, not a fully runnable set. Use ordinary functions and consult the language reference for verified reference-parameter forms.

// Methods are functions with receiver
Vec2 :: struct {
    x: f32
    y: f32
}

// Method declaration - receiver is immutable parameter
length :: fn(self: ref Vec2) f32 {
    ret sqrt(self.x * self.x + self.y * self.y)
}

// Method that modifies the receiver
normalize :: fn(self: ref Vec2) {
    len := sqrt(self.x * self.x + self.y * self.y)
    self.x /= len  // OK: modifying through checked reference field access
    self.y /= len
}

// Explicit receiver call
v := Vec2{3.0, 4.0}
len := length(v)
normalize(v)      // Modifies v through checked reference

6.6 Variadic Functions

Implementation Status: Cut from the current language surface. Parameter forms such as values: ..i32 still parse so the compiler can reject them with semantic exit 6 (Variadic parameters are not supported; pass a slice instead). Do not treat variadic functions as runnable. Pass a slice when a variable argument count is needed. Compiler-owned io.println formatting is unrelated and does not restore user variadics.

// Cut spelling (semantic exit 6):
// sum :: fn(values: ..i32) i32 { ... }

// Current replacement: pass a slice
sum :: fn(values: []i32) i32 {
    total := 0
    for val in values {
        total += val
    }
    ret total
}

7. Generics

7.1 Generic System Design

A7 generics use compile-time type parameters declared inline with $T.

Core principles:

  • $T declares and references a type parameter inline within type expressions.
  • Write $T in both places rather than separate declaration and use syntax.
  • Concrete types are inferred from usage context at compile time.
  • Type-set constraints are checked semantically on declared generic functions and generic record types.

Generic Type Parameter Syntax Rules:

  • Must start with $ followed immediately by a letter (a-z, A-Z)
  • Digits and underscores are accepted after the initial letter: $T1 and $MY_TYPE are valid; $123 is invalid
  • The tokenizer uses Unicode-aware letter and alphanumeric checks after $; use ASCII spellings for the documented language forms
  • Standalone $ is invalid and produces a compilation error
// Generic ref swap is not currently supported. Reading/reassigning ref
// parameters does not provide general value-copy swap semantics.

// Generic function with return type
identity :: fn(x: $T) $T {
    ret x
}

// Generic function - type inferred from first argument
abs :: fn(x: $T) $T {
    ret if x < 0 { -x } else { x }
}

// Multiple generic type parameters
pair :: fn(first: $T, second: $U) {
    x := first
    y := second
}

// Planned broader composite propagation; not backend-complete yet.
first :: fn(arr: []$T) $T {
    ret arr[0]
}

Instantiation and callback rules:

  • Generic local initializers must fit each concrete instantiation, including literal arrays and scalar if/match results. (Branches holding array literals do not yet receive every nested contextual fit.) For example, z: $T = 0 rejects string, and a branch producing 300 rejects i8. A typed integer branch never narrows implicitly because another branch is an untyped constant.
  • Fixed-array initializers such as values: [2]$T = [1, 2] check elements after substituting the concrete type (accepting i8, rejecting 128), while array length mismatches reject before instantiation. Concrete callers keep these checks across ordinary function aliases and parameters. Fully concrete initializers are not re-checked for unrelated generic parameters. Deferred initializers with unresolved element types require a supported direct call or qualifying immutable local alias; unsupported escapes fail at semantic exit 6 without adding runtime generic dispatch or implicit typed narrowing.
  • A function-valued parameter takes one concrete signature per enclosing instantiation. Calls through its local aliases, assignments, and if/match selections keep that signature rather than inferring a fresh type parameter at each callback call. Aliasing a generic declaration does not bind its unresolved type parameters. Callback provenance through record fields and array elements remains incomplete; see Status.

7.2 Generic Types

Generic structs and unions use inline $T syntax in their field types:

// Generic struct - $T used inline in field types
Pair :: struct {
    first: $T,
    second: $U,
}

// Usage - specify concrete types at instantiation
p := Pair(i32, string){first: 42, second: "answer"}

// Generic box
Box :: struct {
    value: $T,
}

// Nested generic instantiation
nested: Box(Box(i32))

// Generic union
Outcome :: union {
    ok: $T,
    err: $E,
}

// Generic tagged union - specializes positionally like a struct
TResult :: union(tag) {
    ok: $T,
    err: $E,
}
r := TResult(i32, string){ok: 1}

A generic union(tag) takes its concrete types positionally in field order: TResult(i32, string) binds $T to i32 and $E to string. Field access on the instance resolves to the bound type. A wrong field type or unknown field fails at semantic exit 6, and conflicting $T bindings at one call site fail at semantic exit 6 (GENERIC_PARAM_MISMATCH). A7 does not support generic enums because enum variants carry no payload types; use a tagged union for payload-bearing alternatives.

$N value parameters accept their declared scalar kind, including usize, bool, and small integer types. Structs and unions instantiate from named constants (Buf(SIZE) with SIZE :: 4) and from literals (Buf(4), Flag(true)). Function calls infer $N when the binding is unique. A value parameter may be forwarded into another generic under matching kind checks, as in Holder($N: usize) :: struct { inner: Buf($N) }. The backend emits value parameters with their declared Zig type, such as comptime N: usize. test_generics_value_param_codegen.py and test_generics_value_params.py cover named constants, literals, inference, forwarding, and kind failures.

7.3 Type Sets and Constraints

Implementation Status: Type-set syntax is implemented for predefined sets, local @type_set(...) aliases, and inline constraints on declared generic functions. Inferred call arguments are checked against declared type sets.

Type sets are defined using the @type_set() builtin function:

// Built-in type sets (will be defined in standard library)
Numeric :: @type_set(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64)
Integer :: @type_set(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize)
Float :: @type_set(f32, f64)
Signed :: @type_set(i8, i16, i32, i64, isize, f32, f64)
Unsigned :: @type_set(u8, u16, u32, u64, usize)

// Custom type sets
SmallInts :: @type_set(i8, u8, i16, u16)
BigInts :: @type_set(i64, u64)

Current Constraint Syntax:

abs($T: Numeric) :: fn(x: $T) $T {
    ret if x < 0 { -x } else { x }
}

min($T: Numeric) :: fn(a: $T, b: $T) $T {
    ret if a < b { a } else { b }
}

A where clause states the same bounds after the signature, as a conjunction of set memberships. It works on generic fns, structs, and unions:

add :: fn(a: $T, b: $T) $T where T: Numeric {
    ret a + b
}

P($T) :: struct {
    x: $T,
} where T: Numeric

Each bound resolves like a declared $T: Set constraint (predefined sets, inline @type_set(...), local aliases). Richer predicates, unknown names, duplicate bounds, bounds on value params, non-set bounds, and where on enums exit 6.

A constrained generic argument satisfies another constraint only when every type in its nonempty source set belongs to the destination set: Float satisfies Numeric, while Numeric does not satisfy Float. An unconstrained argument cannot satisfy a constrained destination. These rules apply to function calls, constrained struct or union construction, and nominal type annotations. An annotation such as b: Box(i32) fails at exit 6 when Box requires Float, including in unused signatures, fields, and type aliases. Argument count and type/value-kind errors keep their own diagnostics.

Record constraints resolve in their defining file after named type aliases are registered, so a type-set member may name a later type alias without capturing an incomplete set. Imported annotations use the owner's constraints, and generic record fields use their declaring record's bounds.

7.4 Generic Specialization

Immutable aliases to generic functions keep concrete instantiation checks across same-file, imported, module-global, and selected-import definitions when the alias copy chain is never reassigned, passed by ref, or captured. Parameter, mutable, captured, and aggregate origins remain incomplete when the chain cannot be traced. This bounded support does not add runtime generic dispatch; see Status.

identity($T) :: fn(value: $T) $T {
    ret value
}

main :: fn() {
    a := identity(7)
    b := identity("ok")
}

Generic functions are specialized from concrete call sites in Zig output. Broader composite generic specialization and deeper propagation through method-style call chains remain implementation work.

Two functions with the same name exit 6 (ALREADY_DEFINED), whatever their signatures. A7 has no function overloading.


8. Memory Management

8.1 Stack Allocation

All local variables are stack-allocated by default:

example :: fn() {
    x := 42            // Stack
    arr: [100]f32      // Stack
    person: Person     // Stack
}  // All automatically freed

8.2 Heap Allocation

Box :: struct {
    value: i32
}

// Allocate a heap struct
box := new Box
if box == nil {
    ret
}
box.value = 42
del box

// Heap fixed arrays are not current syntax. Use stack arrays or slices.
buffer: [1024]u8
slice := buffer[0..1024]

// Initialize fields through the returned reference
point := new Point
if point == nil {
    ret
}
point.x = 10
point.y = 20
del point

// `new T(args...)` and `new T{...}` initializer forms are not current syntax.

// Check allocation
large := new Point
if large == nil {
    // Handle allocation failure
}

Release builds allocate through std.heap.smp_allocator. Debug builds allocate through std.heap.page_allocator. Allocation failure behavior is unchanged.

8.3 Defer Statement

// Defer executes at scope exit
{
    file := open("data.txt")
    defer close(file)

    point := new Point
    defer del point

    // Use file and buffer
    // Both cleaned up automatically
}

// Defer order is LIFO
{
    defer print("3")
    defer print("2")
    defer print("1")
    // Prints: 1 2 3
}

8.4 Memory Safety Status

Current implementation:

  1. Allocation and deallocation: new and del parse, type-check, and lower for the Zig backend.
  2. Deletion and array-slot tracking: del checks reference-like values. Direct reference aliases share allocation deletion state; double del and reads after del fail until reassignment to a fresh allocation.
    • On straight-line and conditional paths, tracked fixed-array ref elements keep allocation identity through literal indices, and array copies copy referent identities into independent slot cells.
    • Replacing a slot never retargets a saved reference. Reading or deleting a known deleted allocation through a tracked element fails at semantic exit 6.
    • Slot tracking does not supply a non-nil proof, and computed indices, slice elements, and uncertain branch joins lack general lifetime analysis.
    • Eligible loop counters keep facts across readonly calls, returned-reference forwarding, and writes to distinct owned storage. Primitive projected lvalues passed to ref parameters keep their storage mutation effects. Local slot replacement does not prove reachable slice backing disjoint; unknown calls, escaped storage, and unsupported projections stay conservative.
  3. Global reference stores: direct global reference stores keep allocation identity across calls, so deleting a stored allocation invalidates caller aliases. Unknown and indirect effects fall back to incomplete tracking.
  4. Simple reference returns: direct calls preserve a selected ref or nil return when every boolean argument is a literal (covering bodies made of blocks, boolean-literal or boolean-parameter conditions, and ref-param or nil returns with explicit ref/bool parameter types). Other return paths remain incomplete. Reference arguments use facts captured during argument evaluation; a guard on an input does not prove a separately returned nil value safe to read.
  5. Scope cleanup: defer del value runs manual cleanup at scope exit.
  6. Non-nil field proofs: ref fields (including a user field named ptr) require a non-nil proof. Field guards track assignments and known call effects.

Readonly-call and entry-point checks:

  • A rejection-only readonly-call analysis checks represented nil field reads across known calls, local boolean branches, LIFO defers, and counted loop bodies, failing a known violation at semantic exit 6 while keeping previously accepted guarded calls and literal-selected non-reading controls valid. Finite counted loops publish their proved final counter value before checking later branches. This pass adds no writes, returned-reference facts, or lifetime effects; unsupported globals, ref fields, containers, nonliteral caller captures, effectful callees, and resource-excluded summaries remain incomplete, and an unknown predicate is never a safety proof.
  • For executable builds, an entry-point check evaluates the entry file's parameterless main after ordinary safety checks. A complete readonly summary proving a reachable nil read adds semantic exit 6 (fatal diagnostics keep priority), reporting the callee source filename, line, and column. Imported or nested main functions do not replace the entry file's main, and --lib has no entry root. Missing, incomplete, and unresolved summaries add no proof or acceptance; effectful entries, ordered mutation, and general caller-local truth remain open.

Not yet implemented:

  1. Ownership, borrowing, or lifetime analysis that proves absence of dangling pointers.
  2. Complete alias tracking through general array-element paths and fields reached through joined allocation sets. These gaps prevent a general double-free or use-after-free safety claim.
  3. Complete propagation of global nil state and parameter proof obligations.
  4. General array/slice bounds-check insertion by the A7 compiler.

9. Planned Array Programming for AI

Tensor APIs, broadcasting, automatic differentiation, GPU movement, and performance annotations remain proposals. Their historical examples now live in the array programming proposal. They are not accepted A7 syntax. Current fixed-array behavior is described in §3.3.


10. Modules and Visibility

10.1 File-Based Module Model

Every A7 source file is a module. There is no explicit module keyword. The current backend lowers supported file-backed imports into the same generated Zig file; A7 multi-file support is a frontend/module feature, not separate object linking.

// File: vector.a7
// This file is automatically the "vector" module

// Public export
pub Vec3 :: struct {
    x: f32
    y: f32
    z: f32
}

// Public function
pub dot :: fn(a: Vec3, b: Vec3) f32 {
    ret a.x * b.x + a.y * b.y + a.z * b.z
}

// Approved private-name spelling; enforcement is incomplete, see §10.4
_value :: 7

10.2 Import Statements

// Current backend-lowered virtual stdlib imports
math :: import "std/math"
io :: import "std/io"

// Aliases are supported for virtual stdlib imports
console :: import "std/io"

// Selected imports bind public names from the module into this file
import "vector" { Vec3, dot }

// Rejected at semantic exit 6; use an alias and qualify names instead
// using import "vector"

// Local aliases lower into the same generated Zig output for simple calls
sibling :: import "./sibling"
subfolder :: import "subfolder/helper"

// From a nested importer, allowed if utils remains inside the entry folder
parent :: import "../utils"
  • Importing the same file twice in one file is a compile error, even through alternate spellings or symlinks. Different files may import the same file.
  • An import alias conflicting with an existing definition in the same scope fails name resolution. Under L28, a local binding cannot reuse an import alias from its own file, including a stdlib alias. This check covers parameters, loop bindings and match captures. Record fields and aliases in other files do not reserve local names. Each file has a separate semantic scope.
  • Selected imports bind each listed public name into the importing file's scope. Private _name items and missing names exit 6. using import parses, then rejects at semantic exit 6 with guidance to write alias :: import "path" and use alias.name.

10.2.1 Module identity and resolution

The resolver checks virtual stdlib spellings first (io, std/io, math, and std/math). A literal path starting with std/ is reserved for shipped modules; project shadows and missing reserved modules fail resolution with exit 3. Explicit relative paths such as ./std/helper follow ordinary local-file rules. Other imports resolve relative to the importing file, first as <path>.a7, then as <path>/mod.a7. A nested file's import "helper" never falls back to the entry directory.

Local source imports must stay inside the entry file's folder. Bundled implementation imports must stay inside a7/stdlib/sources/std. Neither domain falls back to the other. Parent (..) segments are allowed only inside the applicable root; paths or symlinks escaping it, absolute paths, backslashes, null bytes, and empty paths fail resolution. Device and inode identity identify loaded files, duplicate imports, and cycles, so symlinks and hardlinks of one file compare equal and share one loaded dependency in diamond imports.

OS errors during path lookup (including overlong components and paths) produce a located ImportError at resolution exit 3 that preserves the OS failure and import site, including in dependency files.

a7/module_resolver.py implements resolution. test_module_path_identity.py, test_import_selected_using_hardlink.py, and test_packaged_source_modules.py cover path identity, containment, hardlinks, cache reuse, cycle retry, and bundled sources.

10.2.2 Cycles and entry

  • Import cycles are distinct from call recursion. An import cycle (A -> B -> A at load time) is a compile error raised during module loading by the canonical-identity active set in ModuleResolver.load_module. A7 source recursion (a function calling itself, directly or through a cycle of calls) is a separate, banned construct rejected by semantic validation, not by the module loader.
  • Entry-point rule: only the entry file is gated. An executable entry must define main :: fn() with no parameters and no return value; a missing or misshaped main exits 6 at the Entry Point stage in A7Compiler.compile_file_detailed. Imported modules never need their own main. a7 check --lib checks a library file without an entry point; build and run still require one.
  • Other files' declarations require their import alias. Qualified types, struct literals, enum and union members, and constant array lengths resolve in the imported file. Generic bodies keep their defining file's private names. Selected imports bind public names; using import fails with alias guidance.
  • Under L76, an import alias is local to its declaring file: parsed a.b.value() access through a dependency imported by a fails at semantic exit 6. Import that dependency directly in the caller or expose a public wrapper in a. Ordinary struct-field chains remain valid. Multi-dot type annotations (x: a.b.Box) and literals (a.b.Box{...}) fail at parse exit 5; L76 adds no grammar. See P-MOD-import-forwarding.

10.3 Standard Library Status

Current implementation:

  • std/io and io are virtual modules backed by compiler/backend mappings.
  • std/math and math are virtual modules backed by compiler/backend mappings.
  • Virtual stdlib modules are registered through the module resolver and may be imported with arbitrary local aliases, for example console :: import "std/io".
  • Local file imports such as ./vector can resolve from on-disk .a7 files and simple alias-qualified function calls lower into the same generated Zig output file.

The loader supports package-owned A7 implementation modules. This release ships no public implementation module in that directory; std/ascii remains unavailable. The ASCII source used by loader tests is a fixture, not a shipped module.

Planned, not implemented as public stdlib modules yet:

  • std/string
  • std/mem
  • std/collections

10.4 Visibility rules

Each file has its own namespace under L25-L31 and L69. alias.name accesses another file. Top-level _name is private, top-level __name is reserved for the compiler, and other top-level declarations are public. Import aliases stay local under L76. Private declarations remain visible inside their defining file, including generic bodies. Identically named types in different files stay distinct.

All struct fields remain visible to importers under L29. pub is accepted and recorded without overriding name-based top-level visibility or changing field visibility. Local __name bindings remain accepted. Removing pub, rejecting local __ names, and changing import forms require separate compatibility dispositions in P-MOD.

Name resolution and type checking use file-root scopes and declaration identity. The compiler lowers resolved uses to unique names for whole-program checks and one Zig output, keeping module load order and per-file declaration order. Diagnostics for imported constant writes name the qualified binding (such as a.VALUE), and semantic reports keep each declaration's file and lexical scope. Each else if arm creates its own scope: a local shadow leaves the parent binding unchanged afterward, and branch-local declarations stay out of scope outside their branch.


11. Built-in Functions and Operators

11.1 Builtin Functions

These functions are handled specially by the compiler and use the @ prefix:

// Type sets
@type_set :: fn(types: ..type) TypeSet     // Create type set

The tokenizer/parser reserve additional intrinsic spellings, but they are not semantically resolved or backend-lowered yet:

// Memory intrinsics
@size_of :: fn($T: type) usize             // Size in bytes
@align_of :: fn($T: type) usize            // Alignment requirement
@type_id :: fn($T: type) usize             // Unique type identifier
@type_name :: fn($T: type) string          // Type name as string

// Compiler intrinsics
@unreachable :: fn()                       // Mark unreachable code
@likely :: fn(cond: bool) bool             // Branch prediction hint
@unlikely :: fn(cond: bool) bool           // Branch prediction hint

11.2 Standard Library Functions

Current virtual modules (std/io, std/math):

std/io and io (and std/math and math) are alternate public spellings of the same virtual modules (a7/stdlib/__init__.py). io.print, io.println, and io.eprintln lower to __a7_stdout_print and __a7_stderr_print using persistent-writer runtime fragments in a7/stdlib/rt/. The registry binds hooks to declared signatures, argument policies, and Zig mappings, and the backend emits only the fragments a program uses. std/math provides math.sqrt, math.abs, math.floor, math.ceil, math.sin, math.cos, math.tan, math.log, math.exp, math.min, and math.max. Typed spellings such as sqrt_f32 and sqrt_f64 in the planned list below are not callable.

Recoverable I/O (io.println_ok, io.read_line):

Recoverable I/O returns Result(usize, io.IoErr) using the prelude Result type. io.println_ok takes the same literal formats as io.println and returns written byte count including the newline. io.read_line(buf[0..]) requires one mutable []u8 slice (fixed arrays need an explicit slice) and returns the same Result type. Save, forward, or match either result with leading-dot match arms; wrong arity and incompatible arguments fail at semantic exit 6.

Import io in every file that names io.IoErr. Its variants are WriteFailed, FlushFailed, ReadFailed, and EndOfStream. io.read_line keeps unconsumed input across calls:

  • A consumed newline stays in the buffer and counts toward returned bytes.
  • A full buffer returns its count; a later call reads the rest of the line.
  • EOF after some bytes returns their count; EOF before any bytes returns EndOfStream.
  • A zero-length buffer returns ok(0) without consuming input.

No-result std/io calls:

io.print, io.println, and io.eprintln produce no value. Using them in inferred bindings, container elements, if/match results, or format arguments fails at semantic exit 6 at the consuming call's location. (Existing type and exact-constant errors keep priority, and later semantic passes such as recursion checks stop after this failure.) Discarded direct statement calls remain valid, including in defer, for initialization/update, nested functions, and generic bodies. Discarding an outer expression never allows a no-result call to supply a value inside it. Renamed imports follow the same rule. Same-spelled user functions and user void bindings are unchanged; general user void-value policy remains open.

Prelude Option(T) and Result(T, E):

Option(T) and Result(T, E) are package-owned tagged unions available in every file: Option has some: T and none: bool; Result has ok: T and err: E. User declarations of either name fail at semantic exit 6 (field names remain valid). Prelude types do not create std/option or std/result modules. Propagate errors with explicit match; A7 has no ? operator, and get/pop or or{}/use helpers remain deferred.

Zig stdout and stderr buffering:

Stdout helpers share one persistent writer and flush at program exit, before each stderr write, before a panic, before a stdin read, and on newlines when stdout is a terminal. Stderr helpers flush after every call. Writing to a closed pipe exits with status 0 and no message; other formatting or write failures panic. Stdout and stderr stay separate, and stdout content always precedes later stderr writes.

Planned Generation 2 signatures (not callable):

The signatures below describe a planned unqualified API (print_i32, print_f64, printf, eprint, eprintln, print, plus string, ASCII, memory, and assertion functions). Keep Generation 1 and Generation 2 separate: today only io.eprintln exists (stderr with newline), while bare eprint (stderr without newline) and unqualified print :: fn(s: string) are unimplemented proposals.

// Math functions (specific signatures, no generics)
abs_i32 :: fn(x: i32) i32
abs_i64 :: fn(x: i64) i64
abs_f32 :: fn(x: f32) f32
abs_f64 :: fn(x: f64) f64

min_i32 :: fn(a: i32, b: i32) i32
min_i64 :: fn(a: i64, b: i64) i64
min_f32 :: fn(a: f32, b: f32) f32
min_f64 :: fn(a: f64, b: f64) f64

max_i32 :: fn(a: i32, b: i32) i32
max_i64 :: fn(a: i64, b: i64) i64
max_f32 :: fn(a: f32, b: f32) f32
max_f64 :: fn(a: f64, b: f64) f64

// Float math functions
sqrt_f32 :: fn(x: f32) f32
sqrt_f64 :: fn(x: f64) f64
pow_f32 :: fn(x: f32, y: f32) f32
pow_f64 :: fn(x: f64, y: f64) f64
sin_f64 :: fn(x: f64) f64
cos_f64 :: fn(x: f64) f64
tan_f64 :: fn(x: f64) f64

// I/O functions
print :: fn(s: string)
print_i32 :: fn(x: i32)
print_f64 :: fn(x: f64)
printf :: fn(fmt: string, args: ..)
eprint :: fn(s: string)
eprintln :: fn(s: string)

// Assertions (separate functions, no overloading)
assert :: fn(cond: bool)
assert_msg :: fn(cond: bool, msg: string)
panic :: fn(msg: string)

// String functions
str_len :: fn(s: string) usize
str_copy :: fn(dst: []u8, src: string) usize
str_compare :: fn(a: string, b: string) i32
str_find :: fn(haystack: string, needle: string) isize
str_contains :: fn(haystack: string, needle: string) bool
str_starts_with :: fn(s: string, prefix: string) bool
str_ends_with :: fn(s: string, suffix: string) bool

// ASCII character functions
char_is_alpha :: fn(c: char) bool
char_is_digit :: fn(c: char) bool
char_is_upper :: fn(c: char) bool
char_is_lower :: fn(c: char) bool
char_to_upper :: fn(c: char) char
char_to_lower :: fn(c: char) char

// Memory functions
mem_copy :: fn(dst: []u8, src: []u8) usize
mem_move :: fn(dst: []u8, src: []u8) usize
mem_set :: fn(dst: []u8, val: u8) usize
mem_zero :: fn(dst: []u8) usize
mem_compare :: fn(a: []u8, b: []u8) i32
mem_alloc :: fn(size: usize) ref u8
mem_free :: fn(ptr: ref u8)
mem_realloc :: fn(ptr: ref u8, old_size: usize, new_size: usize) ref u8

12. Tokens and AST Components

12.1 Token Types

The authoritative token list is the TokenType enum in a7/tokens.py. The enumeration below mirrors it exactly (member name, then source spelling). Words with no keyword entry lex as IDENTIFIER (see §2.4); cast, const, self, size_of, type, using, and var have no token type of their own.

// Literals
INTEGER_LITERAL       // 42, 0x2A, 0b101010
FLOAT_LITERAL         // 3.14, 2.71e10
STRING_LITERAL        // "hello"
CHAR_LITERAL          // 'a', '\n', '\x41'
TRUE_LITERAL          // true
FALSE_LITERAL         // false
NIL_LITERAL           // nil

// Identifiers, builtins, and generics
IDENTIFIER            // user-defined names
BUILTIN_ID            // @name
GENERIC_TYPE          // $T

// Keywords (each keyword spells itself)
AND AS BOOL BREAK CASE CHAR CONTINUE DEL DEFER ELSE ENUM
F32 F64 FALL FALSE FLOAT FN FOR IF IMPORT IN INT
I8 I16 I32 I64 ISIZE LET MATCH NEW NIL NOT OR
PUB REF RET STRING STRUCT TRUE UNION
U8 U16 U32 U64 UINT USIZE WHERE WHILE

// Operators
PLUS                  // +
MINUS                 // -
MULTIPLY              // *
DIVIDE                // /
MODULO                // %
ASSIGN                // =
PLUS_ASSIGN           // +=
MINUS_ASSIGN          // -=
MULTIPLY_ASSIGN       // *=
DIVIDE_ASSIGN         // /=
MODULO_ASSIGN         // %=
EQUAL                 // ==
NOT_EQUAL             // !=
LESS_THAN             // <
LESS_EQUAL            // <=
GREATER_THAN          // >
GREATER_EQUAL         // >=
BITWISE_AND           // &
BITWISE_OR            // |
BITWISE_XOR           // ^
BITWISE_NOT           // ~
LEFT_SHIFT            // <<
RIGHT_SHIFT           // >>
BITWISE_AND_ASSIGN    // &=
BITWISE_OR_ASSIGN     // |=
BITWISE_XOR_ASSIGN    // ^=
LEFT_SHIFT_ASSIGN     // <<=
RIGHT_SHIFT_ASSIGN    // >>=
LOGICAL_NOT           // !

// Punctuation and declarations
DECLARE_CONST         // ::
DECLARE_VAR           // :=
COLON                 // :
COMMA                 // ,
DOT                   // .
DOT_DOT               // ..
LEFT_PAREN            // (
RIGHT_PAREN           // )
LEFT_BRACKET          // [
RIGHT_BRACKET         // ]
LEFT_BRACE            // {
RIGHT_BRACE           // }

// Statement termination and end of file
TERMINATOR            // newline or ; (consecutive terminators collapse)
EOF                   // end of file

Notes:

  • and, or, and not are keyword tokens; only ! is LOGICAL_NOT.
  • ... and ? have no token: ... is rejected with an unsupported-operator error and ? with an unexpected-character error.
  • The enum also declares SEMICOLON, ADDRESS_OF, DEREFERENCE, and COMMENT, which the tokenizer never emits: ; produces TERMINATOR, & produces BITWISE_AND, and comments are discarded without a token.

12.2 AST Node Types

The following names are a historical design sketch, not the Python AST API. Current node kinds are NodeKind members in a7/ast_nodes.py, such as PROGRAM, FUNCTION, and TYPE_POINTER. The sketch includes proposed nodes absent from that enum.

// Top-level nodes
AST_PROGRAM             // Root of the entire program
AST_IMPORT_DECL         // Import declarations
AST_FUNCTION_DECL       // Function declarations
AST_STRUCT_DECL         // Struct type declarations
AST_UNION_DECL          // Union type declarations
AST_ENUM_DECL           // Enum type declarations
AST_TYPE_ALIAS          // Type alias declarations
AST_CONST_DECL          // Constant declarations
AST_VAR_DECL            // Variable declarations

// Type nodes
AST_TYPE_PRIMITIVE      // Built-in types (i32, f64, etc.)
AST_TYPE_IDENTIFIER     // User-defined type names
AST_TYPE_POINTER        // ref T
AST_TYPE_ARRAY          // [N]T
AST_TYPE_SLICE          // []T
AST_TYPE_FUNCTION       // fn(T, U) V
AST_TYPE_GENERIC        // T with generic parameters
AST_TYPE_STRUCT         // Anonymous struct types
AST_TYPE_UNION          // Anonymous union types

// Expression nodes
AST_EXPR_LITERAL        // Literal values
AST_EXPR_IDENTIFIER     // Variable/function names
AST_EXPR_BINARY         // Binary operations (a + b)
AST_EXPR_UNARY          // Unary operations (-a, !b)
AST_EXPR_CALL           // Function calls
AST_EXPR_INDEX          // Array/slice indexing
AST_EXPR_SLICE          // Slice expressions [start..end]
AST_EXPR_FIELD          // Struct field access (a.field)
AST_EXPR_DEREF          // Internal dereference inserted by typed lowering
AST_EXPR_CAST           // Type casting
AST_EXPR_IF             // Conditional expressions
AST_EXPR_MATCH          // Match expressions
AST_EXPR_STRUCT_INIT    // Struct initialization
AST_EXPR_ARRAY_INIT     // Array initialization

// Statement nodes
AST_STMT_EXPRESSION     // Expression statements
AST_STMT_BLOCK          // Block statements { ... }
AST_STMT_IF             // If statements
AST_STMT_WHILE          // While loops
AST_STMT_FOR            // For loops
AST_STMT_MATCH          // Match statements
AST_STMT_BREAK          // Break statements
AST_STMT_CONTINUE       // Continue statements
AST_STMT_RETURN         // Return statements
AST_STMT_DEFER          // Defer statements
AST_STMT_ASSIGNMENT     // Assignment statements

// Pattern nodes (for match statements)
AST_PATTERN_LITERAL     // Literal patterns (42, "hello")
AST_PATTERN_IDENTIFIER  // Existing identifier patterns or branch-local captures
AST_PATTERN_ENUM        // Enum variant patterns
AST_PATTERN_RANGE       // Range patterns (1..10)
AST_PATTERN_WILDCARD    // Wildcard pattern (_)

// Generic nodes
AST_GENERIC_PARAM       // Generic type parameters ($T, $T: Numeric)
AST_GENERIC_CONSTRAINT  // Type set constraints (Numeric or @type_set(...))
AST_GENERIC_INSTANCE    // Generic instantiation
AST_TYPE_SET            // Type set definitions (@type_set(...))

// Utility nodes
AST_PARAMETER           // Function parameters
AST_FIELD               // Struct/union fields
AST_ENUM_VARIANT        // Enum variants
AST_CASE_BRANCH         // Match case branches
AST_IDENTIFIER_LIST     // List of identifiers
AST_EXPRESSION_LIST     // List of expressions
AST_TYPE_LIST           // List of types

12.3 AST Node Structure

The following A7 structs are historical design sketches. The current compiler uses a Python ASTNode dataclass with optional fields and SourceSpan; it does not use this tagged-data layout or a generic children array.

ASTNode :: struct {
    kind: ASTNodeKind          // Type of the node
    location: SourceLocation   // Position in source file
    data: union {              // Node-specific data
        literal: LiteralData
        binary: BinaryExprData
        function: FunctionData
        // ... other node types
    }
    children: []ref ASTNode    // Child nodes
}

SourceLocation :: struct {
    file: string
    line: i32
    column: i32
    offset: i32
}

LiteralData :: struct {
    type: LiteralType
    value: union {
        int_val: i64
        float_val: f64
        char_val: char
        string_val: string
        bool_val: bool
    }
}

BinaryExprData :: struct {
    operator: TokenType
    left: ref ASTNode
    right: ref ASTNode
}

FunctionData :: struct {
    name: string
    params: []ref ASTNode
    return_type: ref ASTNode
    body: ref ASTNode
    is_generic: bool
    generic_params: []ref ASTNode  // List of AST_GENERIC_PARAM nodes
}

GenericParamData :: struct {
    name: string              // Parameter name (T without $)
    constraint: ref ASTNode   // Optional type set constraint (Numeric or @type_set(...))
}

TypeSetData :: struct {
    name: string              // Type set name
    types: []ref ASTNode      // List of types in the set
}

12.4 Parsing Precedence

Operator precedence (highest to lowest):

  1. Primary expressions (literals, identifiers, parentheses)
  2. Postfix (function calls, array access, field access)
  3. Unary prefix (-, !, ~, cast)
  4. Multiplicative (*, /, %)
  5. Additive (+, -)
  6. Shift (<<, >>)
  7. Relational (<, >, <=, >=)
  8. Equality (==, !=)
  9. Bitwise AND (&)
  10. Bitwise XOR (^)
  11. Bitwise OR (|)
  12. Logical AND (and)
  13. Logical OR (or)
  14. Assignment (=, +=, -=, etc.)

13. Grammar Summary

This abbreviated grammar retains some design-only alternatives. It is not an acceptance grammar. The parser and the qualifications in each section determine current syntax. In particular, import metadata does not imply backend support, and generic declaration examples in §6 and §7 give the accepted spelling.

13.1 Top-Level Grammar

program = (import_decl | declaration)*

import_decl =
    | "import" string_lit
    | identifier "::" "import" string_lit
    | "import" string_lit "{" identifier_list "}"
    | "using" "import" string_lit

declaration =
    | function_decl
    | type_decl
    | const_decl
    | var_decl

function_decl =
    | identifier "::" "fn" "(" param_list? ")" type? where_clause? block
    | identifier "(" generic_params ")" "::" "fn" "(" param_list? ")" type? where_clause? block

generic_params =
    | generic_param ("," generic_param)*

generic_param =
    | "$" identifier
    | "$" identifier ":" type_set
    | "$" identifier ":" "@type_set" "(" type_list ")"

where_clause = "where" identifier ":" type_set ("," identifier ":" type_set)*

A where_clause follows a function signature (before the body {) or follows the { ... } body of a struct or union declaration (Name($T) :: struct { ... } where ...). Only set-membership bounds are accepted; anything richer fails at semantic exit 6 (see §7.3).

13.2 Type Grammar

type =
    | primitive_type
    | identifier type_args?
    | "[" expr? "]" type
    | "ref" type
    | "fn" generic_params? "(" type_list? ")" type?
    | struct_type
    | union_type

type_args = "(" type ("," type)* ")"

type_set = identifier  // References to type sets like Numeric, Integer

struct_type = "struct" generic_params? "{" field_list? "}"
union_type = "union" generic_params? "(" "tag" ")" "{" variant_list "}"

field_list = field ("," field)*
field = "pub"? identifier ":" type

variant_list = variant ("," variant)*
variant = identifier ":" type

The (tag) marker is optional in the parser (union() is also accepted), and there is no rule for an anonymous inline union type even though §12.2 lists AST_TYPE_UNION. See STATUS Known Gaps.

13.3 Expression Grammar

expr = logical_or_expr

logical_or_expr = logical_and_expr ("or" logical_and_expr)*
logical_and_expr = bitwise_or_expr ("and" bitwise_or_expr)*
bitwise_or_expr = bitwise_xor_expr ("|" bitwise_xor_expr)*
bitwise_xor_expr = bitwise_and_expr ("^" bitwise_and_expr)*
bitwise_and_expr = equality_expr ("&" equality_expr)*
equality_expr = relational_expr (("==" | "!=") relational_expr)*
relational_expr = shift_expr (("<" | ">" | "<=" | ">=") shift_expr)*
shift_expr = additive_expr (("<<" | ">>") additive_expr)*
additive_expr = multiplicative_expr (("+" | "-") multiplicative_expr)*
multiplicative_expr = unary_expr (("*" | "/" | "%") unary_expr)*

unary_expr =
    | postfix_expr
    | unary_op unary_expr
    | "cast" "(" type "," expr ")"

postfix_expr =
    | primary_expr
    | postfix_expr "[" expr "]"
    | postfix_expr "[" expr? ".." expr? "]"
    | postfix_expr "." identifier
    | postfix_expr "(" expr_list? ")"

primary_expr =
    | identifier
    | literal
    | "(" expr ")"
    | "if" expr block "else" block_or_if

Assignment is statement-only in the parser. a = b = 3 is rejected; it is not a right-associative expression. See test_statement_forms_codegen.py.

13.4 Statement Grammar

statement =
    | assignment_stmt
    | expr_stmt
    | block_stmt
    | if_stmt
    | match_stmt
    | loop_label loop_stmt
    | for_stmt
    | while_stmt
    | jump_stmt
    | defer_stmt
    | var_decl

loop_label = "@" identifier
loop_stmt = for_stmt | while_stmt

jump_stmt =
    | "ret" expr?
    | "break" identifier?
    | "continue" identifier?

assignment_stmt = postfix_expr assign_op expr

defer_stmt = "defer" statement

Appendix A: Language Semantics

A.1 Evaluation Order

  1. Function arguments: left-to-right
  2. Binary operators: left-to-right
  3. Assignment is statement-only; chained assignment is rejected
  4. Field initialization: declaration order

A.2 Type Conversions

Current checked conversions include:

  • Safe numeric widening according to the implemented scalar compatibility rules.
  • T lvalues to ref T in function calls.
  • Integer literals to an integer destination when the value fits, including arguments and return values. A literal branch can take the other branch's type.

Implicit array-to-slice conversion is not supported; slice arrays explicitly. Mixed-width arithmetic uses the wider compatible type, and narrowing a result requires an explicit checked cast. Integer +, -, and * (including compound assignments) wrap on overflow. In release builds, the backend lowers those integer operations to non-wrapping arithmetic when the safety pass proves the result fits; debug builds and unproven operations keep wrapping, and --no-nonwrap forces wrapping in all profiles. Unsigned negation is rejected. Constant shift counts must be non-negative and smaller than the operand's bit width. Other numeric edge cases still require qualification.

A.3 Name Resolution

  1. Current scope
  2. Enclosing scopes (outward)
  3. File scope
  4. Imported names
  5. Built-in names

A.4 Lifetime Rules

These are intended lifetime requirements, not established compiler guarantees. The current proof limits are in the safety contract.

  1. Stack values live until scope exit
  2. Heap values live until explicit del
  3. References must not outlive referent
  4. Slices must not outlive backing array

Appendix B: Standard Compiler Diagnostics

B.1 Error Categories

The E-number families below are historical design labels. Current diagnostics use the codes and exit stages in the error catalog.

  • E0xxx: Syntax errors
  • E1xxx: Type errors
  • E2xxx: Lifetime errors
  • E3xxx: Generic instantiation errors
  • E4xxx: Module/import errors

B.2 Common Lexer Error Messages

The A7 compiler provides specific error messages for lexical analysis failures:

  • "Unexpected character: 'X'" - Invalid character found in source code
  • "The string is not closed" - Unterminated string literal
  • "The char is not closed" - Unterminated character literal
  • "Tabs '\\t' are unsupported" - Tab character found (not supported)
  • "Invalid string escape sequence" - Unknown escape or malformed \xHH escape in a string literal
  • "Identifier is too long" - Identifier exceeds 100 characters
  • "Number is too long" - Numeric literal exceeds 100 characters

Error Format:

error: <message>, line: <line>, col: <column>
help: <helpful advice>
   <line_number> │ <source_code_line>
                 │ <error_pointer>

B.3 Warning Categories

These W-number families are proposed categories, not a current warning API.

  • W0xxx: Unused code
  • W1xxx: Deprecated features
  • W2xxx: Performance issues
  • W3xxx: Potential bugs

Appendix C: Implementation Limits

The tokenizer enforces the first three limits below. The remaining rows are historical proposed limits, not implemented minimum capacities or enforced caps. The parser instead has MAX_NESTING_DEPTH = 256 for tracked nested constructs; this is not a promise that every 256-deep program completes every compiler pass. See a7/tokens.py and a7/parser.py.

Feature Limit or historical proposal
Identifier length 100 characters
Numeric literal length 100 characters
String literal length 32,767 characters, including both quotes
Function parameters 255
Generic parameters 32
Nested blocks 127
Array dimensions 8
Struct fields 1,023
Union variants 255
Enum values 65,535
Import depth 32 (planned)
Defer statements per scope 255
Match cases 1,023

Import depth 32 is an unapproved proposal. L69 does not authorize that cap. The loader uses an explicit stack; the low-recursion regression loads 1,100 modules in test_iterative_module_loading.py.

Exact evaluation limit Cap
Absolute decimal exponent in a numeric token 4,096
Reduced numerator or denominator 131,072 bits each
Transient arithmetic component 262,144 bits
Work per evaluated initializer or fitting context 2^24 limb-operation credits
Work per compilation 2^32 limb-operation credits
Retained bindings and exact-value cache 16 MiB of logical payload
Constant dependency-chain depth 65,536 bindings
Rendered diagnostic value 256 characters
Exact-evaluation diagnostic message field 2,048 characters
Rendered dependency chain At most 32 links

Exact evaluation accounting rules:

  • Each evaluated initializer keeps its work counter across fitting and repeated checks. All modules share one compilation account; each compilation starts with fresh counters. Limit failures report as located semantic errors (exit 6) without approximate values or silent fallbacks. See P-TYP.
  • Credits count deterministic work under the resource policy (executed exact arithmetic, comparisons, fitting, and cache/reference work, not elapsed time). Size checks run before allocation, so conservative bounds can reject an operation whose reduced result would fit.
  • The checker reports the first classified resource failure per initializer and resource category. Repeated failures in that category keep their failed evaluation state without repeating the diagnostic. Separate initializers, other categories, unclassified failures, and ordinary arithmetic errors still report.
  • Retained bindings and AST cache entries count separately at 64 bytes plus the rounded-up byte lengths of numerator and denominator magnitudes; replacement and release update this logical total (not process RSS). Binding depth covers local, global, and imported exact numeric bindings, not runtime dependencies. Long chain diagnostics keep the first and last 16 links, and the 2,048-char message cap excludes file/span metadata and source excerpts.
  • Generic pattern conversions share the compilation account and original initializer counter. The checker prepares both float-width encodings (f32 and f64) for generic bodies, including unused templates; resource exhaustion fails even in an unused width, while target overflow stays a representability error. Temporary fitted copies release without altering the shared exact template.
  • These rules implement C3–C10 accounting. The C2 exponent check remains semantic exit 6 before exact-value allocation, and full C11 emission qualification remains open. Math-call output and emitted numeric spelling are unchanged.

Appendix D: ASCII Character Set Support

A7 identifiers, keywords, and numeric literals use ASCII only (see §2.1, §2.3, and §2.6). For the accepted escape spellings in character and string literals, see §2.6: \n, \t, \r, \\, \', \", \0, and \xHH with exactly two hex digits.

The tokenizer accepts only the eight escapes listed in §2.6 and rejects \b, \f, \v, and \a.


Appendix E: Implementation Status (a7-py)

Current implementation gaps live in Status. The compiler/package gate is run_all_tests.sh; the full release gate is run_release_checks.sh. A historical test count or feature list does not establish that the current tree passes these checks.

a7-py is not a sandbox. Compile and execute only A7 source you trust.

E.1 Current Constraints and Open Gaps

  1. Supported fall scope restrictions

    • fall is supported in match statements and lowers in Zig.
    • fall must be the final direct statement of a non-final match case.
    • fall is invalid outside match cases, in else branches, in final cases, or nested inside other control-flow statements.
  2. Advanced match diagnostics

    • Exhaustiveness for bool/enum is implemented.
    • Exact duplicate bool, enum, and scalar literal patterns are diagnosed.
    • Wildcard-first and fully covered bool/enum cases make later cases and else branches unreachable.
    • Literal and compile-time constant numeric/char range overlaps are diagnosed.
    • Integer literal/range comparisons retain integer precision after fitting to the subject type, including values beyond 2^53. Distinct adjacent values remain distinct; a literal equal to a singleton range endpoint overlaps it.
    • Conservative non-constant symbolic interval overlaps are diagnosed when inclusive ranges share an endpoint symbol.
    • Bare undefined identifier patterns are undefined-name errors; use _ for wildcards and bind from the scrutinee in the arm body when needed.
  3. Memory/lifetime model depth

    • Basic new/del validation and direct use-after-del rejection exist; full ownership/lifetime and aliasing analysis is not complete.
  4. Backend hardening

    • Zig is the only supported code generation target.
    • The retired C backend no longer defines release readiness or public support status.
    • Backend regression coverage should continue expanding for every new language feature.
  5. Release packaging activation

    • Python packaging and installed CLI are present.
    • Tag-triggered draft GitHub releases attach package, docs, and native example artifacts.
    • Package-registry publishing is not part of the current release workflow.

E.2 Source Of Truth

  • Status tracks language gaps, priorities, and roadmap notes.
  • Release checklist tracks local build and release gates.