From 4f59df0cae86ec63f65ef1ce66d5c28c5fd82989 Mon Sep 17 00:00:00 2001 From: Raymonzut Date: Wed, 20 Oct 2021 21:21:02 +0200 Subject: [PATCH] Parse till operators --- src/grammars/mblf.pest | 16 +++++++++++++- src/main.rs | 48 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/src/grammars/mblf.pest b/src/grammars/mblf.pest index 0790d1a..cf2ca56 100644 --- a/src/grammars/mblf.pest +++ b/src/grammars/mblf.pest @@ -1 +1,15 @@ -alpha = { 'a'..'z' | 'A'..'Z' } +operator = @{ "operator" } // TODO +operand = @{ "operand" } // TODO + +instruction = { operator ~ (" "+ ~ operand)*} + +loopBlockStart = { "[" } +loopBlockEnd = { "]" } +loopBlock = { loopBlockStart + ~ instruction* + ~ loopBlockEnd +} + +statement = _{ instruction | loopBlock } + +file = {SOI ~ (statement ~ ("\n" | "\r\n")+)* ~ EOI} diff --git a/src/main.rs b/src/main.rs index 849a633..278c17f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ extern crate pest; #[macro_use] extern crate pest_derive; +use pest::iterators::Pair; use pest::Parser; #[derive(Parser)] @@ -23,20 +24,55 @@ struct Cli { output_file: std::path::PathBuf, } +fn instruct(statement: Pair, mut out: &File) { + match statement.as_rule() { + Rule::instruction => { + for nested_statement in statement.into_inner() { + instruct(nested_statement, out); + } + out.write(b"\n"); + } + Rule::operator => { + out.write(b"operator "); + } + Rule::operand => { + out.write(b"operand "); + } + + Rule::loopBlock => { + for nested_statement in statement.into_inner() { + instruct(nested_statement, out); + } + } + Rule::loopBlockStart => { + out.write(b"loopBlockStart\n"); + } + Rule::loopBlockEnd => { + out.write(b"loopBlockEnd\n"); + } + Rule::EOI => { + out.write(b"\n"); + } + _ => unreachable!(), + } +} + fn main() -> Result<(), Box> { let args = Cli::from_args(); let content = std::fs::read_to_string(&args.input_file) .with_context(|| format!("could not read source file {:?}", args.input_file))?; - let mut out = File::create(args.output_file)?; - - let _pairs = MblfParser::parse(Rule::alpha, "a").unwrap(); - - + let out = File::create(args.output_file)?; + let parsed_file = MblfParser::parse(Rule::file, &content) + .expect("Parse Error") + .next() + .unwrap(); - out.write_all(&content.as_bytes())?; + for statement in parsed_file.into_inner() { + instruct(statement, &out); + } out.sync_all()?;