harn-parser 0.10.167

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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Operator vocabulary: spelling, precedence, and associativity.
//!
//! This module is the single owner of Harn's expression-operator grammar. The
//! parser climbs [`OperatorGrammar::CURRENT`], the formatter and `harn fix`
//! decide parenthesization with [`operand_needs_parens`], and the spec's
//! precedence table and the tree-sitter grammar's precedence constants are
//! generated from or drift-checked against [`Precedence::ALL`].
//!
//! The groups follow Swift's standard precedence groups where Harn has the
//! same operator: `??` binds looser than range formation and arithmetic and
//! tighter than comparison, and range formation (`a..b`, `a..=b`) binds looser
//! than arithmetic and does not associate.

use std::fmt;

/// A binary operator. Spelling, wire name, and precedence live here so no
/// consumer compares operator text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum BinaryOperator {
    /// `|>`
    Pipe,
    /// `||`
    Or,
    /// `&&`
    And,
    /// `==`
    Eq,
    /// `!=`
    Neq,
    /// `<`
    Lt,
    /// `>`
    Gt,
    /// `<=`
    Lte,
    /// `>=`
    Gte,
    /// `in`
    In,
    /// `not in`
    NotIn,
    /// `??`
    NilCoalesce,
    /// `+`
    Add,
    /// `-`
    Sub,
    /// `*`
    Mul,
    /// `/`
    Div,
    /// `%`
    Mod,
    /// `**`
    Pow,
}

impl BinaryOperator {
    pub const ALL: [BinaryOperator; 18] = [
        BinaryOperator::Pipe,
        BinaryOperator::Or,
        BinaryOperator::And,
        BinaryOperator::Eq,
        BinaryOperator::Neq,
        BinaryOperator::Lt,
        BinaryOperator::Gt,
        BinaryOperator::Lte,
        BinaryOperator::Gte,
        BinaryOperator::In,
        BinaryOperator::NotIn,
        BinaryOperator::NilCoalesce,
        BinaryOperator::Add,
        BinaryOperator::Sub,
        BinaryOperator::Mul,
        BinaryOperator::Div,
        BinaryOperator::Mod,
        BinaryOperator::Pow,
    ];

    /// The operator as written in Harn source.
    #[must_use]
    pub const fn symbol(self) -> &'static str {
        match self {
            BinaryOperator::Pipe => "|>",
            BinaryOperator::Or => "||",
            BinaryOperator::And => "&&",
            BinaryOperator::Eq => "==",
            BinaryOperator::Neq => "!=",
            BinaryOperator::Lt => "<",
            BinaryOperator::Gt => ">",
            BinaryOperator::Lte => "<=",
            BinaryOperator::Gte => ">=",
            BinaryOperator::In => "in",
            BinaryOperator::NotIn => "not in",
            BinaryOperator::NilCoalesce => "??",
            BinaryOperator::Add => "+",
            BinaryOperator::Sub => "-",
            BinaryOperator::Mul => "*",
            BinaryOperator::Div => "/",
            BinaryOperator::Mod => "%",
            BinaryOperator::Pow => "**",
        }
    }

    /// The stable identifier used by AST JSON and other wire projections.
    /// It equals [`Self::symbol`] except that `not in` is spelled `not_in`.
    #[must_use]
    pub const fn wire_name(self) -> &'static str {
        match self {
            BinaryOperator::NotIn => "not_in",
            other => other.symbol(),
        }
    }

    /// Resolve a wire name produced by [`Self::wire_name`].
    #[must_use]
    pub fn from_wire_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|op| op.wire_name() == name)
    }

    #[must_use]
    pub const fn precedence(self) -> Precedence {
        match self {
            BinaryOperator::Pipe => Precedence::Pipe,
            BinaryOperator::Or => Precedence::LogicalOr,
            BinaryOperator::And => Precedence::LogicalAnd,
            BinaryOperator::Eq | BinaryOperator::Neq => Precedence::Equality,
            BinaryOperator::Lt
            | BinaryOperator::Gt
            | BinaryOperator::Lte
            | BinaryOperator::Gte
            | BinaryOperator::In
            | BinaryOperator::NotIn => Precedence::Comparison,
            BinaryOperator::NilCoalesce => Precedence::NilCoalescing,
            BinaryOperator::Add | BinaryOperator::Sub => Precedence::Additive,
            BinaryOperator::Mul | BinaryOperator::Div | BinaryOperator::Mod => {
                Precedence::Multiplicative
            }
            BinaryOperator::Pow => Precedence::Exponent,
        }
    }

    /// Whether a line break may precede the operator inside an expression.
    ///
    /// `-` must not, so a line that starts with `-x` remains a new statement;
    /// `in` and `not in` must not, so a `for x in` header cannot be split.
    #[must_use]
    pub const fn continues_across_newline(self) -> bool {
        !matches!(
            self,
            BinaryOperator::Sub | BinaryOperator::In | BinaryOperator::NotIn
        )
    }

    /// The operator a compound assignment (`+=`, `-=`, ...) applies.
    #[must_use]
    pub const fn is_compound_assignable(self) -> bool {
        matches!(
            self,
            BinaryOperator::Add
                | BinaryOperator::Sub
                | BinaryOperator::Mul
                | BinaryOperator::Div
                | BinaryOperator::Mod
        )
    }

    /// Operators whose result is always a boolean.
    #[must_use]
    pub const fn is_comparison(self) -> bool {
        matches!(
            self.precedence(),
            Precedence::Equality | Precedence::Comparison
        )
    }

    #[must_use]
    pub const fn is_logical(self) -> bool {
        matches!(self, BinaryOperator::And | BinaryOperator::Or)
    }

    #[must_use]
    pub const fn is_arithmetic(self) -> bool {
        matches!(
            self,
            BinaryOperator::Add
                | BinaryOperator::Sub
                | BinaryOperator::Mul
                | BinaryOperator::Div
                | BinaryOperator::Mod
                | BinaryOperator::Pow
        )
    }
}

impl fmt::Display for BinaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.symbol())
    }
}

impl serde::Serialize for BinaryOperator {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.wire_name())
    }
}

/// A prefix operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum UnaryOperator {
    /// `!`
    Not,
    /// `-`
    Neg,
}

impl UnaryOperator {
    pub const ALL: [UnaryOperator; 2] = [UnaryOperator::Not, UnaryOperator::Neg];

    #[must_use]
    pub const fn symbol(self) -> &'static str {
        match self {
            UnaryOperator::Not => "!",
            UnaryOperator::Neg => "-",
        }
    }
}

impl fmt::Display for UnaryOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.symbol())
    }
}

impl serde::Serialize for UnaryOperator {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.symbol())
    }
}

/// How operators of equal precedence group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Associativity {
    Left,
    Right,
    /// Chaining requires explicit parentheses.
    None,
}

impl Associativity {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Associativity::Left => "left",
            Associativity::Right => "right",
            Associativity::None => "none",
        }
    }
}

/// Expression precedence groups, loosest first. The derived ordering is the
/// binding order of [`OperatorGrammar::CURRENT`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Precedence {
    /// `a |> f`
    Pipe,
    /// `c ? a : b`
    Ternary,
    LogicalOr,
    LogicalAnd,
    Equality,
    /// `<`, `>`, `<=`, `>=`, `in`, `not in`
    Comparison,
    /// `??`
    NilCoalescing,
    /// `a..b`, `a..=b`
    Range,
    Additive,
    Multiplicative,
    /// `!x`, `-x`
    Prefix,
    /// `a ** b`
    Exponent,
    /// Calls, member access, subscripts, postfix `?`/`!`, and every primary.
    Postfix,
}

impl Precedence {
    pub const ALL: [Precedence; 13] = [
        Precedence::Pipe,
        Precedence::Ternary,
        Precedence::LogicalOr,
        Precedence::LogicalAnd,
        Precedence::Equality,
        Precedence::Comparison,
        Precedence::NilCoalescing,
        Precedence::Range,
        Precedence::Additive,
        Precedence::Multiplicative,
        Precedence::Prefix,
        Precedence::Exponent,
        Precedence::Postfix,
    ];

    /// Stable group name used by the spec table and the tree-sitter `PREC`
    /// constants.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Precedence::Pipe => "pipe",
            Precedence::Ternary => "ternary",
            Precedence::LogicalOr => "logical_or",
            Precedence::LogicalAnd => "logical_and",
            Precedence::Equality => "equality",
            Precedence::Comparison => "comparison",
            Precedence::NilCoalescing => "nil_coalescing",
            Precedence::Range => "range",
            Precedence::Additive => "additive",
            Precedence::Multiplicative => "multiplicative",
            Precedence::Prefix => "prefix",
            Precedence::Exponent => "exponent",
            Precedence::Postfix => "postfix",
        }
    }

    #[must_use]
    pub const fn associativity(self) -> Associativity {
        match self {
            Precedence::Ternary | Precedence::Prefix | Precedence::Exponent => Associativity::Right,
            Precedence::Range => Associativity::None,
            _ => Associativity::Left,
        }
    }

    /// What the group is, for the spec's precedence table.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Precedence::Pipe => "Pipe",
            Precedence::Ternary => "Ternary conditional",
            Precedence::LogicalOr => "Logical OR",
            Precedence::LogicalAnd => "Logical AND",
            Precedence::Equality => "Equality",
            Precedence::Comparison => "Comparison / membership",
            Precedence::NilCoalescing => "Nil coalescing",
            Precedence::Range => "Range formation",
            Precedence::Additive => "Additive",
            Precedence::Multiplicative => "Multiplicative",
            Precedence::Prefix => "Unary prefix",
            Precedence::Exponent => "Exponentiation",
            Precedence::Postfix => "Postfix",
        }
    }

    /// Source spellings of the operators in this group, for documentation.
    #[must_use]
    pub const fn spellings(self) -> &'static [&'static str] {
        match self {
            Precedence::Pipe => &["|>"],
            Precedence::Ternary => &["? :"],
            Precedence::LogicalOr => &["||"],
            Precedence::LogicalAnd => &["&&"],
            Precedence::Equality => &["==", "!="],
            Precedence::Comparison => &["<", ">", "<=", ">=", "in", "not in"],
            Precedence::NilCoalescing => &["??"],
            Precedence::Range => &[RANGE_EXCLUSIVE, RANGE_INCLUSIVE],
            Precedence::Additive => &["+", "-"],
            Precedence::Multiplicative => &["*", "/", "%"],
            Precedence::Prefix => &["!", "-"],
            Precedence::Exponent => &["**"],
            Precedence::Postfix => &[".", "?.", "[]", "?.[]", "[:]", "()", "?", "!"],
        }
    }

    /// One-based binding strength in the current grammar (1 = loosest).
    #[must_use]
    pub fn level(self) -> usize {
        Self::ALL
            .iter()
            .position(|group| *group == self)
            .map_or(0, |index| index + 1)
    }

    /// The precedence an AST expression node occupies in the current grammar.
    #[must_use]
    pub fn of_node(node: &crate::Node) -> Precedence {
        match node {
            crate::Node::BinaryOp { op, .. } => op.precedence(),
            crate::Node::UnaryOp { .. } => Precedence::Prefix,
            crate::Node::RangeExpr { .. } => Precedence::Range,
            crate::Node::Ternary { .. } => Precedence::Ternary,
            _ => Precedence::Postfix,
        }
    }
}

/// Exclusive-end range spelling: `0..n` yields `0` through `n - 1`.
pub const RANGE_EXCLUSIVE: &str = "..";
/// Inclusive-end range spelling: `1..=n` yields `1` through `n`.
pub const RANGE_INCLUSIVE: &str = "..=";

/// Which operand of an operator a child expression occupies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperandSide {
    Left,
    Right,
    /// The single operand of a prefix operator.
    Prefix,
    /// The receiver of a call, member access, subscript, or postfix operator.
    Postfix,
    /// The condition of `c ? a : b`.
    TernaryCondition,
    /// Either branch of `c ? a : b`.
    TernaryBranch,
}

/// The loosest precedence an expression may have to appear bare as the
/// `side` operand of an operator in group `parent`.
#[must_use]
pub fn loosest_bare_operand(parent: Precedence, side: OperandSide) -> Precedence {
    match side {
        OperandSide::Prefix => Precedence::Prefix,
        OperandSide::Postfix => Precedence::Postfix,
        OperandSide::TernaryCondition => Precedence::LogicalOr,
        OperandSide::TernaryBranch => Precedence::Ternary,
        // The exponent accepts a prefix operand (`2 ** -1`) while the base
        // binds tighter than a prefix (`-2 ** 2` is `-(2 ** 2)`).
        OperandSide::Right if parent == Precedence::Exponent => Precedence::Prefix,
        OperandSide::Left | OperandSide::Right => {
            let same_group_allowed = matches!(
                (parent.associativity(), side),
                (Associativity::Left, OperandSide::Left)
                    | (Associativity::Right, OperandSide::Right)
            );
            if same_group_allowed {
                parent
            } else {
                parent.tighter().unwrap_or(Precedence::Postfix)
            }
        }
    }
}

/// Whether `child` must be parenthesized to keep its grouping as the `side`
/// operand of `parent` in the current grammar.
#[must_use]
pub fn operand_needs_parens(parent: Precedence, child: Precedence, side: OperandSide) -> bool {
    child < loosest_bare_operand(parent, side)
}

impl Precedence {
    /// The next tighter group, if any.
    #[must_use]
    pub fn tighter(self) -> Option<Precedence> {
        Self::ALL.get(self.level()).copied()
    }
}

/// A precedence ladder the parser climbs. [`Self::CURRENT`] is the language;
/// [`Self::LEGACY`] reproduces the pre-0.11 operator grammar (`??` between
/// additive and multiplicative, `a to b [exclusive]` ranges just above `|>`)
/// and exists only so `harn fix --migrate-operator-syntax` can read old source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperatorGrammar {
    ladder: &'static [Precedence],
    legacy_ranges: bool,
}

impl OperatorGrammar {
    pub const CURRENT: OperatorGrammar = OperatorGrammar {
        ladder: &Precedence::ALL,
        legacy_ranges: false,
    };

    pub const LEGACY: OperatorGrammar = OperatorGrammar {
        ladder: &[
            Precedence::Pipe,
            Precedence::Range,
            Precedence::Ternary,
            Precedence::LogicalOr,
            Precedence::LogicalAnd,
            Precedence::Equality,
            Precedence::Comparison,
            Precedence::Additive,
            Precedence::NilCoalescing,
            Precedence::Multiplicative,
            Precedence::Prefix,
            Precedence::Exponent,
            Precedence::Postfix,
        ],
        legacy_ranges: true,
    };

    #[must_use]
    pub fn loosest(self) -> Precedence {
        self.ladder[0]
    }

    /// The group one step tighter than `group` on this ladder.
    #[must_use]
    pub fn tighter(self, group: Precedence) -> Precedence {
        self.ladder
            .iter()
            .position(|candidate| *candidate == group)
            .and_then(|index| self.ladder.get(index + 1))
            .copied()
            .unwrap_or(Precedence::Postfix)
    }

    /// Whether this grammar spells ranges `a to b [exclusive]`.
    #[must_use]
    pub fn legacy_ranges(self) -> bool {
        self.legacy_ranges
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wire_names_round_trip() {
        for op in BinaryOperator::ALL {
            assert_eq!(BinaryOperator::from_wire_name(op.wire_name()), Some(op));
        }
        assert_eq!(BinaryOperator::from_wire_name("not in"), None);
    }

    #[test]
    fn nil_coalescing_sits_between_comparison_and_range() {
        assert!(Precedence::Comparison < Precedence::NilCoalescing);
        assert!(Precedence::NilCoalescing < Precedence::Range);
        assert!(Precedence::Range < Precedence::Additive);
    }

    #[test]
    fn parenthesization_follows_associativity() {
        let add = Precedence::Additive;
        assert!(!operand_needs_parens(add, add, OperandSide::Left));
        assert!(operand_needs_parens(add, add, OperandSide::Right));
        assert!(operand_needs_parens(
            Precedence::Range,
            Precedence::Range,
            OperandSide::Left
        ));
        assert!(!operand_needs_parens(
            Precedence::Exponent,
            Precedence::Prefix,
            OperandSide::Right
        ));
        assert!(operand_needs_parens(
            Precedence::Exponent,
            Precedence::Prefix,
            OperandSide::Left
        ));
        assert!(operand_needs_parens(
            Precedence::Additive,
            Precedence::NilCoalescing,
            OperandSide::Left
        ));
        assert!(!operand_needs_parens(
            Precedence::NilCoalescing,
            Precedence::Additive,
            OperandSide::Right
        ));
    }

    #[test]
    fn legacy_ladder_is_a_permutation_of_the_current_groups() {
        let mut legacy = OperatorGrammar::LEGACY.ladder.to_vec();
        legacy.sort();
        assert_eq!(legacy, Precedence::ALL.to_vec());
    }
}