pub struct Parser<'a> { /* private fields */ }Expand description
A Pratt parser for Swan expressions.
Create one with Parser::new and call Parser::parse once to get the
root node of the expression.
Implementations§
Source§impl<'a> Parser<'a>
impl<'a> Parser<'a>
Sourcepub fn new(lexer: Lexer<'a>) -> Self
pub fn new(lexer: Lexer<'a>) -> Self
Creates a new parser wrapping lexer and pre-loads the look-ahead.
Sourcepub fn parse_expr(&mut self, min_bp: u32) -> Node
pub fn parse_expr(&mut self, min_bp: u32) -> Node
Parses a single complete expression at the given minimum binding power.
min_bp is the binding power of the operator that called us. We only
consume infix operators whose left-binding-power is GREATER than
min_bp; everything else is left for the caller to handle.
Call with min_bp = 0 to parse a full expression.
§Algorithm (step by step)
- Parse a PREFIX production → gives us the left-hand node (lhs).
- Loop:
a. Skip comments and peek at the next token.
b. If
lbp(peek) <= min_bp→ STOP; return lhs. c. Consume the infix token (advance). d. Recursively parse the rhs withmin_bp = rbp(infix_token). e. Combine lhs + rhs into a new node; that becomes the new lhs.
Sourcepub fn parse(&mut self) -> Node
pub fn parse(&mut self) -> Node
Parses the entire input as a single expression and returns its root node.
An empty source (or one containing only comments) gives
Node::Nothing. Parsing never fails; see the
module documentation for how syntax errors are represented.
§Examples
use swan_core::lexer::Lexer;
use swan_core::parser::Parser;
let lexer = Lexer::new("1 + 2 * 3");
let mut parser = Parser::new(lexer);
let ast = parser.parse(); // SumOp(1, ProductOp(2, 3))Auto Trait Implementations§
impl<'a> Freeze for Parser<'a>
impl<'a> RefUnwindSafe for Parser<'a>
impl<'a> Send for Parser<'a>
impl<'a> Sync for Parser<'a>
impl<'a> Unpin for Parser<'a>
impl<'a> UnsafeUnpin for Parser<'a>
impl<'a> UnwindSafe for Parser<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more