forked from MightyPork/crsn
remove unnecessary cloning of SourcePosition, reduce SourcePosition size. clean, format
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use std::fmt::{Debug, Formatter, Display};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
use std::fmt;
|
||||
|
||||
use crate::asm::data::{DataDisp, Mask, RdData, Register};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::patches::ErrWithPos;
|
||||
|
||||
/// Register name
|
||||
@@ -25,27 +26,27 @@ impl Display for Register {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_reg(name: &str, at: SourcePosition) -> Result<Register, CrsnError> {
|
||||
pub fn parse_reg(name: &str, at: &SourcePosition) -> Result<Register, CrsnError> {
|
||||
// TODO deduplicate code
|
||||
if let Some(rn) = name.strip_prefix("arg") {
|
||||
if rn.chars().find(|c: &char| !c.is_ascii_digit()).is_some() {
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at))?;
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at.clone()))?;
|
||||
}
|
||||
let val: u8 = rn.parse().err_pos(at)?;
|
||||
Ok(Register::Arg(val))
|
||||
} else if let Some(rn) = name.strip_prefix("res") {
|
||||
if rn.chars().find(|c: &char| !c.is_ascii_digit()).is_some() {
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at))?;
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at.clone()))?;
|
||||
}
|
||||
let val: u8 = rn.parse().err_pos(at)?;
|
||||
Ok(Register::Res(val))
|
||||
} else if let Some(rn) = name.strip_prefix("r") {
|
||||
if rn.chars().find(|c: &char| !c.is_ascii_digit()).is_some() {
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at))?;
|
||||
return Err(CrsnError::Parse(format!("Bad register: {}", name).into(), at.clone()))?;
|
||||
}
|
||||
let val: u8 = rn.parse().err_pos(at)?;
|
||||
Ok(Register::Gen(val))
|
||||
} else {
|
||||
Err(CrsnError::Parse(format!("Bad reg name: {}", name).into(), at))?
|
||||
Err(CrsnError::Parse(format!("Bad reg name: {}", name).into(), at.clone()))?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::fmt::{Debug, Formatter, Display};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
use std::fmt;
|
||||
|
||||
use crate::asm::data::{DataDisp, Mask, Rd, WrData};
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use std::borrow::Cow;
|
||||
use std::num::ParseIntError;
|
||||
use std::error::Error;
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::{Mask, Register};
|
||||
use crate::asm::data::literal::Label;
|
||||
use crate::asm::instr::Cond;
|
||||
use sexp::SourcePosition;
|
||||
use std::error::Error;
|
||||
|
||||
/// csn_asm unified error type
|
||||
#[derive(Error, Debug)]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::ops::Not;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
|
||||
/// Condition flag
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||
pub enum Cond {
|
||||
@@ -46,7 +47,7 @@ pub enum Cond {
|
||||
NotCarry,
|
||||
}
|
||||
|
||||
pub fn parse_cond(text: &str, pos : SourcePosition) -> Result<Cond, CrsnError> {
|
||||
pub fn parse_cond(text: &str, pos: &SourcePosition) -> Result<Cond, CrsnError> {
|
||||
Ok(match text.trim_end_matches('?') {
|
||||
"eq" | "=" | "==" => Cond::Equal,
|
||||
"ne" | "<>" | "!=" | "≠" => Cond::NotEqual,
|
||||
@@ -67,7 +68,7 @@ pub fn parse_cond(text: &str, pos : SourcePosition) -> Result<Cond, CrsnError> {
|
||||
"ov" | "^" => Cond::Overflow,
|
||||
"nov" | "!ov" | "!^" => Cond::NotOverflow,
|
||||
_ => {
|
||||
return Err(CrsnError::Parse(format!("Unknown cond: {}", text).into(), pos));
|
||||
return Err(CrsnError::Parse(format!("Unknown cond: {}", text).into(), pos.clone()));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32};
|
||||
use std::fmt::Debug;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::{Rd, RdData};
|
||||
use crate::asm::data::literal::{Label, Value};
|
||||
@@ -8,11 +11,9 @@ use crate::asm::instr::{Cond, InstrWithBranches, Op, Routine};
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use crate::builtin::defs::Barrier;
|
||||
use crate::builtin::defs::BuiltinOp;
|
||||
use std::fmt::Debug;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
/// A trait for something that can turn into multiple instructions
|
||||
pub trait Flatten : Debug {
|
||||
pub trait Flatten: Debug {
|
||||
fn flatten(self: Box<Self>, label_num: &AtomicU32) -> Result<Vec<Op>, CrsnError>;
|
||||
|
||||
fn pos(&self) -> SourcePosition;
|
||||
@@ -154,7 +155,7 @@ pub fn labels_to_skips(ops: Vec<Op>) -> Result<Vec<Op>, CrsnError> {
|
||||
let skip = *dest as isize - n as isize + skipped;
|
||||
cleaned.push(Op {
|
||||
cond: op.cond,
|
||||
pos : op.pos.clone(),
|
||||
pos: op.pos.clone(),
|
||||
kind: OpKind::BuiltIn(BuiltinOp::Skip(Rd::new(RdData::Immediate(skip as Value)))),
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
pub use cond::Cond;
|
||||
pub use flatten::Flatten;
|
||||
pub use op::Op;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::literal::RoutineName;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
pub mod op;
|
||||
pub mod cond;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use std::fmt::Debug;
|
||||
|
||||
use sexp::{Atom, Sexp, SourcePosition};
|
||||
|
||||
use crate::asm::instr::Cond;
|
||||
use crate::builtin::defs::BuiltinOp;
|
||||
use crate::module::{EvalRes, OpTrait};
|
||||
use crate::runtime::fault::Fault;
|
||||
use crate::runtime::run_thread::{info::ThreadInfo, state::RunState};
|
||||
use sexp::{Sexp, Atom, SourcePosition};
|
||||
|
||||
/// A higher level simple opration
|
||||
#[derive(Debug)]
|
||||
@@ -18,7 +19,7 @@ pub enum OpKind {
|
||||
#[derive(Debug)]
|
||||
pub struct Op {
|
||||
pub cond: Option<Cond>,
|
||||
pub pos : SourcePosition,
|
||||
pub pos: SourcePosition,
|
||||
pub kind: OpKind,
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -1,11 +1,12 @@
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::instr::flatten::labels_to_skips;
|
||||
use crate::asm::parse::{ParserContext, ParserState};
|
||||
use crate::module::CrsnExtension;
|
||||
use crate::runtime::program::Program;
|
||||
use crate::asm::instr::flatten::labels_to_skips;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
pub mod data;
|
||||
pub mod error;
|
||||
@@ -24,7 +25,7 @@ pub fn assemble(source: &str, parsers: Arc<Vec<Box<dyn CrsnExtension>>>) -> Resu
|
||||
}),
|
||||
};
|
||||
|
||||
let ops = parse::parse(source, SourcePosition::default(), &pcx)?;
|
||||
let ops = parse::parse(source, &SourcePosition::default(), &pcx)?;
|
||||
let ops = labels_to_skips(ops)?;
|
||||
|
||||
Ok(Program::new(ops, parsers)?)
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::asm::patches::NextOrErr;
|
||||
pub struct TokenParser<'a> {
|
||||
orig_len: usize,
|
||||
args: Vec<Sexp>,
|
||||
start_pos: SourcePosition,
|
||||
start_pos: &'a SourcePosition,
|
||||
pub pcx: &'a ParserContext<'a>,
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ impl<'a> IntoIterator for TokenParser<'a> {
|
||||
|
||||
impl<'a> TokenParser<'a> {
|
||||
/// Create a new argument parser
|
||||
pub fn new(mut args: Vec<Sexp>, start_pos: SourcePosition, pcx: &'a ParserContext) -> Self {
|
||||
pub fn new(mut args: Vec<Sexp>, start_pos: &'a SourcePosition, pcx: &'a ParserContext) -> Self {
|
||||
args.reverse();
|
||||
Self {
|
||||
orig_len: args.len(),
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::collections::HashMap;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
pub use parse_instr::parse_instructions;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::literal::{ConstantName, RegisterAlias, Value};
|
||||
use crate::asm::data::Register;
|
||||
@@ -10,7 +11,6 @@ use crate::asm::error::CrsnError;
|
||||
use crate::asm::instr::Op;
|
||||
use crate::asm::parse::sexp_expect::expect_list;
|
||||
use crate::module::CrsnExtension;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
pub mod parse_cond;
|
||||
pub mod parse_instr;
|
||||
@@ -39,7 +39,7 @@ pub struct ParserState {
|
||||
pub constants: HashMap<ConstantName, Value>,
|
||||
}
|
||||
|
||||
pub fn parse(source: &str, pos: SourcePosition, parsers: &ParserContext) -> Result<Vec<Op>, CrsnError> {
|
||||
pub fn parse(source: &str, pos: &SourcePosition, parsers: &ParserContext) -> Result<Vec<Op>, CrsnError> {
|
||||
let (items, _pos) = expect_list(sexp::parse(source)?, true)?;
|
||||
|
||||
/* numbered labels start with a weird high number
|
||||
|
||||
@@ -9,12 +9,12 @@ use crate::asm::patches::TryRemove;
|
||||
|
||||
pub fn parse_cond_branch(tok: Sexp, parsers: &ParserContext) -> Result<(Cond, Box<dyn Flatten>), CrsnError> {
|
||||
let (mut list, pos) = expect_list(tok, false)?;
|
||||
let (kw, kw_pos) = expect_string_atom(list.remove_or_err(0, pos.clone(), "Missing \"cond?\" keyword in conditional branch")?)?;
|
||||
let (kw, kw_pos) = expect_string_atom(list.remove_or_err(0, &pos, "Missing \"cond?\" keyword in conditional branch")?)?;
|
||||
|
||||
if !kw.ends_with('?') {
|
||||
return Err(CrsnError::Parse(format!("Condition must end with '?': {}", kw).into(), kw_pos));
|
||||
}
|
||||
|
||||
Ok((cond::parse_cond(&kw, kw_pos)?, parse_instructions(list.into_iter(), pos, parsers)?))
|
||||
Ok((cond::parse_cond(&kw, &kw_pos)?, parse_instructions(list.into_iter(), &pos, parsers)?))
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ use crate::asm::data::literal::{ConstantName, Label, RegisterAlias, Value};
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::parse::ParserContext;
|
||||
use crate::asm::parse::sexp_expect::expect_string_atom;
|
||||
use std::num::TryFromIntError;
|
||||
use crate::asm::patches::ErrWithPos;
|
||||
|
||||
fn is_valid_identifier(name: &str) -> bool {
|
||||
@@ -46,14 +45,14 @@ pub fn parse_constant_name(name: Sexp) -> Result<(ConstantName, SourcePosition),
|
||||
pub fn parse_label(name: Sexp) -> Result<Label, CrsnError> {
|
||||
// trace!("parse label: {:?}", name);
|
||||
let (name, namepos) = expect_string_atom(name)?;
|
||||
Ok(parse_label_str(&name, namepos)?)
|
||||
Ok(parse_label_str(&name, &namepos)?)
|
||||
}
|
||||
|
||||
pub fn parse_label_str(name: &str, pos: SourcePosition) -> Result<Label, CrsnError> {
|
||||
pub fn parse_label_str(name: &str, pos: &SourcePosition) -> Result<Label, CrsnError> {
|
||||
let label = name.trim_start_matches(':');
|
||||
|
||||
Ok(if label.starts_with('#') {
|
||||
let val = parse_u64(&label[1..], pos.clone())?;
|
||||
let val = parse_u64(&label[1..], pos)?;
|
||||
Label::Numbered(u32::try_from(val).err_pos(pos)?)
|
||||
} else {
|
||||
Label::Named(label.to_string())
|
||||
@@ -67,7 +66,7 @@ pub fn parse_data_disp(tok: Sexp, pcx: &ParserContext) -> Result<DataDisp, CrsnE
|
||||
// TODO implement masks
|
||||
|
||||
match tok {
|
||||
Sexp::Atom(Atom::I(val), pos) => {
|
||||
Sexp::Atom(Atom::I(val), _pos) => {
|
||||
Ok(DataDisp::Immediate(unsafe { std::mem::transmute(val) }))
|
||||
}
|
||||
Sexp::Atom(Atom::S(s), pos) => {
|
||||
@@ -92,7 +91,7 @@ pub fn parse_data_disp(tok: Sexp, pcx: &ParserContext) -> Result<DataDisp, CrsnE
|
||||
if let Some(val) = pstate.reg_aliases.get(reference) {
|
||||
Ok(DataDisp::ObjectPtr(*val))
|
||||
} else {
|
||||
let reg = reg::parse_reg(reference, pos.clone())?;
|
||||
let reg = reg::parse_reg(reference, &pos)?;
|
||||
|
||||
if pstate.reg_aliases.values().find(|v| **v == reg).is_some() {
|
||||
Err(CrsnError::Parse(format!("Sym exists for register {}, direct access denied. Unsym it if needed.", reg).into(), pos))
|
||||
@@ -101,9 +100,9 @@ pub fn parse_data_disp(tok: Sexp, pcx: &ParserContext) -> Result<DataDisp, CrsnE
|
||||
}
|
||||
}
|
||||
} else if s.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
Ok(DataDisp::Immediate(unsafe { std::mem::transmute(parse_i64(&s, pos)?) }))
|
||||
Ok(DataDisp::Immediate(unsafe { std::mem::transmute(parse_i64(&s, &pos)?) }))
|
||||
} else {
|
||||
let reg = reg::parse_reg(&s, pos.clone())?;
|
||||
let reg = reg::parse_reg(&s, &pos)?;
|
||||
|
||||
let pstate = pcx.state.borrow();
|
||||
if pstate.reg_aliases.values().find(|v| **v == reg).is_some() {
|
||||
@@ -122,7 +121,7 @@ pub fn parse_data_disp(tok: Sexp, pcx: &ParserContext) -> Result<DataDisp, CrsnE
|
||||
/// Parse immediate value
|
||||
pub fn parse_value(tok: Sexp, pcx: &ParserContext) -> Result<Value, CrsnError> {
|
||||
match tok {
|
||||
Sexp::Atom(Atom::I(val), pos) => {
|
||||
Sexp::Atom(Atom::I(val), _pos) => {
|
||||
Ok(unsafe { std::mem::transmute(val) })
|
||||
}
|
||||
Sexp::Atom(Atom::S(s), pos) => {
|
||||
@@ -131,7 +130,7 @@ pub fn parse_value(tok: Sexp, pcx: &ParserContext) -> Result<Value, CrsnError> {
|
||||
return Ok(*val);
|
||||
}
|
||||
|
||||
Ok(unsafe { std::mem::transmute(parse_i64(&s, pos)?) })
|
||||
Ok(unsafe { std::mem::transmute(parse_i64(&s, &pos)?) })
|
||||
}
|
||||
other => {
|
||||
Err(CrsnError::Parse(format!("bad value format: {:?}", other).into(), other.pos().clone()))
|
||||
@@ -140,7 +139,7 @@ pub fn parse_value(tok: Sexp, pcx: &ParserContext) -> Result<Value, CrsnError> {
|
||||
}
|
||||
|
||||
|
||||
pub fn parse_u64(literal: &str, pos: SourcePosition) -> Result<u64, CrsnError> {
|
||||
pub fn parse_u64(literal: &str, pos: &SourcePosition) -> Result<u64, CrsnError> {
|
||||
// trace!("parse u64 from {}", literal);
|
||||
let mut without_underscores = Cow::Borrowed(literal);
|
||||
if without_underscores.contains('_') {
|
||||
@@ -156,21 +155,21 @@ pub fn parse_u64(literal: &str, pos: SourcePosition) -> Result<u64, CrsnError> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_i64(literal: &str, pos: SourcePosition) -> Result<i64, CrsnError> {
|
||||
pub fn parse_i64(literal: &str, pos: &SourcePosition) -> Result<i64, CrsnError> {
|
||||
// trace!("parse i64 from {}", literal);
|
||||
if let Some(_value) = literal.strip_prefix("-") {
|
||||
Ok(-1 * i64::try_from(parse_u64(literal, pos.clone())?).err_pos(pos)?)
|
||||
Ok(-1 * i64::try_from(parse_u64(literal, pos)?).err_pos(pos)?)
|
||||
} else {
|
||||
Ok(i64::try_from(parse_u64(literal, pos.clone())?).err_pos(pos)?)
|
||||
Ok(i64::try_from(parse_u64(literal, pos)?).err_pos(pos)?)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_rd(tok: Sexp, pcx: &ParserContext) -> Result<Rd, CrsnError> {
|
||||
let pos = tok.pos().clone();
|
||||
Ok(Rd::new(RdData::try_from(parse_data_disp(tok, pcx)?).err_pos(pos)?))
|
||||
Ok(Rd::new(RdData::try_from(parse_data_disp(tok, pcx)?).err_pos(&pos)?))
|
||||
}
|
||||
|
||||
pub fn parse_wr(tok: Sexp, pcx: &ParserContext) -> Result<Wr, CrsnError> {
|
||||
let pos = tok.pos().clone();
|
||||
Ok(Wr::new(WrData::try_from(parse_data_disp(tok, pcx)?).err_pos(pos)?))
|
||||
Ok(Wr::new(WrData::try_from(parse_data_disp(tok, pcx)?).err_pos(&pos)?))
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ 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;
|
||||
use crate::asm::patches::NextOrErr;
|
||||
|
||||
pub fn parse_instructions(items: impl Iterator<Item=Sexp>, pos: SourcePosition, pcx: &ParserContext) -> Result<Box<dyn Flatten>, CrsnError> {
|
||||
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)?;
|
||||
@@ -21,13 +21,13 @@ pub fn parse_instructions(items: impl Iterator<Item=Sexp>, pos: SourcePosition,
|
||||
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.clone(), pcx)?);
|
||||
parsed.push(parse_routine(toki, pos, pcx)?);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut token_parser = TokenParser::new(toki.collect(), listpos.clone(), pcx);
|
||||
let mut token_parser = TokenParser::new(toki.collect(), &listpos, pcx);
|
||||
for p in pcx.parsers {
|
||||
token_parser = match p.parse_syntax(pos.clone(), &name, token_parser) {
|
||||
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)) => {
|
||||
@@ -45,7 +45,7 @@ pub fn parse_instructions(items: impl Iterator<Item=Sexp>, pos: SourcePosition,
|
||||
// Get back the original iterator
|
||||
let toki = token_parser.into_iter();
|
||||
|
||||
let arg_tokens = TokenParser::new(toki.clone().take_while(|e| e.is_atom()).collect(), listpos.clone(), pcx);
|
||||
let arg_tokens = TokenParser::new(toki.clone().take_while(|e| e.is_atom()).collect(), &listpos, pcx);
|
||||
let branch_tokens = toki
|
||||
.skip_while(|e| e.is_atom())
|
||||
.take_while(|e| e.is_list());
|
||||
@@ -62,7 +62,7 @@ pub fn parse_instructions(items: impl Iterator<Item=Sexp>, pos: SourcePosition,
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(op) = parse_op(name.as_str(), arg_tokens, namepos.clone())? {
|
||||
if let Some(op) = parse_op(name.as_str(), arg_tokens, &namepos)? {
|
||||
parsed.push(Box::new(InstrWithBranches {
|
||||
op,
|
||||
pos: namepos,
|
||||
|
||||
@@ -1,32 +1,33 @@
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::instr::cond::parse_cond;
|
||||
use crate::asm::instr::Op;
|
||||
use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::module::ParseRes;
|
||||
use crate::builtin::BuiltinOps;
|
||||
use sexp::SourcePosition;
|
||||
use crate::module::ParseRes;
|
||||
|
||||
pub fn parse_op<'a>(mut keyword: &str, mut arg_tokens: TokenParser<'a>, spos: SourcePosition) -> Result<Option<Op>, CrsnError> {
|
||||
pub fn parse_op<'a>(mut keyword: &str, mut arg_tokens: TokenParser<'a>, spos: &SourcePosition) -> Result<Option<Op>, CrsnError> {
|
||||
// Include built-in instructions
|
||||
let builtins = [BuiltinOps::new()];
|
||||
let mut cond = None;
|
||||
|
||||
if let Some(pos) = keyword.find('.') {
|
||||
cond = Some(parse_cond(&keyword[(pos + 1)..], spos.clone())?);
|
||||
cond = Some(parse_cond(&keyword[(pos + 1)..], spos)?);
|
||||
keyword = &keyword[..pos];
|
||||
}
|
||||
|
||||
for p in builtins.iter().chain(arg_tokens.pcx.parsers) {
|
||||
arg_tokens = match p.parse_op(spos.clone(), keyword, arg_tokens) {
|
||||
arg_tokens = match p.parse_op(spos, keyword, arg_tokens) {
|
||||
Ok(ParseRes::Parsed(kind)) => return Ok(Some(Op {
|
||||
cond,
|
||||
pos: spos,
|
||||
pos: spos.clone(),
|
||||
kind,
|
||||
})),
|
||||
Ok(ParseRes::ParsedNone) => return Ok(None),
|
||||
Ok(ParseRes::Unknown(to_reuse)) => {
|
||||
if to_reuse.parsing_started() {
|
||||
return Err(CrsnError::Parse(format!("Module \"{}\" started parsing {}, but returned Unknown!", p.name(), keyword).into(), spos));
|
||||
return Err(CrsnError::Parse(format!("Module \"{}\" started parsing {}, but returned Unknown!", p.name(), keyword).into(), spos.clone()));
|
||||
}
|
||||
to_reuse
|
||||
}
|
||||
@@ -36,5 +37,5 @@ pub fn parse_op<'a>(mut keyword: &str, mut arg_tokens: TokenParser<'a>, spos: So
|
||||
}
|
||||
}
|
||||
|
||||
return Err(CrsnError::Parse(format!("Unknown instruction: {}", keyword).into(), spos));
|
||||
return Err(CrsnError::Parse(format!("Unknown instruction: {}", keyword).into(), spos.clone()));
|
||||
}
|
||||
|
||||
@@ -7,14 +7,14 @@ use crate::asm::parse::{parse_instructions, ParserContext};
|
||||
use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::asm::parse::parse_data::parse_reg_alias;
|
||||
use crate::asm::parse::sexp_expect::expect_string_atom;
|
||||
use crate::builtin::parse::parse_routine_name;
|
||||
use crate::asm::patches::NextOrErr;
|
||||
use crate::builtin::parse::parse_routine_name;
|
||||
|
||||
pub fn parse_routine(mut toki: impl Iterator<Item=Sexp> + Clone, rt_pos: SourcePosition, pcx: &ParserContext) -> Result<Box<dyn Flatten>, CrsnError> {
|
||||
pub fn parse_routine(mut toki: impl Iterator<Item=Sexp> + Clone, rt_pos: &SourcePosition, pcx: &ParserContext) -> Result<Box<dyn Flatten>, CrsnError> {
|
||||
let (name, namepos) = expect_string_atom(toki.next_or_err(rt_pos.clone(), "Expected routine name")?)?;
|
||||
let mut name = parse_routine_name(name, namepos)?;
|
||||
let mut name = parse_routine_name(name, &namepos)?;
|
||||
|
||||
let arg_tokens = TokenParser::new(toki.clone().take_while(|e| e.is_atom()).collect(), rt_pos.clone(), pcx);
|
||||
let arg_tokens = TokenParser::new(toki.clone().take_while(|e| e.is_atom()).collect(), rt_pos, pcx);
|
||||
|
||||
// If arity is explicitly given, then either no named argument must be provided,
|
||||
// or their count must match the arity. If no arity is given, then arity is determined
|
||||
@@ -22,7 +22,7 @@ pub fn parse_routine(mut toki: impl Iterator<Item=Sexp> + Clone, rt_pos: SourceP
|
||||
if name.arity == 0 && arg_tokens.len() != 0 {
|
||||
name.arity = arg_tokens.len() as u8;
|
||||
} else if arg_tokens.len() != 0 && name.arity as usize != arg_tokens.len() {
|
||||
return Err(CrsnError::Parse(format!("arity mismatch in routine {}", name.name).into(), rt_pos));
|
||||
return Err(CrsnError::Parse(format!("arity mismatch in routine {}", name.name).into(), rt_pos.clone()));
|
||||
}
|
||||
|
||||
let toki = toki.skip_while(|e| e.is_atom());
|
||||
@@ -44,7 +44,7 @@ pub fn parse_routine(mut toki: impl Iterator<Item=Sexp> + Clone, rt_pos: SourceP
|
||||
}
|
||||
}
|
||||
|
||||
let body = parse_instructions(toki, rt_pos.clone(), pcx)?;
|
||||
let body = parse_instructions(toki, rt_pos, pcx)?;
|
||||
|
||||
{
|
||||
let mut pstate = pcx.state.borrow_mut();
|
||||
@@ -54,7 +54,7 @@ pub fn parse_routine(mut toki: impl Iterator<Item=Sexp> + Clone, rt_pos: SourceP
|
||||
|
||||
return Ok(Box::new(Routine {
|
||||
name,
|
||||
pos: rt_pos,
|
||||
pos: rt_pos.clone(),
|
||||
body,
|
||||
}));
|
||||
}
|
||||
|
||||
+10
-10
@@ -1,12 +1,12 @@
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub trait TryRemove {
|
||||
type Item;
|
||||
fn try_remove(&mut self, index: usize) -> Option<Self::Item>;
|
||||
|
||||
fn remove_or_err(&mut self, index: usize, pos: SourcePosition, err : &'static str) -> Result<Self::Item, CrsnError>;
|
||||
fn remove_or_err(&mut self, index: usize, pos: &SourcePosition, err: &'static str) -> Result<Self::Item, CrsnError>;
|
||||
}
|
||||
|
||||
impl<T> TryRemove for Vec<T> {
|
||||
@@ -20,10 +20,10 @@ impl<T> TryRemove for Vec<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_or_err(&mut self, index: usize, pos: SourcePosition, err : &'static str) -> Result<Self::Item, CrsnError> {
|
||||
fn remove_or_err(&mut self, index: usize, pos: &SourcePosition, err: &'static str) -> Result<Self::Item, CrsnError> {
|
||||
match self.try_remove(index) {
|
||||
None => {
|
||||
Err(CrsnError::Parse(err.into(), pos))
|
||||
Err(CrsnError::Parse(err.into(), pos.clone()))
|
||||
}
|
||||
Some(removed) => Ok(removed)
|
||||
}
|
||||
@@ -31,10 +31,10 @@ impl<T> TryRemove for Vec<T> {
|
||||
}
|
||||
|
||||
pub trait NextOrErr<T> {
|
||||
fn next_or_err(&mut self, pos: SourcePosition, err : &'static str) -> Result<T, CrsnError>;
|
||||
fn next_or_err(&mut self, pos: SourcePosition, err: &'static str) -> Result<T, CrsnError>;
|
||||
}
|
||||
|
||||
impl<T, K : Iterator<Item=T>> NextOrErr<T> for K {
|
||||
impl<T, K: Iterator<Item=T>> NextOrErr<T> for K {
|
||||
fn next_or_err(&mut self, pos: SourcePosition, err: &'static str) -> Result<T, CrsnError> {
|
||||
match self.next() {
|
||||
None => {
|
||||
@@ -46,14 +46,14 @@ impl<T, K : Iterator<Item=T>> NextOrErr<T> for K {
|
||||
}
|
||||
|
||||
pub trait ErrWithPos<T> {
|
||||
fn err_pos(self, pos : SourcePosition) -> Result<T, CrsnError>;
|
||||
fn err_pos(self, pos: &SourcePosition) -> Result<T, CrsnError>;
|
||||
}
|
||||
|
||||
impl<T, E : std::error::Error + Send + Sync + 'static> ErrWithPos<T> for Result<T, E> {
|
||||
fn err_pos(self, pos : SourcePosition) -> Result<T, CrsnError> {
|
||||
impl<T, E: std::error::Error + Send + Sync + 'static> ErrWithPos<T> for Result<T, E> {
|
||||
fn err_pos(self, pos: &SourcePosition) -> Result<T, CrsnError> {
|
||||
match self {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => Err(CrsnError::ParseOther(Box::new(e), pos))
|
||||
Err(e) => Err(CrsnError::ParseOther(Box::new(e), pos.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::{Rd, RdObj, Wr};
|
||||
use crate::asm::data::literal::{DebugMsg, Label, RoutineName};
|
||||
use crate::asm::instr::Op;
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Barrier {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use sexp::Sexp;
|
||||
|
||||
use crate::asm::data::{Rd, RdData};
|
||||
use crate::asm::data::literal::Addr;
|
||||
use crate::asm::instr::Cond;
|
||||
@@ -8,11 +10,6 @@ use crate::module::{EvalRes, OpTrait};
|
||||
use crate::runtime::fault::Fault;
|
||||
use crate::runtime::frame::StackFrame;
|
||||
use crate::runtime::run_thread::{state::RunState, ThreadInfo};
|
||||
use sexp::Sexp;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
impl OpTrait for BuiltinOp {
|
||||
fn execute(&self, info: &ThreadInfo, state: &mut RunState) -> Result<EvalRes, Fault> {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use crate::module::{CrsnExtension, ParseRes};
|
||||
use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use crate::asm::error::CrsnError;
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::module::{CrsnExtension, ParseRes};
|
||||
|
||||
pub mod defs;
|
||||
pub mod exec;
|
||||
pub mod parse;
|
||||
@@ -22,7 +23,7 @@ impl CrsnExtension for BuiltinOps {
|
||||
"builtin"
|
||||
}
|
||||
|
||||
fn parse_op<'a>(&self, pos: SourcePosition, keyword: &str, args: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError> {
|
||||
fn parse_op<'a>(&self, pos: &SourcePosition, keyword: &str, args: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError> {
|
||||
parse::parse_op(pos, keyword, args)
|
||||
}
|
||||
}
|
||||
|
||||
+26
-24
@@ -5,15 +5,14 @@ use crate::asm::data::reg::parse_reg;
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::asm::parse::parse_data::{parse_constant_name, parse_label, parse_rd, parse_reg_alias, parse_value, parse_label_str};
|
||||
use crate::asm::parse::parse_data::{parse_constant_name, parse_label, parse_label_str, parse_rd, parse_reg_alias, parse_value};
|
||||
use crate::asm::parse::sexp_expect::expect_string_atom;
|
||||
use crate::builtin::defs::{Barrier, BuiltinOp};
|
||||
use crate::module::{ParseRes};
|
||||
use crate::utils::A;
|
||||
use crate::asm::patches::ErrWithPos;
|
||||
use crate::builtin::defs::{Barrier, BuiltinOp};
|
||||
use crate::module::ParseRes;
|
||||
use crate::utils::A;
|
||||
|
||||
|
||||
pub(crate) fn parse_op<'a>(op_pos: SourcePosition, keyword: &str, mut args: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError> {
|
||||
pub(crate) fn parse_op<'a>(op_pos: &SourcePosition, keyword: &str, mut args: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError> {
|
||||
let pcx = args.pcx;
|
||||
|
||||
Ok(ParseRes::Parsed(OpKind::BuiltIn(match keyword {
|
||||
@@ -35,7 +34,7 @@ pub(crate) fn parse_op<'a>(op_pos: SourcePosition, keyword: &str, mut args: Toke
|
||||
let (alias, aliaspos) = parse_reg_alias(args.next_or_err()?)?;
|
||||
trace!("alias={:?}", alias);
|
||||
let (rn, rpos) = args.next_string()?;
|
||||
let register = parse_reg(&rn, rpos.clone())?;
|
||||
let register = parse_reg(&rn, &rpos)?;
|
||||
trace!("register={:?}", alias);
|
||||
|
||||
let mut pstate = pcx.state.borrow_mut();
|
||||
@@ -124,7 +123,7 @@ pub(crate) fn parse_op<'a>(op_pos: SourcePosition, keyword: &str, mut args: Toke
|
||||
|
||||
"routine" => {
|
||||
let name = args.next_string()?;
|
||||
BuiltinOp::Routine(parse_routine_name(name.0, name.1)?)
|
||||
BuiltinOp::Routine(parse_routine_name(name.0, &name.1)?)
|
||||
}
|
||||
|
||||
"skip" => {
|
||||
@@ -200,7 +199,7 @@ pub(crate) fn parse_op<'a>(op_pos: SourcePosition, keyword: &str, mut args: Toke
|
||||
|
||||
other => {
|
||||
if let Some(label) = other.strip_prefix(':') {
|
||||
BuiltinOp::Label(parse_label_str(label, op_pos)?)
|
||||
BuiltinOp::Label(parse_label_str(label, &op_pos)?)
|
||||
} else {
|
||||
return Ok(ParseRes::Unknown(args));
|
||||
}
|
||||
@@ -208,7 +207,7 @@ pub(crate) fn parse_op<'a>(op_pos: SourcePosition, keyword: &str, mut args: Toke
|
||||
})))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_routine_name(name: String, pos: SourcePosition) -> Result<RoutineName, CrsnError> {
|
||||
pub(crate) fn parse_routine_name(name: String, pos: &SourcePosition) -> Result<RoutineName, CrsnError> {
|
||||
let (name, arity) = if let Some(n) = name.find('/') {
|
||||
(
|
||||
(&name[0..n]).to_string(),
|
||||
@@ -238,7 +237,7 @@ pub(crate) fn to_sexp(op: &BuiltinOp) -> Sexp {
|
||||
inner.extend(args.iter().map(A));
|
||||
sexp::list(&inner)
|
||||
}
|
||||
},
|
||||
}
|
||||
BuiltinOp::Ret(values) => {
|
||||
if values.is_empty() {
|
||||
sexp::list(&[A("ret")])
|
||||
@@ -287,16 +286,15 @@ pub(crate) fn to_sexp(op: &BuiltinOp) -> Sexp {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
use crate::asm::instr::{Flatten};
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::instr::Flatten;
|
||||
use crate::asm::parse::{parse_instructions, ParserContext};
|
||||
use crate::asm::parse::sexp_expect::expect_list;
|
||||
|
||||
use crate::module::OpTrait;
|
||||
use crate::builtin::BuiltinOps;
|
||||
use crate::module::OpTrait;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
@@ -306,10 +304,10 @@ mod test {
|
||||
("(nop)", "(nop)"),
|
||||
("(halt)", "(halt)"),
|
||||
("(sleep 1000)", "(sleep 1000)"),
|
||||
("(:x)\
|
||||
(j :x)", "(skip 0)"),
|
||||
("(:#7)\
|
||||
(j :#7)", "(skip 0)"),
|
||||
("(:x)", "(:x)"),
|
||||
("(j :x)", "(j :x)"),
|
||||
("(:#7)", "(:#7)"),
|
||||
("(j :#7)", "(j :#7)"),
|
||||
("(fj :x)", "(fj :x)"),
|
||||
("(skip 0)", "(skip 0)"),
|
||||
("(skip r0)", "(skip r0)"),
|
||||
@@ -367,9 +365,9 @@ mod test {
|
||||
/* first cycle */
|
||||
let s = sexp::parse(&format!("({})", sample))
|
||||
.expect("parse sexp");
|
||||
let list = expect_list(Some(s), false).unwrap();
|
||||
let list = expect_list(s, false).unwrap();
|
||||
let num = AtomicU32::new(0);
|
||||
let parsed = parse_instructions(list.into_iter(), &pcx)
|
||||
let parsed = parse_instructions(list.0.into_iter(), &SourcePosition::default(), &pcx)
|
||||
.expect("parse instr").flatten(&num)
|
||||
.expect("flatten").remove(0);
|
||||
|
||||
@@ -379,13 +377,17 @@ mod test {
|
||||
assert_eq!(expected, exported);
|
||||
|
||||
println!(" - 2nd cycle");
|
||||
let pcx = ParserContext {
|
||||
parsers,
|
||||
state: Default::default(),
|
||||
};
|
||||
|
||||
/* second cycle, nothing should change */
|
||||
let s = sexp::parse(&format!("({})", exported))
|
||||
.expect("parse sexp (2c)");
|
||||
let list = expect_list(Some(s), false).unwrap();
|
||||
let list = expect_list(s, false).unwrap();
|
||||
let num = AtomicU32::new(0);
|
||||
let parsed = parse_instructions(list.into_iter(), &pcx)
|
||||
let parsed = parse_instructions(list.0.into_iter(), &SourcePosition::default(), &pcx)
|
||||
.expect("parse instr (2c)").flatten(&num)
|
||||
.expect("flatten (2c)").remove(0);
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
#![allow(unused_variables)]
|
||||
|
||||
use std::fmt::{Debug};
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub use eval_res::EvalRes;
|
||||
use sexp::{Sexp, SourcePosition};
|
||||
|
||||
use crate::asm::data::literal::Value;
|
||||
use crate::asm::data::Mask;
|
||||
@@ -13,8 +14,6 @@ use crate::asm::parse::arg_parser::TokenParser;
|
||||
use crate::runtime::fault::Fault;
|
||||
use crate::runtime::run_thread::state::RunState;
|
||||
use crate::runtime::run_thread::ThreadInfo;
|
||||
use sexp::{Sexp, SourcePosition};
|
||||
|
||||
|
||||
mod eval_res;
|
||||
|
||||
@@ -53,12 +52,12 @@ pub trait CrsnExtension: Debug + Send + Sync + 'static {
|
||||
/// If the instruction keyword is not recognized, return Unknown with the unchanged argument list.
|
||||
///
|
||||
/// pcx is available on the arg_tokens parser
|
||||
fn parse_op<'a>(&self, pos: SourcePosition, keyword: &str, arg_tokens: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError>;
|
||||
fn parse_op<'a>(&self, pos: &SourcePosition, keyword: &str, arg_tokens: TokenParser<'a>) -> Result<ParseRes<'a, OpKind>, CrsnError>;
|
||||
|
||||
/// Parse a generic S-expression (non-op)
|
||||
///
|
||||
/// pcx is available on the arg_tokens parser
|
||||
fn parse_syntax<'a>(&self, pos: SourcePosition, keyword: &str, tokens: TokenParser<'a>)
|
||||
fn parse_syntax<'a>(&self, pos: &SourcePosition, keyword: &str, tokens: TokenParser<'a>)
|
||||
-> Result<ParseRes<'a, Box<dyn Flatten>>, CrsnError>
|
||||
{
|
||||
Ok(ParseRes::Unknown(tokens))
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use sexp::SourcePosition;
|
||||
|
||||
use crate::asm::data::literal::{Addr, Label, RoutineName};
|
||||
use crate::asm::error::CrsnError;
|
||||
use crate::asm::instr::Op;
|
||||
use crate::asm::instr::op::OpKind;
|
||||
use crate::builtin::defs::{Barrier, BuiltinOp};
|
||||
use crate::module::CrsnExtension;
|
||||
use crate::runtime::fault::Fault;
|
||||
use sexp::SourcePosition;
|
||||
use crate::asm::error::CrsnError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Program {
|
||||
@@ -96,9 +97,9 @@ impl Program {
|
||||
pos: SourcePosition {
|
||||
line: 0,
|
||||
column: 0,
|
||||
index: 0
|
||||
index: 0,
|
||||
},
|
||||
cond: None
|
||||
cond: None,
|
||||
}
|
||||
} else {
|
||||
&self.ops[addr.0 as usize]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
pub use option_ext::UncheckedOptionExt;
|
||||
use std::fmt::Display;
|
||||
use sexp::{Sexp, Atom};
|
||||
use std::str::FromStr;
|
||||
|
||||
pub use option_ext::UncheckedOptionExt;
|
||||
use sexp::{Atom, Sexp};
|
||||
|
||||
mod option_ext;
|
||||
|
||||
/// Convert a string token to Sexp
|
||||
|
||||
Reference in New Issue
Block a user