Documentation

Modules

Modules

A module in Arx is a source file (for example, math.x) containing top-level statements such as imports, function definitions, and extern declarations.

Module Layout

```
title: Math module example
summary: Module with one documented function.
```
fn average(x: f32, y: f32) -> f32:
  ```
  title: average
  summary: Returns the arithmetic mean of x and y.
  ```
  return (x + y) * 0.5

Module Scalar State

Module variables support numeric and Boolean scalars, including their supported nullable forms. Literal initializers are checked and converted during analysis. A mutable scalar without an initializer starts at zero (false for Boolean), or none for nullable storage. Constants require a literal initializer.

Storage exists before function bodies run, and a function can refer to a module variable declared later in the file. Function calls share that module's state. A local declaration shadows it without changing the module binding. Assignment to a resolved module variable needs no global statement. Same-named variables in different modules have independent storage. Variables are accessed across modules through functions.

Module initialization

A mutable module scalar with an explicit type may be initialized by an expression, including a function call. These expressions and named function decorators execute once at program startup. A dependency initializes before its importers. Within a module, runtime initialization follows declaration order.

```
title: Initialize module state
```

port: i32 = default_port()

fn default_port() -> i32:
  return 8080

fn main() -> i32:
  assert port == 8080
  return 0

Literal-initialized values are available throughout startup. A runtime-initialized scalar holds its default value until its expression completes. An uncaught exception stops the remaining startup actions and prevents main from running. A linked root with main provides the startup entry point for its imports.

Declare strings, containers, and other resource-owning values inside functions.

Package Layout

When a project uses the default src/ source root, or declares [build].src_dir, Arx treats files under that source root as package modules addressed by dotted names.

Example project layout:

.
├── .arxproject.toml
├── src
│   └── geometry
│       ├── __init__.x
│       ├── shared
│       │   └── math.x
│       └── shapes
│           ├── area.x
│           └── helpers.x
└── tests
    └── test_area.x

With the default src/ source root:

Use __init__.x as the package root, following the same layout idea as Python packages.

Import Syntax

import geometry.shapes.area
import geometry.shapes.area as area

import circle_area from geometry.shapes.area
import circle_area as area_of_circle from geometry.shapes.area

import (circle_area, square_area) from geometry.shapes.area

import radius_to_diameter from .helpers
import (circle_area, square_area) from .area
import clamp from ..shared.math

Rules:

Absolute Imports

Use absolute dotted paths for public imports across package boundaries:

import circle_area from geometry.shapes.area

Installed Package Imports

Arx can also resolve absolute imports from installed Arx source packages declared in [project].dependencies in .arxproject.toml.

For example, if the current project declares an installed dependency that exposes a package root named local_lib, this import resolves from that installed package when no local project source shadows it:

import sum2 from local_lib.stats

Installed package lookup is scoped to the current Python environment running arx. The compiler reads installed distribution metadata, follows transitive dependency metadata, and uses packaged .arxproject.toml files to find Arx source roots. It does not install packages, access the network, or change generated IR/codegen behavior.

For installed packages with the normal project layout, place .arxproject.toml at the packaged project root and declare both [build].src_dir and [build].package:

site-packages/local_lib_project/
├── .arxproject.toml
└── src
    └── local_lib
        ├── __init__.x
        └── stats.x
[build]
src_dir = "src"
package = "local_lib"

With that layout, local_lib.stats resolves to site-packages/local_lib_project/src/local_lib/stats.x.

Flat package layouts are also supported for packages that place .arxproject.toml and .x files directly in the package directory:

site-packages/local_lib/
├── .arxproject.toml
├── __init__.x
└── stats.x

Resolution precedence is:

  1. local/current project source files
  2. installed Arx dependency packages
  3. unresolved import error

The reserved stdlib and internal builtins namespaces always remain owned by the compiler and cannot be replaced by installed packages.

Bundled stdlib

Arx ships a first-party standard library namespace called stdlib.

Example:

import math from stdlib

fn main() -> i32:
  return math.square(4) + math.clamp(0 - 3, 0, 2)

Use stdlib.json to read a JSON configuration and select typed values.

import json from stdlib

fn read_port(source: str) -> i64:
  return json.loads(source).get("server").get<i64>("port")

json.load and json.dump work with open text files on POSIX. For a parsed value, json.dumps preserves number spellings and the original text inside the value. as_str raises ValueError for a decoded NUL because Arx strings cannot store it. The encoded escape is preserved when writing the value back. Values own their encoded text. Indexed access and key lookup can scan the container's text, so repeated lookups on large containers incur that cost.

Use stdlib.yaml for single-document YAML 1.2 configuration. For example, parse server: {port: 8080} with yaml.loads(source) and read the port with value.get("server").get<i64>("port"). yaml.load and yaml.dump use open text files on POSIX. yaml.dumps emits flow syntax and preserves the value types, numeric spellings, and mapping order. Comments and layout are discarded.

The module supports block and flow collections with string keys, single-line plain and quoted scalars, and literal and folded block strings. It rejects duplicate keys, anchors, aliases, explicit tags and keys, directives, nonfinite numbers, and multiple documents. Syntax errors include a one-based line and column. Selected values own their text. Indexed access and key lookup scan the container, as in stdlib.json.

Use stdlib.toml to read TOML 1.0 tables, dotted keys, arrays, arrays of tables, and scalars. For example, toml.loads(source).get("server").get<i64>("port") reads the port from a [server] section. Use as_datetime_text() to read date and time values with their fractional precision and offsets. Leap seconds are unsupported.

toml.dumps writes a table as a TOML document with inline nested tables. It preserves values and key order. Comments and source formatting are discarded. As with JSON, escaped NUL survives serialization and raises ValueError when decoded to str. toml.load and toml.dump use open POSIX text files. The file API normalizes newlines before parsing.

In all three modules, bare get(key) returns a value for further navigation. get<T>(key) accepts bool, i64, f64, str, or the module's value type (JsonValue, YamlValue, or TomlValue). It uses the same checked conversion as the corresponding as_* method. Use get<str> for string values such as "8080".

Bundled builtins

Some compiler-provided builtins live in bundled .x package resources, separately from the importable stdlib. They are not copied into user projects, and local sources cannot replace the reserved namespace. Ambient names are injected only when not shadowed by a declaration or import. Explicit builtins.files imports resolve the canonical File class, not a second implementation.

Core intrinsics such as range and len are resolved by IRx rather than loaded as source modules. Range values are lazy and allocation-free; see for-in workflows. General source generators and yield remain unsupported.

Namespace Imports

Use a module alias when you want to keep names grouped under a module namespace:

```
title: Geometry namespace import
summary: Call one module member through a namespace alias.
```
import geometry.shapes.area as area

fn main() -> f64:
  ```
  title: main
  summary: Demonstrates namespace member access.
  ```
  return area.circle_area(10.0)

Direct symbol imports remain available when you prefer shorter local names:

import circle_area from geometry.shapes.area

Relative Imports

Use relative from imports for package-internal references. For example, inside geometry.shapes.area:

import radius_to_diameter from .helpers
import clamp from ..shared.math

Module Docstring

Arx supports module docstrings in Douki YAML format, delimited by triple backticks:

```
title: Module documentation
summary: Optional summary text
```

Current placement rule:

Valid:

```
title: Module docs
```
fn main() -> i32:
  ```
  title: main
  summary: Entry point for the module.
  ```
  return 1

Invalid (leading indentation before module docstring):

  ```
  title: Module docs
  ```
fn main() -> i32:
  ```
  title: main
  summary: Entry point for the module.
  ```
  return 1

For now, module docstrings are parsed and validated but ignored by AST/IR generation.

stdlib.arrow exports Schema, BatchBuilder, RecordBatch, IPCReader and IPCWriter. It uses ordinary classes and nominal opaque native handles, not new keywords. See the Arrow API and examples. Native bindings are supplied only for the bundled reserved module; a user module cannot gain these bindings merely by declaring matching handle type names.

Tabular standard-library modules

Format classes are not exported from stdlib.arrow. Import shared types from that canonical module rather than through a format module. Namespace-qualified calls and explicit aliases work normally. Format functions are not global builtins, and equally named user functions receive no native privileges. CSV/shared Arrow do not activate the optional Parquet feature.

Search documentation

Type to search.