Skip to main content

harn_parser/
ast.rs

1use harn_lexer::{Span, StringSegment};
2
3/// A node wrapped with source location information.
4#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
5pub struct Spanned<T> {
6    pub node: T,
7    pub span: Span,
8}
9
10impl<T> Spanned<T> {
11    pub fn new(node: T, span: Span) -> Self {
12        Self { node, span }
13    }
14
15    pub fn dummy(node: T) -> Self {
16        Self {
17            node,
18            span: Span::dummy(),
19        }
20    }
21}
22
23/// A spanned AST node — the primary unit throughout the compiler.
24pub type SNode = Spanned<Node>;
25
26/// Helper to wrap a node with a span.
27pub fn spanned(node: Node, span: Span) -> SNode {
28    SNode::new(node, span)
29}
30
31/// If `node` is an `AttributedDecl`, returns `(attrs, inner)`; otherwise
32/// returns an empty attribute slice and the node itself. Use at the top
33/// of any consumer that processes top-level statements so attributes
34/// flow through transparently.
35pub fn peel_attributes(node: &SNode) -> (&[Attribute], &SNode) {
36    match &node.node {
37        Node::AttributedDecl { attributes, inner } => (attributes.as_slice(), inner.as_ref()),
38        _ => (&[], node),
39    }
40}
41
42/// A single argument to an attribute. Positional args have `name = None`;
43/// named args use `name: Some("key")`. Values are restricted to
44/// compile-time metadata expressions by the parser (literal scalars,
45/// identifiers, lists, dicts, and call-shaped sentinels).
46#[derive(Debug, Clone, PartialEq, serde::Serialize)]
47pub struct AttributeArg {
48    pub name: Option<String>,
49    pub value: SNode,
50    pub span: Span,
51}
52
53/// An attribute attached to a declaration: `@deprecated(since: "0.8")`.
54#[derive(Debug, Clone, PartialEq, serde::Serialize)]
55pub struct Attribute {
56    pub name: String,
57    pub args: Vec<AttributeArg>,
58    pub span: Span,
59}
60
61impl Attribute {
62    /// Find a named argument by key.
63    pub fn named_arg(&self, key: &str) -> Option<&SNode> {
64        self.args
65            .iter()
66            .find(|a| a.name.as_deref() == Some(key))
67            .map(|a| &a.value)
68    }
69
70    /// First positional argument, if any.
71    pub fn positional(&self, idx: usize) -> Option<&SNode> {
72        self.args
73            .iter()
74            .filter(|a| a.name.is_none())
75            .nth(idx)
76            .map(|a| &a.value)
77    }
78
79    /// Convenience: extract a string-literal arg by name.
80    pub fn string_arg(&self, key: &str) -> Option<String> {
81        match self.named_arg(key).map(|n| &n.node) {
82            Some(Node::StringLiteral(s)) => Some(s.clone()),
83            Some(Node::RawStringLiteral(s)) => Some(s.clone()),
84            _ => None,
85        }
86    }
87}
88
89/// AST nodes for the Harn language.
90#[derive(Debug, Clone, PartialEq, serde::Serialize)]
91pub enum Node {
92    /// A declaration carrying one or more attributes (`@attr`). The inner
93    /// node is always one of: FnDecl, ToolDecl, Pipeline, StructDecl,
94    /// EnumDecl, TypeDecl, InterfaceDecl, ImplBlock.
95    AttributedDecl {
96        attributes: Vec<Attribute>,
97        inner: Box<SNode>,
98    },
99    Pipeline {
100        name: String,
101        params: Vec<TypedParam>,
102        return_type: Option<TypeExpr>,
103        /// Declared exception channel: `throws E` / `throws (E1 | E2)`, parsed
104        /// as a single [`TypeExpr`] (a `throws (E1 | E2)` clause is a
105        /// [`TypeExpr::Union`]). `None` leaves the callable's thrown-type set
106        /// unconstrained — the historical default, so the annotation is purely
107        /// additive and no existing code is forced to declare it.
108        throws: Option<TypeExpr>,
109        body: Vec<SNode>,
110        extends: Option<String>,
111        is_pub: bool,
112    },
113    /// `let PATTERN [: Type] = EXPR` — a **mutable** binding (reassignable).
114    ///
115    /// This is the TypeScript-aligned `let`: a normal block-scoped mutable
116    /// variable. (Before the const/let keyword re-platform, `let` was
117    /// immutable and `var` was the mutable form; `var` has been removed and
118    /// its mutable role is now `let`.)
119    LetBinding {
120        pattern: BindingPattern,
121        type_ann: Option<TypeExpr>,
122        value: Box<SNode>,
123        /// `true` for a top-level `pub let` — the binding's value is exported
124        /// as part of the module's public surface (bound by value in
125        /// importers, like every other cross-module value). Always `false` for
126        /// block-scoped bindings.
127        is_pub: bool,
128    },
129    /// `const PATTERN [: Type] = EXPR` — an **immutable** binding.
130    ///
131    /// The TypeScript-aligned `const`: the default, immutable binding form
132    /// (reassignment is rejected). When the initializer falls in the pure,
133    /// bounded const-eval subset (literal arithmetic, string concat, literal
134    /// lists/dicts, ternaries, reads of earlier `const` identifiers, and a
135    /// allowlist of pure builtins) it is **folded at compile time** via
136    /// `harn_parser::const_eval`; otherwise it is an ordinary immutable
137    /// runtime binding. Unlike the pre-re-platform `const`, an impure
138    /// initializer is *not* an error (it simply is not folded), and a
139    /// destructuring `pattern` is permitted (only a plain identifier pattern
140    /// is eligible for folding). At runtime a folded binding re-evaluates the
141    /// same expression so the value matches the compile-time fold byte-for-byte.
142    ConstBinding {
143        pattern: BindingPattern,
144        type_ann: Option<TypeExpr>,
145        value: Box<SNode>,
146        /// `true` for a top-level `pub const` — the (compile-time-folded or
147        /// runtime) value is exported as part of the module's public surface.
148        /// Always `false` for block-scoped bindings.
149        is_pub: bool,
150    },
151    OverrideDecl {
152        name: String,
153        params: Vec<String>,
154        body: Vec<SNode>,
155    },
156    ImportDecl {
157        path: String,
158        /// When true, the wildcard import is a re-export: every public symbol
159        /// from the target module becomes part of this module's public surface.
160        is_pub: bool,
161    },
162    /// Selective import: import { foo, bar } from "module"
163    SelectiveImport {
164        names: Vec<String>,
165        path: String,
166        /// When true, the listed names are re-exported as part of this
167        /// module's public surface.
168        is_pub: bool,
169    },
170    EnumDecl {
171        name: String,
172        type_params: Vec<TypeParam>,
173        variants: Vec<EnumVariant>,
174        is_pub: bool,
175    },
176    StructDecl {
177        name: String,
178        type_params: Vec<TypeParam>,
179        fields: Vec<StructField>,
180        is_pub: bool,
181    },
182    InterfaceDecl {
183        name: String,
184        type_params: Vec<TypeParam>,
185        associated_types: Vec<AssociatedType>,
186        methods: Vec<InterfaceMethod>,
187    },
188    /// Impl block: impl TypeName { fn method(self, ...) { ... } ... }
189    ImplBlock {
190        type_name: String,
191        methods: Vec<SNode>,
192    },
193
194    IfElse {
195        condition: Box<SNode>,
196        then_body: Vec<SNode>,
197        /// Source extent of the `then` block, including its braces.
198        then_span: Span,
199        else_body: Option<Vec<SNode>>,
200        /// Source extent of a braced `else` block, including its braces.
201        /// `None` identifies the synthetic wrapper used for `else if`.
202        else_span: Option<Span>,
203    },
204    ForIn {
205        pattern: BindingPattern,
206        iterable: Box<SNode>,
207        body: Vec<SNode>,
208    },
209    MatchExpr {
210        value: Box<SNode>,
211        arms: Vec<MatchArm>,
212    },
213    WhileLoop {
214        condition: Box<SNode>,
215        body: Vec<SNode>,
216    },
217    Retry {
218        count: Box<SNode>,
219        body: Vec<SNode>,
220    },
221    /// Scoped cost-aware LLM routing block:
222    /// `cost_route { key: value ... body }`.
223    ///
224    /// Options are inherited by nested `llm_call` invocations unless a
225    /// call explicitly overrides the same option.
226    CostRoute {
227        options: Vec<(String, SNode)>,
228        body: Vec<SNode>,
229    },
230    ReturnStmt {
231        value: Option<Box<SNode>>,
232    },
233    TryCatch {
234        body: Vec<SNode>,
235        /// Source extent of the `try` block, including its braces.
236        try_span: Span,
237        has_catch: bool,
238        error_var: Option<String>,
239        error_type: Option<TypeExpr>,
240        catch_body: Vec<SNode>,
241        /// Source extent of the `catch` block, including its braces.
242        catch_span: Option<Span>,
243        finally_body: Option<Vec<SNode>>,
244        /// Source extent of the `finally` block, including its braces.
245        finally_span: Option<Span>,
246    },
247    /// Try expression: try { body } — returns Result.Ok(value), an existing Result,
248    /// or Result.Err(error).
249    TryExpr {
250        body: Vec<SNode>,
251    },
252    FnDecl {
253        name: String,
254        type_params: Vec<TypeParam>,
255        params: Vec<TypedParam>,
256        return_type: Option<TypeExpr>,
257        /// Declared exception channel `throws E` / `throws (E1 | E2)`; see the
258        /// [`Node::Pipeline`] `throws` field. `None` = unconstrained.
259        throws: Option<TypeExpr>,
260        where_clauses: Vec<WhereClause>,
261        body: Vec<SNode>,
262        is_pub: bool,
263        is_stream: bool,
264    },
265    ToolDecl {
266        name: String,
267        description: Option<String>,
268        params: Vec<TypedParam>,
269        return_type: Option<TypeExpr>,
270        /// Declared exception channel; see the [`Node::Pipeline`] `throws`
271        /// field. `None` = unconstrained.
272        throws: Option<TypeExpr>,
273        body: Vec<SNode>,
274        is_pub: bool,
275    },
276    /// Top-level `skill NAME { ... }` declaration.
277    ///
278    /// Skills bundle metadata, tool references, MCP server lists, and
279    /// optional lifecycle hooks into a typed unit. Each body entry is a
280    /// `<field_name> <expression>` pair; the compiler lowers the decl to
281    /// `skill_define(skill_registry(), NAME, { field: expr, ... })` and
282    /// binds the resulting registry dict to `NAME`.
283    SkillDecl {
284        name: String,
285        fields: Vec<(String, SNode)>,
286        is_pub: bool,
287    },
288    /// Top-level `eval_pack NAME_OR_STRING { ... }` declaration.
289    ///
290    /// The compiler lowers fields into `eval_pack_manifest({ ... })` and
291    /// binds the normalized manifest to `binding_name`. Optional executable
292    /// body statements are only run when the declaration itself is executed
293    /// in script/block position; top-level pipeline preloading registers the
294    /// manifest data without running the body.
295    EvalPackDecl {
296        binding_name: String,
297        pack_id: String,
298        fields: Vec<(String, SNode)>,
299        body: Vec<SNode>,
300        summarize: Option<Vec<SNode>>,
301        is_pub: bool,
302    },
303    TypeDecl {
304        name: String,
305        type_params: Vec<TypeParam>,
306        type_expr: TypeExpr,
307        is_pub: bool,
308    },
309    SpawnExpr {
310        body: Vec<SNode>,
311    },
312    /// Structured-concurrency nursery: `scope { ... }`. Tasks spawned while this
313    /// block is on the task-scope stack are joined when the block exits — the
314    /// first task error cancels its siblings and propagates out of the block, so
315    /// no spawned task is orphaned or has its error silently swallowed.
316    ScopeBlock {
317        body: Vec<SNode>,
318    },
319    /// Duration literal: 500ms, 5s, 30m, 2h, 1d, 1w
320    DurationLiteral(u64),
321    /// Range expression: `start to end` (inclusive) or `start to end exclusive` (half-open)
322    RangeExpr {
323        start: Box<SNode>,
324        end: Box<SNode>,
325        inclusive: bool,
326    },
327    /// Guard clause: guard condition else { body }
328    GuardStmt {
329        condition: Box<SNode>,
330        else_body: Vec<SNode>,
331    },
332    RequireStmt {
333        condition: Box<SNode>,
334        message: Option<Box<SNode>>,
335    },
336    /// Defer statement: defer { body } — runs body at scope exit.
337    DeferStmt {
338        body: Vec<SNode>,
339    },
340    /// Deadline block: deadline DURATION { body }
341    DeadlineBlock {
342        duration: Box<SNode>,
343        body: Vec<SNode>,
344    },
345    /// Yield expression: yields control to host, optionally with a value.
346    YieldExpr {
347        value: Option<Box<SNode>>,
348    },
349    /// Emit expression: emits one value from a `gen fn` stream.
350    EmitExpr {
351        value: Box<SNode>,
352    },
353    /// Mutex block: mutual exclusion for concurrent access.
354    ///
355    /// `key` is the optional resource expression in `mutex(resource) { ... }`.
356    /// When present, all blocks acquiring the same structural key value
357    /// mutually exclude; when absent (`mutex { ... }`), the block keys on its
358    /// own lexical call-site, so two distinct `mutex {}` blocks no longer
359    /// serialize against each other.
360    MutexBlock {
361        key: Option<Box<SNode>>,
362        body: Vec<SNode>,
363    },
364    /// Break out of a loop.
365    BreakStmt,
366    /// Continue to next loop iteration.
367    ContinueStmt,
368
369    /// First-class HITL primitive expression.
370    ///
371    /// Lexed as a reserved keyword (`request_approval`, `dual_control`,
372    /// `ask_user`, `escalate_to`), parsed at primary-expression position
373    /// as `keyword "(" args ")"`. Each arg is either positional
374    /// (`expr`) or named (`name: expr`).
375    ///
376    /// The compiler lowers this to a call to the matching async stdlib
377    /// builtin in `crates/harn-vm/src/stdlib/hitl.rs`, packaging the
378    /// named arguments into the existing options-dict shape. The
379    /// typechecker assigns each kind its canonical envelope return type.
380    HitlExpr {
381        kind: HitlKind,
382        args: Vec<HitlArg>,
383    },
384
385    Parallel {
386        mode: ParallelMode,
387        /// For Count mode: the count expression. For Each/Settle: the list expression.
388        expr: Box<SNode>,
389        variable: Option<String>,
390        body: Vec<SNode>,
391        /// Optional trailing `with { max_concurrent: N, ... }` option block.
392        /// A vec (rather than a dict) preserves source order for error
393        /// reporting and keeps parsing cheap. Only `max_concurrent` is
394        /// currently honored; unknown keys are rejected by the parser.
395        options: Vec<(String, SNode)>,
396    },
397
398    SelectExpr {
399        cases: Vec<SelectCase>,
400        timeout: Option<(Box<SNode>, Vec<SNode>)>,
401        default_body: Option<Vec<SNode>>,
402    },
403
404    FunctionCall {
405        name: String,
406        type_args: Vec<TypeExpr>,
407        args: Vec<SNode>,
408    },
409    /// A postfix call whose callee is an expression result: `make()(arg)`.
410    ValueCall {
411        callee: Box<SNode>,
412        args: Vec<SNode>,
413    },
414    MethodCall {
415        object: Box<SNode>,
416        method: String,
417        args: Vec<SNode>,
418    },
419    /// Optional method call: `obj?.method(args)` — returns nil if obj is nil.
420    OptionalMethodCall {
421        object: Box<SNode>,
422        method: String,
423        args: Vec<SNode>,
424    },
425    PropertyAccess {
426        object: Box<SNode>,
427        property: String,
428    },
429    /// Optional chaining: `obj?.property` — returns nil if obj is nil.
430    OptionalPropertyAccess {
431        object: Box<SNode>,
432        property: String,
433    },
434    SubscriptAccess {
435        object: Box<SNode>,
436        index: Box<SNode>,
437    },
438    /// Optional subscript: `obj?.[index]` — returns nil if obj is nil.
439    OptionalSubscriptAccess {
440        object: Box<SNode>,
441        index: Box<SNode>,
442    },
443    SliceAccess {
444        object: Box<SNode>,
445        start: Option<Box<SNode>>,
446        end: Option<Box<SNode>>,
447    },
448    BinaryOp {
449        op: String,
450        left: Box<SNode>,
451        right: Box<SNode>,
452    },
453    UnaryOp {
454        op: String,
455        operand: Box<SNode>,
456    },
457    Ternary {
458        condition: Box<SNode>,
459        true_expr: Box<SNode>,
460        false_expr: Box<SNode>,
461    },
462    Assignment {
463        target: Box<SNode>,
464        value: Box<SNode>,
465        /// None = plain `=`, Some("+") = `+=`, etc.
466        op: Option<String>,
467    },
468    ThrowStmt {
469        value: Box<SNode>,
470    },
471
472    /// Enum variant construction: EnumName.Variant(args)
473    EnumConstruct {
474        enum_name: String,
475        variant: String,
476        args: Vec<SNode>,
477    },
478    /// Struct construction: StructName { field: value, ... }
479    StructConstruct {
480        struct_name: String,
481        fields: Vec<DictEntry>,
482    },
483
484    InterpolatedString(Vec<StringSegment>),
485    StringLiteral(String),
486    /// Raw string literal `r"..."` — no escape processing.
487    RawStringLiteral(String),
488    IntLiteral(i64),
489    FloatLiteral(f64),
490    BoolLiteral(bool),
491    NilLiteral,
492    Identifier(String),
493    ListLiteral(Vec<SNode>),
494    DictLiteral(Vec<DictEntry>),
495    /// Spread expression `...expr` inside list/dict literals.
496    Spread(Box<SNode>),
497    /// Try operator: expr? — unwraps Result.Ok or propagates Result.Err.
498    TryOperator {
499        operand: Box<SNode>,
500    },
501    /// Non-null assertion: `expr!` — asserts the operand is not `nil`.
502    /// Statically strips `nil` from the operand's type (`T | nil` -> `T`);
503    /// at runtime it is identity when the value is present and throws a
504    /// structured `unwrap_nil` error when it is `nil`.
505    NonNullAssert {
506        operand: Box<SNode>,
507    },
508    /// Try-star operator: `try* EXPR` — evaluates EXPR; on throw, runs
509    /// pending finally blocks up to the enclosing catch and rethrows
510    /// the original value. On success, evaluates to EXPR's value.
511    /// Lowered per spec/HARN_SPEC.md as:
512    ///   { let _r = try { EXPR }
513    ///     guard is_ok(_r) else { throw unwrap_err(_r) }
514    ///     unwrap(_r) }
515    TryStar {
516        operand: Box<SNode>,
517    },
518
519    /// Or-pattern in a `match` arm: `"ping" | "pong" -> body`. One or
520    /// more alternative patterns that share a single arm body. Only
521    /// legal inside a `MatchArm.pattern` slot.
522    OrPattern(Vec<SNode>),
523
524    Block(Vec<SNode>),
525    Closure {
526        params: Vec<TypedParam>,
527        return_type: Option<TypeExpr>,
528        /// Declared exception channel; see the [`Node::Pipeline`] `throws`
529        /// field. `None` = unconstrained. Only the `fn(params) -> R throws E`
530        /// closure spelling can carry it; the bare `x -> expr` arrow form has
531        /// no place to put a clause and always parses `None`.
532        throws: Option<TypeExpr>,
533        body: Vec<SNode>,
534        /// When true, this closure was written as `fn(params) { body }`.
535        /// The formatter preserves this distinction.
536        fn_syntax: bool,
537    },
538}
539
540/// Whether evaluating a node leaves a value for its surrounding block.
541///
542/// This is the shared AST contract used by both the type checker and compiler:
543/// a false result means block evaluation supplies `nil`, while a true result
544/// whose type cannot be inferred remains gradual rather than becoming `nil`.
545pub fn node_produces_value(node: &Node) -> bool {
546    match node {
547        Node::AttributedDecl { inner, .. } => node_produces_value(&inner.node),
548        Node::LetBinding { .. }
549        | Node::ConstBinding { .. }
550        | Node::Assignment { .. }
551        | Node::ReturnStmt { .. }
552        | Node::FnDecl { .. }
553        | Node::ToolDecl { .. }
554        | Node::SkillDecl { .. }
555        | Node::EvalPackDecl { .. }
556        | Node::ImplBlock { .. }
557        | Node::StructDecl { .. }
558        | Node::EnumDecl { .. }
559        | Node::InterfaceDecl { .. }
560        | Node::TypeDecl { .. }
561        | Node::OverrideDecl { .. }
562        | Node::Pipeline { .. }
563        | Node::ThrowStmt { .. }
564        | Node::BreakStmt
565        | Node::ContinueStmt
566        | Node::RequireStmt { .. }
567        | Node::DeferStmt { .. } => false,
568        _ => true,
569    }
570}
571
572/// First-class human-in-the-loop primitive.
573///
574/// Each `HitlKind` is a reserved keyword expression with VM-enforced
575/// semantics: the names cannot be shadowed or rebound by user code,
576/// signatures are produced by the VM, and the audit log is recorded
577/// deterministically by the runtime.
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
579pub enum HitlKind {
580    /// `request_approval(action: ..., args: ..., quorum: ..., reviewers: ..., ...)`.
581    RequestApproval,
582    /// `dual_control(n: ..., m: ..., action: <closure>, approvers: ...)`.
583    DualControl,
584    /// `ask_user(prompt: ..., schema: ..., timeout: ..., default: ...)`.
585    AskUser,
586    /// `escalate_to(role: ..., reason: ...)`.
587    EscalateTo,
588}
589
590impl HitlKind {
591    /// Keyword surface form (matches the reserved keyword in the lexer
592    /// and the corresponding async builtin name in the VM).
593    pub fn as_keyword(self) -> &'static str {
594        match self {
595            HitlKind::RequestApproval => "request_approval",
596            HitlKind::DualControl => "dual_control",
597            HitlKind::AskUser => "ask_user",
598            HitlKind::EscalateTo => "escalate_to",
599        }
600    }
601}
602
603/// A single argument in a [`Node::HitlExpr`] call. `name` is `Some` when
604/// the caller used named-arg syntax (e.g. `quorum: 2`); positional
605/// arguments leave it as `None` and rely on the kind's parameter order.
606#[derive(Debug, Clone, PartialEq, serde::Serialize)]
607pub struct HitlArg {
608    pub name: Option<String>,
609    pub value: SNode,
610    pub span: Span,
611}
612
613/// Parallel execution mode.
614#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
615pub enum ParallelMode {
616    /// `parallel N { i -> ... }` — run N concurrent tasks.
617    Count,
618    /// `parallel each list { item -> ... }` — map over list concurrently.
619    Each,
620    /// `parallel each list { item -> ... } as stream` — emit as each task completes.
621    EachStream,
622    /// `parallel settle list { item -> ... }` — map with error collection.
623    Settle,
624}
625
626#[derive(Debug, Clone, PartialEq, serde::Serialize)]
627pub struct MatchArm {
628    pub pattern: SNode,
629    /// Optional guard: `pattern if condition -> { body }`.
630    pub guard: Option<Box<SNode>>,
631    pub body: Vec<SNode>,
632    /// Source extent of the whole arm, pattern through closing brace. The
633    /// pattern's own span cannot bound the arm's body, so without this a
634    /// comment after the arm's last statement has no range to be flushed in.
635    /// See `StructField::span`.
636    pub span: Span,
637}
638
639#[derive(Debug, Clone, PartialEq, serde::Serialize)]
640pub struct SelectCase {
641    pub variable: String,
642    pub channel: Box<SNode>,
643    pub body: Vec<SNode>,
644}
645
646#[derive(Debug, Clone, PartialEq, serde::Serialize)]
647pub struct DictEntry {
648    pub key: SNode,
649    pub value: SNode,
650}
651
652/// An enum variant declaration.
653#[derive(Debug, Clone, PartialEq, serde::Serialize)]
654pub struct EnumVariant {
655    pub name: String,
656    pub fields: Vec<TypedParam>,
657    /// Source extent of the variant. A member without a span cannot anchor a
658    /// comment written against it; see `StructField::span`.
659    pub span: Span,
660}
661
662/// A struct field declaration.
663#[derive(Debug, Clone, PartialEq, serde::Serialize)]
664pub struct StructField {
665    pub name: String,
666    pub type_expr: Option<TypeExpr>,
667    pub optional: bool,
668    /// Source extent of the field.
669    ///
670    /// A comment's meaning lives entirely in where it sits, and a comment can
671    /// only be placed next to something that knows its own source lines. Member
672    /// items carrying no span is what let `harn fmt` evict a field's doc
673    /// comment out of the struct and re-attach it to the next declaration,
674    /// where it then described unrelated code.
675    pub span: Span,
676}
677
678/// An associated-type entry in an interface body: `type Item` or
679/// `type Item = string`.
680#[derive(Debug, Clone, PartialEq, serde::Serialize)]
681pub struct AssociatedType {
682    pub name: String,
683    /// The default, when written as `type Item = <default>`.
684    pub default: Option<TypeExpr>,
685    /// Source extent of the entry. See `StructField::span`.
686    pub span: Span,
687}
688
689impl AssociatedType {
690    /// The name/default pair, dropping source position — the shape the
691    /// typechecker's semantic tables carry, which have no use for a span.
692    pub fn to_binding(&self) -> (String, Option<TypeExpr>) {
693        (self.name.clone(), self.default.clone())
694    }
695
696    /// Project a parsed interface body's associated types onto the binding
697    /// pairs the semantic tables hold. The one place this conversion lives.
698    pub fn bindings(items: &[AssociatedType]) -> Vec<(String, Option<TypeExpr>)> {
699        items.iter().map(AssociatedType::to_binding).collect()
700    }
701}
702
703/// An interface method signature.
704#[derive(Debug, Clone, PartialEq, serde::Serialize)]
705pub struct InterfaceMethod {
706    pub name: String,
707    pub type_params: Vec<TypeParam>,
708    pub params: Vec<TypedParam>,
709    pub return_type: Option<TypeExpr>,
710    /// Source extent of the method signature. See `StructField::span`.
711    pub span: Span,
712}
713
714/// A type annotation (optional, for runtime checking).
715#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
716pub enum TypeExpr {
717    /// A named type: int, string, float, bool, nil, list, dict, closure,
718    /// or a user-defined type name.
719    Named(String),
720    /// A union type: `string | nil`, `int | float`.
721    Union(Vec<TypeExpr>),
722    /// An intersection type: `{x: int} & {y: int}`. The value must satisfy
723    /// every component simultaneously. Useful for layered context types
724    /// such as `fn use(ctx: BaseCtx & AuthCtx)`.
725    Intersection(Vec<TypeExpr>),
726    /// A dict shape type: `{name: string, age: int, active?: bool}`.
727    Shape(Vec<ShapeField>),
728    /// An **open** record / row-polymorphic shape: a set of explicit fields
729    /// plus one or more trailing **row tails** (`{id: string, ...R}`,
730    /// `{...R1, ...R2}`). Each tail in `rests` is a row variable
731    /// (`Named(rowvar)`), a gradual map tail (`dict` / `dict<string, V>`), or a
732    /// nested shape — folded left-to-right with right-biased merge once the row
733    /// variables are bound. A closed shape stays `Shape` (empty `rests`).
734    OpenShape {
735        fields: Vec<ShapeField>,
736        rests: Vec<TypeExpr>,
737    },
738    /// A list type: `list<int>`.
739    List(Box<TypeExpr>),
740    /// A dict type with key and value types: `dict<string, int>`.
741    DictType(Box<TypeExpr>, Box<TypeExpr>),
742    /// A lazy iterator type: `iter<int>`. Yields values of the inner type
743    /// via the combinator/sink protocol (`VmValue::Iter` at runtime).
744    Iter(Box<TypeExpr>),
745    /// A synchronous generator type: `Generator<int>`. Produced by a regular
746    /// `fn` body containing `yield`.
747    Generator(Box<TypeExpr>),
748    /// An asynchronous stream type: `Stream<int>`. Produced by `gen fn`.
749    Stream(Box<TypeExpr>),
750    /// An owned handle type: `owned<File>`. Marks the binding as carrying
751    /// sole ownership of a drop-able resource. The compiler emits an
752    /// auto-`drop()` at the binding's enclosing block exit; the lint
753    /// `HARN-OWN-005` flags ownership leaks (e.g. returning the value or
754    /// storing it in a non-owned field).
755    Owned(Box<TypeExpr>),
756    /// A generic type application: `Option<int>`, `Result<string, int>`.
757    Applied { name: String, args: Vec<TypeExpr> },
758    /// A function type: `fn(int, string) -> bool`.
759    FnType {
760        params: Vec<TypeExpr>,
761        return_type: Box<TypeExpr>,
762    },
763    /// The bottom type: the type of expressions that never produce a value
764    /// (return, throw, break, continue).
765    Never,
766    /// A string-literal type: `"pass"`, `"fail"`. Assignable to `string`.
767    /// Used in unions to represent enum-like discriminated values.
768    LitString(String),
769    /// An int-literal type: `0`, `1`, `-1`. Assignable to `int`.
770    LitInt(i64),
771}
772
773/// A field in a dict shape type.
774#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
775pub struct ShapeField {
776    pub name: String,
777    pub type_expr: TypeExpr,
778    pub optional: bool,
779    /// Source extent of this field. This is formatter/LSP provenance, not part
780    /// of a shape's semantic identity or serialized type contract.
781    #[serde(skip, default = "Span::dummy")]
782    pub span: Span,
783}
784
785impl ShapeField {
786    /// Construct a field synthesized by inference or generated metadata.
787    pub fn synthetic(name: impl Into<String>, type_expr: TypeExpr, optional: bool) -> Self {
788        Self {
789            name: name.into(),
790            type_expr,
791            optional,
792            span: Span::dummy(),
793        }
794    }
795}
796
797impl PartialEq for ShapeField {
798    fn eq(&self, other: &Self) -> bool {
799        self.name == other.name
800            && self.type_expr == other.type_expr
801            && self.optional == other.optional
802    }
803}
804
805#[cfg(test)]
806mod shape_field_tests {
807    use super::*;
808
809    #[test]
810    fn source_provenance_does_not_change_shape_field_equality() {
811        let synthetic = ShapeField::synthetic("retries", TypeExpr::Named("int".into()), false);
812        let parsed = ShapeField {
813            span: Span::with_offsets(12, 24, 3, 3),
814            ..synthetic.clone()
815        };
816
817        assert_eq!(synthetic, parsed);
818    }
819
820    #[test]
821    fn source_provenance_is_not_part_of_the_serialized_type_contract() {
822        let field = ShapeField {
823            span: Span::with_offsets(12, 24, 3, 3),
824            ..ShapeField::synthetic("retries", TypeExpr::Named("int".into()), false)
825        };
826
827        let encoded = serde_json::to_string(&field).expect("shape fields serialize");
828        let decoded: ShapeField = serde_json::from_str(&encoded).expect("shape fields deserialize");
829
830        assert!(
831            !encoded.contains("span"),
832            "source provenance leaked: {encoded}"
833        );
834        assert_eq!(decoded, field);
835        assert_eq!(decoded.span, Span::dummy());
836    }
837}
838
839/// A binding pattern for destructuring in let/var/for-in.
840#[derive(Debug, Clone, PartialEq, serde::Serialize)]
841pub enum BindingPattern {
842    /// Simple identifier: `let x = ...`
843    Identifier(String),
844    /// Dict destructuring: `let {name, age} = ...`
845    Dict(Vec<DictPatternField>),
846    /// List destructuring: `let [a, b] = ...`
847    List(Vec<ListPatternElement>),
848    /// Pair destructuring for `for (a, b) in iter { ... }`. The iter must
849    /// yield `VmValue::Pair` values. Not valid in let/var bindings.
850    Pair(String, String),
851}
852
853/// `_` is the discard binding name in `let`/`const`/destructuring positions.
854pub fn is_discard_name(name: &str) -> bool {
855    name == "_"
856}
857
858/// A field in a dict destructuring pattern.
859#[derive(Debug, Clone, PartialEq, serde::Serialize)]
860pub struct DictPatternField {
861    /// The dict key to extract.
862    pub key: String,
863    /// Renamed binding (if different from key), e.g. `{name: alias}`.
864    pub alias: Option<String>,
865    /// True for `...rest` (rest pattern).
866    pub is_rest: bool,
867    /// Default value if the key is missing (nil), e.g. `{name = "default"}`.
868    pub default_value: Option<Box<SNode>>,
869}
870
871/// An element in a list destructuring pattern.
872#[derive(Debug, Clone, PartialEq, serde::Serialize)]
873pub struct ListPatternElement {
874    /// The variable name to bind.
875    pub name: String,
876    /// True for `...rest` (rest pattern).
877    pub is_rest: bool,
878    /// Default value if the index is out of bounds (nil), e.g. `[a = 0]`.
879    pub default_value: Option<Box<SNode>>,
880}
881
882/// Declared variance of a generic type parameter.
883///
884/// - `Invariant` (default, no marker): the parameter appears in both
885///   input and output positions, or mutable state. `T<A>` and `T<B>`
886///   are unrelated unless `A == B`.
887/// - `Covariant` (`out T`): the parameter appears only in output
888///   positions (produced, not consumed). `T<Sub>` flows into
889///   `T<Super>`.
890/// - `Contravariant` (`in T`): the parameter appears only in input
891///   positions (consumed, not produced). `T<Super>` flows into
892///   `T<Sub>`.
893#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
894pub enum Variance {
895    Invariant,
896    Covariant,
897    Contravariant,
898}
899
900/// A generic type parameter on a function or pipeline declaration.
901#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
902pub struct TypeParam {
903    pub name: String,
904    pub variance: Variance,
905}
906
907impl TypeParam {
908    /// Construct an invariant type parameter (the default for
909    /// unannotated `<T>`).
910    pub fn invariant(name: impl Into<String>) -> Self {
911        Self {
912            name: name.into(),
913            variance: Variance::Invariant,
914        }
915    }
916}
917
918/// A where-clause constraint on a generic type parameter.
919#[derive(Debug, Clone, PartialEq, serde::Serialize)]
920pub struct WhereClause {
921    pub type_name: String,
922    pub bound: TypeExpr,
923}
924
925/// A parameter with an optional type annotation and optional default value.
926#[derive(Debug, Clone, PartialEq, serde::Serialize)]
927pub struct TypedParam {
928    pub name: String,
929    pub type_expr: Option<TypeExpr>,
930    pub default_value: Option<Box<SNode>>,
931    /// If true, this is a rest parameter (`...name`) that collects remaining arguments.
932    pub rest: bool,
933}
934
935impl TypedParam {
936    /// Create an untyped parameter.
937    pub fn untyped(name: impl Into<String>) -> Self {
938        Self {
939            name: name.into(),
940            type_expr: None,
941            default_value: None,
942            rest: false,
943        }
944    }
945
946    /// Create a typed parameter.
947    pub fn typed(name: impl Into<String>, type_expr: TypeExpr) -> Self {
948        Self {
949            name: name.into(),
950            type_expr: Some(type_expr),
951            default_value: None,
952            rest: false,
953        }
954    }
955
956    /// Extract just the names from a list of typed params.
957    pub fn names(params: &[TypedParam]) -> Vec<String> {
958        params.iter().map(|p| p.name.clone()).collect()
959    }
960
961    /// Return the index of the first parameter with a default value, or None.
962    pub fn default_start(params: &[TypedParam]) -> Option<usize> {
963        params.iter().position(|p| p.default_value.is_some())
964    }
965}