start interning types

This commit is contained in:
NotAFile 2022-02-15 21:32:55 +01:00
parent 805acee3c5
commit 6148c599b8
5 changed files with 165 additions and 155 deletions

View File

@ -39,7 +39,8 @@ 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![
@ -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 // 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)];
@ -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![ vec![
make_binop_callable("and", "$and"), make_binop_callable("and", "$and"),
make_binop_callable("or", "$or"), make_binop_callable("or", "$or"),
@ -74,3 +75,4 @@ pub fn get_builtins<'ctx>() -> Vec<Callable<'ctx>> {
make_unnop_callable("reduce_or", "$reduce_or"), make_unnop_callable("reduce_or", "$reduce_or"),
] ]
} }
*/

View File

@ -1,11 +1,10 @@
use std::borrow::Borrow;
use std::cell::Cell; use std::cell::Cell;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use super::parser; use super::parser;
use crate::rtlil; use crate::rtlil;
pub use callable::Callable; pub use callable::Callable;
pub use types::{make_primitives, Type, TypeStruct}; pub use types::{Type, TypeStruct, TypingContext};
mod callable; mod callable;
#[cfg(never)] #[cfg(never)]
@ -13,6 +12,7 @@ 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; use crate::builtin_cells::get_builtins;
// pub use lowering::lower_module; // pub use lowering::lower_module;
@ -29,6 +29,7 @@ pub enum CompileErrorKind {
UndefinedReference(String), UndefinedReference(String),
BadArgCount { received: usize, expected: usize }, BadArgCount { received: usize, expected: usize },
TodoError(String), TodoError(String),
TypeError { expected: Type, found: Type },
} }
#[derive(Debug)] #[derive(Debug)]
@ -43,30 +44,31 @@ impl CompileError {
} }
/// A user-defined signal /// A user-defined signal
pub struct Signal<'ctx> { pub struct Signal {
/// 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<'ctx>, pub typ: Type,
// unique ID of the signal // unique ID of the signal
// pub uid: u64, // pub uid: u64,
} }
impl<'ctx> Signal<'ctx> { impl Signal {
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<'ctx> { pub struct Context {
/// map callable name to callable /// map callable name to callable
callables: BTreeMap<String, Callable<'ctx>>, callables: BTreeMap<String, Callable>,
/// types /// type names
types: BTreeMap<String, TypeStruct<'ctx>>, typenames: BTreeMap<String, Type>,
types: TypingContext,
/// map signal name to Signal /// map signal name to Signal
signals: BTreeMap<String, typed_ir::Signal<'ctx>>, signals: BTreeMap<String, typed_ir::Signal>,
/// incrementing counter for unique IDs /// incrementing counter for unique IDs
ids: Counter, ids: Counter,
} }
@ -84,50 +86,81 @@ impl Counter {
} }
} }
impl<'ctx> Context<'ctx> { impl Context {
pub fn new() -> Self { pub fn new() -> Self {
let tcx = TypingContext::new();
Context { Context {
callables: get_builtins() callables: BTreeMap::new(),
.into_iter()
.map(|clb| (clb.name().to_owned(), clb))
.collect(),
signals: BTreeMap::new(), signals: BTreeMap::new(),
types: make_primitives().into_iter().collect(), types: TypingContext::new(),
typenames: [("Logic".to_string(), tcx.primitives.logic)].into(),
ids: Counter::new(), ids: Counter::new(),
} }
} }
fn get_signal(&self, signame: &str) -> Option<&typed_ir::Signal> {
self.signals.get(signame)
}
fn try_get_signal(&self, signame: &str) -> Result<&typed_ir::Signal, CompileError> { fn try_get_signal(&self, signame: &str) -> Result<&typed_ir::Signal, CompileError> {
self.get_signal(signame).ok_or_else(|| { 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(&'ctx self, typename: &str) -> Result<Type<'ctx>, CompileError> { fn try_get_type(&self, typename: &str) -> Result<Type, CompileError> {
self.types.get(typename).ok_or_else(|| { self.typenames.get(typename).map(|t| *t).ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(typename.to_owned())) CompileError::new(CompileErrorKind::UndefinedReference(typename.to_owned()))
}) })
} }
fn try_get_callable(&self, callname: &str) -> Result<&Callable, CompileError> {
self.callables.get(callname).map(|t| t).ok_or_else(|| {
CompileError::new(CompileErrorKind::UndefinedReference(callname.to_owned()))
})
}
fn type_expression( fn type_expression(
&self, &self,
expr: &parser::expression::Expression, expr: &parser::expression::Expression,
) -> Result<typed_ir::Expr, CompileError> { ) -> Result<typed_ir::Expr, CompileError> {
let typ = match expr { use parser::expression::Expression;
parser::expression::Expression::Path(name) => self.try_get_signal(name)?.typ, let id = typed_ir::ExprId(self.ids.next() as u32);
parser::expression::Expression::Literal(_) => todo!(), let t_expr = match expr {
parser::expression::Expression::UnOp(op) => self.type_expression(&op.a)?.typ, Expression::Path(name) => {
parser::expression::Expression::BinOp(_) => todo!(), let signal = self.try_get_signal(name)?;
parser::expression::Expression::Call(call) => todo!(), 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,
}
}
Expression::Call(call) => {
let args_resolved = call
.args
.iter()
.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(typed_ir::Expr { Ok(t_expr)
id: 0,
inputs: vec![],
typ: typ,
})
} }
fn type_comb( fn type_comb(
@ -141,10 +174,10 @@ impl<'ctx> Context<'ctx> {
let sig_typename = &port.net.typ; let sig_typename = &port.net.typ;
let sig_type = self.try_get_type(sig_typename.name.fragment())?; let sig_type = self.try_get_type(sig_typename.name.fragment())?;
let sig = typed_ir::Signal { let sig = typed_ir::Signal {
id: sig_id as u32, id: typed_ir::DefId(sig_id as u32),
typ: sig_type, typ: sig_type,
}; };
signals.push(sig); signals.push(sig.clone());
self.signals.insert(port.net.name.to_string(), sig); self.signals.insert(port.net.name.to_string(), sig);
} }
@ -153,16 +186,23 @@ impl<'ctx> Context<'ctx> {
let root_expr = self.type_expression(&comb.expr)?; 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 { Ok(typed_ir::Block {
signals, signals,
expr: root_expr, expr: root_expr,
}) })
} }
pub fn type_module( pub fn type_module(&mut self, module: parser::Module) -> Result<typed_ir::Block, CompileError> {
&'ctx mut self,
module: parser::Module,
) -> Result<typed_ir::Block<'ctx>, CompileError> {
for item in module.items { for item in module.items {
let block = match &item { let block = match &item {
parser::ModuleItem::Comb(comb) => self.type_comb(comb)?, parser::ModuleItem::Comb(comb) => self.type_comb(comb)?,

View File

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

View File

@ -1,22 +1,35 @@
use super::{types::Type, Context}; 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 /// an abstract element that performs some kind of computation on inputs
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct Expr<'ty> { pub struct Expr {
pub id: u32, pub id: ExprId,
pub inputs: Vec<Expr<'ty>>, pub kind: ExprKind,
pub typ: Type<'ty>, pub typ: Type,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub 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)]
pub struct Signal {
pub id: DefId,
pub typ: Type,
} }
/// A block of HDL code, e.g. comb block /// A block of HDL code, e.g. comb block
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct Block<'ty> { pub struct Block {
pub signals: Vec<Signal<'ty>>, pub signals: Vec<Signal>,
pub expr: Expr<'ty>, pub expr: Expr,
} }

View File

@ -1,42 +1,46 @@
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<'ty> = &'ty TypeStruct<'ty>; pub type Type = InternedType;
pub struct TypeStruct<'ty> { #[derive(Debug, Copy, Clone, PartialEq)]
kind: TypeKind<'ty>, pub struct InternedType(usize);
pub struct TypeStruct {
kind: TypeKind,
} }
#[derive(Debug)] #[derive(Debug)]
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<'ty>), Logic(ElabData),
/// UInt of generic width /// UInt of generic width
UInt(ElabData<'ty>), UInt(ElabData),
/// Callable /// Callable
Callable, Callable,
} }
#[derive(Debug)] #[derive(Debug)]
struct ElabData<'ty> { struct ElabData {
typ: Type<'ty>, typ: Type,
value: ElabValue<'ty>, value: ElabValue,
} }
#[derive(Debug)] #[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<'ty>), Concrete(ElabValueData),
} }
#[derive(Debug)] #[derive(Debug)]
enum ElabValueData<'ty> { enum ElabValueData {
U32(u32), U32(u32),
Bytes(&'ty [u8]), Bytes(Vec<u8>),
} }
/// Types that are only valid during Elaboration /// Types that are only valid during Elaboration
@ -46,98 +50,49 @@ enum ElabKind {
Num, Num,
} }
/// Helper functions to create primitive types pub struct PrimitiveTypes {
impl<'ty> TypeStruct<'ty> { pub elabnum: Type,
/// a logic signal with inferred width pub logic: Type,
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 {
kind: TypeKind::Logic(ElabData { types: vec![TypeStruct {
typ: &TypeStruct { kind: TypeKind::Logic(ElabData {
kind: TypeKind::ElabType(ElabKind::Num), typ: primitives.elabnum,
}, value: ElabValue::Infer,
value: ElabValue::Infer, }),
}), }],
primitives,
} }
} }
/// a logic signal with known width pub fn add(&mut self, typ: TypeStruct) -> Type {
pub fn logic_width(width: u32) -> Self { let id = self.types.len();
Self { self.types.push(typ);
kind: TypeKind::Logic(ElabData::from_u32(width)), InternedType(id)
}
} }
/// return an elaboration number type pub fn get(&self, typ: Type) -> &TypeStruct {
pub fn elab_num() -> Self { &self.types[typ.0]
Self {
kind: TypeKind::ElabType(ElabKind::Num),
}
} }
pub fn bit_width(&self) -> Option<u32> { pub fn pretty_type(&self, w: &mut dyn std::fmt::Write, typ: Type) -> std::fmt::Result {
match &self.kind { match &self.get(typ).kind {
// elab types are not representable in hardware TypeKind::ElabType(val) => write!(w, "{{{:?}}}", val),
TypeKind::ElabType(_) => None, TypeKind::Logic(_) => todo!(),
TypeKind::Logic(data) => data.try_u32(),
TypeKind::UInt(_) => todo!(), TypeKind::UInt(_) => todo!(),
// callables are not representable in hardware
TypeKind::Callable => None,
}
}
pub fn genparam_count(&self) -> u32 {
match self.kind {
TypeKind::ElabType(_) => todo!(),
TypeKind::Logic(_) => 1,
TypeKind::UInt(_) => 1,
TypeKind::Callable => todo!(), TypeKind::Callable => todo!(),
} }
} }
} }
impl std::fmt::Debug for TypeStruct<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
TypeKind::Logic(width) => {
if let Some(num) = width.try_u32() {
write!(f, "Logic<{}>", num)
} else {
write!(f, "Logic<?>")
}
}
_ => f
.debug_struct("TypeStruct")
.field("kind", &self.kind)
.finish(),
}
}
}
/// Helper functions to create primitive elaboration values
impl<'ty> ElabData<'ty> {
/// an integer
pub fn from_u32(val: u32) -> Self {
Self {
typ: &TypeStruct {
kind: TypeKind::ElabType(ElabKind::Num),
},
value: ElabValue::Concrete(ElabValueData::U32(val)),
}
}
/// return Some(u32) if this is a number
pub fn try_u32(&self) -> Option<u32> {
// TODO: assert this is actually a number
match &self.value {
ElabValue::Infer => None,
ElabValue::Concrete(val) => match val {
ElabValueData::U32(num) => Some(*num),
ElabValueData::Bytes(_) => todo!(),
},
}
}
}
pub fn make_primitives() -> Vec<(String, TypeStruct<'static>)> {
vec![("Logic".to_string(), TypeStruct::logic_infer())]
}