From c285d14f2eeb7271131778c28897b4f7f4da2c1e Mon Sep 17 00:00:00 2001 From: Goren Barak Date: Sat, 25 Nov 2023 18:15:48 -0500 Subject: [PATCH] Allowed parsing of variable defenitions to AST. --- src/main.rs | 6 ++++++ src/parse/mod.rs | 1 + src/parse/parse.rs | 47 +++++++++++++++++++++++----------------------- 3 files changed, 30 insertions(+), 24 deletions(-) diff --git a/src/main.rs b/src/main.rs index ba8c58d..56d6099 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,8 @@ pub mod codegen; use crate::codegen::fasm::*; use crate::lex::tok::*; use crate::parse::ast::*; +use crate::parse::parse::*; +use logos::Logos; pub mod parse; @@ -43,4 +45,8 @@ fn main() { // println!("{}", fc); + + let mut lexer = Token::lexer("let a = b;"); + println!("{:?}", lex_str("let a = b;")); + println!("{:?}", parse_var_declaration(lexer)); } diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 851c0bc..bedaa01 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -1 +1,2 @@ +pub mod parse; pub mod ast; diff --git a/src/parse/parse.rs b/src/parse/parse.rs index e0ca71f..0deb14d 100644 --- a/src/parse/parse.rs +++ b/src/parse/parse.rs @@ -2,33 +2,32 @@ use super::ast::*; use crate::lex::tok::*; use logos::Lexer; -fn parse_var_declaration(tokens: Lexer) -> Option { - let tok = None; - match tokens.next() { - Let => { - match tokens.next() { - Identifier => { - let name = tokens.slice(); - println!("{:?}", name); - match tokens.next() { - Equal => { - match tokens.next() { - Number(n) => { - let value = Value::Number(n); - println!("{:?}", value); - return Expr::VarDefenition {name, value}; - }, +macro_rules! unwrap { + ($var:expr) => { + $var.next().unwrap().unwrap() + } +} - Identifier => { - let value = Value::Var(VarReference { name: tokens.slice() }); - return Expr::Vardefenition {name, value}; - } - } - } - } +pub fn parse_var_declaration(mut tokens: Lexer) -> Option { + let mut tok = None; + if unwrap!(tokens) == Let { + if unwrap!(tokens) == Identifier { + let name = tokens.slice(); + + println!("{:?}", name); + if unwrap!(tokens) == Equal { + let temp_token = unwrap!(tokens); + + if let Number(n) = temp_token { + let value = Value::Number(n); + println!("{:?}", value); + tok = Some(Expr::VarDefinition(VarDefinition {name, value})); + } else if temp_token == Identifier { + let value = Value::Var(VarReference { name: tokens.slice() }); + tok = Some(Expr::VarDefinition(VarDefinition {name, value})); } } } - _ => None } + tok }