Compare commits

...

4 Commits

Author SHA1 Message Date
NotAFile 5ac51f8c5f clippy fix 2022-02-15 21:41:01 +01:00
NotAFile 6148c599b8 start interning types 2022-02-15 21:32:55 +01:00
NotAFile 805acee3c5 move lowering code 2022-02-06 23:19:55 +01:00
NotAFile 83bb8d9292 add preliminary type lookup 2022-02-06 21:02:55 +01:00
9 changed files with 512 additions and 332 deletions

View File

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

View File

@ -1,17 +1,22 @@
use std::cell::Cell;
use std::collections::BTreeMap;
use crate::builtin_cells::get_builtins;
use crate::parser;
use crate::parser::expression::Expression;
use super::parser;
use crate::rtlil;
use crate::rtlil::RtlilWrite;
pub use callable::Callable;
pub use types::{Type, TypeStruct};
pub use types::{Type, TypeStruct, TypingContext};
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;
@ -23,6 +28,8 @@ 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)]
@ -37,300 +44,175 @@ impl CompileError {
}
/// A user-defined signal
pub struct Signal<'ctx> {
pub struct Signal {
/// 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<'ctx>,
pub typ: Type,
// unique ID of the signal
// pub uid: u64,
}
impl<'ctx> Signal<'ctx> {
impl Signal {
fn sigspec(&self) -> rtlil::SigSpec {
rtlil::SigSpec::Wire(self.il_id.to_owned())
}
}
/// context used when generating processes
struct ProcContext {
updates: Vec<(rtlil::SigSpec, rtlil::SigSpec)>,
next_sigs: BTreeMap<String, rtlil::SigSpec>,
}
struct Context<'ctx> {
pub struct Context {
/// map callable name to callable
callables: BTreeMap<String, Callable<'ctx>>,
/// types
types: Vec<TypeStruct<'ctx>>,
callables: BTreeMap<String, Callable>,
/// type names
typenames: BTreeMap<String, Type>,
types: TypingContext,
/// map signal name to Signal
signals: BTreeMap<String, Signal<'ctx>>,
signals: BTreeMap<String, typed_ir::Signal>,
/// incrementing counter for unique IDs
ids: Counter,
}
impl<'ctx> Context<'ctx> {
fn get_signal(&self, signame: &str) -> Option<&Signal> {
self.signals.get(signame)
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(),
}
}
fn try_get_signal(&self, signame: &str) -> Result<&Signal, CompileError> {
self.get_signal(signame).ok_or_else(|| {
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()))
})
}
}
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_type(&self, typename: &str) -> Result<Type, CompileError> {
self.typenames.get(typename).copied().ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(typename.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")
fn try_get_callable(&self, callname: &str) -> Result<&Callable, CompileError> {
self.callables.get(callname).ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(callname.to_owned()))
})
}
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(),
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),
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| lower_expression(ctx, module, expr))
.map(|expr| self.type_expression(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)
}
let callable = ctx
.callables
.get(call.name.fragment() as &str)
.ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(
call.name.fragment().to_string(),
))
})?;
fn type_comb(
&mut self,
comb: &parser::comb::CombBlock,
) -> Result<typed_ir::Block, CompileError> {
let mut signals = Vec::new();
if args_resolved.len() != callable.argcount() {
return Err(CompileError::new(CompileErrorKind::BadArgCount {
expected: callable.argcount(),
received: args_resolved.len(),
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,
}));
}
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)
Ok(typed_ir::Block {
signals,
expr: root_expr,
})
}
// 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)?,
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);
}
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;
pub struct Callable<'ty> {
pub struct Callable {
pub name: String,
pub args: Vec<(Option<String>, Type<'ty>)>,
pub ret_type: Option<Type<'ty>>,
pub args: Vec<(Option<String>, Type)>,
pub ret_type: Option<Type>,
}
impl<'ty> Callable<'ty> {
impl<'ty> Callable {
pub fn name(&self) -> &str {
&self.name
}

256
src/frontend/lowering.rs Normal file
View File

@ -0,0 +1,256 @@
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,15 +1,35 @@
use super::types::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>,
/// 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,
}
struct Signal<'ty> {
pub id: u32,
pub typ: Type<'ty>,
#[derive(Debug, Clone)]
pub enum ExprKind {
Literal,
Path(DefId),
Call { called: DefId, args: Vec<Expr> },
}
struct Expression {}
#[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,
}

View File

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

View File

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

View File

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

View File

@ -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::Xor),
map(token(tk::BitAnd), |_| BinOpKind::Xor),
map(token(tk::BitOr), |_| BinOpKind::Or),
map(token(tk::BitAnd), |_| BinOpKind::And),
))(input)
}