tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

129 lignes · 26963 octetsBrut · Historique

ADR 0082: Bounded @comptime evaluation into immutable statics

Status: Proposed (2026-11-11); needs language/evaluator, memory-safety and native-code engineering review (#44).

Context and deliberately bounded scope

Louise needs useful computed constants without making compilation an ambient-effect execution environment. #339's first increment is a declaration, not general syntactic staging: a user may mark a top-level ordinary nullary function @comptime. Its value is evaluated during compilation and installed as immutable data. Macros, hygiene, token/code templates, a comptime expr form, incremental evaluation caches and arbitrary host execution are excluded.

B1 provides only public semantics-neutral foundations: ordinary-entry value mapping for the REPL, a direct evaluator, reification and immutable Core reconstruction. B2 owns source attributes, diagnostics, pipeline placement, C immutable statics and direct-call substitution. A B1 result must not be presented as an accepted user-facing @comptime implementation.

Entry and evaluation

  • The marked declaration is bodied, non-extern and non-intrinsic, has no source parameters (only Core's unit argument), and has a monomorphic result/body: no root type variables, constraints/evidence parameters, capabilities or open/nonempty effect row. Explicit and inferred empty rows are equivalent after type checking.
  • Every marked declaration is evaluated exactly once in source-root order, even when unreachable or unused. A failure is a compilation error. Fresh isolated interpreter state is used per root; no cross-root memoization is introduced. Generic dependencies are allowed only after ordinary evidence specialization; the root itself remains monomorphic. The shared louise_comptime::prepare_required preparation first computes the complete reachable set from the roots, exactly as ordinary opt does before its first evidence pass, then calls louise_core::evidence::run_in_required on that whole set. Processing roots alone is insufficient: their direct callees contain source dictionary calls too. It performs no general user optimization or Perceus, honors neither optimizer escape hatch, preserves original root FnIds and leaves dynamic remaining calls rejected: direct CTFE has no dynamic-closure fallback.
  • CTFE is semantic, not an optimization. LOUISE_NO_OPT does not disable it. Evaluation precedes ordinary optimization and Perceus; a cloned transactional preparation may itself perform the existing @fip/evidence specialization. Commit occurs only after every root and all reification succeeds.
  • Effect-free does not prove termination (#343). The B2 dependency fixed point rejects self/mutual recursion and every root reaching a cyclic direct-call SCC. It also rejects indirect/unknown closure calls, foreign/unknown externs, Handle, Region, Defer, effect/root/actor operations. This analysis is not fusion's notion of purity: division and panic are executable and an actual failure becomes a diagnostic.
  • The direct runtime defense is independently fail-closed. It receives [Val::Unit], ignores root_caps, creates no roots/actor scheduler or externally reachable clock/input/output/table state, runs on the calling thread and accepts only the internal preemption request. Any other request is a structured protocol error. Non-Send Val never crosses a thread boundary.

The direct extern allowlist is louise_interp::comptime_safe_extern, not merely Extern::effect_free. Initially it contains checked Int arithmetic/bit operations/show/hash and parsing; Float arithmetic/conversion/show/hash; String comparison/query/concat/lowercase/trim/slice/debug/parsing; hashes; identity coercion; and tl_panic as a deterministic runtime failure. Split/join/chars, arrays, Bytes, crypto, U64/Dec display/conversion, OS/fs/net/clock/random/process/table operations and all foreign externs are deferred. Every admitted allocating extern has a conservative preflight allocation/content-output charge. This list is shared by B2's gate and the runner, not inferred from a value's display or C ABI.

The B1 public contracts

Ordinary entry result

pub fn run_value_map<T: Send>(
    program: impl Into<Arc<Program>>,
    entry: FnId,
    options: RunOptions,
    map: impl FnOnce(Val) -> Result<T, RtError> + Send,
) -> Result<T, RtError>

The scoped large-stack interpreter thread permits borrowed mapper state without adding a 'static bound; T still must be Send. The scheduler retains the completed entry Val until other actors have unwound. The mapper consumes it on that interpreter thread before teardown, both writer streams are then flushed, and only T crosses the join. Mapper errors are returned; a mapper Rust panic retains the existing interpreter crashed host-error behavior. run and run_with remain unit mappings and retain ordinary roots/default handlers, runnable, output and os.exit policy. C1 maps the already language-Debug-rendered String; raw Val is not stored in a REPL session.

RunOptions::evaluation: Option<EvaluationLimits> separately enables deterministic scoped accounting for an ordinary run; RunOptions::new sets it to None, preserving existing unbounded logical behavior (and the existing independent legacy max_frames option). When present, frame bounds also cover Bind/other CEK growth, and one run-local budget charges steps, allocation and generated/writer output across every actor without a preemption refill. The smaller of legacy and scoped frame limits applies. Directness remains an independent private mode bit: only direct CTFE uses the no-root protocol and extern allowlist. Ordinary bounded entries retain default handlers, actors and host effects. reified-node/static-byte fields are ignored by ordinary evaluation; zero values therefore do not reject an ordinary data result.

stdout, stderr/eprintln, crash reporting and generated content use the same output accounting, while allocation preflight handles interpreter allocations and known primitive growth. Ordinary foreign/native internals and live host IO remain subject to the external process memory/deadline supervisor: logical counters are neither RSS nor a security sandbox. A scoped error remains structured and every later run constructs fresh state; entry values and cleanup retain the same lifecycle.

Direct runner and errors

pub fn run_direct(
    program: impl Into<Arc<Program>>,
    entry: FnId,
    limits: EvaluationLimits,
) -> Result<DirectValue, DirectError>

pub fn run_direct_with(
    program: impl Into<Arc<Program>>,
    entry: FnId,
    limits: EvaluationLimits,
    cancelled: &dyn Fn() -> bool,
) -> Result<DirectValue, DirectError>

run_direct requires compiler-validated Core (valid variables, declarations, arities and runtime invariants); its entry/direct-call bounds and the direct resource gate are additionally checked, but it is not an untrusted binary parser. DirectValue { value: Val, usage: EvaluationUsage } is synchronous and stays on its creating thread. DirectErrorKind distinguishes Runtime(RtError), Evaluation(EvaluationError), cooperative runner Cancelled, a forbidden { effect, op, name: Option<String> } operation, invalid parameter count and missing entry. Evaluation errors include unsupported direct Core forms/externs, limits and invalid direct calls. Before execution, an iterative reachable-function gate rejects indirect calls, Handle, Region, Defer, Perceus reuse and TRMC contexts; this does not replace B2's typed/recursion analysis. DirectFrame { function: FnId, name: String, span: Option<Span> } is innermost-first, using retained Core call/declaration spans. Direct-only provenance records every actual CallFn transition before entry, even when tail-position machine activation replacement leaves no Frame::Return; successful return restores/pops its caller, and the panic-time snapshot freezes the innermost/caller sequence. Thus source provenance is collected without changing ordinary tail semantics or inventing entries for inlined code. If mandatory evidence preparation replaces a trivial extern wrapper with its body, its original enclosing let span retains the caller's original call site and the genuine entry/caller frame is kept; the removed helper is not named as a fictitious runtime transition. The exact runtime panic payload remains unchanged, and tests verify both the useful call-site text and a separate non-inlined branch-containing helper's actual two-frame sequence. Successful calls roll back provenance before later calls, so stale or duplicate caller entries are not retained. Runtime preserves the original structured panic/unhandled/cancel/kill/exit kind; fuel and every direct CEK frame-growth failure are not recovered by parsing text. EvaluationUsage::preemptions counts real yielded slices so tests prove at least two preemptions without a fuel refill.

Cooperative runner cancellation

run_direct delegates to run_direct_with with a predicate that never cancels, preserving its existing signature and behavior. run_direct_with polls the borrowed predicate synchronously on the same caller/interpreter thread before every individual machine reduction, including initial entry. A true result produces structured DirectErrorKind::Cancelled with no Val, without charging the reduction that did not execute. This runner cancellation is distinct from the existing RtError::Cancelled continuation-unwinding effect. Current error and operation outcomes retain their structured frames and usage, and normal direct whole-machine teardown consumes the cancellation outcome exactly once. Fresh per-call interpreter state means neither cancellation nor preemption refills fuel.

This is cooperative machine control, not an asynchronous interrupt. Source preparation/lowering done by a caller and the runner's reachable-graph/extern preflight are not polled. An admitted extern or other already-started primitive reduction is atomic with respect to this callback; cancellation can only take effect before the next reduction, and an already-captured program failure is not suppressed. The predicate may inspect caller-owned synchronization state, but no external atomic, Interp, thread pointer or non-Send Val is embedded in a result or crosses a join. It supplies neither a wall-clock deadline nor process-resource supervision. B1 does not implement LSP scheduling or claim that external LSP cancellation now works. LSP integration and the decision about committing stale results remain subject to the final #44 review gate.

Neutral immutable values and reconstruction

louise_core::static_value contains:

StaticNodeId(u32)
StaticNode = Unit | Int(i64) | FloatBits(u64) | String(String)
           | Construct { tag: u32, name: String, fields: Vec<StaticNodeId> }
           | Tuple(Vec<StaticNodeId>)
StaticValue { /* checked topological root + nodes */ }

StaticValue::{root,nodes} are read-only views. new rejects invalid roots/references, non-topological children, non-small Int and non-finite Float. core_body(first_var) -> CoreBody emits one ordinary Let per node, children first, then a Return, without contexts, reuse tokens, resources or runtime-only variants. Construction is iterative, but the compatibility representation is still nested Box<Expr>: existing recursive Core visitors and final Rust drop therefore share a 1024-node MAX_CORE_NODES reconstruction bound. Oversize valid static DAGs remain available to B2's backend-neutral table path but return StaticValueError::CoreNodeLimit rather than silently risking the recursive compatibility consumers. The default reification visit bound is also 1024, so default accepted values fit this bound; larger custom reification still needs this explicit reconstruction check. B1's maximum-bound fixture covers construction, direct evaluation, opt::run_with_hook reachability/passes and destruction, with no 100k nested-Core safety claim. reconstruct_fn(&FnDecl) preserves identity/parameters/source/module and replaces only the pre-optimization body/variable numbering, dropping stale shapes. B2 attaches results by stable monomorphic source FnId in a BTreeMap, rather than adding a flag to every constructor declaration.

louise_comptime::{reify,reify_detailed} validate Val iteratively. Work items schedule one child at a time; wide constructor/tuple storage and children counts are charged before allocating the reifier's output vectors, rather than eagerly growing an unbounded work stack. ConstructorLayouts::from_hir(&Hir,&TypeckOutput) is authoritative for constructor name/tag/arity, including stored dictionaries; unknown, ambiguous and wrong-arity values have distinct errors. Interning is structural and traversal-order deterministic. Rc addresses are private lookup keys solely to avoid revisiting shared values; address identity is neither returned nor a language behavior. The supported result universe is Unit, small 63-bit Int (bounds included), valid UTF-8 String, exact finite Float bits (including negative zero/subnormals), and recursively supported immutable constructors/tuples. NaN/infinities, promoted Int, Bytes, Array, U64, Dec, closures, resumptions, refs/regions, pids, capabilities, TRMC contexts/reuse tokens and unknown/future variants are rejected. Pointer/layout guessing is forbidden.

pub struct Evaluator<'a> { /* Arc<Program>, &'a ConstructorLayouts, budgets */ }
impl<'a> Evaluator<'a> {
    pub fn new(Arc-like Program, &'a ConstructorLayouts) -> Self;
    pub fn with_limits(..., per_root: EvaluationLimits,
                        compilation: EvaluationLimits) -> Self;
    pub fn evaluate(&mut self, entry: FnId) -> Result<StaticValue, CtfeError>;
    pub fn evaluate_with(&mut self, entry: FnId,
                         cancelled: &dyn Fn() -> bool)
        -> Result<StaticValue, CtfeError>;
}

The returned immutable data is Send + Sync; evaluator state has been dropped. C1 does not depend on this crate. B2 uses this session for all marked roots. evaluate delegates to evaluate_with with &|| false. The cancellable method calls run_direct_with directly, consumes its actual usage once on success or failure, and returns DirectErrorKind::Cancelled inside CtfeError::Evaluation; it never converts cancellation to CompilationLimit, runs reification, or returns a StaticValue after cancellation.

Deterministic resource limits

EvaluationLimits has max_frames, max_steps, max_allocation_bytes, max_output_bytes, max_reified_nodes, and max_static_bytes. Defaults are respectively 4096 frames, 1,000,000 steps, 64 MiB allocation, 16 MiB content output, 1024 reified visits and 16 MiB estimated static data per root. EvaluationLimits::whole_compilation() defaults to 4096 frames (a per-machine ceiling, not accumulated), 10,000,000 steps, 256 MiB allocation, 64 MiB output, 1,000,000 visits and 64 MiB static data. Constants are authoritative, with no environment overrides. Small custom values are library/test inputs and eventually belong in any compiler-input fingerprint if exposed as product configuration.

One machine-loop reduction consumes one step. Direct preemption resumes the same counter; it never restores fuel. Every direct CEK push/extension (Bind, calls, cleanup/continuation protocol included) observes max_frames; the gate then rejects forms with out-of-scope hidden continuation allocation. Environment/argument vectors, literals, constructors/tuples/closures, primitives including bool_val, ReturnN, reified strings/content, work/resolved/output vectors and admitted extern results receive checked saturating charges before their producing operation. Integer cloning/hash scratch are charged by argument size; a BigInt show bound is bits + 3, using log10(2) < 1, rather than an unsound fixed approximation. Integer shift/parse/show and string construction use input-derived conservative bounds. Float-from-Int includes its promoted-Int clone. Shifts charge both operand clones, result/scratch and any negative/oversized amount's full generated diagnostic before execution. Ordinary scoped pure byte/base64/crypto results use their interpreter-specific aggregate content/allocation models without turning on CTFE admission; opaque foreign effects remain externally supervised. Before a multi-shot resume, the implementation inspects the incoming Frame slice in one flat pass and pre-charges its new Frame Vec, Return/ReturnN env or Final args/error strings, and the destination stack capacity. It clones/takes only after frame/allocation checks fit; failed preflight leaves resumption counters and original frames unchanged. Rc/Val graph fields remain ownership copies, not recursive deep copies. max_output_bytes means generated content bytes, not terminal I/O (direct evaluation permits none). These are reproducible logical budgets, not RSS claims: external resource admission remains responsible for actual process memory/deadline enforcement.

A session takes the elementwise minimum of remaining whole-compilation and per-root limits, consumes actual deterministic charges after each root (or failed root), and reports whether a root or aggregate was exhausted for steps, allocation, output, visits and static data alike. Fresh roots cannot multiply fuel, generated content or result size by the number of declarations. Every run_direct/run_direct_with outcome, successful or failed, first passes the whole machine through one graph-wide teardown: retired tail environments, callee environments replaced by successful Return/ReturnN, unwound Frame environments, failed request args, continuation frames/handlers/regions and State table values are included together, with a clone anchoring any returned value. Moving replaced environments into the retired Val vector charges their destination slots just as tail/unwind retirement does; ownership is delayed to whole-machine teardown, not leaked or retained by ordinary RunOptions runs. Direct LetN/non-tail-call pushes complete frame and allocation checks before taking the caller environment, leaving no recoverable error with a by-value Frame owner outside that teardown. A normal-return retirement charge is likewise propagated only after the incoming environment and result are machine-owned. This is not a success-only reifier cleanup. Teardown uses louise_interp::release_value for that subsequent independent result and an internal machine entry for the complete state: it retains one owner per graph node, breaks mutable reference/continuation/region-storage links after queueing their contents, computes a real parent-before-child topological order and only then drops owners. Aliases discovered late therefore cannot recurse through a freed child owner; rejected closures/Arrays/Refs/Resumes/RegionOps/Ctx values use the same path. Compiler-validated direct source excludes unbroken fabricated handler cycles rather than claiming a universal arbitrary-host-object collector or leaking on a cycle. Reifier and bounded Core construction are iterative; a topological table/DAG avoids a deep nested Rust conversion chain, giant nested C expression and exponential expansion of sharing. The separate 1024-node nested-Box consumer bound remains an explicit #44 compatibility/scope decision and is not presented as protecting deep runtime-machine failure paths.

B2 diagnostics and user pipeline

E0114 remains for misplaced/duplicate/argument-bearing attributes. E0902 is invalid declaration/effect/dependency/evaluability; E0903 is direct runtime failure or fuel/frame/protocol exhaustion; E0904 is unsupported result/metadata/reification or static-output exhaustion. Aggregate limit errors identify their root and scope. The original marker span is retained; runtime errors additionally expose their structured source frames. Invalid input never yields a partial transformed Program or runtime fallback. B2 documents these codes in the reference and checks that an earlier successful root is not committed when a later root fails.

The transactional entry points evaluate_declarations_with and evaluate_declarations_for_with return Result<Program, CtfeDriverError>, where CtfeDriverError is Diagnostics(Vec<Diagnostic>) or Cancelled. Both share the one selected-or-all transaction. Only the runner's structured DirectErrorKind::Cancelled becomes driver Cancelled; it never acquires E0903/source syntax or a reconstructed wrapper. Earlier roots' neutral values and the temporary prepared/transformed Programs are dropped rather than committed. Admission, preparation, dependency scans and layout checks remain uncancellable phases before or between cooperative machine runs. The old evaluate_declarations / evaluate_declarations_for APIs delegate with &|| false and retain their diagnostic-only error shape for the compiler.

check, run, test, both testkit modes and native builds share louise_db::evaluate_comptime / louise_comptime::evaluate_declarations. Clean LSP/check analysis performs CTFE for consistent diagnostics through louise_db::semantic_diagnostics(&Db, &Analysis): the analysis database retains each root resolution's immutable lowering settings and source ownership, including its dependency sources. Ownership is the stored source FileId, including a newly opened editor source attached to the package root that Target identifies before that source exists on disk; it is never inferred from a raw source-path prefix. Source-only evaluation lowers and evaluates one selected set per root resolution with that root's std/wire.cluster_policy, never a default or last-loaded package's policy; standalone modules, including editor sources without a loaded package owner, retain the default settings. Shared dependency markers may consequently be checked once per independent root compilation. This selection API affects diagnostics only; a real compilation still evaluates and commits every declaration in one transactional session. Publication is synchronous: at most one selected analysis and CTFE session exists on the server and older diagnostics cannot overwrite a newer document. Deterministic aggregate/per-root budgets bound accepted analyses; independent root-package source analyses have independent sessions just as their real compilations do.

Open LSP cancellation/scheduling boundary for #44 review: B1 supplies the cooperative run_direct_with predicate, and B2 now actually propagates a borrowed predicate through Evaluator::evaluate_with, both transactional driver _with entries, and louise_db::{comptime_diagnostics_with,semantic_diagnostics_with}. The database entries return Result<Vec<Diagnostic>, ComptimeDiagnosticsError> with ComptimeDiagnosticsError::Cancelled; cancellation of any later root-package packet returns immediately and discards diagnostics accumulated from earlier packets, so a future mediator drops that whole candidate instead of publishing it. The borrow-only APIs mutate neither Db source/package membership nor publication metadata. Existing FIP errors still complete before any CTFE predicate is consulted.

The existing semantic_diagnostics and comptime_diagnostics Vec APIs delegate with &|| false; synchronous check, the compiler and the current LSP intentionally still call those uncancelled entries. Adding these library callbacks therefore does not let the synchronous LSP read an external cancellation notification while a root is running, and does not make parsing, lowering, preparation or already-started externs interruptible. The current implementation proves typed in-process cancellation and ordered synchronous publication, not mid-slice external LSP cancellation, a wall-clock deadline or process-resource supervision. Final admission still needs the explicitly chosen LSP scheduling and stale-result policy, with no unsafe cross-thread Val, detached analysis or stale commit. Those decisions require #44 review and cannot be substituted by a synchronous test, the runner API or B2 callback propagation alone.

Native representation and calls (B2)

Native emission reuses existing content-named literal/static-constructor helpers. Every emitted recursive-bearing object is static const, immortal (rc == 0), exactly tagged/shaped and initialized children-before-parents. Strings/Float backing definitions are immutable too. No runtime allocation or orphan-live-block accounting is needed. Existing TRMC writable context cells remain excluded. Mutation/update under Perceus must copy rather than modify a shared result; ordinary and comptime #331 RC checks remain active.

Every successful root declaration is reconstructed from its StaticValue before ordinary optimization, and Program::comptime records the neutral topological DAG by stable FnId. Ordinary interpretation keeps direct calls to these valid wrappers. In C emission, after ordinary optimization and Perceus have established and verified ownership, a proven Value::CallFn(root, [Unit]) becomes the one root static reference, not a copied constructor chain. Program::comptime is read through the existing literal/static-constructor helpers to form the immutable children-before-parents definitions, and the caller records every transitive literal dependency. The rc0 result requires no reference-count operation; the generated unit argument owns no reference. No pre- or mid-Perceus Core call substitution can invalidate its counts.

A valid ordinary wrapper reconstructed from the same StaticValue remains for function values/partial or indirect uses. Default native acceptance requires a direct static table read/no runtime constructor; splitting, debug/release, optimized/unoptimized and single/multi-unit behavior agree. The compatibility MAX_CORE_NODES == 1024 bound covers wrapper reconstruction and static-table preparation without a giant nested initializer; the existing giant-function splitter remains in force.

LOUISE_NO_STATIC_CTORS is an emergency representation-only switch, not an evaluator switch: it keeps ordinary calls to the reconstructed wrappers and lets the existing runtime-construction representation rebuild their ordinary Core values. Default static acceptance evidence is still mandatory.

Consequences and review boundaries

B1 adds louise_comptime, depending on Core/HIR/types/interpreter but neither louise_build, louise_db nor C codegen. This preserves dependency direction: native emission consumes neutral static data and never invokes the interpreter. The new crate and its sole workspace-lock entry are part of that review. C1 consumes only run_value_map; B2 consumes runner, layouts, reifier, session and Core reconstruction on the same signed-off B1 SHA. No issue closes from B1.