Compare commits
No commits in common. "5ac51f8c5fb2bade0d1a506d4fa55e67e303d169" and "dfc74b4b24a52766fe66d0c089cf442254c0698e" have entirely different histories.
5ac51f8c5f
...
dfc74b4b24
|
@ -39,8 +39,7 @@ fn instantiate_binop(celltype: &str, id: &str, args: &[SigSpec], ret: &SigSpec)
|
|||
cell
|
||||
}
|
||||
|
||||
/*
|
||||
fn make_binop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable {
|
||||
fn make_binop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable<'ctx> {
|
||||
// FIXME: CRIMES CRIMES CRIMES
|
||||
let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer()));
|
||||
let args = vec![
|
||||
|
@ -54,7 +53,7 @@ fn make_binop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable {
|
|||
}
|
||||
}
|
||||
|
||||
fn make_unnop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable {
|
||||
fn make_unnop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable<'ctx> {
|
||||
// FIXME: CRIMES CRIMES CRIMES
|
||||
let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer()));
|
||||
let args = vec![(Some("A".to_owned()), logic_type)];
|
||||
|
@ -65,7 +64,7 @@ fn make_unnop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn get_builtins<'ctx>() -> Vec<Callable> {
|
||||
pub fn get_builtins<'ctx>() -> Vec<Callable<'ctx>> {
|
||||
vec![
|
||||
make_binop_callable("and", "$and"),
|
||||
make_binop_callable("or", "$or"),
|
||||
|
@ -75,4 +74,3 @@ pub fn get_builtins<'ctx>() -> Vec<Callable> {
|
|||
make_unnop_callable("reduce_or", "$reduce_or"),
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
|
396
src/frontend.rs
396
src/frontend.rs
|
@ -1,22 +1,17 @@
|
|||
use std::cell::Cell;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::parser;
|
||||
use crate::builtin_cells::get_builtins;
|
||||
use crate::parser;
|
||||
use crate::parser::expression::Expression;
|
||||
use crate::rtlil;
|
||||
use crate::rtlil::RtlilWrite;
|
||||
pub use callable::Callable;
|
||||
pub use types::{Type, TypeStruct, TypingContext};
|
||||
pub use types::{Type, TypeStruct};
|
||||
|
||||
mod callable;
|
||||
#[cfg(never)]
|
||||
pub mod lowering;
|
||||
pub mod typed_ir;
|
||||
pub mod types;
|
||||
|
||||
#[cfg(never)]
|
||||
use crate::builtin_cells::get_builtins;
|
||||
|
||||
// pub use lowering::lower_module;
|
||||
|
||||
/// lots of code is still not width-aware, this constant keeps track of that
|
||||
const TODO_WIDTH: u32 = 1;
|
||||
|
||||
|
@ -28,8 +23,6 @@ fn make_pubid(id: &str) -> String {
|
|||
pub enum CompileErrorKind {
|
||||
UndefinedReference(String),
|
||||
BadArgCount { received: usize, expected: usize },
|
||||
TodoError(String),
|
||||
TypeError { expected: Type, found: Type },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
@ -44,175 +37,300 @@ impl CompileError {
|
|||
}
|
||||
|
||||
/// A user-defined signal
|
||||
pub struct Signal {
|
||||
pub struct Signal<'ctx> {
|
||||
/// the user-visible name of the signal
|
||||
pub name: String,
|
||||
/// the id of the signal in RTLIL
|
||||
pub il_id: String,
|
||||
/// the type of the signal
|
||||
pub typ: Type,
|
||||
pub typ: Type<'ctx>,
|
||||
// unique ID of the signal
|
||||
// pub uid: u64,
|
||||
}
|
||||
|
||||
impl Signal {
|
||||
impl<'ctx> Signal<'ctx> {
|
||||
fn sigspec(&self) -> rtlil::SigSpec {
|
||||
rtlil::SigSpec::Wire(self.il_id.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
/// context used when generating processes
|
||||
struct ProcContext {
|
||||
updates: Vec<(rtlil::SigSpec, rtlil::SigSpec)>,
|
||||
next_sigs: BTreeMap<String, rtlil::SigSpec>,
|
||||
}
|
||||
|
||||
struct Context<'ctx> {
|
||||
/// map callable name to callable
|
||||
callables: BTreeMap<String, Callable>,
|
||||
/// type names
|
||||
typenames: BTreeMap<String, Type>,
|
||||
types: TypingContext,
|
||||
callables: BTreeMap<String, Callable<'ctx>>,
|
||||
/// types
|
||||
types: Vec<TypeStruct<'ctx>>,
|
||||
/// map signal name to Signal
|
||||
signals: BTreeMap<String, typed_ir::Signal>,
|
||||
/// incrementing counter for unique IDs
|
||||
ids: Counter,
|
||||
signals: BTreeMap<String, Signal<'ctx>>,
|
||||
}
|
||||
|
||||
struct Counter(Cell<usize>);
|
||||
|
||||
impl Counter {
|
||||
fn new() -> Counter {
|
||||
Counter(Cell::new(0))
|
||||
}
|
||||
fn next(&self) -> usize {
|
||||
let next = self.0.get() + 1;
|
||||
self.0.set(next);
|
||||
next
|
||||
}
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> Self {
|
||||
let tcx = TypingContext::new();
|
||||
Context {
|
||||
callables: BTreeMap::new(),
|
||||
signals: BTreeMap::new(),
|
||||
types: TypingContext::new(),
|
||||
typenames: [("Logic".to_string(), tcx.primitives.logic)].into(),
|
||||
ids: Counter::new(),
|
||||
}
|
||||
impl<'ctx> Context<'ctx> {
|
||||
fn get_signal(&self, signame: &str) -> Option<&Signal> {
|
||||
self.signals.get(signame)
|
||||
}
|
||||
|
||||
fn try_get_signal(&self, signame: &str) -> Result<&typed_ir::Signal, CompileError> {
|
||||
self.signals.get(signame).ok_or_else(|| {
|
||||
fn try_get_signal(&self, signame: &str) -> Result<&Signal, CompileError> {
|
||||
self.get_signal(signame).ok_or_else(|| {
|
||||
CompileError::new(CompileErrorKind::UndefinedReference(signame.to_owned()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn try_get_type(&self, typename: &str) -> Result<Type, CompileError> {
|
||||
self.typenames.get(typename).copied().ok_or_else(|| {
|
||||
CompileError::new(CompileErrorKind::UndefinedReference(typename.to_owned()))
|
||||
})
|
||||
fn lower_process_statement(
|
||||
ctx: &Context,
|
||||
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
|
||||
let next_sig;
|
||||
if let Some(sig) = pctx.next_sigs.get(assig.lhs) {
|
||||
next_sig = sig.clone();
|
||||
} else {
|
||||
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);
|
||||
|
||||
pctx.next_sigs
|
||||
.insert(assig.lhs.to_owned(), next_sig.clone());
|
||||
|
||||
// trigger the modified value to update
|
||||
pctx.updates
|
||||
.push((ctx.try_get_signal(assig.lhs)?.sigspec(), next_sig.clone()));
|
||||
};
|
||||
|
||||
let next_expr_wire = lower_expression(ctx, module, &assig.expr)?;
|
||||
|
||||
rtlil::CaseRule {
|
||||
assign: vec![(next_sig, next_expr_wire)],
|
||||
switches: vec![],
|
||||
}
|
||||
}
|
||||
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 {
|
||||
let case = lower_process_statement(ctx, pctx, module, &arm.1)?;
|
||||
let compare_sig = lower_expression(ctx, module, &arm.0)?;
|
||||
cases.push((compare_sig, case));
|
||||
}
|
||||
let switch_rule = rtlil::SwitchRule {
|
||||
signal: match_sig,
|
||||
cases,
|
||||
};
|
||||
rtlil::CaseRule {
|
||||
assign: vec![],
|
||||
switches: vec![switch_rule],
|
||||
}
|
||||
}
|
||||
parser::proc::ProcStatement::Block(_) => todo!("blocks unimplemented"),
|
||||
};
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
fn lower_process(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
process: &parser::proc::ProcBlock,
|
||||
) -> Result<(), CompileError> {
|
||||
let mut pctx = ProcContext {
|
||||
updates: vec![],
|
||||
next_sigs: BTreeMap::new(),
|
||||
};
|
||||
let mut cases = vec![];
|
||||
for stmt in &process.items {
|
||||
let case = lower_process_statement(ctx, &mut pctx, module, stmt)?;
|
||||
cases.push(case);
|
||||
}
|
||||
|
||||
fn try_get_callable(&self, callname: &str) -> Result<&Callable, CompileError> {
|
||||
self.callables.get(callname).ok_or_else(|| {
|
||||
CompileError::new(CompileErrorKind::UndefinedReference(callname.to_owned()))
|
||||
})
|
||||
let sync_sig = ctx.try_get_signal(process.net.fragment())?;
|
||||
let sync_cond = rtlil::SyncCond::Posedge(sync_sig.sigspec());
|
||||
let sync_rule = rtlil::SyncRule {
|
||||
cond: sync_cond,
|
||||
assign: pctx.updates,
|
||||
};
|
||||
if cases.len() != 1 {
|
||||
panic!("only one expression per block, for now")
|
||||
}
|
||||
assert_eq!(cases.len(), 1);
|
||||
let ir_proc = rtlil::Process {
|
||||
id: module.make_genid("proc"),
|
||||
root_case: cases.into_iter().next().unwrap(),
|
||||
sync_rules: vec![sync_rule],
|
||||
};
|
||||
module.add_process(ir_proc);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn type_expression(
|
||||
&self,
|
||||
expr: &parser::expression::Expression,
|
||||
) -> Result<typed_ir::Expr, CompileError> {
|
||||
use parser::expression::Expression;
|
||||
let id = typed_ir::ExprId(self.ids.next() as u32);
|
||||
let t_expr = match expr {
|
||||
Expression::Path(name) => {
|
||||
let signal = self.try_get_signal(name)?;
|
||||
typed_ir::Expr {
|
||||
id,
|
||||
kind: typed_ir::ExprKind::Path(signal.id),
|
||||
typ: signal.typ,
|
||||
}
|
||||
}
|
||||
Expression::Literal(_) => todo!(),
|
||||
Expression::UnOp(op) => self.type_expression(&op.a)?,
|
||||
Expression::BinOp(op) => {
|
||||
let (a, b) = (self.type_expression(&op.a)?, self.type_expression(&op.b)?);
|
||||
typed_ir::Expr {
|
||||
id,
|
||||
kind: typed_ir::ExprKind::Call {
|
||||
called: typed_ir::DefId(99),
|
||||
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],
|
||||
},
|
||||
typ: self.types.primitives.elabnum,
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
// TODO: allow ergonomic traversal of AST
|
||||
match expr {
|
||||
Expression::Path(_) => expr,
|
||||
Expression::Literal(_) => expr,
|
||||
Expression::Call(mut call) => {
|
||||
let new_args = call.args.into_iter().map(desugar_expression).collect();
|
||||
call.args = new_args;
|
||||
Expression::Call(call)
|
||||
}
|
||||
Expression::BinOp(op) => Expression::Call(Box::new(desugar_binop(*op))),
|
||||
Expression::UnOp(op) => Expression::Call(Box::new(desugar_unop(*op))),
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_expression(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
expr: &Expression,
|
||||
) -> Result<rtlil::SigSpec, CompileError> {
|
||||
let expr = desugar_expression(expr.clone());
|
||||
match expr {
|
||||
Expression::Path(ident) => {
|
||||
let signal = ctx.try_get_signal(ident)?;
|
||||
Ok(signal.sigspec())
|
||||
}
|
||||
Expression::Call(call) => {
|
||||
let args_resolved = call
|
||||
.args
|
||||
.iter()
|
||||
.map(|expr| self.type_expression(expr))
|
||||
.map(|expr| lower_expression(ctx, module, expr))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
typed_ir::Expr {
|
||||
id,
|
||||
kind: typed_ir::ExprKind::Call {
|
||||
called: typed_ir::DefId(99),
|
||||
args: args_resolved,
|
||||
},
|
||||
typ: self.types.primitives.elabnum,
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(t_expr)
|
||||
}
|
||||
|
||||
fn type_comb(
|
||||
&mut self,
|
||||
comb: &parser::comb::CombBlock,
|
||||
) -> Result<typed_ir::Block, CompileError> {
|
||||
let mut signals = Vec::new();
|
||||
let callable = ctx
|
||||
.callables
|
||||
.get(call.name.fragment() as &str)
|
||||
.ok_or_else(|| {
|
||||
CompileError::new(CompileErrorKind::UndefinedReference(
|
||||
call.name.fragment().to_string(),
|
||||
))
|
||||
})?;
|
||||
|
||||
for port in comb.ports.iter() {
|
||||
let sig_id = self.ids.next();
|
||||
let sig_typename = &port.net.typ;
|
||||
let sig_type = self.try_get_type(sig_typename.name.fragment())?;
|
||||
let sig = typed_ir::Signal {
|
||||
id: typed_ir::DefId(sig_id as u32),
|
||||
typ: sig_type,
|
||||
};
|
||||
signals.push(sig.clone());
|
||||
self.signals.insert(port.net.name.to_string(), sig);
|
||||
}
|
||||
|
||||
let ret_typename = &comb.ret.name;
|
||||
let ret_type = self.try_get_type(ret_typename.fragment())?;
|
||||
|
||||
let root_expr = self.type_expression(&comb.expr)?;
|
||||
|
||||
// TODO: more sophisticated type compat check
|
||||
if root_expr.typ != ret_type {
|
||||
let expected = ret_type;
|
||||
let found = root_expr.typ;
|
||||
return Err(CompileError::new(CompileErrorKind::TypeError {
|
||||
expected,
|
||||
found,
|
||||
if args_resolved.len() != callable.argcount() {
|
||||
return Err(CompileError::new(CompileErrorKind::BadArgCount {
|
||||
expected: callable.argcount(),
|
||||
received: args_resolved.len(),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(typed_ir::Block {
|
||||
signals,
|
||||
expr: root_expr,
|
||||
})
|
||||
}
|
||||
let cell_id = module.make_genid(callable.name());
|
||||
|
||||
pub fn type_module(&mut self, module: parser::Module) -> Result<typed_ir::Block, CompileError> {
|
||||
for item in module.items {
|
||||
let block = match &item {
|
||||
parser::ModuleItem::Comb(comb) => self.type_comb(comb)?,
|
||||
parser::ModuleItem::Proc(_) => todo!(),
|
||||
parser::ModuleItem::State(_) => todo!(),
|
||||
};
|
||||
return Ok(block);
|
||||
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)
|
||||
}
|
||||
Err(CompileError::new(CompileErrorKind::TodoError(
|
||||
"no blocks in module".to_string(),
|
||||
)))
|
||||
// TODO: instantiate operators directly here instead of desugaring, once the callable infrastructure improves
|
||||
// to get better errors
|
||||
Expression::Literal(lit) => Ok(rtlil::SigSpec::Const(
|
||||
lit.span().fragment().parse().unwrap(),
|
||||
TODO_WIDTH,
|
||||
)),
|
||||
Expression::UnOp(_) => todo!(),
|
||||
Expression::BinOp(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_assignment(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
assignment: parser::Assign,
|
||||
) -> Result<(), CompileError> {
|
||||
let target_id = ctx.try_get_signal(assignment.lhs)?.sigspec();
|
||||
let return_wire = lower_expression(ctx, module, &assignment.expr)?;
|
||||
module.add_connection(&target_id, &return_wire);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
|
||||
let mut writer = rtlil::ILWriter::new();
|
||||
let mut ir_module = rtlil::Module::new(make_pubid("test"));
|
||||
let mut context = Context {
|
||||
callables: get_builtins()
|
||||
.into_iter()
|
||||
.map(|clb| (clb.name().to_owned(), clb))
|
||||
.collect(),
|
||||
signals: BTreeMap::new(),
|
||||
types: vec![],
|
||||
};
|
||||
|
||||
writer.write_line("autoidx 1");
|
||||
for item in pa_module.items {
|
||||
match item {
|
||||
parser::ModuleItem::Comb(comb) => lower_comb(&mut context, &mut ir_module, comb)?,
|
||||
parser::ModuleItem::Proc(_) => todo!(),
|
||||
parser::ModuleItem::State(_) => todo!(),
|
||||
}
|
||||
}
|
||||
ir_module.write_rtlil(&mut writer);
|
||||
Ok(writer.finish())
|
||||
}
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
use super::types::Type;
|
||||
|
||||
pub struct Callable {
|
||||
pub struct Callable<'ty> {
|
||||
pub name: String,
|
||||
pub args: Vec<(Option<String>, Type)>,
|
||||
pub ret_type: Option<Type>,
|
||||
pub args: Vec<(Option<String>, Type<'ty>)>,
|
||||
pub ret_type: Option<Type<'ty>>,
|
||||
}
|
||||
|
||||
impl<'ty> Callable {
|
||||
impl<'ty> Callable<'ty> {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
|
|
@ -1,256 +0,0 @@
|
|||
use std::collections::BTreeMap;
|
||||
|
||||
use super::types::{make_primitives, TypeStruct};
|
||||
use super::{make_pubid, CompileError, CompileErrorKind, Context, Signal, TODO_WIDTH};
|
||||
use crate::builtin_cells::get_builtins;
|
||||
use crate::parser;
|
||||
use crate::parser::expression::Expression;
|
||||
use crate::rtlil;
|
||||
use crate::rtlil::RtlilWrite;
|
||||
|
||||
/// context used when generating processes
|
||||
struct ProcContext {
|
||||
updates: Vec<(rtlil::SigSpec, rtlil::SigSpec)>,
|
||||
next_sigs: BTreeMap<String, rtlil::SigSpec>,
|
||||
}
|
||||
|
||||
fn lower_process_statement(
|
||||
ctx: &Context,
|
||||
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
|
||||
let next_sig;
|
||||
if let Some(sig) = pctx.next_sigs.get(assig.lhs) {
|
||||
next_sig = sig.clone();
|
||||
} else {
|
||||
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);
|
||||
|
||||
pctx.next_sigs
|
||||
.insert(assig.lhs.to_owned(), next_sig.clone());
|
||||
|
||||
// trigger the modified value to update
|
||||
pctx.updates
|
||||
.push((ctx.try_get_signal(assig.lhs)?.sigspec(), next_sig.clone()));
|
||||
};
|
||||
|
||||
let next_expr_wire = lower_expression(ctx, module, &assig.expr)?;
|
||||
|
||||
rtlil::CaseRule {
|
||||
assign: vec![(next_sig, next_expr_wire)],
|
||||
switches: vec![],
|
||||
}
|
||||
}
|
||||
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 {
|
||||
let case = lower_process_statement(ctx, pctx, module, &arm.1)?;
|
||||
let compare_sig = lower_expression(ctx, module, &arm.0)?;
|
||||
cases.push((compare_sig, case));
|
||||
}
|
||||
let switch_rule = rtlil::SwitchRule {
|
||||
signal: match_sig,
|
||||
cases,
|
||||
};
|
||||
rtlil::CaseRule {
|
||||
assign: vec![],
|
||||
switches: vec![switch_rule],
|
||||
}
|
||||
}
|
||||
parser::proc::ProcStatement::Block(_) => todo!("blocks unimplemented"),
|
||||
};
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
fn lower_process(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
process: &parser::proc::ProcBlock,
|
||||
) -> Result<(), CompileError> {
|
||||
let mut pctx = ProcContext {
|
||||
updates: vec![],
|
||||
next_sigs: BTreeMap::new(),
|
||||
};
|
||||
let mut cases = vec![];
|
||||
for stmt in &process.items {
|
||||
let case = lower_process_statement(ctx, &mut pctx, module, stmt)?;
|
||||
cases.push(case);
|
||||
}
|
||||
|
||||
let sync_sig = ctx.try_get_signal(process.net.fragment())?;
|
||||
let sync_cond = rtlil::SyncCond::Posedge(sync_sig.sigspec());
|
||||
let sync_rule = rtlil::SyncRule {
|
||||
cond: sync_cond,
|
||||
assign: pctx.updates,
|
||||
};
|
||||
if cases.len() != 1 {
|
||||
panic!("only one expression per block, for now")
|
||||
}
|
||||
assert_eq!(cases.len(), 1);
|
||||
let ir_proc = rtlil::Process {
|
||||
id: module.make_genid("proc"),
|
||||
root_case: cases.into_iter().next().unwrap(),
|
||||
sync_rules: vec![sync_rule],
|
||||
};
|
||||
module.add_process(ir_proc);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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],
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
// TODO: allow ergonomic traversal of AST
|
||||
match expr {
|
||||
Expression::Path(_) => expr,
|
||||
Expression::Literal(_) => expr,
|
||||
Expression::Call(mut call) => {
|
||||
let new_args = call.args.into_iter().map(desugar_expression).collect();
|
||||
call.args = new_args;
|
||||
Expression::Call(call)
|
||||
}
|
||||
Expression::BinOp(op) => Expression::Call(Box::new(desugar_binop(*op))),
|
||||
Expression::UnOp(op) => Expression::Call(Box::new(desugar_unop(*op))),
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_expression(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
expr: &Expression,
|
||||
) -> Result<rtlil::SigSpec, CompileError> {
|
||||
let expr = desugar_expression(expr.clone());
|
||||
match expr {
|
||||
Expression::Path(ident) => {
|
||||
let signal = ctx.try_get_signal(ident)?;
|
||||
Ok(signal.sigspec())
|
||||
}
|
||||
Expression::Call(call) => {
|
||||
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(),
|
||||
))
|
||||
})?;
|
||||
|
||||
if args_resolved.len() != callable.argcount() {
|
||||
return Err(CompileError::new(CompileErrorKind::BadArgCount {
|
||||
expected: callable.argcount(),
|
||||
received: args_resolved.len(),
|
||||
}));
|
||||
}
|
||||
|
||||
let cell_id = module.make_genid(callable.name());
|
||||
|
||||
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)
|
||||
}
|
||||
// TODO: instantiate operators directly here instead of desugaring, once the callable infrastructure improves
|
||||
// to get better errors
|
||||
Expression::Literal(lit) => Ok(rtlil::SigSpec::Const(
|
||||
lit.span().fragment().parse().unwrap(),
|
||||
TODO_WIDTH,
|
||||
)),
|
||||
Expression::UnOp(_) => todo!(),
|
||||
Expression::BinOp(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lower_assignment(
|
||||
ctx: &Context,
|
||||
module: &mut rtlil::Module,
|
||||
assignment: parser::Assign,
|
||||
) -> Result<(), CompileError> {
|
||||
let target_id = ctx.try_get_signal(assignment.lhs)?.sigspec();
|
||||
let return_wire = lower_expression(ctx, module, &assignment.expr)?;
|
||||
module.add_connection(&target_id, &return_wire);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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());
|
||||
let port_tyname = &port.net.typ;
|
||||
ctx.try_get_type(port_tyname.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::Output(99)),
|
||||
));
|
||||
let out_sig = lower_expression(ctx, module, &pa_comb.expr)?;
|
||||
module.add_connection(&rtlil::SigSpec::Wire(ret_id), &out_sig);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
|
||||
let mut writer = rtlil::ILWriter::new();
|
||||
let mut ir_module = rtlil::Module::new(make_pubid("test"));
|
||||
|
||||
writer.write_line("autoidx 1");
|
||||
ir_module.write_rtlil(&mut writer);
|
||||
Ok(writer.finish())
|
||||
}
|
|
@ -1,35 +1,15 @@
|
|||
use super::types::Type;
|
||||
|
||||
/// ID of a definition (e.g. variable, block, function)
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct DefId(pub u32);
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExprId(pub u32);
|
||||
|
||||
/// an abstract element that performs some kind of computation on inputs
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Expr {
|
||||
pub id: ExprId,
|
||||
pub kind: ExprKind,
|
||||
pub typ: Type,
|
||||
/// an abstract element that performs some kind of computation on a value
|
||||
struct Element<'ty> {
|
||||
pub id: u32,
|
||||
pub inputs: Vec<Element<'ty>>,
|
||||
pub typ: Type<'ty>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExprKind {
|
||||
Literal,
|
||||
Path(DefId),
|
||||
Call { called: DefId, args: Vec<Expr> },
|
||||
struct Signal<'ty> {
|
||||
pub id: u32,
|
||||
pub typ: Type<'ty>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Signal {
|
||||
pub id: DefId,
|
||||
pub typ: Type,
|
||||
}
|
||||
|
||||
/// A block of HDL code, e.g. comb block
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Block {
|
||||
pub signals: Vec<Signal>,
|
||||
pub expr: Expr,
|
||||
}
|
||||
struct Expression {}
|
||||
|
|
|
@ -1,98 +1,84 @@
|
|||
use std::fmt::Debug;
|
||||
/// Alias for &TypeStruct to reduce repetition
|
||||
/// and make futura migration to interning
|
||||
/// easier
|
||||
pub type Type = InternedType;
|
||||
pub type Type<'ty> = &'ty TypeStruct<'ty>;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub struct InternedType(usize);
|
||||
|
||||
pub struct TypeStruct {
|
||||
kind: TypeKind,
|
||||
pub struct TypeStruct<'ty> {
|
||||
kind: TypeKind<'ty>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TypeKind {
|
||||
pub enum TypeKind<'ty> {
|
||||
/// Elaboration-time types
|
||||
ElabType(ElabKind),
|
||||
/// Signal/Wire of generic width
|
||||
Logic(ElabData),
|
||||
Logic(ElabData<'ty>),
|
||||
/// UInt of generic width
|
||||
UInt(ElabData),
|
||||
UInt(ElabData<'ty>),
|
||||
/// Callable
|
||||
Callable,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ElabData {
|
||||
typ: Type,
|
||||
value: ElabValue,
|
||||
struct ElabData<'ty> {
|
||||
typ: Type<'ty>,
|
||||
value: ElabValue<'ty>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ElabValue {
|
||||
enum ElabValue<'ty> {
|
||||
/// the value is not given and has to be inferred
|
||||
Infer,
|
||||
/// the value is given as some byte representation
|
||||
Concrete(ElabValueData),
|
||||
Concrete(ElabValueData<'ty>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ElabValueData {
|
||||
enum ElabValueData<'ty> {
|
||||
U32(u32),
|
||||
Bytes(Vec<u8>),
|
||||
Bytes(&'ty [u8]),
|
||||
}
|
||||
|
||||
/// Types that are only valid during Elaboration
|
||||
#[derive(Debug)]
|
||||
enum ElabKind {
|
||||
/// general, unsized number type
|
||||
Num,
|
||||
}
|
||||
|
||||
pub struct PrimitiveTypes {
|
||||
pub elabnum: Type,
|
||||
pub logic: Type,
|
||||
}
|
||||
|
||||
pub struct TypingContext {
|
||||
types: Vec<TypeStruct>,
|
||||
pub primitives: PrimitiveTypes,
|
||||
}
|
||||
|
||||
impl TypingContext {
|
||||
pub fn new() -> Self {
|
||||
let primitives = PrimitiveTypes {
|
||||
elabnum: InternedType(0),
|
||||
logic: InternedType(1),
|
||||
};
|
||||
/// Helper functions to create primitive types
|
||||
impl<'ty> TypeStruct<'ty> {
|
||||
/// a logic signal with inferred width
|
||||
pub fn logic_infer() -> Self {
|
||||
Self {
|
||||
types: vec![TypeStruct {
|
||||
kind: TypeKind::Logic(ElabData {
|
||||
typ: primitives.elabnum,
|
||||
typ: &TypeStruct {
|
||||
kind: TypeKind::ElabType(ElabKind::Num),
|
||||
},
|
||||
value: ElabValue::Infer,
|
||||
}),
|
||||
}],
|
||||
primitives,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&mut self, typ: TypeStruct) -> Type {
|
||||
let id = self.types.len();
|
||||
self.types.push(typ);
|
||||
InternedType(id)
|
||||
/// a logic signal with known width
|
||||
pub fn logic_width(width: u32) -> Self {
|
||||
Self {
|
||||
kind: TypeKind::Logic(ElabData::u32(width)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, typ: Type) -> &TypeStruct {
|
||||
&self.types[typ.0]
|
||||
}
|
||||
|
||||
pub fn pretty_type(&self, w: &mut dyn std::fmt::Write, typ: Type) -> std::fmt::Result {
|
||||
match &self.get(typ).kind {
|
||||
TypeKind::ElabType(val) => write!(w, "{{{:?}}}", val),
|
||||
TypeKind::Logic(_) => todo!(),
|
||||
TypeKind::UInt(_) => todo!(),
|
||||
TypeKind::Callable => todo!(),
|
||||
/// return an elaboration number type
|
||||
pub fn elab_num() -> Self {
|
||||
Self {
|
||||
kind: TypeKind::ElabType(ElabKind::Num),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper functions to create primitive elaboration values
|
||||
impl<'ty> ElabData<'ty> {
|
||||
/// an integer
|
||||
pub fn u32(val: u32) -> Self {
|
||||
Self {
|
||||
typ: &TypeStruct {
|
||||
kind: TypeKind::ElabType(ElabKind::Num),
|
||||
},
|
||||
value: ElabValue::Concrete(ElabValueData::U32(val)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -58,12 +58,7 @@ fn main() {
|
|||
if opt.debug {
|
||||
println!("{:#?}", res);
|
||||
}
|
||||
let mut frontendcontext = crate::frontend::Context::new();
|
||||
let typed = frontendcontext.type_module(res.1);
|
||||
if opt.debug {
|
||||
println!("{:#?}", typed);
|
||||
}
|
||||
/*
|
||||
let lowered = crate::frontend::lower_module(res.1);
|
||||
match lowered {
|
||||
Ok(res) => {
|
||||
let mut file = File::create(opt.output.unwrap_or_else(|| "out.rtlil".into()))
|
||||
|
@ -73,7 +68,6 @@ fn main() {
|
|||
}
|
||||
Err(err) => eprintln!("{:#?}", err),
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,8 +24,8 @@ pub fn typename(input: TokenSpan) -> IResult<TokenSpan, TypeName> {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct TypeName<'a> {
|
||||
pub name: Span<'a>,
|
||||
pub generics: (),
|
||||
name: Span<'a>,
|
||||
generics: (),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
|
@ -80,8 +80,8 @@ fn unary(input: TokenSpan) -> IResult<TokenSpan, Expression> {
|
|||
fn bitop_kind(input: TokenSpan) -> IResult<TokenSpan, BinOpKind> {
|
||||
alt((
|
||||
map(token(tk::BitXor), |_| BinOpKind::Xor),
|
||||
map(token(tk::BitOr), |_| BinOpKind::Or),
|
||||
map(token(tk::BitAnd), |_| BinOpKind::And),
|
||||
map(token(tk::BitOr), |_| BinOpKind::Xor),
|
||||
map(token(tk::BitAnd), |_| BinOpKind::Xor),
|
||||
))(input)
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue