aver/ast/mod.rs
1pub mod types;
2pub use types::Type;
3
4/// Source line number (1-based). 0 = synthetic/unknown.
5pub type SourceLine = usize;
6
7/// A `bool` that compares as always-equal. Used for `last_use` annotations
8/// on `Expr::Resolved` — metadata that should not affect AST equality
9/// (same pattern as `Spanned` ignoring `line` in its `PartialEq`).
10#[derive(Debug, Clone, Copy, Default)]
11pub struct AnnotBool(pub bool);
12
13impl PartialEq for AnnotBool {
14 fn eq(&self, _: &Self) -> bool {
15 true
16 }
17}
18
19impl From<bool> for AnnotBool {
20 fn from(b: bool) -> Self {
21 Self(b)
22 }
23}
24
25/// AST node with source location plus an optional inferred type.
26///
27/// Line-agnostic equality: two `Spanned` values are equal iff their inner
28/// nodes are equal, regardless of line or attached type. The type slot is a
29/// `OnceLock<Type>` populated by the type checker; backends that have not
30/// been migrated to consume it stay agnostic and continue inferring locally.
31/// `OnceLock` (rather than `OnceCell`) keeps `Spanned` `Sync`, which matters
32/// because parts of the AST live behind `Arc` and cross thread boundaries
33/// (e.g. parallel verify execution, REPL background tasks).
34#[derive(Debug)]
35pub struct Spanned<T> {
36 pub node: T,
37 pub line: SourceLine,
38 pub ty: std::sync::OnceLock<Type>,
39}
40
41// `OnceLock` does not derive `Clone` (the cell is invariant over `T`), so the
42// inner type is cloned manually.
43impl<T: Clone> Clone for Spanned<T> {
44 fn clone(&self) -> Self {
45 let ty = std::sync::OnceLock::new();
46 if let Some(t) = self.ty.get() {
47 let _ = ty.set(t.clone());
48 }
49 Self {
50 node: self.node.clone(),
51 line: self.line,
52 ty,
53 }
54 }
55}
56
57impl<T: PartialEq> PartialEq for Spanned<T> {
58 fn eq(&self, other: &Self) -> bool {
59 self.node == other.node
60 }
61}
62
63impl<T> Spanned<T> {
64 pub fn new(node: T, line: SourceLine) -> Self {
65 Self {
66 node,
67 line,
68 ty: std::sync::OnceLock::new(),
69 }
70 }
71
72 /// Create a Spanned with line=0 (synthetic/generated AST, no source location).
73 pub fn bare(node: T) -> Self {
74 Self::new(node, 0)
75 }
76
77 /// Record the inferred type for this node. No-op if a type is already set
78 /// (later inference passes must not contradict the first one).
79 pub fn set_ty(&self, ty: Type) {
80 let _ = self.ty.set(ty);
81 }
82
83 /// Inferred type for this node, if the type checker has visited it.
84 pub fn ty(&self) -> Option<&Type> {
85 self.ty.get()
86 }
87}
88
89#[derive(Debug, Clone, PartialEq)]
90pub enum Literal {
91 Int(i64),
92 Float(f64),
93 Str(String),
94 Bool(bool),
95 Unit,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub enum BinOp {
100 Add,
101 Sub,
102 Mul,
103 Div,
104 Eq,
105 Neq,
106 Lt,
107 Gt,
108 Lte,
109 Gte,
110}
111
112#[derive(Debug)]
113pub struct MatchArm {
114 pub pattern: Pattern,
115 pub body: Box<Spanned<Expr>>,
116 /// Per-arm slot table for the pattern's bindings, in pattern order.
117 /// Filled by the resolver pass; backend code reads from here
118 /// instead of doing a name lookup, so two arms with the same
119 /// binding name (e.g. `deadline` showing up in both `TaskCreated`
120 /// and `DeadlineSet` with different field types) get separate
121 /// slots without colliding in the function-level slot table.
122 /// Wildcard-position bindings (`_`) are stored as `u16::MAX` and
123 /// must never be read.
124 pub binding_slots: std::sync::OnceLock<Vec<u16>>,
125}
126
127// `OnceLock` doesn't derive Clone (cell is invariant over T); copy
128// the inner manually so the resolver's allocations survive the
129// `Arc::make_mut` clones that happen during multimodule flatten.
130impl Clone for MatchArm {
131 fn clone(&self) -> Self {
132 let binding_slots = std::sync::OnceLock::new();
133 if let Some(v) = self.binding_slots.get() {
134 let _ = binding_slots.set(v.clone());
135 }
136 Self {
137 pattern: self.pattern.clone(),
138 body: self.body.clone(),
139 binding_slots,
140 }
141 }
142}
143
144impl PartialEq for MatchArm {
145 fn eq(&self, other: &Self) -> bool {
146 self.pattern == other.pattern && self.body == other.body
147 }
148}
149
150impl MatchArm {
151 /// Build a fresh arm with no binding-slot stamp yet — resolver
152 /// fills `binding_slots` after slot allocation. Use this from any
153 /// site that synthesises an arm (parser, AST rewrites, effect
154 /// lifting, tests).
155 pub fn new(pattern: Pattern, body: Spanned<Expr>) -> Self {
156 Self {
157 pattern,
158 body: Box::new(body),
159 binding_slots: std::sync::OnceLock::new(),
160 }
161 }
162
163 pub fn new_boxed(pattern: Pattern, body: Box<Spanned<Expr>>) -> Self {
164 Self {
165 pattern,
166 body,
167 binding_slots: std::sync::OnceLock::new(),
168 }
169 }
170}
171
172#[derive(Debug, Clone, PartialEq)]
173pub enum Pattern {
174 Wildcard,
175 Literal(Literal),
176 Ident(String),
177 /// Empty list pattern: `[]`
178 EmptyList,
179 /// Cons-like list pattern: `[head, ..tail]`
180 Cons(String, String),
181 /// Tuple pattern: `(a, b)` / `(_, x)` / nested tuples.
182 Tuple(Vec<Pattern>),
183 /// Constructor pattern: fully-qualified name + list of binding names.
184 /// Built-ins: Result.Ok(x), Result.Err(x), Option.Some(x), Option.None.
185 /// User-defined: Shape.Circle(r), Shape.Rect(w, h), Shape.Point.
186 Constructor(String, Vec<String>),
187}
188
189#[derive(Debug, Clone, PartialEq)]
190pub enum StrPart {
191 Literal(String),
192 Parsed(Box<Spanned<Expr>>),
193}
194
195/// Data for a tail-call expression.
196#[derive(Debug, Clone, PartialEq)]
197pub struct TailCallData {
198 /// Target function name (self or mutual-recursive peer).
199 pub target: String,
200 /// Arguments to pass.
201 pub args: Vec<Spanned<Expr>>,
202}
203
204impl TailCallData {
205 pub fn new(target: String, args: Vec<Spanned<Expr>>) -> Self {
206 Self { target, args }
207 }
208}
209
210#[derive(Debug, Clone, PartialEq)]
211pub enum Expr {
212 Literal(Literal),
213 Ident(String),
214 Attr(Box<Spanned<Expr>>, String),
215 FnCall(Box<Spanned<Expr>>, Vec<Spanned<Expr>>),
216 BinOp(BinOp, Box<Spanned<Expr>>, Box<Spanned<Expr>>),
217 /// Unary numeric negation: `-x`. Operand must be numeric (`Int` or
218 /// `Float`); result is the same type. Used to be desugared in the
219 /// parser to `BinOp(Sub, Literal(Int(0)), x)`, which loses the IEEE
220 /// `-0.0` sign bit on `Float` operands and produces an `Int`/`Float`
221 /// mixed `BinOp` that backends had to recognise with pattern hacks.
222 Neg(Box<Spanned<Expr>>),
223 Match {
224 subject: Box<Spanned<Expr>>,
225 arms: Vec<MatchArm>,
226 },
227 Constructor(String, Option<Box<Spanned<Expr>>>),
228 ErrorProp(Box<Spanned<Expr>>),
229 InterpolatedStr(Vec<StrPart>),
230 List(Vec<Spanned<Expr>>),
231 Tuple(Vec<Spanned<Expr>>),
232 /// Map literal: `{"a" => 1, "b" => 2}`
233 MapLiteral(Vec<(Spanned<Expr>, Spanned<Expr>)>),
234 /// Record creation: `User(name = "Alice", age = 30)`
235 RecordCreate {
236 type_name: String,
237 fields: Vec<(String, Spanned<Expr>)>,
238 },
239 /// Record update: `User.update(base, field = newVal, ...)`
240 RecordUpdate {
241 type_name: String,
242 base: Box<Spanned<Expr>>,
243 updates: Vec<(String, Spanned<Expr>)>,
244 },
245 /// Tail-position call to a function in the same SCC (self or mutual recursion).
246 /// Produced by the TCO transform pass before type-checking.
247 /// Reuse info is populated by `ir::reuse::annotate_program_reuse`.
248 TailCall(Box<TailCallData>),
249 /// Independent product: `(a, b, c)!` or `(a, b, c)?!`.
250 /// Elements are independent effectful expressions evaluated with no guaranteed order.
251 /// `unwrap=true` (`?!`): all elements must be Result; unwraps Ok values, propagates first Err.
252 /// `unwrap=false` (`!`): returns raw tuple of results.
253 /// Produces a replay group (effects matched by branch_path + effect_occurrence + type + args).
254 IndependentProduct(Vec<Spanned<Expr>>, bool),
255 /// Compiled variable lookup: `env[last][slot]` — O(1) instead of HashMap scan.
256 /// Produced by the resolver pass for locals inside function bodies.
257 /// `last_use` is set by `ir::last_use` — when true, this is the final
258 /// reference to this slot and backends can move instead of copy.
259 Resolved {
260 slot: u16,
261 name: String,
262 last_use: AnnotBool,
263 },
264}
265
266#[derive(Debug, Clone, PartialEq)]
267pub enum Stmt {
268 Binding(String, Option<String>, Spanned<Expr>),
269 Expr(Spanned<Expr>),
270}
271
272#[derive(Debug, Clone, PartialEq)]
273pub enum FnBody {
274 Block(Vec<Stmt>),
275}
276
277impl FnBody {
278 pub fn from_expr(expr: Spanned<Expr>) -> Self {
279 Self::Block(vec![Stmt::Expr(expr)])
280 }
281
282 pub fn stmts(&self) -> &[Stmt] {
283 match self {
284 Self::Block(stmts) => stmts,
285 }
286 }
287
288 pub fn stmts_mut(&mut self) -> &mut Vec<Stmt> {
289 match self {
290 Self::Block(stmts) => stmts,
291 }
292 }
293
294 pub fn tail_expr(&self) -> Option<&Spanned<Expr>> {
295 match self.stmts().last() {
296 Some(Stmt::Expr(expr)) => Some(expr),
297 _ => None,
298 }
299 }
300
301 pub fn tail_expr_mut(&mut self) -> Option<&mut Spanned<Expr>> {
302 match self.stmts_mut().last_mut() {
303 Some(Stmt::Expr(expr)) => Some(expr),
304 _ => None,
305 }
306 }
307}
308
309/// Compile-time resolution metadata for a function body.
310/// Produced by `resolver::resolve_fn` — maps local variable names to slot indices
311/// so the VM can use `Vec<Value>` instead of `HashMap` lookups.
312#[derive(Debug, Clone, PartialEq)]
313pub struct FnResolution {
314 /// Total number of local slots needed (params + bindings in body).
315 pub local_count: u16,
316 /// Map from local variable name → slot index in the local `Slots` frame.
317 pub local_slots: std::sync::Arc<std::collections::HashMap<String, u16>>,
318 /// Aver type per slot index. Length == `local_count`. Built post-
319 /// typecheck so each entry pulls from the matching `Spanned::ty()`
320 /// stamp on the producer expression, plus pattern-binding shape
321 /// rules (`Result.Ok` → T, `Cons head` → list element, tuple item
322 /// → tuple element, …). Backends that need a typed local table
323 /// (the wasm-gc lowering uses one to declare each `local` with a
324 /// concrete `ValType`) consume this directly instead of re-deriving
325 /// the same information from patterns.
326 ///
327 /// Default `Type::Invalid` for unreachable / unstamped slots — every
328 /// real binding gets overwritten during the slot-types pass, so an
329 /// `Invalid` reaching the backend means the slot was never the
330 /// target of a binding (resolver counted but no expression
331 /// produced into it; usually a wildcard slot the backend skips).
332 pub local_slot_types: std::sync::Arc<Vec<Type>>,
333 /// Whether each slot may share an arena entry with another slot.
334 /// Length == `local_count`. Set by `ir::alias::annotate_program_alias_slots`
335 /// post-`last_use`. Backends that have a `mem::take`-style fast path
336 /// for `Vector.set` / `Map.set` (the VM's `CALL_BUILTIN_OWNED` mask
337 /// plus the fused `VECTOR_SET_OR_KEEP`) must NOT take the fast path
338 /// on a flagged slot — rewriting the shared arena entry would
339 /// mutate the other binding too. Wasm-gc may use it to skip
340 /// clone-on-write when the slot is provably non-aliased; otherwise
341 /// it falls back to `array.copy` + `array.set` on the copy.
342 ///
343 /// Default `false` for slots the analysis hasn't reached (anything
344 /// pre-`last_use`, REPL, partial pipelines), which is the safe-but-
345 /// slow choice everywhere except the VM fast path.
346 pub aliased_slots: std::sync::Arc<Vec<bool>>,
347}
348
349#[derive(Debug, Clone, PartialEq)]
350pub struct FnDef {
351 pub name: String,
352 pub line: usize,
353 pub params: Vec<(String, String)>,
354 pub return_type: String,
355 pub effects: Vec<Spanned<String>>,
356 pub desc: Option<String>,
357 pub body: std::sync::Arc<FnBody>,
358 /// `None` for unresolved (REPL, module loading).
359 pub resolution: Option<FnResolution>,
360}
361
362#[derive(Debug, Clone, PartialEq)]
363pub struct Module {
364 pub name: String,
365 pub line: usize,
366 pub depends: Vec<String>,
367 pub exposes: Vec<String>,
368 pub exposes_opaque: Vec<String>,
369 pub exposes_line: Option<usize>,
370 pub intent: String,
371 /// Module-level effect surface declaration. `None` is legacy/mixed
372 /// (no enforcement, soft warning emitted by `aver check`); `Some([])`
373 /// is explicit pure; `Some([...])` is a declared boundary — every
374 /// function's `! [...]` must be a subset (namespace-level entry like
375 /// `Disk` admits any `Disk.*` method).
376 pub effects: Option<Vec<String>>,
377 pub effects_line: Option<usize>,
378}
379
380#[derive(Debug, Clone, PartialEq)]
381pub enum VerifyGivenDomain {
382 /// Integer range domain in verify law: `1..50` (inclusive).
383 IntRange { start: i64, end: i64 },
384 /// Explicit domain values in verify law: `[v1, v2, ...]`.
385 Explicit(Vec<Spanned<Expr>>),
386}
387
388#[derive(Debug, Clone, PartialEq)]
389pub struct VerifyGiven {
390 pub name: String,
391 pub type_name: String,
392 pub domain: VerifyGivenDomain,
393}
394
395#[derive(Debug, Clone, PartialEq)]
396pub struct VerifyLaw {
397 pub name: String,
398 pub givens: Vec<VerifyGiven>,
399 /// Optional precondition for the law template, written as `when <bool-expr>`.
400 pub when: Option<Spanned<Expr>>,
401 /// Template assertion from source before given-domain expansion.
402 pub lhs: Spanned<Expr>,
403 pub rhs: Spanned<Expr>,
404 /// Per-sample substituted guards for `when`, aligned with `VerifyBlock.cases`.
405 pub sample_guards: Vec<Spanned<Expr>>,
406}
407
408/// Source range for AST nodes that need location tracking.
409/// Used by verify case spans: `cases[i] <-> case_spans[i]`.
410#[derive(Debug, Clone, PartialEq, Default)]
411pub struct SourceSpan {
412 pub line: usize,
413 pub col: usize,
414 pub end_line: usize,
415 pub end_col: usize,
416}
417
418#[derive(Debug, Clone, PartialEq)]
419pub enum VerifyKind {
420 Cases,
421 Law(Box<VerifyLaw>),
422}
423
424#[derive(Debug, Clone, PartialEq)]
425pub struct VerifyBlock {
426 pub fn_name: String,
427 pub line: usize,
428 pub cases: Vec<(Spanned<Expr>, Spanned<Expr>)>,
429 pub case_spans: Vec<SourceSpan>,
430 /// Per-case given bindings for law verify (empty for Cases kind).
431 pub case_givens: Vec<Vec<(String, Spanned<Expr>)>>,
432 /// Parallel to `cases`: `true` when the case was injected by
433 /// `aver verify --hostile` (boundary-value expansion of a law's
434 /// `given` clause), `false` for cases the user wrote directly.
435 /// Empty under non-hostile runs; the renderer uses this to label
436 /// failures as "outside declared given — encode as `when` if
437 /// precondition" when they only fail under the hostile expansion.
438 pub case_hostile_origins: Vec<bool>,
439 /// Parallel to `cases`: per-case hostile effect-profile assignment
440 /// for `--hostile` mode. Each inner Vec lists `(method, profile)`
441 /// pairs (e.g. `("Time.now", "frozen")`) that the runner installs
442 /// as oracle stubs before running the case, alongside any user-given
443 /// stubs. Empty inner Vec for cases that aren't effect-hostile-
444 /// expanded (declared, value-hostile-only, or fns without applicable
445 /// classified effects). All entries empty under non-hostile runs.
446 pub case_hostile_profiles: Vec<Vec<(String, String)>>,
447 /// Parallel to `cases`: `true` when `aver verify --hostile` has
448 /// injected a reverse-order twin of an earlier case. The twin
449 /// shares LHS/RHS/given/profile with its forward sibling — only
450 /// the execution order of independent-product branches
451 /// (`(a, b)!` lowers to `CALL_PAR`) is flipped. A pure law claims
452 /// its branches are independent, so the twin must produce the
453 /// same result; divergence proves the claim doesn't hold under
454 /// the stub map and surfaces as `verify-hostile-order-mismatch`.
455 /// All entries `false` under non-hostile runs.
456 pub case_reverse_order: Vec<bool>,
457 pub kind: VerifyKind,
458 /// Oracle v1: `trace` keyword enables trace-aware assertions
459 /// (`.trace.*`, `.result`, event literals in `.contains` / match
460 /// patterns). Without it, a law checks only the return value, so
461 /// adding a debug print does not break proofs that do not care
462 /// about traces.
463 pub trace: bool,
464 /// Oracle v1: `given` clauses declared at the top of a cases-form
465 /// trace block. Law-form stores its givens inside `VerifyKind::Law`;
466 /// cases-form doesn't have that wrapper, so this field carries them
467 /// so the verify runner can build oracle-stub mappings from the
468 /// same data. Empty for non-trace or law-form blocks.
469 pub cases_givens: Vec<VerifyGiven>,
470}
471
472impl VerifyBlock {
473 /// Construct a VerifyBlock with default (zero) spans for each case.
474 /// Use when source location tracking is not needed (codegen, tests).
475 pub fn new_unspanned(
476 fn_name: String,
477 line: usize,
478 cases: Vec<(Spanned<Expr>, Spanned<Expr>)>,
479 kind: VerifyKind,
480 ) -> Self {
481 let case_spans = vec![SourceSpan::default(); cases.len()];
482 let case_hostile_origins = vec![false; cases.len()];
483 let case_hostile_profiles = vec![Vec::new(); cases.len()];
484 let case_reverse_order = vec![false; cases.len()];
485 Self {
486 fn_name,
487 line,
488 cases,
489 case_spans,
490 case_givens: vec![],
491 case_hostile_origins,
492 case_hostile_profiles,
493 case_reverse_order,
494 kind,
495 trace: false,
496 cases_givens: vec![],
497 }
498 }
499
500 pub fn iter_cases_with_spans(
501 &self,
502 ) -> impl Iterator<Item = (&(Spanned<Expr>, Spanned<Expr>), &SourceSpan)> {
503 debug_assert_eq!(self.cases.len(), self.case_spans.len());
504 self.cases.iter().zip(&self.case_spans)
505 }
506}
507
508#[derive(Debug, Clone, PartialEq)]
509pub struct DecisionBlock {
510 pub name: String,
511 pub line: usize,
512 pub date: String,
513 pub reason: String,
514 pub chosen: Spanned<DecisionImpact>,
515 pub rejected: Vec<Spanned<DecisionImpact>>,
516 pub impacts: Vec<Spanned<DecisionImpact>>,
517 pub author: Option<String>,
518}
519
520#[derive(Debug, Clone, PartialEq, Eq, Hash)]
521pub enum DecisionImpact {
522 Symbol(String),
523 Semantic(String),
524}
525
526impl DecisionImpact {
527 pub fn text(&self) -> &str {
528 match self {
529 DecisionImpact::Symbol(s) | DecisionImpact::Semantic(s) => s,
530 }
531 }
532
533 pub fn as_context_string(&self) -> String {
534 match self {
535 DecisionImpact::Symbol(s) => s.clone(),
536 DecisionImpact::Semantic(s) => format!("\"{}\"", s),
537 }
538 }
539}
540
541/// A variant in a sum type definition.
542/// e.g. `Circle(Float)` → `TypeVariant { name: "Circle", fields: ["Float"] }`
543#[derive(Debug, Clone, PartialEq)]
544pub struct TypeVariant {
545 pub name: String,
546 pub fields: Vec<String>, // type annotations (e.g. "Float", "String")
547}
548
549/// A user-defined type definition.
550#[derive(Debug, Clone, PartialEq)]
551pub enum TypeDef {
552 /// `type Shape` with variants Circle(Float), Rect(Float, Float), Point
553 Sum {
554 name: String,
555 variants: Vec<TypeVariant>,
556 line: usize,
557 },
558 /// `record User` with fields name: String, age: Int
559 Product {
560 name: String,
561 fields: Vec<(String, String)>,
562 line: usize,
563 },
564}
565
566#[derive(Debug, Clone, PartialEq)]
567pub enum TopLevel {
568 Module(Module),
569 FnDef(FnDef),
570 Verify(VerifyBlock),
571 Decision(DecisionBlock),
572 Stmt(Stmt),
573 TypeDef(TypeDef),
574}