Browse documentation
Language

Language reference

Variables, functions, static types, control flow, classes, and the current language contracts.

ImplementedAner 0.1.0 or newer

This reference covers the scalar core, import free temporal, binary, range, outcome and collection values, and built in aner.nn, aner.viz, aner.dataset, aner.tensor, aner.metrics, aner.ml, aner.data, aner.dev, aner.parallel, aner.llm, aner.secrets, aner.science, aner.api, aner.db, aner.math, aner.random, aner.units, and experimental aner.quantum modules supported by aner check and aner run. Sections marked as proposals describe additional numerical syntax and large data features that are not implemented.

The examples use an installed aner command. See installation and release availability to choose a package for your system, and VS Code setup for editing and notebooks. Match the documentation and editor extension to the release you install.

Aner supports Number, Float32 scalars and packed arrays, 8/16/32/64-bit integers with packed array storage, checked numeric promotion, Float64 / and integer_div. Integer literals default to Int64, and floating literals to Float64; conversions that lose precision require an explicit constructor. The examples require a compatible runtime with the documented capabilities, including function parameter defaults, expected type Optional/Result constructors, bracket array access, Result propagation, aner.math, scalar aner.units types/literals, packed unit bearing arrays and CSV unit columns. The complete research syntax example and scalar unit basics exercise them without external data; records, automatic source unit inference, general dataset unit schemas and typed named repetition results remain proposals.

Source and execution

Programs are UTF-8 text in .aner files. This is the canonical source extension for interpreted execution and the development native compilation subset. A UTF-8 byte order mark is allowed at the beginning. Any editor can create them; the Aner executable checks and executes them.

The notebook document extension is .anernb (Interactive Aner Notebook), distinct from plain .aner source. The Aner extension provides Aner — notebook, which follows the document’s execution mode: shared native values, imports, and functions by default, or independent executions when explicitly configured. A remembered Aner kernel selection does not override the document’s mode. No source wrappers or previous cell replay are used. Markdown and images belong to the document, not Aner syntax. The optional Jupyter kernel executes Aner .ipynb notebooks through the same native session engine. Development inspection is opt in and represents completed cells. See the notebook guide for setup, session lifecycle, and limits.

text
aner check program.aner
aner program.aner
aner run program.aner
aner run program.aner --max-steps 2000000
aner --help
aner --version

run is optional: aner program.aner is equivalent to aner run program.aner, including --max-steps, --dev, --prod, --debug-viz, and --debug-values. A positional source path defaults to execution. check, run, session, build, and maps remain reserved command names; use a path such as ./check to execute a file with a reserved name. Filenames beginning with - also need a path prefix such as ./.

check parses and statically checks the entire file without executing it, then prints OK. run performs the same checks before interpreting the program. It prints only the program's output on success. Diagnostic failures return a nonzero process status and identify a source location when applicable. A file may contain direct top level statements, or define fn main() -> Unit. Mixing executable top level statements with main is rejected. Helper functions remain file level declarations in either form. In a direct script, statements execute in source order; a function can access typed global bindings, but reading one before its initializer executes produces R1001. A file containing only helper functions and no statements or main has no entry point and is rejected by check and run.

aner build FILE.aner -o OUTPUT [--emit-cpp FILE] [--emit-manifest FILE] [--strict-declarations] compiles the supported development CPU subset into a standalone executable. The same frontend checks the source before lowering typed scalar code, supported fixed arrays and admitted typed CPU tasks to C++20. The build retains a JSON manifest beside the executable, with source, generated code, ABI, target and numerical policy identity. Unsupported constructs produce located diagnostics; builds never fall back to interpretation. Building requires a matching source build SDK and C++20 toolchain. Published 0.0.4 packages do not contain this compiler milestone. See native compilation for the exact boundary and executable example. aner run and aner session --stdio retain their interpreted execution paths; an interactive terminal REPL and JIT remain separate possibilities.

Data types

Use Number when one scalar variable or parameter should accept integers and floating values while retaining their concrete representation. Integer literals default to Int64, and floating literals to Float64. Choose an explicit integer width, Float32 or Float64 when storage or precision is part of the contract; packed arrays require one concrete element type.

TypeMeaningExample
NumberScalar numeric umbrella retaining the concrete integer type or Float32/Float64; not a packed array dtypevar value: Number = 42;
Int8, Int16, Int32, Int64Signed fixed width integers with checked arithmetic; Int64 is the literal defaultlet count: Int64 = 42;
UInt8, UInt16, UInt32, UInt64Unsigned fixed width integers with checked arithmeticlet pixel: UInt8 = 255;
Float32IEEE 754 binary32 number; four byte packed array storagelet sample: Float32 = 0.5;
Float64IEEE 754 binary64 numberlet weight: Float64 = 72.5;
Quantity<UnitCode>Immutable Float64 magnitude in an exact registered linear or interval unit; requires aner.unitslet length: Quantity<m> = 2.0@m;
Point<UnitCode>Immutable Float64 absolute temperature reading in an exact registered point unit; requires aner.unitslet room: Point<degC> = 20.0@degC;
BoolBoolean, without numeric truthinesslet included: Bool = true;
StringImmutable UTF-8 textlet label: String = "sample";
DateChecked immutable Gregorian calendar datelet day = Date(2026, 10, 12);
TimeImmutable wall clock position with exact nanosecondslet clock = Time(9, 30, 0);
DateTimeImmutable instant with an explicit fixed UTC offsetlet instant = DateTime(day, clock, 0);
DurationExact signed Int64 nanoseconds with checked arithmeticlet elapsed = Duration.from_seconds(2);
BytesImmutable shared unsigned byte storage with explicit encodinglet raw = Bytes.encode_utf8("text");
RangeLazy half open Int64 arithmetic progressionlet indices = Range(0, 10, 2);
RandomGeneratorMutable seed and draw cursor; aliases share state; requires aner.randomlet rng = random.generator(seed: 42);
Optional<T>Present typed payload or explicit typed absencelet missing = Optional.none<Float64>();
Result<T, E>Typed success or recoverable error outcomelet parsed = Date.try_parse("2026-10-12");
UnitNo meaningful returned value; written ()let nothing: Unit = ();
AnyA value retaining its concrete runtime type; omitted field/input annotations default to thisvar item: Any = "hello";
ListMutable ordered mixed values, with duplicates and indexed methods; no importlet items = List(1, "hello");
DictionaryMutable scalar keys mapped to mixed values, in insertion order; no importlet record = Dictionary(); record.set("name", "Aner");
SetMutable unique scalar values, in insertion order; no importlet unique = Set(1, "1", true);
Array<T>Fixed contiguous scalar dtype and initialized size; no importlet a = Array<Int64>(size: 4, fill: 0);
DynamicArray<T>Growable contiguous scalar dtype with explicit capacity; no importlet a = DynamicArray<Float64>(capacity: 4);
NDArray<T>Fixed contiguous rank 1 to 8 shape and explicit scalar dtype; no importlet a = NDArray<Float64>(shape: List(2, 3), fill: 0.0);
TensorDense rank two values; CPU Float64 by default, explicit CPU/CUDA Float64 or Float32 and MPS Float32; literals/operations require a numerical/data importlet x: Tensor = [[1.0, 2.0]];
QuantumCircuitExperimental immutable gate description; requires aner.quantum in Aner 0.0.5 runtimelet bell = quantum.circuit(qubits: 2).h(0).cx(0, 1)
QuantumBackendExperimental explicit execution target; only local CPU currently availablelet backend = quantum.cpu()
QuantumResultExperimental ideal CPU reference and finite shot resultlet result = bell.run(backend: backend, shots: 1024, seed: 42)
DatasetImmutable source metadata and selected rowslet flowers = dataset.iris();
DatasetSplitImmutable training/test viewslet parts = dataset.split(flowers, 0.2, 2026);
DatasetPartitionImmutable training/validation/test views with protected roleslet parts = flowers.partition(0.2, 0.2, 42);
DatasetFoldsImmutable seeded cross validation selectionslet folds = flowers.kfold(5, 42);
DatasetBatchesLazy deterministic mini batch schedulelet batches = flowers.batches(16, 42, true);
OptimizerKeyed mutable SGD/Adam moments; copies share statelet state = nn.optimizer("adam", 0.001);
TrainingConfigImmutable epochs, batch size, rate, seed and validation contractlet config = ml.training(5, 128, 0.001, 42);
StandardizerFixed training derived column statisticslet scaler = dataset.fit_standardizer(x_train);
KNNClassifierImmutable fitted nearest neighbor classifier; requires aner.mllet model = ml.fit_knn(x, labels, 5);
KMeansModelImmutable fitted clustering model; requires aner.mllet model = ml.fit_kmeans(x, 3, 100, 0.000001, 42);
DataSchemaImmutable external table schema; requires aner.datalet s = data.schema();
DataScanDeferred external CSV planlet q = data.scan_csv("data.csv", s, "NA");
DataReportCompleted selected row summarylet r = data.summarize(q, 1048576, 256);
DataTableCollected typed columns with validity informationlet t = data.collect(q, 1000, 1048576, 256);
NeuralNetworkImmutable sequential neural configurationlet net = nn.sequential(seed: 42);
ClassifierPipelineNeural classifier and preprocessing configurationlet plan = ml.classifier(net, standardize: true, loss: "cross_entropy");
FittedClassifierTrained immutable classifier snapshotlet fitted = plan.fit(training, epochs: 2000, rate: 0.1);
EvaluationReportDetached classifier evaluation and provenancelet report = fitted.evaluate(testing);

Declarations may omit their type annotation: let weight = 72.5;. Integer literals infer Int64, and floating point literals infer Float64; bindings keep their declared or inferred static type. Use var value: Number = 42 to permit any supported concrete numeric representation, or Number(42) to infer the numeric abstraction. Function parameters may omit their annotation to accept Any; Number parameters accept only numeric values. A return annotation may be omitted when the body determines a compatible result type; different concrete numeric return types merge to Number without converting their values. Explicit annotations remain supported and are required for value return inference cycles.

Concrete integer values promote automatically at Float64 boundaries and in mixed numeric arithmetic only when binary64 represents the integer exactly; otherwise execution reports R1003. Float64(value) explicitly permits integer to float rounding. Concrete integer to integer boundaries check the actual value for exact range, including narrowing and signedness changes. Every integer constructor, such as Int16(value) or UInt64(value), explicitly truncates a finite, in range floating value toward zero; floats and statically Number expressions never convert implicitly to an integer. Float32 inputs widen to Float64 exactly; Float32 boundaries check exact representation of integer/Float64 inputs unless an explicit Float32(value) permits rounding. Unsigned constructors reject negative floats even when truncation would give zero. Number(value) preserves the concrete numeric value. Casts check types without converting. See Number and numeric conversion for complete rules, arithmetic examples and precision limits.

Decimal integer literals have type Int64. The largest positive literal in the default Int64 context is 9223372036854775807. Positive values through 18446744073709551615 are accepted in an explicit UInt64 context such as let value: UInt64 = 18446744073709551615 or UInt64(18446744073709551615). An unannotated larger literal or one passed directly to Number is rejected. See fixed width integers for every range and promotion rule. The minimum signed value is written -9223372036854775808: the integer must be the next token after the minus (whitespace and comments may separate them). An out of range positive magnitude is not made valid by placing it inside parentheses before negation.

Floating point literals require digits before a decimal point, digits after that point if present, and digits after an exponent if present. Examples: 15.0, 1e3, 2.5e-4. A decimal point or exponent is required to distinguish them from integer literals. .5 and 1. are invalid. Out of range literals, including overflow and underflow, are rejected; nonfinite values may still result from arithmetic. Unary plus is not supported.

Decimal source literals accept a single underscore between adjacent digits: 10_000_000, 1_000.25_0, 1e1_0 and 1_0.2_5e-1_0. Group sizes are unrestricted. Separators change readability only; inferred types, exact values and range checks are unchanged. They cannot lead or trail a digit group, repeat consecutively, or touch the decimal point, exponent marker or exponent sign: 1_, 1__0, 1_.0, 1._0, 1_e2, 1e_2 and 1e+_2 are lexical errors. _name and _1 remain identifiers. This source syntax does not alter numeric parsing of CSV fields or runtime Strings.

Built in collection types

Dictionary, List, and Set are available without imports or type arguments. They are mutable reference types; a binding retains its declared or inferred type, and a let binding does not freeze the referenced object. Retrieval of a mixed value has static type Any and requires a checked cast before a type specific operation.

Each collection has its own reference: Dictionary, List, and Set. These pages define construction, element and key contracts, methods, equality, copying, errors, limits, and time/space complexity. The data structure index lists the complete reference category.

Mixed values with Any

One linked list can hold integers, strings, floats, booleans, user objects, and native values without <T>. Unannotated class fields and ordinary/method inputs mean Any; writing : Any explicitly is equivalent. For example:

aner
class Node {
    public let value
    public var next: Node?
}

fn show(value) { print(value) }
let first = Node(value: 10, next: null)
let second = Node(value: "hello", next: first)
show(second.value)
print(type_of(first.value)) // Int64
print(cast<Int64>(first.value) + 5) // 15

Any accepts every existing non Unit value type, including null. The concrete value is preserved; it is not converted to a string or float. Link annotations such as Node? still ensure that a list links only to Nodes or null. Omitting a link's annotation makes it Any too, so typed member access/unwrap would then require a checked cast.

Local/global bindings with no annotation still infer one static type: var x = 1 cannot later receive a String. Use var x: Any = 1 to opt into changing its concrete value type. An inferred result that returns an Any field/input is Any. To intentionally return unrelated concrete types from separate branches, write -> Any; unrelated concrete returns do not automatically become Any.

type(value) and type_of(value) return the same concrete runtime type name, including a concrete generic class name or null. dtype(value) reports scalar or homogeneous array/Tensor storage datatype; heterogeneous List/Dictionary/Set always report "Any", and unsupported objects or null produce R3202. Inspection does not scan elements or transfer device memory. See Type inspection. cast<Type>(value) recovers a checked static type; mismatches produce runtime diagnostic R1002, and nullable class casts accept null. Casts do not perform conversions: cast<Number> accepts any supported integer type, Float32, or Float64, but an Int64 cannot be cast to Float64; use Float64(cast<Int64>(value)) for that conversion. Unit is neither an Any payload nor a valid cast target. cast is a built in intrinsic; user defined generic functions remain unimplemented.

Any does not bypass annotated fields, parameters, results, visibility, or immutability. Arithmetic, ordering, conditionals, typed native calls, and member access require an appropriate static type, so use a checked cast when retrieving Any data. type_of does not automatically narrow the static type in a branch. Incorrect casts reset a native notebook session like other runtime failures.

print on Any prints scalar contents or null; user objects and native composite values show a type label such as <Node> or <Tensor>, rather than dumping graphs or arrays. Core collections render bounded, cycle safe contents, also when stored in Any. Any expressions at notebook top level use the same display. Equality uses scalar contents with matching concrete tags, object/collection identity, or null; different tags compare unequal, with no numeric coercion. RandomGenerator handles compare by shared identity. Equality of other native composite values with the same tag is unsupported and reports R1002.

See the mixed linked list example for append, prepend, traversal, and retrieval. Homogeneous generic lists remain available when one element type is desired.

Typed array declarations

Array<T> and DynamicArray<T> require an explicit primitive 8/16/32/64-bit signed or unsigned integer, Float32, Float64, Bool, or String element type, or a registered Quantity<UnitCode>/Point<UnitCode> specialization, in declarations, constructors and casts. Primitive arrays require no import; unit element types require aner.units. See unit arrays for exact writes, packed storage and physical arithmetic. Number is not an array dtype: storage remains homogeneous and does not change when values are written. Float64 scalar boundaries admit checked exact integer promotion; array to array arithmetic still requires its documented dtypes. Array runtime failures use R3001; an inexact automatic numeric conversion reports R1003.

The Array reference defines fixed length initialized storage. The DynamicArray reference defines variable length storage, explicit initial capacity, and growth. Each reference defines only its own construction, methods, ownership, error, and complexity contracts.

Immutable numerical snapshots

Numerical Array, DynamicArray, and NDArray values expose .snapshot() -> FrozenArray<T>. The snapshot owns an independent immutable numerical copy, preserves NDArray shape and dtype, and supports checked flat .get(index) or shaped bracket reads. Local parallel.repeat tasks share its const backing; ordinary mutable parameter graphs keep private copies. The snapshot cannot be mutated or cast into a mutable array. It supports fixed width integers and Float32/Float64, with memory quotas and copy accounting described in immutable numerical inputs. Compatible cluster processes on the same host map one native read only immutable backing, avoiding per worker numerical payload copies; private copy transport remains available when native sharing is unavailable. Workers return exact typed output batches.

With import aner.parallel, a repetition task may declare a fourth parameter out: OutputRegion<T> and return Unit. The call then requires output_shape: List(...) and returns immutable OutputResults<T> of shape [iterations, ...output_shape]. Each task writes only its own region, with checked bounds, exact numerical dtypes, complete initialization, and scoped lifetime. Completed results can be reused as immutable inputs in later local or cluster repetitions: local task heaps share their native backing, while compatible cluster processes on one host map a shared read only numerical payload. Other hosts and private fallback imports retain their own backing. The opt in overload preserves existing repetition calls. See typed output regions. These contextual type names retain existing user declarations with the same names.

Multidimensional arrays

NDArray<T> is the shaped form of typed storage, with explicit primitive 8/16/32/64-bit signed or unsigned integer, Float32, Float64, Bool or String elements without an import, or Quantity/Point elements after importing aner.units. Construct with NDArray<Float64>(shape: List(2, 3), fill: 0.0). Rank is 1 to 8; dimensions are nonnegative Int64 values and the product is bounded. get(indices: List) and set(indices: List, value: T) validate one coordinate per axis. Shape/strides are runtime metadata and indices are zero based.

Reshape preserves total element count and shares fixed storage; DynamicArray reshape makes a detached fixed copy. Transpose, permutation, flatten, copies and arithmetic results are independent. Primitive numerical add/sub/mul and Float32/Float64 div implement checked trailing axis singleton broadcasting; unit operands follow the physical arithmetic rules. Rank two matmul is a separate operation. Reductions apply to all elements; Array sorting/search remains one dimensional. Dtypes, casts, Any, generic class fields, object identity, runtime errors and Tensor import policy follow existing typed array rules. Read multidimensional methods and Big O.

Keywords, names, and strings

The reserved words are:

text
fn let var if else while for in return true false import class null self public private

Names are case sensitive. Identifiers start with an ASCII letter or underscore and continue with ASCII letters, digits, or underscores. Unicode text is allowed in strings. // begins a comment that ends at the next line break. Block comments are not supported.

Strings use double quotes and support \", \\, \n, \r, and \t escapes. Unescaped line breaks, raw ASCII control characters below U+0020 (including tabs), and unknown escapes are errors. Immutable String methods provide Unicode scalar indexing, slicing, literal search, splitting/joining, Unicode 17.0.0 full default casing/case folding, and whitespace trimming. String(value) explicitly converts any supported integer type, Float32, Float64, Number, Bool, String, Quantity or Point; unit bearing values retain literal unit notation; + concatenates two Strings. Text is never implicitly normalized, and indices do not represent grapheme clusters. Interpolation and raw strings remain deferred. See the separate String reference for method contracts, limits, and time/space complexity.

Built in type names include Number, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float32, Float64, Bool, String, Unit, Any, Date, Time, DateTime, Duration, Bytes, Range, Optional<T>, Result<T, E>, List, Dictionary, Set, Array<T>, DynamicArray<T>, NDArray<T>, FrozenArray<T>, Quantity<UnitCode>, Point<UnitCode>, Tensor and the native module types listed above. Native module type names, including DatasetPartition, DatasetFolds, DatasetBatches, Optimizer, TrainingConfig, SimulationResults, SemanticTensor, EvidenceTensor, ContextExport, AdaptiveFrame, FeatureLedger, DBConnection, DBResult, SecretRef, RandomGenerator and API/LLM handles, cannot be redeclared. print, type, type_of, dtype, cast, the Number, all eight integer, Float32/Float64 and String conversions, integer_div, and the built in constructors are also reserved. The namespaces nn, viz, dev, dataset, tensor, metrics, ml, data, parallel, nlp, llm, secrets, api, db, postgres, mysql, mssql, mongodb, science, math, random and units cannot be redeclared. The scalar type roots Quantity and Point are also reserved. Vector, Matrix, dot, transpose, sum, mean, len, rows, and cols are reserved as unqualified names for later numerical work. Some operations are available now as qualified functions such as nn.matmul, nn.transpose, and nn.mean. Future data vocabulary such as table, join, and gpu is not reserved now. Domain operations should become ordinary typed APIs unless their semantics require a language construct.

Bindings, scopes, and functions

Braces delimit blocks; indentation does not define scope. Imports, declarations, assignments, returns, and expression statements can end with a semicolon, a line break after a completed expression, the end of the source, or a closing brace. Multiple simple statements on the same line require semicolons.

Expressions continue across line breaks when an operator or call delimiter continues the expression. For example, 1 + followed by 2 is one expression; a leading + 2 on the following line can also continue 1. Use a semicolon to make that boundary explicit. Calls and tensor literals may span lines. A return immediately followed by a line break is a bare Unit return; put a returned expression on the same line as return, or begin its parentheses there.

A direct script needs no function wrapper:

aner
var a = 10
let b = 20
c = 30
a = a + 5
print(a + b + c)

The following complete program form remains valid:

text
fn square(x: Float64) -> Float64 {
    return x * x;
}

fn main() -> Unit {
    let threshold = 18.5;
    var total: Int64 = 0;
    var i: Int64 = 0;
    while i < 3 {
        total = total + i;
        i = i + 1;
    }
    if total == 3 {
        print(square(threshold));
    } else {
        print("Unexpected total");
    }
}

let creates an immutable binding; var permits reassignment of the same declared or inferred type. An explicit Number binding can hold any supported integer type, Float32, or Float64; an explicit Any binding can hold different supported concrete value types. Both require an initializer. A bare assignment such as a = 10 creates a mutable binding in the current scope if no binding of that name is visible. Otherwise it assigns to the visible binding, requiring a compatible type and mutability, with checked exact integer conversions and integer to Float64 promotion where needed. This rule applies both to direct statements and function bodies. Parameters are immutable. Blocks have lexical scope: duplicate declarations in one scope are rejected, and an explicit declaration in an inner block can shadow an outer binding. Numeric compound updates +=, -=, *= and /= require an existing mutable binding or an indexed numeric array cell; they never declare a fresh binding. Raw numeric updates use the promotion rules below, and their result must fit the binding or array cell type. Since / returns Float64, an integer or Float32 binding or cell cannot use /=; use integer_div with ordinary assignment for integer division. Quantity/Point var bindings admit a unit operation only when its result has exactly the binding's declared unit and kind: length += 50.0@cm or temperature += 5.0@delta_K may be valid, while Point -= Point changes kind and is rejected. Quantity scaling requires Float64. String, Bool, object field and SemanticTensor/EvidenceTensor compound updates are unsupported. A let array binding still permits element mutation because its storage has the existing mutable array contract.

Expression statements must have type Unit in .aner scripts and ordinary function/block bodies. At the outermost level of a persistent session cell, scalar expressions such as a or 1 + 2 are also allowed and display their result. Composite values still require explicit accessors or summary functions; no automatic tensor/table expansion is performed.

Default parameters and contextual outcome construction

User functions and class methods can declare trailing scalar literal defaults:

aner
fn scale(value: Float64, factor: Float64 = 2.0) -> Float64 {
    return value * factor
}
print(scale(3.0))
print(scale(factor: 4.0, value: 3.0))

The output is 6.0, then 12.0. Defaults are typechecked when the signature is checked and must be integer, Float64, Bool or String literals, compatible null, a negated numeric literal, or a signed unit literal. Float32(numeric literal), including a signed numeric literal, is also supported for explicit rounded defaults, such as value: Float32 = Float32(0.1). Unit literal defaults require aner.units and the exact declared unit type, for example step: Quantity<m> = 1.0@m; a centimeter default does not implicitly convert into a meter parameter. Names, general calls, arithmetic expressions, collections and wrapper constructors are not default expressions. Required parameters must precede all defaulted parameters. Class fields still require explicit constructor values; field defaults are not implemented.

A caller can omit trailing positional values or omit a named optional parameter. Explicit arguments evaluate once in source order; omitted literal defaults are supplied afterward in formal parameter order. Exact type checks, unknown/duplicate-label errors and required argument checks remain in force. Defaults use the same checked numeric boundary rules as supplied arguments and do not introduce shared mutable default objects.

An expected Optional<T> or Result<T, E> type supplies omitted factory arguments in an annotated binding, assignment, explicitly declared return, typed user function argument, declared class constructor field or wrapper unwrap_or fallback. Expected types also flow into nested factories:

aner
let missing: Optional<Int64> = Optional.none()
let nested: Result<Optional<Int64>, String> = Result.ok(Optional.none())
fn read(valid: Bool) -> Result<Int64, String> {
    if valid { return Result.ok(7) }
    return Result.err("invalid reading")
}
print(missing.is_none())
print(nested.unwrap().is_none())
print(read(true).unwrap())

The output is true, true, then 7. Without an expected wrapper type, Result.ok/Result.err still require both type arguments and Optional.none requires its payload type. Optional.some(value) can infer its payload from a concrete value. Expected numeric payloads follow the Number and checked exact Float64 promotion rules. Constructor inference does not add general user generic-function/type inference. See Optional and Result.

Functions are resolved before their bodies, so forward calls and recursion work. Calls accept positional and named arguments with compatible types, including Number inputs and checked exact integer conversions and integer to Float64 promotion; positional arguments must precede named arguments. Each argument expression evaluates once in source order, even when named arguments reorder parameters. Unknown, duplicate, or missing required arguments are errors; omitted declared defaults supply optional user function arguments. User function labels come from their declared parameter names; built in labels are part of the API contract. Calls may have a trailing comma; function parameter declarations do not. Functions are not general values and cannot be nested inside other functions. parallel.repeat has one checked call site exception: a directly named top level task function may be supplied to its task argument, as described below. A local variable may shadow a user function name, but calling that variable is an error. A non Unit function must return a matching value on every path under a conservative check: even an apparently infinite loop does not establish a guaranteed return. A Unit function may fall through, use return;, or return ().

A result annotation is optional: fn square(x: Float64) { return x * x } infers Float64, while fn announce() { print("Aner") } infers Unit. Returned values must determine a compatible static type, and non Unit results still require a return on every path. Int64 and Float64 return branches infer Number while preserving each concrete value. Unannotated parameters explicitly default to Any, while annotated inputs retain their checks. Value return inference cycles need an explicit annotation such as -> Int64; retaining annotations is also useful for public API contracts. The expression return at a line break is still a Unit return, not a value from the next line.

Return inference merges differing concrete numeric results, including Float32/Float64 and integer widths, to Number; otherwise it uses exact types except that references to the same class, that class's nullable type, and null can merge to the nullable class type. Mixed incompatible results, including Unit mixed with a value, report E1002; missing non Unit return paths report E1004. Bodies with no expression return, or only bare return/literal return (), establish Unit before checking their calls, so recursive Unit methods can omit annotations. A cycle of value return dependencies needs an explicit result annotation to break it (E1009). The inference dependency chain is bounded to 128 calls (E1007).

An inferred body is checked when its result is first needed. Any globals used by that body must already be known at that point. An explicit result annotation allows body checking to be deferred, but does not make a runtime read before a global's initialization valid. Generic methods are inferred for each concrete specialization.

if and while conditions require Bool. else is optional; else if is supported. break, continue, general user defined modules, value structs, and inheritance are outside the current core. User defined reference classes and their methods are supported. The built in modules listed at the top can currently be imported. print is permitted in ordinary functions; no purity or checked effect guarantee is claimed.

for index in Range(start: 0, stop: 4, step: 1) { print(index) } lazily binds immutable Int64 values for the half open progression. It prints 0 through 3. The Range expression evaluates once; bounds and step retain the Range contract. Range iteration and DatasetBatches iteration are both implemented; List and array iteration require their own access patterns.

Lazy dataset iteration

for name in schedule { ... } iterates a DatasetBatches schedule in its fixed order. Each iteration binds one immutable Dataset view, including a final partial batch. The binding is local to the body, and return exits the surrounding function. Schedule construction stores row order; feature and target tensors materialize only when requested for a batch. Iteration consumes the normal execution budget.

aner
import aner.dataset

let training = dataset.iris().partition(validation: 0.2, test: 0.2, seed: 42).train()
for batch in training.batches(size: 16, seed: 42, shuffle: true) {
    print(batch.rows())
}

This built in iteration currently accepts DatasetBatches. General collection and user defined iterators are not implemented. See dataset partitions for roles, group safeguards and complexity.

Checked repetition task names

parallel.repeat accepts the directly named function trial in this complete program:

aner
import aner.parallel
import aner.random

fn trial(parameters: List, iteration: Int64, seed: Int64) -> Float64 {
    let center = cast<Float64>(parameters.get(0))
    return center + random.normal(mean: 0.0, stddev: 1.0, seed: seed)
}

let results = parallel.repeat(iterations: 4, task: trial,
    parameters: List(10.0), seed: 42)
print(results.rows()) // 4

The checker resolves that name before execution and requires (List, Int64, Int64) inputs with a numeric scalar or numeric List result. Each repetition starts from a private copy of the same initial parameters and receives a deterministic iteration seed. This call site contract does not create a first class function value: assigning trial to a variable, supplying a String/closure/alias, or invoking a stored function remains unsupported. ParallelTask is the internal signature argument contract, rather than a general source type to instantiate.

The task and its checked helper call graph cannot capture globals or perform I/O, print, clock reads, network/credential operations, nested parallel work, neural/Tensor/Dataset/model operations, or worker side Dev/Viz captures. Local supported value/collection/class operations and explicitly seeded, stateless aner.random sampling are admitted. Entropy acquisition with random.seed() and mutable RandomGenerator construction, calls and parameter transport are rejected in isolated tasks; acquire a replay seed before launching them and use addressed draws. Static violations use E2803; runtime task/result/storage failures use R2803. Ordinary functions retain their usual effects. See the repetition API for named defaults, isolation, ordered results, statistics, CSV effects and runnable stochastic growth examples.

Instance methods and concise model APIs

Built in values expose typed instance calls and chains. For example:

aner
import aner.dataset
import aner.nn
import aner.ml

let split = dataset.iris().split(test: 0.2, seed: 2026)
let network = nn.sequential(seed: 42)
    .dense(inputs: 4, outputs: 8)
    .tanh()
    .dense(inputs: 8, outputs: 3)
let pipeline = ml.classifier(network, standardize: true, loss: "cross_entropy")
let fitted = pipeline.fit(split.train(), epochs: 2000, rate: 0.1)
print(fitted.evaluate(split.test()).summary())

A receiver is evaluated once, before that call's explicit arguments. Method names are resolved using its static type. A leading . may continue an expression on the following line; use a semicolon when a statement must end. These methods call native Aner implementations and preserve ordinary checker diagnostics and argument evaluation order. They are not dynamic attribute lookup or source translation.

NeuralNetwork holds an immutable configuration; layer methods return another configuration. ClassifierPipeline.fit creates a new fitted value. An ordinary plan learns preprocessing only from its training input; a compatible pipeline.warm_start(model) reuses the immutable prior model's parameters and fitted scaler. FittedClassifier.evaluate reuses those fixed statistics and returns an EvaluationReport. The same fitted value can evaluate multiple compatible dataset views. See Aner Neural for supported layers, numerical semantics, provenance, and resource limits.

ml.classifier(network, standardize: true, loss: "mse") selects mean squared error between row wise softmax probabilities and one hot targets, averaged over all rows × classes. The optional loss string accepts exactly "cross_entropy" and "mse"; omission preserves cross entropy from raw logits, averaged over rows. The selection applies to initial loss, full batch SGD or Adam training, final loss, and evaluation. Keep the network's last Dense stage as raw logits: MSE applies softmax internally. The fit(training, epochs: ..., rate: ...) interface is unchanged. The optional optimizer argument accepts "sgd" or "adam". Either may be supplied without an explicit loss; unsupported optimizer names raise R2701. Custom Dense initialization, pre fit summaries, detached fitted weights/biases, fitted.save(path), and ml.load_classifier(path) are implemented. These APIs require a compatible native runtime and editor integration with their signatures and snippets. See model state and complexity.

The built in object style interface is separate from the user defined reference classes below. Inheritance, value structs, traits/interfaces, tuple destructuring, and general collection literals remain unimplemented. Tensor aliases retain their documented shared gradient behavior; a let binding does not promise deep immutability of every native value.

User defined reference classes

aner
class Node {
    let value: Int64
    var next: Node?

    fn get() {
        return value
    }
}

let node = Node(value: 10, next: null)
print(node.get())

Classes are nominal reference types. Field annotations may be omitted to store Any; annotated fields retain their static checks. Fields are private by default and methods public by default; private and public explicitly override either default. Only a method of the owning concrete class may read/write its private fields or call its private methods. Synthesized constructors are public and require all declared fields, including private ones; no field defaults or custom constructors are provided. let fields cannot be reassigned; var fields can. An immutable binding to an object does not freeze that object's mutable fields. Copies alias the same object, and compatible object references compare by identity. Class methods receive an implicit typed receiver; writing self in the parameter list is optional. Their input annotations are optional and default to Any, while the return type can be inferred. Inside methods, unqualified fields and method calls resolve against the current object; locals and parameters may shadow fields, with self.field available to disambiguate. Names are scoped to the class; class declarations may refer to one another.

Node? permits Node or null. Checking a reference against null allows direct field or method access on paths where it is known to be nonnull. This includes if/else, early return guards, while traversal, and short circuit &&/|| conditions:

aner
if head == null { return }
var cursor = head
while cursor.next != null {
    cursor = cursor.next
}

The declared type remains unchanged: a narrowed Node? variable or field can still receive null. Reassignment forgets its proof and proofs about its fields. Field writes conservatively forget all field proofs because another reference may alias the same object. User function/method calls forget field and global proofs; local reference values remain valid. Store a checked reference in a local binding before such a call, or check again afterward. Loop checking accounts for changes across iterations. Proofs do not carry between functions or notebook cells.

.unwrap() remains an explicit runtime checked extraction when no null check proves safety. Nullable syntax applies to user defined class references, not general scalar missingness. Unwrapping null or exceeding the object heap's limits produces R2801.

Inside a method, bare value lookup prefers locals/parameters, then fields of the current object, then global bindings. For ordinary unqualified calls, a local binding or field of that name blocks the call; otherwise the current object's methods precede global functions. print, Number, the eight integer conversions, Float32, Float64, integer_div, String, type, type_of, dtype, cast, and the List/Dictionary/Set/Array/DynamicArray/NDArray constructors retain their built in unqualified call meaning; a same named method must be selected explicitly, such as self.print(). Explicit member calls retain the usual static type and visibility checks.

The managed heap allows cycles and performs iterative tracing from live globals after each successful session cell. It does not collect during a cell. Programs/sessions permit at most 256 class declarations and concrete specializations combined, with 64 fields per class and 1,024 functions/method templates/specialized methods combined. Classes and collections share 16,384 outstanding heap objects and 262,144 value slots (class fields, List elements, Set members, and two per Dictionary pair). Directly stored collection Strings have a separate 16 MiB ceiling. The existing 128 call runtime depth limit still applies; see collection memory accounting. Typed arrays share the object count but have a separate 64 MiB buffer/String budget and 10,000,000 element capacity limit; their typed elements do not consume tagged collection slots. These are not process memory limits. Scripts release their heap at termination. Classes persist in sessions and cannot be redefined without a restart; static errors roll back new definitions, while runtime errors clear all session state. See the complete OOP tutorial for examples and ownership details.

Generic classes

aner
class Node<T> {
    let value: T
    var next: Node<T>?
    fn get() { return value }
}
let integer = Node<Int64>(value: 10, next: null)
let text = Node<String>(value: "sample", next: null)
print(integer.get())
print(text.get())

This example defines a separate generic Node; it cannot coexist with a nongeneric class of the same name. Constructor type arguments are explicit, with no inference from values. Type arguments may use supported scalar/native types, user defined classes, nullable class references, and nested generic classes. Unit is not an accepted type argument; null is a value, not a type. Each concrete specialization has its own nominal type. Fields are private unless declared public; the constructor still accepts all field values.

Aner substitutes class type parameters through fields, method parameters/results, and constructor references. It checks every method body when a class is specialized, including methods the program never calls. Generic functions, independently generic methods, traits, and type constraints are not implemented. Int32 remains unavailable; the supported integer type is Int64.

Generic expansion is bounded by 262,144 cloned class/function/field/parameter/type/expression/statement nodes cumulatively, a type nesting depth of 128, at most 32 parameters/arguments in a type list, and 16 KiB per canonical concrete type name. Classes and methods also count toward the shared declaration limits above. Failed session checks roll back new specializations and their budget use. These safeguards are not a process memory quota. See generic classes and examples.

Built in argument labels

Named argument labels form part of each checked function or method signature. A label selects a parameter destination without changing the source evaluation order of expressions. An unknown label, duplicate destination, missing required argument, or incompatible parameter type is a static error.

aner
fn difference(left: Int64, right: Int64) { return left - right }
print(difference(right: 2, left: 10))

The output is 8. The call supplies right before left; binding uses the labels, while argument expressions are evaluated in their written order. A method receiver precedes its explicit arguments.

Optional parameters are specific to the selected built in overload. The compiler inserts only the documented defaults. Variadic collection constructors accept positional values and do not accept named arguments. User defined functions and methods support the trailing literal defaults described above; built in optional arguments retain their documented overload defaults.

Parameter labels, types, results, errors, and complexity are specified by each API reference. Data structure APIs are indexed in the data structure reference. Module APIs are documented in datasets, external data, classical machine learning, neural networks, development observations, and training reports. VS Code signature help displays these checked contracts during editing.

Persistent notebook sessions

Each notebook session retains native global values, imported included modules, and checked function/class definitions. Cells are parsed and checked as a whole against the existing typed state, then execute once in the order requested. Types do not change between cells. Imports belong before functions or statements within each cell and remain available afterward. Session cells reject main; use direct statements or change the notebook to independent program mode with Aner: Use Independent Programs. Save the notebook to retain that mode; Aner: Use Shared Variables selects persistent execution again. A mode change cancels old work and clears state without running or replaying cells.

An explicit top level let or var declaration may reinitialize a name from an earlier cell when its type and mutability match. Duplicate declarations inside one cell are errors. Bare assignment still cannot update let. An unchanged top level function declaration from an earlier cell may be repeated only when its complete source text matches exactly, including internal spacing and comments. The existing checked definition is retained, while other statements in the cell execute normally. Changed function declarations require a restart; class redefinition remains unsupported. Restart an existing session once after installing the updated runtime. A runtime diagnostic in an earlier cell's function retains that definition's source.

Parse/check failure preserves the previous state and executes nothing. Execution failure clears the entire session. Restart, Stop, timeout, notebook closure, and extension reload also clear its state; no earlier cells are replayed. Output and external effects already produced are not rolled back. Saved notebook outputs are historical document content, not serialized variables or model checkpoints. See session behavior and limits.

Operators and evaluation

OperatorsAccepted operands and result
+, -, *Numeric operands: concrete integer pairs use a lossless common integer type with checked overflow; Float64 selects Float64, while a Float32 operand without Float64 selects Float32, after checked exact integer promotion. A Number operand gives a static Number result.
/Numeric operands; Float64 result after checked exact integer promotion, so 5 / 2 is 2.5
+Two Strings; new concatenated String
%Integer values; remainder in the lossless common integer type, with the dividend's sign. Statically Number operands must retain integers.
unary -One Number, any fixed width integer, Float32, Float64 or linear Quantity; Point negation is rejected
+, -, *, /Registered compatible Quantity/Point operations; checked unit result according to scalar unit arithmetic
+, -Two SemanticTensor or two EvidenceTensor; native shape, coordinate, unit and uncertainty checks apply
==, !=Numeric fixed width integer/Float32/Float64/Number values, matching other raw scalar values, compatible same kind Quantity/Point values, Date/Time/DateTime/Duration/Bytes/Range values, or compatible managed references; Bool result. Reference classes, collections, arrays and outcome wrappers compare identity. Any uses its documented runtime equality rules.
<, <=, >, >=Numeric fixed width integer/Float32/Float64/Number values, matching Date/Time/DateTime/Duration/Bytes values, or same kind compatible Quantity/Point values; Bool result
&&, `
value[index], value[row, column, ...]Checked Array/DynamicArray/NDArray scalar access; indices are Int64
postfix ?One Result success payload, or early error return from an explicitly Result returning function
+=, -=, *=, /=Statement updates of an existing numeric var or numeric indexed array cell; numeric results must fit the destination type, with checked exact Float64 promotion. Integer and Float32 destinations reject /=. Quantity/Point binding updates require an unchanged exact result type.

Precedence from lowest to highest: ||; &&; equality; numeric ordering; + -; * / %; unary - !; postfix calls, member access, brackets and Result propagation. Compound assignments are statements rather than value producing expressions. Arithmetic operators group left to right. Parentheses explicitly group expressions. Comparison chains, including mixed comparisons such as a < b == true, require explicit parentheses. Write (a < b) == true, or use a < b && b < c for a range check.

Operands and call arguments evaluate left to right. && and || short circuit; their unneeded right operand is not evaluated, but it is still type checked. The entire program, including unused functions and unreachable branches, must be well typed before any output or other execution occurs.

Bracket access is implemented for Array, DynamicArray and NDArray only. The opening [ must appear on the same physical line as the receiver's final token; selector contents may span lines. A [ beginning a new statement is not silently attached to a previous call or value. Array/DynamicArray take one coordinate; NDArray takes one through eight coordinates with the exact runtime rank. Negative/out-of-range coordinates fail. String, Dictionary, List, Tensor and SemanticTensor retain their explicit accessor APIs; slice/advanced-index syntax is not introduced. See Array and NDArray.

An indexed assignment evaluates its receiver and coordinates once, validates the address, then evaluates the right side and writes. A compound update additionally captures the prior value before right side effects. Thus an effectful right side cannot change which prior value is used in the arithmetic. Right side effects are not rolled back if the final write or computation fails. Numeric arrays retain finite value validation; raw scalar Float64 compound updates use ordinary Float64 arithmetic and can produce nonfinite results. Scalar Quantity/Point operations retain finite/range checks and report located R3701 unit/numeric diagnostics.

result? requires an explicitly annotated enclosing Result<T, E> function and exactly the operand's error type E. It evaluates once and unwraps one success layer. An error skips the rest of that function and returns a new enclosing error Result containing the same error payload; its success type may differ. Put ? on the same line as the operand's final token, including a multiline call's closing parenthesis. Top level propagation, Optional propagation, inferred Result return boundaries and automatic native error capture are unsupported. For nested Results, use a binding or (nested?)? rather than adjacent ??. Nullable class type syntax such as Node? keeps its existing meaning. See Result propagation.

All fixed width integer addition/subtraction/multiplication and negation check overflow. Integer arithmetic uses a lossless common type: same sign operands select the wider width; mixed signed/unsigned operands require a signed width covering both complete ranges. Any signed type mixed with UInt64 requires explicit conversion; comparisons remain supported. integer_div(a, b) accepts integer values and returns their common integer type, truncated toward zero; % uses the same type and the dividend's sign. Zero divisors and minimum integer division/remainder by negative one are runtime errors. For example, -7 / 3 is Float64, integer_div(-7, 3) is -2, and -7 % 3 is -1.

Typed numeric comparisons compare integer and floating point values without first rounding the integer to Float64. For example, 9007199254740993 > 9007199254740992.0 is true. Any equality and collection key/element equality retain their concrete tag rules, so an Int64 1 and Float64 1.0 remain distinct there.

Scalar Float32/Float64 arithmetic follows IEEE 754: overflow and division by zero may produce infinities or NaNs. A NaN is a numeric value category, not a missing observation. Fast math transformations are disabled. Cross hardware bitwise equality is not promised.

Output and runtime limits

print(value) writes a newline and returns Unit. It accepts all fixed width integers, Float32, Float64, Number, Bool, String, Quantity/Point, Date/Time/DateTime/Duration/Bytes/Range, Optional/Result, List/Dictionary/Set, Array/DynamicArray/NDArray, contextual/scientific values (AdaptiveFrame, FramePartition, FeatureLedger, ContextBatch, ContextLinearModel, ContextPrediction, SemanticTensor, EvidenceTensor and ContextExport), DBConnection/DBResult, SecretRef, LLMClient/LLMMessage/LLMResponse, APIApp, or Any. Statically typed Unit, null, user objects, Tensor and other model/dataset handles are rejected; Any retains its existing concrete value display. Scalar Quantity/Point values display roundtrippable unit literals such as 2.0@m or 3.0@"m/s". Admitted native composites use their type label or bounded inspection display; use module accessors and tensor.item or tensor.value to inspect numerical contents. Booleans print as true or false. Strings print their contents without quotation marks. Finite floating point output includes a decimal point or exponent. For example, a value otherwise formatted as 15 prints as 15.0. Nonfinite values print as inf, -inf, or nan. This initial human readable format is not a dataset serialization format.

The CLI limits source files to 2 MiB. Invalid UTF-8 is rejected. The frontend has a combined nesting budget of 128 across statement, expression, and unary parser entries, plus a separate expression tree depth limit of 128. These internal counters do not promise 128 nested parentheses; excessive depth produces an E0001 diagnostic. The interpreter permits at most 128 active function calls and 256 combined active statement/expression evaluations. These runtime nesting limits produce R0002 diagnostics and remain in force when the step budget is raised. Execution defaults to a budget of 1,000,000 steps. --max-steps N changes the budget for run; use a positive integer. Steps count interpreter work, not seconds, and their exact number is not a stable language contract. These safeguards are not a memory quota or security sandbox.

Native sessions additionally bound each source cell to 1 MiB, persistent global bindings to 4,096, functions/methods to 1,024, classes to 256, and retained function/class source to 8 MiB. The editor imposes a 120 second per cell timeout; its native text response payload is limited to 1 MiB, reserving 16 KiB for diagnostics and allowing 1008 KiB of stdout. The opt in development protocol adds a separate observation payload capped at 512 KiB, with explicit omission/truncation markers. These are resource bounds, not a total retained memory budget. See the notebook limits.

See hello, scalars, control flow, and notebook variables for runnable examples.

Native random sampling

import aner.random enables versioned Philox4x32 to 10 sampling: Float64 uniform values in [0,1), inclusive Int64 integers, Bernoulli outcomes, weighted choices and normal values with explicit mean/standard deviation. let rng = random.generator(seed: 42) seeds a generator once; calls such as rng.uniform() advance its owned cursor until rng.reseed(seed: 42) explicitly resets it. random.generator() acquires an OS generated seed, available through rng.seed(). The stateless distribution calls require a seed and accept a draw identity (default zero); repeated identities replay. Use those addressed calls for stable sequential/parallel comparisons. random.engine() identifies the new protocol. Invalid sampling arguments use source located R3901. See the random API for seed ownership, relative weights, numerical limits and compatibility with existing module streams.

Aner Neural module and tensors

Write import aner.nn at the start of a file or cell, before all functions and executable statements. This exposes Tensor values and the nn namespace; successful session imports remain available in later cells. Unknown modules, duplicate imports within one source, and imports nested in blocks or following functions/statements are rejected. Other supported imports may appear alongside it, in any order. These are included modules; general package loading remains future work.

text
import aner.nn;
fn main() -> Unit {
    let x: Tensor = [[1.0, 2.0], [3.0, 4.0]];
    let y = nn.matmul(x, nn.transpose(x));
    print(nn.value(y, 0, 0)); // 5.0
}

Literals must have one or more nonempty rows of equal length. Each entry is an expression of type Float64, evaluated in row order from left to right. Integer entries require explicit conversion. Flat array literals, trailing commas, Tensor bracket indexing and nested tensor elements are unsupported. Tensor is rank two and construction defaults to CPU Float64; explicit dtype/device methods have their documented support, while generic dtype/rank/device syntax is not implemented.

Tensor operations use functions, not scalar operators. Shapes are checked at runtime; check checks argument types and arity but does not execute kernels or infer matrix dimensions. nn.add_bias explicitly broadcasts a single bias row; other elementwise operations require exact shapes. Nonfinite tensor inputs, outputs, and gradient contributions are rejected, unlike scalar Float64 arithmetic. Tensor literals and neural kernels use R2001; the additional modules translate their own API failures as specified below. Memory/graph/operation limits and the full differentiation contract are in Aner Neural.

Ordinary Tensor assignments share immutable numeric storage. Differentiation gradient state is shared by aliases and is updated by nn.backward; Tensor is not a pure value with no hidden state. Optimizer calls return new parameter tensors; reassignment must use var. General effects and concurrency guarantees are not implemented.

The interpreter step budget counts tensor dispatch, not each kernel iteration; neural operations have separate fixed resource limits. Neither policy is a process wide memory quota or security sandbox.

Scientific plotting module

import aner.plot exposes immutable Chart and ChartTheme values. Constructors accept checked numeric Lists, packed arrays or Tensor vectors; general charting adds no new grammar. For example, plot.line(x: List(1, 2), y: List(3, 4)).title("Study").theme(plot.theme("auto")).show() emits a native SVG chart. Modifiers return new values and do not mutate earlier charts. plot.world and plot.usa use the optional offline world and usa packs of Natural Earth boundaries. plot.map(region: String, keys: List, values: Any) joins the installed Chile, Argentina, Europe, Mexico, Canada or state/DC county/place catalogues by stable String codes; plot.boundaries(region: String) exposes their GeoJSON text. plot.choropleth accepts explicit GeoJSON joins. The map catalogue documents administrative levels, key systems, source vintages and no data behavior; city places, counties and metropolitan areas are distinct geographies.

Chart expressions display at their evaluation position in notebook cells. .show() also works in functions and loops; declarations only store the value. .save(path) creates a new SVG file. Presentation, finite data validation, statistical definitions, palettes, company themes, map provenance and resource limits are documented in Aner Plot. Plotting errors use R4001. The library runs independently of development inspection and neural capture.

Visual capture module

import aner.viz; exposes viz.capture(step: Int64, loss: Tensor) -> Unit; use it alongside aner.nn. When aner FILE --debug-viz NEW_DIRECTORY, aner FILE --dev NEW_DIRECTORY, or notebook Development mode is enabled, the call records a copy of the graph reachable from a scalar loss, including available gradients. It does not execute backward or update parameters. Without recording, capture is an operation with no effect after ordinary argument evaluation; full type checking still applies.

Use a strictly increasing nonnegative step counter. Shapes, counter range, capture limits, optional raw values, and report files are specified in Aner Visual Debugger. Capture failures use source diagnostic R2101; output directory or report writing failures use CLI diagnostic E9004. Ordinary program output remains on stdout, and debug report status goes to stderr. Legacy --debug-viz reports are written after success; --dev also saves partial observations for source located runtime failure.

Development observation module and runtime modes

Programs execute in production by default. --prod makes that choice explicit; --dev NEW_DIRECTORY enables bounded observations and writes inspection.html, inspection.json, and neural report files. The output path must be new. --dev and --prod cannot be combined. The -dev suffix of the release version is unrelated to the runtime recording mode.

import aner.dev enables dev.enabled() -> Bool and dev.capture(label: String, value: Any) -> Unit. A capture stores a bounded, read only description at that execution step. Development also observes assignments, object fields, and collection mutations. Descriptions preserve concrete type tags, exact integer decimal text, and stable heap reference identities; cycles and omitted values are labeled. Recording does not call user getters or retain a live heap/autograd graph.

Production skips automatic inspection and report generation. Capture arguments still evaluate normally; guard costly diagnostic expressions with if dev.enabled() { ... }. The same numerical kernels, seeds, type/shape checks, and resource limits apply in both modes. Runtime mode does not compile the program or provide pause/step debugging.

VS Code .anernb documents use a separate metadata.aner.runtime_mode setting; absent metadata defaults to production. The optional Jupyter adapter supports %aner dev, %aner prod, and other kernel controls in separate cells; those controls are not .aner syntax. Both notebook adapters consume the versioned native observation protocol after a cell completes. See development and production, notebooks, and the Jupyter kernel.

Proposed additional numerical syntax: not implemented

Vector<Float64>, Matrix<Float64> and flat array literals remain later design/implementation milestones. Scalar unit literals and unit bearing Array/DynamicArray/NDArray elements are implemented through aner.units. Scalar bracket get/set is implemented for Array, DynamicArray and NDArray; slices, String/Dictionary brackets and general tensor indexing syntax remain outside this addition. Rank two Tensor literals and native matrix multiplication are available through aner.nn. The linear algebra example is a proposal and currently fails to check.

Future vector/matrix aliases or additional operators must preserve the existing distinction between mutable Array/NDArray buffers and immutable Tensor numerical storage. NDArray already has runtime ranks 1 to 8, native numerical methods and documented trailing axis singleton broadcasting; this is not a proposal. Named scientific axes require their separate coordinate/alignment rules. General array arithmetic operators, tensor bracket selectors and infix matrix product @ notation need an explicit grammar and compatibility decision; use existing checked methods such as .matmul() or nn.matmul today.

The proposed example's mathematical results are a dot product of 32.0 and a matrix product of [[19.0, 22.0], [43.0, 50.0]]. These are expected results, not an execution report.

Proposed additional data features: not implemented

Typed tables and datasets need nullable fields, dates/timestamps, categorical values, exact decimals where required and schema conversion. CSV schemas already support explicit registered physical unit columns and ingestion normalization, alongside declared primitive types and missing tokens. Zero, empty strings, NaN, and missing values must remain distinct. Float64? and missing are candidates, not active syntax. Patient identifiers should remain text when leading zeros and exact formatting matter.

Large data operations need explicit schemas, predictable join cardinality, batch processing, inspectable query plans, and bounded previews. Dense matrices alone do not address this problem. The initial external CSV module below adds explicit typed columns and missing tokens. Clinical meaning, patient/time partitions, inferred or heterogeneous unit schemas and richer missingness reasons still require separate contracts. Each feature should gain valid/invalid examples and a precise contract before implementation.

Built in dataset values

import aner.dataset; enables the offline teaching catalogue and immutable Dataset, DatasetSplit, and Standardizer values. It may appear in any order with the other built in imports, once per module in each source, before functions and executable statements. Dataset APIs expose Tensor independently; nn.* operations still require an explicit neural import. Composite dataset/scaler values have no direct equality or print operation. Runtime dataset errors use R2201 with source locations. See the dataset reference for the complete implemented API and current numeric classification scope.

Shared tensor, metrics, and fitted ML values

aner.tensor, aner.metrics, and aner.ml are included modules imported once per source before functions and executable statements. Like aner.nn, aner.dataset, and aner.data, each exposes the Tensor type and rank two literals. Qualified calls require their own module import: importing aner.ml does not enable tensor.*, nn.*, or metrics.* calls. aner.viz alone does not expose Tensor. All module namespaces and type names are reserved regardless of imports.

aner.tensor provides zeros, random, rows, cols, value, item, and row wise argmax. It currently uses the same native storage implementation as Aner Neural, through a public facade; it is not a second tensor type or a completed backend extraction.

aner.ml exposes KNNClassifier and KMeansModel. Aner code creates these only through their respective fit functions. They may be function parameters, return values, or inferred bindings; copies share immutable fitted state detached from autograd. ml.predict(model, features) selects a built in signature using the model's static type. This does not introduce user defined overloads or a universal model class. K means does not support ml.predict_proba; an unsupported signature fails before execution. Models cannot be printed or compared directly.

KMeans exact accumulation and optional local CPU Float64 execution/max_workspace_bytes controls require the matching development runtime; published Aner 0.0.5 retains its legacy serial algorithm. All five fitting controls remain required, shorter calls remain serial, and updated serial/parallel calls agree bitwise in the same binary/floating-point environment. These native library kernels do not extend the bounded Tensor/model surface of aner build. See the KMeans guide for numerical scope, the charged 64 MiB default workspace cap and the complete local example.

metrics.accuracy(predicted_ids, true_ids) takes matching N × 1 label tensors. Neural code first obtains IDs with nn.argmax(scores) or tensor.argmax(scores). The existing nn.accuracy(scores, true_ids) retains its score matrix interface. metrics.mean_squared_error returns a detached Float64 evaluation value; differentiable neural loss remains nn.mse. Confusion matrices and adjusted Rand index are also available.

ML API failures use R2301, metrics use R2401, and neutral tensor calls use R2501, with source locations. Errors in an argument expression retain that expression's diagnostic; for example a nonfinite tensor literal still reports R2001. Shapes and numerical limits are runtime checks, whereas names, imports, arity, and types are checked before any execution. See the full API and algorithm contracts.

External contextual inference (development)

Independent observations can form an unlabeled AdaptiveFrame with data.frame(..., target: "", ...). ml.align_inputs(self: ..., observations: ..., columns: List(...)) explicitly maps distinct source columns into the fitted feature order and converts declared compatible units. Its reference is a retained FeatureLedger or raw input ContextLinearModel. It preserves external row identity and target meaning while leaving fitted parameters and training influences unchanged. For a model with fitted preprocessing, align to the first ledger, apply the same retained stages and then predict. Unlabeled targets cannot be read, fitted or scored as if labels existed. Alignment establishes inference compatibility; it grants no fit permission. See external contextual inference for the checked example and limits. These APIs require the matching Aner 0.0.5 runtime and are absent from published 0.0.4 packages.

External CSV data module

These data calls describe Aner 0.0.5 native runtime; earlier packages may predate them. See the data guide for matching development API requirements.

import aner.data; exposes DataSchema, DataScan, DataReport, DataTable, DataColumn, DataCondition and the existing Tensor type/literal syntax. Calls in other namespaces still need their own imports. These new values are opaque immutable handles; Aner code creates them with module functions, may pass or return them through annotated functions, and cannot print them directly. Column comparisons build conditions; schemas, scans, reports, tables and conditions cannot be compared for scalar equality. data.explain(scan) and data.summary(report) return inspectable text. Retrieve a table's cached report with table.overview() and format it with report.summary(); this starts no source/table traversal or deeper profiling.

CSV schemas declare column type names as Strings: "String", "Int64", "Float64", "Bool" and "DateTime", plus a Bool indicating whether missing cells are permitted. This adds missingness inside native data columns, not nullable scalar syntax or a missing language keyword. A missing cell must be checked through data.is_missing; reading it through a typed scalar accessor fails. No implicit scalar conversions are added.

data.col("name") returns a reusable DataColumn. Comparing it with a supported scalar or another column builds a DataCondition; &&, || and ! compose conditions natively. scan.filter(condition) and table.filter(condition) return lazy scans, while frame.filter(condition) preserves an AdaptiveFrame view. Numeric column comparisons allow exact mixed Int64/Float64 operands without rounding large integers. The data.rows signatures accept DataReport or DataTable. These are built in operations, not user defined operator overloading. Column existence, compatible types/units, CSV parsing and allocation limits remain runtime checks. See filtering and missing value semantics.

Plan construction performs no file read. Executing a plan resolves relative paths against the process working directory, reopens the source, validates the ordered header and every source field before filtering, and processes selected values in bounded column batches. data.collect has separate selected row and managed allocation limits; exceeding either returns an error without a partial table. data.to_tensor separately checks missingness, numeric types, exact integer conversion range, cell count, and output payload bytes. The source may change between executions; plans are not immutable data snapshots.

Native module errors use source diagnostic R2601. Resource limits constrain managed buffers per execution, not all interpreter values or total process RAM. The complete implemented functions and CSV/memory contracts are in Aner Data. No join, sorting, group by, external schema file parser, Parquet, SQL, or general nullable scalar API is introduced by this milestone.

Native language model and credential modules

import aner.llm exposes LLMClient, LLMMessage, and LLMResponse, with one native interface for Ollama chat, OpenAI Responses, OpenRouter chat completions, Anthropic Messages, Google Gemini stable v1 Interactions, and vLLM compatible chat services. import aner.secrets exposes opaque SecretRef values; LLM client constructors accept this type for an explicit credential reference, required for OpenAI, OpenRouter, Anthropic and Gemini. Calls in the secrets namespace require its own import. Client construction makes no network request. generate and chat perform one synchronous bounded request to the explicit provider; Aner checking validates types and arity without inference.

Response accessors expose normalized input_tokens, output_tokens and total_tokens, plus cached_input_tokens, cache_write_input_tokens and reasoning_tokens detail counts. A count of -1 means unavailable; a reported zero remains zero. Cache details are included in input and reasoning is included in output; do not add them again. Provider/model metadata and per request usage can support experiment logs, while the provider’s billing records remain authoritative for charges.

Clients, messages, responses, and credentials are opaque native handles. They may be passed through annotated functions and retained in user classes. Direct handle inspection hides message text, generated text, and secret values. Generated content becomes a normal String when answer.text() is called; ordinary String output and development capture semantics then apply. Credentials have no raw value getter or implicit conversion to String. See Language model connections and Credentials for exact provider, transport, storage, error and time and space contracts.

Experimental quantum circuits

import aner.quantum exposes QuantumCircuit, QuantumBackend and QuantumResult in Aner 0.0.5 runtime. Gate methods create new immutable circuit descriptions; run(backend: ..., shots: ..., seed: ...) executes a bounded ideal CPU simulation with terminal measurement of every qubit. quantum.cpu() is available; quantum.gpu(), quantum.cluster() and quantum.hardware(target: ...) are unavailable descriptors for planned adapters. Unsupported execution fails explicitly with R3901 containing E_QUANTUM_BACKEND.

Use concise ordinary Aner: let bell = quantum.circuit(qubits: 2).h(0).cx(0, 1). Qubit zero is the least significant bit. Counts and sampled_z represent finite measurements; exact probability and expectation_z inspect the CPU simulator and are not promised on physical hardware. See the experimental module guide for diagrams, complete runnable examples, numerical/resource bounds and backend portability requirements. Quantum values do not join Tensor differentiation graphs. Checked parallel.repeat tasks currently reject quantum calls and values; use ordinary classical loops for parameter sweeps.

Scalar mathematics

import aner.math enables native Float64 math.sqrt, math.abs, math.pow, math.exp, natural math.log, base two math.log2, base ten math.log10, math.round, math.floor, math.ceil, math.sin, math.cos and math.tan, plus immutable Float64 values math.pi, math.e and math.tau. Rounding returns Float64; math.round resolves ties to even without changing the ambient rounding mode. Raw scalar / still returns Float64; integer_div retains exact truncating integer division. Inputs and results follow the explicit domain/range checks in aner.math. Concrete integer or Number arguments use checked exact Float64 promotion; trigonometric arguments are raw radians. These scalar functions are admitted in checked repetition tasks. aner.units provides unit bearing scalars separately; math calls require an explicit raw .value() boundary. General nonlinear uncertainty propagation remains planned work.

Scalar physical units

import aner.units enables immutable Quantity<UnitCode> and Point<UnitCode> values with Float64 magnitudes and one exact registered unit. The 23 code registry is shared with SemanticTensor/EvidenceTensor. Use Quantity<m> for distance, Point<degC> for an absolute temperature reading and Quantity<delta_degC> for a temperature interval. Nonidentifier codes are quoted: Quantity<"m/s"> or Quantity<"1">.

aner
import aner.units
let distance: Quantity<m> = 2.0@m + 50.0@cm
let speed: Quantity<"m/s"> = distance / 5.0@s
let rise: Quantity<delta_degC> = 25.0@degC - 20.0@degC
print(distance)
print(speed)
print(rise)
print(1.0@m == 100.0@cm)

The output is 2.5@m, 0.5@"m/s", 5.0@delta_degC, then true. Unit literals attach only to Float64 literals, with @ and the fixed unit code on the literal's physical line. 2@m and value@m are rejected. A signed lexical point literal such as -5.0@degC constructs a negative reading; unary negation of an existing Point, including -(5.0@degC), is rejected.

Computed magnitudes use units.quantity(value: Float64, unit: String) or units.point(value: Float64, unit: String). units.convert(value, target_unit: String) and .to(target_unit: String) convert compatible dimensions and quantity kind. Construction/conversion unit arguments must be literal Strings so checking determines the exact result type. Assignment, annotated parameters/returns, class fields, wrapper payloads and casts require that exact type; use .to("m") before supplying centimeters to a meter parameter. Quantity<UnitCode> is a unit specialization, not a generic storage dtype declaration. Unit still means the no value return type.

Quantity addition/subtraction converts compatible operands and retains the left unit. Point minus Point yields the left point's difference unit; Point plus/minus an interval yields that Point type; interval plus Point yields the right Point type. Point plus Point, interval minus Point, Point products/scaling/negation and point to interval conversion are rejected. Float64 scaling preserves a Quantity unit. Two quantity products/ratios derive only an existing scale one linear registry unit, such as m/s, J, W or 1; a product with unregistered result dimensions, such as m * m, is rejected during checking. Float64 divided by Quantity is outside this initial API.

Same concrete unit comparisons use the stored magnitudes directly; cross unit comparisons convert both operands to the same deterministic canonical representation. Dimensions and point/interval kind must match. Comparisons use exact Float64 values without an implicit epsilon. Cross unit normalization can fail if its finite nonzero result cannot be represented. .value()/units.value(value) explicitly returns raw Float64; .unit()/units.unit(value) returns the declared code. print and String retain roundtrippable unit literal notation. type reports the exact specialization and dtype reports Float64.

Values store an inline magnitude and a reference to shared immutable registry metadata. They are supported as Any/List/Dictionary values, Optional/Result payloads, class fields and isolated repetition parameters. Any/List equality compares matching concrete unit and magnitude; typed unit operators compare compatible physical values. Quantity/Point Dictionary keys, Set elements and List sorting are rejected. Packed Array/DynamicArray/NDArray now admit unit bearing elements with Float64 magnitude storage and one unit descriptor per buffer. Their .values() method explicitly returns independent raw magnitudes; scalar .value() likewise drops the unit. Numeric repetition outputs retain their existing separate contract. Units do not declare measurement uncertainty, missingness or observation coordinates.

Runtime unit/numeric failures use located R3701 diagnostics. Inputs and results must remain finite; zero division, overflow and nonzero linear underflow to zero fail, while representable subnormals and legitimate affine offset cancellation remain valid. See aner.units for full signatures, registry codes, arithmetic tables, numerical bounds and complete basic and laboratory programs.

Arrays with physical units

After import aner.units, construct Array<Quantity<m>>(size: 3, fill: 0.0@m), DynamicArray<Point<degC>>(capacity: 4) or NDArray<Quantity<"m/s">>(shape: List(2, 3), fill: 0.0@"m/s"). Reads retain the exact element specialization; writes and typed casts require it without implicit conversion. type reports the nested unit type while dtype remains Float64.

Named array arithmetic uses the scalar affine/dimension rules. Point means retain their Point type; Point standard deviations return an interval Quantity. Literal .to("unit") creates a fresh converted same family buffer, including same unit conversion. .values() creates a fresh primitive Float64 buffer and explicitly removes units. Direct unit array .to_float()/.to_tensor() are unavailable; exported values can use the established numerical bridges. This introduces no array infix operators. See the complete unit array reference for reductions, registered products, broadcasting, ownership, bounds and runnable experiments.

CSV columns with physical units

Import aner.data and aner.units; declare a numerical source column using schema.unit_column(name: "distance_cm", unit: "cm", nullable: false). CSV cells remain plain source numbers. scan.convert_unit(column, target_unit) records compatible ingestion normalization while retaining original source interpretation; every present source field is normalized and validated before filters/projection.

The opaque schema/scan configuration permits runtime unit Strings. Typed output methods table.unit_value(row, column, target_unit), table.unit_values(column, target_unit) and report.unit_mean(column, target_unit) instead require literal target unit Strings so checking fixes their Quantity/Point result type. No new generic call syntax is introduced. Whole column retrieval produces a fresh packed unit array and requires all selected cells present; explicit where_present establishes that policy without zero filling. Raw numeric means/getters/Tensor conversion reject unit columns. See aner.data unit column APIs for physical filters, source/target metadata, exact argument labels and complete fixture examples.

Native basic value contracts

Date, Time, DateTime, Duration, Bytes, Range, Optional, and Result<T, E> need no import. Their separate references define construction, ownership, exact parsing, checked access, and time and space complexity: Date, Time, DateTime, Duration, Bytes, Range, Optional, and Result.

for index in Range(start: 0, stop: 10, step: 2) { print(index) } iterates lazily with an immutable Int64 loop binding. Existing DatasetBatches iteration remains supported; List and array iteration are not generalized by this addition. Range and outcome values are not implicitly converted to Bool.

Temporal equality and ordering use their native value contracts; DateTime compares exact instants independently of presentation offset. Bytes equality compares contents and ordering compares unsigned bytes. Range equality compares declared start, stop and step. Optional and Result equality compare managed wrapper identity, and their payload accessors remain explicit after branch checks. Outcomes do not catch runtime errors. Explicit postfix ? propagates one Result layer through a compatible declared Result returning function; Optional and nullable class access remain explicit.

NLP values

import aner.nlp enables TextCorpus, TextVectorizer, TextFeatures, TextIndex, TextMatches, TextContext, TokenBatch, TextTokens, TaggedCorpus, TextTagger, TextTagging and TaggingEvaluation, together with Tensor annotations for explicit numerical bridges. These immutable types support typed functions, collections and persistent sessions. Calls and instance methods require their owning module import. See natural language processing for all parameters, partition roles, provenance and resource limits. NLP and the neural bridge operations require Aner 0.0.5 or newer.

Source aligned POS and named entity tagging uses explicit source token boundaries, gold labels and task specific metrics. The contextual tagger retains canonical settings, training identity and exact averaging/shuffle state across checkpoints. These APIs require Aner 0.0.5 or newer.

Aner documentation · Reference and guides