Skip to main content

rudb_parse/
rules.rs

1//! The shape of the generated rule table, and the filter that reads it.
2//!
3//! `generated::rules` is data. This is the handful of types that give it meaning, and they are
4//! written by hand because they are an interface: the generator in `xtask` writes discriminants
5//! that have to mean the same thing here, and there is a test on each side that says so.
6//!
7//! The one idea worth stating on its own is the FIRST filter. A choice in this grammar can have
8//! forty alternatives, `Statement` has thirty six, and upstream tries them in order, descending
9//! into each one far enough to fail. Every node here carries a 64 bit set of the token keys it can
10//! begin with, and a token maps to exactly one of those keys, so an alternative that cannot
11//! possibly match is skipped on one AND rather than on a subtree walk. The set is a superset by
12//! construction: keywords share 58 buckets, so a bit that is set may still fail, and a bit that is
13//! clear can never match. Being wrong in that direction costs a wasted attempt and never changes
14//! what the parser accepts, which is what makes it safe to put in front of a dialect we are
15//! copying rather than defining.
16//!
17//! `spec/20-the-grammar.md` sections 3 and 5.
18
19use crate::token::{Kind, NOT_A_KEYWORD, Token};
20
21/// What a node is.
22///
23/// The discriminants are written into `generated::rules` as `Op::Name`, so they are not load
24/// bearing on their own, but `xtask`'s copy of this enum has to have the same variants in the same
25/// order for the generator to be able to name them. `the_ops_match_the_generator` is that check.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27#[repr(u8)]
28pub enum Op {
29    /// A word. `a` indexes `generated::keywords::KEYWORDS`, and the comparison is an index compare
30    /// because the tokenizer already resolved the token's word to the same table.
31    Keyword = 0,
32    /// Punctuation or an operator. `a` indexes `SYMBOLS` and the comparison is on text.
33    Symbol = 1,
34    /// A reference to a rule. `a` is the rule index.
35    Rule = 2,
36    /// `a` is a start index into `CHILDREN`, `b` is how many. All of them, in order.
37    Sequence = 3,
38    /// Same layout. Ordered choice, first success wins, no backtracking into a taken alternative.
39    Choice = 4,
40    /// `a` is the child node. Matches it or matches nothing.
41    Optional = 5,
42    /// `a` is the child node. One or more. `X*` is `Optional(Repeat(X))` in the table, because
43    /// that is what upstream builds and a separate zero or more node would be a second thing to
44    /// keep in step for no gain.
45    Repeat = 6,
46    /// An identifier matcher. `a` is a `Suggestion`, `flags` bit 0 is `RESERVED`.
47    Identifier = 7,
48    /// A numeric literal.
49    Number = 8,
50    /// A string literal, including its adjacent continuations.
51    String = 9,
52    /// An operator token, subject to the exclusions in `OperatorMatcher`.
53    Operator = 10,
54    /// The end of the input.
55    EndOfInput = 11,
56    /// A word in one of the five keyword classes. `a` is the class mask.
57    ///
58    /// The grammar spells these as an ordered choice of two hundred literals, because a PEG has no
59    /// way to say "a word in this set". Upstream compiles that to two hundred `KeywordMatcher`
60    /// objects and tries them in turn. The words in a list are distinct and a `KeywordMatcher` is a
61    /// case insensitive text compare, so membership in the list is exactly a mask test on the class
62    /// the tokenizer already resolved, and the two are the same predicate.
63    KeywordClass = 12,
64}
65
66/// One node. Twelve bytes.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct Node {
69    pub op: Op,
70    /// Per op. Only `Identifier` uses it today, for `RESERVED`.
71    pub flags: u8,
72    pub a: u32,
73    pub b: u32,
74}
75
76impl Node {
77    /// On an `Identifier` node: the keyword check is dropped, so any word matches.
78    ///
79    /// This is the whole of `ReservedIdentifierMatcher`. It is worth knowing that upstream applies
80    /// it to the rule named `ReservedKeyword`, so a grammar rule that reads
81    /// `ColLabel <- ReservedKeyword / ...` does not test for a reserved word, it accepts any word
82    /// at all. Reading the grammar text alone would get that backwards.
83    pub const RESERVED: u8 = 1 << 0;
84
85    /// The children of a sequence or a choice.
86    pub fn children(self) -> &'static [u32] {
87        &crate::generated::rules::CHILDREN[self.a as usize..(self.a + self.b) as usize]
88    }
89}
90
91/// One rule.
92#[derive(Debug, Clone, Copy)]
93pub struct Rule {
94    pub name: &'static str,
95    /// The node its body compiled to.
96    pub root: u32,
97    /// Whether upstream memoizes it. Twenty two rules do, and they are the ones deep in the
98    /// expression grammar that a failing alternative re-enters at the same position over and over.
99    pub memoized: bool,
100}
101
102/// What an identifier matcher was built to suggest.
103///
104/// Kept rather than reduced to the two answers it implies, because upstream derives both from it
105/// and keeping the derivation in one place is how the two stay comparable. `identifier_matcher.hpp`
106/// is the source.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108#[repr(u32)]
109pub enum Suggestion {
110    Variable = 0,
111    CatalogName = 1,
112    SchemaName = 2,
113    TableName = 3,
114    ColumnName = 4,
115    ScalarFunctionName = 5,
116    TableFunctionName = 6,
117    TypeName = 7,
118    PragmaName = 8,
119    SettingName = 9,
120    FileName = 10,
121}
122
123impl Suggestion {
124    /// Which keyword class may be used as a bare word here, on top of unreserved.
125    ///
126    /// Type name positions allow the type name class, both function name positions allow the
127    /// combined type and function class, and everything else allows the column name class. That
128    /// `TypeFuncKeyword <- TypeNameKeyword / FuncNameKeyword` is a rule in the grammar and also a
129    /// category in the matcher is not a coincidence, it is the same union written once.
130    /// `ParsedGrammarKeywordHelper`'s constructor holds a table of five rule names against five
131    /// keyword sets, and the entry for `typefunc_keyword_map` names that rule, which it then walks
132    /// through its references to collect the words. So the category is not a sixth list somebody
133    /// has to keep in step with the other five, it is what that one line of the grammar says.
134    pub const fn allowed_class(self) -> u8 {
135        use crate::generated::keywords::{COLUMN_NAME, FUNC_NAME, TYPE_NAME};
136        match self {
137            Suggestion::TypeName => TYPE_NAME,
138            Suggestion::ScalarFunctionName | Suggestion::TableFunctionName => TYPE_NAME | FUNC_NAME,
139            _ => COLUMN_NAME,
140        }
141    }
142
143    /// Whether a single quoted string is accepted where this name is expected.
144    ///
145    /// Two positions only. `FROM 'file.parquet'` is the reason, and `SELECT 'x' FROM t` staying a
146    /// string literal rather than becoming a column reference is the reason it is only two.
147    pub const fn supports_string_literal(self) -> bool {
148        matches!(self, Suggestion::TableName | Suggestion::FileName)
149    }
150}
151
152/// How many bits of a FIRST set go to token kinds before the keyword buckets start.
153pub const KIND_BITS: u32 = 6;
154/// The keyword buckets, being the rest of the 64.
155pub const BUCKETS: u32 = 64 - KIND_BITS;
156
157/// A bare or quoted name.
158pub const FIRST_IDENT: u64 = 1 << 0;
159/// A numeric literal.
160pub const FIRST_NUMBER: u64 = 1 << 1;
161/// A string literal.
162pub const FIRST_STRING: u64 = 1 << 2;
163/// An operator or a piece of punctuation.
164pub const FIRST_OPERATOR: u64 = 1 << 3;
165/// A `;`.
166pub const FIRST_TERMINATOR: u64 = 1 << 4;
167/// The end of the input.
168pub const FIRST_END: u64 = 1 << 5;
169/// Every keyword bucket at once, which is what an identifier matcher accepts, because which words
170/// it takes depends on the class and on the position and the filter is not the place to decide it.
171pub const FIRST_ANY_KEYWORD: u64 = !((1 << KIND_BITS) - 1);
172
173/// Which bucket a keyword falls in.
174pub const fn bucket(index: u32) -> u64 {
175    1 << (KIND_BITS + index % BUCKETS)
176}
177
178/// The one FIRST bit this token sets.
179///
180/// Exactly one bit, so the filter is `FIRST[node] & key(token) != 0` with no loop and no branch.
181pub fn token_key(token: Token) -> u64 {
182    match token.kind {
183        Kind::Identifier | Kind::QuotedIdentifier => FIRST_IDENT,
184        // A word the tokenizer resolved to the table. A word in no class arrives as `Identifier`,
185        // so this branch always has a real index and the fallback is unreachable in practice.
186        Kind::Keyword => {
187            if token.keyword == NOT_A_KEYWORD {
188                FIRST_IDENT
189            } else {
190                bucket(u32::from(token.keyword))
191            }
192        }
193        Kind::Number => FIRST_NUMBER,
194        Kind::String => FIRST_STRING,
195        Kind::Operator => FIRST_OPERATOR,
196        Kind::Terminator => FIRST_TERMINATOR,
197        Kind::EndOfInput => FIRST_END,
198    }
199}
200
201/// Whether a node could possibly begin with this token.
202///
203/// False means it cannot, and that is the only answer the caller may act on. True means try it.
204pub fn can_start(node: u32, key: u64) -> bool {
205    crate::generated::rules::FIRST[node as usize] & key != 0
206}
207
208/// The rule with this name, if there is one.
209pub fn rule(name: &str) -> Option<&'static Rule> {
210    crate::generated::rules::RULES
211        .binary_search_by(|candidate| candidate.name.cmp(name))
212        .ok()
213        .map(|index| &crate::generated::rules::RULES[index])
214}
215
216#[cfg(test)]
217mod tests {
218    use super::{Node, Op, Suggestion, bucket, can_start, rule, token_key};
219    use crate::generated::rules::{CHILDREN, FIRST, NODES, NULLABLE, PROGRAM, RULES, SYMBOLS};
220    use crate::token::{Flags, Kind, Token};
221
222    fn token(kind: Kind, keyword: u16) -> Token {
223        Token { kind, flags: Flags::default(), keyword, start: 0, end: 1 }
224    }
225
226    #[test]
227    fn a_node_is_twelve_bytes() {
228        assert_eq!(size_of::<Node>(), 12);
229    }
230
231    #[test]
232    fn the_tables_are_parallel_and_in_range() {
233        assert_eq!(NODES.len(), FIRST.len());
234        assert_eq!(NODES.len(), NULLABLE.len());
235        for node in &NODES {
236            match node.op {
237                Op::Sequence | Op::Choice => {
238                    assert!(node.b > 0, "an empty sequence or choice matches nothing");
239                    let end = (node.a + node.b) as usize;
240                    assert!(end <= CHILDREN.len());
241                    for child in &CHILDREN[node.a as usize..end] {
242                        assert!((*child as usize) < NODES.len());
243                    }
244                }
245                Op::Optional | Op::Repeat => assert!((node.a as usize) < NODES.len()),
246                Op::Rule => assert!((node.a as usize) < RULES.len()),
247                Op::Symbol => assert!((node.a as usize) < SYMBOLS.len()),
248                Op::Keyword => {
249                    assert!((node.a as usize) < crate::generated::keywords::KEYWORDS.len())
250                }
251                _ => {}
252            }
253        }
254        for entry in &RULES {
255            assert!((entry.root as usize) < NODES.len());
256        }
257    }
258
259    #[test]
260    fn the_roots_are_there_and_named() {
261        assert_eq!(RULES[PROGRAM as usize].name, "Program");
262        assert!(rule("Program").is_some());
263        assert!(rule("SelectStatement").is_some());
264        // Overridden by a matcher, so its written body is dead, but the rule itself is very much
265        // reachable and has to be in the table.
266        assert!(rule("Identifier").is_some());
267        // Not reachable from Program once `Identifier` is overridden, so it should be gone.
268        assert!(rule("PlainIdentifier").is_none());
269    }
270
271    #[test]
272    fn a_repeat_never_wraps_something_that_matches_nothing() {
273        // `RepeatMatchProcess` upstream loops while the child succeeds and has no guard for a
274        // child that succeeds without consuming, so this is the difference between a table that
275        // terminates and one that does not.
276        for node in &NODES {
277            if node.op == Op::Repeat {
278                assert!(!NULLABLE[node.a as usize]);
279            }
280        }
281    }
282
283    #[test]
284    fn the_filter_only_ever_says_no_to_things_that_could_not_match() {
285        // `SELECT` starts a statement, so the root has to admit it.
286        let select = crate::generated::keywords::KEYWORDS
287            .binary_search_by(|(word, _)| (*word).cmp("select"))
288            .expect("select is a keyword");
289        let key = token_key(token(Kind::Keyword, select as u16));
290        assert!(can_start(RULES[PROGRAM as usize].root, key));
291
292        // A number does not start a statement, and the root is nullable through
293        // `Statement? (';'+ / EndOfInput)`, so this is about the FIRST set and not about whether
294        // the parse eventually succeeds on an empty script.
295        let number = token_key(token(Kind::Number, u16::MAX));
296        let select_rule = rule("SelectStatement").expect("SelectStatement is a rule");
297        assert!(!can_start(select_rule.root, number));
298    }
299
300    #[test]
301    fn a_token_maps_to_exactly_one_bit() {
302        for kind in [
303            Kind::Identifier,
304            Kind::QuotedIdentifier,
305            Kind::Number,
306            Kind::String,
307            Kind::Operator,
308            Kind::Terminator,
309            Kind::EndOfInput,
310        ] {
311            assert_eq!(token_key(token(kind, u16::MAX)).count_ones(), 1, "{kind:?}");
312        }
313        assert_eq!(token_key(token(Kind::Keyword, 3)).count_ones(), 1);
314        assert_eq!(bucket(0).count_ones(), 1);
315    }
316
317    #[test]
318    fn the_two_derived_answers_match_the_matcher_header() {
319        use crate::generated::keywords::{COLUMN_NAME, FUNC_NAME, TYPE_NAME};
320        assert_eq!(Suggestion::TypeName.allowed_class(), TYPE_NAME);
321        assert_eq!(Suggestion::ScalarFunctionName.allowed_class(), TYPE_NAME | FUNC_NAME);
322        assert_eq!(Suggestion::TableFunctionName.allowed_class(), TYPE_NAME | FUNC_NAME);
323        assert_eq!(Suggestion::Variable.allowed_class(), COLUMN_NAME);
324        assert!(Suggestion::TableName.supports_string_literal());
325        assert!(Suggestion::FileName.supports_string_literal());
326        assert!(!Suggestion::ColumnName.supports_string_literal());
327    }
328}