Skip to main content

dive_syntax/
ast.rs

1//! Typed views over the concrete syntax tree.
2//!
3//! Each type wraps a [`SyntaxNode`] of one kind and offers accessors for its
4//! parts. They are cheap to clone and never copy text. Accessors return
5//! `Option` because a tree built after a syntax error may be incomplete.
6//!
7//! # Example
8//!
9//! ```
10//! use dive_syntax::{parse_module, ast::{Expr, Unit}};
11//!
12//! let p = parse_module("---- MODULE M ----\nEXTENDS Naturals\nF(a, b) == a + b\n====");
13//! let m = p.module().unwrap();
14//! assert_eq!(m.extends(), ["Naturals"]);
15//! let Some(Unit::OperatorDef(def)) = m.units().next() else { panic!() };
16//! assert_eq!(def.name().as_deref(), Some("F"));
17//! assert_eq!(def.parameters(), ["a", "b"]);
18//! let Some(Expr::Infix(sum)) = def.body() else { panic!() };
19//! assert_eq!(sum.operator().map(|t| t.text().to_string()).as_deref(), Some("+"));
20//! ```
21
22#[allow(
23    clippy::enum_glob_use,
24    reason = "the grammar names over a hundred token and node kinds"
25)]
26use crate::kind::SyntaxKind::{self, *};
27use crate::kind::{SyntaxNode, SyntaxToken};
28
29/// A typed wrapper around a [`SyntaxNode`] of a particular kind.
30pub trait AstNode: Sized {
31    /// Whether nodes of `kind` can be wrapped.
32    fn can_cast(kind: SyntaxKind) -> bool;
33    /// Wraps `node` if it has the right kind.
34    fn cast(node: SyntaxNode) -> Option<Self>;
35    /// The underlying node.
36    fn syntax(&self) -> &SyntaxNode;
37}
38
39macro_rules! ast_node {
40    ($(#[$m:meta])* $name:ident, $kind:ident) => {
41        $(#[$m])*
42        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
43        pub struct $name(SyntaxNode);
44
45        impl AstNode for $name {
46            fn can_cast(kind: SyntaxKind) -> bool {
47                kind == $kind
48            }
49            fn cast(node: SyntaxNode) -> Option<Self> {
50                Self::can_cast(node.kind()).then(|| Self(node))
51            }
52            fn syntax(&self) -> &SyntaxNode {
53                &self.0
54            }
55        }
56    };
57}
58
59fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
60    parent.children().find_map(N::cast)
61}
62
63fn children<N: AstNode>(parent: &SyntaxNode) -> impl Iterator<Item = N> + use<N> {
64    parent.children().filter_map(N::cast)
65}
66
67/// The non-trivia tokens directly under `parent`.
68fn tokens(parent: &SyntaxNode) -> impl Iterator<Item = SyntaxToken> + use<> {
69    parent
70        .children_with_tokens()
71        .filter_map(rowan::NodeOrToken::into_token)
72        .filter(|t| !t.kind().is_trivia())
73}
74
75fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
76    tokens(parent).find(|t| t.kind() == kind)
77}
78
79fn has_token(parent: &SyntaxNode, kind: SyntaxKind) -> bool {
80    token(parent, kind).is_some()
81}
82
83fn ident_texts(parent: &SyntaxNode) -> Vec<String> {
84    tokens(parent)
85        .filter(|t| t.kind() == IDENT)
86        .map(|t| t.text().to_owned())
87        .collect()
88}
89
90fn first_expr(parent: &SyntaxNode) -> Option<Expr> {
91    parent.children().find_map(Expr::cast)
92}
93
94fn last_expr(parent: &SyntaxNode) -> Option<Expr> {
95    parent.children().filter_map(Expr::cast).last()
96}
97
98ast_node!(
99    /// The whole file.
100    SourceFile,
101    SOURCE_FILE
102);
103ast_node!(
104    /// A module (top-level or nested).
105    Module,
106    MODULE
107);
108ast_node!(
109    /// `VARIABLE(S) x, y`.
110    VariableDecl,
111    VARIABLE_DECL
112);
113ast_node!(
114    /// `CONSTANT(S) ...`.
115    ConstantDecl,
116    CONSTANT_DECL
117);
118ast_node!(
119    /// `RECURSIVE ...`.
120    RecursiveDecl,
121    RECURSIVE_DECL
122);
123ast_node!(
124    /// An operator definition.
125    OperatorDef,
126    OPERATOR_DEF
127);
128ast_node!(
129    /// A function definition `f[x \in S] == e`.
130    FunctionDef,
131    FUNCTION_DEF
132);
133ast_node!(
134    /// A module definition `I == INSTANCE M WITH ...`.
135    ModuleDef,
136    MODULE_DEF
137);
138ast_node!(
139    /// `[LOCAL] INSTANCE M WITH ...` as a unit.
140    Instance,
141    INSTANCE
142);
143ast_node!(
144    /// `INSTANCE M WITH ...`.
145    Instantiation,
146    INSTANTIATION
147);
148ast_node!(
149    /// `x <- e`.
150    Substitution,
151    SUBSTITUTION
152);
153ast_node!(
154    /// `ASSUME`/`ASSUMPTION`/`AXIOM`.
155    Assumption,
156    ASSUMPTION
157);
158ast_node!(
159    /// `THEOREM`, `LEMMA`, `PROPOSITION`, `COROLLARY`.
160    Theorem,
161    THEOREM
162);
163ast_node!(
164    /// `USE` or `HIDE`.
165    UseOrHide,
166    USE_OR_HIDE
167);
168ast_node!(
169    /// A step-structured proof.
170    Proof,
171    PROOF
172);
173ast_node!(
174    /// `BY ...`, `OBVIOUS` or `OMITTED`.
175    TerminalProof,
176    TERMINAL_PROOF
177);
178ast_node!(
179    /// One proof step.
180    ProofStep,
181    PROOF_STEP
182);
183ast_node!(
184    /// `ASSUME ... PROVE ...`.
185    AssumeProve,
186    ASSUME_PROVE
187);
188ast_node!(
189    /// A declared constant or parameter `c` or `F(_, _)`.
190    IdentDecl,
191    IDENT_DECL
192);
193ast_node!(
194    /// `x \in S` or `<<x, y>> \in S` in a quantifier or function.
195    QuantBound,
196    QUANT_BOUND
197);
198ast_node!(
199    /// A possibly qualified name.
200    GeneralId,
201    GENERAL_ID
202);
203ast_node!(
204    /// `Op(args)`.
205    OpApplication,
206    OP_APPLICATION
207);
208ast_node!(
209    /// `a op b`.
210    InfixExpr,
211    INFIX_EXPR
212);
213ast_node!(
214    /// `op e`.
215    PrefixExpr,
216    PREFIX_EXPR
217);
218ast_node!(
219    /// `e op`.
220    PostfixExpr,
221    POSTFIX_EXPR
222);
223
224impl SourceFile {
225    /// The top-level module.
226    #[must_use]
227    pub fn module(&self) -> Option<Module> {
228        child(&self.0)
229    }
230}
231
232/// A module-level unit.
233#[derive(Debug, Clone, PartialEq, Eq, Hash)]
234pub enum Unit {
235    /// `VARIABLE ...`
236    VariableDecl(VariableDecl),
237    /// `CONSTANT ...`
238    ConstantDecl(ConstantDecl),
239    /// `RECURSIVE ...`
240    RecursiveDecl(RecursiveDecl),
241    /// An operator definition.
242    OperatorDef(OperatorDef),
243    /// A function definition.
244    FunctionDef(FunctionDef),
245    /// A module definition (`I == INSTANCE M`).
246    ModuleDef(ModuleDef),
247    /// `INSTANCE M`.
248    Instance(Instance),
249    /// An assumption.
250    Assumption(Assumption),
251    /// A theorem.
252    Theorem(Theorem),
253    /// `USE`/`HIDE`.
254    UseOrHide(UseOrHide),
255    /// A nested module.
256    Module(Module),
257    /// Tokens skipped after a syntax error.
258    Error(SyntaxNode),
259}
260
261impl Unit {
262    fn cast(node: SyntaxNode) -> Option<Self> {
263        Some(match node.kind() {
264            VARIABLE_DECL => Self::VariableDecl(VariableDecl(node)),
265            CONSTANT_DECL => Self::ConstantDecl(ConstantDecl(node)),
266            RECURSIVE_DECL => Self::RecursiveDecl(RecursiveDecl(node)),
267            OPERATOR_DEF => Self::OperatorDef(OperatorDef(node)),
268            FUNCTION_DEF => Self::FunctionDef(FunctionDef(node)),
269            MODULE_DEF => Self::ModuleDef(ModuleDef(node)),
270            INSTANCE => Self::Instance(Instance(node)),
271            ASSUMPTION => Self::Assumption(Assumption(node)),
272            THEOREM => Self::Theorem(Theorem(node)),
273            USE_OR_HIDE => Self::UseOrHide(UseOrHide(node)),
274            MODULE => Self::Module(Module(node)),
275            ERROR => Self::Error(node),
276            _ => return None,
277        })
278    }
279}
280
281impl Module {
282    /// The module's name.
283    #[must_use]
284    pub fn name(&self) -> Option<String> {
285        let header = self.0.children().find(|n| n.kind() == MODULE_HEADER)?;
286        token(&header, IDENT).map(|t| t.text().to_owned())
287    }
288
289    /// Names in the `EXTENDS` clause.
290    #[must_use]
291    pub fn extends(&self) -> Vec<String> {
292        self.0
293            .children()
294            .find(|n| n.kind() == EXTENDS)
295            .map_or_else(Vec::new, |e| ident_texts(&e))
296    }
297
298    /// The units of the module body, in order.
299    pub fn units(&self) -> impl Iterator<Item = Unit> + use<> {
300        self.0.children().filter_map(Unit::cast)
301    }
302
303    /// The operator definitions directly in this module.
304    pub fn operator_definitions(&self) -> impl Iterator<Item = OperatorDef> + use<> {
305        children(&self.0)
306    }
307
308    /// Whether the closing `====` is present.
309    #[must_use]
310    pub fn is_closed(&self) -> bool {
311        has_token(&self.0, END_MODULE)
312    }
313}
314
315impl VariableDecl {
316    /// The declared variable names.
317    #[must_use]
318    pub fn names(&self) -> Vec<String> {
319        ident_texts(&self.0)
320    }
321}
322
323impl ConstantDecl {
324    /// The declared items.
325    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
326        self.0.children()
327    }
328}
329
330impl RecursiveDecl {
331    /// The declared items.
332    pub fn items(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
333        self.0.children()
334    }
335}
336
337impl IdentDecl {
338    /// The declared name.
339    #[must_use]
340    pub fn name(&self) -> Option<String> {
341        token(&self.0, IDENT).map(|t| t.text().to_owned())
342    }
343
344    /// The number of `_` arguments.
345    #[must_use]
346    pub fn arity(&self) -> usize {
347        tokens(&self.0).filter(|t| t.kind() == UNDERSCORE).count()
348    }
349}
350
351/// The text of the operator or name defined by a left-hand side node.
352fn lhs_name(lhs: &SyntaxNode) -> Option<String> {
353    match lhs.kind() {
354        IDENT_LHS => token(lhs, IDENT).map(|t| t.text().to_owned()),
355        PREFIX_LHS => tokens(lhs).next().map(|t| t.text().to_owned()),
356        INFIX_LHS | POSTFIX_LHS => tokens(lhs).nth(1).map(|t| t.text().to_owned()),
357        _ => None,
358    }
359}
360
361fn find_lhs(node: &SyntaxNode) -> Option<SyntaxNode> {
362    node.children()
363        .find(|n| matches!(n.kind(), IDENT_LHS | PREFIX_LHS | INFIX_LHS | POSTFIX_LHS))
364}
365
366impl OperatorDef {
367    /// The defined name or operator symbol.
368    #[must_use]
369    pub fn name(&self) -> Option<String> {
370        find_lhs(&self.0).and_then(|l| lhs_name(&l))
371    }
372
373    /// The left-hand side node (`IDENT_LHS`, `PREFIX_LHS`, `INFIX_LHS` or `POSTFIX_LHS`).
374    #[must_use]
375    pub fn lhs(&self) -> Option<SyntaxNode> {
376        find_lhs(&self.0)
377    }
378
379    /// Parameter names (identifiers and operator symbols).
380    #[must_use]
381    pub fn parameters(&self) -> Vec<String> {
382        let Some(lhs) = find_lhs(&self.0) else {
383            return Vec::new();
384        };
385        match lhs.kind() {
386            IDENT_LHS => lhs
387                .children()
388                .filter_map(|p| match p.kind() {
389                    IDENT_DECL => token(&p, IDENT).map(|t| t.text().to_owned()),
390                    PREFIX_DECL => tokens(&p).next().map(|t| t.text().to_owned()),
391                    INFIX_DECL | POSTFIX_DECL => tokens(&p).nth(1).map(|t| t.text().to_owned()),
392                    _ => None,
393                })
394                .collect(),
395            PREFIX_LHS => tokens(&lhs)
396                .nth(1)
397                .map(|t| t.text().to_owned())
398                .into_iter()
399                .collect(),
400            INFIX_LHS => {
401                let t: Vec<SyntaxToken> = tokens(&lhs).collect();
402                [t.first(), t.get(2)]
403                    .into_iter()
404                    .flatten()
405                    .map(|t| t.text().to_owned())
406                    .collect()
407            }
408            _ => tokens(&lhs)
409                .next()
410                .map(|t| t.text().to_owned())
411                .into_iter()
412                .collect(),
413        }
414    }
415
416    /// Whether the definition is `LOCAL`.
417    #[must_use]
418    pub fn is_local(&self) -> bool {
419        has_token(&self.0, LOCAL_KW)
420    }
421
422    /// The defining expression.
423    #[must_use]
424    pub fn body(&self) -> Option<Expr> {
425        last_expr(&self.0)
426    }
427}
428
429impl FunctionDef {
430    /// The function name.
431    #[must_use]
432    pub fn name(&self) -> Option<String> {
433        token(&self.0, IDENT).map(|t| t.text().to_owned())
434    }
435
436    /// The bound variables.
437    pub fn bounds(&self) -> impl Iterator<Item = QuantBound> + use<> {
438        children(&self.0)
439    }
440
441    /// The defining expression.
442    #[must_use]
443    pub fn body(&self) -> Option<Expr> {
444        last_expr(&self.0)
445    }
446
447    /// Whether the definition is `LOCAL`.
448    #[must_use]
449    pub fn is_local(&self) -> bool {
450        has_token(&self.0, LOCAL_KW)
451    }
452}
453
454impl ModuleDef {
455    /// The defined name.
456    #[must_use]
457    pub fn name(&self) -> Option<String> {
458        find_lhs(&self.0).and_then(|l| lhs_name(&l))
459    }
460
461    /// The instantiation.
462    #[must_use]
463    pub fn instantiation(&self) -> Option<Instantiation> {
464        child(&self.0)
465    }
466}
467
468impl Instance {
469    /// Whether the instance is `LOCAL`.
470    #[must_use]
471    pub fn is_local(&self) -> bool {
472        has_token(&self.0, LOCAL_KW)
473    }
474
475    /// The instantiation.
476    #[must_use]
477    pub fn instantiation(&self) -> Option<Instantiation> {
478        child(&self.0)
479    }
480}
481
482impl Instantiation {
483    /// The instantiated module's name.
484    #[must_use]
485    pub fn module_name(&self) -> Option<String> {
486        token(&self.0, IDENT).map(|t| t.text().to_owned())
487    }
488
489    /// The `WITH` substitutions.
490    pub fn substitutions(&self) -> impl Iterator<Item = Substitution> + use<> {
491        children(&self.0)
492    }
493}
494
495impl Substitution {
496    /// The substituted name or operator symbol.
497    #[must_use]
498    pub fn target(&self) -> Option<SyntaxToken> {
499        tokens(&self.0).next()
500    }
501
502    /// The replacement (an expression, `OP_REF` or `LAMBDA` node).
503    #[must_use]
504    pub fn replacement(&self) -> Option<SyntaxNode> {
505        self.0.children().last()
506    }
507}
508
509impl Assumption {
510    /// The assumption's name, if any.
511    #[must_use]
512    pub fn name(&self) -> Option<String> {
513        has_token(&self.0, DEF_EQ)
514            .then(|| token(&self.0, IDENT).map(|t| t.text().to_owned()))
515            .flatten()
516    }
517
518    /// The assumed expression.
519    #[must_use]
520    pub fn expr(&self) -> Option<Expr> {
521        last_expr(&self.0)
522    }
523}
524
525impl Theorem {
526    /// The theorem's name, if any.
527    #[must_use]
528    pub fn name(&self) -> Option<String> {
529        has_token(&self.0, DEF_EQ)
530            .then(|| token(&self.0, IDENT).map(|t| t.text().to_owned()))
531            .flatten()
532    }
533
534    /// The statement: an `ASSUME_PROVE` (or labelled one) or an expression.
535    #[must_use]
536    pub fn statement(&self) -> Option<SyntaxNode> {
537        self.0
538            .children()
539            .find(|n| n.kind() != PROOF && n.kind() != TERMINAL_PROOF)
540    }
541
542    /// The proof, if any (`PROOF` or `TERMINAL_PROOF` node).
543    #[must_use]
544    pub fn proof(&self) -> Option<SyntaxNode> {
545        self.0
546            .children()
547            .find(|n| matches!(n.kind(), PROOF | TERMINAL_PROOF))
548    }
549}
550
551impl Proof {
552    /// The steps, the last of which is the `QED` step.
553    pub fn steps(&self) -> impl Iterator<Item = ProofStep> + use<> {
554        children(&self.0)
555    }
556}
557
558impl ProofStep {
559    /// The step number token, e.g. `<1>2.`.
560    #[must_use]
561    pub fn step_token(&self) -> Option<SyntaxToken> {
562        tokens(&self.0).next()
563    }
564
565    /// The step body node.
566    #[must_use]
567    pub fn body(&self) -> Option<SyntaxNode> {
568        self.0
569            .children()
570            .find(|n| !matches!(n.kind(), PROOF | TERMINAL_PROOF))
571    }
572
573    /// The step's proof, if any.
574    #[must_use]
575    pub fn proof(&self) -> Option<SyntaxNode> {
576        self.0
577            .children()
578            .find(|n| matches!(n.kind(), PROOF | TERMINAL_PROOF))
579    }
580}
581
582impl QuantBound {
583    /// The bound names (also those inside a `<<x, y>>` tuple).
584    #[must_use]
585    pub fn names(&self) -> Vec<String> {
586        let mut v = ident_texts(&self.0);
587        if let Some(t) = self.0.children().find(|n| n.kind() == IDENT_TUPLE) {
588            v.extend(ident_texts(&t));
589        }
590        v
591    }
592
593    /// Whether the names form a tuple pattern.
594    #[must_use]
595    pub fn is_tuple(&self) -> bool {
596        self.0.children().any(|n| n.kind() == IDENT_TUPLE)
597    }
598
599    /// The bounding set.
600    #[must_use]
601    pub fn set(&self) -> Option<Expr> {
602        first_expr(&self.0)
603    }
604}
605
606/// Defines a wrapper accepting several node kinds.
607macro_rules! ast_node_multi {
608    ($(#[$m:meta])* $name:ident, [$($kind:ident),+]) => {
609        $(#[$m])*
610        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
611        pub struct $name(SyntaxNode);
612
613        impl AstNode for $name {
614            fn can_cast(kind: SyntaxKind) -> bool {
615                matches!(kind, $($kind)|+)
616            }
617            fn cast(node: SyntaxNode) -> Option<Self> {
618                Self::can_cast(node.kind()).then(|| Self(node))
619            }
620            fn syntax(&self) -> &SyntaxNode {
621                &self.0
622            }
623        }
624    };
625}
626
627ast_node!(
628    /// `LET defs IN e`.
629    LetExpr,
630    LET_EXPR
631);
632ast_node!(
633    /// `IF c THEN a ELSE b`.
634    IfExpr,
635    IF_EXPR
636);
637ast_node!(
638    /// `CASE p -> e [] ... [] OTHER -> e`.
639    CaseExpr,
640    CASE_EXPR
641);
642ast_node!(
643    /// `CHOOSE x \in S : P`.
644    ChooseExpr,
645    CHOOSE
646);
647ast_node!(
648    /// `f[a, b]`.
649    FcnAppl,
650    FCN_APPL
651);
652ast_node!(
653    /// `r.field`.
654    RecordField,
655    RECORD_FIELD
656);
657ast_node!(
658    /// `lab :: e`.
659    LabelExpr,
660    LABEL
661);
662ast_node!(
663    /// `LAMBDA x, y : e` (an operator argument, not an expression).
664    Lambda,
665    LAMBDA
666);
667ast_node_multi!(
668    /// `\A`, `\E` (bounded or not), `\AA` and `\EE`.
669    QuantExpr,
670    [BOUNDED_QUANT, UNBOUNDED_QUANT, TEMPORAL_QUANT]
671);
672ast_node_multi!(
673    /// A bulleted `/\` or `\/` list.
674    JunctionList,
675    [CONJ_LIST, DISJ_LIST]
676);
677
678/// An expression.
679#[derive(Debug, Clone, PartialEq, Eq, Hash)]
680pub enum Expr {
681    /// A name such as `x` or `M!Op`.
682    Name(GeneralId),
683    /// `Op(args)`.
684    Apply(OpApplication),
685    /// `a op b`.
686    Infix(InfixExpr),
687    /// `op e`.
688    Prefix(PrefixExpr),
689    /// `e op`.
690    Postfix(PostfixExpr),
691    /// `LET ... IN e`.
692    Let(LetExpr),
693    /// `IF ... THEN ... ELSE ...`.
694    If(IfExpr),
695    /// `CASE ...`.
696    Case(CaseExpr),
697    /// A quantifier.
698    Quant(QuantExpr),
699    /// `CHOOSE ...`.
700    Choose(ChooseExpr),
701    /// A bulleted conjunction or disjunction list.
702    Junction(JunctionList),
703    /// `f[args]`.
704    FcnAppl(FcnAppl),
705    /// `r.field`.
706    Field(RecordField),
707    /// `lab :: e`.
708    Label(LabelExpr),
709    /// Any other expression form; see [`Expr::syntax`] and its kind.
710    Other(SyntaxNode),
711}
712
713impl Expr {
714    /// Whether nodes of `kind` are expressions.
715    #[must_use]
716    pub fn can_cast(kind: SyntaxKind) -> bool {
717        matches!(
718            kind,
719            GENERAL_ID
720                | OP_APPLICATION
721                | NUMBER_LIT
722                | DECIMAL_LIT
723                | STRING_LIT
724                | PREFIX_EXPR
725                | INFIX_EXPR
726                | POSTFIX_EXPR
727                | CARTESIAN_PRODUCT
728                | PAREN_EXPR
729                | RECORD_FIELD
730                | FCN_APPL
731                | TUPLE
732                | SET_ENUM
733                | SET_FILTER
734                | SET_MAP
735                | FCN_CONSTRUCTOR
736                | SET_OF_FCNS
737                | RECORD
738                | SET_OF_RECORDS
739                | EXCEPT
740                | ACTION_EXPR
741                | FAIRNESS_EXPR
742                | IF_EXPR
743                | CASE_EXPR
744                | LET_EXPR
745                | CONJ_LIST
746                | DISJ_LIST
747                | BOUNDED_QUANT
748                | UNBOUNDED_QUANT
749                | TEMPORAL_QUANT
750                | CHOOSE
751                | LABEL
752        )
753    }
754
755    /// Wraps an expression node.
756    #[must_use]
757    pub fn cast(node: SyntaxNode) -> Option<Self> {
758        Some(match node.kind() {
759            GENERAL_ID => Self::Name(GeneralId(node)),
760            OP_APPLICATION => Self::Apply(OpApplication(node)),
761            INFIX_EXPR => Self::Infix(InfixExpr(node)),
762            PREFIX_EXPR => Self::Prefix(PrefixExpr(node)),
763            POSTFIX_EXPR => Self::Postfix(PostfixExpr(node)),
764            LET_EXPR => Self::Let(LetExpr(node)),
765            IF_EXPR => Self::If(IfExpr(node)),
766            CASE_EXPR => Self::Case(CaseExpr(node)),
767            BOUNDED_QUANT | UNBOUNDED_QUANT | TEMPORAL_QUANT => Self::Quant(QuantExpr(node)),
768            CHOOSE => Self::Choose(ChooseExpr(node)),
769            CONJ_LIST | DISJ_LIST => Self::Junction(JunctionList(node)),
770            FCN_APPL => Self::FcnAppl(FcnAppl(node)),
771            RECORD_FIELD => Self::Field(RecordField(node)),
772            LABEL => Self::Label(LabelExpr(node)),
773            k if Self::can_cast(k) => Self::Other(node),
774            _ => return None,
775        })
776    }
777
778    /// The underlying node.
779    #[must_use]
780    pub fn syntax(&self) -> &SyntaxNode {
781        match self {
782            Self::Name(n) => &n.0,
783            Self::Apply(n) => &n.0,
784            Self::Infix(n) => &n.0,
785            Self::Prefix(n) => &n.0,
786            Self::Postfix(n) => &n.0,
787            Self::Let(n) => &n.0,
788            Self::If(n) => &n.0,
789            Self::Case(n) => &n.0,
790            Self::Quant(n) => &n.0,
791            Self::Choose(n) => &n.0,
792            Self::Junction(n) => &n.0,
793            Self::FcnAppl(n) => &n.0,
794            Self::Field(n) => &n.0,
795            Self::Label(n) => &n.0,
796            Self::Other(n) => n,
797        }
798    }
799}
800
801fn exprs(n: &SyntaxNode) -> Vec<Expr> {
802    n.children().filter_map(Expr::cast).collect()
803}
804
805impl LetExpr {
806    /// The definitions (operator, function and module definitions, and
807    /// `RECURSIVE` declarations).
808    #[must_use]
809    pub fn definitions(&self) -> Vec<Unit> {
810        self.0
811            .children()
812            .find(|n| n.kind() == LET_DEFS)
813            .map_or_else(Vec::new, |d| d.children().filter_map(Unit::cast).collect())
814    }
815
816    /// The expression after `IN`.
817    #[must_use]
818    pub fn body(&self) -> Option<Expr> {
819        last_expr(&self.0)
820    }
821}
822
823impl IfExpr {
824    /// The condition.
825    #[must_use]
826    pub fn condition(&self) -> Option<Expr> {
827        exprs(&self.0).into_iter().next()
828    }
829
830    /// The `THEN` branch.
831    #[must_use]
832    pub fn then_branch(&self) -> Option<Expr> {
833        exprs(&self.0).into_iter().nth(1)
834    }
835
836    /// The `ELSE` branch.
837    #[must_use]
838    pub fn else_branch(&self) -> Option<Expr> {
839        exprs(&self.0).into_iter().nth(2)
840    }
841}
842
843impl CaseExpr {
844    /// The `guard -> value` arms, without `OTHER`.
845    #[must_use]
846    pub fn arms(&self) -> Vec<(Option<Expr>, Option<Expr>)> {
847        self.0
848            .children()
849            .filter(|n| n.kind() == CASE_ARM)
850            .map(|a| {
851                let mut e = exprs(&a).into_iter();
852                (e.next(), e.next())
853            })
854            .collect()
855    }
856
857    /// The `OTHER` value, if present.
858    #[must_use]
859    pub fn other(&self) -> Option<Expr> {
860        self.0
861            .children()
862            .find(|n| n.kind() == OTHER_ARM)
863            .and_then(|o| first_expr(&o))
864    }
865}
866
867impl QuantExpr {
868    /// The quantifier token: `\A`, `\E`, `\AA`, `\EE` or a Unicode spelling.
869    #[must_use]
870    pub fn quantifier(&self) -> Option<SyntaxToken> {
871        tokens(&self.0).next()
872    }
873
874    /// Whether this is `\A`/`\AA` (otherwise `\E`/`\EE`).
875    #[must_use]
876    pub fn is_forall(&self) -> bool {
877        self.quantifier()
878            .is_some_and(|t| matches!(t.kind(), FORALL_KW | TEMPORAL_FORALL_KW))
879    }
880
881    /// Whether this is a temporal quantifier `\AA`/`\EE`.
882    #[must_use]
883    pub fn is_temporal(&self) -> bool {
884        self.0.kind() == TEMPORAL_QUANT
885    }
886
887    /// The bounds, for `\A x \in S : P`.
888    pub fn bounds(&self) -> impl Iterator<Item = QuantBound> + use<> {
889        children(&self.0)
890    }
891
892    /// The unbounded names, for `\A x, y : P`.
893    #[must_use]
894    pub fn unbounded_names(&self) -> Vec<String> {
895        ident_texts(&self.0)
896    }
897
898    /// The quantified expression.
899    #[must_use]
900    pub fn body(&self) -> Option<Expr> {
901        last_expr(&self.0)
902    }
903}
904
905impl ChooseExpr {
906    /// The bound name, or the names of a `<<x, y>>` pattern.
907    #[must_use]
908    pub fn names(&self) -> Vec<String> {
909        let mut v = ident_texts(&self.0);
910        if let Some(t) = self.0.children().find(|n| n.kind() == IDENT_TUPLE) {
911            v.extend(ident_texts(&t));
912        }
913        v
914    }
915
916    /// The bounding set, for `CHOOSE x \in S : P`.
917    #[must_use]
918    pub fn set(&self) -> Option<Expr> {
919        has_token(&self.0, IN_OP)
920            .then(|| exprs(&self.0).into_iter().next())
921            .flatten()
922    }
923
924    /// The condition.
925    #[must_use]
926    pub fn body(&self) -> Option<Expr> {
927        last_expr(&self.0)
928    }
929}
930
931impl JunctionList {
932    /// Whether this is a `/\` list (otherwise `\/`).
933    #[must_use]
934    pub fn is_conjunction(&self) -> bool {
935        self.0.kind() == CONJ_LIST
936    }
937
938    /// The items' expressions, in order.
939    #[must_use]
940    pub fn items(&self) -> Vec<Expr> {
941        self.0
942            .children()
943            .filter_map(|item| first_expr(&item))
944            .collect()
945    }
946}
947
948impl FcnAppl {
949    /// The function. `None` for SANY's bare `[a, b]` form, which semantic
950    /// analysis rejects.
951    #[must_use]
952    pub fn function(&self) -> Option<Expr> {
953        let first = self
954            .0
955            .children_with_tokens()
956            .find(|e| !e.kind().is_trivia())?;
957        first.into_node().and_then(Expr::cast)
958    }
959
960    /// The arguments inside the brackets.
961    #[must_use]
962    pub fn arguments(&self) -> Vec<Expr> {
963        let mut seen_bracket = false;
964        let mut out = Vec::new();
965        for e in self.0.children_with_tokens() {
966            match e {
967                rowan::NodeOrToken::Token(t) if t.kind() == L_BRACK => seen_bracket = true,
968                rowan::NodeOrToken::Node(n) if seen_bracket => out.extend(Expr::cast(n)),
969                _ => {}
970            }
971        }
972        out
973    }
974}
975
976impl RecordField {
977    /// The record expression.
978    #[must_use]
979    pub fn record(&self) -> Option<Expr> {
980        first_expr(&self.0)
981    }
982
983    /// The field name.
984    #[must_use]
985    pub fn field(&self) -> Option<String> {
986        token(&self.0, IDENT).map(|t| t.text().to_owned())
987    }
988}
989
990impl LabelExpr {
991    /// The label's name.
992    #[must_use]
993    pub fn name(&self) -> Option<String> {
994        let first = self.0.children().next()?;
995        let id = if first.kind() == OP_APPLICATION {
996            first.children().find(|n| n.kind() == GENERAL_ID)?
997        } else {
998            first
999        };
1000        GeneralId::cast(id).and_then(|g| g.name())
1001    }
1002
1003    /// The labelled expression (or `ASSUME_PROVE`).
1004    #[must_use]
1005    pub fn body(&self) -> Option<SyntaxNode> {
1006        self.0.children().nth(1)
1007    }
1008}
1009
1010impl Lambda {
1011    /// The parameter names.
1012    #[must_use]
1013    pub fn parameters(&self) -> Vec<String> {
1014        ident_texts(&self.0)
1015    }
1016
1017    /// The body.
1018    #[must_use]
1019    pub fn body(&self) -> Option<Expr> {
1020        last_expr(&self.0)
1021    }
1022}
1023
1024impl GeneralId {
1025    /// The final name part as text (an identifier, operator, or selector).
1026    #[must_use]
1027    pub fn name(&self) -> Option<String> {
1028        self.0
1029            .children_with_tokens()
1030            .filter(|e| e.kind() != ID_PREFIX && !e.kind().is_trivia())
1031            .last()
1032            .map(|e| e.to_string())
1033    }
1034}
1035
1036impl OpApplication {
1037    /// The applied operator's name.
1038    #[must_use]
1039    pub fn operator(&self) -> Option<GeneralId> {
1040        child(&self.0)
1041    }
1042
1043    /// The argument nodes (expressions, `OP_REF` or `LAMBDA`).
1044    #[must_use]
1045    pub fn arguments(&self) -> Vec<SyntaxNode> {
1046        self.0
1047            .children()
1048            .find(|n| n.kind() == OP_ARGS)
1049            .map_or_else(Vec::new, |a| a.children().collect())
1050    }
1051}
1052
1053fn operator_token(n: &SyntaxNode) -> Option<SyntaxToken> {
1054    tokens(n).find(|t| t.kind().is_operator())
1055}
1056
1057impl InfixExpr {
1058    /// The left operand.
1059    #[must_use]
1060    pub fn lhs(&self) -> Option<Expr> {
1061        first_expr(&self.0)
1062    }
1063
1064    /// The operator token.
1065    #[must_use]
1066    pub fn operator(&self) -> Option<SyntaxToken> {
1067        operator_token(&self.0)
1068    }
1069
1070    /// The right operand.
1071    #[must_use]
1072    pub fn rhs(&self) -> Option<Expr> {
1073        self.0.children().filter_map(Expr::cast).nth(1)
1074    }
1075}
1076
1077impl PrefixExpr {
1078    /// The operator token.
1079    #[must_use]
1080    pub fn operator(&self) -> Option<SyntaxToken> {
1081        operator_token(&self.0)
1082    }
1083
1084    /// The operand.
1085    #[must_use]
1086    pub fn operand(&self) -> Option<Expr> {
1087        first_expr(&self.0)
1088    }
1089}
1090
1091impl PostfixExpr {
1092    /// The operand.
1093    #[must_use]
1094    pub fn operand(&self) -> Option<Expr> {
1095        first_expr(&self.0)
1096    }
1097
1098    /// The operator token.
1099    #[must_use]
1100    pub fn operator(&self) -> Option<SyntaxToken> {
1101        operator_token(&self.0)
1102    }
1103}
1104
1105impl AssumeProve {
1106    /// The `ASSUME` items (expressions, `NEW_DECL`s or nested `ASSUME_PROVE`s).
1107    pub fn assumptions(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
1108        let prove_seen = std::cell::Cell::new(false);
1109        let node = self.0.clone();
1110        let mut out = Vec::new();
1111        for e in node.children_with_tokens() {
1112            match e {
1113                rowan::NodeOrToken::Token(t) if matches!(t.kind(), PROVE_KW | BOX_PROVE_KW) => {
1114                    prove_seen.set(true);
1115                }
1116                rowan::NodeOrToken::Node(n) if !prove_seen.get() => out.push(n),
1117                _ => {}
1118            }
1119        }
1120        out.into_iter()
1121    }
1122
1123    /// The `PROVE` expression.
1124    #[must_use]
1125    pub fn goal(&self) -> Option<Expr> {
1126        last_expr(&self.0)
1127    }
1128}