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::Callable;
use crate::frontend::{CallArgument, Callable, Type};
use crate::rtlil;
use crate::rtlil::SigSpec;
@ -39,32 +38,39 @@ fn instantiate_binop(celltype: &str, id: &str, args: &[SigSpec], ret: &SigSpec)
cell
}
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()));
fn make_binop_callable(name: &str, celltype: &'static str) -> Callable {
let args = vec![
(Some("a".to_owned()), logic_type),
(Some("b".to_owned()), logic_type),
CallArgument {
name: "A".to_owned(),
atype: Type::wire(),
},
CallArgument {
name: "B".to_owned(),
atype: Type::wire(),
},
];
Callable {
name: name.to_owned(),
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> {
// 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)];
fn make_unnop_callable(name: &str, celltype: &'static str) -> Callable {
let args = vec![CallArgument {
name: "A".to_owned(),
atype: Type::wire(),
}];
Callable {
name: name.to_owned(),
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![
make_binop_callable("and", "$and"),
make_binop_callable("or", "$or"),

View File

@ -4,11 +4,6 @@ use crate::builtin_cells::get_builtins;
use crate::parser;
use crate::rtlil;
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
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
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())
}
@ -58,16 +82,14 @@ struct ProcContext {
next_sigs: BTreeMap<String, rtlil::SigSpec>,
}
struct Context<'ctx> {
struct Context {
/// map callable name to callable
callables: BTreeMap<String, Callable<'ctx>>,
/// types
types: Vec<TypeStruct<'ctx>>,
callables: BTreeMap<String, Callable>,
/// 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> {
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 {
expected: callable.argcount(),
expected: callable.args.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);
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);
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
@ -285,30 +307,24 @@ fn lower_assignment(
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(pa_module.name.fragment()));
let mut ir_module = rtlil::Module::new(make_pubid(pa_module.name));
let mut context = Context {
callables: get_builtins()
.into_iter()
.map(|clb| (clb.name().to_owned(), clb))
.map(|clb| (clb.name.to_owned(), clb))
.collect(),
signals: BTreeMap::new(),
types: vec![],
};
writer.write_line("autoidx 1");
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 {
name: port.net.name.fragment().to_string(),
il_id: make_pubid(port.net.name.fragment()),
typ: sigtype,
name: port.net.name.to_owned(),
il_id: make_pubid(port.net.name),
typ: Type::Wire(GenericParam::Solved(port.net.width.unwrap_or(1) as u32)),
};
let sig = context
.signals
.entry(port.net.name.fragment().to_string())
.entry(port.net.name.to_owned())
.or_insert(sig);
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(
sig.il_id.to_owned(),
TODO_WIDTH,
port.net.width.unwrap_or(1) as u32,
Some(dir_option),
);
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 frontend;
mod literals;
mod package;
mod parser;
mod rtlil;
@ -26,14 +25,7 @@ struct Opt {
fn main() {
let opt = Opt::from_args();
// 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 infile = File::open(opt.input).expect("could not open file");
let mut input = String::new();
infile
.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)
}
// 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> {
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)
}
#[derive(Debug)]
pub struct TypeName<'a> {
name: Span<'a>,
generics: (),
}
#[derive(Debug)]
pub struct NetDecl<'a> {
pub name: Span<'a>,
pub typ: TypeName<'a>,
pub name: &'a str,
pub width: Option<u64>,
pub value: Option<(u64, u64)>,
}
@ -115,12 +93,14 @@ pub enum Expression<'a> {
fn declaration(i: Span) -> IResult<Span, NetDecl> {
map(
tuple((
separated_pair(identifier, ws0(char(':')), typename),
ws0(alt((tag("reg"), tag("wire")))),
opt(ws0(widthspec)),
identifier,
opt(preceded(ws0(char('=')), intliteral)),
)),
|((ident, typ), value)| NetDecl {
name: ident,
typ,
|(_, width, ident, value)| NetDecl {
name: ident.fragment(),
width,
value,
},
)(i)
@ -192,7 +172,7 @@ fn assign_statement(input: Span) -> IResult<Span, Assign> {
}
pub fn parse(input: Span) -> IResult<Span, Module> {
ws0(module)(input)
module(input)
}
#[cfg(test)]

View File

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