Replaced Items’ String-based names with proper Paths
diff --git a/src/bindgen/cdecl.rs b/src/bindgen/cdecl.rs index 449371b..5815d7f 100644 --- a/src/bindgen/cdecl.rs +++ b/src/bindgen/cdecl.rs
@@ -71,7 +71,7 @@ fn build_type(&mut self, t: &Type, is_const: bool) { match t { - &Type::Path(ref path) => { + &Type::Path(ref generic) => { if is_const { assert!( self.type_qualifers.len() == 0, @@ -86,14 +86,14 @@ "error generating cdecl for {:?}", t ); - self.type_name = path.name.clone(); + self.type_name = generic.export_name().to_owned(); assert!( self.type_generic_args.len() == 0, "error generating cdecl for {:?}", t ); - self.type_generic_args = path.generics.clone(); - self.type_ctype = path.ctype; + self.type_generic_args = generic.generics().to_owned(); + self.type_ctype = generic.ctype().cloned(); } &Type::Primitive(ref p) => { if is_const { @@ -263,7 +263,7 @@ layout_vertical: bool, void_prototype: bool, ) { - &CDecl::from_func(f, layout_vertical).write(out, Some(&f.name), void_prototype); + &CDecl::from_func(f, layout_vertical).write(out, Some(f.path().name()), void_prototype); } pub fn write_field<F: Write>(out: &mut SourceWriter<F>, t: &Type, ident: &str) {
diff --git a/src/bindgen/declarationtyperesolver.rs b/src/bindgen/declarationtyperesolver.rs index 69bb0e4..bc98d6c7 100644 --- a/src/bindgen/declarationtyperesolver.rs +++ b/src/bindgen/declarationtyperesolver.rs
@@ -4,10 +4,12 @@ use std::collections::HashSet; +use bindgen::ir::Path; + pub struct DeclarationTypeResolver { - structs: HashSet<String>, - enums: HashSet<String>, - unions: HashSet<String>, + structs: HashSet<Path>, + enums: HashSet<Path>, + unions: HashSet<Path>, } #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] @@ -36,24 +38,25 @@ } } - pub fn add_enum(&mut self, name: &str) { - self.enums.insert(name.to_owned()); + pub fn add_enum(&mut self, path: &Path) { + self.enums.insert(path.clone()); } - pub fn add_struct(&mut self, name: &str) { - self.structs.insert(name.to_owned()); + pub fn add_struct(&mut self, path: &Path) { + self.structs.insert(path.clone()); } - pub fn add_union(&mut self, name: &str) { - self.unions.insert(name.to_owned()); + pub fn add_union(&mut self, path: &Path) { + self.unions.insert(path.clone()); } - pub fn type_for(&self, name: &str) -> Option<DeclarationType> { - if self.structs.contains(name) { + pub fn type_for(&self, path: &Path) -> Option<DeclarationType> { + // FIXME: don't look up by name, but by full path: + if self.structs.contains(path) { Some(DeclarationType::Struct) - } else if self.enums.contains(name) { + } else if self.enums.contains(path) { Some(DeclarationType::Enum) - } else if self.unions.contains(name) { + } else if self.unions.contains(path) { Some(DeclarationType::Union) } else { None
diff --git a/src/bindgen/dependencies.rs b/src/bindgen/dependencies.rs index aa5565a..8ac5903 100644 --- a/src/bindgen/dependencies.rs +++ b/src/bindgen/dependencies.rs
@@ -28,13 +28,13 @@ (&ItemContainer::Enum(ref x), &ItemContainer::Enum(ref y)) if x.tag.is_none() && y.tag.is_none() => { - x.name.cmp(&y.name) + x.path.cmp(&y.path) } (&ItemContainer::Enum(ref x), _) if x.tag.is_none() => Ordering::Less, (_, &ItemContainer::Enum(ref x)) if x.tag.is_none() => Ordering::Greater, (&ItemContainer::OpaqueItem(ref x), &ItemContainer::OpaqueItem(ref y)) => { - x.name.cmp(&y.name) + x.path.cmp(&y.path) } (&ItemContainer::OpaqueItem(_), _) => Ordering::Less, (_, &ItemContainer::OpaqueItem(_)) => Ordering::Greater,
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs index 88bcfd5..0a79d03 100644 --- a/src/bindgen/ir/constant.rs +++ b/src/bindgen/ir/constant.rs
@@ -10,7 +10,7 @@ use bindgen::config::{Config, Language}; use bindgen::declarationtyperesolver::DeclarationTypeResolver; use bindgen::ir::{ - AnnotationSet, Cfg, ConditionWrite, Documentation, Item, ItemContainer, ToCondition, Type, + AnnotationSet, Cfg, ConditionWrite, Documentation, Item, ItemContainer, Path, ToCondition, Type, }; use bindgen::writer::{Source, SourceWriter}; @@ -93,7 +93,8 @@ #[derive(Debug, Clone)] pub struct Constant { - pub name: String, + pub path: Path, + pub export_name: String, pub ty: Type, pub value: LiteralExpr, pub cfg: Option<Cfg>, @@ -103,7 +104,7 @@ impl Constant { pub fn load( - name: String, + path: Path, item: &syn::ItemConst, mod_cfg: &Option<Cfg>, ) -> Result<Constant, String> { @@ -115,21 +116,22 @@ let ty = ty.unwrap(); - if !ty.is_primitive_or_ptr_primitive() && match *item.expr { - syn::Expr::Struct(_) => false, - _ => true, - } { + if !ty.is_primitive_or_ptr_primitive() + && match *item.expr { + syn::Expr::Struct(_) => false, + _ => true, + } { return Err("Unhanded const definition".to_owned()); } - Ok(Constant { - name: name, - ty: ty, - value: LiteralExpr::load(&item.expr)?, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + Ok(Constant::new( + path, + ty, + LiteralExpr::load(&item.expr)?, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) } pub fn load_assoc( @@ -137,6 +139,8 @@ item: &syn::ImplItemConst, mod_cfg: &Option<Cfg>, ) -> Result<Constant, String> { + let path = Path::new(name); + let ty = Type::load(&item.ty)?; if ty.is_none() { @@ -145,27 +149,52 @@ let ty = ty.unwrap(); - if !ty.is_primitive_or_ptr_primitive() && match item.expr { - syn::Expr::Struct(_) => false, - _ => true, - } { + if !ty.is_primitive_or_ptr_primitive() + && match item.expr { + syn::Expr::Struct(_) => false, + _ => true, + } { return Err("Unhanded const definition".to_owned()); } - Ok(Constant { - name: name, - ty: ty, - value: LiteralExpr::load(&item.expr)?, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + Ok(Constant::new( + path, + ty, + LiteralExpr::load(&item.expr)?, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) + } + + pub fn new( + path: Path, + ty: Type, + value: LiteralExpr, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + ty, + value, + cfg, + annotations, + documentation, + } } } impl Item for Constant { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -185,7 +214,7 @@ } fn rename_for_config(&mut self, config: &Config) { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { @@ -204,9 +233,9 @@ out.write("static const "); } self.ty.write(config, out); - write!(out, " {} = {};", self.name, self.value.0) + write!(out, " {} = {};", self.export_name(), self.value.0) } else { - write!(out, "#define {} {}", self.name, self.value.0) + write!(out, "#define {} {}", self.export_name(), self.value.0) } condition.write_after(config, out); }
diff --git a/src/bindgen/ir/enumeration.rs b/src/bindgen/ir/enumeration.rs index 68694ab..cc75468 100644 --- a/src/bindgen/ir/enumeration.rs +++ b/src/bindgen/ir/enumeration.rs
@@ -11,7 +11,7 @@ use bindgen::dependencies::Dependencies; use bindgen::ir::{ AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, GenericPath, Item, - ItemContainer, Repr, ReprStyle, ReprType, Struct, ToCondition, Type, + ItemContainer, Path, Repr, ReprStyle, ReprType, Struct, ToCondition, Type, }; use bindgen::library::Library; use bindgen::mangle; @@ -23,6 +23,7 @@ #[derive(Debug, Clone)] pub struct EnumVariant { pub name: String, + pub export_name: String, pub discriminant: Option<u64>, pub body: Option<(String, Struct)>, pub documentation: Documentation, @@ -58,11 +59,7 @@ if is_tagged { res.push(( "tag".to_string(), - Type::Path(GenericPath { - name: "Tag".to_string(), - generics: vec![], - ctype: None, - }), + Type::Path(GenericPath::new(Path::new("Tag"), vec![])), Documentation::none(), )); } @@ -85,36 +82,42 @@ let body = match variant.fields { syn::Fields::Unit => None, - syn::Fields::Named(ref fields) => Some(Struct { - name: format!("{}_Body", variant.ident), - generic_params, - fields: parse_fields(is_tagged, &fields.named)?, - is_tagged, - is_enum_variant_body: true, - is_transparent: false, - tuple_struct: false, - cfg: Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), - annotations: AnnotationSet::load(&variant.attrs)?, - documentation: Documentation::none(), - }), - syn::Fields::Unnamed(ref fields) => Some(Struct { - name: format!("{}_Body", variant.ident), - generic_params, - fields: parse_fields(is_tagged, &fields.unnamed)?, - is_tagged, - is_enum_variant_body: true, - is_transparent: false, - tuple_struct: true, - cfg: Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), - annotations: AnnotationSet::load(&variant.attrs)?, - documentation: Documentation::none(), - }), + syn::Fields::Named(ref fields) => { + let path = Path::new(format!("{}_Body", variant.ident)); + Some(Struct::new( + path, + generic_params, + parse_fields(is_tagged, &fields.named)?, + is_tagged, + true, + false, + false, + Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), + AnnotationSet::load(&variant.attrs)?, + Documentation::none(), + )) + } + syn::Fields::Unnamed(ref fields) => { + let path = Path::new(format!("{}_Body", variant.ident)); + Some(Struct::new( + path, + generic_params, + parse_fields(is_tagged, &fields.unnamed)?, + is_tagged, + true, + false, + true, + Cfg::append(mod_cfg, Cfg::load(&variant.attrs)), + AnnotationSet::load(&variant.attrs)?, + Documentation::none(), + )) + } }; - Ok(EnumVariant { - name: variant.ident.to_string(), + Ok(EnumVariant::new( + variant.ident.to_string(), discriminant, - body: body.map(|body| { + body.map(|body| { ( RenameRule::SnakeCase.apply_to_pascal_case( &format!("{}", variant.ident), @@ -123,8 +126,24 @@ body, ) }), - documentation: Documentation::load(&variant.attrs), - }) + Documentation::load(&variant.attrs), + )) + } + + pub fn new( + name: String, + discriminant: Option<u64>, + body: Option<(String, Struct)>, + documentation: Documentation, + ) -> Self { + let export_name = name.clone(); + Self { + name, + export_name, + discriminant, + body, + documentation, + } } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { @@ -139,16 +158,15 @@ } } - fn specialize(&self, generic_values: &Vec<Type>, mappings: &Vec<(&String, &Type)>) -> Self { - Self { - name: mangle::mangle_path(&self.name, generic_values), - discriminant: self.discriminant, - body: self - .body + fn specialize(&self, generic_values: &[Type], mappings: &[(&Path, &Type)]) -> Self { + Self::new( + mangle::mangle_name(&self.name, generic_values), + self.discriminant, + self.body .as_ref() .map(|&(ref name, ref ty)| (name.clone(), ty.specialize(generic_values, mappings))), - documentation: self.documentation.clone(), - } + self.documentation.clone(), + ) } fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { @@ -167,7 +185,7 @@ impl Source for EnumVariant { fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { self.documentation.write(config, out); - write!(out, "{}", self.name); + write!(out, "{}", self.export_name); if let Some(discriminant) = self.discriminant { write!(out, " = {}", discriminant); } @@ -177,7 +195,8 @@ #[derive(Debug, Clone)] pub struct Enum { - pub name: String, + pub path: Path, + pub export_name: String, pub generic_params: GenericParams, pub repr: Repr, pub variants: Vec<EnumVariant>, @@ -223,7 +242,7 @@ return Err("Enum not marked with a valid repr(prim) or repr(C).".to_owned()); } - let generics = GenericParams::new(&item.generics); + let generic_params = GenericParams::new(&item.generics); let mut variants = Vec::new(); let mut is_tagged = false; @@ -232,7 +251,7 @@ let variant = EnumVariant::load( repr.style == ReprStyle::Rust, variant, - generics.clone(), + generic_params.clone(), mod_cfg, )?; is_tagged = is_tagged || variant.body.is_some(); @@ -243,35 +262,60 @@ if let Some(names) = annotations.list("enum-trailing-values") { for name in names { - variants.push(EnumVariant { - name, - discriminant: None, - body: None, - documentation: Documentation::none(), - }); + variants.push(EnumVariant::new(name, None, None, Documentation::none())); } } - Ok(Enum { - generic_params: generics, - name: item.ident.to_string(), + let path = Path::new(item.ident.to_string()); + let tag = if is_tagged { + Some("Tag".to_string()) + } else { + None + }; + Ok(Enum::new( + path, + generic_params, repr, variants, - tag: if is_tagged { - Some("Tag".to_string()) - } else { - None - }, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + tag, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), annotations, - documentation: Documentation::load(&item.attrs), - }) + Documentation::load(&item.attrs), + )) + } + + pub fn new( + path: Path, + generic_params: GenericParams, + repr: Repr, + variants: Vec<EnumVariant>, + tag: Option<String>, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generic_params, + repr, + variants, + tag, + cfg, + annotations, + documentation, + } } } impl Item for Enum { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -292,11 +336,11 @@ fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { if self.tag.is_some() && self.repr.style == ReprStyle::C { - resolver.add_struct(&self.name); + resolver.add_struct(&self.path); } else if self.tag.is_some() && self.repr.style != ReprStyle::C { - resolver.add_union(&self.name); + resolver.add_union(&self.path); } else if self.repr.style == ReprStyle::C { - resolver.add_enum(&self.name); + resolver.add_enum(&self.path); } } @@ -307,19 +351,17 @@ } fn rename_for_config(&mut self, config: &Config) { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); if config.language == Language::C && self.tag.is_some() { // it makes sense to always prefix Tag with type name in C - let new_tag = format!("{}_Tag", self.name); + let new_tag = format!("{}_Tag", self.export_name); if self.repr.style == ReprStyle::Rust { for variant in &mut self.variants { if let Some((_, ref mut body)) = variant.body { - body.fields[0].1 = Type::Path(GenericPath { - name: new_tag.clone(), - generics: vec![], - ctype: None, - }); + let path = Path::new(new_tag.clone()); + let generic_path = GenericPath::new(path, vec![]); + body.fields[0].1 = Type::Path(generic_path); } } } @@ -336,9 +378,9 @@ || self.annotations.bool("prefix-with-name").unwrap_or(false) { for variant in &mut self.variants { - variant.name = format!("{}_{}", self.name, variant.name); + variant.export_name = format!("{}_{}", self.export_name, variant.export_name); if let Some((_, ref mut body)) = variant.body { - body.name = format!("{}_{}", self.name, body.name); + body.export_name = format!("{}_{}", self.export_name, body.export_name()); } } } @@ -352,16 +394,18 @@ self.variants = self .variants .iter() - .map(|variant| EnumVariant { - name: r.apply_to_pascal_case(&variant.name, IdentifierType::EnumVariant(self)), - discriminant: variant.discriminant.clone(), - body: variant.body.as_ref().map(|body| { - ( - r.apply_to_snake_case(&body.0, IdentifierType::StructMember), - body.1.clone(), - ) - }), - documentation: variant.documentation.clone(), + .map(|variant| { + EnumVariant::new( + r.apply_to_pascal_case(&variant.name, IdentifierType::EnumVariant(self)), + variant.discriminant.clone(), + variant.body.as_ref().map(|body| { + ( + r.apply_to_snake_case(&body.0, IdentifierType::StructMember), + body.1.clone(), + ) + }), + variant.documentation.clone(), + ) }) .collect(); } @@ -369,19 +413,19 @@ fn instantiate_monomorph( &self, - generic_values: &Vec<Type>, + generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", - self.name + self.path.name() ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", - self.name, + self.path.name(), self.generic_params.len(), generic_values.len(), ); @@ -398,24 +442,24 @@ } } - let monomorph = Enum { - name: mangle::mangle_path(&self.name, generic_values), - tag: self.tag.clone(), - generic_params: GenericParams::default(), - repr: self.repr.clone(), - variants: self - .variants + let mangled_path = mangle::mangle_path(&self.path, generic_values); + let monomorph = Enum::new( + mangled_path, + GenericParams::default(), + self.repr.clone(), + self.variants .iter() .map(|v| v.specialize(generic_values, &mappings)) .collect(), - cfg: self.cfg.clone(), - annotations: self.annotations.clone(), - documentation: self.documentation.clone(), - }; + self.tag.clone(), + self.cfg.clone(), + self.annotations.clone(), + self.documentation.clone(), + ); monomorph.add_monomorphs(library, out); - out.insert_enum(self, monomorph, generic_values.clone()); + out.insert_enum(self, monomorph, generic_values.to_owned()); } fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { @@ -451,14 +495,14 @@ self.generic_params.write(config, out); if is_tagged && config.language == Language::Cxx { out.write(if separate_tag { "struct " } else { "union " }); - write!(out, "{}", self.name); + write!(out, "{}", self.export_name()); out.open_brace(); } let enum_name = if let Some(ref tag) = self.tag { tag } else { - &self.name + self.export_name() }; // Emit the actual enum @@ -531,7 +575,7 @@ out.write(if separate_tag { "struct" } else { "union" }); if config.style.generate_tag() { - write!(out, " {}", self.name); + write!(out, " {}", self.export_name()); } out.open_brace(); @@ -573,9 +617,9 @@ out.new_line(); } if config.style.generate_typedef() { - write!(out, "{} {};", body.name, field_name); + write!(out, "{} {};", body.export_name(), field_name); } else { - write!(out, "struct {} {};", body.name, field_name); + write!(out, "struct {} {};", body.export_name(), field_name); } } @@ -602,27 +646,25 @@ .apply_to_snake_case(name, IdentifierType::FunctionArg) }; - write!(out, "static {} {}(", self.name, variant.name); + write!(out, "static {} {}(", self.export_name, variant.export_name); if let Some((_, ref body)) = variant.body { - out.write_vertical_source_list( - &body - .fields - .iter() - .skip(skip_fields) - .map(|&(ref name, ref ty, _)| { - // const-ref args to constructor - (format!("const& {}", arg_renamer(name)), ty.clone()) - }) - .collect(), - ListType::Join(","), - ); + let vec: Vec<_> = body + .fields + .iter() + .skip(skip_fields) + .map(|&(ref name, ref ty, _)| { + // const-ref args to constructor + (format!("const& {}", arg_renamer(name)), ty.clone()) + }) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Join(",")); } write!(out, ")"); out.open_brace(); - write!(out, "{} result;", self.name); + write!(out, "{} result;", self.export_name); if let Some((ref variant_name, ref body)) = variant.body { for &(ref field_name, ..) in body.fields.iter().skip(skip_fields) { @@ -638,7 +680,7 @@ } out.new_line(); - write!(out, "result.tag = {}::{};", enum_name, variant.name); + write!(out, "result.tag = {}::{};", enum_name, variant.export_name); out.new_line(); write!(out, "return result;"); out.close_brace(false); @@ -649,9 +691,9 @@ out.new_line(); // FIXME: create a config for method case - write!(out, "bool Is{}() const", variant.name); + write!(out, "bool Is{}() const", variant.export_name); out.open_brace(); - write!(out, "return tag == {}::{};", enum_name, variant.name); + write!(out, "return tag == {}::{};", enum_name, variant.export_name); out.close_brace(false); } } @@ -668,7 +710,11 @@ out.new_line(); out.new_line(); - write!(out, "bool operator==(const {}& {}) const", self.name, other); + write!( + out, + "bool operator==(const {}& {}) const", + self.export_name, other + ); out.open_brace(); write!(out, "if (tag != {}.tag)", other); out.open_brace(); @@ -683,7 +729,7 @@ out, "case {}::{}: return {} == {}.{};", self.tag.as_ref().unwrap(), - variant.name, + variant.export_name, variant_name, other, variant_name @@ -698,7 +744,11 @@ if config.structure.derive_neq(&self.annotations) { out.new_line(); out.new_line(); - write!(out, "bool operator!=(const {}& {}) const", self.name, other); + write!( + out, + "bool operator!=(const {}& {}) const", + self.export_name, other + ); out.open_brace(); write!(out, "return !(*this == {});", other); out.close_brace(false); @@ -708,7 +758,7 @@ if config.language == Language::C { if config.style.generate_typedef() { out.close_brace(false); - write!(out, " {};", self.name); + write!(out, " {};", self.export_name); } else { out.close_brace(true); }
diff --git a/src/bindgen/ir/function.rs b/src/bindgen/ir/function.rs index b3e753b..5a4ea4e 100644 --- a/src/bindgen/ir/function.rs +++ b/src/bindgen/ir/function.rs
@@ -11,7 +11,7 @@ use bindgen::declarationtyperesolver::DeclarationTypeResolver; use bindgen::dependencies::Dependencies; use bindgen::ir::{ - AnnotationSet, Cfg, ConditionWrite, Documentation, PrimitiveType, ToCondition, Type, + AnnotationSet, Cfg, ConditionWrite, Documentation, Path, PrimitiveType, ToCondition, Type, }; use bindgen::library::Library; use bindgen::monomorph::Monomorphs; @@ -21,7 +21,7 @@ #[derive(Debug, Clone)] pub struct Function { - pub name: String, + pub path: Path, pub ret: Type, pub args: Vec<(String, Type)>, pub extern_decl: bool, @@ -32,7 +32,7 @@ impl Function { pub fn load( - name: String, + path: Path, decl: &syn::FnDecl, extern_decl: bool, attrs: &[syn::Attribute], @@ -51,16 +51,20 @@ }; Ok(Function { - name: name, - ret: ret, - args: args, - extern_decl: extern_decl, + path, + ret, + args, + extern_decl, cfg: Cfg::append(mod_cfg, Cfg::load(attrs)), annotations: AnnotationSet::load(attrs)?, documentation: Documentation::load(attrs), }) } + pub fn path(&self) -> &Path { + &self.path + } + pub fn simplify_standard_types(&mut self) { self.ret.simplify_standard_types(); for &mut (_, ref mut ty) in &mut self.args {
diff --git a/src/bindgen/ir/generic_path.rs b/src/bindgen/ir/generic_path.rs new file mode 100644 index 0000000..78f007b --- /dev/null +++ b/src/bindgen/ir/generic_path.rs
@@ -0,0 +1,143 @@ +use std::io::Write; +use std::ops::Deref; + +use syn; + +use bindgen::config::{Config, Language}; +use bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; +use bindgen::ir::{Path, Type}; +use bindgen::utilities::IterHelpers; +use bindgen::writer::{Source, SourceWriter}; + +#[derive(Default, Debug, Clone)] +pub struct GenericParams(pub Vec<Path>); + +impl GenericParams { + pub fn new(generics: &syn::Generics) -> Self { + GenericParams( + generics + .params + .iter() + .filter_map(|x| match x { + &syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => { + Some(Path::new(ident.to_string())) + } + _ => None, + }) + .collect(), + ) + } +} + +impl Deref for GenericParams { + type Target = [Path]; + + fn deref(&self) -> &[Path] { + &self.0 + } +} + +impl Source for GenericParams { + fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { + if !self.0.is_empty() { + if config.language == Language::Cxx { + out.write("template<"); + for (i, item) in self.0.iter().enumerate() { + if i != 0 { + out.write(", "); + } + write!(out, "typename {}", item); + } + out.write(">"); + out.new_line(); + } + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct GenericPath { + path: Path, + export_name: String, + generics: Vec<Type>, + ctype: Option<DeclarationType>, +} + +impl GenericPath { + pub fn new(path: Path, generics: Vec<Type>) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generics, + ctype: None, + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn generics(&self) -> &[Type] { + &self.generics + } + + pub fn ctype(&self) -> Option<&DeclarationType> { + self.ctype.as_ref() + } + + pub fn name(&self) -> &str { + self.path.name() + } + + pub fn export_name(&self) -> &str { + &self.export_name + } + + pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) { + for generic in &mut self.generics { + generic.rename_for_config(config, generic_params); + } + if !generic_params.contains(&self.path) { + config.export.rename(&mut self.export_name); + } + } + + pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { + self.ctype = resolver.type_for(&self.path); + } + + pub fn load(path: &syn::Path) -> Result<Self, String> { + assert!( + path.segments.len() > 0, + "{:?} doesn't have any segments", + path + ); + let last_segment_token = path.segments.last().unwrap(); + let last_segment = last_segment_token.value(); + let name = last_segment.ident.to_string(); + + let path = Path::new(name); + let phantom_data_path = Path::new("PhantomData"); + if path == phantom_data_path { + return Ok(Self::new(path, Vec::new())); + } + + let generics = match &last_segment.arguments { + &syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { + ref args, + .. + }) => args.iter().try_skip_map(|x| match *x { + &syn::GenericArgument::Type(ref x) => Type::load(x), + &syn::GenericArgument::Lifetime(_) => Ok(None), + _ => Err(format!("can't handle generic argument {:?}", x)), + })?, + &syn::PathArguments::Parenthesized(_) => { + return Err("Path contains parentheses.".to_owned()); + } + _ => Vec::new(), + }; + + Ok(Self::new(path, generics)) + } +}
diff --git a/src/bindgen/ir/generics.rs b/src/bindgen/ir/generics.rs deleted file mode 100644 index 9865a16..0000000 --- a/src/bindgen/ir/generics.rs +++ /dev/null
@@ -1,53 +0,0 @@ -use std::io::Write; -use std::ops::Deref; - -use syn; - -use bindgen::config::{Config, Language}; -use bindgen::writer::{Source, SourceWriter}; - -#[derive(Default, Debug, Clone)] -pub struct GenericParams(pub Vec<String>); - -impl GenericParams { - pub fn new(generics: &syn::Generics) -> Self { - GenericParams( - generics - .params - .iter() - .filter_map(|x| match x { - &syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => { - Some(ident.to_string()) - } - _ => None, - }) - .collect::<Vec<_>>(), - ) - } -} - -impl Deref for GenericParams { - type Target = [String]; - - fn deref(&self) -> &[String] { - &self.0 - } -} - -impl Source for GenericParams { - fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { - if !self.0.is_empty() { - if config.language == Language::Cxx { - out.write("template<"); - for (i, item) in self.0.iter().enumerate() { - if i != 0 { - out.write(", "); - } - write!(out, "typename {}", item); - } - out.write(">"); - out.new_line(); - } - } - } -}
diff --git a/src/bindgen/ir/global.rs b/src/bindgen/ir/global.rs index bb44762..6fc261b 100644 --- a/src/bindgen/ir/global.rs +++ b/src/bindgen/ir/global.rs
@@ -9,13 +9,14 @@ use bindgen::config::Config; use bindgen::declarationtyperesolver::DeclarationTypeResolver; use bindgen::dependencies::Dependencies; -use bindgen::ir::{AnnotationSet, Cfg, Documentation, Item, ItemContainer, Type}; +use bindgen::ir::{AnnotationSet, Cfg, Documentation, Item, ItemContainer, Path, Type}; use bindgen::library::Library; use bindgen::writer::{Source, SourceWriter}; #[derive(Debug, Clone)] pub struct Static { - pub name: String, + pub path: Path, + pub export_name: String, pub ty: Type, pub mutable: bool, pub cfg: Option<Cfg>, @@ -31,14 +32,34 @@ return Err("Cannot have a zero sized static definition.".to_owned()); } - Ok(Static { - name: item.ident.to_string(), - ty: ty.unwrap(), - mutable: item.mutability.is_some(), - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + Ok(Static::new( + Path::new(item.ident.to_string()), + ty.unwrap(), + item.mutability.is_some(), + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) + } + + pub fn new( + path: Path, + ty: Type, + mutable: bool, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + ty, + mutable, + cfg, + annotations, + documentation, + } } pub fn simplify_standard_types(&mut self) { @@ -47,8 +68,12 @@ } impl Item for Static { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -90,6 +115,6 @@ } } self.ty.write(config, out); - write!(out, " {};", self.name); + write!(out, " {};", self.export_name()); } }
diff --git a/src/bindgen/ir/item.rs b/src/bindgen/ir/item.rs index 8e0237e..ee1ffd5 100644 --- a/src/bindgen/ir/item.rs +++ b/src/bindgen/ir/item.rs
@@ -9,14 +9,20 @@ use bindgen::declarationtyperesolver::DeclarationTypeResolver; use bindgen::dependencies::Dependencies; use bindgen::ir::{ - AnnotationSet, Cfg, Constant, Enum, OpaqueItem, Static, Struct, Type, Typedef, Union, + AnnotationSet, Cfg, Constant, Enum, OpaqueItem, Path, Static, Struct, Type, Typedef, Union, }; use bindgen::library::Library; use bindgen::monomorph::Monomorphs; /// An item is any type of rust item besides a function pub trait Item { - fn name(&self) -> &str; + fn path(&self) -> &Path; + fn name(&self) -> &str { + self.path().name() + } + fn export_name(&self) -> &str { + self.name() + } fn cfg(&self) -> &Option<Cfg>; fn annotations(&self) -> &AnnotationSet; fn annotations_mut(&mut self) -> &mut AnnotationSet; @@ -31,12 +37,7 @@ } fn rename_for_config(&mut self, _config: &Config) {} fn add_dependencies(&self, _library: &Library, _out: &mut Dependencies) {} - fn instantiate_monomorph( - &self, - _generics: &Vec<Type>, - _library: &Library, - _out: &mut Monomorphs, - ) { + fn instantiate_monomorph(&self, _generics: &[Type], _library: &Library, _out: &mut Monomorphs) { unreachable!("Cannot instantiate {} as a generic.", self.name()) } } @@ -74,7 +75,7 @@ #[derive(Debug, Clone)] pub struct ItemMap<T: Item> { - data: BTreeMap<String, ItemValue<T>>, + data: BTreeMap<Path, ItemValue<T>>, } impl<T: Item + Clone> ItemMap<T> { @@ -92,7 +93,7 @@ } pub fn try_insert(&mut self, item: T) -> bool { - match (item.cfg().is_some(), self.data.get_mut(item.name())) { + match (item.cfg().is_some(), self.data.get_mut(item.path())) { (true, Some(&mut ItemValue::Cfg(ref mut items))) => { items.push(item); return true; @@ -109,12 +110,11 @@ _ => {} } + let path = item.path().clone(); if item.cfg().is_some() { - self.data - .insert(item.name().to_owned(), ItemValue::Cfg(vec![item])); + self.data.insert(path, ItemValue::Cfg(vec![item])); } else { - self.data - .insert(item.name().to_owned(), ItemValue::Single(item)); + self.data.insert(path, ItemValue::Single(item)); } true @@ -139,8 +139,8 @@ result } - pub fn get_items(&self, name: &str) -> Option<Vec<ItemContainer>> { - match self.data.get(name) { + pub fn get_items(&self, path: &Path) -> Option<Vec<ItemContainer>> { + match self.data.get(path) { Some(&ItemValue::Cfg(ref items)) => Some(items.iter().map(|x| x.container()).collect()), Some(&ItemValue::Single(ref item)) => Some(vec![item.container()]), None => None, @@ -208,11 +208,11 @@ } #[allow(dead_code)] - pub fn for_items<F>(&self, name: &str, mut callback: F) + pub fn for_items<F>(&self, path: &Path, mut callback: F) where F: FnMut(&T), { - match self.data.get(name) { + match self.data.get(path) { Some(&ItemValue::Cfg(ref items)) => { for item in items { callback(item); @@ -225,11 +225,11 @@ } } - pub fn for_items_mut<F>(&mut self, name: &str, mut callback: F) + pub fn for_items_mut<F>(&mut self, path: &Path, mut callback: F) where F: FnMut(&mut T), { - match self.data.get_mut(name) { + match self.data.get_mut(path) { Some(&mut ItemValue::Cfg(ref mut items)) => { for item in items { callback(item);
diff --git a/src/bindgen/ir/mod.rs b/src/bindgen/ir/mod.rs index bbedf24..ae9890e 100644 --- a/src/bindgen/ir/mod.rs +++ b/src/bindgen/ir/mod.rs
@@ -8,7 +8,7 @@ pub mod documentation; pub mod enumeration; pub mod function; -pub mod generics; +pub mod generic_path; pub mod global; pub mod item; pub mod opaque; @@ -25,7 +25,7 @@ pub use self::documentation::Documentation; pub use self::enumeration::*; pub use self::function::*; -pub use self::generics::*; +pub use self::generic_path::*; pub use self::global::*; pub use self::item::*; pub use self::opaque::*;
diff --git a/src/bindgen/ir/opaque.rs b/src/bindgen/ir/opaque.rs index 0e4cdc8..0db02bc 100644 --- a/src/bindgen/ir/opaque.rs +++ b/src/bindgen/ir/opaque.rs
@@ -20,7 +20,8 @@ #[derive(Debug, Clone)] pub struct OpaqueItem { - pub name: Path, + pub path: Path, + pub export_name: String, pub generic_params: GenericParams, pub cfg: Option<Cfg>, pub annotations: AnnotationSet, @@ -28,25 +29,47 @@ } impl OpaqueItem { - pub fn new( - name: String, + pub fn load( + path: Path, generics: &syn::Generics, - attrs: &Vec<syn::Attribute>, + attrs: &[syn::Attribute], mod_cfg: &Option<Cfg>, + ) -> Result<OpaqueItem, String> { + Ok(Self::new( + path, + GenericParams::new(generics), + Cfg::append(mod_cfg, Cfg::load(attrs)), + AnnotationSet::load(attrs).unwrap_or(AnnotationSet::new()), + Documentation::load(attrs), + )) + } + + pub fn new( + path: Path, + generic_params: GenericParams, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, ) -> OpaqueItem { - OpaqueItem { - name: name, - generic_params: GenericParams::new(generics), - cfg: Cfg::append(mod_cfg, Cfg::load(attrs)), - annotations: AnnotationSet::load(attrs).unwrap_or(AnnotationSet::new()), - documentation: Documentation::load(attrs), + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generic_params, + cfg, + annotations, + documentation, } } } impl Item for OpaqueItem { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -66,43 +89,44 @@ } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { - resolver.add_struct(&self.name); + resolver.add_struct(&self.path); } fn rename_for_config(&mut self, config: &Config) { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); } fn add_dependencies(&self, _: &Library, _: &mut Dependencies) {} fn instantiate_monomorph( &self, - generic_values: &Vec<Type>, + generic_values: &[Type], _library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", - self.name + self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", - self.name, + self.path, self.generic_params.len(), generic_values.len(), ); - let monomorph = OpaqueItem { - name: mangle::mangle_path(&self.name, generic_values), - generic_params: GenericParams::default(), - cfg: self.cfg.clone(), - annotations: self.annotations.clone(), - documentation: self.documentation.clone(), - }; + let mangled_path = mangle::mangle_path(&self.path, generic_values); + let monomorph = OpaqueItem::new( + mangled_path, + GenericParams::default(), + self.cfg.clone(), + self.annotations.clone(), + self.documentation.clone(), + ); - out.insert_opaque(self, monomorph, generic_values.clone()); + out.insert_opaque(self, monomorph, generic_values.to_owned()); } } @@ -116,9 +140,14 @@ self.generic_params.write(config, out); if config.style.generate_typedef() && config.language == Language::C { - write!(out, "typedef struct {} {};", self.name, self.name); + write!( + out, + "typedef struct {} {};", + self.export_name(), + self.export_name() + ); } else { - write!(out, "struct {};", self.name); + write!(out, "struct {};", self.export_name()); } condition.write_after(config, out);
diff --git a/src/bindgen/ir/path.rs b/src/bindgen/ir/path.rs index 5168e64..a657c71 100644 --- a/src/bindgen/ir/path.rs +++ b/src/bindgen/ir/path.rs
@@ -2,63 +2,41 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use syn; +use std::cmp::Ordering; +use std::fmt; -use bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver}; -use bindgen::ir::Type; -use bindgen::utilities::IterHelpers; - -pub type Path = String; - -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct GenericPath { - pub name: String, - pub generics: Vec<Type>, - pub ctype: Option<DeclarationType>, +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Path { + name: String, } -impl GenericPath { - pub fn new(name: String, generics: Vec<Type>) -> GenericPath { - GenericPath { - name: name, - generics: generics, - ctype: None, - } +impl Path { + pub fn new<T>(name: T) -> Self + where + String: From<T>, + { + Self { name: name.into() } } - pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { - self.ctype = resolver.type_for(&self.name); + pub fn name(&self) -> &str { + &self.name } +} - pub fn load(path: &syn::Path) -> Result<GenericPath, String> { - assert!( - path.segments.len() > 0, - "{:?} doesn't have any segments", - path - ); - let last_segment_token = path.segments.last().unwrap(); - let last_segment = last_segment_token.value(); - let name = last_segment.ident.to_string(); +impl PartialOrd for Path { + fn partial_cmp(&self, other: &Path) -> Option<Ordering> { + Some(self.cmp(other)) + } +} - if name == "PhantomData" { - return Ok(GenericPath::new(name, Vec::new())); - } +impl Ord for Path { + fn cmp(&self, other: &Path) -> Ordering { + self.name.cmp(&other.name) + } +} - let generics = match &last_segment.arguments { - &syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { - ref args, - .. - }) => args.iter().try_skip_map(|x| match *x { - &syn::GenericArgument::Type(ref x) => Type::load(x), - &syn::GenericArgument::Lifetime(_) => Ok(None), - _ => Err(format!("can't handle generic argument {:?}", x)), - })?, - &syn::PathArguments::Parenthesized(_) => { - return Err("Path contains parentheses.".to_owned()); - } - _ => Vec::new(), - }; - - Ok(GenericPath::new(name, generics)) +impl fmt::Display for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.name) } }
diff --git a/src/bindgen/ir/structure.rs b/src/bindgen/ir/structure.rs index 94565b9..d12b410 100644 --- a/src/bindgen/ir/structure.rs +++ b/src/bindgen/ir/structure.rs
@@ -10,8 +10,8 @@ use bindgen::declarationtyperesolver::DeclarationTypeResolver; use bindgen::dependencies::Dependencies; use bindgen::ir::{ - AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Repr, - ToCondition, Type, Typedef, + AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, + Repr, ToCondition, Type, Typedef, }; use bindgen::library::Library; use bindgen::mangle; @@ -22,7 +22,8 @@ #[derive(Debug, Clone)] pub struct Struct { - pub name: String, + pub path: Path, + pub export_name: String, pub generic_params: GenericParams, pub fields: Vec<(String, Type, Documentation)>, /// Whether there's a tag field on the body of this struct. When this is @@ -74,18 +75,49 @@ } }; - Ok(Self { - name: item.ident.to_string(), - generic_params: GenericParams::new(&item.generics), - fields: fields, - is_tagged: false, - is_enum_variant_body: false, - is_transparent: is_transparent, - tuple_struct: tuple_struct, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + let is_tagged = false; + let is_enum_variant_body = false; + + Ok(Struct::new( + Path::new(item.ident.to_string()), + GenericParams::new(&item.generics), + fields, + is_tagged, + is_enum_variant_body, + is_transparent, + tuple_struct, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) + } + + pub fn new( + path: Path, + generic_params: GenericParams, + fields: Vec<(String, Type, Documentation)>, + is_tagged: bool, + is_enum_variant_body: bool, + is_transparent: bool, + tuple_struct: bool, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generic_params, + fields, + is_tagged, + is_enum_variant_body, + is_transparent, + tuple_struct, + cfg, + annotations, + documentation, + } } pub fn simplify_standard_types(&mut self) { @@ -116,29 +148,33 @@ } } - pub fn specialize(&self, generic_values: &Vec<Type>, mappings: &Vec<(&String, &Type)>) -> Self { - Self { - name: mangle::mangle_path(&self.name, generic_values), - generic_params: GenericParams::default(), - fields: self - .fields + pub fn specialize(&self, generic_values: &[Type], mappings: &[(&Path, &Type)]) -> Self { + let mangled_path = mangle::mangle_path(&self.path, generic_values); + Struct::new( + mangled_path, + GenericParams::default(), + self.fields .iter() - .map(|x| (x.0.clone(), x.1.specialize(&mappings), x.2.clone())) + .map(|x| (x.0.clone(), x.1.specialize(mappings), x.2.clone())) .collect(), - is_enum_variant_body: self.is_enum_variant_body, - is_tagged: self.is_tagged, - is_transparent: self.is_transparent, - tuple_struct: self.tuple_struct, - cfg: self.cfg.clone(), - annotations: self.annotations.clone(), - documentation: self.documentation.clone(), - } + self.is_tagged, + self.is_enum_variant_body, + self.is_transparent, + self.tuple_struct, + self.cfg.clone(), + self.annotations.clone(), + self.documentation.clone(), + ) } } impl Item for Struct { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -159,7 +195,7 @@ fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { if !self.is_transparent { - resolver.add_struct(&self.name); + resolver.add_struct(&self.path); } } @@ -171,7 +207,7 @@ fn rename_for_config(&mut self, config: &Config) { if !self.is_tagged || config.language == Language::C { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); } { let fields = self @@ -227,19 +263,19 @@ fn instantiate_monomorph( &self, - generic_values: &Vec<Type>, + generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", - self.name + self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", - self.name, + self.path, self.generic_params.len(), generic_values.len(), ); @@ -255,7 +291,7 @@ // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); - out.insert_struct(self, monomorph, generic_values.clone()); + out.insert_struct(self, monomorph, generic_values.to_owned()); } } @@ -263,7 +299,8 @@ fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { if self.is_transparent { let typedef = Typedef { - name: self.name.clone(), + path: self.path.clone(), + export_name: self.export_name.to_owned(), generic_params: self.generic_params.clone(), aliased: self.fields[0].1.clone(), cfg: self.cfg.clone(), @@ -296,7 +333,7 @@ out.write("struct"); if config.language == Language::Cxx || config.style.generate_tag() { - write!(out, " {}", self.name); + write!(out, " {}", self.export_name()); } out.open_brace(); @@ -304,14 +341,12 @@ if config.documentation { out.write_vertical_source_list(&self.fields, ListType::Cap(";")); } else { - out.write_vertical_source_list( - &self - .fields - .iter() - .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) - .collect(), - ListType::Cap(";"), - ); + let vec: Vec<_> = self + .fields + .iter() + .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Cap(";")); } if config.language == Language::Cxx { @@ -333,29 +368,25 @@ .unwrap_or(&RenameRule::GeckoCase) .apply_to_snake_case(name, IdentifierType::FunctionArg) }; - write!(out, "{}(", self.name); - out.write_vertical_source_list( - &self - .fields - .iter() - .map(|&(ref name, ref ty, _)| { - // const-ref args to constructor - (format!("const& {}", arg_renamer(name)), ty.clone()) - }) - .collect(), - ListType::Join(","), - ); + write!(out, "{}(", self.export_name()); + let vec: Vec<_> = self + .fields + .iter() + .map(|&(ref name, ref ty, _)| { + // const-ref args to constructor + (format!("const& {}", arg_renamer(name)), ty.clone()) + }) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Join(",")); write!(out, ")"); out.new_line(); write!(out, " : "); - out.write_vertical_source_list( - &self - .fields - .iter() - .map(|x| format!("{}({})", x.0, arg_renamer(&x.0))) - .collect(), - ListType::Join(","), - ); + let vec: Vec<_> = self + .fields + .iter() + .map(|x| format!("{}({})", x.0, arg_renamer(&x.0))) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Join(",")); out.new_line(); write!(out, "{{}}"); out.new_line(); @@ -380,19 +411,19 @@ write!( out, "bool operator{}(const {}& {}) const", - op, self.name, other + op, + self.export_name(), + other ); out.open_brace(); out.write("return "); - out.write_vertical_source_list( - &self - .fields - .iter() - .skip(skip_fields) - .map(|x| format!("{} {} {}.{}", x.0, op, other, x.0)) - .collect(), - ListType::Join(&format!(" {}", conjuc)), - ); + let vec: Vec<_> = self + .fields + .iter() + .skip(skip_fields) + .map(|x| format!("{} {} {}.{}", x.0, op, other, x.0)) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Join(&format!(" {}", conjuc))); out.write(";"); out.close_brace(false); }; @@ -431,7 +462,7 @@ if config.language == Language::C && config.style.generate_typedef() { out.close_brace(false); - write!(out, " {};", self.name); + write!(out, " {};", self.export_name()); } else { out.close_brace(true); }
diff --git a/src/bindgen/ir/ty.rs b/src/bindgen/ir/ty.rs index 0a160a8..bf652e2 100644 --- a/src/bindgen/ir/ty.rs +++ b/src/bindgen/ir/ty.rs
@@ -179,6 +179,12 @@ ArrayLength::Name(ref string) | ArrayLength::Value(ref string) => string, } } + + fn rename_for_config(&mut self, config: &Config) { + if let ArrayLength::Name(ref mut name) = self { + config.export.rename(name); + } + } } #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -229,19 +235,19 @@ } } &syn::Type::Path(ref path) => { - let path = GenericPath::load(&path.path)?; + let generic_path = GenericPath::load(&path.path)?; - if path.name == "PhantomData" { + if generic_path.name() == "PhantomData" { return Ok(None); } - if let Some(prim) = PrimitiveType::maybe(&path.name) { - if path.generics.len() > 0 { + if let Some(prim) = PrimitiveType::maybe(generic_path.name()) { + if generic_path.generics().len() > 0 { return Err("Primitive has generics.".to_owned()); } Type::Primitive(prim) } else { - Type::Path(path) + Type::Path(generic_path) } } &syn::Type::Array(syn::TypeArray { @@ -255,10 +261,8 @@ Some(converted) => converted, None => return Err("Cannot have an array of zero sized types.".to_owned()), }; - - let path = GenericPath::load(&path.path)?; - let len = ArrayLength::Name(path.name); - // panic!("panic -> name: {:?}", len); + let generic_path = GenericPath::load(&path.path)?; + let len = ArrayLength::Name(generic_path.export_name().to_owned()); Type::Array(Box::new(converted), len) } &syn::Type::Array(syn::TypeArray { @@ -334,14 +338,14 @@ _ => return None, }; - if path.generics.len() != 1 { + if path.generics().len() != 1 { return None; } - let mut generic = path.generics[0].clone(); + let mut generic = path.generics()[0].clone(); generic.simplify_standard_types(); - match &*path.name { + match path.name() { // FIXME(#223): This is not quite correct. "Option" if generic.is_repr_ptr() => Some(generic), "NonNull" => Some(Type::Ptr(Box::new(generic))), @@ -361,8 +365,8 @@ match current { &Type::ConstPtr(ref ty) => current = ty, &Type::Ptr(ref ty) => current = ty, - &Type::Path(ref path) => { - return Some(path.name.clone()); + &Type::Path(ref generic) => { + return Some(generic.path().clone()); } &Type::Primitive(..) => { return None; @@ -377,20 +381,21 @@ } } - pub fn specialize(&self, mappings: &Vec<(&String, &Type)>) -> Type { + pub fn specialize(&self, mappings: &[(&Path, &Type)]) -> Type { match self { &Type::ConstPtr(ref ty) => Type::ConstPtr(Box::new(ty.specialize(mappings))), &Type::Ptr(ref ty) => Type::Ptr(Box::new(ty.specialize(mappings))), - &Type::Path(ref path) => { + &Type::Path(ref generic_path) => { for &(param, value) in mappings { - if *path.name == *param { + if generic_path.path() == param { return value.clone(); } } let specialized = GenericPath::new( - path.name.clone(), - path.generics + generic_path.path().clone(), + generic_path + .generics() .iter() .map(|x| x.specialize(mappings)) .collect(), @@ -421,14 +426,15 @@ &Type::Ptr(ref ty) => { ty.add_dependencies_ignoring_generics(generic_params, library, out); } - &Type::Path(ref path) => { - for generic_value in &path.generics { + &Type::Path(ref generic) => { + for generic_value in generic.generics() { generic_value.add_dependencies_ignoring_generics(generic_params, library, out); } - if !generic_params.contains(&path.name) { - if let Some(items) = library.get_items(&path.name) { - if !out.items.contains(&path.name) { - out.items.insert(path.name.clone()); + let path = generic.path(); + if !generic_params.contains(path) { + if let Some(items) = library.get_items(path) { + if !out.items.contains(path) { + out.items.insert(path.clone()); for item in &items { item.deref().add_dependencies(library, out); @@ -441,7 +447,7 @@ warn!( "Can't find {}. This usually means that this type was incompatible or \ not found.", - path.name + path ); } } @@ -471,15 +477,15 @@ &Type::Ptr(ref ty) => { ty.add_monomorphs(library, out); } - &Type::Path(ref path) => { - if path.generics.len() == 0 || out.contains(&path) { + &Type::Path(ref generic) => { + if generic.generics().len() == 0 || out.contains(&generic) { return; } - - if let Some(items) = library.get_items(&path.name) { + let path = generic.path(); + if let Some(items) = library.get_items(path) { for item in items { item.deref() - .instantiate_monomorph(&path.generics, library, out); + .instantiate_monomorph(generic.generics(), library, out); } } } @@ -504,20 +510,13 @@ &mut Type::Ptr(ref mut ty) => { ty.rename_for_config(config, generic_params); } - &mut Type::Path(ref mut path) => { - for generic in &mut path.generics { - generic.rename_for_config(config, generic_params); - } - if !generic_params.contains(&path.name) { - config.export.rename(&mut path.name); - } + &mut Type::Path(ref mut ty) => { + ty.rename_for_config(config, generic_params); } &mut Type::Primitive(_) => {} &mut Type::Array(ref mut ty, ref mut len) => { ty.rename_for_config(config, generic_params); - if let ArrayLength::Name(ref mut name) = len { - config.export.rename(name); - } + len.rename_for_config(config); } &mut Type::FuncPtr(ref mut ret, ref mut args) => { ret.rename_for_config(config, generic_params); @@ -536,8 +535,8 @@ &mut Type::Ptr(ref mut ty) => { ty.resolve_declaration_types(resolver); } - &mut Type::Path(ref mut path) => { - path.resolve_declaration_types(resolver); + &mut Type::Path(ref mut generic_path) => { + generic_path.resolve_declaration_types(resolver); } &mut Type::Primitive(_) => {} &mut Type::Array(ref mut ty, _) => { @@ -560,19 +559,18 @@ &mut Type::Ptr(ref mut ty) => { ty.mangle_paths(monomorphs); } - &mut Type::Path(ref mut path) => { - if path.generics.len() == 0 { + &mut Type::Path(ref mut generic_path) => { + if generic_path.generics().len() == 0 { return; } - if let Some(mangled) = monomorphs.mangle_path(path) { - path.name = mangled.clone(); - path.generics = Vec::new(); + if let Some(mangled_path) = monomorphs.mangle_path(&generic_path) { + *generic_path = GenericPath::new(mangled_path.clone(), vec![]); } else { error!( "Cannot find a mangling for generic path {:?}. This usually means that a \ type referenced by this generic was incompatible or not found.", - path + generic_path ); } }
diff --git a/src/bindgen/ir/typedef.rs b/src/bindgen/ir/typedef.rs index 6e13e1a..a11e41c 100644 --- a/src/bindgen/ir/typedef.rs +++ b/src/bindgen/ir/typedef.rs
@@ -22,7 +22,8 @@ /// A type alias that is represented as a C typedef #[derive(Debug, Clone)] pub struct Typedef { - pub name: String, + pub path: Path, + pub export_name: String, pub generic_params: GenericParams, pub aliased: Type, pub cfg: Option<Cfg>, @@ -33,19 +34,40 @@ impl Typedef { pub fn load(item: &syn::ItemType, mod_cfg: &Option<Cfg>) -> Result<Typedef, String> { if let Some(x) = Type::load(&item.ty)? { - Ok(Typedef { - name: item.ident.to_string(), - generic_params: GenericParams::new(&item.generics), - aliased: x, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + let path = Path::new(item.ident.to_string()); + Ok(Typedef::new( + path, + GenericParams::new(&item.generics), + x, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) } else { Err("Cannot have a typedef of a zero sized type.".to_owned()) } } + pub fn new( + path: Path, + generic_params: GenericParams, + aliased: Type, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generic_params, + aliased, + cfg, + annotations, + documentation, + } + } + pub fn simplify_standard_types(&mut self) { self.aliased.simplify_standard_types(); } @@ -60,7 +82,7 @@ if out.contains_key(&alias_path) { warn!( "Multiple typedef's with annotations for {}. Ignoring annotations from {}.", - alias_path, self.name + alias_path, self.path ); return; } @@ -92,8 +114,12 @@ } impl Item for Typedef { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -113,7 +139,7 @@ } fn rename_for_config(&mut self, config: &Config) { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); self.aliased.rename_for_config(config, &self.generic_params); } @@ -128,19 +154,19 @@ fn instantiate_monomorph( &self, - generic_values: &Vec<Type>, + generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", - self.name + self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", - self.name, + self.path, self.generic_params.len(), generic_values.len(), ); @@ -151,19 +177,20 @@ .zip(generic_values.iter()) .collect::<Vec<_>>(); - let monomorph = Typedef { - name: mangle::mangle_path(&self.name, generic_values), - generic_params: GenericParams::default(), - aliased: self.aliased.specialize(&mappings), - cfg: self.cfg.clone(), - annotations: self.annotations.clone(), - documentation: self.documentation.clone(), - }; + let mangled_path = mangle::mangle_path(&self.path, generic_values); + let monomorph = Typedef::new( + mangled_path, + GenericParams::default(), + self.aliased.specialize(&mappings), + self.cfg.clone(), + self.annotations.clone(), + self.documentation.clone(), + ); // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); - out.insert_typedef(self, monomorph, generic_values.clone()); + out.insert_typedef(self, monomorph, generic_values.to_owned()); } } @@ -178,9 +205,9 @@ if config.language == Language::C { out.write("typedef "); - (self.name.clone(), self.aliased.clone()).write(config, out); + (self.export_name().to_owned(), self.aliased.clone()).write(config, out); } else { - write!(out, "using {} = ", self.name); + write!(out, "using {} = ", self.export_name()); self.aliased.write(config, out); } out.write(";");
diff --git a/src/bindgen/ir/union.rs b/src/bindgen/ir/union.rs index ecc2086..ac92bc9 100644 --- a/src/bindgen/ir/union.rs +++ b/src/bindgen/ir/union.rs
@@ -11,8 +11,8 @@ use bindgen::dependencies::Dependencies; use bindgen::ir::SynFieldHelpers; use bindgen::ir::{ - AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Repr, - ToCondition, Type, + AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path, + Repr, ToCondition, Type, }; use bindgen::library::Library; use bindgen::mangle; @@ -23,7 +23,8 @@ #[derive(Debug, Clone)] pub struct Union { - pub name: String, + pub path: Path, + pub export_name: String, pub generic_params: GenericParams, pub fields: Vec<(String, Type, Documentation)>, pub tuple_union: bool, @@ -47,15 +48,37 @@ (out, false) }; - Ok(Union { - name: item.ident.to_string(), - generic_params: GenericParams::new(&item.generics), - fields: fields, - tuple_union: tuple_union, - cfg: Cfg::append(mod_cfg, Cfg::load(&item.attrs)), - annotations: AnnotationSet::load(&item.attrs)?, - documentation: Documentation::load(&item.attrs), - }) + Ok(Union::new( + Path::new(item.ident.to_string()), + GenericParams::new(&item.generics), + fields, + tuple_union, + Cfg::append(mod_cfg, Cfg::load(&item.attrs)), + AnnotationSet::load(&item.attrs)?, + Documentation::load(&item.attrs), + )) + } + + pub fn new( + path: Path, + generic_params: GenericParams, + fields: Vec<(String, Type, Documentation)>, + tuple_union: bool, + cfg: Option<Cfg>, + annotations: AnnotationSet, + documentation: Documentation, + ) -> Self { + let export_name = path.name().to_owned(); + Self { + path, + export_name, + generic_params, + fields, + tuple_union, + cfg, + annotations, + documentation, + } } pub fn simplify_standard_types(&mut self) { @@ -88,8 +111,12 @@ } impl Item for Union { - fn name(&self) -> &str { - &self.name + fn path(&self) -> &Path { + &self.path + } + + fn export_name(&self) -> &str { + &self.export_name } fn cfg(&self) -> &Option<Cfg> { @@ -109,7 +136,7 @@ } fn collect_declaration_types(&self, resolver: &mut DeclarationTypeResolver) { - resolver.add_union(&self.name); + resolver.add_union(&self.path); } fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { @@ -119,7 +146,7 @@ } fn rename_for_config(&mut self, config: &Config) { - config.export.rename(&mut self.name); + config.export.rename(&mut self.export_name); for &mut (_, ref mut ty, _) in &mut self.fields { ty.rename_for_config(config, &self.generic_params); } @@ -170,19 +197,19 @@ fn instantiate_monomorph( &self, - generic_values: &Vec<Type>, + generic_values: &[Type], library: &Library, out: &mut Monomorphs, ) { assert!( self.generic_params.len() > 0, "{} is not generic", - self.name + self.path ); assert!( self.generic_params.len() == generic_values.len(), "{} has {} params but is being instantiated with {} values", - self.name, + self.path, self.generic_params.len(), generic_values.len(), ); @@ -193,24 +220,24 @@ .zip(generic_values.iter()) .collect::<Vec<_>>(); - let monomorph = Union { - name: mangle::mangle_path(&self.name, generic_values), - generic_params: GenericParams::default(), - fields: self - .fields + let mangled_path = mangle::mangle_path(&self.path, generic_values); + let monomorph = Union::new( + mangled_path, + GenericParams::default(), + self.fields .iter() .map(|x| (x.0.clone(), x.1.specialize(&mappings), x.2.clone())) .collect(), - tuple_union: self.tuple_union, - cfg: self.cfg.clone(), - annotations: self.annotations.clone(), - documentation: self.documentation.clone(), - }; + self.tuple_union, + self.cfg.clone(), + self.annotations.clone(), + self.documentation.clone(), + ); // Instantiate any monomorphs for any generic paths we may have just created. monomorph.add_monomorphs(library, out); - out.insert_union(self, monomorph, generic_values.clone()); + out.insert_union(self, monomorph, generic_values.to_owned()); } } @@ -237,7 +264,7 @@ out.write("union"); if config.language == Language::Cxx || config.style.generate_tag() { - write!(out, " {}", self.name); + write!(out, " {}", self.export_name); } out.open_brace(); @@ -245,19 +272,17 @@ if config.documentation { out.write_vertical_source_list(&self.fields, ListType::Cap(";")); } else { - out.write_vertical_source_list( - &self - .fields - .iter() - .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) - .collect(), - ListType::Cap(";"), - ); + let vec: Vec<_> = self + .fields + .iter() + .map(|&(ref name, ref ty, _)| (name.clone(), ty.clone())) + .collect(); + out.write_vertical_source_list(&vec[..], ListType::Cap(";")); } if config.language == Language::C && config.style.generate_typedef() { out.close_brace(false); - write!(out, " {};", self.name); + write!(out, " {};", self.export_name); } else { out.close_brace(true); }
diff --git a/src/bindgen/library.rs b/src/bindgen/library.rs index 9acf8c2..3409c4d 100644 --- a/src/bindgen/library.rs +++ b/src/bindgen/library.rs
@@ -55,17 +55,17 @@ pub fn generate(mut self) -> Result<Bindings, Error> { self.remove_excluded(); - self.functions.sort_by(|x, y| x.name.cmp(&y.name)); + self.functions.sort_by(|x, y| x.path.cmp(&y.path)); self.transfer_annotations(); - self.rename_items(); self.simplify_standard_types(); if self.config.language == Language::C { self.instantiate_monomorphs(); - self.resolve_declaration_types(); } + self.rename_items(); + let mut dependencies = Dependencies::new(); for function in &self.functions { @@ -75,9 +75,10 @@ global.add_dependencies(&self, &mut dependencies); }); for name in &self.config.export.include { - if let Some(items) = self.get_items(name) { - if !dependencies.items.contains(name) { - dependencies.items.insert(name.clone()); + let path = Path::new(name.clone()); + if let Some(items) = self.get_items(&path) { + if !dependencies.items.contains(&path) { + dependencies.items.insert(path); for item in &items { item.deref().add_dependencies(&self, &mut dependencies); @@ -140,22 +141,23 @@ fn remove_excluded(&mut self) { let config = &self.config; + // FIXME: interpret `config.export.exclude` as `Path`s. self.functions - .retain(|x| !config.export.exclude.contains(&x.name)); + .retain(|x| !config.export.exclude.iter().any(|y| y == x.path().name())); self.enums - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.structs - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.unions - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.opaque_items - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.typedefs - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.globals - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); self.constants - .filter(|x| config.export.exclude.contains(&x.name)); + .filter(|x| config.export.exclude.iter().any(|y| y == x.path().name())); } fn transfer_annotations(&mut self) {
diff --git a/src/bindgen/mangle.rs b/src/bindgen/mangle.rs index 27bf5f3..5fdcfe2 100644 --- a/src/bindgen/mangle.rs +++ b/src/bindgen/mangle.rs
@@ -2,36 +2,46 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bindgen::ir::Type; +use bindgen::ir::{Path, Type}; -pub fn mangle_path(name: &str, generic_values: &[Type]) -> String { - internal_mangle_path(name, generic_values, true) +pub fn mangle_path(path: &Path, generic_values: &[Type]) -> Path { + internal_mangle_path(path, generic_values, true) } -fn internal_mangle_path(name: &str, generic_values: &[Type], last_in_parent: bool) -> String { +pub fn mangle_name(name: &str, generic_values: &[Type]) -> String { + internal_mangle_name(name, generic_values, true) +} + +fn internal_mangle_path(path: &Path, generic_values: &[Type], last_in_parent: bool) -> Path { + let name = path.name(); + let mangled_name = internal_mangle_name(name, generic_values, last_in_parent); + Path::new(mangled_name) +} + +fn internal_mangle_name(name: &str, generic_values: &[Type], last_in_parent: bool) -> String { if generic_values.is_empty() { - return String::from(name); + return name.to_owned(); } - let mut out = String::from(name); + let mut mangled = name.to_owned(); - out.push_str("_"); // < + mangled.push_str("_"); // < for (i, ty) in generic_values.iter().enumerate() { if i != 0 { - out.push_str("__"); // , + mangled.push_str("__"); // , } let is_last = i == generic_values.len() - 1; match ty { - &Type::Path(ref path) => { - out.push_str(&internal_mangle_path( - &path.name, - &path.generics, + &Type::Path(ref generic) => { + mangled.push_str(&internal_mangle_name( + generic.export_name(), + generic.generics(), last_in_parent && is_last, )); } &Type::Primitive(ref primitive) => { - out.push_str(primitive.to_repr_rust()); + mangled.push_str(primitive.to_repr_rust()); } &Type::ConstPtr(..) | &Type::Ptr(..) | &Type::Array(..) | &Type::FuncPtr(..) => { unimplemented!() @@ -40,11 +50,11 @@ // Skip writing the trailing '>' mangling when possible if is_last && !last_in_parent { - out.push_str("___"); // > + mangled.push_str("___"); // > } } - out + mangled } #[test] @@ -56,46 +66,57 @@ } fn path(path: &str) -> Type { - Type::Path(GenericPath::new(path.to_owned(), Vec::new())) + generic_path(path, &vec![]) } fn generic_path(path: &str, generics: &[Type]) -> Type { - Type::Path(GenericPath::new(path.to_owned(), generics.to_owned())) + let path = Path::new(path); + let generic_path = GenericPath::new(path, generics.to_owned()); + Type::Path(generic_path) } // Foo<f32> => Foo_f32 - assert_eq!(mangle_path("Foo", &vec![float()]), "Foo_f32"); + assert_eq!( + mangle_path(&Path::new("Foo"), &vec![float()]), + Path::new("Foo_f32") + ); // Foo<Bar<f32>> => Foo_Bar_f32 assert_eq!( - mangle_path("Foo", &vec![generic_path("Bar", &[float()])]), - "Foo_Bar_f32" + mangle_path(&Path::new("Foo"), &vec![generic_path("Bar", &[float()])]), + Path::new("Foo_Bar_f32") ); // Foo<Bar> => Foo_Bar - assert_eq!(mangle_path("Foo", &[path("Bar")]), "Foo_Bar"); + assert_eq!( + mangle_path(&Path::new("Foo"), &[path("Bar")]), + Path::new("Foo_Bar") + ); // Foo<Bar<T>> => Foo_Bar_T assert_eq!( - mangle_path("Foo", &[generic_path("Bar", &[path("T")])]), - "Foo_Bar_T" + mangle_path(&Path::new("Foo"), &[generic_path("Bar", &[path("T")])]), + Path::new("Foo_Bar_T") ); // Foo<Bar<T>, E> => Foo_Bar_T_____E assert_eq!( - mangle_path("Foo", &[generic_path("Bar", &[path("T")]), path("E")]), - "Foo_Bar_T_____E" + mangle_path( + &Path::new("Foo"), + &[generic_path("Bar", &[path("T")]), path("E")] + ), + Path::new("Foo_Bar_T_____E") ); // Foo<Bar<T>, Bar<E>> => Foo_Bar_T_____Bar_E assert_eq!( mangle_path( - "Foo", + &Path::new("Foo"), &[ generic_path("Bar", &[path("T")]), generic_path("Bar", &[path("E")]), ] ), - "Foo_Bar_T_____Bar_E" + Path::new("Foo_Bar_T_____Bar_E") ); }
diff --git a/src/bindgen/monomorph.rs b/src/bindgen/monomorph.rs index 31268f9..c0739ab 100644 --- a/src/bindgen/monomorph.rs +++ b/src/bindgen/monomorph.rs
@@ -23,35 +23,35 @@ } pub fn insert_struct(&mut self, generic: &Struct, monomorph: Struct, parameters: Vec<Type>) { - let replacement_path = GenericPath::new(generic.name.clone(), parameters); + let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements - .insert(replacement_path, monomorph.name.clone()); + .insert(replacement_path, monomorph.path.clone()); self.structs.push(monomorph); } pub fn insert_enum(&mut self, generic: &Enum, monomorph: Enum, parameters: Vec<Type>) { - let replacement_path = GenericPath::new(generic.name.clone(), parameters); + let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements - .insert(replacement_path, monomorph.name.clone()); + .insert(replacement_path, monomorph.path.clone()); self.enums.push(monomorph); } pub fn insert_union(&mut self, generic: &Union, monomorph: Union, parameters: Vec<Type>) { - let replacement_path = GenericPath::new(generic.name.clone(), parameters); + let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements - .insert(replacement_path, monomorph.name.clone()); + .insert(replacement_path, monomorph.path.clone()); self.unions.push(monomorph); } @@ -61,24 +61,24 @@ monomorph: OpaqueItem, parameters: Vec<Type>, ) { - let replacement_path = GenericPath::new(generic.name.clone(), parameters); + let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements - .insert(replacement_path, monomorph.name.clone()); + .insert(replacement_path, monomorph.path.clone()); self.opaques.push(monomorph); } pub fn insert_typedef(&mut self, generic: &Typedef, monomorph: Typedef, parameters: Vec<Type>) { - let replacement_path = GenericPath::new(generic.name.clone(), parameters); + let replacement_path = GenericPath::new(generic.path.clone(), parameters); debug_assert!(generic.generic_params.len() > 0); debug_assert!(!self.contains(&replacement_path)); self.replacements - .insert(replacement_path, monomorph.name.clone()); + .insert(replacement_path, monomorph.path.clone()); self.typedefs.push(monomorph); }
diff --git a/src/bindgen/parser.rs b/src/bindgen/parser.rs index d078646..1d60444 100644 --- a/src/bindgen/parser.rs +++ b/src/bindgen/parser.rs
@@ -5,14 +5,16 @@ use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::Read; -use std::path::{Path, PathBuf}; +use std::path::{Path as FilePath, PathBuf as FilePathBuf}; use syn; use bindgen::cargo::{Cargo, PackageRef}; use bindgen::error::Error; -use bindgen::ir::{AnnotationSet, Cfg, Constant, Documentation, Enum, Function, GenericParams}; -use bindgen::ir::{ItemMap, OpaqueItem, Static, Struct, Typedef, Union}; +use bindgen::ir::{ + AnnotationSet, Cfg, Constant, Documentation, Enum, Function, GenericParams, ItemMap, + OpaqueItem, Path, Static, Struct, Typedef, Union, +}; use bindgen::utilities::{SynAbiHelpers, SynItemHelpers}; const STD_CRATES: &'static [&'static str] = &[ @@ -27,7 +29,7 @@ type ParseResult = Result<Parse, Error>; /// Parses a single rust source file, not following `mod` or `extern crate`. -pub fn parse_src(src_file: &Path) -> ParseResult { +pub fn parse_src(src_file: &FilePath) -> ParseResult { let mod_name = src_file.file_stem().unwrap().to_str().unwrap(); let mut context = Parser { @@ -65,8 +67,8 @@ lib: Cargo, parse_deps: bool, include: &Option<Vec<String>>, - exclude: &Vec<String>, - expand: &Vec<String>, + exclude: &[String], + expand: &[String], expand_all_features: bool, expand_default_features: bool, expand_features: &Option<Vec<String>>, @@ -76,8 +78,8 @@ lib: Some(lib), parse_deps: parse_deps, include: include.clone(), - exclude: exclude.clone(), - expand: expand.clone(), + exclude: exclude.to_owned(), + expand: expand.to_owned(), expand_all_features, expand_default_features, expand_features: expand_features.clone(), @@ -107,7 +109,7 @@ expand_features: Option<Vec<String>>, parsed_crates: HashSet<String>, - cache_src: HashMap<PathBuf, Vec<syn::Item>>, + cache_src: HashMap<FilePathBuf, Vec<syn::Item>>, cache_expanded_crate: HashMap<String, Vec<syn::Item>>, cfg_stack: Vec<Cfg>, @@ -267,7 +269,7 @@ Ok(()) } - fn parse_mod(&mut self, pkg: &PackageRef, mod_path: &Path) -> Result<(), Error> { + fn parse_mod(&mut self, pkg: &PackageRef, mod_path: &FilePath) -> Result<(), Error> { let mod_parsed = { let owned_mod_path = mod_path.to_path_buf(); @@ -303,7 +305,7 @@ fn process_mod( &mut self, pkg: &PackageRef, - mod_dir: &Path, + mod_dir: &FilePath, items: &[syn::Item], ) -> Result<(), Error> { self.out.load_syn_crate_mod( @@ -446,16 +448,16 @@ } pub fn add_std_types(&mut self) { - let mut add_opaque = |name: &str, generic_params: Vec<&str>| { - self.opaque_items.try_insert(OpaqueItem { - name: name.to_owned(), - generic_params: GenericParams( - generic_params.iter().map(|x| (*x).to_owned()).collect(), - ), - cfg: None, - annotations: AnnotationSet::new(), - documentation: Documentation::none(), - }) + let mut add_opaque = |path: &str, generic_params: Vec<&str>| { + let path = Path::new(path); + let generic_params: Vec<_> = generic_params.into_iter().map(|s| Path::new(s)).collect(); + self.opaque_items.try_insert(OpaqueItem::new( + path, + GenericParams(generic_params), + None, + AnnotationSet::new(), + Documentation::none(), + )) }; add_opaque("String", vec![]); @@ -564,14 +566,8 @@ ); return; } - - match Function::load( - function.ident.to_string(), - &function.decl, - true, - &function.attrs, - mod_cfg, - ) { + let path = Path::new(function.ident.to_string()); + match Function::load(path, &function.decl, true, &function.attrs, mod_cfg) { Ok(func) => { info!("Take {}::{}.", crate_name, &function.ident); @@ -608,13 +604,8 @@ if let syn::Visibility::Public(_) = item.vis { if item.is_no_mangle() && (item.abi.is_omitted() || item.abi.is_c()) { - match Function::load( - item.ident.to_string(), - &item.decl, - false, - &item.attrs, - mod_cfg, - ) { + let path = Path::new(item.ident.to_string()); + match Function::load(path, &item.decl, false, &item.attrs, mod_cfg) { Ok(func) => { info!("Take {}::{}.", crate_name, &item.ident); @@ -693,9 +684,9 @@ return; } - let const_name = item.ident.to_string(); + let path = Path::new(item.ident.to_string()); - match Constant::load(const_name.clone(), item, mod_cfg) { + match Constant::load(path, item, mod_cfg) { Ok(constant) => { info!("Take {}::{}.", crate_name, &item.ident); @@ -758,12 +749,10 @@ } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); - self.opaque_items.try_insert(OpaqueItem::new( - item.ident.to_string(), - &item.generics, - &item.attrs, - mod_cfg, - )); + let path = Path::new(item.ident.to_string()); + self.opaque_items.try_insert( + OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), + ); } } } @@ -778,12 +767,10 @@ } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); - self.opaque_items.try_insert(OpaqueItem::new( - item.ident.to_string(), - &item.generics, - &item.attrs, - mod_cfg, - )); + let path = Path::new(item.ident.to_string()); + self.opaque_items.try_insert( + OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), + ); } } } @@ -805,12 +792,10 @@ } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); - self.opaque_items.try_insert(OpaqueItem::new( - item.ident.to_string(), - &item.generics, - &item.attrs, - mod_cfg, - )); + let path = Path::new(item.ident.to_string()); + self.opaque_items.try_insert( + OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), + ); } } } @@ -825,12 +810,10 @@ } Err(msg) => { info!("Take {}::{} - opaque ({}).", crate_name, &item.ident, msg); - self.opaque_items.try_insert(OpaqueItem::new( - item.ident.to_string(), - &item.generics, - &item.attrs, - mod_cfg, - )); + let path = Path::new(item.ident.to_string()); + self.opaque_items.try_insert( + OpaqueItem::load(path, &item.generics, &item.attrs, mod_cfg).unwrap(), + ); } } }
diff --git a/src/bindgen/rename.rs b/src/bindgen/rename.rs index 1d7399f..eb5b129 100644 --- a/src/bindgen/rename.rs +++ b/src/bindgen/rename.rs
@@ -4,7 +4,7 @@ use std::str::FromStr; -use bindgen::ir::Enum; +use bindgen::ir::{Enum, Item}; /// The type of identifier to be renamed. #[derive(Debug, Clone, Copy)] @@ -96,7 +96,7 @@ if let &RenameRule::QualifiedScreamingSnakeCase = self { result.push_str( &RenameRule::ScreamingSnakeCase - .apply_to_pascal_case(&e.name, IdentifierType::Enum), + .apply_to_pascal_case(e.path().name(), IdentifierType::Enum), ); result.push_str("_"); } @@ -177,7 +177,7 @@ if let &RenameRule::QualifiedScreamingSnakeCase = self { result.push_str( &RenameRule::ScreamingSnakeCase - .apply_to_snake_case(&e.name, IdentifierType::Enum), + .apply_to_snake_case(e.path().name(), IdentifierType::Enum), ); result.push_str("_"); }
diff --git a/src/bindgen/writer.rs b/src/bindgen/writer.rs index e8daf51..a824405 100644 --- a/src/bindgen/writer.rs +++ b/src/bindgen/writer.rs
@@ -176,7 +176,7 @@ pub fn write_horizontal_source_list<'b, S: Source>( &mut self, - items: &Vec<S>, + items: &[S], list_type: ListType<'b>, ) { for (i, ref item) in items.iter().enumerate() { @@ -197,7 +197,7 @@ pub fn write_vertical_source_list<'b, S: Source>( &mut self, - items: &Vec<S>, + items: &[S], list_type: ListType<'b>, ) { let align_length = self.line_length_for_align();
diff --git a/tests/expectations/both/transform-op.c b/tests/expectations/both/transform-op.c index c655225..583fd71 100644 --- a/tests/expectations/both/transform-op.c +++ b/tests/expectations/both/transform-op.c
@@ -12,44 +12,44 @@ float y; } StylePoint_f32; -enum StyleFoo_Tag { +enum StyleFoo_i32_Tag { Foo_i32, Bar_i32, Baz_i32, Bazz_i32, }; -typedef uint8_t StyleFoo_Tag; +typedef uint8_t StyleFoo_i32_Tag; typedef struct StyleFoo_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t x; StylePoint_i32 y; StylePoint_f32 z; } StyleFoo_Body_i32; typedef struct StyleBar_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t _0; } StyleBar_Body_i32; typedef struct StyleBaz_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; StylePoint_i32 _0; } StyleBaz_Body_i32; typedef union StyleFoo_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; StyleFoo_Body_i32 foo; StyleBar_Body_i32 bar; StyleBaz_Body_i32 baz; } StyleFoo_i32; -typedef enum StyleBar_Tag { +typedef enum StyleBar_i32_Tag { Bar1_i32, Bar2_i32, Bar3_i32, Bar4_i32, -} StyleBar_Tag; +} StyleBar_i32_Tag; typedef struct StyleBar1_Body_i32 { int32_t x; @@ -66,7 +66,7 @@ } StyleBar3_Body_i32; typedef struct StyleBar_i32 { - StyleBar_Tag tag; + StyleBar_i32_Tag tag; union { StyleBar1_Body_i32 bar1; StyleBar2_Body_i32 bar2;
diff --git a/tests/expectations/tag/transform-op.c b/tests/expectations/tag/transform-op.c index a814e9f..188b74b 100644 --- a/tests/expectations/tag/transform-op.c +++ b/tests/expectations/tag/transform-op.c
@@ -12,39 +12,39 @@ float y; }; -enum StyleFoo_Tag { +enum StyleFoo_i32_Tag { Foo_i32, Bar_i32, Baz_i32, Bazz_i32, }; -typedef uint8_t StyleFoo_Tag; +typedef uint8_t StyleFoo_i32_Tag; struct StyleFoo_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t x; struct StylePoint_i32 y; struct StylePoint_f32 z; }; struct StyleBar_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t _0; }; struct StyleBaz_Body_i32 { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; struct StylePoint_i32 _0; }; union StyleFoo_i32 { - enum StyleFoo_Tag tag; + enum StyleFoo_i32_Tag tag; struct StyleFoo_Body_i32 foo; struct StyleBar_Body_i32 bar; struct StyleBaz_Body_i32 baz; }; -enum StyleBar_Tag { +enum StyleBar_i32_Tag { Bar1_i32, Bar2_i32, Bar3_i32, @@ -66,7 +66,7 @@ }; struct StyleBar_i32 { - enum StyleBar_Tag tag; + enum StyleBar_i32_Tag tag; union { struct StyleBar1_Body_i32 bar1; struct StyleBar2_Body_i32 bar2;
diff --git a/tests/expectations/transform-op.c b/tests/expectations/transform-op.c index 6f67f8d..03c4744 100644 --- a/tests/expectations/transform-op.c +++ b/tests/expectations/transform-op.c
@@ -12,33 +12,33 @@ float y; } StylePoint_f32; -enum StyleFoo_Tag { +enum StyleFoo_i32_Tag { Foo_i32, Bar_i32, Baz_i32, Bazz_i32, }; -typedef uint8_t StyleFoo_Tag; +typedef uint8_t StyleFoo_i32_Tag; typedef struct { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t x; StylePoint_i32 y; StylePoint_f32 z; } StyleFoo_Body_i32; typedef struct { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; int32_t _0; } StyleBar_Body_i32; typedef struct { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; StylePoint_i32 _0; } StyleBaz_Body_i32; typedef union { - StyleFoo_Tag tag; + StyleFoo_i32_Tag tag; StyleFoo_Body_i32 foo; StyleBar_Body_i32 bar; StyleBaz_Body_i32 baz; @@ -49,7 +49,7 @@ Bar2_i32, Bar3_i32, Bar4_i32, -} StyleBar_Tag; +} StyleBar_i32_Tag; typedef struct { int32_t x; @@ -66,7 +66,7 @@ } StyleBar3_Body_i32; typedef struct { - StyleBar_Tag tag; + StyleBar_i32_Tag tag; union { StyleBar1_Body_i32 bar1; StyleBar2_Body_i32 bar2;