harn-parser 0.5.1

Parser, AST, and type checker for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use harn_lexer::{Span, StringSegment};

/// A node wrapped with source location information.
#[derive(Debug, Clone, PartialEq)]
pub struct Spanned<T> {
    pub node: T,
    pub span: Span,
}

impl<T> Spanned<T> {
    pub fn new(node: T, span: Span) -> Self {
        Self { node, span }
    }

    pub fn dummy(node: T) -> Self {
        Self {
            node,
            span: Span::dummy(),
        }
    }
}

/// A spanned AST node — the primary unit throughout the compiler.
pub type SNode = Spanned<Node>;

/// Helper to wrap a node with a span.
pub fn spanned(node: Node, span: Span) -> SNode {
    SNode::new(node, span)
}

/// AST nodes for the Harn language.
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
    // Declarations
    Pipeline {
        name: String,
        params: Vec<String>,
        body: Vec<SNode>,
        extends: Option<String>,
    },
    LetBinding {
        pattern: BindingPattern,
        type_ann: Option<TypeExpr>,
        value: Box<SNode>,
    },
    VarBinding {
        pattern: BindingPattern,
        type_ann: Option<TypeExpr>,
        value: Box<SNode>,
    },
    OverrideDecl {
        name: String,
        params: Vec<String>,
        body: Vec<SNode>,
    },
    ImportDecl {
        path: String,
    },
    /// Selective import: import { foo, bar } from "module"
    SelectiveImport {
        names: Vec<String>,
        path: String,
    },
    EnumDecl {
        name: String,
        variants: Vec<EnumVariant>,
    },
    StructDecl {
        name: String,
        fields: Vec<StructField>,
    },
    InterfaceDecl {
        name: String,
        methods: Vec<InterfaceMethod>,
    },
    /// Impl block: impl TypeName { fn method(self, ...) { ... } ... }
    ImplBlock {
        type_name: String,
        methods: Vec<SNode>,
    },

    // Control flow
    IfElse {
        condition: Box<SNode>,
        then_body: Vec<SNode>,
        else_body: Option<Vec<SNode>>,
    },
    ForIn {
        pattern: BindingPattern,
        iterable: Box<SNode>,
        body: Vec<SNode>,
    },
    MatchExpr {
        value: Box<SNode>,
        arms: Vec<MatchArm>,
    },
    WhileLoop {
        condition: Box<SNode>,
        body: Vec<SNode>,
    },
    Retry {
        count: Box<SNode>,
        body: Vec<SNode>,
    },
    ReturnStmt {
        value: Option<Box<SNode>>,
    },
    TryCatch {
        body: Vec<SNode>,
        error_var: Option<String>,
        error_type: Option<TypeExpr>,
        catch_body: Vec<SNode>,
        finally_body: Option<Vec<SNode>>,
    },
    /// Try expression: try { body } — returns Result.Ok(value) or Result.Err(error).
    TryExpr {
        body: Vec<SNode>,
    },
    FnDecl {
        name: String,
        type_params: Vec<TypeParam>,
        params: Vec<TypedParam>,
        return_type: Option<TypeExpr>,
        where_clauses: Vec<WhereClause>,
        body: Vec<SNode>,
        is_pub: bool,
    },
    TypeDecl {
        name: String,
        type_expr: TypeExpr,
    },
    SpawnExpr {
        body: Vec<SNode>,
    },
    /// Duration literal: 500ms, 5s, 30m, 2h
    DurationLiteral(u64),
    /// Range expression: start upto end (exclusive) or start thru end (inclusive)
    RangeExpr {
        start: Box<SNode>,
        end: Box<SNode>,
        inclusive: bool,
    },
    /// Guard clause: guard condition else { body }
    GuardStmt {
        condition: Box<SNode>,
        else_body: Vec<SNode>,
    },
    /// Ask expression: ask { system: "...", user: "...", ... }
    AskExpr {
        fields: Vec<DictEntry>,
    },
    /// Deadline block: deadline DURATION { body }
    DeadlineBlock {
        duration: Box<SNode>,
        body: Vec<SNode>,
    },
    /// Yield expression: yields control to host, optionally with a value.
    YieldExpr {
        value: Option<Box<SNode>>,
    },
    /// Mutex block: mutual exclusion for concurrent access.
    MutexBlock {
        body: Vec<SNode>,
    },
    /// Break out of a loop.
    BreakStmt,
    /// Continue to next loop iteration.
    ContinueStmt,

    // Concurrency
    Parallel {
        count: Box<SNode>,
        variable: Option<String>,
        body: Vec<SNode>,
    },
    ParallelMap {
        list: Box<SNode>,
        variable: String,
        body: Vec<SNode>,
    },
    ParallelSettle {
        list: Box<SNode>,
        variable: String,
        body: Vec<SNode>,
    },

    SelectExpr {
        cases: Vec<SelectCase>,
        timeout: Option<(Box<SNode>, Vec<SNode>)>,
        default_body: Option<Vec<SNode>>,
    },

    // Expressions
    FunctionCall {
        name: String,
        args: Vec<SNode>,
    },
    MethodCall {
        object: Box<SNode>,
        method: String,
        args: Vec<SNode>,
    },
    /// Optional method call: `obj?.method(args)` — returns nil if obj is nil.
    OptionalMethodCall {
        object: Box<SNode>,
        method: String,
        args: Vec<SNode>,
    },
    PropertyAccess {
        object: Box<SNode>,
        property: String,
    },
    /// Optional chaining: `obj?.property` — returns nil if obj is nil.
    OptionalPropertyAccess {
        object: Box<SNode>,
        property: String,
    },
    SubscriptAccess {
        object: Box<SNode>,
        index: Box<SNode>,
    },
    SliceAccess {
        object: Box<SNode>,
        start: Option<Box<SNode>>,
        end: Option<Box<SNode>>,
    },
    BinaryOp {
        op: String,
        left: Box<SNode>,
        right: Box<SNode>,
    },
    UnaryOp {
        op: String,
        operand: Box<SNode>,
    },
    Ternary {
        condition: Box<SNode>,
        true_expr: Box<SNode>,
        false_expr: Box<SNode>,
    },
    Assignment {
        target: Box<SNode>,
        value: Box<SNode>,
        /// None = plain `=`, Some("+") = `+=`, etc.
        op: Option<String>,
    },
    ThrowStmt {
        value: Box<SNode>,
    },

    /// Enum variant construction: EnumName.Variant(args)
    EnumConstruct {
        enum_name: String,
        variant: String,
        args: Vec<SNode>,
    },
    /// Struct construction: StructName { field: value, ... }
    StructConstruct {
        struct_name: String,
        fields: Vec<DictEntry>,
    },

    // Literals
    InterpolatedString(Vec<StringSegment>),
    StringLiteral(String),
    IntLiteral(i64),
    FloatLiteral(f64),
    BoolLiteral(bool),
    NilLiteral,
    Identifier(String),
    ListLiteral(Vec<SNode>),
    DictLiteral(Vec<DictEntry>),
    /// Spread expression `...expr` inside list/dict literals.
    Spread(Box<SNode>),
    /// Try operator: expr? — unwraps Result.Ok or propagates Result.Err.
    TryOperator {
        operand: Box<SNode>,
    },

    // Blocks
    Block(Vec<SNode>),
    Closure {
        params: Vec<TypedParam>,
        body: Vec<SNode>,
        /// When true, this closure was written as `fn(params) { body }`.
        /// The formatter preserves this distinction.
        fn_syntax: bool,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
    pub pattern: SNode,
    pub body: Vec<SNode>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SelectCase {
    pub variable: String,
    pub channel: Box<SNode>,
    pub body: Vec<SNode>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DictEntry {
    pub key: SNode,
    pub value: SNode,
}

/// An enum variant declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumVariant {
    pub name: String,
    pub fields: Vec<TypedParam>,
}

/// A struct field declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct StructField {
    pub name: String,
    pub type_expr: Option<TypeExpr>,
    pub optional: bool,
}

/// An interface method signature.
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceMethod {
    pub name: String,
    pub params: Vec<TypedParam>,
    pub return_type: Option<TypeExpr>,
}

/// A type annotation (optional, for runtime checking).
#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
    /// A named type: int, string, float, bool, nil, list, dict, closure,
    /// or a user-defined type name.
    Named(String),
    /// A union type: `string | nil`, `int | float`.
    Union(Vec<TypeExpr>),
    /// A dict shape type: `{name: string, age: int, active?: bool}`.
    Shape(Vec<ShapeField>),
    /// A list type: `list<int>`.
    List(Box<TypeExpr>),
    /// A dict type with key and value types: `dict<string, int>`.
    DictType(Box<TypeExpr>, Box<TypeExpr>),
    /// A function type: `fn(int, string) -> bool`.
    FnType {
        params: Vec<TypeExpr>,
        return_type: Box<TypeExpr>,
    },
}

/// A field in a dict shape type.
#[derive(Debug, Clone, PartialEq)]
pub struct ShapeField {
    pub name: String,
    pub type_expr: TypeExpr,
    pub optional: bool,
}

/// A binding pattern for destructuring in let/var/for-in.
#[derive(Debug, Clone, PartialEq)]
pub enum BindingPattern {
    /// Simple identifier: `let x = ...`
    Identifier(String),
    /// Dict destructuring: `let {name, age} = ...`
    Dict(Vec<DictPatternField>),
    /// List destructuring: `let [a, b] = ...`
    List(Vec<ListPatternElement>),
}

/// A field in a dict destructuring pattern.
#[derive(Debug, Clone, PartialEq)]
pub struct DictPatternField {
    /// The dict key to extract.
    pub key: String,
    /// Renamed binding (if different from key), e.g. `{name: alias}`.
    pub alias: Option<String>,
    /// True for `...rest` (rest pattern).
    pub is_rest: bool,
}

/// An element in a list destructuring pattern.
#[derive(Debug, Clone, PartialEq)]
pub struct ListPatternElement {
    /// The variable name to bind.
    pub name: String,
    /// True for `...rest` (rest pattern).
    pub is_rest: bool,
}

/// A generic type parameter on a function or pipeline declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeParam {
    pub name: String,
}

/// A where-clause constraint on a generic type parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct WhereClause {
    pub type_name: String,
    pub bound: String,
}

/// A parameter with an optional type annotation and optional default value.
#[derive(Debug, Clone, PartialEq)]
pub struct TypedParam {
    pub name: String,
    pub type_expr: Option<TypeExpr>,
    pub default_value: Option<Box<SNode>>,
}

impl TypedParam {
    /// Create an untyped parameter.
    pub fn untyped(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            type_expr: None,
            default_value: None,
        }
    }

    /// Create a typed parameter.
    pub fn typed(name: impl Into<String>, type_expr: TypeExpr) -> Self {
        Self {
            name: name.into(),
            type_expr: Some(type_expr),
            default_value: None,
        }
    }

    /// Extract just the names from a list of typed params.
    pub fn names(params: &[TypedParam]) -> Vec<String> {
        params.iter().map(|p| p.name.clone()).collect()
    }

    /// Return the index of the first parameter with a default value, or None.
    pub fn default_start(params: &[TypedParam]) -> Option<usize> {
        params.iter().position(|p| p.default_value.is_some())
    }
}