pub struct ImportResolver<'mod_lifetime, 'crate_lft: 'mod_lifetime> {
module_path: &'mod_lifetime str,
- imports: HashMap<syn::Ident, String>,
+ imports: HashMap<syn::Ident, (String, syn::Path)>,
declared: HashMap<syn::Ident, DeclType<'crate_lft>>,
+ priv_modules: HashSet<syn::Ident>,
}
impl<'mod_lifetime, 'crate_lft: 'mod_lifetime> ImportResolver<'mod_lifetime, 'crate_lft> {
- fn process_use_intern(imports: &mut HashMap<syn::Ident, String>, u: &syn::UseTree, partial_path: &str) {
+ fn process_use_intern(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::UseTree, partial_path: &str, mut path: syn::punctuated::Punctuated<syn::PathSegment, syn::token::Colon2>) {
match u {
syn::UseTree::Path(p) => {
- let new_path = format!("{}::{}", partial_path, p.ident);
- Self::process_use_intern(imports, &p.tree, &new_path);
+ let new_path = format!("{}{}::", partial_path, p.ident);
+ path.push(syn::PathSegment { ident: p.ident.clone(), arguments: syn::PathArguments::None });
+ Self::process_use_intern(imports, &p.tree, &new_path, path);
},
syn::UseTree::Name(n) => {
- let full_path = format!("{}::{}", partial_path, n.ident);
- imports.insert(n.ident.clone(), full_path);
+ let full_path = format!("{}{}", partial_path, n.ident);
+ path.push(syn::PathSegment { ident: n.ident.clone(), arguments: syn::PathArguments::None });
+ imports.insert(n.ident.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
},
syn::UseTree::Group(g) => {
for i in g.items.iter() {
- Self::process_use_intern(imports, i, partial_path);
+ Self::process_use_intern(imports, i, partial_path, path.clone());
}
},
syn::UseTree::Rename(r) => {
- let full_path = format!("{}::{}", partial_path, r.ident);
- imports.insert(r.rename.clone(), full_path);
+ let full_path = format!("{}{}", partial_path, r.ident);
+ path.push(syn::PathSegment { ident: r.ident.clone(), arguments: syn::PathArguments::None });
+ imports.insert(r.rename.clone(), (full_path, syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
},
syn::UseTree::Glob(_) => {
eprintln!("Ignoring * use for {} - this may result in resolution failures", partial_path);
}
}
- pub fn process_use(imports: &mut HashMap<syn::Ident, String>, u: &syn::ItemUse) {
+ fn process_use(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, u: &syn::ItemUse) {
if let syn::Visibility::Public(_) = u.vis {
// We actually only use these for #[cfg(fuzztarget)]
eprintln!("Ignoring pub(use) tree!");
return;
}
if u.leading_colon.is_some() { eprintln!("Ignoring leading-colon use!"); return; }
- match &u.tree {
- syn::UseTree::Path(p) => {
- let new_path = format!("{}", p.ident);
- Self::process_use_intern(imports, &p.tree, &new_path);
- },
- syn::UseTree::Name(n) => {
- let full_path = format!("{}", n.ident);
- imports.insert(n.ident.clone(), full_path);
- },
- _ => unimplemented!(),
- }
+ Self::process_use_intern(imports, &u.tree, "", syn::punctuated::Punctuated::new());
+ }
+
+ fn insert_primitive(imports: &mut HashMap<syn::Ident, (String, syn::Path)>, id: &str) {
+ let ident = syn::Ident::new(id, Span::call_site());
+ let mut path = syn::punctuated::Punctuated::new();
+ path.push(syn::PathSegment { ident: ident.clone(), arguments: syn::PathArguments::None });
+ imports.insert(ident, (id.to_owned(), syn::Path { leading_colon: Some(syn::Token![::](Span::call_site())), segments: path }));
}
pub fn new(module_path: &'mod_lifetime str, contents: &'crate_lft [syn::Item]) -> Self {
let mut imports = HashMap::new();
// Add primitives to the "imports" list:
- imports.insert(syn::Ident::new("bool", Span::call_site()), "bool".to_string());
- imports.insert(syn::Ident::new("u64", Span::call_site()), "u64".to_string());
- imports.insert(syn::Ident::new("u32", Span::call_site()), "u32".to_string());
- imports.insert(syn::Ident::new("u16", Span::call_site()), "u16".to_string());
- imports.insert(syn::Ident::new("u8", Span::call_site()), "u8".to_string());
- imports.insert(syn::Ident::new("usize", Span::call_site()), "usize".to_string());
- imports.insert(syn::Ident::new("str", Span::call_site()), "str".to_string());
- imports.insert(syn::Ident::new("String", Span::call_site()), "String".to_string());
+ Self::insert_primitive(&mut imports, "bool");
+ Self::insert_primitive(&mut imports, "u64");
+ Self::insert_primitive(&mut imports, "u32");
+ Self::insert_primitive(&mut imports, "u16");
+ Self::insert_primitive(&mut imports, "u8");
+ Self::insert_primitive(&mut imports, "usize");
+ Self::insert_primitive(&mut imports, "str");
+ Self::insert_primitive(&mut imports, "String");
// These are here to allow us to print native Rust types in trait fn impls even if we don't
// have C mappings:
- imports.insert(syn::Ident::new("Result", Span::call_site()), "Result".to_string());
- imports.insert(syn::Ident::new("Vec", Span::call_site()), "Vec".to_string());
- imports.insert(syn::Ident::new("Option", Span::call_site()), "Option".to_string());
+ Self::insert_primitive(&mut imports, "Result");
+ Self::insert_primitive(&mut imports, "Vec");
+ Self::insert_primitive(&mut imports, "Option");
let mut declared = HashMap::new();
+ let mut priv_modules = HashSet::new();
for item in contents.iter() {
match item {
}
}
},
+ syn::Item::Type(t) if export_status(&t.attrs) == ExportStatus::Export => {
+ if let syn::Visibility::Public(_) = t.vis {
+ let mut process_alias = true;
+ for tok in t.generics.params.iter() {
+ if let syn::GenericParam::Lifetime(_) = tok {}
+ else { process_alias = false; }
+ }
+ if process_alias {
+ match &*t.ty {
+ syn::Type::Path(_) => { declared.insert(t.ident.clone(), DeclType::StructImported); },
+ _ => {},
+ }
+ }
+ }
+ },
syn::Item::Enum(e) => {
if let syn::Visibility::Public(_) = e.vis {
match export_status(&e.attrs) {
declared.insert(t.ident.clone(), DeclType::Trait(t));
}
},
+ syn::Item::Mod(m) => {
+ priv_modules.insert(m.ident.clone());
+ },
_ => {},
}
}
- Self { module_path, imports, declared }
+ Self { module_path, imports, declared, priv_modules }
}
pub fn get_declared_type(&self, ident: &syn::Ident) -> Option<&DeclType<'crate_lft>> {
}
pub fn maybe_resolve_ident(&self, id: &syn::Ident) -> Option<String> {
- if let Some(imp) = self.imports.get(id) {
+ if let Some((imp, _)) = self.imports.get(id) {
Some(imp.clone())
} else if self.declared.get(id).is_some() {
Some(self.module_path.to_string() + "::" + &format!("{}", id))
}
pub fn maybe_resolve_non_ignored_ident(&self, id: &syn::Ident) -> Option<String> {
- if let Some(imp) = self.imports.get(id) {
+ if let Some((imp, _)) = self.imports.get(id) {
Some(imp.clone())
} else if let Some(decl_type) = self.declared.get(id) {
match decl_type {
let remaining: String = seg_iter.map(|seg| {
format!("::{}", seg.ident)
}).collect();
- if let Some(imp) = self.imports.get(&first_seg.ident) {
+ if let Some((imp, _)) = self.imports.get(&first_seg.ident) {
if remaining != "" {
Some(imp.clone() + &remaining)
} else {
Some(imp.clone())
}
+ } else if let Some(_) = self.priv_modules.get(&first_seg.ident) {
+ Some(format!("{}::{}{}", self.module_path, first_seg.ident, remaining))
} else { None }
}
}
+
+ /// Map all the Paths in a Type into absolute paths given a set of imports (generated via process_use_intern)
+ pub fn resolve_imported_refs(&self, mut ty: syn::Type) -> syn::Type {
+ match &mut ty {
+ syn::Type::Path(p) => {
+ if let Some(ident) = p.path.get_ident() {
+ if let Some((_, newpath)) = self.imports.get(ident) {
+ p.path = newpath.clone();
+ }
+ } else { unimplemented!(); }
+ },
+ syn::Type::Reference(r) => {
+ r.elem = Box::new(self.resolve_imported_refs((*r.elem).clone()));
+ },
+ syn::Type::Slice(s) => {
+ s.elem = Box::new(self.resolve_imported_refs((*s.elem).clone()));
+ },
+ syn::Type::Tuple(t) => {
+ for e in t.elems.iter_mut() {
+ *e = self.resolve_imported_refs(e.clone());
+ }
+ },
+ _ => unimplemented!(),
+ }
+ ty
+ }
}
// templates_defined is walked to write the C++ header, so if we use the default hashing it get
pub traits: HashMap<String, &'a syn::ItemTrait>,
/// Aliases from paths to some other Type
pub type_aliases: HashMap<String, syn::Type>,
+ /// Value is an alias to Key (maybe with some generics)
+ pub reverse_alias_map: HashMap<String, Vec<(syn::Path, syn::PathArguments)>>,
/// Template continer types defined, map from mangled type name -> whether a destructor fn
/// exists.
///
pub template_file: &'a mut File,
/// Set of containers which are clonable
pub clonable_types: HashSet<String>,
+ /// Key impls Value
+ pub trait_impls: HashMap<String, Vec<String>>,
}
/// A struct which tracks resolving rust types into C-mapped equivalents, exists for one specific
}
/// Gets the C-mapped type for types which are outside of the crate, or which are manually
/// ignored by for some reason need mapping anyway.
- fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, ptr_for_ref: bool) -> Option<&'b str> {
+ fn c_type_from_path<'b>(&self, full_path: &'b str, is_ref: bool, _ptr_for_ref: bool) -> Option<&'b str> {
if self.is_primitive(full_path) {
return Some(full_path);
}
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some("*const std::os::raw::c_char"),
- // List of structs we map that aren't detected:
- "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures"),
- "ln::features::InitFeatures" if is_ref => Some("*const crate::ln::features::InitFeatures"),
- "ln::features::InitFeatures" => Some("crate::ln::features::InitFeatures"),
_ => None,
}
}
"ln::channelmanager::PaymentPreimage" if is_ref => Some("&::lightning::ln::channelmanager::PaymentPreimage(unsafe { *"),
"ln::channelmanager::PaymentSecret" => Some("::lightning::ln::channelmanager::PaymentSecret("),
- // List of structs we map (possibly during processing of other files):
- "ln::features::InitFeatures" if !is_ref => Some("*unsafe { Box::from_raw("),
-
// List of traits we map (possibly during processing of other files):
"crate::util::logger::Logger" => Some(""),
"ln::channelmanager::PaymentPreimage" if is_ref => Some(" })"),
"ln::channelmanager::PaymentSecret" => Some(".data)"),
- // List of structs we map (possibly during processing of other files):
- "ln::features::InitFeatures" if is_ref => Some(".inner) }"),
- "ln::features::InitFeatures" if !is_ref => Some(".take_inner()) }"),
-
// List of traits we map (possibly during processing of other files):
"crate::util::logger::Logger" => Some(""),
_ => None,
}.map(|s| s.to_owned())
}
- fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
+ fn to_c_conversion_inline_prefix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
if self.is_primitive(full_path) {
return Some("".to_owned());
}
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some("local_"),
- // List of structs we map (possibly during processing of other files):
- "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some("crate::ln::features::InitFeatures { inner: &mut "),
- "ln::features::InitFeatures" if is_ref => Some("Box::into_raw(Box::new(crate::ln::features::InitFeatures { inner: &mut "),
- "ln::features::InitFeatures" if !is_ref => Some("crate::ln::features::InitFeatures { inner: Box::into_raw(Box::new("),
-
_ => None,
}.map(|s| s.to_owned())
}
- fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, ptr_for_ref: bool) -> Option<String> {
+ fn to_c_conversion_inline_suffix_from_path(&self, full_path: &str, is_ref: bool, _ptr_for_ref: bool) -> Option<String> {
if self.is_primitive(full_path) {
return Some("".to_owned());
}
// Override the default since Records contain an fmt with a lifetime:
"util::logger::Record" => Some(".as_ptr()"),
- // List of structs we map (possibly during processing of other files):
- "ln::features::InitFeatures" if is_ref && ptr_for_ref => Some(", is_owned: false }"),
- "ln::features::InitFeatures" if is_ref => Some(", is_owned: false }))"),
- "ln::features::InitFeatures" => Some(")), is_owned: true }"),
-
_ => None,
}.map(|s| s.to_owned())
}
").into() }"))
},
"Vec" if !is_ref => {
- Some(("Vec::new(); for item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
+ Some(("Vec::new(); for mut item in ", vec![(format!(".drain(..) {{ local_{}.push(", var_name), "item".to_string())], "); }"))
},
"Slice" => {
Some(("Vec::new(); for item in ", vec![(format!(".iter() {{ local_{}.push(", var_name), "**item".to_string())], "); }"))