From 452d28719f246317fd97e6ffb57e26a5a30a7ba7 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Mon, 17 Oct 2022 09:35:03 -0400 Subject: [PATCH] Expose a method to parse AST from tokens directly --- parser/src/parser.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/parser/src/parser.rs b/parser/src/parser.rs index 49d2e53..9531eb3 100644 --- a/parser/src/parser.rs +++ b/parser/src/parser.rs @@ -5,9 +5,11 @@ //! parse a whole program, a single statement, or a single //! expression. +use std::iter; + +use crate::lexer::LexResult; pub use crate::mode::Mode; use crate::{ast, error::ParseError, lexer, python}; -use std::iter; /* * Parse python code. @@ -23,6 +25,17 @@ pub fn parse_program(source: &str, source_path: &str) -> Result, + source_path: &str, +) -> Result { + parse_tokens(lxr, Mode::Module, source_path).map(|top| match top { + ast::Mod::Module { body, .. } => body, + _ => unreachable!(), + }) +} + /// Parses a python expression /// /// # Example @@ -80,6 +93,20 @@ pub fn parse(source: &str, mode: Mode, source_path: &str) -> Result, + mode: Mode, + source_path: &str, +) -> Result { + let marker_token = (Default::default(), mode.to_marker(), Default::default()); + let tokenizer = iter::once(Ok(marker_token)).chain(lxr); + + python::TopParser::new() + .parse(tokenizer) + .map_err(|e| crate::error::parse_error_from_lalrpop(e, source_path)) +} + #[cfg(test)] mod tests { use super::*;