Parse till operators

rewrite/grammar-implicit-whitespace
Raymon Zutekouw 3 years ago
parent 59d5b1c384
commit 4f59df0cae
  1. 16
      src/grammars/mblf.pest
  2. 48
      src/main.rs

@ -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}

@ -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()?;

Loading…
Cancel
Save