diff --git a/examples/if.rs b/examples/if.rs new file mode 100644 index 0000000000000000000000000000000000000000..8bda63162c5aaa6613801468a47b3a458e88956a --- /dev/null +++ b/examples/if.rs @@ -0,0 +1,6 @@ +fn main() { + let a = { + let b = 1; + b + }; +} diff --git a/src/ast/main.rs b/src/ast/main.rs index 0eb05e3ce7421141a341870832239739c2d5d1cd..3e05258d76b8c6703911db9d9771e2067fa79561 100644 --- a/src/ast/main.rs +++ b/src/ast/main.rs @@ -1,3 +1,6 @@ +use std::fs::File; +use std::io::prelude::*; + use lalrpop_util::lalrpop_mod; lalrpop_mod!(pub parser, "/ast/parser.rs"); @@ -7,13 +10,32 @@ use parser::*; pub mod ast; use ast::*; -fn main() { +fn main() {} + +pub fn read(file_name: &str) -> std::io::Result<String> { + let mut file = File::open(file_name)?; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + Ok(contents) +} + +// pub fn parse(file_name: &str) -> Program { +// let p = read(file_name).expect("File not found"); +// ProgramParser::new().parse(&p).unwrap() +// } + +#[test] +fn t1() { let s = " - { - let ; + { + let a = { + let b = 1 + 1; ; + if a { } + + b } + } "; - - println!("{:?}", BlockExpressionParser::new().parse(s)); + StmtsParser::new().parse(s).unwrap(); } diff --git a/src/ast/parser.lalrpop b/src/ast/parser.lalrpop index 95085a640661cfeea82d7a4aed6ad15be0f0f0c0..2688e4aae7b764e33bff25995c07f90a8873cc92 100644 --- a/src/ast/parser.lalrpop +++ b/src/ast/parser.lalrpop @@ -4,40 +4,68 @@ use crate::ast::*; grammar; -pub ExpressionWithoutBlock: () = { - LiteralExpression => () +match { + // The default whitespace skipping is disabled an `ignore pattern` is specified + r"\s*" => { }, + // Skip `// comments` + r"//[^\n\r]*" => { }, + // Skip `/* comments */` + r"/\*([^\*]*\*+[^\*/])*([^\*]*\*+|[^\*])*\*/" => { }, + _ } -pub LiteralExpression = { - Num - Id +//pub Expr: () +pub Expr: () = { + ExprStmt => (), + ExprNoBlock => (), } -ExpressionWithBlock: () = { - BlockExpression => () +pub ExprNoBlock: () = { + Expr AddSub Factor => (), + Factor => (), } -pub BlockExpression: ()= { - "{" Statements? "}" => () +pub AddSub: () = { + "+" => (), + "-" => (), } -pub Statements: () = { - Statement+ => (), - Statement+ ExpressionWithoutBlock => (), - ExpressionWithBlock => () +pub Factor: () = { + Factor MulDiv Term => (), + Term => (), } -pub Statement: () = { - ";" => (), - "let" ";" => (), - ExpressionStatement => () +pub MulDiv: () = { + "/" => (), + "*" => (), +} + +pub Term: () = { + Id => (), + Num => (), +} + + + + +pub ExprStmt: () = { + "if" Expr Stmts "else" Stmts => (), + Stmts => (), +} + +pub Stmts: () = { + "{" Stmt* "}" => (), } -pub ExpressionStatement: () = { - ExpressionWithoutBlock ";" => (), - ExpressionWithBlock ";"? => () +pub Stmt: () = { + ";" => (), + "let" Id "=" Expr => (), + "if" Expr Stmts ("else" Stmts)? => (), + ExprNoBlock => (), + Stmts => (), } + pub Num: i32 = { r"[0-9]+" => i32::from_str(<>).unwrap(), };