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/// AST nodes for the Harn language.
32#[derive(Debug, Clone, PartialEq)]
33pub enum Node {
34    // Declarations
35    Pipeline {
36        name: String,
37        params: Vec<String>,
38        body: Vec<SNode>,
39        extends: Option<String>,
40    },
41    LetBinding {
42        pattern: BindingPattern,
43        type_ann: Option<TypeExpr>,
44        value: Box<SNode>,
45    },
46    VarBinding {
47        pattern: BindingPattern,
48        type_ann: Option<TypeExpr>,
49        value: Box<SNode>,
50    },
51    OverrideDecl {
52        name: String,
53        params: Vec<String>,
54        body: Vec<SNode>,
55    },
56    ImportDecl {
57        path: String,
58    },
59    /// Selective import: import { foo, bar } from "module"
60    SelectiveImport {
61        names: Vec<String>,
62        path: String,
63    },
64    EnumDecl {
65        name: String,
66        variants: Vec<EnumVariant>,
67    },
68    StructDecl {
69        name: String,
70        fields: Vec<StructField>,
71    },
72    InterfaceDecl {
73        name: String,
74        methods: Vec<InterfaceMethod>,
75    },
76    /// Impl block: impl TypeName { fn method(self, ...) { ... } ... }
77    ImplBlock {
78        type_name: String,
79        methods: Vec<SNode>,
80    },
81
82    // Control flow
83    IfElse {
84        condition: Box<SNode>,
85        then_body: Vec<SNode>,
86        else_body: Option<Vec<SNode>>,
87    },
88    ForIn {
89        pattern: BindingPattern,
90        iterable: Box<SNode>,
91        body: Vec<SNode>,
92    },
93    MatchExpr {
94        value: Box<SNode>,
95        arms: Vec<MatchArm>,
96    },
97    WhileLoop {
98        condition: Box<SNode>,
99        body: Vec<SNode>,
100    },
101    Retry {
102        count: Box<SNode>,
103        body: Vec<SNode>,
104    },
105    ReturnStmt {
106        value: Option<Box<SNode>>,
107    },
108    TryCatch {
109        body: Vec<SNode>,
110        error_var: Option<String>,
111        error_type: Option<TypeExpr>,
112        catch_body: Vec<SNode>,
113        finally_body: Option<Vec<SNode>>,
114    },
115    /// Try expression: try { body } — returns Result.Ok(value) or Result.Err(error).
116    TryExpr {
117        body: Vec<SNode>,
118    },
119    FnDecl {
120        name: String,
121        type_params: Vec<TypeParam>,
122        params: Vec<TypedParam>,
123        return_type: Option<TypeExpr>,
124        where_clauses: Vec<WhereClause>,
125        body: Vec<SNode>,
126        is_pub: bool,
127    },
128    TypeDecl {
129        name: String,
130        type_expr: TypeExpr,
131    },
132    SpawnExpr {
133        body: Vec<SNode>,
134    },
135    /// Duration literal: 500ms, 5s, 30m, 2h
136    DurationLiteral(u64),
137    /// Range expression: start upto end (exclusive) or start thru end (inclusive)
138    RangeExpr {
139        start: Box<SNode>,
140        end: Box<SNode>,
141        inclusive: bool,
142    },
143    /// Guard clause: guard condition else { body }
144    GuardStmt {
145        condition: Box<SNode>,
146        else_body: Vec<SNode>,
147    },
148    /// Ask expression: ask { system: "...", user: "...", ... }
149    AskExpr {
150        fields: Vec<DictEntry>,
151    },
152    /// Deadline block: deadline DURATION { body }
153    DeadlineBlock {
154        duration: Box<SNode>,
155        body: Vec<SNode>,
156    },
157    /// Yield expression: yields control to host, optionally with a value.
158    YieldExpr {
159        value: Option<Box<SNode>>,
160    },
161    /// Mutex block: mutual exclusion for concurrent access.
162    MutexBlock {
163        body: Vec<SNode>,
164    },
165    /// Break out of a loop.
166    BreakStmt,
167    /// Continue to next loop iteration.
168    ContinueStmt,
169
170    // Concurrency
171    Parallel {
172        count: Box<SNode>,
173        variable: Option<String>,
174        body: Vec<SNode>,
175    },
176    ParallelMap {
177        list: Box<SNode>,
178        variable: String,
179        body: Vec<SNode>,
180    },
181    ParallelSettle {
182        list: Box<SNode>,
183        variable: String,
184        body: Vec<SNode>,
185    },
186
187    SelectExpr {
188        cases: Vec<SelectCase>,
189        timeout: Option<(Box<SNode>, Vec<SNode>)>,
190        default_body: Option<Vec<SNode>>,
191    },
192
193    // Expressions
194    FunctionCall {
195        name: String,
196        args: Vec<SNode>,
197    },
198    MethodCall {
199        object: Box<SNode>,
200        method: String,
201        args: Vec<SNode>,
202    },
203    /// Optional method call: `obj?.method(args)` — returns nil if obj is nil.
204    OptionalMethodCall {
205        object: Box<SNode>,
206        method: String,
207        args: Vec<SNode>,
208    },
209    PropertyAccess {
210        object: Box<SNode>,
211        property: String,
212    },
213    /// Optional chaining: `obj?.property` — returns nil if obj is nil.
214    OptionalPropertyAccess {
215        object: Box<SNode>,
216        property: String,
217    },
218    SubscriptAccess {
219        object: Box<SNode>,
220        index: Box<SNode>,
221    },
222    SliceAccess {
223        object: Box<SNode>,
224        start: Option<Box<SNode>>,
225        end: Option<Box<SNode>>,
226    },
227    BinaryOp {
228        op: String,
229        left: Box<SNode>,
230        right: Box<SNode>,
231    },
232    UnaryOp {
233        op: String,
234        operand: Box<SNode>,
235    },
236    Ternary {
237        condition: Box<SNode>,
238        true_expr: Box<SNode>,
239        false_expr: Box<SNode>,
240    },
241    Assignment {
242        target: Box<SNode>,
243        value: Box<SNode>,
244        /// None = plain `=`, Some("+") = `+=`, etc.
245        op: Option<String>,
246    },
247    ThrowStmt {
248        value: Box<SNode>,
249    },
250
251    /// Enum variant construction: EnumName.Variant(args)
252    EnumConstruct {
253        enum_name: String,
254        variant: String,
255        args: Vec<SNode>,
256    },
257    /// Struct construction: StructName { field: value, ... }
258    StructConstruct {
259        struct_name: String,
260        fields: Vec<DictEntry>,
261    },
262
263    // Literals
264    InterpolatedString(Vec<StringSegment>),
265    StringLiteral(String),
266    IntLiteral(i64),
267    FloatLiteral(f64),
268    BoolLiteral(bool),
269    NilLiteral,
270    Identifier(String),
271    ListLiteral(Vec<SNode>),
272    DictLiteral(Vec<DictEntry>),
273    /// Spread expression `...expr` inside list/dict literals.
274    Spread(Box<SNode>),
275    /// Try operator: expr? — unwraps Result.Ok or propagates Result.Err.
276    TryOperator {
277        operand: Box<SNode>,
278    },
279
280    // Blocks
281    Block(Vec<SNode>),
282    Closure {
283        params: Vec<TypedParam>,
284        body: Vec<SNode>,
285    },
286}
287
288#[derive(Debug, Clone, PartialEq)]
289pub struct MatchArm {
290    pub pattern: SNode,
291    pub body: Vec<SNode>,
292}
293
294#[derive(Debug, Clone, PartialEq)]
295pub struct SelectCase {
296    pub variable: String,
297    pub channel: Box<SNode>,
298    pub body: Vec<SNode>,
299}
300
301#[derive(Debug, Clone, PartialEq)]
302pub struct DictEntry {
303    pub key: SNode,
304    pub value: SNode,
305}
306
307/// An enum variant declaration.
308#[derive(Debug, Clone, PartialEq)]
309pub struct EnumVariant {
310    pub name: String,
311    pub fields: Vec<TypedParam>,
312}
313
314/// A struct field declaration.
315#[derive(Debug, Clone, PartialEq)]
316pub struct StructField {
317    pub name: String,
318    pub type_expr: Option<TypeExpr>,
319    pub optional: bool,
320}
321
322/// An interface method signature.
323#[derive(Debug, Clone, PartialEq)]
324pub struct InterfaceMethod {
325    pub name: String,
326    pub params: Vec<TypedParam>,
327    pub return_type: Option<TypeExpr>,
328}
329
330/// A type annotation (optional, for runtime checking).
331#[derive(Debug, Clone, PartialEq)]
332pub enum TypeExpr {
333    /// A named type: int, string, float, bool, nil, list, dict, closure,
334    /// or a user-defined type name.
335    Named(String),
336    /// A union type: `string | nil`, `int | float`.
337    Union(Vec<TypeExpr>),
338    /// A dict shape type: `{name: string, age: int, active?: bool}`.
339    Shape(Vec<ShapeField>),
340    /// A list type: `list<int>`.
341    List(Box<TypeExpr>),
342    /// A dict type with key and value types: `dict<string, int>`.
343    DictType(Box<TypeExpr>, Box<TypeExpr>),
344    /// A function type: `fn(int, string) -> bool`.
345    FnType {
346        params: Vec<TypeExpr>,
347        return_type: Box<TypeExpr>,
348    },
349}
350
351/// A field in a dict shape type.
352#[derive(Debug, Clone, PartialEq)]
353pub struct ShapeField {
354    pub name: String,
355    pub type_expr: TypeExpr,
356    pub optional: bool,
357}
358
359/// A binding pattern for destructuring in let/var/for-in.
360#[derive(Debug, Clone, PartialEq)]
361pub enum BindingPattern {
362    /// Simple identifier: `let x = ...`
363    Identifier(String),
364    /// Dict destructuring: `let {name, age} = ...`
365    Dict(Vec<DictPatternField>),
366    /// List destructuring: `let [a, b] = ...`
367    List(Vec<ListPatternElement>),
368}
369
370/// A field in a dict destructuring pattern.
371#[derive(Debug, Clone, PartialEq)]
372pub struct DictPatternField {
373    /// The dict key to extract.
374    pub key: String,
375    /// Renamed binding (if different from key), e.g. `{name: alias}`.
376    pub alias: Option<String>,
377    /// True for `...rest` (rest pattern).
378    pub is_rest: bool,
379}
380
381/// An element in a list destructuring pattern.
382#[derive(Debug, Clone, PartialEq)]
383pub struct ListPatternElement {
384    /// The variable name to bind.
385    pub name: String,
386    /// True for `...rest` (rest pattern).
387    pub is_rest: bool,
388}
389
390/// A generic type parameter on a function or pipeline declaration.
391#[derive(Debug, Clone, PartialEq)]
392pub struct TypeParam {
393    pub name: String,
394}
395
396/// A where-clause constraint on a generic type parameter.
397#[derive(Debug, Clone, PartialEq)]
398pub struct WhereClause {
399    pub type_name: String,
400    pub bound: String,
401}
402
403/// A parameter with an optional type annotation and optional default value.
404#[derive(Debug, Clone, PartialEq)]
405pub struct TypedParam {
406    pub name: String,
407    pub type_expr: Option<TypeExpr>,
408    pub default_value: Option<Box<SNode>>,
409}
410
411impl TypedParam {
412    /// Create an untyped parameter.
413    pub fn untyped(name: impl Into<String>) -> Self {
414        Self {
415            name: name.into(),
416            type_expr: None,
417            default_value: None,
418        }
419    }
420
421    /// Create a typed parameter.
422    pub fn typed(name: impl Into<String>, type_expr: TypeExpr) -> Self {
423        Self {
424            name: name.into(),
425            type_expr: Some(type_expr),
426            default_value: None,
427        }
428    }
429
430    /// Extract just the names from a list of typed params.
431    pub fn names(params: &[TypedParam]) -> Vec<String> {
432        params.iter().map(|p| p.name.clone()).collect()
433    }
434
435    /// Return the index of the first parameter with a default value, or None.
436    pub fn default_start(params: &[TypedParam]) -> Option<usize> {
437        params.iter().position(|p| p.default_value.is_some())
438    }
439}