Compare commits

..

No commits in common. "7fea40208d52340c2404758ff7ffa0b79170bc52" and "6317987ed6ee8a555639ea76cabdbcb130e18222" have entirely different histories.

9 changed files with 97 additions and 246 deletions

View File

@ -1,7 +0,0 @@
module reduce_or (
a: Logic
)
-> Logic<1> {
}

View File

@ -1,5 +1,4 @@
use crate::frontend::types::{Type, TypeStruct}; use crate::frontend::{CallArgument, Callable, Type};
use crate::frontend::Callable;
use crate::rtlil; use crate::rtlil;
use crate::rtlil::SigSpec; use crate::rtlil::SigSpec;
@ -39,32 +38,39 @@ 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(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![ let args = vec![
(Some("a".to_owned()), logic_type), CallArgument {
(Some("b".to_owned()), logic_type), name: "A".to_owned(),
atype: Type::wire(),
},
CallArgument {
name: "B".to_owned(),
atype: Type::wire(),
},
]; ];
Callable { Callable {
name: name.to_owned(), name: name.to_owned(),
args, args,
ret_type: Some(logic_type), ret: Type::wire(),
instantiate: Box::new(move |id, args, ret| instantiate_binop(celltype, id, args, ret)),
} }
} }
fn make_unnop_callable<'ctx>(name: &str, celltype: &'static str) -> Callable<'ctx> { fn make_unnop_callable(name: &str, celltype: &'static str) -> Callable {
// FIXME: CRIMES CRIMES CRIMES let args = vec![CallArgument {
let logic_type: &'static TypeStruct = Box::leak(Box::new(TypeStruct::logic_infer())); name: "A".to_owned(),
let args = vec![(Some("A".to_owned()), logic_type)]; atype: Type::wire(),
}];
Callable { Callable {
name: name.to_owned(), name: name.to_owned(),
args, args,
ret_type: Some(logic_type), ret: Type::wire(),
instantiate: Box::new(move |id, args, ret| instantiate_unop(celltype, id, args, ret)),
} }
} }
pub fn get_builtins<'ctx>() -> Vec<Callable<'ctx>> { pub fn get_builtins() -> Vec<Callable> {
vec![ vec![
make_binop_callable("and", "$and"), make_binop_callable("and", "$and"),
make_binop_callable("or", "$or"), make_binop_callable("or", "$or"),

View File

@ -4,11 +4,6 @@ use crate::builtin_cells::get_builtins;
use crate::parser; use crate::parser;
use crate::rtlil; use crate::rtlil;
use crate::rtlil::RtlilWrite; use crate::rtlil::RtlilWrite;
pub use callable::Callable;
pub use types::{Type, TypeStruct};
mod callable;
pub mod types;
/// 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;
@ -34,19 +29,48 @@ impl CompileError {
} }
} }
pub enum GenericParam<T> {
Unsolved,
Solved(T),
}
pub enum Type {
/// a wire of some width
Wire(GenericParam<u32>),
}
impl Type {
pub fn wire() -> Self {
Self::Wire(GenericParam::Unsolved)
}
}
pub struct CallArgument {
pub name: String,
pub atype: Type,
}
// module that can be instantiated like a function
pub struct Callable {
pub name: String,
pub args: Vec<CallArgument>,
pub ret: Type,
pub instantiate: Box<dyn Fn(&str, &[rtlil::SigSpec], &rtlil::SigSpec) -> rtlil::Cell>,
}
/// 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())
} }
@ -58,16 +82,14 @@ struct ProcContext {
next_sigs: BTreeMap<String, rtlil::SigSpec>, next_sigs: BTreeMap<String, rtlil::SigSpec>,
} }
struct Context<'ctx> { struct Context {
/// map callable name to callable /// map callable name to callable
callables: BTreeMap<String, Callable<'ctx>>, callables: BTreeMap<String, Callable>,
/// types
types: Vec<TypeStruct<'ctx>>,
/// map signal name to Signal /// map signal name to Signal
signals: BTreeMap<String, Signal<'ctx>>, signals: BTreeMap<String, Signal>,
} }
impl<'ctx> Context<'ctx> { impl Context {
fn get_signal(&self, signame: &str) -> Option<&Signal> { fn get_signal(&self, signame: &str) -> Option<&Signal> {
self.signals.get(signame) self.signals.get(signame)
} }
@ -247,22 +269,22 @@ fn lower_expression(
)) ))
})?; })?;
if args_resolved.len() != callable.argcount() { if args_resolved.len() != callable.args.len() {
return Err(CompileError::new(CompileErrorKind::BadArgCount { return Err(CompileError::new(CompileErrorKind::BadArgCount {
expected: callable.argcount(), expected: callable.args.len(),
received: args_resolved.len(), received: args_resolved.len(),
})); }));
} }
let cell_id = module.make_genid(&callable.name()); let cell_id = module.make_genid(&callable.name);
let output_gen_id = format!("{}$out", &cell_id); let output_gen_id = format!("{}$out", &cell_id);
module.add_wire(rtlil::Wire::new(&output_gen_id, TODO_WIDTH, None)); module.add_wire(rtlil::Wire::new(&output_gen_id, TODO_WIDTH, None));
let output_gen_wire = rtlil::SigSpec::Wire(output_gen_id); let output_gen_wire = rtlil::SigSpec::Wire(output_gen_id);
// let cell = let cell =
// (*callable.instantiate)(&cell_id, args_resolved.as_slice(), &output_gen_wire); (*callable.instantiate)(&cell_id, args_resolved.as_slice(), &output_gen_wire);
// module.add_cell(cell); module.add_cell(cell);
Ok(output_gen_wire) Ok(output_gen_wire)
} }
// TODO: instantiate operators directly here instead of desugaring, once the callable infrastructure improves // TODO: instantiate operators directly here instead of desugaring, once the callable infrastructure improves
@ -285,30 +307,24 @@ fn lower_assignment(
pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> { pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
let mut writer = rtlil::ILWriter::new(); let mut writer = rtlil::ILWriter::new();
let mut ir_module = rtlil::Module::new(make_pubid(pa_module.name.fragment())); let mut ir_module = rtlil::Module::new(make_pubid(pa_module.name));
let mut context = Context { let mut context = Context {
callables: get_builtins() callables: get_builtins()
.into_iter() .into_iter()
.map(|clb| (clb.name().to_owned(), clb)) .map(|clb| (clb.name.to_owned(), clb))
.collect(), .collect(),
signals: BTreeMap::new(), signals: BTreeMap::new(),
types: vec![],
}; };
writer.write_line("autoidx 1"); writer.write_line("autoidx 1");
for (idx, port) in pa_module.ports.iter().enumerate() { for (idx, port) in pa_module.ports.iter().enumerate() {
// FIXME: Actually resolve types
let sigtype = TypeStruct::logic_width(TODO_WIDTH);
// FIXME: CRIMES CRIMES CRIMES
let sigtype = Box::leak(Box::new(sigtype));
let sig = Signal { let sig = Signal {
name: port.net.name.fragment().to_string(), name: port.net.name.to_owned(),
il_id: make_pubid(port.net.name.fragment()), il_id: make_pubid(port.net.name),
typ: sigtype, typ: Type::Wire(GenericParam::Solved(port.net.width.unwrap_or(1) as u32)),
}; };
let sig = context let sig = context
.signals .signals
.entry(port.net.name.fragment().to_string()) .entry(port.net.name.to_owned())
.or_insert(sig); .or_insert(sig);
let dir_option = match port.direction { let dir_option = match port.direction {
@ -317,7 +333,7 @@ pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
}; };
let wire = rtlil::Wire::new( let wire = rtlil::Wire::new(
sig.il_id.to_owned(), sig.il_id.to_owned(),
TODO_WIDTH, port.net.width.unwrap_or(1) as u32,
Some(dir_option), Some(dir_option),
); );
ir_module.add_wire(wire); ir_module.add_wire(wire);

View File

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

View File

@ -1,84 +0,0 @@
/// Alias for &TypeStruct to reduce repetition
/// and make futura migration to interning
/// easier
pub type Type<'ty> = &'ty TypeStruct<'ty>;
pub struct TypeStruct<'ty> {
kind: TypeKind<'ty>,
}
pub enum TypeKind<'ty> {
/// Elaboration-time types
ElabType(ElabKind),
/// Signal/Wire of generic width
Logic(ElabData<'ty>),
/// UInt of generic width
UInt(ElabData<'ty>),
/// Callable
Callable,
}
struct ElabData<'ty> {
typ: Type<'ty>,
value: ElabValue<'ty>,
}
enum ElabValue<'ty> {
/// the value is not given and has to be inferred
Infer,
/// the value is given as some byte representation
Concrete(ElabValueData<'ty>),
}
enum ElabValueData<'ty> {
U32(u32),
Bytes(&'ty [u8]),
}
/// Types that are only valid during Elaboration
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 {
Self {
kind: TypeKind::Logic(ElabData {
typ: &TypeStruct {
kind: TypeKind::ElabType(ElabKind::Num),
},
value: ElabValue::Infer,
}),
}
}
/// a logic signal with known width
pub fn logic_width(width: u32) -> Self {
Self {
kind: TypeKind::Logic(ElabData::u32(width)),
}
}
/// 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)),
}
}
}

View File

@ -1,7 +1,6 @@
mod builtin_cells; mod builtin_cells;
mod frontend; mod frontend;
mod literals; mod literals;
mod package;
mod parser; mod parser;
mod rtlil; mod rtlil;
@ -26,14 +25,7 @@ struct Opt {
fn main() { fn main() {
let opt = Opt::from_args(); let opt = Opt::from_args();
// let mut infile = File::open(opt.input).expect("could not open file"); let mut infile = File::open(opt.input).expect("could not open file");
let packages = package::PackageRegistry::new();
let mut infile = packages
.get("builtins")
.expect("no package")
.open()
.expect("could not open file");
let mut input = String::new(); let mut input = String::new();
infile infile
.read_to_string(&mut input) .read_to_string(&mut input)

View File

@ -1,37 +0,0 @@
use std::collections::BTreeMap;
use std::fs::File;
use std::path::PathBuf;
pub struct Package {
name: String,
path: PathBuf,
}
impl Package {
pub fn open(&self) -> Result<File, std::io::Error> {
let filepath = self.path.join("main.hyd");
File::open(filepath)
}
}
pub struct PackageRegistry {
packages: BTreeMap<String, Package>,
}
impl PackageRegistry {
pub fn new() -> Self {
let mut packages = BTreeMap::new();
packages.insert(
"builtins".to_string(),
Package {
name: "builtins".to_string(),
path: "./lib/builtins/".into(),
},
);
Self { packages }
}
pub fn get(&self, name: &str) -> Option<&Package> {
self.packages.get(name)
}
}

View File

@ -38,22 +38,6 @@ fn identifier(input: Span) -> IResult<Span, Span> {
))(input) ))(input)
} }
// TODO: allow recursive generics
fn typename(input: Span) -> IResult<Span, TypeName> {
map(
tuple((
identifier,
opt(delimited(char('<'), ws0(expression), char('>')))
)),
|(ident, _)| {
TypeName {
name: ident,
generics: ()
}
}
)(input)
}
fn widthspec(input: Span) -> IResult<Span, u64> { fn widthspec(input: Span) -> IResult<Span, u64> {
delimited(char('['), ws0(decimal), char(']'))(input) delimited(char('['), ws0(decimal), char(']'))(input)
} }
@ -62,16 +46,10 @@ fn intliteral(input: Span) -> IResult<Span, (u64, u64)> {
tuple((terminated(decimal, char('\'')), alt((decimal, hexadecimal))))(input) tuple((terminated(decimal, char('\'')), alt((decimal, hexadecimal))))(input)
} }
#[derive(Debug)]
pub struct TypeName<'a> {
name: Span<'a>,
generics: (),
}
#[derive(Debug)] #[derive(Debug)]
pub struct NetDecl<'a> { pub struct NetDecl<'a> {
pub name: Span<'a>, pub name: &'a str,
pub typ: TypeName<'a>, pub width: Option<u64>,
pub value: Option<(u64, u64)>, pub value: Option<(u64, u64)>,
} }
@ -115,12 +93,14 @@ pub enum Expression<'a> {
fn declaration(i: Span) -> IResult<Span, NetDecl> { fn declaration(i: Span) -> IResult<Span, NetDecl> {
map( map(
tuple(( tuple((
separated_pair(identifier, ws0(char(':')), typename), ws0(alt((tag("reg"), tag("wire")))),
opt(ws0(widthspec)),
identifier,
opt(preceded(ws0(char('=')), intliteral)), opt(preceded(ws0(char('=')), intliteral)),
)), )),
|((ident, typ), value)| NetDecl { |(_, width, ident, value)| NetDecl {
name: ident, name: ident.fragment(),
typ, width,
value, value,
}, },
)(i) )(i)
@ -192,7 +172,7 @@ fn assign_statement(input: Span) -> IResult<Span, Assign> {
} }
pub fn parse(input: Span) -> IResult<Span, Module> { pub fn parse(input: Span) -> IResult<Span, Module> {
ws0(module)(input) module(input)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -4,14 +4,14 @@ use nom::{
character::complete::{char, multispace1}, character::complete::{char, multispace1},
combinator::{consumed, map}, combinator::{consumed, map},
error::context, error::context,
multi::{many0, separated_list0}, multi::{many1, separated_list0},
sequence::{delimited, terminated, tuple, preceded}, sequence::{delimited, terminated, tuple},
}; };
use crate::parser::{ use crate::parser::{
assign_statement, declaration, identifier, assign_statement, declaration, identifier,
proc::{proc_block, ProcBlock}, proc::{proc_block, ProcBlock},
ws0, Assign, IResult, NetDecl, Span, typename ws0, Assign, IResult, NetDecl, Span,
}; };
#[derive(Debug)] #[derive(Debug)]
@ -29,7 +29,7 @@ pub struct PortDecl<'a> {
#[derive(Debug)] #[derive(Debug)]
pub struct Module<'a> { pub struct Module<'a> {
pub name: Span<'a>, pub name: &'a str,
pub ports: Vec<PortDecl<'a>>, pub ports: Vec<PortDecl<'a>>,
pub items: Vec<ModuleItem<'a>>, pub items: Vec<ModuleItem<'a>>,
} }
@ -42,18 +42,22 @@ pub enum ModuleItem<'a> {
fn port_decl(i: Span) -> IResult<Span, PortDecl> { fn port_decl(i: Span) -> IResult<Span, PortDecl> {
map( map(
consumed( consumed(tuple((
alt((
map(tag("input"), |_| PortDirection::Input),
map(tag("output"), |_| PortDirection::Output),
)),
declaration, declaration,
), ))),
|(pos, net)| PortDecl { |(pos, (direction, net))| PortDecl {
pos, pos,
direction: PortDirection::Input, direction,
net, net,
}, },
)(i) )(i)
} }
fn inputs_list(input: Span) -> IResult<Span, Vec<PortDecl>> { fn ports_list(input: Span) -> IResult<Span, Vec<PortDecl>> {
separated_list0(ws0(char(',')), ws0(port_decl))(input) separated_list0(ws0(char(',')), ws0(port_decl))(input)
} }
@ -83,14 +87,12 @@ pub fn module(input: Span) -> IResult<Span, Module> {
tuple(( tuple((
tag("module"), tag("module"),
ws0(identifier), ws0(identifier),
ws0(delimited(char('('), ws0(inputs_list), char(')'))), ws0(delimited(char('('), ws0(ports_list), char(')'))),
ws0(preceded(tag("->"), ws0(typename))), ws0(delimited(char('{'), many1(ws0(module_item)), char('}'))),
ws0(delimited(char('{'), ws0(many0(ws0(module_item))), char('}'))),
)), )),
|(_, name, inputs, ret, items)| Module { |(_, name, ports, items)| Module {
name, name: (*name.fragment()),
// TODO: add back in returns ports,
ports: inputs,
items, items,
}, },
), ),