Croissant Runtime
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
crsn/crsn/src/asm/parse/parse_instr.rs

88 lines
3.1 KiB

use sexp::{Sexp, SourcePosition, Atom};
use crate::asm::error::CrsnError;
use crate::asm::instr::{Flatten, InstrWithBranches};
use crate::asm::parse::arg_parser::TokenParser;
use crate::asm::parse::parse_cond::parse_cond_branch;
use crate::asm::parse::parse_routine::parse_routine;
use crate::asm::parse::ParserContext;
use crate::asm::parse::sexp_expect::{expect_list, expect_string_atom};
use crate::asm::patches::NextOrErr;
use crate::module::ParseRes;
use super::parse_op::parse_op;
pub fn parse_instructions(items: impl Iterator<Item=Sexp>, pos: &SourcePosition, pcx: &ParserContext) -> Result<Box<dyn Flatten>, CrsnError> {
let mut parsed = vec![];
for expr in items {
let (tokens, listpos) = expect_list(expr, false)?;
let mut toki = tokens.into_iter();
let (name, namepos) = expect_string_atom(toki.next_or_err(listpos.clone(), "Expected instruction name token")?)?;
if name == "proc" {
parsed.push(parse_routine(toki, pos, pcx)?);
continue;
}
// Let extensions parse custom syntax
let mut token_parser = TokenParser::new(toki.collect(), &listpos, pcx);
for p in pcx.parsers {
token_parser = match p.parse_syntax(pos, &name, token_parser) {
Ok(ParseRes::Parsed(op)) => return Ok(op),
Ok(ParseRes::ParsedNone) => return Ok(Box::new(())),
Ok(ParseRes::Unknown(to_reuse)) => {
if to_reuse.parsing_started() {
panic!("Module \"{}\" started parsing syntax, but returned Unknown!", p.name());
}
to_reuse
}
Err(err) => {
return Err(err);
}
}
}
// Get back the original iterator
let token_count = token_parser.len();
let toki : std::vec::IntoIter<Sexp> = token_parser.into_iter();
let branch_tokens = toki.clone().rev()
.take_while(|e| {
if let Sexp::List(ref items, _) = e {
if items.len() > 1 {
if let Sexp::Atom(Atom::S(ref kw), _) = items[0] {
if kw.ends_with('?') {
return true;
}
}
}
}
false
})
.collect::<Vec<_>>();
let arg_tokens = TokenParser::new(toki.take(token_count - branch_tokens.len()).collect(), &listpos, pcx);
let branches = {
let mut branches = vec![];
for t in branch_tokens {
branches.push(parse_cond_branch(t, pcx)?);
}
if branches.is_empty() {
None
} else {
Some(branches)
}
};
if let Some(op) = parse_op(name.as_str(), arg_tokens, &namepos)? {
parsed.push(Box::new(InstrWithBranches {
op,
pos: namepos,
branches,
}));
}
}
Ok(Box::new(parsed))
}