Skip to main content

glrmask\public_api/
expr.rs

1//! Expression operators have no source, lexical scope or path segment of their own.
2use super::*;
3use super::module::{CompiledPart, Binding};
4
5/// A grammar expression.
6#[derive(Debug, Clone)]
7pub struct Expr(pub(crate) Arc<ExprNode>);
8
9#[derive(Debug, Clone)]
10pub(crate) enum ExprLeaf {
11    Grammar(Grammar),
12    Module(Module),
13    Constraint(CompiledPart),
14    TokenSet(TokenSet),
15}
16
17#[derive(Debug, Clone)]
18pub(crate) enum ExprNode {
19    Leaf(ExprLeaf),
20    Literal(Vec<u8>),
21    Choice(Vec<Expr>),
22    Sequence(Vec<Expr>),
23}
24
25impl From<&Expr> for Expr {
26    fn from(e: &Expr) -> Self { e.clone() }
27}
28impl From<Module> for Expr {
29    fn from(m: Module) -> Self {
30        Expr(Arc::new(ExprNode::Leaf(ExprLeaf::Module(m))))
31    }
32}
33impl From<&Module> for Expr {
34    fn from(m: &Module) -> Self {
35        Expr(Arc::new(ExprNode::Leaf(ExprLeaf::Module(m.clone()))))
36    }
37}
38impl From<Constraint> for Expr {
39    fn from(c: Constraint) -> Self { Self(Arc::new(ExprNode::Leaf(ExprLeaf::Constraint(c.into())))) }
40}
41impl From<&Constraint> for Expr {
42    fn from(c: &Constraint) -> Self { Self::from(c.clone()) }
43}
44impl From<Grammar> for Expr {
45    fn from(g: Grammar) -> Self {
46        Expr(Arc::new(ExprNode::Leaf(ExprLeaf::Grammar(g))))
47    }
48}
49impl From<&Grammar> for Expr {
50    fn from(g: &Grammar) -> Self {
51        Expr::from(g.clone())
52    }
53}
54impl From<TokenSet> for Expr {
55    fn from(t: TokenSet) -> Self {
56        Expr(Arc::new(ExprNode::Leaf(ExprLeaf::TokenSet(t))))
57    }
58}
59impl From<&TokenSet> for Expr {
60    fn from(t: &TokenSet) -> Self {
61        Expr(Arc::new(ExprNode::Leaf(ExprLeaf::TokenSet(t.clone()))))
62    }
63}
64
65impl Expr {
66    /// Matches `bytes` exactly.
67    pub fn literal(bytes: impl AsRef<[u8]>) -> Self {
68        Self(Arc::new(ExprNode::Literal(bytes.as_ref().to_vec())))
69    }
70
71    /// Matches `parts` in order.
72    pub fn sequence(parts: impl IntoIterator<Item = Expr>) -> Self {
73        Self(Arc::new(ExprNode::Sequence(parts.into_iter().collect())))
74    }
75
76    /// Matches any one of `parts`.
77    pub fn choice(parts: impl IntoIterator<Item = Expr>) -> Self {
78        let list: Vec<Expr> = parts.into_iter().collect();
79        if list.len() == 1 {
80            list.into_iter().next().unwrap()
81        } else {
82            Self(Arc::new(ExprNode::Choice(list)))
83        }
84    }
85
86    pub(super) fn skeleton(&self, allow_modules: bool) -> Result<(Grammar, Vec<(String, Binding)>)> {
87        fn walk(
88            expr: &Expr,
89            leaves: &mut Vec<(String, Binding)>,
90            externs: &mut Vec<(String, ExternKind)>,
91            depth: usize,
92            count: &mut usize,
93            allow_modules: bool,
94        ) -> Result<crate::grammar::ast::GrammarExpr> {
95            *count += 1;
96            if depth > graph::MAX_DEPTH || *count > graph::MAX_NODES {
97                return Err(Error::ResourceLimit("the expression is too large or too deeply nested".into()));
98            }
99            Ok(match expr.0.as_ref() {
100                ExprNode::Leaf(leaf) => {
101                    let name = format!("leaf{}", leaves.len());
102                    let (kind, binding) = match leaf {
103                        ExprLeaf::Grammar(g) => (ExternKind::Grammar, Binding::Grammar(g.clone())),
104                        ExprLeaf::Module(m) => {
105                            if !allow_modules {
106                                return Err(Error::InvalidInput("a Grammar expression cannot contain a Module".into()));
107                            }
108                            (ExternKind::Grammar, Binding::Module(m.clone()))
109                        },
110                        ExprLeaf::Constraint(c) => {
111                            if !allow_modules { return Err(Error::InvalidInput("a Grammar expression cannot contain a Constraint".into())); }
112                            (ExternKind::Grammar, Binding::Constraint(c.clone()))
113                        },
114                        ExprLeaf::TokenSet(t) => {
115                            if !allow_modules {
116                                return Err(Error::InvalidInput("a Grammar expression cannot contain a TokenSet".into()));
117                            }
118                            (ExternKind::Token, Binding::TokenSet(t.clone()))
119                        },
120                    };
121                    externs.push((name.clone(), kind));
122                    leaves.push((name.clone(), binding));
123                    crate::grammar::ast::GrammarExpr::Ref(name)
124                }
125                ExprNode::Literal(bytes) => {
126                    crate::grammar::ast::GrammarExpr::Literal(bytes.clone())
127                }
128                ExprNode::Choice(parts) => {
129                    if parts.is_empty() {
130                        crate::grammar::ast::GrammarExpr::Choice(Vec::new())
131                    } else if parts.len() == 1 {
132                        walk(&parts[0], leaves, externs, depth + 1, count, allow_modules)?
133                    } else {
134                        let walked = parts.iter().map(|p| walk(p, leaves, externs, depth + 1, count, allow_modules)).collect::<Result<Vec<_>>>()?;
135                        crate::grammar::ast::GrammarExpr::Choice(walked)
136                    }
137                }
138                ExprNode::Sequence(parts) => {
139                    if parts.is_empty() {
140                        crate::grammar::ast::GrammarExpr::Epsilon
141                    } else if parts.len() == 1 {
142                        walk(&parts[0], leaves, externs, depth + 1, count, allow_modules)?
143                    } else {
144                        let walked = parts.iter().map(|p| walk(p, leaves, externs, depth + 1, count, allow_modules)).collect::<Result<Vec<_>>>()?;
145                        crate::grammar::ast::GrammarExpr::Sequence(walked)
146                    }
147                }
148            })
149        }
150        let mut leaves = Vec::new();
151        let mut externs = Vec::new();
152        let body = walk(self, &mut leaves, &mut externs, 0, &mut 0, allow_modules)?;
153        let named = crate::grammar::ast::NamedGrammar {
154            start: "expr_root".into(),
155            rules: vec![crate::grammar::ast::NamedRule {
156                name: "expr_root".into(),
157                expr: body,
158                is_terminal: false,
159                is_internal: false,
160            }],
161            ignore: None,
162            lexer_partitions: BTreeMap::new(),
163            lexer_literal_partitions: BTreeMap::new(),
164            default_lexer_partition: None,
165        };
166        let grammar = Grammar::new(GrammarSource::Constructed);
167        let _ = grammar.parsed_component.set(ParsedComponent::from_named(named, &externs).map_err(crate::error::from_grammar));
168        grammar.component()?;
169        Ok((grammar, leaves))
170    }
171}
172
173pub(crate) fn check_expr_unbound(expr: &Expr) -> Vec<String> {
174    let mut unbound = Vec::new();
175    fn walk(e: &Expr, out: &mut Vec<String>) {
176        match e.0.as_ref() {
177            ExprNode::Leaf(ExprLeaf::Grammar(g)) => {
178                for u in g.externs().unbound().iter() {
179                    out.push(u.name().to_string());
180                }
181            }
182            ExprNode::Leaf(ExprLeaf::Module(m)) => {
183                for u in m.externs().unbound().iter() {
184                    out.push(u.name().to_string());
185                }
186            }
187            ExprNode::Choice(parts) | ExprNode::Sequence(parts) => {
188                for p in parts {
189                    walk(p, out);
190                }
191            }
192            _ => {}
193        }
194    }
195    walk(expr, &mut unbound);
196    unbound
197}