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)]
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 literal
44/// expressions by the parser (string/int/float/bool/nil/identifier).
45#[derive(Debug, Clone, PartialEq)]
46pub struct AttributeArg {
47    pub name: Option<String>,
48    pub value: SNode,
49    pub span: Span,
50}
51
52/// An attribute attached to a declaration: `@deprecated(since: "0.8")`.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Attribute {
55    pub name: String,
56    pub args: Vec<AttributeArg>,
57    pub span: Span,
58}
59
60impl Attribute {
61    /// Find a named argument by key.
62    pub fn named_arg(&self, key: &str) -> Option<&SNode> {
63        self.args
64            .iter()
65            .find(|a| a.name.as_deref() == Some(key))
66            .map(|a| &a.value)
67    }
68
69    /// First positional argument, if any.
70    pub fn positional(&self, idx: usize) -> Option<&SNode> {
71        self.args
72            .iter()
73            .filter(|a| a.name.is_none())
74            .nth(idx)
75            .map(|a| &a.value)
76    }
77
78    /// Convenience: extract a string-literal arg by name.
79    pub fn string_arg(&self, key: &str) -> Option<String> {
80        match self.named_arg(key).map(|n| &n.node) {
81            Some(Node::StringLiteral(s)) => Some(s.clone()),
82            Some(Node::RawStringLiteral(s)) => Some(s.clone()),
83            _ => None,
84        }
85    }
86}
87
88/// AST nodes for the Harn language.
89#[derive(Debug, Clone, PartialEq)]
90pub enum Node {
91    /// A declaration carrying one or more attributes (`@attr`). The inner
92    /// node is always one of: FnDecl, ToolDecl, Pipeline, StructDecl,
93    /// EnumDecl, TypeDecl, InterfaceDecl, ImplBlock.
94    AttributedDecl {
95        attributes: Vec<Attribute>,
96        inner: Box<SNode>,
97    },
98    Pipeline {
99        name: String,
100        params: Vec<String>,
101        return_type: Option<TypeExpr>,
102        body: Vec<SNode>,
103        extends: Option<String>,
104        is_pub: bool,
105    },
106    LetBinding {
107        pattern: BindingPattern,
108        type_ann: Option<TypeExpr>,
109        value: Box<SNode>,
110    },
111    VarBinding {
112        pattern: BindingPattern,
113        type_ann: Option<TypeExpr>,
114        value: Box<SNode>,
115    },
116    OverrideDecl {
117        name: String,
118        params: Vec<String>,
119        body: Vec<SNode>,
120    },
121    ImportDecl {
122        path: String,
123    },
124    /// Selective import: import { foo, bar } from "module"
125    SelectiveImport {
126        names: Vec<String>,
127        path: String,
128    },
129    EnumDecl {
130        name: String,
131        type_params: Vec<TypeParam>,
132        variants: Vec<EnumVariant>,
133        is_pub: bool,
134    },
135    StructDecl {
136        name: String,
137        type_params: Vec<TypeParam>,
138        fields: Vec<StructField>,
139        is_pub: bool,
140    },
141    InterfaceDecl {
142        name: String,
143        type_params: Vec<TypeParam>,
144        associated_types: Vec<(String, Option<TypeExpr>)>,
145        methods: Vec<InterfaceMethod>,
146    },
147    /// Impl block: impl TypeName { fn method(self, ...) { ... } ... }
148    ImplBlock {
149        type_name: String,
150        methods: Vec<SNode>,
151    },
152
153    IfElse {
154        condition: Box<SNode>,
155        then_body: Vec<SNode>,
156        else_body: Option<Vec<SNode>>,
157    },
158    ForIn {
159        pattern: BindingPattern,
160        iterable: Box<SNode>,
161        body: Vec<SNode>,
162    },
163    MatchExpr {
164        value: Box<SNode>,
165        arms: Vec<MatchArm>,
166    },
167    WhileLoop {
168        condition: Box<SNode>,
169        body: Vec<SNode>,
170    },
171    Retry {
172        count: Box<SNode>,
173        body: Vec<SNode>,
174    },
175    ReturnStmt {
176        value: Option<Box<SNode>>,
177    },
178    TryCatch {
179        body: Vec<SNode>,
180        error_var: Option<String>,
181        error_type: Option<TypeExpr>,
182        catch_body: Vec<SNode>,
183        finally_body: Option<Vec<SNode>>,
184    },
185    /// Try expression: try { body } — returns Result.Ok(value) or Result.Err(error).
186    TryExpr {
187        body: Vec<SNode>,
188    },
189    FnDecl {
190        name: String,
191        type_params: Vec<TypeParam>,
192        params: Vec<TypedParam>,
193        return_type: Option<TypeExpr>,
194        where_clauses: Vec<WhereClause>,
195        body: Vec<SNode>,
196        is_pub: bool,
197    },
198    ToolDecl {
199        name: String,
200        description: Option<String>,
201        params: Vec<TypedParam>,
202        return_type: Option<TypeExpr>,
203        body: Vec<SNode>,
204        is_pub: bool,
205    },
206    TypeDecl {
207        name: String,
208        type_params: Vec<TypeParam>,
209        type_expr: TypeExpr,
210    },
211    SpawnExpr {
212        body: Vec<SNode>,
213    },
214    /// Duration literal: 500ms, 5s, 30m, 2h, 1d, 1w
215    DurationLiteral(u64),
216    /// Range expression: `start to end` (inclusive) or `start to end exclusive` (half-open)
217    RangeExpr {
218        start: Box<SNode>,
219        end: Box<SNode>,
220        inclusive: bool,
221    },
222    /// Guard clause: guard condition else { body }
223    GuardStmt {
224        condition: Box<SNode>,
225        else_body: Vec<SNode>,
226    },
227    RequireStmt {
228        condition: Box<SNode>,
229        message: Option<Box<SNode>>,
230    },
231    /// Defer statement: defer { body } — runs body at scope exit.
232    DeferStmt {
233        body: Vec<SNode>,
234    },
235    /// Deadline block: deadline DURATION { body }
236    DeadlineBlock {
237        duration: Box<SNode>,
238        body: Vec<SNode>,
239    },
240    /// Yield expression: yields control to host, optionally with a value.
241    YieldExpr {
242        value: Option<Box<SNode>>,
243    },
244    /// Mutex block: mutual exclusion for concurrent access.
245    MutexBlock {
246        body: Vec<SNode>,
247    },
248    /// Break out of a loop.
249    BreakStmt,
250    /// Continue to next loop iteration.
251    ContinueStmt,
252
253    Parallel {
254        mode: ParallelMode,
255        /// For Count mode: the count expression. For Each/Settle: the list expression.
256        expr: Box<SNode>,
257        variable: Option<String>,
258        body: Vec<SNode>,
259        /// Optional trailing `with { max_concurrent: N, ... }` option block.
260        /// A vec (rather than a dict) preserves source order for error
261        /// reporting and keeps parsing cheap. Only `max_concurrent` is
262        /// currently honored; unknown keys are rejected by the parser.
263        options: Vec<(String, SNode)>,
264    },
265
266    SelectExpr {
267        cases: Vec<SelectCase>,
268        timeout: Option<(Box<SNode>, Vec<SNode>)>,
269        default_body: Option<Vec<SNode>>,
270    },
271
272    FunctionCall {
273        name: String,
274        args: Vec<SNode>,
275    },
276    MethodCall {
277        object: Box<SNode>,
278        method: String,
279        args: Vec<SNode>,
280    },
281    /// Optional method call: `obj?.method(args)` — returns nil if obj is nil.
282    OptionalMethodCall {
283        object: Box<SNode>,
284        method: String,
285        args: Vec<SNode>,
286    },
287    PropertyAccess {
288        object: Box<SNode>,
289        property: String,
290    },
291    /// Optional chaining: `obj?.property` — returns nil if obj is nil.
292    OptionalPropertyAccess {
293        object: Box<SNode>,
294        property: String,
295    },
296    SubscriptAccess {
297        object: Box<SNode>,
298        index: Box<SNode>,
299    },
300    SliceAccess {
301        object: Box<SNode>,
302        start: Option<Box<SNode>>,
303        end: Option<Box<SNode>>,
304    },
305    BinaryOp {
306        op: String,
307        left: Box<SNode>,
308        right: Box<SNode>,
309    },
310    UnaryOp {
311        op: String,
312        operand: Box<SNode>,
313    },
314    Ternary {
315        condition: Box<SNode>,
316        true_expr: Box<SNode>,
317        false_expr: Box<SNode>,
318    },
319    Assignment {
320        target: Box<SNode>,
321        value: Box<SNode>,
322        /// None = plain `=`, Some("+") = `+=`, etc.
323        op: Option<String>,
324    },
325    ThrowStmt {
326        value: Box<SNode>,
327    },
328
329    /// Enum variant construction: EnumName.Variant(args)
330    EnumConstruct {
331        enum_name: String,
332        variant: String,
333        args: Vec<SNode>,
334    },
335    /// Struct construction: StructName { field: value, ... }
336    StructConstruct {
337        struct_name: String,
338        fields: Vec<DictEntry>,
339    },
340
341    InterpolatedString(Vec<StringSegment>),
342    StringLiteral(String),
343    /// Raw string literal `r"..."` — no escape processing.
344    RawStringLiteral(String),
345    IntLiteral(i64),
346    FloatLiteral(f64),
347    BoolLiteral(bool),
348    NilLiteral,
349    Identifier(String),
350    ListLiteral(Vec<SNode>),
351    DictLiteral(Vec<DictEntry>),
352    /// Spread expression `...expr` inside list/dict literals.
353    Spread(Box<SNode>),
354    /// Try operator: expr? — unwraps Result.Ok or propagates Result.Err.
355    TryOperator {
356        operand: Box<SNode>,
357    },
358    /// Try-star operator: `try* EXPR` — evaluates EXPR; on throw, runs
359    /// pending finally blocks up to the enclosing catch and rethrows
360    /// the original value. On success, evaluates to EXPR's value.
361    /// Lowered per spec/HARN_SPEC.md as:
362    ///   { let _r = try { EXPR }
363    ///     guard is_ok(_r) else { throw unwrap_err(_r) }
364    ///     unwrap(_r) }
365    TryStar {
366        operand: Box<SNode>,
367    },
368
369    Block(Vec<SNode>),
370    Closure {
371        params: Vec<TypedParam>,
372        body: Vec<SNode>,
373        /// When true, this closure was written as `fn(params) { body }`.
374        /// The formatter preserves this distinction.
375        fn_syntax: bool,
376    },
377}
378
379/// Parallel execution mode.
380#[derive(Debug, Clone, Copy, PartialEq)]
381pub enum ParallelMode {
382    /// `parallel N { i -> ... }` — run N concurrent tasks.
383    Count,
384    /// `parallel each list { item -> ... }` — map over list concurrently.
385    Each,
386    /// `parallel settle list { item -> ... }` — map with error collection.
387    Settle,
388}
389
390#[derive(Debug, Clone, PartialEq)]
391pub struct MatchArm {
392    pub pattern: SNode,
393    /// Optional guard: `pattern if condition -> { body }`.
394    pub guard: Option<Box<SNode>>,
395    pub body: Vec<SNode>,
396}
397
398#[derive(Debug, Clone, PartialEq)]
399pub struct SelectCase {
400    pub variable: String,
401    pub channel: Box<SNode>,
402    pub body: Vec<SNode>,
403}
404
405#[derive(Debug, Clone, PartialEq)]
406pub struct DictEntry {
407    pub key: SNode,
408    pub value: SNode,
409}
410
411/// An enum variant declaration.
412#[derive(Debug, Clone, PartialEq)]
413pub struct EnumVariant {
414    pub name: String,
415    pub fields: Vec<TypedParam>,
416}
417
418/// A struct field declaration.
419#[derive(Debug, Clone, PartialEq)]
420pub struct StructField {
421    pub name: String,
422    pub type_expr: Option<TypeExpr>,
423    pub optional: bool,
424}
425
426/// An interface method signature.
427#[derive(Debug, Clone, PartialEq)]
428pub struct InterfaceMethod {
429    pub name: String,
430    pub type_params: Vec<TypeParam>,
431    pub params: Vec<TypedParam>,
432    pub return_type: Option<TypeExpr>,
433}
434
435/// A type annotation (optional, for runtime checking).
436#[derive(Debug, Clone, PartialEq)]
437pub enum TypeExpr {
438    /// A named type: int, string, float, bool, nil, list, dict, closure,
439    /// or a user-defined type name.
440    Named(String),
441    /// A union type: `string | nil`, `int | float`.
442    Union(Vec<TypeExpr>),
443    /// A dict shape type: `{name: string, age: int, active?: bool}`.
444    Shape(Vec<ShapeField>),
445    /// A list type: `list<int>`.
446    List(Box<TypeExpr>),
447    /// A dict type with key and value types: `dict<string, int>`.
448    DictType(Box<TypeExpr>, Box<TypeExpr>),
449    /// A lazy iterator type: `iter<int>`. Yields values of the inner type
450    /// via the combinator/sink protocol (`VmValue::Iter` at runtime).
451    Iter(Box<TypeExpr>),
452    /// A generic type application: `Option<int>`, `Result<string, int>`.
453    Applied { name: String, args: Vec<TypeExpr> },
454    /// A function type: `fn(int, string) -> bool`.
455    FnType {
456        params: Vec<TypeExpr>,
457        return_type: Box<TypeExpr>,
458    },
459    /// The bottom type: the type of expressions that never produce a value
460    /// (return, throw, break, continue).
461    Never,
462    /// A string-literal type: `"pass"`, `"fail"`. Assignable to `string`.
463    /// Used in unions to represent enum-like discriminated values.
464    LitString(String),
465    /// An int-literal type: `0`, `1`, `-1`. Assignable to `int`.
466    LitInt(i64),
467}
468
469/// A field in a dict shape type.
470#[derive(Debug, Clone, PartialEq)]
471pub struct ShapeField {
472    pub name: String,
473    pub type_expr: TypeExpr,
474    pub optional: bool,
475}
476
477/// A binding pattern for destructuring in let/var/for-in.
478#[derive(Debug, Clone, PartialEq)]
479pub enum BindingPattern {
480    /// Simple identifier: `let x = ...`
481    Identifier(String),
482    /// Dict destructuring: `let {name, age} = ...`
483    Dict(Vec<DictPatternField>),
484    /// List destructuring: `let [a, b] = ...`
485    List(Vec<ListPatternElement>),
486    /// Pair destructuring for `for (a, b) in iter { ... }`. The iter must
487    /// yield `VmValue::Pair` values. Not valid in let/var bindings.
488    Pair(String, String),
489}
490
491/// A field in a dict destructuring pattern.
492#[derive(Debug, Clone, PartialEq)]
493pub struct DictPatternField {
494    /// The dict key to extract.
495    pub key: String,
496    /// Renamed binding (if different from key), e.g. `{name: alias}`.
497    pub alias: Option<String>,
498    /// True for `...rest` (rest pattern).
499    pub is_rest: bool,
500    /// Default value if the key is missing (nil), e.g. `{name = "default"}`.
501    pub default_value: Option<Box<SNode>>,
502}
503
504/// An element in a list destructuring pattern.
505#[derive(Debug, Clone, PartialEq)]
506pub struct ListPatternElement {
507    /// The variable name to bind.
508    pub name: String,
509    /// True for `...rest` (rest pattern).
510    pub is_rest: bool,
511    /// Default value if the index is out of bounds (nil), e.g. `[a = 0]`.
512    pub default_value: Option<Box<SNode>>,
513}
514
515/// Declared variance of a generic type parameter.
516///
517/// - `Invariant` (default, no marker): the parameter appears in both
518///   input and output positions, or mutable state. `T<A>` and `T<B>`
519///   are unrelated unless `A == B`.
520/// - `Covariant` (`out T`): the parameter appears only in output
521///   positions (produced, not consumed). `T<Sub>` flows into
522///   `T<Super>`.
523/// - `Contravariant` (`in T`): the parameter appears only in input
524///   positions (consumed, not produced). `T<Super>` flows into
525///   `T<Sub>`.
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub enum Variance {
528    Invariant,
529    Covariant,
530    Contravariant,
531}
532
533/// A generic type parameter on a function or pipeline declaration.
534#[derive(Debug, Clone, PartialEq)]
535pub struct TypeParam {
536    pub name: String,
537    pub variance: Variance,
538}
539
540impl TypeParam {
541    /// Construct an invariant type parameter (the default for
542    /// unannotated `<T>`).
543    pub fn invariant(name: impl Into<String>) -> Self {
544        Self {
545            name: name.into(),
546            variance: Variance::Invariant,
547        }
548    }
549}
550
551/// A where-clause constraint on a generic type parameter.
552#[derive(Debug, Clone, PartialEq)]
553pub struct WhereClause {
554    pub type_name: String,
555    pub bound: String,
556}
557
558/// A parameter with an optional type annotation and optional default value.
559#[derive(Debug, Clone, PartialEq)]
560pub struct TypedParam {
561    pub name: String,
562    pub type_expr: Option<TypeExpr>,
563    pub default_value: Option<Box<SNode>>,
564    /// If true, this is a rest parameter (`...name`) that collects remaining arguments.
565    pub rest: bool,
566}
567
568impl TypedParam {
569    /// Create an untyped parameter.
570    pub fn untyped(name: impl Into<String>) -> Self {
571        Self {
572            name: name.into(),
573            type_expr: None,
574            default_value: None,
575            rest: false,
576        }
577    }
578
579    /// Create a typed parameter.
580    pub fn typed(name: impl Into<String>, type_expr: TypeExpr) -> Self {
581        Self {
582            name: name.into(),
583            type_expr: Some(type_expr),
584            default_value: None,
585            rest: false,
586        }
587    }
588
589    /// Extract just the names from a list of typed params.
590    pub fn names(params: &[TypedParam]) -> Vec<String> {
591        params.iter().map(|p| p.name.clone()).collect()
592    }
593
594    /// Return the index of the first parameter with a default value, or None.
595    pub fn default_start(params: &[TypedParam]) -> Option<usize> {
596        params.iter().position(|p| p.default_value.is_some())
597    }
598}