Skip to main content

pred_recdec/
lib.rs

1//! # Predicated Recursive Descent
2//! 
3//! aka pred recdec
4//! 
5//! It is **VERY HIGHLY RECOMMENDED** that you use the mimalloc crate (or some other high-performance memory allocator) if you use this library:
6//!
7//! ```
8//! use mimalloc::MiMalloc;
9//! #[global_allocator]
10//! static GLOBAL: MiMalloc = MiMalloc;
11//! ```
12//!
13//! You want:
14//! - [bnf::bnf_to_grammar]
15//! - [bnf::Grammar]
16//! - [bnf::tokenize]
17//! - [bnf::Token]
18//! - [ast::ASTNode]
19//! - [ast::parse]
20//! 
21//! This library provides a way to write and run [BNF](https://en.wikipedia.org/wiki/Backus–Naur_form) grammars with annotations that make them behave like a handwritten recursive descent parser.
22//!
23//! The structure of the BNF corresponds to the structure of the resulting ASTs. Tokenization is handled automatically; you do not need to write a lexical grammar. The tokenizer handles comments, whitespace, maximal munch, and even regex tests. Unless you're trying to do something silly like how Lua uses context-sensitive long brackets for comments, that's all you need.
24//! 
25//! The resulting parser is scannerful but tolerant of soft keywords. It performs no memoization or backtracking. Impure hooks are safe. There's no lookahead generation or guessing: the parser only does exactly what you specify in the BNF, in order.
26//! 
27//! This is strong enough to parse C. Yes, the language with the super horrible grammar that needs arbitrary lookahead and state munging to parse correctly.
28//! 
29//! This is *not* a PEG or packrat thing.
30//!
31//! Performance: varies between 50% and 400% slower than a native machine code handwritten parser. For more complex grammars, the performance loss is less. Totally usable!
32//! 
33//! Simple example (totally not lisp), capable of parsing the input `(a b (q x)kfwaiei i  9 (af0f1a) () () )`:
34//! 
35//! ```text
36//! S ::= @peek(0, "(") parenexpr
37//! parenexpr ::=
38//!     @peek(1, ")") "(" ")"
39//!     | "(" itemlist ")"
40//! itemlist ::=
41//!     @peek(0, ")") #end of list
42//!     | item $become itemlist
43//! item ::=
44//!     @peek(0, "(") parenexpr
45//!     | @auto r`[a-zA-Z_][a-zA-Z_0-9]*|[0-9\.]*`r
46//! ```
47//!
48//! ## Example usage
49//!
50//! ```
51//! # {} /*
52//! let mut g = bnf_to_grammar(&grammar_source).unwrap();
53//! let tokens = tokenize(&mut g, &test_source);
54//! let tokens = tokens.unwrap();
55//! 
56//! use std::rc::Rc;
57//! let ast = parse(&g,
58//!     "S", // Name of your root-most rule
59//!     &tokens[..],
60//!     Rc::new(<_>::default()), // guards (see test in `src/c.rs` for a detailed usage example)
61//!     Rc::new(<_>::default()) // hooks (same)
62//! );
63//! 
64//! if let Ok(ast) = &ast
65//! {
66//!     print_ast_pred_recdec(ast, &g.string_cache_inv, 0);
67//! }
68//! drop(ast.unwrap());
69//! # */
70//! ```
71//!
72//! ## BNF Extensions
73//!
74//! Mini glossary: nonterminal = "call of another rule", terminal = "immediate match of a token's contents".
75//!
76//! Common EBNF syntax like `[]` or `()?` is not supported. Don't worry, you can make flat lists just fine.
77//! 
78//! Extensions from pure BNF are:
79//! 
80//! `\` - End-of-line escaping with `\`, so you can write multiline regexes.
81//!
82//! `#` - Comments until the end of the line, outside of strings/regexes.
83//!
84//! `"...` - Terms starting with `"` are inline strings. They register with the tokenizer and check the entire body of a token. (Strings are interned, so this is O(1).)
85//! 
86//! Terms starting with ```r`...```, ```R`...```, or ```A`...``` are inline regexes:
87//! - ```r`...`r``` registers with the tokenizer and does a full token match (i.e. it's given an implicit trailing `\z` during token matching).
88//! - ```R`...`r``` DOES NOT register with the tokenizer, but does a full token match (i.e. it's given an implicit trailing `\z`). This is provided as an optimization: sometimes you want to combine tokenizer regexes into a single regex for performance reasons, which should be done manually.
89//! - ```A`...`r``` DOES NOT register with the tokenizer, and only checks against the start of the token. This is only provided as an optimization: ```R``r``` is strictly more powerful.
90//!
91//! Regex results are cached, so checking them is amortized O(1).
92//!
93//! Terms beginning with `!` currently only have one kind:
94//! - `!hook`, e.g. `!hook(fix_infix_expr)`, are calls to user-provided code. This is **allowed to be impure**, e.g. management of **typedef symbol tables**.
95//!
96//! Terms beginning with `@` are guards/predicates. They determine, at the start of a given alternation/production, whether it is valid. If true, that production is taken, and none of the others will be attempted (at this location). Remember, there's no backtracking or magic.
97//! - `@peek(N, STRING)` - Checks if, relative to the parse position, the given token contains the given text.
98//! - `@peekr(N, REGEX)` - Same, but only for regexes.
99//! - `@auto item` - Desugars to `@peek(0, item) item` or `@peekr(0, item) item` automatically.
100//! - `@guard(name)` - Calls user-provided code to determine if the production is accepted. This is allowed to be impure, but you should be careful with it, since a path hasn't been committed yet.
101//! - `@recover` - Pseudo-guard, is never attempted. Instead, it tells the associated grammar rule that if it fails, it's allowed to recover (into a poisoned state) by seeking for a particular set of tokens.
102//! - `@recover_before` - Same, but stops right before accepting any seek token instead of consuming it.
103//! 
104//! Terms starting with `$` are directives:
105//!- `$become nonterminal` performs a tail call, keeping the current AST node name. This can be used to build lists without smashing the stack.
106//!- `$become_as nonterminal` performs a tail call, replacing the current AST node's name with that of the target.
107//!- `$any` matches and includes any one token as a terminal.
108//!- `$pruned` specifies that this particular production doesn't generate AST nodes for bare terminals. This is useful for reducing AST bloat. For example, `@peek(1, ")") "(" ")" $pruned` is a non-empty production but produces zero AST nodes.
109//!- `$hoist` deletes the most recent child and moves its children into the current AST node's child list.
110//!- `$hoist_unit` does the same, but only if the child has exactly one child.
111//!- `$drop` deletes the most recent child.
112//!- `$drop_empty` does the same, but only if the child has exactly zero children.
113//!- `$rename nonterminal` renames the current AST node, giving it the same name as `nonterminal` but does NOT invoke a run of parsing `nonterminal` (i.e. it's skipped over).
114//! 
115//! You'll note that there's no "negative rule-match-check predicate" extension (e.g. no "parse A, but only if it doesn't also parse B"). This is by design. Rule-level negation is way too powerful, and requires an extremely sophisticated parser generator (e.g. packrat) to handle both correctly and cheaply. For any reasonably simple implementation, it would be incompatible with impure hooks. `__RESERVED_WORDS`, described below, is the only exception, because it's easy to define in a sane way.
116//!
117//! For negative token predicates (peeks), you can refactor the grammar slightly, or if it's a particularly complicated peek, write a custom guard. So this isn't a limitation.
118//!
119//! ## Magic pseudo-rules
120//!
121//! The following magic pseudo rule names are available (e.g. `__COMMENTS ::= //`):
122//!
123//! - `__BRACKET_PAIRS` e.g. `::= ( ) | { }` - Tell the tokenizer to pair-up these tokens with each other so that hooks can skip over their contents in O(1) time.
124//! - `__COMMENTS` e.g. `::= "//" | "#"` -- Tell the tokenizer that this is a kind of single-line comment.
125//! - `__COMMENT_PAIRS` e.g. `::= /* */` - Tell the tokenizer that this is a kind of pair-based comment.
126//! - `__COMMENT_PAIRS_NESTED` - Same, but nesting, like in Rust.
127//! - `__COMMENT_REGEXES` - Same, but formed as a regex. These are slower than the above, because the Rust `regex` crate doesn't have a JIT.
128//! - `__RESERVED_WORDS` - e.g. `::= auto break case` - Specifies a list of token contents that are not allowed to be "accepted" by regex terminals like ```r`[a-zA-Z_]+`r```
129
130pub mod bnf;
131pub mod ast;
132mod json;
133
134// Thing
135pub (crate) use rustc_hash::FxBuildHasher as HashBuilder;
136
137#[cfg(test)]
138mod test {
139    #[test]
140    fn test_lib() {
141        use crate::*;
142        pub use bnf::*;
143        pub use ast::*;
144        
145        let grammar_source = r#"
146    __BRACKET_PAIRS ::= ( )
147    S ::= @peek(0, "(") parenexpr $become EOF
148    EOF ::= @eof
149    parenexpr ::=
150        @peek(1, ")") "(" ")" $pruned
151        | "(" $become itemlist $pruned
152    itemlist ::=
153        @peek(0, ")") $pruned ")"
154        | @peek(0, "(") parenexpr $become itemlist
155        | @auto r`[a-zA-Z_][a-zA-Z_0-9]*|[0-9\.]*`r $become itemlist
156        "#;
157        
158        let test_source = r#"
159        (a b (q x)kfwaiei i  9 (af0f1a) () () )
160        "#;
161        
162        let mut g = bnf_to_grammar(&grammar_source).unwrap();
163        let tokens = tokenize(&mut g, &test_source);
164        let tokens = tokens.unwrap();
165        
166        use std::rc::Rc;
167        let ast = parse(&g, "S", &tokens[..], Rc::new(<_>::default()), Rc::new(<_>::default()));
168        
169        if let Ok(ast) = &ast
170        {
171            print_ast_pred_recdec(ast, &g.string_cache_inv, 0);
172        }
173        drop(ast.unwrap());
174        
175        
176        
177        let test_source = r#"
178        ( a ) a
179        "#;
180        
181        let tokens = tokenize(&mut g, &test_source);
182        let tokens = tokens.unwrap();
183        let ast = parse(&g, "S", &tokens[..], Rc::new(<_>::default()), Rc::new(<_>::default()));
184        //println!("{:?}", ast);
185        let ast = ast.unwrap_err();
186        assert_eq!(ast.token_index, 3);
187        assert_eq!(ast.rule, 2);
188        assert_eq!(ast.in_alt, 0);
189        assert_eq!(ast.alt_progress, Some(1));
190        assert_eq!(ast.on_behalf_of_rule, 1);
191        
192        
193        
194        let test_source = r#"    ( a ) ) "#;
195        
196        let tokens = tokenize(&mut g, &test_source);
197        let tokens = tokens.unwrap_err();
198        //println!("{:?}", tokens);
199        assert_eq!(tokens.produced, 3);
200        assert_eq!(tokens.location, 10);
201        assert_eq!(tokens.pairing_error, Some((")".to_string(), false)));
202        
203        
204        
205        let grammar_source = r#"
206    S ::= NUL a2 a $drop a a $hoist a $drop_empty NUL $drop_empty a2 a $hoist_unit a2 $hoist_unit EOF $drop
207    EOF ::= @eof
208    NUL ::=
209    a ::= "a"
210    a2 ::= "a" "a" $rename ax
211    ax ::= #dummy
212        "#;
213        let mut g = bnf_to_grammar(&grammar_source).unwrap();
214        
215        let test_source = r#"aaa a a aa a aaa"#;
216        
217        let tokens = tokenize(&mut g, &test_source);
218        let tokens = tokens.unwrap();
219        let ast = parse(&g, "S", &tokens[..], Rc::new(<_>::default()), Rc::new(<_>::default()));
220        let ast = ast.unwrap();
221        print_ast_pred_recdec(&ast, &g.string_cache_inv, 0);
222        let s = ast_to_shape_string(&ast);
223        println!("{}", s);
224        assert_eq!(s, "++-+..-+.-.+..-.-");
225        
226        assert_eq!(*g.string_cache_inv[ast.children.unwrap()[1].text as usize], "ax");
227    }
228}