harn-parser 0.7.4

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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 {
    Pipeline {
        name: String,
        params: Vec<String>,
        body: Vec<SNode>,
        extends: Option<String>,
        is_pub: bool,
    },
    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,
        type_params: Vec<TypeParam>,
        variants: Vec<EnumVariant>,
        is_pub: bool,
    },
    StructDecl {
        name: String,
        type_params: Vec<TypeParam>,
        fields: Vec<StructField>,
        is_pub: bool,
    },
    InterfaceDecl {
        name: String,
        type_params: Vec<TypeParam>,
        associated_types: Vec<(String, Option<TypeExpr>)>,
        methods: Vec<InterfaceMethod>,
    },
    /// Impl block: impl TypeName { fn method(self, ...) { ... } ... }
    ImplBlock {
        type_name: String,
        methods: Vec<SNode>,
    },

    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,
    },
    ToolDecl {
        name: String,
        description: Option<String>,
        params: Vec<TypedParam>,
        return_type: Option<TypeExpr>,
        body: Vec<SNode>,
        is_pub: bool,
    },
    TypeDecl {
        name: String,
        type_params: Vec<TypeParam>,
        type_expr: TypeExpr,
    },
    SpawnExpr {
        body: Vec<SNode>,
    },
    /// Duration literal: 500ms, 5s, 30m, 2h, 1d, 1w
    DurationLiteral(u64),
    /// Range expression: `start to end` (inclusive) or `start to end exclusive` (half-open)
    RangeExpr {
        start: Box<SNode>,
        end: Box<SNode>,
        inclusive: bool,
    },
    /// Guard clause: guard condition else { body }
    GuardStmt {
        condition: Box<SNode>,
        else_body: Vec<SNode>,
    },
    RequireStmt {
        condition: Box<SNode>,
        message: Option<Box<SNode>>,
    },
    /// Defer statement: defer { body } — runs body at scope exit.
    DeferStmt {
        body: Vec<SNode>,
    },
    /// 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,

    Parallel {
        mode: ParallelMode,
        /// For Count mode: the count expression. For Each/Settle: the list expression.
        expr: Box<SNode>,
        variable: Option<String>,
        body: Vec<SNode>,
        /// Optional trailing `with { max_concurrent: N, ... }` option block.
        /// A vec (rather than a dict) preserves source order for error
        /// reporting and keeps parsing cheap. Only `max_concurrent` is
        /// currently honored; unknown keys are rejected by the parser.
        options: Vec<(String, SNode)>,
    },

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

    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>,
    },

    InterpolatedString(Vec<StringSegment>),
    StringLiteral(String),
    /// Raw string literal `r"..."` — no escape processing.
    RawStringLiteral(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>,
    },
    /// Try-star operator: `try* EXPR` — evaluates EXPR; on throw, runs
    /// pending finally blocks up to the enclosing catch and rethrows
    /// the original value. On success, evaluates to EXPR's value.
    /// Lowered per spec/HARN_SPEC.md as:
    ///   { let _r = try { EXPR }
    ///     guard is_ok(_r) else { throw unwrap_err(_r) }
    ///     unwrap(_r) }
    TryStar {
        operand: Box<SNode>,
    },

    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,
    },
}

/// Parallel execution mode.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ParallelMode {
    /// `parallel N { i -> ... }` — run N concurrent tasks.
    Count,
    /// `parallel each list { item -> ... }` — map over list concurrently.
    Each,
    /// `parallel settle list { item -> ... }` — map with error collection.
    Settle,
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
    pub pattern: SNode,
    /// Optional guard: `pattern if condition -> { body }`.
    pub guard: Option<Box<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 type_params: Vec<TypeParam>,
    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 lazy iterator type: `iter<int>`. Yields values of the inner type
    /// via the combinator/sink protocol (`VmValue::Iter` at runtime).
    Iter(Box<TypeExpr>),
    /// A generic type application: `Option<int>`, `Result<string, int>`.
    Applied { name: String, args: Vec<TypeExpr> },
    /// A function type: `fn(int, string) -> bool`.
    FnType {
        params: Vec<TypeExpr>,
        return_type: Box<TypeExpr>,
    },
    /// The bottom type: the type of expressions that never produce a value
    /// (return, throw, break, continue).
    Never,
    /// A string-literal type: `"pass"`, `"fail"`. Assignable to `string`.
    /// Used in unions to represent enum-like discriminated values.
    LitString(String),
    /// An int-literal type: `0`, `1`, `-1`. Assignable to `int`.
    LitInt(i64),
}

/// 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>),
    /// Pair destructuring for `for (a, b) in iter { ... }`. The iter must
    /// yield `VmValue::Pair` values. Not valid in let/var bindings.
    Pair(String, String),
}

/// 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,
    /// Default value if the key is missing (nil), e.g. `{name = "default"}`.
    pub default_value: Option<Box<SNode>>,
}

/// 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,
    /// Default value if the index is out of bounds (nil), e.g. `[a = 0]`.
    pub default_value: Option<Box<SNode>>,
}

/// Declared variance of a generic type parameter.
///
/// - `Invariant` (default, no marker): the parameter appears in both
///   input and output positions, or mutable state. `T<A>` and `T<B>`
///   are unrelated unless `A == B`.
/// - `Covariant` (`out T`): the parameter appears only in output
///   positions (produced, not consumed). `T<Sub>` flows into
///   `T<Super>`.
/// - `Contravariant` (`in T`): the parameter appears only in input
///   positions (consumed, not produced). `T<Super>` flows into
///   `T<Sub>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Variance {
    Invariant,
    Covariant,
    Contravariant,
}

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

impl TypeParam {
    /// Construct an invariant type parameter (the default for
    /// unannotated `<T>`).
    pub fn invariant(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            variance: Variance::Invariant,
        }
    }
}

/// 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>>,
    /// If true, this is a rest parameter (`...name`) that collects remaining arguments.
    pub rest: bool,
}

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

    /// 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,
            rest: false,
        }
    }

    /// 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())
    }
}