feat(tazjin/rlox): Wire up parser to the REPL

Change-Id: I940448c63ce105d53a0f281b6320ffb01378f207
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2235
Reviewed-by: tazjin <mail@tazj.in>
Tested-by: BuildkiteCI
This commit is contained in:
Vincent Ambo 2020-12-06 15:49:44 +01:00 committed by tazjin
parent 4812fc2ee6
commit 1835b2be99
2 changed files with 21 additions and 7 deletions

View file

@ -1,4 +1,5 @@
use crate::errors::{report, Error}; use crate::errors::{report, Error};
use crate::parser;
use crate::scanner::{self, Token}; use crate::scanner::{self, Token};
// Run some Lox code and print it to stdout // Run some Lox code and print it to stdout
@ -6,12 +7,19 @@ pub fn run(code: &str) {
let chars: Vec<char> = code.chars().collect(); let chars: Vec<char> = code.chars().collect();
match scanner::scan(&chars) { match scanner::scan(&chars) {
Ok(tokens) => print_tokens(tokens), Ok(tokens) => {
print_tokens(&tokens);
match parser::parse(tokens) {
Ok(expr) => println!("Expression:\n{:?}", expr),
Err(error) => report_errors(vec![error]),
}
}
Err(errors) => report_errors(errors), Err(errors) => report_errors(errors),
} }
} }
fn print_tokens<'a>(tokens: Vec<Token<'a>>) { fn print_tokens<'a>(tokens: &Vec<Token<'a>>) {
println!("Tokens:");
for token in tokens { for token in tokens {
println!("{:?}", token); println!("{:?}", token);
} }

View file

@ -11,17 +11,17 @@ use crate::scanner::{Token, TokenKind};
// AST // AST
#[derive(Debug)] #[derive(Debug)]
struct Binary<'a> { pub struct Binary<'a> {
left: Box<Expr<'a>>, left: Box<Expr<'a>>,
operator: Token<'a>, operator: Token<'a>,
right: Box<Expr<'a>>, right: Box<Expr<'a>>,
} }
#[derive(Debug)] #[derive(Debug)]
struct Grouping<'a>(Box<Expr<'a>>); pub struct Grouping<'a>(Box<Expr<'a>>);
#[derive(Debug)] #[derive(Debug)]
enum Literal { pub enum Literal {
Boolean(bool), Boolean(bool),
Number(f64), Number(f64),
String(String), String(String),
@ -29,13 +29,13 @@ enum Literal {
} }
#[derive(Debug)] #[derive(Debug)]
struct Unary<'a> { pub struct Unary<'a> {
operator: Token<'a>, operator: Token<'a>,
right: Box<Expr<'a>>, right: Box<Expr<'a>>,
} }
#[derive(Debug)] #[derive(Debug)]
enum Expr<'a> { pub enum Expr<'a> {
Binary(Binary<'a>), Binary(Binary<'a>),
Grouping(Grouping<'a>), Grouping(Grouping<'a>),
Literal(Literal), Literal(Literal),
@ -200,3 +200,9 @@ impl<'a> Parser<'a> {
return Ok(expr); return Ok(expr);
} }
} }
pub fn parse<'a>(tokens: Vec<Token<'a>>) -> ExprResult<'a> {
let mut parser = Parser { tokens, current: 0 };
parser.expression()
}