Vector Labs

Arra — Core IR

Status

This document is the normative boundary between elaborated Arra and executable Core. Surface Syntax defines source parsing; Essential Arra defines source semantics.

Core is deliberately smaller than the surface language but not untyped. The front end produces immutable monomorphic Typed IR, lowers it structurally, and then invokes an independent Core checker. The deterministic treewalk interpreter executes only checked Core.

1. Module

A Core module contains:

Module {
  name
  entry
  operations
  constructors
  nominals
  initializationEffects
  body
}

The body is one ordered expression producing the selected entry after module initialization. Source modules, dependency selectors, interfaces, hook tables, theories, models, laws, and evidence do not remain. Operation, constructor, and nominal schemas remain because independent checking and execution require their identity and representation contracts.

All names are resolved and globally stable. Primitive access has already been restricted to the installed Prelude graph.

2. Types, dimensions, and effects

Core monotypes are:

Type =
    I64 | Nat | U8 | F64 | Bool | Char | String | Symbol | Bottom
  | Generic(name)
  | Named(name, arguments)
  | Function(argument, effects, result)
  | Record(fields)
  | Array(element, dimension)
  | Exists(dimensionBinder, body)
  | TypeConstructor(constructor)
  | ConstructorApplication(constructor, argument)

Dimension = Static(nonnegative integer)
          | Bound(name)
          | Any

TypeConstructor = Nominal(name)
                | Frame(dimension)
                | ConstructorVariable(name)

Effects = { labels: EffectLabel*, tail: name? }
EffectLabel = { nominalName, typeArguments }

Record([]) is unit. Tuples are records whose fields are canonical ordinals; Core has no tuple type. Record field order is canonical and field identity is either a lower-case label or a normalized nonnegative ordinal.

Generic and constructor variables may remain inside a checked generic Core binding where independent checking needs the specialized schema. Surface Name, Fields, theory constraints, models, and evidence never become Core types. Static field names have already specialized to FieldName.

Bottom is permitted where any result type is demanded, but only an effect performance has bottom result. Dimensions are literal, bound by existential unpack, or dynamically unknown. Nested Array nodes encode rank.

An effect label includes its nominal constructor and all type arguments. Effect rows are canonical sets with at most one tail. They constrain possible effects; strict expression order determines runtime order.

3. Patterns

Pattern =
    Wild
  | Var(name, type)
  | Literal(value)
  | Record((field, pattern)*)
  | Constructor(name, payload?)
  | Array(pattern*)

Tuple patterns are ordinal record patterns. Patterns bind completed values and perform no computation. Constructor identity is checked against the module schema. Array patterns are exact-length patterns. Core has no hook, extractor, view-pattern, or conditional-path pattern.

4. Terms

Every term stores its monotype, effect row, and source span:

Expr =
    Literal(value)
  | Variable(name)
  | Lambda(name, argumentType, body)
  | Apply(mapping, argument)
  | Let(name, type, initializer, body)
  | LetRec(bindings, body)
  | Record((field, value)*)
  | Concat(leftRecord, rightRecord)
  | Remove(record, field)
  | Array(elements)
  | Project(record, field)
  | Update(record, field, replacement)
  | ArrayGet(array, index)
  | ArrayFilter(array, predicate)
  | ArrayFlatten(array, depth)
  | Unfold(protocol, target, seed, step)
  | GenerateExact(frameExtents, seed, step)
  | View(recordArrayRow)
  | PackDim(runtimeDimension, value)
  | UnpackDim(package, dimensionName, valueName, body)
  | Constructor(name, payload?)
  | Case(subject, branches, fallback?)
  | Perform(operation, payload)
  | Handle(computation, handler)
  | Primitive(identity)

There are no Core nodes for:

4.1 Functions and bindings

Lambda is a completed pure value; its function type contains its body’s latent effects. Apply evaluates the mapping then argument once and invokes the mapping. Surface subject-first ordering has already become ordered Let and Apply structure.

Let evaluates its initializer once before its body. LetRec allocates every binding in one lexical recursive environment; each initializer is a function value satisfying its annotation. Module initialization is represented by the outer ordered let chain.

4.2 Records

Record evaluates fields once in source-established order and stores them in canonical field order. Concat requires disjoint field sets and produces their canonical union. Remove requires the field to exist. Project and Update use one concrete canonical field identity.

Tuple and unit operations are these same record operations over ordinal or empty fields. Nominal record projection and update have been lowered through known representation metadata without erasing nominal type boundaries.

4.3 Arrays

Array constructs a regular leading axis. Every element has an equal checked type and compatible inner shape. ArrayGet uses a checked nonnegative Nat index contract; source wrappers perform bounds validation before unchecked raw primitives where the lowering chooses a primitive call instead.

ArrayFilter preserves source order and evaluates its predicate in order. ArrayFlatten concatenates a fixed nested depth while preserving element order. Unfold repeatedly invokes a step until its protocol-specific stop result, targeting either a regular array or a source nominal collection protocol. GenerateExact reifies each static or existential frame extent and invokes its step exactly the frame cardinality in row-major order.

Arrays of structural records use canonical column storage. View presents one logical row over those columns without changing observable record semantics. Dense U8, Char, and Symbol arrays retain specialized flat lane storage.

4.4 Existential dimensions

PackDim(d, value) introduces one runtime dimension witness and a value whose type mentions it. UnpackDim evaluates the package once, binds both witness and value, and checks the body under the fresh dimension name. The witness cannot escape except through another existential package.

4.5 Algebraic data

Constructor checks its optional payload against the declared schema. Case evaluates its subject once, tests branches in order, and evaluates only the selected body. The optional fallback represents a conservative residual path. Structural exhaustiveness has already removed unreachable failure where proven.

4.6 Effects

Perform names one declared operation, checks its payload, contributes the operation’s exact instantiated effect label, and has type Bottom.

Handle evaluates one computation under one exact effect handler. It contains one clause per declared operation and one return clause. The handled effect is removed only from the computation; clause-body effects remain outside. Core operations are non-resumable and carry no continuation value.

5. Evaluation order

Core is strict and deterministic:

  1. Let: initializer, then body.
  2. Apply: mapping, then argument, then call.
  3. Record and Array: elements in stored source-established order.
  4. Concat: left, then right.
  5. Update: record, then replacement.
  6. ArrayGet: array, then index.
  7. Filter/unfold/generation: source or seed, modifier, then sequential invocations.
  8. Case: subject once, then only the selected branch.
  9. Perform: payload before transfer.
  10. Handle: handled computation first; then the selected operation or return clause.

Effects are sets in annotations, not traces. An optimizer may reorder only when it proves observational equivalence, including failure and divergence.

6. Primitive ABI

Primitive(identity) is a typed function value to the compiler-owned registry. Primitive names are not a public user FFI. Prelude wraps raw status and unchecked operations into source types, effects, and failures.

The registry contains these identities.

6.1 Scalars

prim.i64.add
prim.i64.sub
prim.i64.mul
prim.i64.divUnchecked
prim.i64.checkedAddRaw
prim.i64.checkedSubRaw
prim.i64.checkedMulRaw
prim.i64.saturatingAdd
prim.i64.eq
prim.i64.lt
prim.i64.neg

prim.nat.mul
prim.nat.add
prim.nat.subUnchecked
prim.nat.eq
prim.nat.lt

prim.u8.eq
prim.u8.lt

prim.f64.add
prim.f64.sub
prim.f64.mul
prim.f64.div
prim.f64.eq
prim.f64.lt
prim.f64.neg
prim.f64.sqrt

prim.char.eq
prim.char.lt
prim.char.codePoint
prim.char.fromCodePointRaw

I64 addition, subtraction, multiplication, and negation are modular two’s-complement operations. divUnchecked requires a nonzero divisor; Prelude checks it and defines minI64 / -1 = minI64. Nat subtraction is unchecked only after a source-level order test. Raw checked conversions and arithmetic return a Boolean success status plus a result slot.

6.2 Text, symbols, and conversions

prim.string.concat
prim.string.eq
prim.string.lt
prim.string.byteLength
prim.string.byteAtUnchecked
prim.string.sliceBytesUnchecked
prim.string.characterAtByteUnchecked
prim.string.characterCount
prim.string.toCharacters
prim.string.fromCharacters
prim.string.encodeUtf8
prim.string.decodeUtf8Raw
prim.string.split
prim.string.join
prim.string.parseI64Raw
prim.string.fromI64

prim.symbol.intern
prim.symbol.spelling
prim.symbol.eq

prim.convert.i64ToF64
prim.convert.i64ToNatRaw
prim.convert.natToI64Raw
prim.convert.u8ToI64
prim.convert.u8ToNat
prim.convert.i64ToU8Raw
prim.convert.natToU8Raw
prim.convert.u8ToChar
prim.convert.charToU8Raw

Unchecked String byte operations require validated UTF-8 boundaries supplied by Prelude. decodeUtf8Raw returns success, decoded text, valid-prefix length, whether the invalid sequence length is known, and that length. It does not raise a source effect. Symbol interning uses exact UTF-8 spelling and process-lifetime identity.

6.3 Arrays

prim.array.length
prim.array.inBounds
prim.array.columnInBounds
prim.array.sliceInBounds
prim.array.indexUnchecked
prim.array.updateUnchecked
prim.array.generate
prim.array.reverse
prim.array.enumerate
prim.array.concat
prim.array.take
prim.array.drop
prim.array.zip
prim.array.adjacentPairs
prim.array.any
prim.array.all
prim.array.rowUnchecked
prim.array.columnUnchecked
prim.array.sliceUnchecked

Bounds predicates are total and pure. Their corresponding unchecked selectors are valid only on a successful predicate result retained in the same lowering path. zip returns raw success and length information consumed by Prelude rather than raising. Array construction uses literals, Unfold, GenerateExact, or the listed structural operations.

6.4 IO

prim.io.argumentsRaw
prim.io.readLineRaw
prim.io.readBytesRaw
prim.io.writeBytesRaw
prim.io.createBytesRaw
prim.io.appendBytesRaw
prim.io.writeBytesAtomicallyRaw
prim.io.writeLineRaw
prim.io.writeErrorLineRaw

Raw IO reports host results structurally:

Prelude assigns source IO and Fail contracts, preserves resource identity, and maps write status to WriteImpact. Text writes encode to UTF-8 before using the byte primitives.

7. Lowering obligations

Lowering from Typed IR must:

  1. preserve source evaluation order with explicit lets;
  2. replace every hook request with its selected direct implementation;
  3. replace constraint-derived requirements with their certified implementation;
  4. erase theories, models, laws, certifications, and evidence;
  5. turn implicit to into an explicit selected application;
  6. expand invocation residuals, structural alignment, atops, forks, and trains into functions and applications;
  7. compile conditional paths into ordered cases and explicit residual failure;
  8. convert tuple/unit syntax to ordinal/empty records;
  9. specialize static field names and lower row concat/removal directly;
  10. lower regular traversal, filtering, flattening, unfolding, and exact generation to their structural nodes;
  11. retain existential runtime witnesses with pack/unpack;
  12. preserve nominal identities and canonical columnar layouts;
  13. erase module syntax after full qualification and deterministic initialization ordering;
  14. attach the exact monotype and effect annotation to every term.

No lowering step may re-run hook or model selection. Selected source declaration identity is part of elaboration output.

8. Independent validation

The Core checker reconstructs every term’s type and effects from:

It rejects unbound names, annotation mismatches, illegal recursive values, invalid constructor payloads, noncanonical or mismatched records, incompatible array elements and shapes, invalid unpack escapes, malformed cases, wrong operation payloads, incomplete or duplicate handlers, incorrect handled effects, bottom annotations on non-performance terms, and primitive ABI mismatches.

Bottom is permitted where a demanded result is expected. Effect checking permits an expression with a subset of the annotated effect upper bound, but the stored annotation itself must match the independently reconstructed result for that term.

9. Reference execution

The treewalk interpreter implements every Core node and primitive listed here. It preserves strict ordering, arbitrary-precision Nat, modular I64, Unicode scalar validity, regular arrays, canonical record columns, exact nominal constructors, existential witnesses, non-resumable handlers, and structured raw IO results.

Host exceptions are implementation failures unless the primitive contract explicitly maps the condition to a raw status. A future optimizer or native backend is conforming only if it consumes checked Core and preserves these observable semantics.