pub struct ParserState<'tokens, 'arena, K, R, N, Ctx = ()>{
pub context: Ctx,
/* private fields */
}Expand description
Stateful helper passed around by grammar routines.
Fields§
§context: CtxImplementations§
Source§impl<'tokens, 'arena, K, R, N, Ctx> ParserState<'tokens, 'arena, K, R, N, Ctx>
impl<'tokens, 'arena, K, R, N, Ctx> ParserState<'tokens, 'arena, K, R, N, Ctx>
Sourcepub fn new(
tokens: &'tokens [Token<K>],
arena: &'arena mut NodeArena<K, R, N>,
include_trivia: bool,
context: Ctx,
) -> Self
pub fn new( tokens: &'tokens [Token<K>], arena: &'arena mut NodeArena<K, R, N>, include_trivia: bool, context: Ctx, ) -> Self
Construct a new parser state.
Examples found in repository?
32fn main() {
33 // Create a parser
34 let mut parser = Parser::create();
35
36 // Register a simple rule: Expr -> Ident Plus Ident
37 parser.register_rule(
38 Rule::Expr,
39 helpers::seq(vec![
40 helpers::token(Token::Ident),
41 helpers::token(Token::Plus),
42 helpers::token(Token::Ident),
43 ]),
44 );
45
46 // Create token stream: "a + b"
47 let tokens = vec![
48 TokenStruct::create(Token::Ident, Span::new(0..1), "a", Vec::new(), Vec::new()),
49 TokenStruct::create(Token::Plus, Span::new(2..3), "+", Vec::new(), Vec::new()),
50 TokenStruct::create(Token::Ident, Span::new(4..5), "b", Vec::new(), Vec::new()),
51 ];
52
53 // Parse the tokens
54 let mut arena: NodeArena<Token, Rule, RawNodeId> = NodeArena::new();
55 let mut state = ParserState::new(&tokens, &mut arena, false, ());
56
57 match parser.parse_rule(Rule::Expr, &mut state) {
58 Ok(_) => {
59 println!("✓ Successfully parsed!");
60 println!("CST contains {} nodes", arena.len());
61 }
62 Err(e) => {
63 println!("✗ Parse error: {:?}", e);
64 }
65 }
66}More examples
32fn main() {
33 let mut parser = Parser::create();
34
35 // Define a simple statement rule: Ident Plus Ident Semicolon
36 parser.register_rule(
37 Rule::Statement,
38 helpers::seq(vec![
39 helpers::token(Token::Ident),
40 helpers::token(Token::Plus),
41 helpers::token(Token::Ident),
42 helpers::token(Token::Semicolon),
43 ]),
44 );
45
46 // Configure error recovery: use semicolon as sync token
47 parser.set_sync_tokens(vec![Token::Semicolon]);
48
49 // Create token stream with an error: "a + invalid ; b + c ;"
50 // The parser should recover after the first semicolon
51 let tokens = vec![
52 TokenStruct::create(Token::Ident, Span::new(0..1), "a", Vec::new(), Vec::new()),
53 TokenStruct::create(Token::Plus, Span::new(2..3), "+", Vec::new(), Vec::new()),
54 TokenStruct::create(
55 Token::Invalid,
56 Span::new(4..10),
57 "invalid",
58 Vec::new(),
59 Vec::new(),
60 ),
61 TokenStruct::create(
62 Token::Semicolon,
63 Span::new(11..12),
64 ";",
65 Vec::new(),
66 Vec::new(),
67 ),
68 TokenStruct::create(Token::Ident, Span::new(13..14), "b", Vec::new(), Vec::new()),
69 TokenStruct::create(Token::Plus, Span::new(15..16), "+", Vec::new(), Vec::new()),
70 TokenStruct::create(Token::Ident, Span::new(17..18), "c", Vec::new(), Vec::new()),
71 TokenStruct::create(
72 Token::Semicolon,
73 Span::new(19..20),
74 ";",
75 Vec::new(),
76 Vec::new(),
77 ),
78 ];
79
80 let mut arena: NodeArena<Token, Rule, RawNodeId> = NodeArena::new();
81 let mut state = ParserState::new(&tokens, &mut arena, false, ());
82
83 println!("Parsing with error recovery enabled...");
84 println!("Input: a + invalid ; b + c ;");
85 println!();
86
87 // Try to parse - should recover after first error
88 match parser.parse_rule(Rule::Statement, &mut state) {
89 Ok(_) => {
90 println!("✓ Parsed successfully (with recovery)!");
91 }
92 Err(e) => {
93 println!("✗ Parse error: {:?}", e);
94 println!("Note: Error recovery attempted to sync at semicolon");
95 }
96 }
97}Sourcepub fn with_memo(
tokens: &'tokens [Token<K>],
arena: &'arena mut NodeArena<K, R, N>,
include_trivia: bool,
context: Ctx,
memo: Option<&'arena mut MemoTable<K, R, N>>,
) -> Self
pub fn with_memo( tokens: &'tokens [Token<K>], arena: &'arena mut NodeArena<K, R, N>, include_trivia: bool, context: Ctx, memo: Option<&'arena mut MemoTable<K, R, N>>, ) -> Self
Construct a new parser state with memoization support.
Sourcepub fn skip_trivia(&mut self)
pub fn skip_trivia(&mut self)
Skip trivia tokens at the current cursor.
This method uses the precomputed non-trivia index when available for better performance on large token streams.
Sourcepub fn peek(&self, offset: usize) -> Option<&Token<K>>
pub fn peek(&self, offset: usize) -> Option<&Token<K>>
Return a reference to a token offset positions away.
Sourcepub fn advance(&mut self) -> Option<&Token<K>>
pub fn advance(&mut self) -> Option<&Token<K>>
Advance the cursor by one token and return the new token.
Sourcepub fn expect(&mut self, kind: K) -> Result<&'tokens Token<K>, ParseError<K, R>>
pub fn expect(&mut self, kind: K) -> Result<&'tokens Token<K>, ParseError<K, R>>
Expect a specific token kind.
Sourcepub fn expect_node(&mut self, kind: K) -> Result<N, ParseError<K, R>>
pub fn expect_node(&mut self, kind: K) -> Result<N, ParseError<K, R>>
Expect a token and wrap it inside a CST node.
Sourcepub fn current_span(&self) -> Span
pub fn current_span(&self) -> Span
Current source span or a default span if the stream is empty.
Sourcepub fn current_token(&self) -> Option<&Token<K>>
pub fn current_token(&self) -> Option<&Token<K>>
Get the current token (if any).
Returns None if at end of input.
Sourcepub fn remaining_tokens(&self) -> usize
pub fn remaining_tokens(&self) -> usize
Get the number of remaining tokens.
This counts all tokens (including trivia if include_trivia is true).
Sourcepub fn rule_stack(&self) -> &[R]
pub fn rule_stack(&self) -> &[R]
Get the rule stack for debugging/inspection.
Returns a slice of rule IDs currently being parsed.
Sourcepub fn arena_size(&self) -> usize
pub fn arena_size(&self) -> usize
Get the number of nodes in the arena.
Sourcepub fn start_node(&self, rule_id: R) -> NodeBuilder<R, N>
pub fn start_node(&self, rule_id: R) -> NodeBuilder<R, N>
Start building a new CST node for the provided rule.
Sourcepub fn alloc_node(
&mut self,
kind: CstKind<K, R>,
span: Span,
children: NodeChildren<N>,
) -> N
pub fn alloc_node( &mut self, kind: CstKind<K, R>, span: Span, children: NodeChildren<N>, ) -> N
Allocate a node inside the arena.
Sourcepub fn current_rule(&self) -> Option<R>
pub fn current_rule(&self) -> Option<R>
Get the current rule context (top of the stack).
Sourcepub fn build_context_stack(&self) -> Vec<ErrorContext<R>>
pub fn build_context_stack(&self) -> Vec<ErrorContext<R>>
Build an error context stack from the current rule stack.