futilehdl/src/frontend.rs

337 lines
10 KiB
Rust
Raw Normal View History

2022-01-05 01:08:25 +00:00
use std::collections::BTreeMap;
2022-01-05 01:09:08 +00:00
use crate::builtin_cells::get_builtins;
2022-01-04 22:05:25 +00:00
use crate::parser;
2022-02-04 23:58:47 +00:00
use crate::parser::expression::Expression;
2022-01-04 22:05:25 +00:00
use crate::rtlil;
2022-01-16 18:11:56 +00:00
use crate::rtlil::RtlilWrite;
pub use callable::Callable;
pub use types::{Type, TypeStruct};
mod callable;
2022-01-30 22:54:19 +00:00
pub mod typed_ir;
2022-02-01 18:46:06 +00:00
pub mod types;
2022-01-04 22:05:25 +00:00
/// lots of code is still not width-aware, this constant keeps track of that
const TODO_WIDTH: u32 = 1;
2022-01-04 22:05:25 +00:00
fn make_pubid(id: &str) -> String {
"\\".to_owned() + id
}
#[derive(Debug)]
pub enum CompileErrorKind {
2022-01-05 01:09:08 +00:00
UndefinedReference(String),
2022-01-14 14:32:00 +00:00
BadArgCount { received: usize, expected: usize },
}
#[derive(Debug)]
pub struct CompileError {
kind: CompileErrorKind,
}
impl CompileError {
fn new(kind: CompileErrorKind) -> Self {
2022-01-05 01:09:08 +00:00
Self { kind }
}
}
2022-01-17 20:02:11 +00:00
/// A user-defined signal
pub struct Signal<'ctx> {
2022-01-17 20:02:11 +00:00
/// the user-visible name of the signal
pub name: String,
/// the id of the signal in RTLIL
2022-01-17 20:04:22 +00:00
pub il_id: String,
2022-01-17 20:02:11 +00:00
/// the type of the signal
pub typ: Type<'ctx>,
2022-01-17 20:02:11 +00:00
// unique ID of the signal
// pub uid: u64,
}
impl<'ctx> Signal<'ctx> {
2022-01-17 20:04:22 +00:00
fn sigspec(&self) -> rtlil::SigSpec {
rtlil::SigSpec::Wire(self.il_id.to_owned())
}
}
2022-01-17 23:11:37 +00:00
/// context used when generating processes
struct ProcContext {
updates: Vec<(rtlil::SigSpec, rtlil::SigSpec)>,
next_sigs: BTreeMap<String, rtlil::SigSpec>,
}
struct Context<'ctx> {
2022-01-17 20:02:11 +00:00
/// map callable name to callable
callables: BTreeMap<String, Callable<'ctx>>,
/// types
types: Vec<TypeStruct<'ctx>>,
2022-01-17 20:02:11 +00:00
/// map signal name to Signal
signals: BTreeMap<String, Signal<'ctx>>,
}
2022-01-04 22:05:25 +00:00
impl<'ctx> Context<'ctx> {
2022-01-17 20:04:22 +00:00
fn get_signal(&self, signame: &str) -> Option<&Signal> {
self.signals.get(signame)
}
fn try_get_signal(&self, signame: &str) -> Result<&Signal, CompileError> {
2022-01-20 18:55:17 +00:00
self.get_signal(signame).ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(signame.to_owned()))
})
2022-01-17 20:04:22 +00:00
}
}
fn lower_process_statement(
ctx: &Context,
2022-01-17 23:11:37 +00:00
pctx: &mut ProcContext,
module: &mut rtlil::Module,
stmt: &parser::proc::ProcStatement,
) -> Result<rtlil::CaseRule, CompileError> {
let rule = match stmt {
parser::proc::ProcStatement::IfElse(_) => todo!("if/else unimplemented"),
parser::proc::ProcStatement::Assign(assig) => {
// FIXME: actually store this
2022-01-17 23:11:37 +00:00
let next_sig;
if let Some(sig) = pctx.next_sigs.get(assig.lhs) {
next_sig = sig.clone();
2022-01-20 18:55:17 +00:00
} else {
2022-01-17 23:11:37 +00:00
let next_gen_id = format!("${}$next", assig.lhs);
module.add_wire(rtlil::Wire::new(&next_gen_id, TODO_WIDTH, None));
next_sig = rtlil::SigSpec::Wire(next_gen_id);
2022-01-20 18:55:17 +00:00
pctx.next_sigs
.insert(assig.lhs.to_owned(), next_sig.clone());
2022-01-17 23:11:37 +00:00
// trigger the modified value to update
2022-01-20 18:55:17 +00:00
pctx.updates
.push((ctx.try_get_signal(assig.lhs)?.sigspec(), next_sig.clone()));
2022-01-17 23:11:37 +00:00
};
let next_expr_wire = lower_expression(ctx, module, &assig.expr)?;
rtlil::CaseRule {
2022-01-20 18:51:09 +00:00
assign: vec![(next_sig, next_expr_wire)],
2022-01-17 16:37:15 +00:00
switches: vec![],
}
2022-01-17 16:37:15 +00:00
}
parser::proc::ProcStatement::Match(match_block) => {
let match_sig = lower_expression(ctx, module, &match_block.expr)?;
let mut cases = vec![];
for arm in &match_block.arms {
2022-01-17 23:11:37 +00:00
let case = lower_process_statement(ctx, pctx, module, &arm.1)?;
let compare_sig = lower_expression(ctx, module, &arm.0)?;
cases.push((compare_sig, case));
2022-01-17 16:37:15 +00:00
}
let switch_rule = rtlil::SwitchRule {
signal: match_sig,
cases,
};
rtlil::CaseRule {
assign: vec![],
switches: vec![switch_rule],
}
2022-01-17 16:37:15 +00:00
}
parser::proc::ProcStatement::Block(_) => todo!("blocks unimplemented"),
};
Ok(rule)
}
2022-01-17 00:15:27 +00:00
fn lower_process(
ctx: &Context,
module: &mut rtlil::Module,
2022-01-17 16:37:15 +00:00
process: &parser::proc::ProcBlock,
2022-01-17 00:15:27 +00:00
) -> Result<(), CompileError> {
2022-01-17 23:11:37 +00:00
let mut pctx = ProcContext {
updates: vec![],
next_sigs: BTreeMap::new(),
};
let mut cases = vec![];
for stmt in &process.items {
2022-01-17 23:11:37 +00:00
let case = lower_process_statement(ctx, &mut pctx, module, stmt)?;
cases.push(case);
}
2022-01-17 23:11:37 +00:00
let sync_sig = ctx.try_get_signal(process.net.fragment())?;
let sync_cond = rtlil::SyncCond::Posedge(sync_sig.sigspec());
2022-01-17 00:15:27 +00:00
let sync_rule = rtlil::SyncRule {
cond: sync_cond,
2022-01-17 23:11:37 +00:00
assign: pctx.updates,
2022-01-17 00:15:27 +00:00
};
if cases.len() != 1 {
panic!("only one expression per block, for now")
}
assert_eq!(cases.len(), 1);
2022-01-17 00:15:27 +00:00
let ir_proc = rtlil::Process {
id: module.make_genid("proc"),
root_case: cases.into_iter().next().unwrap(),
2022-01-17 00:15:27 +00:00
sync_rules: vec![sync_rule],
};
module.add_process(ir_proc);
Ok(())
}
2022-02-04 23:58:47 +00:00
fn desugar_binop<'a>(op: parser::expression::BinOp<'a>) -> parser::expression::Call<'a> {
let a = desugar_expression(op.a);
let b = desugar_expression(op.b);
let op_func = match op.kind {
parser::expression::BinOpKind::And => "and",
parser::expression::BinOpKind::Or => "or",
parser::expression::BinOpKind::Xor => "xor",
};
parser::expression::Call {
name: op_func.into(),
args: vec![a, b],
2022-01-17 18:20:51 +00:00
}
}
2022-02-04 23:58:47 +00:00
fn desugar_unop<'a>(op: parser::expression::UnOp<'a>) -> parser::expression::Call<'a> {
let a = desugar_expression(op.a);
let op_func = match op.kind {
parser::expression::UnOpKind::BitNot => "not",
parser::expression::UnOpKind::Not => todo!(),
};
parser::expression::Call {
name: op_func.into(),
args: vec![a],
}
}
fn desugar_expression<'a>(expr: Expression<'a>) -> Expression<'a> {
2022-01-17 18:20:51 +00:00
// TODO: allow ergonomic traversal of AST
match expr {
2022-02-04 23:58:47 +00:00
Expression::Path(_) => expr,
Expression::Literal(_) => expr,
Expression::Call(mut call) => {
2022-01-20 18:51:09 +00:00
let new_args = call.args.into_iter().map(desugar_expression).collect();
2022-01-17 18:20:51 +00:00
call.args = new_args;
2022-02-04 23:58:47 +00:00
Expression::Call(call)
2022-01-20 18:55:17 +00:00
}
2022-02-04 23:58:47 +00:00
Expression::BinOp(op) => Expression::Call(Box::new(desugar_binop(*op))),
Expression::UnOp(op) => Expression::Call(Box::new(desugar_unop(*op))),
2022-01-17 18:20:51 +00:00
}
}
2022-01-05 01:09:08 +00:00
fn lower_expression(
ctx: &Context,
module: &mut rtlil::Module,
2022-02-04 23:58:47 +00:00
expr: &Expression,
) -> Result<rtlil::SigSpec, CompileError> {
2022-01-17 18:20:51 +00:00
let expr = desugar_expression(expr.clone());
2022-01-04 22:05:25 +00:00
match expr {
2022-02-04 23:58:47 +00:00
Expression::Path(ident) => {
2022-01-17 20:04:22 +00:00
let signal = ctx.try_get_signal(ident)?;
Ok(signal.sigspec())
2022-01-20 18:55:17 +00:00
}
2022-02-04 23:58:47 +00:00
Expression::Call(call) => {
2022-01-05 01:09:08 +00:00
let args_resolved = call
.args
.iter()
.map(|expr| lower_expression(ctx, module, expr))
.collect::<Result<Vec<_>, _>>()?;
let callable = ctx
.callables
.get(call.name.fragment() as &str)
.ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(
call.name.fragment().to_string(),
))
})?;
2022-01-05 01:08:25 +00:00
if args_resolved.len() != callable.argcount() {
2022-01-14 14:32:00 +00:00
return Err(CompileError::new(CompileErrorKind::BadArgCount {
expected: callable.argcount(),
2022-01-14 14:32:00 +00:00
received: args_resolved.len(),
}));
2022-01-05 01:38:56 +00:00
}
2022-02-02 00:03:03 +00:00
let cell_id = module.make_genid(callable.name());
2022-01-05 01:08:25 +00:00
let output_gen_id = format!("{}$out", &cell_id);
module.add_wire(rtlil::Wire::new(&output_gen_id, TODO_WIDTH, None));
let output_gen_wire = rtlil::SigSpec::Wire(output_gen_id);
// let cell =
// (*callable.instantiate)(&cell_id, args_resolved.as_slice(), &output_gen_wire);
// module.add_cell(cell);
Ok(output_gen_wire)
2022-01-04 22:05:25 +00:00
}
2022-01-17 18:20:51 +00:00
// TODO: instantiate operators directly here instead of desugaring, once the callable infrastructure improves
// to get better errors
2022-02-04 23:58:47 +00:00
Expression::Literal(lit) => Ok(rtlil::SigSpec::Const(
lit.span().fragment().parse().unwrap(),
TODO_WIDTH,
)),
Expression::UnOp(_) => todo!(),
Expression::BinOp(_) => todo!(),
2022-01-04 22:05:25 +00:00
}
}
2022-01-05 01:09:08 +00:00
fn lower_assignment(
ctx: &Context,
module: &mut rtlil::Module,
assignment: parser::Assign,
) -> Result<(), CompileError> {
2022-01-17 20:04:22 +00:00
let target_id = ctx.try_get_signal(assignment.lhs)?.sigspec();
2022-01-05 01:08:25 +00:00
let return_wire = lower_expression(ctx, module, &assignment.expr)?;
2022-01-16 19:13:04 +00:00
module.add_connection(&target_id, &return_wire);
2022-01-04 22:05:25 +00:00
Ok(())
}
2022-02-04 23:58:47 +00:00
fn lower_comb(
ctx: &mut Context,
module: &mut rtlil::Module,
pa_comb: parser::comb::CombBlock,
) -> Result<(), CompileError> {
for (num, port) in pa_comb.ports.iter().enumerate() {
let port_id = make_pubid(port.net.name.fragment());
module.add_wire(rtlil::Wire::new(
port_id.clone(),
TODO_WIDTH,
Some(rtlil::PortOption::Input((num + 1) as i32)),
));
let typ = TypeStruct::logic_width(TODO_WIDTH);
let signal = Signal {
name: port.net.name.fragment().to_string(),
il_id: port_id,
// TODO: CRIMES CRIMES CRIMES
typ: Box::leak(Box::new(typ)),
};
ctx.signals
.insert(port.net.name.fragment().to_string(), signal);
}
let ret_id = module.make_genid("ret");
module.add_wire(rtlil::Wire::new(
ret_id.clone(),
TODO_WIDTH,
Some(rtlil::PortOption::Input(99)),
));
let out_sig = lower_expression(ctx, module, &pa_comb.expr)?;
module.add_connection(&rtlil::SigSpec::Wire(ret_id), &out_sig);
Ok(())
}
2022-01-04 22:05:25 +00:00
pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
let mut writer = rtlil::ILWriter::new();
2022-02-03 00:55:12 +00:00
let mut ir_module = rtlil::Module::new(make_pubid("test"));
2022-01-17 20:02:11 +00:00
let mut context = Context {
2022-01-05 01:09:08 +00:00
callables: get_builtins()
.into_iter()
.map(|clb| (clb.name().to_owned(), clb))
2022-01-05 01:09:08 +00:00
.collect(),
2022-01-17 20:02:11 +00:00
signals: BTreeMap::new(),
types: vec![],
2022-01-05 01:09:08 +00:00
};
2022-01-04 22:05:25 +00:00
writer.write_line("autoidx 1");
2022-01-16 20:46:44 +00:00
for item in pa_module.items {
match item {
2022-02-04 23:58:47 +00:00
parser::ModuleItem::Comb(comb) => lower_comb(&mut context, &mut ir_module, comb)?,
parser::ModuleItem::Proc(_) => todo!(),
parser::ModuleItem::State(_) => todo!(),
2022-01-04 22:05:25 +00:00
}
}
ir_module.write_rtlil(&mut writer);
Ok(writer.finish())
}