Experimental documentation — Work in progress
This page has not completed the documentation audit. Current documentation version: experimental.
Code generation
bin/sagan --emit-cpp translates a semantically validated executable unit into
C++. With an output path it writes a .cpp file; without one it prints the
translation. tests/integration/codegen_test.sh compiles representative output
with g++ and runs the resulting native executable.
The current subset supports typed functions, scalar literals, plain and
interpolated strings,
local declarations, immutable local and module-level constants, assignment,
parallel local declarations and simultaneous reassignment,
calls, grouping, common unary/binary operators,
prefix and postfix numeric increment and decrement, checked integer arithmetic,
dimensioned Cartesian and spherical vector and point values, Cartesian spreads,
indexing, named components, iteration,
printing and interpolation,
typed expression lambdas, source-level function types, higher-order calls, and
escaping shared-reference captures,
classes with typed fields, default or overloaded new(...) construction, self, and
public/private fields and methods,
reference-counted class and face values, dynamic face dispatch, and composed
face default methods with explicit conflict resolution,
nominal enums with named output, equality, and match cases,
typed optional values with payload matching, safe ?. propagation, and lazy ?? fallback,
checked integer and floating-point exponentiation through ^ and ^=,
conditional expressions, if/else, while/until, loop control, and
returns. Value-bearing scream exceptions, ordered exact type-and-value
unless handlers, outward propagation, and finally cleanup also lower to the
native runtime. Cleanup runs when control leaves the protected region normally,
through an exception, or by early return. Homogeneous array literals preserve the element width inferred by the
type checker, array indexing is bounds-checked, and for … in iterates values
by local copy. Array spreads evaluate each operand once and append its elements
in source order. The built-in print(value)
accepts one checked value, writes its
human-readable form followed by a newline, and lowers to the generated C++
output helper. Generated entry points select UTF-8 console input and output on
Windows, preventing Unicode text from being interpreted through a legacy code
page; other platforms keep their existing UTF-8 environment. Names are
deterministically encoded as legal C++ identifiers, so
Unicode and emoji Sagan names do not depend on a C++ compiler's identifier
spelling support. The backend synthesizes native C++ int main() for the
selected root file. Root statements execute in source order; normal completion
returns success, and Sagan exit(code) supplies an explicit process status.
Unsupported AST forms produce a source-located backend diagnostic rather than
silently generating incorrect code. The emitter currently requires explicit
function signatures. At the program root it emits functions, const
bindings, mutable let bindings, and executable statements. Root bindings
have shared storage visible to functions, while their initializers execute in
source order. The type checker enforces the const view; this is not a
deep-frozen object graph.
Homogeneous dictionary literals with backend-supported scalar key and value
types lower to std::unordered_map. Key lookup is checked and raises the native
out-of-range exception when a key is absent. Dictionary spreads evaluate each
operand once and apply entries from left to right; later entries replace earlier
values for the same key. Dictionary iteration is not lowered yet.
match evaluates its subject exactly once, compares expression-shaped cases in
source order, and executes the first equal case or the final case else
fallback. Destructuring and type-pattern matching are not part of the current
language subset.
Integer addition, subtraction, multiplication, division, remainder, negation,
increment, decrement, exponentiation, and their compound-assignment forms use
generated helpers. Integer overflow and zero divisors raise runtime errors;
floating-point remainder uses fmod and floating-point division also rejects a
zero divisor.
Cartesian vectors and points lower to separate fixed-size native runtime types,
so a point is not silently interchangeable with a vector. Their dimensions and
component types come from the checked semantic model. Vectors support checked
addition, subtraction, unary negation, scalar multiplication and division,
equality, and compound forms. Vector-vector multiplication is deliberately not
assigned an implicit dot, cross, or component-wise meaning. Points support
checked translation by vectors and subtraction into displacement vectors;
point addition and direction-first translation are rejected. Explicit generic
annotations for dimensioned values and physical units are implemented. Both dimensioned
families provide .x, .y, .z, and .w component access where their
dimension permits it; components are assignable because variables are mutable
by default.
Spherical points and vectors lower to two further fixed-size families and retain
their s(...)/s<...> printed forms. Points expose radius, inclination, and
azimuth; vectors expose magnitude, inclination, and azimuth. They support
storage, indexing, iteration, equality, interpolation, and printing. Arithmetic
and Cartesian conversion are intentionally absent until the core math API fixes
the conversion conventions.
Faces lower to native abstract interfaces with virtual methods. Semantic
analysis first verifies every required signature and resolves defaults, then the
backend emits conforming classes and flattens applicable transitive default
method bodies. Class construction uses shared reference-counted storage, and
conversion to a declared face preserves object identity for runtime dispatch.
Weak class fields lower to std::weak_ptr<T>. Strong values assign directly to
that storage; reads call lock() and lower to std::optional<std::shared_ptr<T>>,
which is the native representation consumed by Sagan's ?., ??, and optional
matching operations. Before emission, type checking rejects all-strong class
field cycles and strong face-typed fields, so the generated reference-counted
object graph requires an explicit non-owning edge wherever a cycle is possible.
Payload-bearing enums lower to tagged structs whose payload storage uses
std::variant; cases with multiple payload values use std::tuple. Generated
match branches test the case tag and extract typed payload bindings by variant
index. Payload-free enums retain the smaller native enum class representation.
Generic functions lower to C++ function templates and rely on the already
checked Sagan call-site inference. Generic sum enums use a single tagged,
type-erased native representation; construction stores statically verified
payloads in std::any, and match bindings recover the substituted payload type.
This representation is an initial backend strategy, not a settled ABI.
Generic classes and generic faces lower to C++ class
templates. Construction uses the checked specialization with std::make_shared,
and conversion to a specialized face uses the corresponding virtual template
base. Ordinary defaults compile into the face template and retain virtual
dispatch through self. Class-level generic methods lower to member templates;
method-specific generics on faces are rejected because C++ cannot provide
virtual function templates.
--emit-cpp-modules resolves a loose or manifest-discovered module graph and links its
selective imports and exported namespace members into one checked compilation unit. Dependency-private
top-level names receive deterministic module-qualified identities, imported
aliases point to exported identities, and dependency declarations are emitted
before their consumers. The module demo compiles and executes the resulting
C++ translation.
--emit-cpp-package starts from a strict package manifest, maps qualified
module names to nested files under its source root, and uses the same linking
and validation pipeline. The package demo compiles and executes that result.
Open work includes generated-code structure, borrowing, contextual self
capture in escaping closures, richer exception patterns, debug information, compiler selection and flags,
standard-library linkage, platform support, optimization, broader expression
and statement lowering, and deterministic constraints beyond the implemented
numeric subset. Native compiler
invocation is available through direct source execution and --run-package;
toolchain discovery and configuration remain intentionally minimal.