Skip to content

codegen: Prefer use instead of type aliases. #396

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bindgen-integration/cpp/Test.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ class Test {
Test(int foo);
Test(double foo);
};

typedef Test TypeAlias;
6 changes: 3 additions & 3 deletions libbindgen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ cfg-if = "0.1.0"
clang-sys = { version = "0.12", features = ["runtime", "clang_3_9"] }
lazy_static = "0.2.1"
rustc-serialize = "0.3.19"
syntex_syntax = "0.50"
syntex_syntax = "0.54"
regex = "0.2"

[dependencies.aster]
features = ["with-syntex"]
version = "0.34"
version = "0.38"

[dependencies.env_logger]
optional = true
Expand All @@ -46,7 +46,7 @@ version = "0.3"

[dependencies.quasi]
features = ["with-syntex"]
version = "0.26"
version = "0.29"

[features]
assert_no_dangling_items = []
Expand Down
5 changes: 2 additions & 3 deletions libbindgen/src/codegen/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,16 +153,15 @@ pub mod ast_ty {
}

pub fn float_expr(f: f64) -> P<ast::Expr> {
use aster::str::ToInternedString;
use aster::symbol::ToSymbol;
let mut string = f.to_string();

// So it gets properly recognised as a floating point constant.
if !string.contains('.') {
string.push('.');
}

let interned_str = string.as_str().to_interned_string();
let kind = ast::LitKind::FloatUnsuffixed(interned_str);
let kind = ast::LitKind::FloatUnsuffixed(string.as_str().to_symbol());
aster::AstBuilder::new().expr().lit().build_lit(kind)
}

Expand Down
63 changes: 45 additions & 18 deletions libbindgen/src/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -523,22 +523,46 @@ impl CodeGenerator for Type {
typedef = typedef.attr().doc(comment);
}

let mut generics = typedef.type_(rust_name).generics();
for template_arg in applicable_template_args.iter() {
let template_arg = ctx.resolve_type(*template_arg);
if template_arg.is_named() {
let name = template_arg.name().unwrap();
if name.contains("typename ") {
warn!("Item contained `typename`'d template \
parameter: {:?}", item);
return;
// We prefer using `pub use` over `pub type` because of:
// https://github.com/rust-lang/rust/issues/26264
let simple_enum_path = match inner_rust_type.node {
ast::TyKind::Path(None, ref p) => {
if applicable_template_args.is_empty() &&
!inner_item.expect_type().canonical_type(ctx).is_builtin_or_named() &&
p.segments.iter().all(|p| p.parameters.is_none()) {
Some(p.clone())
} else {
None
}
generics =
generics.ty_param_id(template_arg.name().unwrap());
}
}
},
_ => None,
};

let typedef = generics.build().build_ty(inner_rust_type);
let typedef = if let Some(mut p) = simple_enum_path {
if p.segments.len() == 1 {
p.segments.insert(0, ast::PathSegment {
identifier: ctx.ext_cx().ident_of("self"),
parameters: None,
});
}
typedef.use_().build(p).as_(rust_name)
} else {
let mut generics = typedef.type_(rust_name).generics();
for template_arg in applicable_template_args.iter() {
let template_arg = ctx.resolve_type(*template_arg);
if template_arg.is_named() {
let name = template_arg.name().unwrap();
if name.contains("typename ") {
warn!("Item contained `typename`'d template \
parameter: {:?}", item);
return;
}
generics =
generics.ty_param_id(template_arg.name().unwrap());
}
}
generics.build().build_ty(inner_rust_type)
};
result.push(typedef)
}
TypeKind::Enum(ref ei) => {
Expand Down Expand Up @@ -1863,16 +1887,19 @@ impl ToRustTy for Type {
if let ast::TyKind::Path(_, ref mut path) = inner_ty.node {
let template_args = template_args.iter()
.map(|arg| arg.to_rust_ty(ctx))
.collect();
.collect::<Vec<_>>();

path.segments.last_mut().unwrap().parameters =
ast::PathParameters::AngleBracketed(
path.segments.last_mut().unwrap().parameters = if template_args.is_empty() {
None
} else {
Some(P(ast::PathParameters::AngleBracketed(
ast::AngleBracketedParameterData {
lifetimes: vec![],
types: P::from_vec(template_args),
bindings: P::from_vec(vec![]),
}
);
)))
}
}

P(inner_ty)
Expand Down
3 changes: 2 additions & 1 deletion libbindgen/src/ir/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,7 @@ impl<'ctx> BindgenContext<'ctx> {
pub fn gen<F, Out>(&mut self, cb: F) -> Out
where F: FnOnce(&Self) -> Out,
{
use aster::symbol::ToSymbol;
use syntax::ext::expand::ExpansionConfig;
use syntax::codemap::{ExpnInfo, MacroBang, NameAndSpan};
use syntax::ext::base;
Expand All @@ -475,7 +476,7 @@ impl<'ctx> BindgenContext<'ctx> {
ctx.0.bt_push(ExpnInfo {
call_site: self.span,
callee: NameAndSpan {
format: MacroBang(parse::token::intern("")),
format: MacroBang("".to_symbol()),
allow_internal_unstable: false,
span: None,
},
Expand Down
8 changes: 8 additions & 0 deletions libbindgen/src/ir/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ impl Type {
}
}

/// Is this an enum type?
pub fn is_enum(&self) -> bool {
match self.kind {
TypeKind::Enum(..) => true,
_ => false,
}
}

/// Is this either a builtin or named type?
pub fn is_builtin_or_named(&self) -> bool {
match self.kind {
Expand Down
6 changes: 6 additions & 0 deletions libbindgen/tests/expectations/tests/anon_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,9 @@ fn bindgen_test_layout_Test() {
impl Clone for Test {
fn clone(&self) -> Self { *self }
}
pub const Foo: _bindgen_ty_1 = _bindgen_ty_1::Foo;
pub const Bar: _bindgen_ty_1 = _bindgen_ty_1::Bar;
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_1 { Foo = 0, Bar = 1, }
pub use self::_bindgen_ty_1 as Baz;
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ impl _bindgen_ty_1 {
((val as u32 as u32) << 24u32) & (4278190080usize as u32);
}
}
pub type mach_msg_type_descriptor_t = _bindgen_ty_1;
pub use self::_bindgen_ty_1 as mach_msg_type_descriptor_t;
2 changes: 1 addition & 1 deletion libbindgen/tests/expectations/tests/inherit_typedef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn bindgen_test_layout_Foo() {
impl Clone for Foo {
fn clone(&self) -> Self { *self }
}
pub type TypedefedFoo = Foo;
pub use self::Foo as TypedefedFoo;
#[repr(C)]
#[derive(Debug, Copy)]
pub struct Bar {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ pub mod root {
fn clone(&self) -> Self { *self }
}
}
pub type ReferencesBar = root::foo::Bar;
pub use root::foo::Bar as ReferencesBar;
}
2 changes: 1 addition & 1 deletion libbindgen/tests/expectations/tests/union_fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ fn bindgen_test_layout__bindgen_ty_1() {
impl Clone for _bindgen_ty_1 {
fn clone(&self) -> Self { *self }
}
pub type nsStyleUnion = _bindgen_ty_1;
pub use self::_bindgen_ty_1 as nsStyleUnion;
2 changes: 1 addition & 1 deletion libbindgen/tests/expectations/tests/unknown_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ pub struct _bindgen_ty_1 {
impl Clone for _bindgen_ty_1 {
fn clone(&self) -> Self { *self }
}
pub type max_align_t = _bindgen_ty_1;
pub use self::_bindgen_ty_1 as max_align_t;
5 changes: 5 additions & 0 deletions libbindgen/tests/headers/anon_enum.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,8 @@ struct Test {
float bar;
enum { T_NONE };
};

typedef enum {
Foo,
Bar,
} Baz;