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. Twenty four bytes, and everything the matcher needs to decide what to do with it.
67///
68/// The FIRST set and the nullable bit live in here rather than in two arrays beside it. They used
69/// to be parallel tables, on the theory that the filter could read eight bytes of `FIRST` and skip
70/// the node entirely, and that theory was wrong in the case that matters. A node that survives the
71/// filter is loaded immediately afterwards, and surviving is the common case: the filter is there
72/// to cut the thirty six alternatives of `Statement` down, and the one that matches still has to be
73/// walked. So the old layout paid three cache lines on every node it did not reject and saved two
74/// on every node it did, and the walk visits far more of the first kind.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Node {
77 /// What this node can start with, as a set of token keys. A superset, always.
78 pub first: u64,
79 pub a: u32,
80 pub b: u32,
81 pub op: Op,
82 /// Per op, plus `NULLABLE`, which every op can carry.
83 pub flags: u8,
84}
85
86impl Node {
87 /// On an `Identifier` node: the keyword check is dropped, so any word matches.
88 ///
89 /// This is the whole of `ReservedIdentifierMatcher`. It is worth knowing that upstream applies
90 /// it to the rule named `ReservedKeyword`, so a grammar rule that reads
91 /// `ColLabel <- ReservedKeyword / ...` does not test for a reserved word, it accepts any word
92 /// at all. Reading the grammar text alone would get that backwards.
93 pub const RESERVED: u8 = 1 << 0;
94
95 /// This node can match without consuming a token, so its FIRST set says nothing about whether
96 /// it applies and the filter has to let it through.
97 pub const NULLABLE: u8 = 1 << 1;
98
99 /// Whether a node could possibly begin with this token.
100 ///
101 /// False means it cannot, and that is the only answer the caller may act on. True means try it.
102 /// A nullable node always answers true.
103 pub fn can_start(self, key: u64) -> bool {
104 self.flags & Self::NULLABLE != 0 || self.first & key != 0
105 }
106
107 /// The children of a sequence or a choice.
108 pub fn children(self) -> &'static [u32] {
109 &crate::generated::rules::CHILDREN[self.a as usize..(self.a + self.b) as usize]
110 }
111}
112
113/// One rule.
114#[derive(Debug, Clone, Copy)]
115pub struct Rule {
116 pub name: &'static str,
117 /// The node its body compiled to. The matcher does not read this. A `Rule` node carries the
118 /// same number in its `b`, so entering a rule is a field of a node already in a register rather
119 /// than an index into a second table. This is here for the name lookup and for the tests.
120 pub root: u32,
121 /// Whether upstream memoizes it. Twenty two rules do, and they are the ones deep in the
122 /// expression grammar that a failing alternative re-enters at the same position over and over.
123 pub memoized: bool,
124}
125
126/// What an identifier matcher was built to suggest.
127///
128/// Kept rather than reduced to the two answers it implies, because upstream derives both from it
129/// and keeping the derivation in one place is how the two stay comparable. `identifier_matcher.hpp`
130/// is the source.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132#[repr(u32)]
133pub enum Suggestion {
134 Variable = 0,
135 CatalogName = 1,
136 SchemaName = 2,
137 TableName = 3,
138 ColumnName = 4,
139 ScalarFunctionName = 5,
140 TableFunctionName = 6,
141 TypeName = 7,
142 PragmaName = 8,
143 SettingName = 9,
144 FileName = 10,
145}
146
147impl Suggestion {
148 /// Which keyword class may be used as a bare word here, on top of unreserved.
149 ///
150 /// Type name positions allow the type name class, both function name positions allow the
151 /// combined type and function class, and everything else allows the column name class. That
152 /// `TypeFuncKeyword <- TypeNameKeyword / FuncNameKeyword` is a rule in the grammar and also a
153 /// category in the matcher is not a coincidence, it is the same union written once.
154 /// `ParsedGrammarKeywordHelper`'s constructor holds a table of five rule names against five
155 /// keyword sets, and the entry for `typefunc_keyword_map` names that rule, which it then walks
156 /// through its references to collect the words. So the category is not a sixth list somebody
157 /// has to keep in step with the other five, it is what that one line of the grammar says.
158 pub const fn allowed_class(self) -> u8 {
159 use crate::generated::keywords::{COLUMN_NAME, FUNC_NAME, TYPE_NAME};
160 match self {
161 Suggestion::TypeName => TYPE_NAME,
162 Suggestion::ScalarFunctionName | Suggestion::TableFunctionName => TYPE_NAME | FUNC_NAME,
163 _ => COLUMN_NAME,
164 }
165 }
166
167 /// Whether a single quoted string is accepted where this name is expected.
168 ///
169 /// Two positions only. `FROM 'file.parquet'` is the reason, and `SELECT 'x' FROM t` staying a
170 /// string literal rather than becoming a column reference is the reason it is only two.
171 pub const fn supports_string_literal(self) -> bool {
172 matches!(self, Suggestion::TableName | Suggestion::FileName)
173 }
174}
175
176/// How many bits of a FIRST set go to token kinds before the keyword buckets start.
177pub const KIND_BITS: u32 = 6;
178/// The keyword buckets, being the rest of the 64.
179pub const BUCKETS: u32 = 64 - KIND_BITS;
180
181/// A bare or quoted name.
182pub const FIRST_IDENT: u64 = 1 << 0;
183/// A numeric literal.
184pub const FIRST_NUMBER: u64 = 1 << 1;
185/// A string literal.
186pub const FIRST_STRING: u64 = 1 << 2;
187/// An operator or a piece of punctuation.
188pub const FIRST_OPERATOR: u64 = 1 << 3;
189/// A `;`.
190pub const FIRST_TERMINATOR: u64 = 1 << 4;
191/// The end of the input.
192pub const FIRST_END: u64 = 1 << 5;
193/// Every keyword bucket at once, which is what an identifier matcher accepts, because which words
194/// it takes depends on the class and on the position and the filter is not the place to decide it.
195pub const FIRST_ANY_KEYWORD: u64 = !((1 << KIND_BITS) - 1);
196
197/// Which bucket a keyword falls in.
198pub const fn bucket(index: u32) -> u64 {
199 1 << (KIND_BITS + index % BUCKETS)
200}
201
202/// The one FIRST bit this token sets.
203///
204/// Exactly one bit, so the filter is one AND against the node's set, with no loop and no branch.
205pub fn token_key(token: Token) -> u64 {
206 match token.kind {
207 Kind::Identifier | Kind::QuotedIdentifier => FIRST_IDENT,
208 // A word the tokenizer resolved to the table. A word in no class arrives as `Identifier`,
209 // so this branch always has a real index and the fallback is unreachable in practice.
210 Kind::Keyword => {
211 if token.keyword == NOT_A_KEYWORD {
212 FIRST_IDENT
213 } else {
214 bucket(u32::from(token.keyword))
215 }
216 }
217 Kind::Number => FIRST_NUMBER,
218 Kind::String => FIRST_STRING,
219 Kind::Operator => FIRST_OPERATOR,
220 Kind::Terminator => FIRST_TERMINATOR,
221 Kind::EndOfInput => FIRST_END,
222 }
223}
224
225/// The rule with this name, if there is one.
226pub fn rule(name: &str) -> Option<&'static Rule> {
227 crate::generated::rules::RULES
228 .binary_search_by(|candidate| candidate.name.cmp(name))
229 .ok()
230 .map(|index| &crate::generated::rules::RULES[index])
231}
232
233#[cfg(test)]
234mod tests {
235 use super::{Node, Op, Suggestion, bucket, rule, token_key};
236 use crate::generated::rules::{CHILDREN, NODES, PROGRAM, RULES, SYMBOLS};
237 use crate::token::{Flags, Kind, Token};
238
239 fn token(kind: Kind, keyword: u16) -> Token {
240 Token { kind, flags: Flags::default(), keyword, start: 0, end: 1 }
241 }
242
243 #[test]
244 fn a_node_is_twenty_four_bytes() {
245 assert_eq!(size_of::<Node>(), 24);
246 }
247
248 #[test]
249 fn the_tables_are_in_range() {
250 for node in &NODES {
251 match node.op {
252 Op::Sequence | Op::Choice => {
253 assert!(node.b > 0, "an empty sequence or choice matches nothing");
254 let end = (node.a + node.b) as usize;
255 assert!(end <= CHILDREN.len());
256 for child in &CHILDREN[node.a as usize..end] {
257 assert!((*child as usize) < NODES.len());
258 }
259 }
260 Op::Optional | Op::Repeat => assert!((node.a as usize) < NODES.len()),
261 Op::Rule => {
262 assert!((node.a as usize) < RULES.len());
263 // The body index the matcher actually jumps to, which is the one thing in the
264 // table that is written twice and so is the one thing that can disagree.
265 assert_eq!(node.b, RULES[node.a as usize].root);
266 }
267 Op::Symbol => assert!((node.a as usize) < SYMBOLS.len()),
268 Op::Keyword => {
269 assert!((node.a as usize) < crate::generated::keywords::KEYWORDS.len())
270 }
271 _ => {}
272 }
273 }
274 for entry in &RULES {
275 assert!((entry.root as usize) < NODES.len());
276 }
277 }
278
279 #[test]
280 fn the_roots_are_there_and_named() {
281 assert_eq!(RULES[PROGRAM as usize].name, "Program");
282 assert!(rule("Program").is_some());
283 assert!(rule("SelectStatement").is_some());
284 // Overridden by a matcher, so its written body is dead, but the rule itself is very much
285 // reachable and has to be in the table.
286 assert!(rule("Identifier").is_some());
287 // Not reachable from Program once `Identifier` is overridden, so it should be gone.
288 assert!(rule("PlainIdentifier").is_none());
289 }
290
291 #[test]
292 fn a_repeat_never_wraps_something_that_matches_nothing() {
293 // `RepeatMatchProcess` upstream loops while the child succeeds and has no guard for a
294 // child that succeeds without consuming, so this is the difference between a table that
295 // terminates and one that does not.
296 for node in &NODES {
297 if node.op == Op::Repeat {
298 assert_eq!(NODES[node.a as usize].flags & Node::NULLABLE, 0);
299 }
300 }
301 }
302
303 #[test]
304 fn the_filter_only_ever_says_no_to_things_that_could_not_match() {
305 // `SELECT` starts a statement, so the root has to admit it.
306 let select = crate::generated::keywords::KEYWORDS
307 .binary_search_by(|(word, _)| (*word).cmp("select"))
308 .expect("select is a keyword");
309 let key = token_key(token(Kind::Keyword, select as u16));
310 assert!(NODES[RULES[PROGRAM as usize].root as usize].can_start(key));
311
312 // A number does not start a statement, and the root is nullable through
313 // `Statement? (';'+ / EndOfInput)`, so this is about the FIRST set and not about whether
314 // the parse eventually succeeds on an empty script.
315 let number = token_key(token(Kind::Number, u16::MAX));
316 let select_rule = rule("SelectStatement").expect("SelectStatement is a rule");
317 assert!(!NODES[select_rule.root as usize].can_start(number));
318 }
319
320 #[test]
321 fn a_token_maps_to_exactly_one_bit() {
322 for kind in [
323 Kind::Identifier,
324 Kind::QuotedIdentifier,
325 Kind::Number,
326 Kind::String,
327 Kind::Operator,
328 Kind::Terminator,
329 Kind::EndOfInput,
330 ] {
331 assert_eq!(token_key(token(kind, u16::MAX)).count_ones(), 1, "{kind:?}");
332 }
333 assert_eq!(token_key(token(Kind::Keyword, 3)).count_ones(), 1);
334 assert_eq!(bucket(0).count_ones(), 1);
335 }
336
337 #[test]
338 fn the_two_derived_answers_match_the_matcher_header() {
339 use crate::generated::keywords::{COLUMN_NAME, FUNC_NAME, TYPE_NAME};
340 assert_eq!(Suggestion::TypeName.allowed_class(), TYPE_NAME);
341 assert_eq!(Suggestion::ScalarFunctionName.allowed_class(), TYPE_NAME | FUNC_NAME);
342 assert_eq!(Suggestion::TableFunctionName.allowed_class(), TYPE_NAME | FUNC_NAME);
343 assert_eq!(Suggestion::Variable.allowed_class(), COLUMN_NAME);
344 assert!(Suggestion::TableName.supports_string_literal());
345 assert!(Suggestion::FileName.supports_string_literal());
346 assert!(!Suggestion::ColumnName.supports_string_literal());
347 }
348}