#[allow(
clippy::enum_glob_use,
reason = "the grammar names over a hundred token and node kinds"
)]
use crate::kind::SyntaxKind::{self, *};
use crate::kind::{SyntaxNode, SyntaxToken};
pub trait AstNode: Sized {
fn can_cast(kind: SyntaxKind) -> bool;
fn cast(node: SyntaxNode) -> Option<Self>;
fn syntax(&self) -> &SyntaxNode;
}
macro_rules! ast_node {
($(#[$m:meta])* $name:ident, $kind:ident) => {
$(#[$m])*
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct $name(SyntaxNode);
impl AstNode for $name {
fn can_cast(kind: SyntaxKind) -> bool {
kind == $kind
}
fn cast(node: SyntaxNode) -> Option<Self> {
Self::can_cast(node.kind()).then(|| Self(node))
}
fn syntax(&self) -> &SyntaxNode {
&self.0
}
}
};
}
fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
parent.children().find_map(N::cast)
}
fn children<N: AstNode>(parent: &SyntaxNode) -> impl Iterator<Item = N> + use<N> {
parent.children().filter_map(N::cast)
}
fn tokens(parent: &SyntaxNode) -> impl Iterator<Item = SyntaxToken> + use<> {
parent
.children_with_tokens()
.filter_map(rowan::NodeOrToken::into_token)
.filter(|t| !t.kind().is_trivia())
}
fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
tokens(parent).find(|t| t.kind() == kind)
}
fn has_token(parent: &SyntaxNode, kind: SyntaxKind) -> bool {
token(parent, kind).is_some()
}
fn ident_texts(parent: &SyntaxNode) -> Vec<String> {
tokens(parent)
.filter(|t| t.kind() == IDENT)
.map(|t| t.text().to_owned())
.collect()
}
fn first_expr(parent: &SyntaxNode) -> Option<Expr> {
parent.children().find_map(Expr::cast)
}
fn last_expr(parent: &SyntaxNode) -> Option<Expr> {
parent.children().filter_map(Expr::cast).last()
}
ast_node!(
SourceFile,
SOURCE_FILE
);
ast_node!(
Module,
MODULE
);
ast_node!(
VariableDecl,
VARIABLE_DECL
);
ast_node!(
ConstantDecl,
CONSTANT_DECL
);
ast_node!(
RecursiveDecl,
RECURSIVE_DECL
);
ast_node!(
OperatorDef,
OPERATOR_DEF
);
ast_node!(
FunctionDef,
FUNCTION_DEF
);
ast_node!(
ModuleDef,
MODULE_DEF
);
ast_node!(
Instance,
INSTANCE
);
ast_node!(
Instantiation,
INSTANTIATION
);
ast_node!(
Substitution,
SUBSTITUTION
);
ast_node!(
Assumption,
ASSUMPTION
);
ast_node!(
Theorem,
THEOREM
);
ast_node!(
UseOrHide,
USE_OR_HIDE
);
ast_node!(
Proof,
PROOF
);
ast_node!(
TerminalProof,
TERMINAL_PROOF
);
ast_node!(
ProofStep,
PROOF_STEP
);
ast_node!(
AssumeProve,
ASSUME_PROVE
);
ast_node!(
IdentDecl,
IDENT_DECL
);
ast_node!(
QuantBound,
QUANT_BOUND
);
ast_node!(
GeneralId,
GENERAL_ID
);
ast_node!(
OpApplication,
OP_APPLICATION
);
ast_node!(
InfixExpr,
INFIX_EXPR
);
ast_node!(
PrefixExpr,
PREFIX_EXPR
);
ast_node!(
PostfixExpr,
POSTFIX_EXPR
);
impl SourceFile {
#[must_use]
pub fn module(&self) -> Option<Module> {
child(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Unit {
VariableDecl(VariableDecl),
ConstantDecl(ConstantDecl),
RecursiveDecl(RecursiveDecl),
OperatorDef(OperatorDef),
FunctionDef(FunctionDef),
ModuleDef(ModuleDef),
Instance(Instance),
Assumption(Assumption),
Theorem(Theorem),
UseOrHide(UseOrHide),
Module(Module),
Error(SyntaxNode),
}
impl Unit {
fn cast(node: SyntaxNode) -> Option<Self> {
Some(match node.kind() {
VARIABLE_DECL => Self::VariableDecl(VariableDecl(node)),
CONSTANT_DECL => Self::ConstantDecl(ConstantDecl(node)),
RECURSIVE_DECL => Self::RecursiveDecl(RecursiveDecl(node)),
OPERATOR_DEF => Self::OperatorDef(OperatorDef(node)),
FUNCTION_DEF => Self::FunctionDef(FunctionDef(node)),
MODULE_DEF => Self::ModuleDef(ModuleDef(node)),
INSTANCE => Self::Instance(Instance(node)),
ASSUMPTION => Self::Assumption(Assumption(node)),
THEOREM => Self::Theorem(Theorem(node)),
USE_OR_HIDE => Self::UseOrHide(UseOrHide(node)),
MODULE => Self::Module(Module(node)),
ERROR => Self::Error(node),
_ => return None,
})
}
}
impl Module {
#[must_use]
pub fn name(&self) -> Option<String> {
let header = self.0.children().find(|n| n.kind() == MODULE_HEADER)?;
token(&header, IDENT).map(|t| t.text().to_owned())
}
#[must_use]
pub fn extends(&self) -> Vec<String> {
self.0
.children()
.find(|n| n.kind() == EXTENDS)
.map_or_else(Vec::new, |e| ident_texts(&e))
}
pub fn units(&self) -> impl Iterator<Item = Unit> + use<> {
self.0.children().filter_map(Unit::cast)
}
pub fn operator_definitions(&self) -> impl Iterator<Item = OperatorDef> + use<> {
children(&self.0)
}
#[must_use]
pub fn is_closed(&self) -> bool {
has_token(&self.0, END_MODULE)
}
}
impl VariableDecl {
#[must_use]
pub fn names(&self) -> Vec<String> {
ident_texts(&self.0)
}
}
impl ConstantDecl {
pub fn items(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
self.0.children()
}
}
impl RecursiveDecl {
pub fn items(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
self.0.children()
}
}
impl IdentDecl {
#[must_use]
pub fn name(&self) -> Option<String> {
token(&self.0, IDENT).map(|t| t.text().to_owned())
}
#[must_use]
pub fn arity(&self) -> usize {
tokens(&self.0).filter(|t| t.kind() == UNDERSCORE).count()
}
}
fn lhs_name(lhs: &SyntaxNode) -> Option<String> {
match lhs.kind() {
IDENT_LHS => token(lhs, IDENT).map(|t| t.text().to_owned()),
PREFIX_LHS => tokens(lhs).next().map(|t| t.text().to_owned()),
INFIX_LHS | POSTFIX_LHS => tokens(lhs).nth(1).map(|t| t.text().to_owned()),
_ => None,
}
}
fn find_lhs(node: &SyntaxNode) -> Option<SyntaxNode> {
node.children()
.find(|n| matches!(n.kind(), IDENT_LHS | PREFIX_LHS | INFIX_LHS | POSTFIX_LHS))
}
impl OperatorDef {
#[must_use]
pub fn name(&self) -> Option<String> {
find_lhs(&self.0).and_then(|l| lhs_name(&l))
}
#[must_use]
pub fn lhs(&self) -> Option<SyntaxNode> {
find_lhs(&self.0)
}
#[must_use]
pub fn parameters(&self) -> Vec<String> {
let Some(lhs) = find_lhs(&self.0) else {
return Vec::new();
};
match lhs.kind() {
IDENT_LHS => lhs
.children()
.filter_map(|p| match p.kind() {
IDENT_DECL => token(&p, IDENT).map(|t| t.text().to_owned()),
PREFIX_DECL => tokens(&p).next().map(|t| t.text().to_owned()),
INFIX_DECL | POSTFIX_DECL => tokens(&p).nth(1).map(|t| t.text().to_owned()),
_ => None,
})
.collect(),
PREFIX_LHS => tokens(&lhs)
.nth(1)
.map(|t| t.text().to_owned())
.into_iter()
.collect(),
INFIX_LHS => {
let t: Vec<SyntaxToken> = tokens(&lhs).collect();
[t.first(), t.get(2)]
.into_iter()
.flatten()
.map(|t| t.text().to_owned())
.collect()
}
_ => tokens(&lhs)
.next()
.map(|t| t.text().to_owned())
.into_iter()
.collect(),
}
}
#[must_use]
pub fn is_local(&self) -> bool {
has_token(&self.0, LOCAL_KW)
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl FunctionDef {
#[must_use]
pub fn name(&self) -> Option<String> {
token(&self.0, IDENT).map(|t| t.text().to_owned())
}
pub fn bounds(&self) -> impl Iterator<Item = QuantBound> + use<> {
children(&self.0)
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
#[must_use]
pub fn is_local(&self) -> bool {
has_token(&self.0, LOCAL_KW)
}
}
impl ModuleDef {
#[must_use]
pub fn name(&self) -> Option<String> {
find_lhs(&self.0).and_then(|l| lhs_name(&l))
}
#[must_use]
pub fn instantiation(&self) -> Option<Instantiation> {
child(&self.0)
}
}
impl Instance {
#[must_use]
pub fn is_local(&self) -> bool {
has_token(&self.0, LOCAL_KW)
}
#[must_use]
pub fn instantiation(&self) -> Option<Instantiation> {
child(&self.0)
}
}
impl Instantiation {
#[must_use]
pub fn module_name(&self) -> Option<String> {
token(&self.0, IDENT).map(|t| t.text().to_owned())
}
pub fn substitutions(&self) -> impl Iterator<Item = Substitution> + use<> {
children(&self.0)
}
}
impl Substitution {
#[must_use]
pub fn target(&self) -> Option<SyntaxToken> {
tokens(&self.0).next()
}
#[must_use]
pub fn replacement(&self) -> Option<SyntaxNode> {
self.0.children().last()
}
}
impl Assumption {
#[must_use]
pub fn name(&self) -> Option<String> {
has_token(&self.0, DEF_EQ)
.then(|| token(&self.0, IDENT).map(|t| t.text().to_owned()))
.flatten()
}
#[must_use]
pub fn expr(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl Theorem {
#[must_use]
pub fn name(&self) -> Option<String> {
has_token(&self.0, DEF_EQ)
.then(|| token(&self.0, IDENT).map(|t| t.text().to_owned()))
.flatten()
}
#[must_use]
pub fn statement(&self) -> Option<SyntaxNode> {
self.0
.children()
.find(|n| n.kind() != PROOF && n.kind() != TERMINAL_PROOF)
}
#[must_use]
pub fn proof(&self) -> Option<SyntaxNode> {
self.0
.children()
.find(|n| matches!(n.kind(), PROOF | TERMINAL_PROOF))
}
}
impl Proof {
pub fn steps(&self) -> impl Iterator<Item = ProofStep> + use<> {
children(&self.0)
}
}
impl ProofStep {
#[must_use]
pub fn step_token(&self) -> Option<SyntaxToken> {
tokens(&self.0).next()
}
#[must_use]
pub fn body(&self) -> Option<SyntaxNode> {
self.0
.children()
.find(|n| !matches!(n.kind(), PROOF | TERMINAL_PROOF))
}
#[must_use]
pub fn proof(&self) -> Option<SyntaxNode> {
self.0
.children()
.find(|n| matches!(n.kind(), PROOF | TERMINAL_PROOF))
}
}
impl QuantBound {
#[must_use]
pub fn names(&self) -> Vec<String> {
let mut v = ident_texts(&self.0);
if let Some(t) = self.0.children().find(|n| n.kind() == IDENT_TUPLE) {
v.extend(ident_texts(&t));
}
v
}
#[must_use]
pub fn is_tuple(&self) -> bool {
self.0.children().any(|n| n.kind() == IDENT_TUPLE)
}
#[must_use]
pub fn set(&self) -> Option<Expr> {
first_expr(&self.0)
}
}
macro_rules! ast_node_multi {
($(#[$m:meta])* $name:ident, [$($kind:ident),+]) => {
$(#[$m])*
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct $name(SyntaxNode);
impl AstNode for $name {
fn can_cast(kind: SyntaxKind) -> bool {
matches!(kind, $($kind)|+)
}
fn cast(node: SyntaxNode) -> Option<Self> {
Self::can_cast(node.kind()).then(|| Self(node))
}
fn syntax(&self) -> &SyntaxNode {
&self.0
}
}
};
}
ast_node!(
LetExpr,
LET_EXPR
);
ast_node!(
IfExpr,
IF_EXPR
);
ast_node!(
CaseExpr,
CASE_EXPR
);
ast_node!(
ChooseExpr,
CHOOSE
);
ast_node!(
FcnAppl,
FCN_APPL
);
ast_node!(
RecordField,
RECORD_FIELD
);
ast_node!(
LabelExpr,
LABEL
);
ast_node!(
Lambda,
LAMBDA
);
ast_node_multi!(
QuantExpr,
[BOUNDED_QUANT, UNBOUNDED_QUANT, TEMPORAL_QUANT]
);
ast_node_multi!(
JunctionList,
[CONJ_LIST, DISJ_LIST]
);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Expr {
Name(GeneralId),
Apply(OpApplication),
Infix(InfixExpr),
Prefix(PrefixExpr),
Postfix(PostfixExpr),
Let(LetExpr),
If(IfExpr),
Case(CaseExpr),
Quant(QuantExpr),
Choose(ChooseExpr),
Junction(JunctionList),
FcnAppl(FcnAppl),
Field(RecordField),
Label(LabelExpr),
Other(SyntaxNode),
}
impl Expr {
#[must_use]
pub fn can_cast(kind: SyntaxKind) -> bool {
matches!(
kind,
GENERAL_ID
| OP_APPLICATION
| NUMBER_LIT
| DECIMAL_LIT
| STRING_LIT
| PREFIX_EXPR
| INFIX_EXPR
| POSTFIX_EXPR
| CARTESIAN_PRODUCT
| PAREN_EXPR
| RECORD_FIELD
| FCN_APPL
| TUPLE
| SET_ENUM
| SET_FILTER
| SET_MAP
| FCN_CONSTRUCTOR
| SET_OF_FCNS
| RECORD
| SET_OF_RECORDS
| EXCEPT
| ACTION_EXPR
| FAIRNESS_EXPR
| IF_EXPR
| CASE_EXPR
| LET_EXPR
| CONJ_LIST
| DISJ_LIST
| BOUNDED_QUANT
| UNBOUNDED_QUANT
| TEMPORAL_QUANT
| CHOOSE
| LABEL
)
}
#[must_use]
pub fn cast(node: SyntaxNode) -> Option<Self> {
Some(match node.kind() {
GENERAL_ID => Self::Name(GeneralId(node)),
OP_APPLICATION => Self::Apply(OpApplication(node)),
INFIX_EXPR => Self::Infix(InfixExpr(node)),
PREFIX_EXPR => Self::Prefix(PrefixExpr(node)),
POSTFIX_EXPR => Self::Postfix(PostfixExpr(node)),
LET_EXPR => Self::Let(LetExpr(node)),
IF_EXPR => Self::If(IfExpr(node)),
CASE_EXPR => Self::Case(CaseExpr(node)),
BOUNDED_QUANT | UNBOUNDED_QUANT | TEMPORAL_QUANT => Self::Quant(QuantExpr(node)),
CHOOSE => Self::Choose(ChooseExpr(node)),
CONJ_LIST | DISJ_LIST => Self::Junction(JunctionList(node)),
FCN_APPL => Self::FcnAppl(FcnAppl(node)),
RECORD_FIELD => Self::Field(RecordField(node)),
LABEL => Self::Label(LabelExpr(node)),
k if Self::can_cast(k) => Self::Other(node),
_ => return None,
})
}
#[must_use]
pub fn syntax(&self) -> &SyntaxNode {
match self {
Self::Name(n) => &n.0,
Self::Apply(n) => &n.0,
Self::Infix(n) => &n.0,
Self::Prefix(n) => &n.0,
Self::Postfix(n) => &n.0,
Self::Let(n) => &n.0,
Self::If(n) => &n.0,
Self::Case(n) => &n.0,
Self::Quant(n) => &n.0,
Self::Choose(n) => &n.0,
Self::Junction(n) => &n.0,
Self::FcnAppl(n) => &n.0,
Self::Field(n) => &n.0,
Self::Label(n) => &n.0,
Self::Other(n) => n,
}
}
}
fn exprs(n: &SyntaxNode) -> Vec<Expr> {
n.children().filter_map(Expr::cast).collect()
}
impl LetExpr {
#[must_use]
pub fn definitions(&self) -> Vec<Unit> {
self.0
.children()
.find(|n| n.kind() == LET_DEFS)
.map_or_else(Vec::new, |d| d.children().filter_map(Unit::cast).collect())
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl IfExpr {
#[must_use]
pub fn condition(&self) -> Option<Expr> {
exprs(&self.0).into_iter().next()
}
#[must_use]
pub fn then_branch(&self) -> Option<Expr> {
exprs(&self.0).into_iter().nth(1)
}
#[must_use]
pub fn else_branch(&self) -> Option<Expr> {
exprs(&self.0).into_iter().nth(2)
}
}
impl CaseExpr {
#[must_use]
pub fn arms(&self) -> Vec<(Option<Expr>, Option<Expr>)> {
self.0
.children()
.filter(|n| n.kind() == CASE_ARM)
.map(|a| {
let mut e = exprs(&a).into_iter();
(e.next(), e.next())
})
.collect()
}
#[must_use]
pub fn other(&self) -> Option<Expr> {
self.0
.children()
.find(|n| n.kind() == OTHER_ARM)
.and_then(|o| first_expr(&o))
}
}
impl QuantExpr {
#[must_use]
pub fn quantifier(&self) -> Option<SyntaxToken> {
tokens(&self.0).next()
}
#[must_use]
pub fn is_forall(&self) -> bool {
self.quantifier()
.is_some_and(|t| matches!(t.kind(), FORALL_KW | TEMPORAL_FORALL_KW))
}
#[must_use]
pub fn is_temporal(&self) -> bool {
self.0.kind() == TEMPORAL_QUANT
}
pub fn bounds(&self) -> impl Iterator<Item = QuantBound> + use<> {
children(&self.0)
}
#[must_use]
pub fn unbounded_names(&self) -> Vec<String> {
ident_texts(&self.0)
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl ChooseExpr {
#[must_use]
pub fn names(&self) -> Vec<String> {
let mut v = ident_texts(&self.0);
if let Some(t) = self.0.children().find(|n| n.kind() == IDENT_TUPLE) {
v.extend(ident_texts(&t));
}
v
}
#[must_use]
pub fn set(&self) -> Option<Expr> {
has_token(&self.0, IN_OP)
.then(|| exprs(&self.0).into_iter().next())
.flatten()
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl JunctionList {
#[must_use]
pub fn is_conjunction(&self) -> bool {
self.0.kind() == CONJ_LIST
}
#[must_use]
pub fn items(&self) -> Vec<Expr> {
self.0
.children()
.filter_map(|item| first_expr(&item))
.collect()
}
}
impl FcnAppl {
#[must_use]
pub fn function(&self) -> Option<Expr> {
let first = self
.0
.children_with_tokens()
.find(|e| !e.kind().is_trivia())?;
first.into_node().and_then(Expr::cast)
}
#[must_use]
pub fn arguments(&self) -> Vec<Expr> {
let mut seen_bracket = false;
let mut out = Vec::new();
for e in self.0.children_with_tokens() {
match e {
rowan::NodeOrToken::Token(t) if t.kind() == L_BRACK => seen_bracket = true,
rowan::NodeOrToken::Node(n) if seen_bracket => out.extend(Expr::cast(n)),
_ => {}
}
}
out
}
}
impl RecordField {
#[must_use]
pub fn record(&self) -> Option<Expr> {
first_expr(&self.0)
}
#[must_use]
pub fn field(&self) -> Option<String> {
token(&self.0, IDENT).map(|t| t.text().to_owned())
}
}
impl LabelExpr {
#[must_use]
pub fn name(&self) -> Option<String> {
let first = self.0.children().next()?;
let id = if first.kind() == OP_APPLICATION {
first.children().find(|n| n.kind() == GENERAL_ID)?
} else {
first
};
GeneralId::cast(id).and_then(|g| g.name())
}
#[must_use]
pub fn body(&self) -> Option<SyntaxNode> {
self.0.children().nth(1)
}
}
impl Lambda {
#[must_use]
pub fn parameters(&self) -> Vec<String> {
ident_texts(&self.0)
}
#[must_use]
pub fn body(&self) -> Option<Expr> {
last_expr(&self.0)
}
}
impl GeneralId {
#[must_use]
pub fn name(&self) -> Option<String> {
self.0
.children_with_tokens()
.filter(|e| e.kind() != ID_PREFIX && !e.kind().is_trivia())
.last()
.map(|e| e.to_string())
}
}
impl OpApplication {
#[must_use]
pub fn operator(&self) -> Option<GeneralId> {
child(&self.0)
}
#[must_use]
pub fn arguments(&self) -> Vec<SyntaxNode> {
self.0
.children()
.find(|n| n.kind() == OP_ARGS)
.map_or_else(Vec::new, |a| a.children().collect())
}
}
fn operator_token(n: &SyntaxNode) -> Option<SyntaxToken> {
tokens(n).find(|t| t.kind().is_operator())
}
impl InfixExpr {
#[must_use]
pub fn lhs(&self) -> Option<Expr> {
first_expr(&self.0)
}
#[must_use]
pub fn operator(&self) -> Option<SyntaxToken> {
operator_token(&self.0)
}
#[must_use]
pub fn rhs(&self) -> Option<Expr> {
self.0.children().filter_map(Expr::cast).nth(1)
}
}
impl PrefixExpr {
#[must_use]
pub fn operator(&self) -> Option<SyntaxToken> {
operator_token(&self.0)
}
#[must_use]
pub fn operand(&self) -> Option<Expr> {
first_expr(&self.0)
}
}
impl PostfixExpr {
#[must_use]
pub fn operand(&self) -> Option<Expr> {
first_expr(&self.0)
}
#[must_use]
pub fn operator(&self) -> Option<SyntaxToken> {
operator_token(&self.0)
}
}
impl AssumeProve {
pub fn assumptions(&self) -> impl Iterator<Item = SyntaxNode> + use<> {
let prove_seen = std::cell::Cell::new(false);
let node = self.0.clone();
let mut out = Vec::new();
for e in node.children_with_tokens() {
match e {
rowan::NodeOrToken::Token(t) if matches!(t.kind(), PROVE_KW | BOX_PROVE_KW) => {
prove_seen.set(true);
}
rowan::NodeOrToken::Node(n) if !prove_seen.get() => out.push(n),
_ => {}
}
}
out.into_iter()
}
#[must_use]
pub fn goal(&self) -> Option<Expr> {
last_expr(&self.0)
}
}