Skip to content

Commit

Permalink
add use lifetimes
Browse files Browse the repository at this point in the history
  • Loading branch information
UnsignedByte committed Mar 7, 2025
1 parent 25e2eda commit 89bbe7e
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 57 deletions.
33 changes: 22 additions & 11 deletions crates/ast/src/component.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{Command, Id, Signature};
use fil_gen as gen;
use fgen::GenConfig;
use fil_gen as fgen;
use fil_utils::{self as utils, AttrCtx};
use gen::GenConfig;
use std::path::PathBuf;

#[derive(Default)]
Expand All @@ -10,15 +10,19 @@ pub struct Extern {
pub path: String,
pub comps: Vec<Signature>,
/// name of the tool that generates this module
pub gen: Option<String>,
pub gen_tool: Option<String>,
}
impl Extern {
pub fn new(
path: String,
comps: Vec<Signature>,
gen: Option<String>,
gen_tool: Option<String>,
) -> Self {
Self { path, comps, gen }
Self {
path,
comps,
gen_tool,
}
}

pub fn map_path<F>(mut self, func: F) -> Self
Expand Down Expand Up @@ -60,7 +64,9 @@ pub struct Namespace {
impl Namespace {
/// Returns true if the namespace declares at least one generative module
pub fn requires_gen(&self) -> bool {
self.externs.iter().any(|Extern { gen, .. }| gen.is_some())
self.externs
.iter()
.any(|Extern { gen_tool, .. }| gen_tool.is_some())
}

/// Initialize the generator executor using the given generate definitions.
Expand All @@ -71,14 +77,19 @@ impl Namespace {
&self,
out_dir: Option<PathBuf>,
config: GenConfig,
) -> gen::GenExec {
let mut gen_exec = gen::GenExec::new(false, out_dir, config);
for Extern { path, gen, .. } in &self.externs {
let Some(tool_name) = gen else {
) -> fgen::GenExec {
let mut gen_exec = fgen::GenExec::new(false, out_dir, config);
for Extern { path, gen_tool, .. } in &self.externs {
let Some(tool_name) = gen_tool else {
continue;
};
let tool = gen_exec.register_tool_from_file(path.into());
assert!(&tool.name == tool_name, "Generate definition for tool `{}` does not match the tool name `{}`", tool_name, tool.name);
assert!(
&tool.name == tool_name,
"Generate definition for tool `{}` does not match the tool name `{}`",
tool_name,
tool.name
);
}
gen_exec
}
Expand Down
12 changes: 6 additions & 6 deletions crates/ast/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use fil_utils::{
};
use itertools::Itertools;
use pest::pratt_parser::{Assoc, Op, PrattParser};
use pest_consume::{match_nodes, Error, Parser};
use pest_consume::{Error, Parser, match_nodes};
use std::fs;
use std::hash::Hash;
use std::path::Path;
Expand Down Expand Up @@ -901,9 +901,9 @@ impl FilamentParser {
fn comp_or_ext(input: Node) -> ParseResult<BodyEl> {
Ok(match_nodes!(
input.into_children();
[external(sig)] => BodyEl::Ext(sig),
[generate(sig)] => BodyEl::Ext(sig),
[component(comp)] => BodyEl::Comp(comp),
[external(sig)] => BodyEl::Ext(Box::new(sig)),
[generate(sig)] => BodyEl::Ext(Box::new(sig)),
[component(comp)] => BodyEl::Comp(Box::new(comp)),
))
}

Expand All @@ -925,8 +925,8 @@ impl FilamentParser {

for m in mixed {
match m {
BodyEl::Ext(sig) => namespace.externs.push(sig),
BodyEl::Comp(comp) => namespace.components.push(comp),
BodyEl::Ext(sig) => namespace.externs.push(*sig),
BodyEl::Comp(comp) => namespace.components.push(*comp),
}
}
namespace
Expand Down
18 changes: 9 additions & 9 deletions crates/filament/src/ir_passes/mono/monomorphize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{
Base, CompKey, InstanceInfo, IntoBase, IntoUdl, MonoDeferred, MonoSig,
Underlying, UnderlyingComp,
};
use fil_gen as gen;
use fil_gen as fgen;
use fil_ir::{self as ir, Ctx, IndexStore};
use ir::{AddCtx, EntryPoint};
use itertools::Itertools;
Expand Down Expand Up @@ -68,13 +68,13 @@ pub struct Monomorphize<'a> {
/// Tracks which components are defined in which files
pub ext_map: HashMap<String, Vec<ir::CompIdx>>,
/// Generator executor
gen_exec: &'a mut Option<gen::GenExec>,
gen_exec: &'a mut Option<fgen::GenExec>,
}

impl<'a> Monomorphize<'a> {
fn new(
old: &'a ir::Context,
gen_exec: &'a mut Option<gen::GenExec>,
gen_exec: &'a mut Option<fgen::GenExec>,
) -> Self {
Monomorphize {
ctx: ir::Context::default(),
Expand Down Expand Up @@ -104,7 +104,7 @@ impl Monomorphize<'_> {
}

/// Generate an component using the `gen` framework
pub fn gen(
pub fn generated(
&mut self,
comp: Underlying<ir::Component>,
params: Vec<u64>,
Expand All @@ -117,14 +117,14 @@ impl Monomorphize<'_> {
let Some(tool) = &is.gen_tool else {
unreachable!("gen component does not have a tool")
};
let inst = gen::Instance {
let inst = fgen::Instance {
name: is.name.as_ref().to_string(),
parameters: params.iter().map(|p| p.to_string()).collect(),
};

// Running the tool returns the location of the Verilog file that
// contains the definition and mapping for existential parameters.
let gen::ToolOutput {
let fgen::ToolOutput {
name,
file,
exist_params,
Expand Down Expand Up @@ -241,7 +241,7 @@ impl Monomorphize<'_> {
}

if underlying.is_gen() {
return self.gen(comp, params, n_ck);
return self.generated(comp, params, n_ck);
}

// Copy the component signature if it is an external and return it.
Expand Down Expand Up @@ -275,7 +275,7 @@ impl Monomorphize<'_> {
/// Returns an empty context if there is no top-level component.
pub fn transform(
ctx: &ir::Context,
gen: &mut Option<gen::GenExec>,
generated: &mut Option<fgen::GenExec>,
) -> ir::Context {
let Some(entrypoint) = &ctx.entrypoint else {
log::warn!("Program has no entrypoint. Result will be empty.");
Expand All @@ -292,7 +292,7 @@ impl Monomorphize<'_> {

let entrypoint = entrypoint.ul();
// Monomorphize the entrypoint
let mut mono = Monomorphize::new(ctx, gen);
let mut mono = Monomorphize::new(ctx, generated);
let ck = CompKey::new(entrypoint, bindings.clone());
mono.monomorphize(ck.clone());

Expand Down
8 changes: 5 additions & 3 deletions crates/filament/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use std::fs;
/// Contains the bindings that are provided by the user.
pub struct ProvidedBindings {
/// Gen configuration variables
gen: GenConfig,
r#gen: GenConfig,
/// Parameters to give to the components
params: HashMap<String, Vec<u64>>,
}
Expand Down Expand Up @@ -69,7 +69,7 @@ fn run(opts: &cmdline::Opts) -> Result<(), u64> {
"`--out-dir <dir>` to store the generated files."
))
}
Some(ns.init_gen(opts.out_dir.clone(), provided_bindings.gen))
Some(ns.init_gen(opts.out_dir.clone(), provided_bindings.r#gen))
} else {
None
};
Expand Down Expand Up @@ -163,7 +163,9 @@ fn main() {
Err(err) => {
eprintln!("Compilation failed with {err} errors.");
if !opts.show_models {
eprintln!("Run with --show-models to generate assignments for failing constraints.");
eprintln!(
"Run with --show-models to generate assignments for failing constraints."
);
}
std::process::exit(1)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/gen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ fn main() {
.filter_level(opts.log_level)
.target(env_logger::Target::Stderr)
.init();
let mut gen = GenExec::new(opts.dry_run, None, GenConfig::default());
let mut g = GenExec::new(opts.dry_run, None, GenConfig::default());

// Deserialize the tool description
let desc = fs::read_to_string(opts.tool).unwrap();
let tool: fil_gen::Tool = toml::from_str(&desc).unwrap();
let name = tool.name.clone();
gen.register_tool(tool);
g.register_tool(tool);
// Deserialize the manifest file
let manifest_str = fs::read_to_string(opts.manifest).unwrap();
let manifest: fil_gen::Manifest = toml::from_str(&manifest_str).unwrap();

for instance in &manifest.modules {
gen.gen_instance(&name, instance);
g.gen_instance(&name, instance);
}
}
30 changes: 18 additions & 12 deletions crates/ir/src/from_ast/astconv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1071,10 +1071,10 @@ impl From<ast::Component> for ComponentTransform {
/// Convert an [ast::Extern] into an external/generated [ComponentTransform]
impl From<ast::Extern> for ComponentTransform {
fn from(ext: ast::Extern) -> Self {
let typ = if ext.gen.is_none() {
let typ = if ext.gen_tool.is_none() {
TypeInfo::External(ext.path)
} else {
TypeInfo::Generated(ext.gen.unwrap())
TypeInfo::Generated(ext.gen_tool.unwrap())
};
Self {
typ,
Expand Down Expand Up @@ -1110,16 +1110,22 @@ fn try_transform(ns: ast::Namespace) -> BuildRes<ir::Context> {
.externs
.into_iter()
// track (extern location / gen tool name, signature, body)
.flat_map(|ast::Extern { comps, gen, path }| {
comps.into_iter().map(move |comp| {
let typ = if let Some(name) = &gen {
TypeInfo::Generated(name.clone())
} else {
TypeInfo::External(path.clone())
};
ComponentTransform { typ, sig: comp }
})
})
.flat_map(
|ast::Extern {
comps,
gen_tool,
path,
}| {
comps.into_iter().map(move |comp| {
let typ = if let Some(name) = &gen_tool {
TypeInfo::Generated(name.clone())
} else {
TypeInfo::External(path.clone())
};
ComponentTransform { typ, sig: comp }
})
},
)
// add signatures of components as well as their command bodies
.chain(ns.components.into_iter().map(ComponentTransform::from))
.enumerate();
Expand Down
6 changes: 3 additions & 3 deletions crates/ir/src/utils/index_store.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{utils, utils::Idx, AddCtx, Ctx, MutCtx};
use crate::{AddCtx, Ctx, MutCtx, utils, utils::Idx};
use bitvec::vec::BitVec;
use std::{fmt::Display, marker::PhantomData};

Expand Down Expand Up @@ -89,7 +89,7 @@ where

/// Iterate over the valid indices in the store.
/// This can be useful because it allows mutable borrows of the owners of the store.
pub fn idx_iter(&self) -> impl Iterator<Item = I> {
pub fn idx_iter(&self) -> impl Iterator<Item = I> + use<T, I> {
self.valid
.clone()
.into_iter()
Expand All @@ -99,7 +99,7 @@ where
}

/// Iterate over the valid indices and the values in the store.
pub fn iter(&self) -> impl Iterator<Item = (I, &T)> + '_ {
pub fn iter(&self) -> impl Iterator<Item = (I, &T)> {
self.store
.iter()
.enumerate()
Expand Down
4 changes: 2 additions & 2 deletions crates/ir/src/utils/interned.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{utils, utils::Idx, AddCtx, Ctx};
use crate::{AddCtx, Ctx, utils, utils::Idx};
use std::{collections::HashMap, fmt::Display, rc::Rc};

#[derive(Clone)]
Expand Down Expand Up @@ -94,7 +94,7 @@ where

/// Iterator over indices of the interned values.
/// Useful since it does not take ownership of self.
pub fn idx_iter(&self) -> impl Iterator<Item = I> {
pub fn idx_iter(&self) -> impl Iterator<Item = I> + use<T, I> {
(0..self.store.len()).map(I::new)
}
}
Expand Down
3 changes: 2 additions & 1 deletion crates/utils/src/global_sym.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::{mem, sync};

use string_interner::{
backend::BucketBackend, symbol::SymbolU32, StringInterner,
StringInterner, backend::BucketBackend, symbol::SymbolU32,
};

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand All @@ -17,6 +17,7 @@ fn singleton() -> &'static mut Pool {
// SAFETY:
// - writing to the singleton is OK because we only do it one time
// - the ONCE guarantees that SINGLETON is init'ed before assume_init_ref
#[allow(static_mut_refs)]
unsafe {
ONCE.call_once(|| {
SINGLETON.write(Pool::new());
Expand Down
16 changes: 9 additions & 7 deletions crates/utils/src/gsym.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
use std::{mem, sync};
use string_interner::{
backend::BucketBackend, symbol::SymbolU32, StringInterner,
StringInterner, backend::BucketBackend, symbol::SymbolU32,
};

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GSym(SymbolU32);

type Pool = StringInterner<BucketBackend>;

fn singleton() -> &'static mut Pool {
fn singleton() -> *mut Pool {
static mut SINGLETON: mem::MaybeUninit<Pool> = mem::MaybeUninit::uninit();
static ONCE: sync::Once = sync::Once::new();

// SAFETY:
// - writing to the singleton is OK because we only do it one time
// - the ONCE guarantees that SINGLETON is init'ed before assume_init_ref
#[allow(static_mut_refs)]
unsafe {
ONCE.call_once(|| {
SINGLETON.write(Pool::new());
});
SINGLETON.assume_init_mut()

SINGLETON.as_mut_ptr() as *mut Pool
}
}

Expand All @@ -37,25 +39,25 @@ impl GSym {

impl From<&str> for GSym {
fn from(s: &str) -> Self {
GSym(singleton().get_or_intern(s))
GSym(unsafe { singleton().as_mut().unwrap().get_or_intern(s) })
}
}

impl From<String> for GSym {
fn from(s: String) -> Self {
GSym(singleton().get_or_intern(&s))
GSym(unsafe { singleton().as_mut().unwrap().get_or_intern(&s) })
}
}

impl From<&String> for GSym {
fn from(s: &String) -> Self {
GSym(singleton().get_or_intern(s))
GSym(unsafe { singleton().as_mut().unwrap().get_or_intern(s) })
}
}

impl From<GSym> for &'static str {
fn from(sym: GSym) -> Self {
singleton().resolve(sym.0).unwrap()
unsafe { singleton().as_ref().unwrap().resolve(sym.0).unwrap() }
}
}

Expand Down
Loading

0 comments on commit 89bbe7e

Please sign in to comment.