Compare commits

..

No commits in common. "5ac51f8c5fb2bade0d1a506d4fa55e67e303d169" and "dfc74b4b24a52766fe66d0c089cf442254c0698e" have entirely different histories.

9 changed files with 334 additions and 514 deletions

View File

@ -39,8 +39,7 @@ fn instantiate_binop(celltype: &str, id: &str, args: &[SigSpec], ret: &SigSpec)
cell cell
} }
/* fn make_binop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable<'ctx> {
fn make_binop_callable<'ctx>(name: &str, _celltype: &'static str) -> Callable {
// FIXME: CRIMES CRIMES CRIMES // FIXME: CRIMES CRIMES CRIMES
let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer())); let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer()));
let args = vec![ 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 // FIXME: CRIMES CRIMES CRIMES
let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer())); let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer()));
let args = vec![(Some("A".to_owned()), logic_type)]; 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![ vec![
make_binop_callable("and", "$and"), make_binop_callable("and", "$and"),
make_binop_callable("or", "$or"), make_binop_callable("or", "$or"),
@ -75,4 +74,3 @@ pub fn get_builtins<'ctx>() -> Vec<Callable> {
make_unnop_callable("reduce_or", "$reduce_or"), make_unnop_callable("reduce_or", "$reduce_or"),
] ]
} }
*/

View File

@ -1,22 +1,17 @@
use std::cell::Cell;
use std::collections::BTreeMap; 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;
use crate::rtlil::RtlilWrite;
pub use callable::Callable; pub use callable::Callable;
pub use types::{Type, TypeStruct, TypingContext}; pub use types::{Type, TypeStruct};
mod callable; mod callable;
#[cfg(never)]
pub mod lowering;
pub mod typed_ir; pub mod typed_ir;
pub mod types; 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 /// lots of code is still not width-aware, this constant keeps track of that
const TODO_WIDTH: u32 = 1; const TODO_WIDTH: u32 = 1;
@ -28,8 +23,6 @@ fn make_pubid(id: &str) -> String {
pub enum CompileErrorKind { pub enum CompileErrorKind {
UndefinedReference(String), UndefinedReference(String),
BadArgCount { received: usize, expected: usize }, BadArgCount { received: usize, expected: usize },
TodoError(String),
TypeError { expected: Type, found: Type },
} }
#[derive(Debug)] #[derive(Debug)]
@ -44,175 +37,300 @@ impl CompileError {
} }
/// A user-defined signal /// A user-defined signal
pub struct Signal { pub struct Signal<'ctx> {
/// the user-visible name of the signal /// the user-visible name of the signal
pub name: String, pub name: String,
/// the id of the signal in RTLIL /// the id of the signal in RTLIL
pub il_id: String, pub il_id: String,
/// the type of the signal /// the type of the signal
pub typ: Type, pub typ: Type<'ctx>,
// unique ID of the signal // unique ID of the signal
// pub uid: u64, // pub uid: u64,
} }
impl Signal { impl<'ctx> Signal<'ctx> {
fn sigspec(&self) -> rtlil::SigSpec { fn sigspec(&self) -> rtlil::SigSpec {
rtlil::SigSpec::Wire(self.il_id.to_owned()) 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 /// map callable name to callable
callables: BTreeMap<String, Callable>, callables: BTreeMap<String, Callable<'ctx>>,
/// type names /// types
typenames: BTreeMap<String, Type>, types: Vec<TypeStruct<'ctx>>,
types: TypingContext,
/// map signal name to Signal /// map signal name to Signal
signals: BTreeMap<String, typed_ir::Signal>, signals: BTreeMap<String, Signal<'ctx>>,
/// incrementing counter for unique IDs
ids: Counter,
} }
struct Counter(Cell<usize>); impl<'ctx> Context<'ctx> {
fn get_signal(&self, signame: &str) -> Option<&Signal> {
impl Counter { self.signals.get(signame)
fn new() -> Counter {
Counter(Cell::new(0))
}
fn next(&self) -> usize {
let next = self.0.get() + 1;
self.0.set(next);
next
}
} }
impl Context { fn try_get_signal(&self, signame: &str) -> Result<&Signal, CompileError> {
pub fn new() -> Self { self.get_signal(signame).ok_or_else(|| {
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(),
}
}
fn try_get_signal(&self, signame: &str) -> Result<&typed_ir::Signal, CompileError> {
self.signals.get(signame).ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(signame.to_owned())) 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 try_get_callable(&self, callname: &str) -> Result<&Callable, CompileError> { fn lower_process_statement(
self.callables.get(callname).ok_or_else(|| { ctx: &Context,
CompileError::new(CompileErrorKind::UndefinedReference(callname.to_owned())) 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 type_expression( fn lower_process(
&self, ctx: &Context,
expr: &parser::expression::Expression, module: &mut rtlil::Module,
) -> Result<typed_ir::Expr, CompileError> { process: &parser::proc::ProcBlock,
use parser::expression::Expression; ) -> Result<(), CompileError> {
let id = typed_ir::ExprId(self.ids.next() as u32); let mut pctx = ProcContext {
let t_expr = match expr { updates: vec![],
Expression::Path(name) => { next_sigs: BTreeMap::new(),
let signal = self.try_get_signal(name)?; };
typed_ir::Expr { let mut cases = vec![];
id, for stmt in &process.items {
kind: typed_ir::ExprKind::Path(signal.id), let case = lower_process_statement(ctx, &mut pctx, module, stmt)?;
typ: signal.typ, 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")
} }
Expression::Literal(_) => todo!(), assert_eq!(cases.len(), 1);
Expression::UnOp(op) => self.type_expression(&op.a)?, let ir_proc = rtlil::Process {
Expression::BinOp(op) => { id: module.make_genid("proc"),
let (a, b) = (self.type_expression(&op.a)?, self.type_expression(&op.b)?); root_case: cases.into_iter().next().unwrap(),
typed_ir::Expr { sync_rules: vec![sync_rule],
id, };
kind: typed_ir::ExprKind::Call { module.add_process(ir_proc);
called: typed_ir::DefId(99), 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], 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) => { Expression::Call(call) => {
let args_resolved = call let args_resolved = call
.args .args
.iter() .iter()
.map(|expr| self.type_expression(expr)) .map(|expr| lower_expression(ctx, module, expr))
.collect::<Result<Vec<_>, _>>()?; .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( let callable = ctx
&mut self, .callables
comb: &parser::comb::CombBlock, .get(call.name.fragment() as &str)
) -> Result<typed_ir::Block, CompileError> { .ok_or_else(|| {
let mut signals = Vec::new(); CompileError::new(CompileErrorKind::UndefinedReference(
call.name.fragment().to_string(),
))
})?;
for port in comb.ports.iter() { if args_resolved.len() != callable.argcount() {
let sig_id = self.ids.next(); return Err(CompileError::new(CompileErrorKind::BadArgCount {
let sig_typename = &port.net.typ; expected: callable.argcount(),
let sig_type = self.try_get_type(sig_typename.name.fragment())?; received: args_resolved.len(),
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,
})); }));
} }
Ok(typed_ir::Block { let cell_id = module.make_genid(callable.name());
signals,
expr: root_expr, 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!(),
}
} }
pub fn type_module(&mut self, module: parser::Module) -> Result<typed_ir::Block, CompileError> { fn lower_assignment(
for item in module.items { ctx: &Context,
let block = match &item { module: &mut rtlil::Module,
parser::ModuleItem::Comb(comb) => self.type_comb(comb)?, 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::Proc(_) => todo!(),
parser::ModuleItem::State(_) => todo!(), parser::ModuleItem::State(_) => todo!(),
};
return Ok(block);
}
Err(CompileError::new(CompileErrorKind::TodoError(
"no blocks in module".to_string(),
)))
} }
} }
ir_module.write_rtlil(&mut writer);
Ok(writer.finish())
}

View File

@ -1,12 +1,12 @@
use super::types::Type; use super::types::Type;
pub struct Callable { pub struct Callable<'ty> {
pub name: String, pub name: String,
pub args: Vec<(Option<String>, Type)>, pub args: Vec<(Option<String>, Type<'ty>)>,
pub ret_type: Option<Type>, pub ret_type: Option<Type<'ty>>,
} }
impl<'ty> Callable { impl<'ty> Callable<'ty> {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
&self.name &self.name
} }

View File

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

View File

@ -1,35 +1,15 @@
use super::types::Type; use super::types::Type;
/// ID of a definition (e.g. variable, block, function) /// an abstract element that performs some kind of computation on a value
#[derive(Debug, Clone, Copy)] struct Element<'ty> {
pub struct DefId(pub u32); pub id: u32,
#[derive(Debug, Clone, Copy)] pub inputs: Vec<Element<'ty>>,
pub struct ExprId(pub u32); pub typ: Type<'ty>,
/// 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,
} }
#[derive(Debug, Clone)] struct Signal<'ty> {
pub enum ExprKind { pub id: u32,
Literal, pub typ: Type<'ty>,
Path(DefId),
Call { called: DefId, args: Vec<Expr> },
} }
#[derive(Debug, Clone)] struct Expression {}
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,
}

View File

@ -1,98 +1,84 @@
use std::fmt::Debug;
/// Alias for &TypeStruct to reduce repetition /// Alias for &TypeStruct to reduce repetition
/// and make futura migration to interning /// and make futura migration to interning
/// easier /// easier
pub type Type = InternedType; pub type Type<'ty> = &'ty TypeStruct<'ty>;
#[derive(Debug, Copy, Clone, PartialEq)] pub struct TypeStruct<'ty> {
pub struct InternedType(usize); kind: TypeKind<'ty>,
pub struct TypeStruct {
kind: TypeKind,
} }
#[derive(Debug)] pub enum TypeKind<'ty> {
enum TypeKind {
/// Elaboration-time types /// Elaboration-time types
ElabType(ElabKind), ElabType(ElabKind),
/// Signal/Wire of generic width /// Signal/Wire of generic width
Logic(ElabData), Logic(ElabData<'ty>),
/// UInt of generic width /// UInt of generic width
UInt(ElabData), UInt(ElabData<'ty>),
/// Callable /// Callable
Callable, Callable,
} }
#[derive(Debug)] struct ElabData<'ty> {
struct ElabData { typ: Type<'ty>,
typ: Type, value: ElabValue<'ty>,
value: ElabValue,
} }
#[derive(Debug)] enum ElabValue<'ty> {
enum ElabValue {
/// the value is not given and has to be inferred /// the value is not given and has to be inferred
Infer, Infer,
/// the value is given as some byte representation /// the value is given as some byte representation
Concrete(ElabValueData), Concrete(ElabValueData<'ty>),
} }
#[derive(Debug)] enum ElabValueData<'ty> {
enum ElabValueData {
U32(u32), U32(u32),
Bytes(Vec<u8>), Bytes(&'ty [u8]),
} }
/// Types that are only valid during Elaboration /// Types that are only valid during Elaboration
#[derive(Debug)]
enum ElabKind { enum ElabKind {
/// general, unsized number type /// general, unsized number type
Num, Num,
} }
pub struct PrimitiveTypes { /// Helper functions to create primitive types
pub elabnum: Type, impl<'ty> TypeStruct<'ty> {
pub logic: Type, /// a logic signal with inferred width
} pub fn logic_infer() -> Self {
pub struct TypingContext {
types: Vec<TypeStruct>,
pub primitives: PrimitiveTypes,
}
impl TypingContext {
pub fn new() -> Self {
let primitives = PrimitiveTypes {
elabnum: InternedType(0),
logic: InternedType(1),
};
Self { Self {
types: vec![TypeStruct {
kind: TypeKind::Logic(ElabData { kind: TypeKind::Logic(ElabData {
typ: primitives.elabnum, typ: &TypeStruct {
kind: TypeKind::ElabType(ElabKind::Num),
},
value: ElabValue::Infer, value: ElabValue::Infer,
}), }),
}],
primitives,
} }
} }
pub fn add(&mut self, typ: TypeStruct) -> Type { /// a logic signal with known width
let id = self.types.len(); pub fn logic_width(width: u32) -> Self {
self.types.push(typ); Self {
InternedType(id) kind: TypeKind::Logic(ElabData::u32(width)),
}
} }
pub fn get(&self, typ: Type) -> &TypeStruct { /// return an elaboration number type
&self.types[typ.0] pub fn elab_num() -> Self {
Self {
kind: TypeKind::ElabType(ElabKind::Num),
}
}
} }
pub fn pretty_type(&self, w: &mut dyn std::fmt::Write, typ: Type) -> std::fmt::Result { /// Helper functions to create primitive elaboration values
match &self.get(typ).kind { impl<'ty> ElabData<'ty> {
TypeKind::ElabType(val) => write!(w, "{{{:?}}}", val), /// an integer
TypeKind::Logic(_) => todo!(), pub fn u32(val: u32) -> Self {
TypeKind::UInt(_) => todo!(), Self {
TypeKind::Callable => todo!(), typ: &TypeStruct {
kind: TypeKind::ElabType(ElabKind::Num),
},
value: ElabValue::Concrete(ElabValueData::U32(val)),
} }
} }
} }

View File

@ -58,12 +58,7 @@ fn main() {
if opt.debug { if opt.debug {
println!("{:#?}", res); println!("{:#?}", res);
} }
let mut frontendcontext = crate::frontend::Context::new(); let lowered = crate::frontend::lower_module(res.1);
let typed = frontendcontext.type_module(res.1);
if opt.debug {
println!("{:#?}", typed);
}
/*
match lowered { match lowered {
Ok(res) => { Ok(res) => {
let mut file = File::create(opt.output.unwrap_or_else(|| "out.rtlil".into())) let mut file = File::create(opt.output.unwrap_or_else(|| "out.rtlil".into()))
@ -73,7 +68,6 @@ fn main() {
} }
Err(err) => eprintln!("{:#?}", err), Err(err) => eprintln!("{:#?}", err),
} }
*/
} }
} }
} }

View File

@ -24,8 +24,8 @@ pub fn typename(input: TokenSpan) -> IResult<TokenSpan, TypeName> {
#[derive(Debug)] #[derive(Debug)]
pub struct TypeName<'a> { pub struct TypeName<'a> {
pub name: Span<'a>, name: Span<'a>,
pub generics: (), generics: (),
} }
#[derive(Debug)] #[derive(Debug)]

View File

@ -80,8 +80,8 @@ fn unary(input: TokenSpan) -> IResult<TokenSpan, Expression> {
fn bitop_kind(input: TokenSpan) -> IResult<TokenSpan, BinOpKind> { fn bitop_kind(input: TokenSpan) -> IResult<TokenSpan, BinOpKind> {
alt(( alt((
map(token(tk::BitXor), |_| BinOpKind::Xor), map(token(tk::BitXor), |_| BinOpKind::Xor),
map(token(tk::BitOr), |_| BinOpKind::Or), map(token(tk::BitOr), |_| BinOpKind::Xor),
map(token(tk::BitAnd), |_| BinOpKind::And), map(token(tk::BitAnd), |_| BinOpKind::Xor),
))(input) ))(input)
} }