Compare commits

..

5 Commits

Author SHA1 Message Date
NotAFile 7fea40208d start reworking syntax for stdlib 2022-01-24 00:10:09 +01:00
NotAFile 0d9abac065 cargo fmt 2022-01-23 22:52:06 +01:00
NotAFile b22c348d8f use package system 2022-01-23 22:51:39 +01:00
NotAFile a1f953e989 start on package system 2022-01-23 21:52:08 +01:00
NotAFile ec87f29c5c break things by adding first hacky type system 2022-01-23 21:04:19 +01:00
9 changed files with 246 additions and 97 deletions

7
lib/builtins/main.hyd Normal file
View File

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

View File

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

View File

@ -4,6 +4,11 @@ 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;
@ -29,48 +34,19 @@ 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 {
pub struct Signal<'ctx> {
/// 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,
pub typ: Type<'ctx>,
// unique ID of the signal
// pub uid: u64,
}
impl Signal {
impl<'ctx> Signal<'ctx> {
fn sigspec(&self) -> rtlil::SigSpec {
rtlil::SigSpec::Wire(self.il_id.to_owned())
}
@ -82,14 +58,16 @@ struct ProcContext {
next_sigs: BTreeMap<String, rtlil::SigSpec>,
}
struct Context {
struct Context<'ctx> {
/// map callable name to callable
callables: BTreeMap<String, Callable>,
callables: BTreeMap<String, Callable<'ctx>>,
/// types
types: Vec<TypeStruct<'ctx>>,
/// map signal name to Signal
signals: BTreeMap<String, Signal>,
signals: BTreeMap<String, Signal<'ctx>>,
}
impl Context {
impl<'ctx> Context<'ctx> {
fn get_signal(&self, signame: &str) -> Option<&Signal> {
self.signals.get(signame)
}
@ -269,22 +247,22 @@ fn lower_expression(
))
})?;
if args_resolved.len() != callable.args.len() {
if args_resolved.len() != callable.argcount() {
return Err(CompileError::new(CompileErrorKind::BadArgCount {
expected: callable.args.len(),
expected: callable.argcount(),
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
@ -307,24 +285,30 @@ 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));
let mut ir_module = rtlil::Module::new(make_pubid(pa_module.name.fragment()));
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.to_owned(),
il_id: make_pubid(port.net.name),
typ: Type::Wire(GenericParam::Solved(port.net.width.unwrap_or(1) as u32)),
name: port.net.name.fragment().to_string(),
il_id: make_pubid(port.net.name.fragment()),
typ: sigtype,
};
let sig = context
.signals
.entry(port.net.name.to_owned())
.entry(port.net.name.fragment().to_string())
.or_insert(sig);
let dir_option = match port.direction {
@ -333,7 +317,7 @@ pub fn lower_module(pa_module: parser::Module) -> Result<String, CompileError> {
};
let wire = rtlil::Wire::new(
sig.il_id.to_owned(),
port.net.width.unwrap_or(1) as u32,
TODO_WIDTH,
Some(dir_option),
);
ir_module.add_wire(wire);

17
src/frontend/callable.rs Normal file
View File

@ -0,0 +1,17 @@
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()
}
}

84
src/frontend/types.rs Normal file
View File

@ -0,0 +1,84 @@
/// 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,6 +1,7 @@
mod builtin_cells;
mod frontend;
mod literals;
mod package;
mod parser;
mod rtlil;
@ -25,7 +26,14 @@ struct Opt {
fn main() {
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();
infile
.read_to_string(&mut input)

37
src/package.rs Normal file
View File

@ -0,0 +1,37 @@
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,6 +38,22 @@ 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)
}
@ -46,10 +62,16 @@ 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: &'a str,
pub width: Option<u64>,
pub name: Span<'a>,
pub typ: TypeName<'a>,
pub value: Option<(u64, u64)>,
}
@ -93,14 +115,12 @@ pub enum Expression<'a> {
fn declaration(i: Span) -> IResult<Span, NetDecl> {
map(
tuple((
ws0(alt((tag("reg"), tag("wire")))),
opt(ws0(widthspec)),
identifier,
separated_pair(identifier, ws0(char(':')), typename),
opt(preceded(ws0(char('=')), intliteral)),
)),
|(_, width, ident, value)| NetDecl {
name: ident.fragment(),
width,
|((ident, typ), value)| NetDecl {
name: ident,
typ,
value,
},
)(i)
@ -172,7 +192,7 @@ fn assign_statement(input: Span) -> IResult<Span, Assign> {
}
pub fn parse(input: Span) -> IResult<Span, Module> {
module(input)
ws0(module)(input)
}
#[cfg(test)]

View File

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