From a1a046f9dde731e6e3d0ffe825ad01aeb1c9e70e Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Fri, 3 Sep 2021 00:06:38 +0200 Subject: ch2: added parser following chapter 2 --- src/main.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 5 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 361f76f..0e91734 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,18 +1,74 @@ mod lexer; +mod parser; -use lexer::Lexer; +use lexer::{Lexer, Token}; +use parser::Parser; use std::io::Read; +fn handle_definition(p: &mut Parser) +where + I: Iterator, +{ + match p.parse_definition() { + Ok(expr) => println!("Parse 'def'\n{:?}", expr), + Err(err) => { + eprintln!("Error: {:?}", err); + p.get_next_token(); + } + } +} + +fn handle_extern(p: &mut Parser) +where + I: Iterator, +{ + match p.parse_extern() { + Ok(expr) => println!("Parse 'extern'\n{:?}", expr), + Err(err) => { + eprintln!("Error: {:?}", err); + p.get_next_token(); + } + } +} + +fn handle_top_level_expression(p: &mut Parser) +where + I: Iterator, +{ + match p.parse_top_level_expr() { + Ok(expr) => println!("Parse top-level expression\n{:?}", expr), + Err(err) => { + eprintln!("Error: {:?}", err); + p.get_next_token(); + } + } +} + fn main() { - println!("Lex stdin."); - println!("ENTER to lex current input."); + println!("Parse stdin."); + println!("ENTER to parse current input."); println!("C-c to exit."); - let mut lex = Lexer::new(std::io::stdin().bytes().filter_map(|v| { + + let lexer = Lexer::new(std::io::stdin().bytes().filter_map(|v| { let v = v.ok()?; Some(v.into()) })); + let mut parser = Parser::new(lexer); + + // Throw first coin and initialize cur_tok. + parser.get_next_token(); + loop { - println!("{:?}", lex.gettok()); + match *parser.cur_tok() { + Token::Eof => break, + Token::Char(';') => { + // Ignore top-level semicolon. + parser.get_next_token() + } + Token::Def => handle_definition(&mut parser), + Token::Extern => handle_extern(&mut parser), + _ => handle_top_level_expression(&mut parser), + } } } -- cgit v1.2.3