Parse till operators

This commit is contained in:
2021-10-20 21:21:02 +02:00
committed by raymon
parent 3d60b6cb5d
commit c57a9c2849
2 changed files with 57 additions and 7 deletions
+15 -1
View File
@@ -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}
+42 -6
View File
@@ -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<Rule>, 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<dyn std::error::Error>> {
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 out = File::create(args.output_file)?;
let _pairs = MblfParser::parse(Rule::alpha, "a").unwrap();
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()?;