From cca5215060cb472902d52fba9414fdd0ea9009d9 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Thu, 22 Oct 2020 17:45:08 -0700 Subject: [PATCH 1/8] Diagnostic improvement. --- syntax/check.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/syntax/check.rs b/syntax/check.rs index 2f3c33483..ced15707e 100644 --- a/syntax/check.rs +++ b/syntax/check.rs @@ -67,7 +67,7 @@ fn check_type_ident(cx: &mut Check, ident: &Ident) { && !cx.types.cxx.contains(ident) && !cx.types.rust.contains(ident) { - cx.error(ident, "unsupported type"); + cx.error(ident, &format!("unsupported type: {}", ident)); } } From 9a158e408fc916255be0dbf88cf39d1d6176d548 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Sat, 24 Oct 2020 20:51:25 -0700 Subject: [PATCH 2/8] Adding tests for types in namespaces. --- tests/ffi/lib.rs | 36 +++++++++++++++++++++++ tests/ffi/tests.cc | 72 ++++++++++++++++++++++++++++++++++++++++++++++ tests/ffi/tests.h | 21 ++++++++++++++ tests/test.rs | 23 +++++++++++++++ 4 files changed, 152 insertions(+) diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs index 4078b374e..621608e92 100644 --- a/tests/ffi/lib.rs +++ b/tests/ffi/lib.rs @@ -49,6 +49,32 @@ pub mod ffi { CVal, } + #[namespace(namespace = A)] + #[derive(Clone)] + struct AShared { + z: usize, + } + + #[namespace(namespace = A)] + enum AEnum { + AAVal, + ABVal = 2020, + ACVal, + } + + #[namespace(namespace = A::B)] + enum ABEnum { + ABAVal, + ABBVal = 2020, + ABCVal, + } + + #[namespace(namespace = A::B)] + #[derive(Clone)] + struct ABShared { + z: usize, + } + extern "C" { include!("tests/ffi/tests.h"); @@ -78,6 +104,10 @@ pub mod ffi { fn c_return_identity(_: usize) -> usize; fn c_return_sum(_: usize, _: usize) -> usize; fn c_return_enum(n: u16) -> Enum; + fn c_return_ns_ref(shared: &AShared) -> &usize; + fn c_return_nested_ns_ref(shared: &ABShared) -> &usize; + fn c_return_ns_enum(n: u16) -> AEnum; + fn c_return_nested_ns_enum(n: u16) -> ABEnum; fn c_take_primitive(n: usize); fn c_take_shared(shared: Shared); @@ -108,6 +138,12 @@ pub mod ffi { fn c_take_callback(callback: fn(String) -> usize); */ fn c_take_enum(e: Enum); + fn c_take_ns_enum(e: AEnum); + fn c_take_nested_ns_enum(e: ABEnum); + fn c_take_ns_shared(shared: AShared); + fn c_take_nested_ns_shared(shared: ABShared); + fn c_take_rust_vec_ns_shared(v: Vec); + fn c_take_rust_vec_nested_ns_shared(v: Vec); fn c_try_return_void() -> Result<()>; fn c_try_return_primitive() -> Result; diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 983cf955a..2c3739776 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -43,6 +43,10 @@ size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } +::A::AShared c_return_ns_shared() { return ::A::AShared{2020}; } + +::A::B::ABShared c_return_nested_ns_shared() { return ::A::B::ABShared{2020}; } + rust::Box c_return_box() { return rust::Box::from_raw(cxx_test_suite_get_box()); } @@ -53,6 +57,10 @@ std::unique_ptr c_return_unique_ptr() { const size_t &c_return_ref(const Shared &shared) { return shared.z; } +const size_t &c_return_ns_ref(const ::A::AShared &shared) { return shared.z; } + +const size_t &c_return_nested_ns_ref(const ::A::B::ABShared &shared) { return shared.z; } + size_t &c_return_mut(Shared &shared) { return shared.z; } rust::Str c_return_str(const Shared &shared) { @@ -144,6 +152,26 @@ Enum c_return_enum(uint16_t n) { } } +::A::AEnum c_return_ns_enum(uint16_t n) { + if (n <= static_cast(::A::AEnum::AAVal)) { + return ::A::AEnum::AAVal; + } else if (n <= static_cast(::A::AEnum::ABVal)) { + return ::A::AEnum::ABVal; + } else { + return ::A::AEnum::ACVal; + } +} + +::A::B::ABEnum c_return_nested_ns_enum(uint16_t n) { + if (n <= static_cast(::A::B::ABEnum::ABAVal)) { + return ::A::B::ABEnum::ABAVal; + } else if (n <= static_cast(::A::B::ABEnum::ABBVal)) { + return ::A::B::ABEnum::ABBVal; + } else { + return ::A::B::ABEnum::ABCVal; + } +} + void c_take_primitive(size_t n) { if (n == 2020) { cxx_test_suite_set_correct(); @@ -156,6 +184,18 @@ void c_take_shared(Shared shared) { } } +void c_take_ns_shared(::A::AShared shared) { + if (shared.z == 2020) { + cxx_test_suite_set_correct(); + } +} + +void c_take_nested_ns_shared(::A::B::ABShared shared) { + if (shared.z == 2020) { + cxx_test_suite_set_correct(); + } +} + void c_take_box(rust::Box r) { if (cxx_test_suite_r_is_correct(&*r)) { cxx_test_suite_set_correct(); @@ -258,6 +298,26 @@ void c_take_rust_vec_shared(rust::Vec v) { } } +void c_take_rust_vec_ns_shared(rust::Vec<::A::AShared> v) { + uint32_t sum = 0; + for (auto i : v) { + sum += i.z; + } + if (sum == 2021) { + cxx_test_suite_set_correct(); + } +} + +void c_take_rust_vec_nested_ns_shared(rust::Vec<::A::B::ABShared> v) { + uint32_t sum = 0; + for (auto i : v) { + sum += i.z; + } + if (sum == 2021) { + cxx_test_suite_set_correct(); + } +} + void c_take_rust_vec_string(rust::Vec v) { (void)v; cxx_test_suite_set_correct(); @@ -326,6 +386,18 @@ void c_take_enum(Enum e) { } } +void c_take_ns_enum(::A::AEnum e) { + if (e == ::A::AEnum::AAVal) { + cxx_test_suite_set_correct(); + } +} + +void c_take_nested_ns_enum(::A::B::ABEnum e) { + if (e == ::A::B::ABEnum::ABAVal) { + cxx_test_suite_set_correct(); + } +} + void c_try_return_void() {} size_t c_try_return_primitive() { return 2020; } diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index b3f547e5b..70d0a439a 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -3,6 +3,15 @@ #include #include +namespace A { + struct AShared; + enum class AEnum : uint16_t; + namespace B { + struct ABShared; + enum class ABEnum : uint16_t; + } // namespace B +} // namespace A + namespace tests { struct R; @@ -44,9 +53,13 @@ enum COwnedEnum { size_t c_return_primitive(); Shared c_return_shared(); +::A::AShared c_return_ns_shared(); +::A::B::ABShared c_return_nested_ns_shared(); rust::Box c_return_box(); std::unique_ptr c_return_unique_ptr(); const size_t &c_return_ref(const Shared &shared); +const size_t &c_return_ns_ref(const ::A::AShared &shared); +const size_t &c_return_nested_ns_ref(const ::A::B::ABShared &shared); size_t &c_return_mut(Shared &shared); rust::Str c_return_str(const Shared &shared); rust::Slice c_return_sliceu8(const Shared &shared); @@ -66,9 +79,13 @@ rust::Vec c_return_rust_vec_string(); size_t c_return_identity(size_t n); size_t c_return_sum(size_t n1, size_t n2); Enum c_return_enum(uint16_t n); +::A::AEnum c_return_ns_enum(uint16_t n); +::A::B::ABEnum c_return_nested_ns_enum(uint16_t n); void c_take_primitive(size_t n); void c_take_shared(Shared shared); +void c_take_ns_shared(::A::AShared shared); +void c_take_nested_ns_shared(::A::B::ABShared shared); void c_take_box(rust::Box r); void c_take_unique_ptr(std::unique_ptr c); void c_take_ref_r(const R &r); @@ -86,6 +103,8 @@ void c_take_ref_vector(const std::vector &v); void c_take_rust_vec(rust::Vec v); void c_take_rust_vec_index(rust::Vec v); void c_take_rust_vec_shared(rust::Vec v); +void c_take_rust_vec_ns_shared(rust::Vec<::A::AShared> v); +void c_take_rust_vec_nested_ns_shared(rust::Vec<::A::B::ABShared> v); void c_take_rust_vec_string(rust::Vec v); void c_take_rust_vec_shared_index(rust::Vec v); void c_take_rust_vec_shared_forward_iterator(rust::Vec v); @@ -98,6 +117,8 @@ void c_take_ref_rust_vec_copy(const rust::Vec &v); void c_take_callback(rust::Fn callback); */ void c_take_enum(Enum e); +void c_take_ns_enum(::A::AEnum e); +void c_take_nested_ns_enum(::A::B::ABEnum e); void c_try_return_void(); size_t c_try_return_primitive(); diff --git a/tests/test.rs b/tests/test.rs index b92eebfbd..eece7ff0a 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -23,12 +23,16 @@ macro_rules! check { #[test] fn test_c_return() { let shared = ffi::Shared { z: 2020 }; + let ns_shared = ffi::AShared { z: 2020 }; + let nested_ns_shared = ffi::ABShared { z: 2020 }; assert_eq!(2020, ffi::c_return_primitive()); assert_eq!(2020, ffi::c_return_shared().z); assert_eq!(2020, *ffi::c_return_box()); ffi::c_return_unique_ptr(); assert_eq!(2020, *ffi::c_return_ref(&shared)); + assert_eq!(2020, *ffi::c_return_ns_ref(&ns_shared)); + assert_eq!(2020, *ffi::c_return_nested_ns_ref(&nested_ns_shared)); assert_eq!("2020", ffi::c_return_str(&shared)); assert_eq!(b"2020\0", ffi::c_return_sliceu8(&shared)); assert_eq!("2020", ffi::c_return_rust_string()); @@ -64,6 +68,14 @@ fn test_c_return() { enm @ ffi::Enum::CVal => assert_eq!(2021, enm.repr), _ => assert!(false), } + match ffi::c_return_ns_enum(0) { + enm @ ffi::AEnum::AAVal => assert_eq!(0, enm.repr), + _ => assert!(false), + } + match ffi::c_return_nested_ns_enum(0) { + enm @ ffi::ABEnum::ABAVal => assert_eq!(0, enm.repr), + _ => assert!(false), + } } #[test] @@ -88,6 +100,8 @@ fn test_c_take() { check!(ffi::c_take_primitive(2020)); check!(ffi::c_take_shared(ffi::Shared { z: 2020 })); + check!(ffi::c_take_ns_shared(ffi::AShared { z: 2020 })); + check!(ffi::c_take_nested_ns_shared(ffi::ABShared { z: 2020 })); check!(ffi::c_take_box(Box::new(2020))); check!(ffi::c_take_ref_c(&unique_ptr)); check!(cxx_test_suite::module::ffi::c_take_unique_ptr(unique_ptr)); @@ -119,7 +133,16 @@ fn test_c_take() { check!(ffi::c_take_ref_rust_vec(&test_vec)); check!(ffi::c_take_ref_rust_vec_index(&test_vec)); check!(ffi::c_take_ref_rust_vec_copy(&test_vec)); + let ns_shared_test_vec = vec![ffi::AShared { z: 1010 }, ffi::AShared { z: 1011 }]; + check!(ffi::c_take_rust_vec_ns_shared(ns_shared_test_vec)); + let nested_ns_shared_test_vec = vec![ffi::ABShared { z: 1010 }, ffi::ABShared { z: 1011 }]; + check!(ffi::c_take_rust_vec_nested_ns_shared( + nested_ns_shared_test_vec + )); + check!(ffi::c_take_enum(ffi::Enum::AVal)); + check!(ffi::c_take_ns_enum(ffi::AEnum::AAVal)); + check!(ffi::c_take_nested_ns_enum(ffi::ABEnum::ABAVal)); } /* From 5e79c647696e55934e108397b2e1c3e824ce8079 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Sat, 24 Oct 2020 21:09:42 -0700 Subject: [PATCH 3/8] Tests for namespaced opaque extern types. --- tests/ffi/extra.rs | 6 ++++++ tests/ffi/lib.rs | 16 ++++++++++++++++ tests/ffi/tests.cc | 20 ++++++++++++++++++++ tests/ffi/tests.h | 10 ++++++++++ tests/test.rs | 4 ++++ 5 files changed, 56 insertions(+) diff --git a/tests/ffi/extra.rs b/tests/ffi/extra.rs index a809ea4ef..1faf37579 100644 --- a/tests/ffi/extra.rs +++ b/tests/ffi/extra.rs @@ -12,20 +12,26 @@ pub mod ffi2 { impl UniquePtr {} impl UniquePtr {} + impl UniquePtr {} extern "C" { include!("tests/ffi/tests.h"); type D = crate::other::D; type E = crate::other::E; + #[namespace (namespace = F)] + type F = crate::other::f::F; fn c_take_trivial_ptr(d: UniquePtr); fn c_take_trivial_ref(d: &D); fn c_take_trivial(d: D); fn c_take_opaque_ptr(e: UniquePtr); fn c_take_opaque_ref(e: &E); + fn c_take_opaque_ns_ptr(e: UniquePtr); + fn c_take_opaque_ns_ref(e: &F); fn c_return_trivial_ptr() -> UniquePtr; fn c_return_trivial() -> D; fn c_return_opaque_ptr() -> UniquePtr; + fn c_return_ns_opaque_ptr() -> UniquePtr; } } diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs index 621608e92..f25fd2a03 100644 --- a/tests/ffi/lib.rs +++ b/tests/ffi/lib.rs @@ -25,6 +25,22 @@ mod other { e_str: CxxString, } + pub mod f { + use cxx::kind::Opaque; + use cxx::{type_id, CxxString, ExternType}; + + #[repr(C)] + pub struct F { + e: u64, + e_str: CxxString, + } + + unsafe impl ExternType for F { + type Id = type_id!("F::F"); + type Kind = Opaque; + } + } + unsafe impl ExternType for D { type Id = type_id!("tests::D"); type Kind = Trivial; diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 2c3739776..db5143555 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -478,12 +478,25 @@ void c_take_opaque_ptr(std::unique_ptr e) { } } +void c_take_opaque_ns_ptr(std::unique_ptr<::F::F> f) { + if (f->f == 40) { + cxx_test_suite_set_correct(); + } +} + void c_take_opaque_ref(const E& e) { if (e.e == 40 && e.e_str == "hello") { cxx_test_suite_set_correct(); } } +void c_take_opaque_ns_ref(const ::F::F& f) { + if (f.f == 40 && f.f_str == "hello") { + cxx_test_suite_set_correct(); + } +} + + std::unique_ptr c_return_trivial_ptr() { auto d = std::unique_ptr(new D()); d->d = 30; @@ -503,6 +516,13 @@ std::unique_ptr c_return_opaque_ptr() { return e; } +std::unique_ptr<::F::F> c_return_ns_opaque_ptr() { + auto f = std::unique_ptr<::F::F>(new ::F::F()); + f->f = 40; + f->f_str = std::string("hello"); + return f; +} + extern "C" const char *cxx_run_test() noexcept { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index 70d0a439a..4bdf69e4a 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -12,6 +12,13 @@ namespace A { } // namespace B } // namespace A +namespace F { + struct F { + uint64_t f; + std::string f_str; + }; +} + namespace tests { struct R; @@ -137,10 +144,13 @@ void c_take_trivial_ptr(std::unique_ptr d); void c_take_trivial_ref(const D& d); void c_take_trivial(D d); void c_take_opaque_ptr(std::unique_ptr e); +void c_take_opaque_ns_ptr(std::unique_ptr<::F::F> f); void c_take_opaque_ref(const E& e); +void c_take_opaque_ns_ref(const ::F::F& f); std::unique_ptr c_return_trivial_ptr(); D c_return_trivial(); std::unique_ptr c_return_opaque_ptr(); +std::unique_ptr<::F::F> c_return_ns_opaque_ptr(); rust::String cOverloadedFunction(int32_t x); rust::String cOverloadedFunction(rust::Str x); diff --git a/tests/test.rs b/tests/test.rs index eece7ff0a..73bb084d7 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -230,4 +230,8 @@ fn test_extern_opaque() { let e = ffi2::c_return_opaque_ptr(); check!(ffi2::c_take_opaque_ref(e.as_ref().unwrap())); check!(ffi2::c_take_opaque_ptr(e)); + + let f = ffi2::c_return_ns_opaque_ptr(); + check!(ffi2::c_take_opaque_ns_ref(f.as_ref().unwrap())); + check!(ffi2::c_take_opaque_ns_ptr(f)); } From 585bb0bc5605ccf28b5a814b5727967b8ee67c83 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Mon, 26 Oct 2020 13:17:17 -0700 Subject: [PATCH 4/8] Tests for namespaced extern trivial types --- tests/ffi/extra.rs | 8 ++++++++ tests/ffi/lib.rs | 10 ++++++++++ tests/ffi/tests.cc | 33 ++++++++++++++++++++++++++++++++- tests/ffi/tests.h | 12 ++++++++++++ tests/test.rs | 7 +++++++ 5 files changed, 69 insertions(+), 1 deletion(-) diff --git a/tests/ffi/extra.rs b/tests/ffi/extra.rs index 1faf37579..092172454 100644 --- a/tests/ffi/extra.rs +++ b/tests/ffi/extra.rs @@ -13,6 +13,7 @@ pub mod ffi2 { impl UniquePtr {} impl UniquePtr {} impl UniquePtr {} + impl UniquePtr {} extern "C" { include!("tests/ffi/tests.h"); @@ -21,16 +22,23 @@ pub mod ffi2 { type E = crate::other::E; #[namespace (namespace = F)] type F = crate::other::f::F; + #[namespace (namespace = G)] + type G = crate::other::G; fn c_take_trivial_ptr(d: UniquePtr); fn c_take_trivial_ref(d: &D); fn c_take_trivial(d: D); + fn c_take_trivial_ns_ptr(g: UniquePtr); + fn c_take_trivial_ns_ref(g: &G); + fn c_take_trivial_ns(g: G); fn c_take_opaque_ptr(e: UniquePtr); fn c_take_opaque_ref(e: &E); fn c_take_opaque_ns_ptr(e: UniquePtr); fn c_take_opaque_ns_ref(e: &F); fn c_return_trivial_ptr() -> UniquePtr; fn c_return_trivial() -> D; + fn c_return_trivial_ns_ptr() -> UniquePtr; + fn c_return_trivial_ns() -> G; fn c_return_opaque_ptr() -> UniquePtr; fn c_return_ns_opaque_ptr() -> UniquePtr; } diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs index f25fd2a03..1cd92f936 100644 --- a/tests/ffi/lib.rs +++ b/tests/ffi/lib.rs @@ -41,6 +41,16 @@ mod other { } } + #[repr(C)] + pub struct G { + pub g: u64, + } + + unsafe impl ExternType for G { + type Id = type_id!("G::G"); + type Kind = Trivial; + } + unsafe impl ExternType for D { type Id = type_id!("tests::D"); type Kind = Trivial; diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index db5143555..017cb82e9 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -466,12 +466,32 @@ void c_take_trivial_ref(const D& d) { cxx_test_suite_set_correct(); } } + void c_take_trivial(D d) { if (d.d == 30) { cxx_test_suite_set_correct(); } } + +void c_take_trivial_ns_ptr(std::unique_ptr<::G::G> g) { + if (g->g == 30) { + cxx_test_suite_set_correct(); + } +} + +void c_take_trivial_ns_ref(const ::G::G& g) { + if (g.g == 30) { + cxx_test_suite_set_correct(); + } +} + +void c_take_trivial_ns(::G::G g) { + if (g.g == 30) { + cxx_test_suite_set_correct(); + } +} + void c_take_opaque_ptr(std::unique_ptr e) { if (e->e == 40) { cxx_test_suite_set_correct(); @@ -496,7 +516,6 @@ void c_take_opaque_ns_ref(const ::F::F& f) { } } - std::unique_ptr c_return_trivial_ptr() { auto d = std::unique_ptr(new D()); d->d = 30; @@ -509,6 +528,18 @@ D c_return_trivial() { return d; } +std::unique_ptr<::G::G> c_return_trivial_ns_ptr() { + auto g = std::unique_ptr<::G::G>(new ::G::G()); + g->g = 30; + return g; +} + +::G::G c_return_trivial_ns() { + ::G::G g; + g.g = 30; + return g; +} + std::unique_ptr c_return_opaque_ptr() { auto e = std::unique_ptr(new E()); e->e = 40; diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index 4bdf69e4a..7f6267260 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -19,6 +19,12 @@ namespace F { }; } +namespace G { + struct G { + uint64_t g; + }; +} + namespace tests { struct R; @@ -143,12 +149,18 @@ const rust::Vec &c_try_return_ref_rust_vec(const C &c); void c_take_trivial_ptr(std::unique_ptr d); void c_take_trivial_ref(const D& d); void c_take_trivial(D d); + +void c_take_trivial_ns_ptr(std::unique_ptr<::G::G> g); +void c_take_trivial_ns_ref(const ::G::G& g); +void c_take_trivial_ns(::G::G g); void c_take_opaque_ptr(std::unique_ptr e); void c_take_opaque_ns_ptr(std::unique_ptr<::F::F> f); void c_take_opaque_ref(const E& e); void c_take_opaque_ns_ref(const ::F::F& f); std::unique_ptr c_return_trivial_ptr(); D c_return_trivial(); +std::unique_ptr<::G::G> c_return_trivial_ns_ptr(); +::G::G c_return_trivial_ns(); std::unique_ptr c_return_opaque_ptr(); std::unique_ptr<::F::F> c_return_ns_opaque_ptr(); diff --git a/tests/test.rs b/tests/test.rs index 73bb084d7..02cb494d6 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -223,6 +223,13 @@ fn test_extern_trivial() { let d = ffi2::c_return_trivial_ptr(); check!(ffi2::c_take_trivial_ptr(d)); cxx::UniquePtr::new(ffi2::D { d: 42 }); + + let g = ffi2::c_return_trivial_ns(); + check!(ffi2::c_take_trivial_ns_ref(&g)); + check!(ffi2::c_take_trivial_ns(g)); + let g = ffi2::c_return_trivial_ns_ptr(); + check!(ffi2::c_take_trivial_ns_ptr(g)); + cxx::UniquePtr::new(ffi2::G { g: 42 }); } #[test] From d47af7a9d3640438e3d1371a739297b789296cfb Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Mon, 26 Oct 2020 13:18:48 -0700 Subject: [PATCH 5/8] Tests for opaque C types in namepsaces --- tests/ffi/extra.rs | 5 +++++ tests/ffi/tests.cc | 10 ++++++++++ tests/ffi/tests.h | 9 +++++++++ tests/test.rs | 3 +++ 4 files changed, 27 insertions(+) diff --git a/tests/ffi/extra.rs b/tests/ffi/extra.rs index 092172454..aa83cc21f 100644 --- a/tests/ffi/extra.rs +++ b/tests/ffi/extra.rs @@ -25,6 +25,9 @@ pub mod ffi2 { #[namespace (namespace = G)] type G = crate::other::G; + #[namespace(namespace = H)] + type H; + fn c_take_trivial_ptr(d: UniquePtr); fn c_take_trivial_ref(d: &D); fn c_take_trivial(d: D); @@ -41,5 +44,7 @@ pub mod ffi2 { fn c_return_trivial_ns() -> G; fn c_return_opaque_ptr() -> UniquePtr; fn c_return_ns_opaque_ptr() -> UniquePtr; + fn c_return_ns_unique_ptr() -> UniquePtr; + fn c_take_ref_ns_c(h: &H); } } diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 017cb82e9..585a99b90 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -55,6 +55,10 @@ std::unique_ptr c_return_unique_ptr() { return std::unique_ptr(new C{2020}); } +std::unique_ptr<::H::H> c_return_ns_unique_ptr() { + return std::unique_ptr<::H::H>(new ::H::H{"hello"}); +} + const size_t &c_return_ref(const Shared &shared) { return shared.z; } const size_t &c_return_ns_ref(const ::A::AShared &shared) { return shared.z; } @@ -220,6 +224,12 @@ void c_take_ref_c(const C &c) { } } +void c_take_ref_ns_c(const ::H::H &h) { + if (h.h == "hello") { + cxx_test_suite_set_correct(); + } +} + void c_take_str(rust::Str s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index 7f6267260..dfedb3c02 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -25,6 +25,13 @@ namespace G { }; } +namespace H { + class H { + public: + std::string h; + }; +} + namespace tests { struct R; @@ -70,6 +77,7 @@ ::A::AShared c_return_ns_shared(); ::A::B::ABShared c_return_nested_ns_shared(); rust::Box c_return_box(); std::unique_ptr c_return_unique_ptr(); +std::unique_ptr<::H::H> c_return_ns_unique_ptr(); const size_t &c_return_ref(const Shared &shared); const size_t &c_return_ns_ref(const ::A::AShared &shared); const size_t &c_return_nested_ns_ref(const ::A::B::ABShared &shared); @@ -103,6 +111,7 @@ void c_take_box(rust::Box r); void c_take_unique_ptr(std::unique_ptr c); void c_take_ref_r(const R &r); void c_take_ref_c(const C &c); +void c_take_ref_ns_c(const ::H::H &h); void c_take_str(rust::Str s); void c_take_sliceu8(rust::Slice s); void c_take_rust_string(rust::String s); diff --git a/tests/test.rs b/tests/test.rs index 02cb494d6..39a700ed9 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -30,6 +30,7 @@ fn test_c_return() { assert_eq!(2020, ffi::c_return_shared().z); assert_eq!(2020, *ffi::c_return_box()); ffi::c_return_unique_ptr(); + ffi2::c_return_ns_unique_ptr(); assert_eq!(2020, *ffi::c_return_ref(&shared)); assert_eq!(2020, *ffi::c_return_ns_ref(&ns_shared)); assert_eq!(2020, *ffi::c_return_nested_ns_ref(&nested_ns_shared)); @@ -97,6 +98,7 @@ fn test_c_try_return() { #[test] fn test_c_take() { let unique_ptr = ffi::c_return_unique_ptr(); + let unique_ptr_ns = ffi2::c_return_ns_unique_ptr(); check!(ffi::c_take_primitive(2020)); check!(ffi::c_take_shared(ffi::Shared { z: 2020 })); @@ -104,6 +106,7 @@ fn test_c_take() { check!(ffi::c_take_nested_ns_shared(ffi::ABShared { z: 2020 })); check!(ffi::c_take_box(Box::new(2020))); check!(ffi::c_take_ref_c(&unique_ptr)); + check!(ffi2::c_take_ref_ns_c(&unique_ptr_ns)); check!(cxx_test_suite::module::ffi::c_take_unique_ptr(unique_ptr)); check!(ffi::c_take_str("2020")); check!(ffi::c_take_sliceu8(b"2020")); From ddc146ef9f4d67ddf75bf7174fdc1e2a95a2ced5 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Sun, 25 Oct 2020 21:40:17 -0700 Subject: [PATCH 6/8] Adding tests for functions in other namespaces. --- tests/ffi/extra.rs | 5 +++++ tests/ffi/lib.rs | 3 +++ tests/ffi/tests.cc | 21 +++++++++++++++++++++ tests/ffi/tests.h | 6 ++++++ tests/test.rs | 3 +++ 5 files changed, 38 insertions(+) diff --git a/tests/ffi/extra.rs b/tests/ffi/extra.rs index aa83cc21f..633cf9372 100644 --- a/tests/ffi/extra.rs +++ b/tests/ffi/extra.rs @@ -46,5 +46,10 @@ pub mod ffi2 { fn c_return_ns_opaque_ptr() -> UniquePtr; fn c_return_ns_unique_ptr() -> UniquePtr; fn c_take_ref_ns_c(h: &H); + + #[namespace (namespace = other)] + fn ns_c_take_trivial(d: D); + #[namespace (namespace = other)] + fn ns_c_return_trivial() -> D; } } diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs index 1cd92f936..a491ae20a 100644 --- a/tests/ffi/lib.rs +++ b/tests/ffi/lib.rs @@ -199,6 +199,9 @@ pub mod ffi { fn cOverloadedFunction(x: i32) -> String; #[rust_name = "str_overloaded_function"] fn cOverloadedFunction(x: &str) -> String; + + #[namespace (namespace = other)] + fn ns_c_take_ns_shared(shared: AShared); } extern "C" { diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 585a99b90..1f0f8ff15 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -627,3 +627,24 @@ extern "C" const char *cxx_run_test() noexcept { } } // namespace tests + +namespace other { + + void ns_c_take_trivial(::tests::D d) { + if (d.d == 30) { + cxx_test_suite_set_correct(); + } + } + + ::tests::D ns_c_return_trivial() { + ::tests::D d; + d.d = 30; + return d; + } + + void ns_c_take_ns_shared(::A::AShared shared) { + if (shared.z == 2020) { + cxx_test_suite_set_correct(); + } + } +} \ No newline at end of file diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index dfedb3c02..40bc802c5 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -177,3 +177,9 @@ rust::String cOverloadedFunction(int32_t x); rust::String cOverloadedFunction(rust::Str x); } // namespace tests + +namespace other { + void ns_c_take_trivial(::tests::D d); + ::tests::D ns_c_return_trivial(); + void ns_c_take_ns_shared(::A::AShared shared); +} // namespace other \ No newline at end of file diff --git a/tests/test.rs b/tests/test.rs index 39a700ed9..21f8a8c19 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -103,6 +103,7 @@ fn test_c_take() { check!(ffi::c_take_primitive(2020)); check!(ffi::c_take_shared(ffi::Shared { z: 2020 })); check!(ffi::c_take_ns_shared(ffi::AShared { z: 2020 })); + check!(ffi::ns_c_take_ns_shared(ffi::AShared { z: 2020 })); check!(ffi::c_take_nested_ns_shared(ffi::ABShared { z: 2020 })); check!(ffi::c_take_box(Box::new(2020))); check!(ffi::c_take_ref_c(&unique_ptr)); @@ -226,6 +227,8 @@ fn test_extern_trivial() { let d = ffi2::c_return_trivial_ptr(); check!(ffi2::c_take_trivial_ptr(d)); cxx::UniquePtr::new(ffi2::D { d: 42 }); + let d = ffi2::ns_c_return_trivial(); + check!(ffi2::ns_c_take_trivial(d)); let g = ffi2::c_return_trivial_ns(); check!(ffi2::c_take_trivial_ns_ref(&g)); From 0fac32193904fdd75dcff71e5e4bd846b6e560b7 Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Sun, 25 Oct 2020 21:52:55 -0700 Subject: [PATCH 7/8] Adding tests for method calls in foreign namespaces --- tests/BUCK | 7 +++++++ tests/BUILD | 8 ++++++++ tests/ffi/build.rs | 2 +- tests/ffi/class_in_ns.rs | 21 +++++++++++++++++++++ tests/ffi/lib.rs | 1 + tests/ffi/tests.cc | 12 +++++++++++- tests/ffi/tests.h | 14 +++++++++++++- tests/test.rs | 9 +++++++++ 8 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 tests/ffi/class_in_ns.rs diff --git a/tests/BUCK b/tests/BUCK index 5bbe50099..f51be097a 100644 --- a/tests/BUCK +++ b/tests/BUCK @@ -15,6 +15,7 @@ rust_library( "ffi/extra.rs", "ffi/lib.rs", "ffi/module.rs", + "ffi/class_in_ns.rs", ], crate = "cxx_test_suite", deps = [ @@ -30,6 +31,7 @@ cxx_library( ":bridge/source", ":extra/source", ":module/source", + ":class_in_ns/source", ], headers = { "ffi/lib.rs.h": ":bridge/header", @@ -52,3 +54,8 @@ rust_cxx_bridge( name = "module", src = "ffi/module.rs", ) + +rust_cxx_bridge( + name = "class_in_ns", + src = "ffi/class_in_ns.rs", +) diff --git a/tests/BUILD b/tests/BUILD index 57ffab996..a400f4768 100644 --- a/tests/BUILD +++ b/tests/BUILD @@ -18,6 +18,7 @@ rust_library( "ffi/extra.rs", "ffi/lib.rs", "ffi/module.rs", + "ffi/class_in_ns.rs", ], deps = [ ":impl", @@ -32,6 +33,7 @@ cc_library( ":bridge/source", ":extra/source", ":module/source", + ":class_in_ns/source", ], hdrs = ["ffi/tests.h"], deps = [ @@ -57,3 +59,9 @@ rust_cxx_bridge( src = "ffi/module.rs", deps = [":impl"], ) + +rust_cxx_bridge( + name = "class_in_ns", + src = "ffi/class_in_ns.rs", + deps = [":impl"], +) \ No newline at end of file diff --git a/tests/ffi/build.rs b/tests/ffi/build.rs index 4b2cbdfe9..9bdb711e5 100644 --- a/tests/ffi/build.rs +++ b/tests/ffi/build.rs @@ -6,7 +6,7 @@ fn main() { } CFG.include_prefix = "tests/ffi"; - let sources = vec!["lib.rs", "extra.rs", "module.rs"]; + let sources = vec!["lib.rs", "extra.rs", "module.rs", "class_in_ns.rs"]; cxx_build::bridges(sources) .file("tests.cc") .flag_if_supported(cxxbridge_flags::STD) diff --git a/tests/ffi/class_in_ns.rs b/tests/ffi/class_in_ns.rs new file mode 100644 index 000000000..8b5056132 --- /dev/null +++ b/tests/ffi/class_in_ns.rs @@ -0,0 +1,21 @@ +// To test receivers on a type in a namespace outide +// the default. cxx::bridge blocks can only have a single +// receiver type, and there can only be one such block per, +// which is why this is outside. + +#[rustfmt::skip] +#[cxx::bridge(namespace = tests)] +pub mod ffi3 { + + extern "C" { + include!("tests/ffi/tests.h"); + + #[namespace (namespace = I)] + type I; + + fn get(self: &I) -> u32; + + #[namespace (namespace = I)] + fn ns_c_return_unique_ptr_ns() -> UniquePtr; + } +} diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs index a491ae20a..be145f37f 100644 --- a/tests/ffi/lib.rs +++ b/tests/ffi/lib.rs @@ -4,6 +4,7 @@ clippy::trivially_copy_pass_by_ref )] +pub mod class_in_ns; pub mod extra; pub mod module; diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc index 1f0f8ff15..05bf5fbb6 100644 --- a/tests/ffi/tests.cc +++ b/tests/ffi/tests.cc @@ -647,4 +647,14 @@ namespace other { cxx_test_suite_set_correct(); } } -} \ No newline at end of file +} // namespace other + +namespace I { + uint32_t I::get() const { + return a; + } + + std::unique_ptr ns_c_return_unique_ptr_ns() { + return std::unique_ptr(new I()); + } +} // namespace I diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h index 40bc802c5..3835660c3 100644 --- a/tests/ffi/tests.h +++ b/tests/ffi/tests.h @@ -182,4 +182,16 @@ namespace other { void ns_c_take_trivial(::tests::D d); ::tests::D ns_c_return_trivial(); void ns_c_take_ns_shared(::A::AShared shared); -} // namespace other \ No newline at end of file +} // namespace other + +namespace I { + class I { + private: + uint32_t a; + public: + I() : a(1000) {} + uint32_t get() const; + }; + + std::unique_ptr ns_c_return_unique_ptr_ns(); +} // namespace I diff --git a/tests/test.rs b/tests/test.rs index 21f8a8c19..20b23acef 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -1,3 +1,4 @@ +use cxx_test_suite::class_in_ns::ffi3; use cxx_test_suite::extra::ffi2; use cxx_test_suite::ffi; use std::cell::Cell; @@ -193,6 +194,14 @@ fn test_c_method_calls() { assert!(unique_ptr.get_fail().is_err()); } +#[test] +fn test_c_ns_method_calls() { + let unique_ptr = ffi3::ns_c_return_unique_ptr_ns(); + + let old_value = unique_ptr.get(); + assert_eq!(1000, old_value); +} + #[test] fn test_enum_representations() { assert_eq!(0, ffi::Enum::AVal.repr); From c871343ac270f073fd4790269da267e8cb91dbde Mon Sep 17 00:00:00 2001 From: Adrian Taylor Date: Wed, 21 Oct 2020 18:20:55 -0700 Subject: [PATCH 8/8] Allow namespace override. This change allows a #[namespace (namespace = A::B)] attribute for each item in a cxx::bridge. We now have a fair number of different types of name floating around: * C++ identifiers * C++ fully-qualified names * Rust identifiers * Rust fully-qualified names (future, when we support sub-modules) * Items with both a Rust and C++ name (a 'Pair') * Types with only a known Rust name, which can be resolved to a C++ name. This change attempts to put some sensible names for all these things in syntax/mod.rs, and so that would be a good place to start review. At the moment, the Namespace (included in each CppName) is ruthlessly cloned all over the place. As a given namespace is likely to be applicable to many types and functions, it may save significant memory in future to use Rc<> here. But let's not optimise too early. --- gen/src/mod.rs | 9 +- gen/src/namespace_organizer.rs | 40 +++ gen/src/out.rs | 5 +- gen/src/write.rs | 355 ++++++++++++++----------- macro/src/expand.rs | 201 +++++++------- syntax/atom.rs | 2 +- syntax/attrs.rs | 32 ++- syntax/check.rs | 77 +++--- syntax/ident.rs | 18 +- syntax/impls.rs | 88 +++++- syntax/mangle.rs | 25 +- syntax/mod.rs | 57 +++- syntax/parse.rs | 163 +++++++----- syntax/qualified.rs | 1 + syntax/symbol.rs | 57 +++- syntax/tokens.rs | 24 +- syntax/types.rs | 49 +++- tests/ui/by_value_not_supported.stderr | 2 +- 18 files changed, 757 insertions(+), 448 deletions(-) create mode 100644 gen/src/namespace_organizer.rs diff --git a/gen/src/mod.rs b/gen/src/mod.rs index 2fee0e91d..92e8ec84b 100644 --- a/gen/src/mod.rs +++ b/gen/src/mod.rs @@ -5,6 +5,7 @@ pub(super) mod error; mod file; pub(super) mod fs; pub(super) mod include; +mod namespace_organizer; pub(super) mod out; mod write; @@ -109,22 +110,22 @@ pub(super) fn generate(syntax: File, opt: &Opt) -> Result { .ok_or(Error::NoBridgeMod)?; let ref namespace = bridge.namespace; let trusted = bridge.unsafety.is_some(); - let ref apis = syntax::parse_items(errors, bridge.content, trusted); + let ref apis = syntax::parse_items(errors, bridge.content, trusted, namespace); let ref types = Types::collect(errors, apis); errors.propagate()?; - check::typecheck(errors, namespace, apis, types); + check::typecheck(errors, apis, types); errors.propagate()?; // Some callers may wish to generate both header and C++ // from the same token stream to avoid parsing twice. But others // only need to generate one or the other. Ok(GeneratedCode { header: if opt.gen_header { - write::gen(namespace, apis, types, opt, true).content() + write::gen(apis, types, opt, true).content() } else { Vec::new() }, implementation: if opt.gen_implementation { - write::gen(namespace, apis, types, opt, false).content() + write::gen(apis, types, opt, false).content() } else { Vec::new() }, diff --git a/gen/src/namespace_organizer.rs b/gen/src/namespace_organizer.rs new file mode 100644 index 000000000..c54e784ef --- /dev/null +++ b/gen/src/namespace_organizer.rs @@ -0,0 +1,40 @@ +use crate::syntax::Api; +use proc_macro2::Ident; +use std::collections::BTreeMap; + +pub(crate) struct NamespaceEntries<'a> { + pub(crate) entries: Vec<&'a Api>, + pub(crate) children: BTreeMap<&'a Ident, NamespaceEntries<'a>>, +} + +pub(crate) fn sort_by_namespace(apis: &[Api]) -> NamespaceEntries { + let api_refs = apis.iter().collect::>(); + sort_by_inner_namespace(api_refs, 0) +} + +fn sort_by_inner_namespace(apis: Vec<&Api>, depth: usize) -> NamespaceEntries { + let mut root = NamespaceEntries { + entries: Vec::new(), + children: BTreeMap::new(), + }; + + let mut kids_by_child_ns = BTreeMap::new(); + for api in apis { + if let Some(ns) = api.get_namespace() { + let first_ns_elem = ns.iter().nth(depth); + if let Some(first_ns_elem) = first_ns_elem { + let list = kids_by_child_ns.entry(first_ns_elem).or_insert(Vec::new()); + list.push(api); + continue; + } + } + root.entries.push(api); + } + + for (k, v) in kids_by_child_ns.into_iter() { + root.children + .insert(k, sort_by_inner_namespace(v, depth + 1)); + } + + root +} diff --git a/gen/src/out.rs b/gen/src/out.rs index d42ea7475..8a6bd8610 100644 --- a/gen/src/out.rs +++ b/gen/src/out.rs @@ -1,10 +1,8 @@ use crate::gen::include::Includes; -use crate::syntax::namespace::Namespace; use std::cell::RefCell; use std::fmt::{self, Arguments, Write}; pub(crate) struct OutFile { - pub namespace: Namespace, pub header: bool, pub include: Includes, pub front: Content, @@ -18,9 +16,8 @@ pub struct Content { } impl OutFile { - pub fn new(namespace: Namespace, header: bool) -> Self { + pub fn new(header: bool) -> Self { OutFile { - namespace, header, include: Includes::new(), front: Content::new(), diff --git a/gen/src/write.rs b/gen/src/write.rs index 318460461..2ff5b47c0 100644 --- a/gen/src/write.rs +++ b/gen/src/write.rs @@ -1,20 +1,17 @@ +use crate::gen::namespace_organizer::{sort_by_namespace, NamespaceEntries}; use crate::gen::out::OutFile; use crate::gen::{include, Opt}; use crate::syntax::atom::Atom::{self, *}; -use crate::syntax::namespace::Namespace; use crate::syntax::symbol::Symbol; -use crate::syntax::{mangle, Api, Enum, ExternFn, ExternType, Signature, Struct, Type, Types, Var}; +use crate::syntax::{ + mangle, Api, CppName, Enum, ExternFn, ExternType, ResolvableName, Signature, Struct, Type, + Types, Var, +}; use proc_macro2::Ident; use std::collections::HashMap; -pub(super) fn gen( - namespace: &Namespace, - apis: &[Api], - types: &Types, - opt: &Opt, - header: bool, -) -> OutFile { - let mut out_file = OutFile::new(namespace.clone(), header); +pub(super) fn gen(apis: &[Api], types: &Types, opt: &Opt, header: bool) -> OutFile { + let mut out_file = OutFile::new(header); let out = &mut out_file; if header { @@ -32,16 +29,36 @@ pub(super) fn gen( write_include_cxxbridge(out, apis, types); out.next_section(); - for name in namespace { - writeln!(out, "namespace {} {{", name); + + let apis_by_namespace = sort_by_namespace(apis); + + gen_namespace_contents(&apis_by_namespace, types, opt, header, out); + + if !header { + out.next_section(); + write_generic_instantiations(out, types); } + write!(out.front, "{}", out.include); + + out_file +} + +fn gen_namespace_contents( + ns_entries: &NamespaceEntries, + types: &Types, + opt: &Opt, + header: bool, + out: &mut OutFile, +) { + let apis = &ns_entries.entries; + out.next_section(); for api in apis { match api { - Api::Struct(strct) => write_struct_decl(out, &strct.ident), - Api::CxxType(ety) => write_struct_using(out, &ety.ident), - Api::RustType(ety) => write_struct_decl(out, &ety.ident), + Api::Struct(strct) => write_struct_decl(out, &strct.ident.cxx.ident), + Api::CxxType(ety) => write_struct_using(out, &ety.ident.cxx), + Api::RustType(ety) => write_struct_decl(out, &ety.ident.cxx.ident), _ => {} } } @@ -51,7 +68,7 @@ pub(super) fn gen( if let Api::RustFunction(efn) = api { if let Some(receiver) = &efn.sig.receiver { methods_for_type - .entry(&receiver.ty) + .entry(&receiver.ty.rust) .or_insert_with(Vec::new) .push(efn); } @@ -62,22 +79,22 @@ pub(super) fn gen( match api { Api::Struct(strct) => { out.next_section(); - if !types.cxx.contains(&strct.ident) { - write_struct(out, strct); + if !types.cxx.contains(&strct.ident.rust) { + write_struct(out, strct, types); } } Api::Enum(enm) => { out.next_section(); - if types.cxx.contains(&enm.ident) { + if types.cxx.contains(&enm.ident.rust) { check_enum(out, enm); } else { write_enum(out, enm); } } Api::RustType(ety) => { - if let Some(methods) = methods_for_type.get(&ety.ident) { + if let Some(methods) = methods_for_type.get(&ety.ident.rust) { out.next_section(); - write_struct_with_methods(out, ety, methods); + write_struct_with_methods(out, ety, methods, types); } } _ => {} @@ -87,8 +104,8 @@ pub(super) fn gen( out.next_section(); for api in apis { if let Api::TypeAlias(ety) = api { - if types.required_trivial.contains_key(&ety.ident) { - check_trivial_extern_type(out, &ety.ident) + if types.required_trivial.contains_key(&ety.ident.rust) { + check_trivial_extern_type(out, &ety.ident.cxx) } } } @@ -116,24 +133,18 @@ pub(super) fn gen( } out.next_section(); - for name in namespace.iter().rev() { - writeln!(out, "}} // namespace {}", name); - } - if !header { - out.next_section(); - write_generic_instantiations(out, types); + for (child_ns, child_ns_entries) in &ns_entries.children { + writeln!(out, "namespace {} {{", child_ns); + gen_namespace_contents(&child_ns_entries, types, opt, header, out); + writeln!(out, "}} // namespace {}", child_ns); } - - write!(out.front, "{}", out.include); - - out_file } fn write_includes(out: &mut OutFile, types: &Types) { for ty in types { match ty { - Type::Ident(ident) => match Atom::from(ident) { + Type::Ident(ident) => match Atom::from(&ident.rust) { Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(I8) | Some(I16) | Some(I32) | Some(I64) => out.include.cstdint = true, Some(Usize) => out.include.cstddef = true, @@ -332,17 +343,17 @@ fn write_include_cxxbridge(out: &mut OutFile, apis: &[Api], types: &Types) { out.end_block("namespace rust"); } -fn write_struct(out: &mut OutFile, strct: &Struct) { - let guard = format!("CXXBRIDGE05_STRUCT_{}{}", out.namespace, strct.ident); +fn write_struct(out: &mut OutFile, strct: &Struct, types: &Types) { + let guard = format!("CXXBRIDGE05_STRUCT_{}", strct.ident.cxx.to_symbol()); writeln!(out, "#ifndef {}", guard); writeln!(out, "#define {}", guard); for line in strct.doc.to_string().lines() { writeln!(out, "//{}", line); } - writeln!(out, "struct {} final {{", strct.ident); + writeln!(out, "struct {} final {{", strct.ident.cxx.ident); for field in &strct.fields { write!(out, " "); - write_type_space(out, &field.ty); + write_type_space(out, &field.ty, types); writeln!(out, "{};", field.ident); } writeln!(out, "}};"); @@ -353,25 +364,39 @@ fn write_struct_decl(out: &mut OutFile, ident: &Ident) { writeln!(out, "struct {};", ident); } -fn write_struct_using(out: &mut OutFile, ident: &Ident) { - writeln!(out, "using {} = {};", ident, ident); +fn write_struct_using(out: &mut OutFile, ident: &CppName) { + writeln!( + out, + "using {} = {};", + ident.ident, + ident.to_fully_qualified() + ); } -fn write_struct_with_methods(out: &mut OutFile, ety: &ExternType, methods: &[&ExternFn]) { - let guard = format!("CXXBRIDGE05_STRUCT_{}{}", out.namespace, ety.ident); +fn write_struct_with_methods( + out: &mut OutFile, + ety: &ExternType, + methods: &[&ExternFn], + types: &Types, +) { + let guard = format!("CXXBRIDGE05_STRUCT_{}", ety.ident.cxx.to_symbol()); writeln!(out, "#ifndef {}", guard); writeln!(out, "#define {}", guard); for line in ety.doc.to_string().lines() { writeln!(out, "//{}", line); } - writeln!(out, "struct {} final {{", ety.ident); - writeln!(out, " {}() = delete;", ety.ident); - writeln!(out, " {}(const {} &) = delete;", ety.ident, ety.ident); + writeln!(out, "struct {} final {{", ety.ident.cxx.ident); + writeln!(out, " {}() = delete;", ety.ident.cxx.ident); + writeln!( + out, + " {}(const {} &) = delete;", + ety.ident.cxx.ident, ety.ident.cxx.ident + ); for method in methods { write!(out, " "); let sig = &method.sig; - let local_name = method.ident.cxx.to_string(); - write_rust_function_shim_decl(out, &local_name, sig, false); + let local_name = method.ident.cxx.ident.to_string(); + write_rust_function_shim_decl(out, &local_name, sig, false, types); writeln!(out, ";"); } writeln!(out, "}};"); @@ -379,13 +404,13 @@ fn write_struct_with_methods(out: &mut OutFile, ety: &ExternType, methods: &[&Ex } fn write_enum(out: &mut OutFile, enm: &Enum) { - let guard = format!("CXXBRIDGE05_ENUM_{}{}", out.namespace, enm.ident); + let guard = format!("CXXBRIDGE05_ENUM_{}", enm.ident.cxx.to_symbol()); writeln!(out, "#ifndef {}", guard); writeln!(out, "#define {}", guard); for line in enm.doc.to_string().lines() { writeln!(out, "//{}", line); } - write!(out, "enum class {} : ", enm.ident); + write!(out, "enum class {} : ", enm.ident.cxx.ident); write_atom(out, enm.repr); writeln!(out, " {{"); for variant in &enm.variants { @@ -396,7 +421,11 @@ fn write_enum(out: &mut OutFile, enm: &Enum) { } fn check_enum(out: &mut OutFile, enm: &Enum) { - write!(out, "static_assert(sizeof({}) == sizeof(", enm.ident); + write!( + out, + "static_assert(sizeof({}) == sizeof(", + enm.ident.cxx.ident + ); write_atom(out, enm.repr); writeln!(out, "), \"incorrect size\");"); for variant in &enm.variants { @@ -405,12 +434,12 @@ fn check_enum(out: &mut OutFile, enm: &Enum) { writeln!( out, ">({}::{}) == {}, \"disagrees with the value in #[cxx::bridge]\");", - enm.ident, variant.ident, variant.discriminant, + enm.ident.cxx.ident, variant.ident, variant.discriminant, ); } } -fn check_trivial_extern_type(out: &mut OutFile, id: &Ident) { +fn check_trivial_extern_type(out: &mut OutFile, id: &CppName) { // NOTE: The following two static assertions are just nice-to-have and not // necessary for soundness. That's because triviality is always declared by // the user in the form of an unsafe impl of cxx::ExternType: @@ -429,6 +458,7 @@ fn check_trivial_extern_type(out: &mut OutFile, id: &Ident) { // not being recognized as such by the C++ type system due to a move // constructor or destructor. + let id = &id.to_fully_qualified(); out.include.type_traits = true; writeln!(out, "static_assert("); writeln!( @@ -450,7 +480,7 @@ fn check_trivial_extern_type(out: &mut OutFile, id: &Ident) { ); } -fn write_exception_glue(out: &mut OutFile, apis: &[Api]) { +fn write_exception_glue(out: &mut OutFile, apis: &[&Api]) { let mut has_cxx_throws = false; for api in apis { if let Api::CxxFunction(efn) = api { @@ -486,13 +516,17 @@ fn write_cxx_function_shim( } else { write_extern_return_type_space(out, &efn.ret, types); } - let mangled = mangle::extern_fn(&out.namespace, efn); + let mangled = mangle::extern_fn(efn, types); write!(out, "{}(", mangled); if let Some(receiver) = &efn.receiver { if receiver.mutability.is_none() { write!(out, "const "); } - write!(out, "{} &self", receiver.ty); + write!( + out, + "{} &self", + types.resolve(&receiver.ty).to_fully_qualified() + ); } for (i, arg) in efn.args.iter().enumerate() { if i > 0 || efn.receiver.is_some() { @@ -510,21 +544,26 @@ fn write_cxx_function_shim( if !efn.args.is_empty() || efn.receiver.is_some() { write!(out, ", "); } - write_indirect_return_type_space(out, efn.ret.as_ref().unwrap()); + write_indirect_return_type_space(out, efn.ret.as_ref().unwrap(), types); write!(out, "*return$"); } writeln!(out, ") noexcept {{"); write!(out, " "); - write_return_type(out, &efn.ret); + write_return_type(out, &efn.ret, types); match &efn.receiver { None => write!(out, "(*{}$)(", efn.ident.rust), - Some(receiver) => write!(out, "({}::*{}$)(", receiver.ty, efn.ident.rust), + Some(receiver) => write!( + out, + "({}::*{}$)(", + types.resolve(&receiver.ty).to_fully_qualified(), + efn.ident.rust + ), } for (i, arg) in efn.args.iter().enumerate() { if i > 0 { write!(out, ", "); } - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); } write!(out, ")"); if let Some(receiver) = &efn.receiver { @@ -534,8 +573,13 @@ fn write_cxx_function_shim( } write!(out, " = "); match &efn.receiver { - None => write!(out, "{}", efn.ident.cxx), - Some(receiver) => write!(out, "&{}::{}", receiver.ty, efn.ident.cxx), + None => write!(out, "{}", efn.ident.cxx.to_fully_qualified()), + Some(receiver) => write!( + out, + "&{}::{}", + types.resolve(&receiver.ty).to_fully_qualified(), + efn.ident.cxx.ident + ), } writeln!(out, ";"); write!(out, " "); @@ -548,7 +592,7 @@ fn write_cxx_function_shim( if indirect_return { out.include.new = true; write!(out, "new (return$) "); - write_indirect_return_type(out, efn.ret.as_ref().unwrap()); + write_indirect_return_type(out, efn.ret.as_ref().unwrap(), types); write!(out, "("); } else if efn.ret.is_some() { write!(out, "return "); @@ -570,10 +614,10 @@ fn write_cxx_function_shim( write!(out, ", "); } if let Type::RustBox(_) = &arg.ty { - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); write!(out, "::from_raw({})", arg.ident); } else if let Type::UniquePtr(_) = &arg.ty { - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); write!(out, "({})", arg.ident); } else if arg.ty == RustString { write!( @@ -582,7 +626,7 @@ fn write_cxx_function_shim( arg.ident, ); } else if let Type::RustVec(_) = arg.ty { - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); write!(out, "(::rust::unsafe_bitcopy, *{})", arg.ident); } else if types.needs_indirect_abi(&arg.ty) { out.include.utility = true; @@ -632,17 +676,17 @@ fn write_function_pointer_trampoline( types: &Types, ) { out.next_section(); - let r_trampoline = mangle::r_trampoline(&out.namespace, efn, var); + let r_trampoline = mangle::r_trampoline(efn, var, types); let indirect_call = true; write_rust_function_decl_impl(out, &r_trampoline, f, types, indirect_call); out.next_section(); - let c_trampoline = mangle::c_trampoline(&out.namespace, efn, var).to_string(); + let c_trampoline = mangle::c_trampoline(efn, var, types).to_string(); write_rust_function_shim_impl(out, &c_trampoline, f, types, &r_trampoline, indirect_call); } fn write_rust_function_decl(out: &mut OutFile, efn: &ExternFn, types: &Types, _: &Option) { - let link_name = mangle::extern_fn(&out.namespace, efn); + let link_name = mangle::extern_fn(efn, types); let indirect_call = false; write_rust_function_decl_impl(out, &link_name, efn, types, indirect_call); } @@ -665,7 +709,11 @@ fn write_rust_function_decl_impl( if receiver.mutability.is_none() { write!(out, "const "); } - write!(out, "{} &self", receiver.ty); + write!( + out, + "{} &self", + types.resolve(&receiver.ty).to_fully_qualified() + ); needs_comma = true; } for arg in &sig.args { @@ -679,7 +727,7 @@ fn write_rust_function_decl_impl( if needs_comma { write!(out, ", "); } - write_return_type(out, &sig.ret); + write_return_type(out, &sig.ret, types); write!(out, "*return$"); needs_comma = true; } @@ -697,10 +745,14 @@ fn write_rust_function_shim(out: &mut OutFile, efn: &ExternFn, types: &Types) { writeln!(out, "//{}", line); } let local_name = match &efn.sig.receiver { - None => efn.ident.cxx.to_string(), - Some(receiver) => format!("{}::{}", receiver.ty, efn.ident.cxx), + None => efn.ident.cxx.ident.to_string(), + Some(receiver) => format!( + "{}::{}", + types.resolve(&receiver.ty).ident, + efn.ident.cxx.ident + ), }; - let invoke = mangle::extern_fn(&out.namespace, efn); + let invoke = mangle::extern_fn(efn, types); let indirect_call = false; write_rust_function_shim_impl(out, &local_name, efn, types, &invoke, indirect_call); } @@ -710,14 +762,15 @@ fn write_rust_function_shim_decl( local_name: &str, sig: &Signature, indirect_call: bool, + types: &Types, ) { - write_return_type(out, &sig.ret); + write_return_type(out, &sig.ret, types); write!(out, "{}(", local_name); for (i, arg) in sig.args.iter().enumerate() { if i > 0 { write!(out, ", "); } - write_type_space(out, &arg.ty); + write_type_space(out, &arg.ty, types); write!(out, "{}", arg.ident); } if indirect_call { @@ -749,7 +802,7 @@ fn write_rust_function_shim_impl( // We've already defined this inside the struct. return; } - write_rust_function_shim_decl(out, local_name, sig, indirect_call); + write_rust_function_shim_decl(out, local_name, sig, indirect_call, types); if out.header { writeln!(out, ";"); return; @@ -759,7 +812,7 @@ fn write_rust_function_shim_impl( if arg.ty != RustString && types.needs_indirect_abi(&arg.ty) { out.include.utility = true; write!(out, " ::rust::ManuallyDrop<"); - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); writeln!(out, "> {}$(::std::move({0}));", arg.ident); } } @@ -767,18 +820,18 @@ fn write_rust_function_shim_impl( let indirect_return = indirect_return(sig, types); if indirect_return { write!(out, "::rust::MaybeUninit<"); - write_type(out, sig.ret.as_ref().unwrap()); + write_type(out, sig.ret.as_ref().unwrap(), types); writeln!(out, "> return$;"); write!(out, " "); } else if let Some(ret) = &sig.ret { write!(out, "return "); match ret { Type::RustBox(_) => { - write_type(out, ret); + write_type(out, ret, types); write!(out, "::from_raw("); } Type::UniquePtr(_) => { - write_type(out, ret); + write_type(out, ret, types); write!(out, "("); } Type::Ref(_) => write!(out, "*"), @@ -844,10 +897,10 @@ fn write_rust_function_shim_impl( writeln!(out, "}}"); } -fn write_return_type(out: &mut OutFile, ty: &Option) { +fn write_return_type(out: &mut OutFile, ty: &Option, types: &Types) { match ty { None => write!(out, "void "), - Some(ty) => write_type_space(out, ty), + Some(ty) => write_type_space(out, ty, types), } } @@ -857,27 +910,27 @@ fn indirect_return(sig: &Signature, types: &Types) -> bool { .map_or(false, |ret| sig.throws || types.needs_indirect_abi(ret)) } -fn write_indirect_return_type(out: &mut OutFile, ty: &Type) { +fn write_indirect_return_type(out: &mut OutFile, ty: &Type, types: &Types) { match ty { Type::RustBox(ty) | Type::UniquePtr(ty) => { - write_type_space(out, &ty.inner); + write_type_space(out, &ty.inner, types); write!(out, "*"); } Type::Ref(ty) => { if ty.mutability.is_none() { write!(out, "const "); } - write_type(out, &ty.inner); + write_type(out, &ty.inner, types); write!(out, " *"); } Type::Str(_) => write!(out, "::rust::Str::Repr"), Type::SliceRefU8(_) => write!(out, "::rust::Slice::Repr"), - _ => write_type(out, ty), + _ => write_type(out, ty, types), } } -fn write_indirect_return_type_space(out: &mut OutFile, ty: &Type) { - write_indirect_return_type(out, ty); +fn write_indirect_return_type_space(out: &mut OutFile, ty: &Type, types: &Types) { + write_indirect_return_type(out, ty, types); match ty { Type::RustBox(_) | Type::UniquePtr(_) | Type::Ref(_) => {} Type::Str(_) | Type::SliceRefU8(_) => write!(out, " "), @@ -888,32 +941,32 @@ fn write_indirect_return_type_space(out: &mut OutFile, ty: &Type) { fn write_extern_return_type_space(out: &mut OutFile, ty: &Option, types: &Types) { match ty { Some(Type::RustBox(ty)) | Some(Type::UniquePtr(ty)) => { - write_type_space(out, &ty.inner); + write_type_space(out, &ty.inner, types); write!(out, "*"); } Some(Type::Ref(ty)) => { if ty.mutability.is_none() { write!(out, "const "); } - write_type(out, &ty.inner); + write_type(out, &ty.inner, types); write!(out, " *"); } Some(Type::Str(_)) => write!(out, "::rust::Str::Repr "), Some(Type::SliceRefU8(_)) => write!(out, "::rust::Slice::Repr "), Some(ty) if types.needs_indirect_abi(ty) => write!(out, "void "), - _ => write_return_type(out, ty), + _ => write_return_type(out, ty, types), } } fn write_extern_arg(out: &mut OutFile, arg: &Var, types: &Types) { match &arg.ty { Type::RustBox(ty) | Type::UniquePtr(ty) | Type::CxxVector(ty) => { - write_type_space(out, &ty.inner); + write_type_space(out, &ty.inner, types); write!(out, "*"); } Type::Str(_) => write!(out, "::rust::Str::Repr "), Type::SliceRefU8(_) => write!(out, "::rust::Slice::Repr "), - _ => write_type_space(out, &arg.ty), + _ => write_type_space(out, &arg.ty, types), } if types.needs_indirect_abi(&arg.ty) { write!(out, "*"); @@ -921,37 +974,37 @@ fn write_extern_arg(out: &mut OutFile, arg: &Var, types: &Types) { write!(out, "{}", arg.ident); } -fn write_type(out: &mut OutFile, ty: &Type) { +fn write_type(out: &mut OutFile, ty: &Type, types: &Types) { match ty { - Type::Ident(ident) => match Atom::from(ident) { + Type::Ident(ident) => match Atom::from(&ident.rust) { Some(atom) => write_atom(out, atom), - None => write!(out, "{}", ident), + None => write!(out, "{}", types.resolve(ident).to_fully_qualified()), }, Type::RustBox(ty) => { write!(out, "::rust::Box<"); - write_type(out, &ty.inner); + write_type(out, &ty.inner, types); write!(out, ">"); } Type::RustVec(ty) => { write!(out, "::rust::Vec<"); - write_type(out, &ty.inner); + write_type(out, &ty.inner, types); write!(out, ">"); } Type::UniquePtr(ptr) => { write!(out, "::std::unique_ptr<"); - write_type(out, &ptr.inner); + write_type(out, &ptr.inner, types); write!(out, ">"); } Type::CxxVector(ty) => { write!(out, "::std::vector<"); - write_type(out, &ty.inner); + write_type(out, &ty.inner, types); write!(out, ">"); } Type::Ref(r) => { if r.mutability.is_none() { write!(out, "const "); } - write_type(out, &r.inner); + write_type(out, &r.inner, types); write!(out, " &"); } Type::Slice(_) => { @@ -967,7 +1020,7 @@ fn write_type(out: &mut OutFile, ty: &Type) { Type::Fn(f) => { write!(out, "::rust::{}<", if f.throws { "TryFn" } else { "Fn" }); match &f.ret { - Some(ret) => write_type(out, ret), + Some(ret) => write_type(out, ret, types), None => write!(out, "void"), } write!(out, "("); @@ -975,7 +1028,7 @@ fn write_type(out: &mut OutFile, ty: &Type) { if i > 0 { write!(out, ", "); } - write_type(out, &arg.ty); + write_type(out, &arg.ty, types); } write!(out, ")>"); } @@ -1003,8 +1056,8 @@ fn write_atom(out: &mut OutFile, atom: Atom) { } } -fn write_type_space(out: &mut OutFile, ty: &Type) { - write_type(out, ty); +fn write_type_space(out: &mut OutFile, ty: &Type, types: &Types) { + write_type(out, ty, types); write_space_after_type(out, ty); } @@ -1025,28 +1078,20 @@ fn write_space_after_type(out: &mut OutFile, ty: &Type) { // Only called for legal referent types of unique_ptr and element types of // std::vector and Vec. -fn to_typename(namespace: &Namespace, ty: &Type) -> String { +fn to_typename(ty: &Type, types: &Types) -> String { match ty { - Type::Ident(ident) => { - let mut path = String::new(); - for name in namespace { - path += &name.to_string(); - path += "::"; - } - path += &ident.to_string(); - path - } - Type::CxxVector(ptr) => format!("::std::vector<{}>", to_typename(namespace, &ptr.inner)), + Type::Ident(ident) => types.resolve(&ident).to_fully_qualified(), + Type::CxxVector(ptr) => format!("::std::vector<{}>", to_typename(&ptr.inner, types)), _ => unreachable!(), } } // Only called for legal referent types of unique_ptr and element types of // std::vector and Vec. -fn to_mangled(namespace: &Namespace, ty: &Type) -> String { +fn to_mangled(ty: &Type, types: &Types) -> Symbol { match ty { - Type::Ident(_) => to_typename(namespace, ty).replace("::", "$"), - Type::CxxVector(ptr) => format!("std$vector${}", to_mangled(namespace, &ptr.inner)), + Type::Ident(ident) => ident.to_symbol(types), + Type::CxxVector(ptr) => to_mangled(&ptr.inner, types).prefix_with("std$vector$"), _ => unreachable!(), } } @@ -1057,19 +1102,20 @@ fn write_generic_instantiations(out: &mut OutFile, types: &Types) { if let Type::RustBox(ty) = ty { if let Type::Ident(inner) = &ty.inner { out.next_section(); - write_rust_box_extern(out, inner); + write_rust_box_extern(out, &types.resolve(&inner)); } } else if let Type::RustVec(ty) = ty { if let Type::Ident(inner) = &ty.inner { - if Atom::from(inner).is_none() { + if Atom::from(&inner.rust).is_none() { out.next_section(); - write_rust_vec_extern(out, inner); + write_rust_vec_extern(out, inner, types); } } } else if let Type::UniquePtr(ptr) = ty { if let Type::Ident(inner) = &ptr.inner { - if Atom::from(inner).is_none() - && (!types.aliases.contains_key(inner) || types.explicit_impls.contains(ty)) + if Atom::from(&inner.rust).is_none() + && (!types.aliases.contains_key(&inner.rust) + || types.explicit_impls.contains(ty)) { out.next_section(); write_unique_ptr(out, inner, types); @@ -1077,8 +1123,9 @@ fn write_generic_instantiations(out: &mut OutFile, types: &Types) { } } else if let Type::CxxVector(ptr) = ty { if let Type::Ident(inner) = &ptr.inner { - if Atom::from(inner).is_none() - && (!types.aliases.contains_key(inner) || types.explicit_impls.contains(ty)) + if Atom::from(&inner.rust).is_none() + && (!types.aliases.contains_key(&inner.rust) + || types.explicit_impls.contains(ty)) { out.next_section(); write_cxx_vector(out, ty, inner, types); @@ -1093,12 +1140,12 @@ fn write_generic_instantiations(out: &mut OutFile, types: &Types) { for ty in types { if let Type::RustBox(ty) = ty { if let Type::Ident(inner) = &ty.inner { - write_rust_box_impl(out, inner); + write_rust_box_impl(out, &types.resolve(&inner)); } } else if let Type::RustVec(ty) = ty { if let Type::Ident(inner) = &ty.inner { - if Atom::from(inner).is_none() { - write_rust_vec_impl(out, inner); + if Atom::from(&inner.rust).is_none() { + write_rust_vec_impl(out, inner, types); } } } @@ -1107,14 +1154,9 @@ fn write_generic_instantiations(out: &mut OutFile, types: &Types) { out.end_block("namespace rust"); } -fn write_rust_box_extern(out: &mut OutFile, ident: &Ident) { - let mut inner = String::new(); - for name in &out.namespace { - inner += &name.to_string(); - inner += "::"; - } - inner += &ident.to_string(); - let instance = inner.replace("::", "$"); +fn write_rust_box_extern(out: &mut OutFile, ident: &CppName) { + let inner = ident.to_fully_qualified(); + let instance = ident.to_symbol(); writeln!(out, "#ifndef CXXBRIDGE05_RUST_BOX_{}", instance); writeln!(out, "#define CXXBRIDGE05_RUST_BOX_{}", instance); @@ -1131,10 +1173,10 @@ fn write_rust_box_extern(out: &mut OutFile, ident: &Ident) { writeln!(out, "#endif // CXXBRIDGE05_RUST_BOX_{}", instance); } -fn write_rust_vec_extern(out: &mut OutFile, element: &Ident) { +fn write_rust_vec_extern(out: &mut OutFile, element: &ResolvableName, types: &Types) { let element = Type::Ident(element.clone()); - let inner = to_typename(&out.namespace, &element); - let instance = to_mangled(&out.namespace, &element); + let inner = to_typename(&element, types); + let instance = to_mangled(&element, types); writeln!(out, "#ifndef CXXBRIDGE05_RUST_VEC_{}", instance); writeln!(out, "#define CXXBRIDGE05_RUST_VEC_{}", instance); @@ -1166,14 +1208,9 @@ fn write_rust_vec_extern(out: &mut OutFile, element: &Ident) { writeln!(out, "#endif // CXXBRIDGE05_RUST_VEC_{}", instance); } -fn write_rust_box_impl(out: &mut OutFile, ident: &Ident) { - let mut inner = String::new(); - for name in &out.namespace { - inner += &name.to_string(); - inner += "::"; - } - inner += &ident.to_string(); - let instance = inner.replace("::", "$"); +fn write_rust_box_impl(out: &mut OutFile, ident: &CppName) { + let inner = ident.to_fully_qualified(); + let instance = ident.to_symbol(); writeln!(out, "template <>"); writeln!(out, "void Box<{}>::uninit() noexcept {{", inner); @@ -1186,10 +1223,10 @@ fn write_rust_box_impl(out: &mut OutFile, ident: &Ident) { writeln!(out, "}}"); } -fn write_rust_vec_impl(out: &mut OutFile, element: &Ident) { +fn write_rust_vec_impl(out: &mut OutFile, element: &ResolvableName, types: &Types) { let element = Type::Ident(element.clone()); - let inner = to_typename(&out.namespace, &element); - let instance = to_mangled(&out.namespace, &element); + let inner = to_typename(&element, types); + let instance = to_mangled(&element, types); writeln!(out, "template <>"); writeln!(out, "Vec<{}>::Vec() noexcept {{", inner); @@ -1225,9 +1262,9 @@ fn write_rust_vec_impl(out: &mut OutFile, element: &Ident) { writeln!(out, "}}"); } -fn write_unique_ptr(out: &mut OutFile, ident: &Ident, types: &Types) { +fn write_unique_ptr(out: &mut OutFile, ident: &ResolvableName, types: &Types) { let ty = Type::Ident(ident.clone()); - let instance = to_mangled(&out.namespace, &ty); + let instance = to_mangled(&ty, types); writeln!(out, "#ifndef CXXBRIDGE05_UNIQUE_PTR_{}", instance); writeln!(out, "#define CXXBRIDGE05_UNIQUE_PTR_{}", instance); @@ -1241,8 +1278,8 @@ fn write_unique_ptr(out: &mut OutFile, ident: &Ident, types: &Types) { fn write_unique_ptr_common(out: &mut OutFile, ty: &Type, types: &Types) { out.include.new = true; out.include.utility = true; - let inner = to_typename(&out.namespace, ty); - let instance = to_mangled(&out.namespace, ty); + let inner = to_typename(ty, types); + let instance = to_mangled(ty, types); let can_construct_from_value = match ty { // Some aliases are to opaque types; some are to trivial types. We can't @@ -1250,7 +1287,7 @@ fn write_unique_ptr_common(out: &mut OutFile, ty: &Type, types: &Types) { // bindings for a "new" method anyway. But the Rust code can't be called // for Opaque types because the 'new' method is not implemented. Type::Ident(ident) => { - types.structs.contains_key(ident) || types.aliases.contains_key(ident) + types.structs.contains_key(&ident.rust) || types.aliases.contains_key(&ident.rust) } _ => false, }; @@ -1315,10 +1352,10 @@ fn write_unique_ptr_common(out: &mut OutFile, ty: &Type, types: &Types) { writeln!(out, "}}"); } -fn write_cxx_vector(out: &mut OutFile, vector_ty: &Type, element: &Ident, types: &Types) { +fn write_cxx_vector(out: &mut OutFile, vector_ty: &Type, element: &ResolvableName, types: &Types) { let element = Type::Ident(element.clone()); - let inner = to_typename(&out.namespace, &element); - let instance = to_mangled(&out.namespace, &element); + let inner = to_typename(&element, types); + let instance = to_mangled(&element, types); writeln!(out, "#ifndef CXXBRIDGE05_VECTOR_{}", instance); writeln!(out, "#define CXXBRIDGE05_VECTOR_{}", instance); diff --git a/macro/src/expand.rs b/macro/src/expand.rs index 4a4ec642b..1bcaa1e30 100644 --- a/macro/src/expand.rs +++ b/macro/src/expand.rs @@ -1,12 +1,11 @@ use crate::derive::DeriveAttribute; use crate::syntax::atom::Atom::{self, *}; use crate::syntax::file::Module; -use crate::syntax::namespace::Namespace; use crate::syntax::report::Errors; use crate::syntax::symbol::Symbol; use crate::syntax::{ - self, check, mangle, Api, Enum, ExternFn, ExternType, Impl, Signature, Struct, Type, TypeAlias, - Types, + self, check, mangle, Api, CppName, Enum, ExternFn, ExternType, Impl, ResolvableName, Signature, + Struct, Type, TypeAlias, Types, }; use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote, quote_spanned, ToTokens}; @@ -17,11 +16,11 @@ pub fn bridge(mut ffi: Module) -> Result { let ref mut errors = Errors::new(); let content = mem::take(&mut ffi.content); let trusted = ffi.unsafety.is_some(); - let ref apis = syntax::parse_items(errors, content, trusted); + let namespace = &ffi.namespace; + let ref apis = syntax::parse_items(errors, content, trusted, namespace); let ref types = Types::collect(errors, apis); errors.propagate()?; - let namespace = &ffi.namespace; - check::typecheck(errors, namespace, apis, types); + check::typecheck(errors, apis, types); errors.propagate()?; Ok(expand(ffi, apis, types)) @@ -30,7 +29,6 @@ pub fn bridge(mut ffi: Module) -> Result { fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream { let mut expanded = TokenStream::new(); let mut hidden = TokenStream::new(); - let namespace = &ffi.namespace; for api in apis { if let Api::RustType(ety) = api { @@ -42,23 +40,23 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream { for api in apis { match api { Api::Include(_) | Api::RustType(_) | Api::Impl(_) => {} - Api::Struct(strct) => expanded.extend(expand_struct(namespace, strct)), - Api::Enum(enm) => expanded.extend(expand_enum(namespace, enm)), + Api::Struct(strct) => expanded.extend(expand_struct(strct)), + Api::Enum(enm) => expanded.extend(expand_enum(enm)), Api::CxxType(ety) => { let ident = &ety.ident; - if !types.structs.contains_key(ident) && !types.enums.contains_key(ident) { - expanded.extend(expand_cxx_type(namespace, ety)); + if !types.structs.contains_key(&ident.rust) + && !types.enums.contains_key(&ident.rust) + { + expanded.extend(expand_cxx_type(ety)); } } Api::CxxFunction(efn) => { - expanded.extend(expand_cxx_function_shim(namespace, efn, types)); - } - Api::RustFunction(efn) => { - hidden.extend(expand_rust_function_shim(namespace, efn, types)) + expanded.extend(expand_cxx_function_shim(efn, types)); } + Api::RustFunction(efn) => hidden.extend(expand_rust_function_shim(efn, types)), Api::TypeAlias(alias) => { expanded.extend(expand_type_alias(alias)); - hidden.extend(expand_type_alias_verify(namespace, alias, types)); + hidden.extend(expand_type_alias_verify(alias, types)); } } } @@ -67,33 +65,33 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream { let explicit_impl = types.explicit_impls.get(ty); if let Type::RustBox(ty) = ty { if let Type::Ident(ident) = &ty.inner { - if Atom::from(ident).is_none() { - hidden.extend(expand_rust_box(namespace, ident)); + if Atom::from(&ident.rust).is_none() { + hidden.extend(expand_rust_box(ident, types)); } } } else if let Type::RustVec(ty) = ty { if let Type::Ident(ident) = &ty.inner { - if Atom::from(ident).is_none() { - hidden.extend(expand_rust_vec(namespace, ident)); + if Atom::from(&ident.rust).is_none() { + hidden.extend(expand_rust_vec(ident, types)); } } } else if let Type::UniquePtr(ptr) = ty { if let Type::Ident(ident) = &ptr.inner { - if Atom::from(ident).is_none() - && (explicit_impl.is_some() || !types.aliases.contains_key(ident)) + if Atom::from(&ident.rust).is_none() + && (explicit_impl.is_some() || !types.aliases.contains_key(&ident.rust)) { - expanded.extend(expand_unique_ptr(namespace, ident, types, explicit_impl)); + expanded.extend(expand_unique_ptr(ident, types, explicit_impl)); } } } else if let Type::CxxVector(ptr) = ty { if let Type::Ident(ident) = &ptr.inner { - if Atom::from(ident).is_none() - && (explicit_impl.is_some() || !types.aliases.contains_key(ident)) + if Atom::from(&ident.rust).is_none() + && (explicit_impl.is_some() || !types.aliases.contains_key(&ident.rust)) { // Generate impl for CxxVector if T is a struct or opaque // C++ type. Impl for primitives is already provided by cxx // crate. - expanded.extend(expand_cxx_vector(namespace, ident, explicit_impl)); + expanded.extend(expand_cxx_vector(ident, explicit_impl, types)); } } } @@ -126,11 +124,12 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream { } } -fn expand_struct(namespace: &Namespace, strct: &Struct) -> TokenStream { - let ident = &strct.ident; +fn expand_struct(strct: &Struct) -> TokenStream { + let ident = &strct.ident.rust; + let cxx_ident = &strct.ident.cxx; let doc = &strct.doc; let derives = DeriveAttribute(&strct.derives); - let type_id = type_id(namespace, ident); + let type_id = type_id(cxx_ident); let fields = strct.fields.iter().map(|field| { // This span on the pub makes "private type in public interface" errors // appear in the right place. @@ -153,11 +152,12 @@ fn expand_struct(namespace: &Namespace, strct: &Struct) -> TokenStream { } } -fn expand_enum(namespace: &Namespace, enm: &Enum) -> TokenStream { - let ident = &enm.ident; +fn expand_enum(enm: &Enum) -> TokenStream { + let ident = &enm.ident.rust; + let cxx_ident = &enm.ident.cxx; let doc = &enm.doc; let repr = enm.repr; - let type_id = type_id(namespace, ident); + let type_id = type_id(cxx_ident); let variants = enm.variants.iter().map(|variant| { let variant_ident = &variant.ident; let discriminant = &variant.discriminant; @@ -186,10 +186,11 @@ fn expand_enum(namespace: &Namespace, enm: &Enum) -> TokenStream { } } -fn expand_cxx_type(namespace: &Namespace, ety: &ExternType) -> TokenStream { - let ident = &ety.ident; +fn expand_cxx_type(ety: &ExternType) -> TokenStream { + let ident = &ety.ident.rust; + let cxx_ident = &ety.ident.cxx; let doc = &ety.doc; - let type_id = type_id(namespace, ident); + let type_id = type_id(&cxx_ident); quote! { #doc @@ -205,7 +206,7 @@ fn expand_cxx_type(namespace: &Namespace, ety: &ExternType) -> TokenStream { } } -fn expand_cxx_function_decl(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream { +fn expand_cxx_function_decl(efn: &ExternFn, types: &Types) -> TokenStream { let receiver = efn.receiver.iter().map(|receiver| { let receiver_type = receiver.ty(); quote!(_: #receiver_type) @@ -236,7 +237,7 @@ fn expand_cxx_function_decl(namespace: &Namespace, efn: &ExternFn, types: &Types let ret = expand_extern_type(efn.ret.as_ref().unwrap()); outparam = Some(quote!(__return: *mut #ret)); } - let link_name = mangle::extern_fn(namespace, efn); + let link_name = mangle::extern_fn(efn, types); let local_name = format_ident!("__{}", efn.ident.rust); quote! { #[link_name = #link_name] @@ -244,9 +245,9 @@ fn expand_cxx_function_decl(namespace: &Namespace, efn: &ExternFn, types: &Types } } -fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream { +fn expand_cxx_function_shim(efn: &ExternFn, types: &Types) -> TokenStream { let doc = &efn.doc; - let decl = expand_cxx_function_decl(namespace, efn, types); + let decl = expand_cxx_function_decl(efn, types); let receiver = efn.receiver.iter().map(|receiver| { let ampersand = receiver.ampersand; let mutability = receiver.mutability; @@ -272,14 +273,14 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types let arg_vars = efn.args.iter().map(|arg| { let var = &arg.ident; match &arg.ty { - Type::Ident(ident) if ident == RustString => { + Type::Ident(ident) if ident.rust == RustString => { quote!(#var.as_mut_ptr() as *const ::cxx::private::RustString) } Type::RustBox(_) => quote!(::std::boxed::Box::into_raw(#var)), Type::UniquePtr(_) => quote!(::cxx::UniquePtr::into_raw(#var)), Type::RustVec(_) => quote!(#var.as_mut_ptr() as *const ::cxx::private::RustVec<_>), Type::Ref(ty) => match &ty.inner { - Type::Ident(ident) if ident == RustString => match ty.mutability { + Type::Ident(ident) if ident.rust == RustString => match ty.mutability { None => quote!(::cxx::private::RustString::from_ref(#var)), Some(_) => quote!(::cxx::private::RustString::from_mut(#var)), }, @@ -306,9 +307,7 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types .filter_map(|arg| { if let Type::Fn(f) = &arg.ty { let var = &arg.ident; - Some(expand_function_pointer_trampoline( - namespace, efn, var, f, types, - )) + Some(expand_function_pointer_trampoline(efn, var, f, types)) } else { None } @@ -355,7 +354,7 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types }; let expr = if efn.throws { efn.ret.as_ref().and_then(|ret| match ret { - Type::Ident(ident) if ident == RustString => { + Type::Ident(ident) if ident.rust == RustString => { Some(quote!(#call.map(|r| r.into_string()))) } Type::RustBox(_) => Some(quote!(#call.map(|r| ::std::boxed::Box::from_raw(r)))), @@ -368,7 +367,7 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types } Type::UniquePtr(_) => Some(quote!(#call.map(|r| ::cxx::UniquePtr::from_raw(r)))), Type::Ref(ty) => match &ty.inner { - Type::Ident(ident) if ident == RustString => match ty.mutability { + Type::Ident(ident) if ident.rust == RustString => match ty.mutability { None => Some(quote!(#call.map(|r| r.as_string()))), Some(_) => Some(quote!(#call.map(|r| r.as_mut_string()))), }, @@ -388,7 +387,7 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types }) } else { efn.ret.as_ref().and_then(|ret| match ret { - Type::Ident(ident) if ident == RustString => Some(quote!(#call.into_string())), + Type::Ident(ident) if ident.rust == RustString => Some(quote!(#call.into_string())), Type::RustBox(_) => Some(quote!(::std::boxed::Box::from_raw(#call))), Type::RustVec(vec) => { if vec.inner == RustString { @@ -399,7 +398,7 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types } Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::from_raw(#call))), Type::Ref(ty) => match &ty.inner { - Type::Ident(ident) if ident == RustString => match ty.mutability { + Type::Ident(ident) if ident.rust == RustString => match ty.mutability { None => Some(quote!(#call.as_string())), Some(_) => Some(quote!(#call.as_mut_string())), }, @@ -445,14 +444,13 @@ fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types } fn expand_function_pointer_trampoline( - namespace: &Namespace, efn: &ExternFn, var: &Ident, sig: &Signature, types: &Types, ) -> TokenStream { - let c_trampoline = mangle::c_trampoline(namespace, efn, var); - let r_trampoline = mangle::r_trampoline(namespace, efn, var); + let c_trampoline = mangle::c_trampoline(efn, var, types); + let r_trampoline = mangle::r_trampoline(efn, var, types); let local_name = parse_quote!(__); let catch_unwind_label = format!("::{}::{}", efn.ident.rust, var); let shim = expand_rust_function_shim_impl( @@ -500,7 +498,7 @@ fn expand_rust_type_assert_sized(ety: &ExternType) -> TokenStream { let sized = quote_spanned! {ety.semi_token.span=> #begin_span std::marker::Sized }; - quote_spanned! {ident.span()=> + quote_spanned! {ident.rust.span()=> let _ = { fn __AssertSized() {} __AssertSized::<#ident> @@ -508,8 +506,8 @@ fn expand_rust_type_assert_sized(ety: &ExternType) -> TokenStream { } } -fn expand_rust_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream { - let link_name = mangle::extern_fn(namespace, efn); +fn expand_rust_function_shim(efn: &ExternFn, types: &Types) -> TokenStream { + let link_name = mangle::extern_fn(efn, types); let local_name = format_ident!("__{}", efn.ident.rust); let catch_unwind_label = format!("::{}", efn.ident.rust); let invoke = Some(&efn.ident.rust); @@ -553,7 +551,7 @@ fn expand_rust_function_shim_impl( let arg_vars = sig.args.iter().map(|arg| { let ident = &arg.ident; match &arg.ty { - Type::Ident(i) if i == RustString => { + Type::Ident(i) if i.rust == RustString => { quote!(::std::mem::take((*#ident).as_mut_string())) } Type::RustBox(_) => quote!(::std::boxed::Box::from_raw(#ident)), @@ -566,7 +564,7 @@ fn expand_rust_function_shim_impl( } Type::UniquePtr(_) => quote!(::cxx::UniquePtr::from_raw(#ident)), Type::Ref(ty) => match &ty.inner { - Type::Ident(i) if i == RustString => match ty.mutability { + Type::Ident(i) if i.rust == RustString => match ty.mutability { None => quote!(#ident.as_string()), Some(_) => quote!(#ident.as_mut_string()), }, @@ -601,7 +599,9 @@ fn expand_rust_function_shim_impl( call.extend(quote! { (#(#vars),*) }); let conversion = sig.ret.as_ref().and_then(|ret| match ret { - Type::Ident(ident) if ident == RustString => Some(quote!(::cxx::private::RustString::from)), + Type::Ident(ident) if ident.rust == RustString => { + Some(quote!(::cxx::private::RustString::from)) + } Type::RustBox(_) => Some(quote!(::std::boxed::Box::into_raw)), Type::RustVec(vec) => { if vec.inner == RustString { @@ -612,7 +612,7 @@ fn expand_rust_function_shim_impl( } Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::into_raw)), Type::Ref(ty) => match &ty.inner { - Type::Ident(ident) if ident == RustString => match ty.mutability { + Type::Ident(ident) if ident.rust == RustString => match ty.mutability { None => Some(quote!(::cxx::private::RustString::from_ref)), Some(_) => Some(quote!(::cxx::private::RustString::from_mut)), }, @@ -686,13 +686,9 @@ fn expand_type_alias(alias: &TypeAlias) -> TokenStream { } } -fn expand_type_alias_verify( - namespace: &Namespace, - alias: &TypeAlias, - types: &Types, -) -> TokenStream { +fn expand_type_alias_verify(alias: &TypeAlias, types: &Types) -> TokenStream { let ident = &alias.ident; - let type_id = type_id(namespace, ident); + let type_id = type_id(&ident.cxx); let begin_span = alias.type_token.span; let end_span = alias.semi_token.span; let begin = quote_spanned!(begin_span=> ::cxx::private::verify_extern_type::<); @@ -702,7 +698,7 @@ fn expand_type_alias_verify( const _: fn() = #begin #ident, #type_id #end; }; - if types.required_trivial.contains_key(&alias.ident) { + if types.required_trivial.contains_key(&alias.ident.rust) { let begin = quote_spanned!(begin_span=> ::cxx::private::verify_extern_kind::<); verify.extend(quote! { const _: fn() = #begin #ident, ::cxx::kind::Trivial #end; @@ -712,25 +708,19 @@ fn expand_type_alias_verify( verify } -fn type_id(namespace: &Namespace, ident: &Ident) -> TokenStream { - let mut path = String::new(); - for name in namespace { - path += &name.to_string(); - path += "::"; - } - path += &ident.to_string(); - +fn type_id(ident: &CppName) -> TokenStream { + let path = ident.to_fully_qualified(); quote! { ::cxx::type_id!(#path) } } -fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream { - let link_prefix = format!("cxxbridge05$box${}{}$", namespace, ident); +fn expand_rust_box(ident: &ResolvableName, types: &Types) -> TokenStream { + let link_prefix = format!("cxxbridge05$box${}$", types.resolve(ident).to_symbol()); let link_uninit = format!("{}uninit", link_prefix); let link_drop = format!("{}drop", link_prefix); - let local_prefix = format_ident!("{}__box_", ident); + let local_prefix = format_ident!("{}__box_", &ident.rust); let local_uninit = format_ident!("{}uninit", local_prefix); let local_drop = format_ident!("{}drop", local_prefix); @@ -754,15 +744,15 @@ fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream { } } -fn expand_rust_vec(namespace: &Namespace, elem: &Ident) -> TokenStream { - let link_prefix = format!("cxxbridge05$rust_vec${}{}$", namespace, elem); +fn expand_rust_vec(elem: &ResolvableName, types: &Types) -> TokenStream { + let link_prefix = format!("cxxbridge05$rust_vec${}$", elem.to_symbol(types)); let link_new = format!("{}new", link_prefix); let link_drop = format!("{}drop", link_prefix); let link_len = format!("{}len", link_prefix); let link_data = format!("{}data", link_prefix); let link_stride = format!("{}stride", link_prefix); - let local_prefix = format_ident!("{}__vec_", elem); + let local_prefix = format_ident!("{}__vec_", elem.rust); let local_new = format_ident!("{}new", local_prefix); let local_drop = format_ident!("{}drop", local_prefix); let local_len = format_ident!("{}len", local_prefix); @@ -800,13 +790,12 @@ fn expand_rust_vec(namespace: &Namespace, elem: &Ident) -> TokenStream { } fn expand_unique_ptr( - namespace: &Namespace, - ident: &Ident, + ident: &ResolvableName, types: &Types, explicit_impl: Option<&Impl>, ) -> TokenStream { - let name = ident.to_string(); - let prefix = format!("cxxbridge05$unique_ptr${}{}$", namespace, ident); + let name = ident.rust.to_string(); + let prefix = format!("cxxbridge05$unique_ptr${}$", ident.to_symbol(types)); let link_null = format!("{}null", prefix); let link_new = format!("{}new", prefix); let link_raw = format!("{}raw", prefix); @@ -814,21 +803,22 @@ fn expand_unique_ptr( let link_release = format!("{}release", prefix); let link_drop = format!("{}drop", prefix); - let new_method = if types.structs.contains_key(ident) || types.aliases.contains_key(ident) { - Some(quote! { - fn __new(mut value: Self) -> *mut ::std::ffi::c_void { - extern "C" { - #[link_name = #link_new] - fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident); + let new_method = + if types.structs.contains_key(&ident.rust) || types.aliases.contains_key(&ident.rust) { + Some(quote! { + fn __new(mut value: Self) -> *mut ::std::ffi::c_void { + extern "C" { + #[link_name = #link_new] + fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident); + } + let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>(); + unsafe { __new(&mut repr, &mut value) } + repr } - let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>(); - unsafe { __new(&mut repr, &mut value) } - repr - } - }) - } else { - None - }; + }) + } else { + None + }; let begin_span = explicit_impl.map_or_else(Span::call_site, |explicit| explicit.impl_token.span); @@ -883,16 +873,19 @@ fn expand_unique_ptr( } fn expand_cxx_vector( - namespace: &Namespace, - elem: &Ident, + elem: &ResolvableName, explicit_impl: Option<&Impl>, + types: &Types, ) -> TokenStream { let _ = explicit_impl; - let name = elem.to_string(); - let prefix = format!("cxxbridge05$std$vector${}{}$", namespace, elem); + let name = elem.rust.to_string(); + let prefix = format!("cxxbridge05$std$vector${}$", elem.to_symbol(types)); let link_size = format!("{}size", prefix); let link_get_unchecked = format!("{}get_unchecked", prefix); - let unique_ptr_prefix = format!("cxxbridge05$unique_ptr$std$vector${}{}$", namespace, elem); + let unique_ptr_prefix = format!( + "cxxbridge05$unique_ptr$std$vector${}$", + elem.to_symbol(types) + ); let link_unique_ptr_null = format!("{}null", unique_ptr_prefix); let link_unique_ptr_raw = format!("{}raw", unique_ptr_prefix); let link_unique_ptr_get = format!("{}get", unique_ptr_prefix); @@ -979,7 +972,7 @@ fn indirect_return(sig: &Signature, types: &Types) -> bool { fn expand_extern_type(ty: &Type) -> TokenStream { match ty { - Type::Ident(ident) if ident == RustString => quote!(::cxx::private::RustString), + Type::Ident(ident) if ident.rust == RustString => quote!(::cxx::private::RustString), Type::RustBox(ty) | Type::UniquePtr(ty) => { let inner = expand_extern_type(&ty.inner); quote!(*mut #inner) @@ -991,7 +984,7 @@ fn expand_extern_type(ty: &Type) -> TokenStream { Type::Ref(ty) => { let mutability = ty.mutability; match &ty.inner { - Type::Ident(ident) if ident == RustString => { + Type::Ident(ident) if ident.rust == RustString => { quote!(&#mutability ::cxx::private::RustString) } Type::RustVec(ty) => { diff --git a/syntax/atom.rs b/syntax/atom.rs index 6e5fa8801..7d0ef6b62 100644 --- a/syntax/atom.rs +++ b/syntax/atom.rs @@ -81,7 +81,7 @@ impl AsRef for Atom { impl PartialEq for Type { fn eq(&self, atom: &Atom) -> bool { match self { - Type::Ident(ident) => ident == atom, + Type::Ident(ident) => ident.rust == atom, _ => false, } } diff --git a/syntax/attrs.rs b/syntax/attrs.rs index 4c8a3e5da..25af2296c 100644 --- a/syntax/attrs.rs +++ b/syntax/attrs.rs @@ -1,3 +1,4 @@ +use crate::syntax::namespace::Namespace; use crate::syntax::report::Errors; use crate::syntax::Atom::{self, *}; use crate::syntax::{Derive, Doc}; @@ -12,19 +13,7 @@ pub struct Parser<'a> { pub repr: Option<&'a mut Option>, pub cxx_name: Option<&'a mut Option>, pub rust_name: Option<&'a mut Option>, -} - -pub(super) fn parse_doc(cx: &mut Errors, attrs: &[Attribute]) -> Doc { - let mut doc = Doc::new(); - parse( - cx, - attrs, - Parser { - doc: Some(&mut doc), - ..Parser::default() - }, - ); - doc + pub namespace: Option<&'a mut Namespace>, } pub(super) fn parse(cx: &mut Errors, attrs: &[Attribute], mut parser: Parser) { @@ -79,6 +68,16 @@ pub(super) fn parse(cx: &mut Errors, attrs: &[Attribute], mut parser: Parser) { } Err(err) => return cx.push(err), } + } else if attr.path.is_ident("namespace") { + match parse_namespace_attribute.parse2(attr.tokens.clone()) { + Ok(attr) => { + if let Some(namespace) = &mut parser.namespace { + **namespace = attr; + continue; + } + } + Err(err) => return cx.push(err), + } } return cx.error(attr, "unsupported attribute"); } @@ -131,3 +130,10 @@ fn parse_function_alias_attribute(input: ParseStream) -> Result { input.parse() } } + +fn parse_namespace_attribute(input: ParseStream) -> Result { + let content; + syn::parenthesized!(content in input); + let namespace = content.parse::()?; + Ok(namespace) +} diff --git a/syntax/check.rs b/syntax/check.rs index ced15707e..9aba9ac56 100644 --- a/syntax/check.rs +++ b/syntax/check.rs @@ -1,5 +1,4 @@ use crate::syntax::atom::Atom::{self, *}; -use crate::syntax::namespace::Namespace; use crate::syntax::report::Errors; use crate::syntax::types::TrivialReason; use crate::syntax::{ @@ -11,15 +10,13 @@ use quote::{quote, ToTokens}; use std::fmt::Display; pub(crate) struct Check<'a> { - namespace: &'a Namespace, apis: &'a [Api], types: &'a Types<'a>, errors: &'a mut Errors, } -pub(crate) fn typecheck(cx: &mut Errors, namespace: &Namespace, apis: &[Api], types: &Types) { +pub(crate) fn typecheck(cx: &mut Errors, apis: &[Api], types: &Types) { do_typecheck(&mut Check { - namespace, apis, types, errors: cx, @@ -27,11 +24,11 @@ pub(crate) fn typecheck(cx: &mut Errors, namespace: &Namespace, apis: &[Api], ty } fn do_typecheck(cx: &mut Check) { - ident::check_all(cx, cx.namespace, cx.apis); + ident::check_all(cx, cx.apis); for ty in cx.types { match ty { - Type::Ident(ident) => check_type_ident(cx, ident), + Type::Ident(ident) => check_type_ident(cx, &ident.rust), Type::RustBox(ptr) => check_type_box(cx, ptr), Type::RustVec(ty) => check_type_rust_vec(cx, ty), Type::UniquePtr(ptr) => check_type_unique_ptr(cx, ptr), @@ -67,20 +64,20 @@ fn check_type_ident(cx: &mut Check, ident: &Ident) { && !cx.types.cxx.contains(ident) && !cx.types.rust.contains(ident) { - cx.error(ident, &format!("unsupported type: {}", ident)); + cx.error(ident, &format!("unsupported type: {}", ident.to_string())); } } fn check_type_box(cx: &mut Check, ptr: &Ty1) { if let Type::Ident(ident) = &ptr.inner { - if cx.types.cxx.contains(ident) - && !cx.types.structs.contains_key(ident) - && !cx.types.enums.contains_key(ident) + if cx.types.cxx.contains(&ident.rust) + && !cx.types.structs.contains_key(&ident.rust) + && !cx.types.enums.contains_key(&ident.rust) { cx.error(ptr, error::BOX_CXX_TYPE.msg); } - if Atom::from(ident).is_none() { + if Atom::from(&ident.rust).is_none() { return; } } @@ -90,15 +87,15 @@ fn check_type_box(cx: &mut Check, ptr: &Ty1) { fn check_type_rust_vec(cx: &mut Check, ty: &Ty1) { if let Type::Ident(ident) = &ty.inner { - if cx.types.cxx.contains(ident) - && !cx.types.structs.contains_key(ident) - && !cx.types.enums.contains_key(ident) + if cx.types.cxx.contains(&ident.rust) + && !cx.types.structs.contains_key(&ident.rust) + && !cx.types.enums.contains_key(&ident.rust) { cx.error(ty, "Rust Vec containing C++ type is not supported yet"); return; } - match Atom::from(ident) { + match Atom::from(&ident.rust) { None | Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(Usize) | Some(I8) | Some(I16) | Some(I32) | Some(I64) | Some(Isize) | Some(F32) | Some(F64) | Some(RustString) => return, @@ -112,11 +109,11 @@ fn check_type_rust_vec(cx: &mut Check, ty: &Ty1) { fn check_type_unique_ptr(cx: &mut Check, ptr: &Ty1) { if let Type::Ident(ident) = &ptr.inner { - if cx.types.rust.contains(ident) { + if cx.types.rust.contains(&ident.rust) { cx.error(ptr, "unique_ptr of a Rust type is not supported yet"); } - match Atom::from(ident) { + match Atom::from(&ident.rust) { None | Some(CxxString) => return, _ => {} } @@ -129,14 +126,14 @@ fn check_type_unique_ptr(cx: &mut Check, ptr: &Ty1) { fn check_type_cxx_vector(cx: &mut Check, ptr: &Ty1) { if let Type::Ident(ident) = &ptr.inner { - if cx.types.rust.contains(ident) { + if cx.types.rust.contains(&ident.rust) { cx.error( ptr, "C++ vector containing a Rust type is not supported yet", ); } - match Atom::from(ident) { + match Atom::from(&ident.rust) { None | Some(U8) | Some(U16) | Some(U32) | Some(U64) | Some(Usize) | Some(I8) | Some(I16) | Some(I32) | Some(I64) | Some(Isize) | Some(F32) | Some(F64) | Some(CxxString) => return, @@ -170,15 +167,15 @@ fn check_type_slice(cx: &mut Check, ty: &Slice) { fn check_api_struct(cx: &mut Check, strct: &Struct) { let ident = &strct.ident; - check_reserved_name(cx, ident); + check_reserved_name(cx, &ident.rust); if strct.fields.is_empty() { let span = span_for_struct_error(strct); cx.error(span, "structs without any fields are not supported"); } - if cx.types.cxx.contains(ident) { - if let Some(ety) = cx.types.untrusted.get(ident) { + if cx.types.cxx.contains(&ident.rust) { + if let Some(ety) = cx.types.untrusted.get(&ident.rust) { let msg = "extern shared struct must be declared in an `unsafe extern` block"; cx.error(ety, msg); } @@ -200,7 +197,7 @@ fn check_api_struct(cx: &mut Check, strct: &Struct) { } fn check_api_enum(cx: &mut Check, enm: &Enum) { - check_reserved_name(cx, &enm.ident); + check_reserved_name(cx, &enm.ident.rust); if enm.variants.is_empty() { let span = span_for_enum_error(enm); @@ -209,11 +206,13 @@ fn check_api_enum(cx: &mut Check, enm: &Enum) { } fn check_api_type(cx: &mut Check, ety: &ExternType) { - check_reserved_name(cx, &ety.ident); + check_reserved_name(cx, &ety.ident.rust); - if let Some(reason) = cx.types.required_trivial.get(&ety.ident) { + if let Some(reason) = cx.types.required_trivial.get(&ety.ident.rust) { let what = match reason { - TrivialReason::StructField(strct) => format!("a field of `{}`", strct.ident), + TrivialReason::StructField(strct) => { + format!("a field of `{}`", strct.ident.cxx.to_fully_qualified()) + } TrivialReason::FunctionArgument(efn) => format!("an argument of `{}`", efn.ident.rust), TrivialReason::FunctionReturn(efn) => format!("a return value of `{}`", efn.ident.rust), }; @@ -229,7 +228,7 @@ fn check_api_fn(cx: &mut Check, efn: &ExternFn) { if let Some(receiver) = &efn.receiver { let ref span = span_for_receiver_error(receiver); - if receiver.ty == "Self" { + if receiver.ty.is_self() { let mutability = match receiver.mutability { Some(_) => "mut ", None => "", @@ -241,9 +240,9 @@ fn check_api_fn(cx: &mut Check, efn: &ExternFn) { mutability = mutability, ); cx.error(span, msg); - } else if !cx.types.structs.contains_key(&receiver.ty) - && !cx.types.cxx.contains(&receiver.ty) - && !cx.types.rust.contains(&receiver.ty) + } else if !cx.types.structs.contains_key(&receiver.ty.rust) + && !cx.types.cxx.contains(&receiver.ty.rust) + && !cx.types.rust.contains(&receiver.ty.rust) { cx.error(span, "unrecognized receiver type"); } @@ -290,7 +289,7 @@ fn check_api_fn(cx: &mut Check, efn: &ExternFn) { fn check_api_impl(cx: &mut Check, imp: &Impl) { if let Type::UniquePtr(ty) | Type::CxxVector(ty) = &imp.ty { if let Type::Ident(inner) = &ty.inner { - if Atom::from(inner).is_none() { + if Atom::from(&inner.rust).is_none() { return; } } @@ -357,7 +356,7 @@ fn check_reserved_name(cx: &mut Check, ident: &Ident) { fn is_unsized(cx: &mut Check, ty: &Type) -> bool { let ident = match ty { - Type::Ident(ident) => ident, + Type::Ident(ident) => &ident.rust, Type::CxxVector(_) | Type::Slice(_) | Type::Void(_) => return true, _ => return false, }; @@ -400,20 +399,20 @@ fn span_for_receiver_error(receiver: &Receiver) -> TokenStream { fn describe(cx: &mut Check, ty: &Type) -> String { match ty { Type::Ident(ident) => { - if cx.types.structs.contains_key(ident) { + if cx.types.structs.contains_key(&ident.rust) { "struct".to_owned() - } else if cx.types.enums.contains_key(ident) { + } else if cx.types.enums.contains_key(&ident.rust) { "enum".to_owned() - } else if cx.types.aliases.contains_key(ident) { + } else if cx.types.aliases.contains_key(&ident.rust) { "C++ type".to_owned() - } else if cx.types.cxx.contains(ident) { + } else if cx.types.cxx.contains(&ident.rust) { "opaque C++ type".to_owned() - } else if cx.types.rust.contains(ident) { + } else if cx.types.rust.contains(&ident.rust) { "opaque Rust type".to_owned() - } else if Atom::from(ident) == Some(CxxString) { + } else if Atom::from(&ident.rust) == Some(CxxString) { "C++ string".to_owned() } else { - ident.to_string() + ident.rust.to_string() } } Type::RustBox(_) => "Box".to_owned(), diff --git a/syntax/ident.rs b/syntax/ident.rs index 66f736510..354790a3e 100644 --- a/syntax/ident.rs +++ b/syntax/ident.rs @@ -1,6 +1,5 @@ use crate::syntax::check::Check; -use crate::syntax::namespace::Namespace; -use crate::syntax::{error, Api}; +use crate::syntax::{error, Api, CppName}; use proc_macro2::Ident; fn check(cx: &mut Check, ident: &Ident) { @@ -13,28 +12,31 @@ fn check(cx: &mut Check, ident: &Ident) { } } -pub(crate) fn check_all(cx: &mut Check, namespace: &Namespace, apis: &[Api]) { - for segment in namespace { +fn check_ident(cx: &mut Check, ident: &CppName) { + for segment in &ident.ns { check(cx, segment); } + check(cx, &ident.ident); +} +pub(crate) fn check_all(cx: &mut Check, apis: &[Api]) { for api in apis { match api { Api::Include(_) | Api::Impl(_) => {} Api::Struct(strct) => { - check(cx, &strct.ident); + check_ident(cx, &strct.ident.cxx); for field in &strct.fields { check(cx, &field.ident); } } Api::Enum(enm) => { - check(cx, &enm.ident); + check_ident(cx, &enm.ident.cxx); for variant in &enm.variants { check(cx, &variant.ident); } } Api::CxxType(ety) | Api::RustType(ety) => { - check(cx, &ety.ident); + check_ident(cx, &ety.ident.cxx); } Api::CxxFunction(efn) | Api::RustFunction(efn) => { check(cx, &efn.ident.rust); @@ -43,7 +45,7 @@ pub(crate) fn check_all(cx: &mut Check, namespace: &Namespace, apis: &[Api]) { } } Api::TypeAlias(alias) => { - check(cx, &alias.ident); + check_ident(cx, &alias.ident.cxx); } } } diff --git a/syntax/impls.rs b/syntax/impls.rs index 6a177d529..a83ce7475 100644 --- a/syntax/impls.rs +++ b/syntax/impls.rs @@ -1,8 +1,13 @@ -use crate::syntax::{ExternFn, Impl, Receiver, Ref, Signature, Slice, Ty1, Type}; +use crate::syntax::{ + Api, CppName, ExternFn, Impl, Namespace, Pair, Receiver, Ref, ResolvableName, Signature, Slice, + Symbol, Ty1, Type, Types, +}; +use proc_macro2::{Ident, Span}; use std::borrow::Borrow; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::{Deref, DerefMut}; +use syn::Token; impl Deref for ExternFn { type Target = Signature; @@ -274,3 +279,84 @@ impl Borrow for &Impl { &self.ty } } + +impl Pair { + /// Use this constructor when the item can't have a different + /// name in Rust and C++. For cases where #[rust_name] and similar + /// attributes can be used, construct the object by hand. + pub fn new(ns: Namespace, ident: Ident) -> Self { + Self { + rust: ident.clone(), + cxx: CppName::new(ns, ident), + } + } +} + +impl ResolvableName { + pub fn new(ident: Ident) -> Self { + Self { rust: ident } + } + + pub fn from_pair(pair: Pair) -> Self { + Self { rust: pair.rust } + } + + pub fn make_self(span: Span) -> Self { + Self { + rust: Token![Self](span).into(), + } + } + + pub fn is_self(&self) -> bool { + self.rust == "Self" + } + + pub fn span(&self) -> Span { + self.rust.span() + } + + pub fn to_symbol(&self, types: &Types) -> Symbol { + types.resolve(self).to_symbol() + } +} + +impl Api { + pub fn get_namespace(&self) -> Option<&Namespace> { + match self { + Api::CxxFunction(cfn) => Some(&cfn.ident.cxx.ns), + Api::CxxType(cty) => Some(&cty.ident.cxx.ns), + Api::Enum(enm) => Some(&enm.ident.cxx.ns), + Api::Struct(strct) => Some(&strct.ident.cxx.ns), + Api::RustType(rty) => Some(&rty.ident.cxx.ns), + Api::RustFunction(rfn) => Some(&rfn.ident.cxx.ns), + Api::Impl(_) | Api::Include(_) | Api::TypeAlias(_) => None, + } + } +} + +impl CppName { + pub fn new(ns: Namespace, ident: Ident) -> Self { + Self { ns, ident } + } + + fn iter_all_segments( + &self, + ) -> std::iter::Chain, std::iter::Once<&Ident>> { + self.ns.iter().chain(std::iter::once(&self.ident)) + } + + fn join(&self, sep: &str) -> String { + self.iter_all_segments() + .map(|s| s.to_string()) + .collect::>() + .join(sep) + } + + pub fn to_symbol(&self) -> Symbol { + Symbol::from_idents(self.iter_all_segments()) + } + + pub fn to_fully_qualified(&self) -> String { + format!("::{}", self.join("::")) + } +} diff --git a/syntax/mangle.rs b/syntax/mangle.rs index e4618875d..9255feb6e 100644 --- a/syntax/mangle.rs +++ b/syntax/mangle.rs @@ -1,6 +1,5 @@ -use crate::syntax::namespace::Namespace; use crate::syntax::symbol::{self, Symbol}; -use crate::syntax::ExternFn; +use crate::syntax::{ExternFn, Types}; use proc_macro2::Ident; const CXXBRIDGE: &str = "cxxbridge05"; @@ -11,19 +10,27 @@ macro_rules! join { }; } -pub fn extern_fn(namespace: &Namespace, efn: &ExternFn) -> Symbol { +pub fn extern_fn(efn: &ExternFn, types: &Types) -> Symbol { match &efn.receiver { - Some(receiver) => join!(namespace, CXXBRIDGE, receiver.ty, efn.ident.rust), - None => join!(namespace, CXXBRIDGE, efn.ident.rust), + Some(receiver) => { + let receiver_ident = types.resolve(&receiver.ty); + join!( + efn.ident.cxx.ns, + CXXBRIDGE, + receiver_ident.ident, + efn.ident.rust + ) + } + None => join!(efn.ident.cxx.ns, CXXBRIDGE, efn.ident.rust), } } // The C half of a function pointer trampoline. -pub fn c_trampoline(namespace: &Namespace, efn: &ExternFn, var: &Ident) -> Symbol { - join!(extern_fn(namespace, efn), var, 0) +pub fn c_trampoline(efn: &ExternFn, var: &Ident, types: &Types) -> Symbol { + join!(extern_fn(efn, types), var, 0) } // The Rust half of a function pointer trampoline. -pub fn r_trampoline(namespace: &Namespace, efn: &ExternFn, var: &Ident) -> Symbol { - join!(extern_fn(namespace, efn), var, 1) +pub fn r_trampoline(efn: &ExternFn, var: &Ident, types: &Types) -> Symbol { + join!(extern_fn(efn, types), var, 1) } diff --git a/syntax/mod.rs b/syntax/mod.rs index c8dea67f2..bb9566d50 100644 --- a/syntax/mod.rs +++ b/syntax/mod.rs @@ -21,7 +21,9 @@ mod tokens; pub mod types; use self::discriminant::Discriminant; +use self::namespace::Namespace; use self::parse::kw; +use self::symbol::Symbol; use proc_macro2::{Ident, Span}; use syn::punctuated::Punctuated; use syn::token::{Brace, Bracket, Paren}; @@ -33,6 +35,29 @@ pub use self::doc::Doc; pub use self::parse::parse_items; pub use self::types::Types; +/// A Rust identifier will forver == a proc_macro2::Ident, +/// but for completeness here's a type alias. +pub type RsIdent = Ident; + +/// At the moment, a Rust name is simply a proc_macro2::Ident. +/// In the future, it may become namespaced based on a mod path. +pub type RsName = RsIdent; + +/// At the moment, a C++ identifier is also a proc_macro2::Ident. +/// In the future, we may wish to make a newtype wrapper here +/// to avoid confusion between C++ and Rust identifiers. +pub type CppIdent = Ident; + +#[derive(Clone)] +/// A C++ identifier in a particular namespace. +/// It is intentional that this does not impl Display, +/// because we want to force users actively to decide whether to output +/// it as a qualified name or as an unqualfiied name. +pub struct CppName { + pub ns: Namespace, + pub ident: CppIdent, +} + pub enum Api { Include(String), Struct(Struct), @@ -48,7 +73,7 @@ pub enum Api { pub struct ExternType { pub doc: Doc, pub type_token: Token![type], - pub ident: Ident, + pub ident: Pair, pub semi_token: Token![;], pub trusted: bool, } @@ -57,7 +82,7 @@ pub struct Struct { pub doc: Doc, pub derives: Vec, pub struct_token: Token![struct], - pub ident: Ident, + pub ident: Pair, pub brace_token: Brace, pub fields: Vec, } @@ -65,15 +90,18 @@ pub struct Struct { pub struct Enum { pub doc: Doc, pub enum_token: Token![enum], - pub ident: Ident, + pub ident: Pair, pub brace_token: Brace, pub variants: Vec, pub repr: Atom, } +/// A type with a defined Rust name and a fully resolved, +/// qualified, namespaced, C++ name. +#[derive(Clone)] pub struct Pair { - pub cxx: Ident, - pub rust: Ident, + pub cxx: CppName, + pub rust: RsName, } pub struct ExternFn { @@ -87,7 +115,7 @@ pub struct ExternFn { pub struct TypeAlias { pub doc: Doc, pub type_token: Token![type], - pub ident: Ident, + pub ident: Pair, pub eq_token: Token![=], pub ty: RustType, pub semi_token: Token![;], @@ -112,7 +140,7 @@ pub struct Signature { #[derive(Eq, PartialEq, Hash)] pub struct Var { - pub ident: Ident, + pub ident: RsIdent, // fields and variables are not namespaced pub ty: Type, } @@ -121,18 +149,18 @@ pub struct Receiver { pub lifetime: Option, pub mutability: Option, pub var: Token![self], - pub ty: Ident, + pub ty: ResolvableName, pub shorthand: bool, } pub struct Variant { - pub ident: Ident, + pub ident: RsIdent, pub discriminant: Discriminant, pub expr: Option, } pub enum Type { - Ident(Ident), + Ident(ResolvableName), RustBox(Box), RustVec(Box), UniquePtr(Box), @@ -146,7 +174,7 @@ pub enum Type { } pub struct Ty1 { - pub name: Ident, + pub name: ResolvableName, pub langle: Token![<], pub inner: Type, pub rangle: Token![>], @@ -169,3 +197,10 @@ pub enum Lang { Cxx, Rust, } + +/// Wrapper for a type which needs to be resolved +/// before it can be printed in C++. +#[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] +pub struct ResolvableName { + pub rust: RsName, +} diff --git a/syntax/parse.rs b/syntax/parse.rs index 367ad059f..0a86b6cdb 100644 --- a/syntax/parse.rs +++ b/syntax/parse.rs @@ -3,8 +3,8 @@ use crate::syntax::file::{Item, ItemForeignMod}; use crate::syntax::report::Errors; use crate::syntax::Atom::*; use crate::syntax::{ - attrs, error, Api, Doc, Enum, ExternFn, ExternType, Impl, Lang, Pair, Receiver, Ref, Signature, - Slice, Struct, Ty1, Type, TypeAlias, Var, Variant, + attrs, error, Api, CppName, Doc, Enum, ExternFn, ExternType, Impl, Lang, Namespace, Pair, + Receiver, Ref, ResolvableName, Signature, Slice, Struct, Ty1, Type, TypeAlias, Var, Variant, }; use proc_macro2::{Delimiter, Group, TokenStream, TokenTree}; use quote::{format_ident, quote, quote_spanned}; @@ -20,20 +20,22 @@ pub mod kw { syn::custom_keyword!(Result); } -pub fn parse_items(cx: &mut Errors, items: Vec, trusted: bool) -> Vec { +pub fn parse_items(cx: &mut Errors, items: Vec, trusted: bool, ns: &Namespace) -> Vec { let mut apis = Vec::new(); for item in items { match item { - Item::Struct(item) => match parse_struct(cx, item) { + Item::Struct(item) => match parse_struct(cx, item, ns.clone()) { Ok(strct) => apis.push(strct), Err(err) => cx.push(err), }, - Item::Enum(item) => match parse_enum(cx, item) { + Item::Enum(item) => match parse_enum(cx, item, ns.clone()) { Ok(enm) => apis.push(enm), Err(err) => cx.push(err), }, - Item::ForeignMod(foreign_mod) => parse_foreign_mod(cx, foreign_mod, &mut apis, trusted), - Item::Impl(item) => match parse_impl(item) { + Item::ForeignMod(foreign_mod) => { + parse_foreign_mod(cx, foreign_mod, &mut apis, trusted, ns) + } + Item::Impl(item) => match parse_impl(item, ns) { Ok(imp) => apis.push(imp), Err(err) => cx.push(err), }, @@ -44,7 +46,7 @@ pub fn parse_items(cx: &mut Errors, items: Vec, trusted: bool) -> Vec apis } -fn parse_struct(cx: &mut Errors, item: ItemStruct) -> Result { +fn parse_struct(cx: &mut Errors, item: ItemStruct, mut ns: Namespace) -> Result { let generics = &item.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { let struct_token = item.struct_token; @@ -65,6 +67,7 @@ fn parse_struct(cx: &mut Errors, item: ItemStruct) -> Result { attrs::Parser { doc: Some(&mut doc), derives: Some(&mut derives), + namespace: Some(&mut ns), ..Default::default() }, ); @@ -81,7 +84,7 @@ fn parse_struct(cx: &mut Errors, item: ItemStruct) -> Result { doc, derives, struct_token: item.struct_token, - ident: item.ident, + ident: Pair::new(ns.clone(), item.ident), brace_token: fields.brace_token, fields: fields .named @@ -89,14 +92,14 @@ fn parse_struct(cx: &mut Errors, item: ItemStruct) -> Result { .map(|field| { Ok(Var { ident: field.ident.unwrap(), - ty: parse_type(&field.ty)?, + ty: parse_type(&field.ty, &ns)?, }) }) .collect::>()?, })) } -fn parse_enum(cx: &mut Errors, item: ItemEnum) -> Result { +fn parse_enum(cx: &mut Errors, item: ItemEnum, mut ns: Namespace) -> Result { let generics = &item.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { let enum_token = item.enum_token; @@ -117,6 +120,7 @@ fn parse_enum(cx: &mut Errors, item: ItemEnum) -> Result { attrs::Parser { doc: Some(&mut doc), repr: Some(&mut repr), + namespace: Some(&mut ns), ..Default::default() }, ); @@ -167,7 +171,7 @@ fn parse_enum(cx: &mut Errors, item: ItemEnum) -> Result { Ok(Api::Enum(Enum { doc, enum_token, - ident: item.ident, + ident: Pair::new(ns, item.ident), brace_token, variants, repr, @@ -179,6 +183,7 @@ fn parse_foreign_mod( foreign_mod: ItemForeignMod, out: &mut Vec, trusted: bool, + ns: &Namespace, ) { let lang = match parse_lang(&foreign_mod.abi) { Ok(lang) => lang, @@ -202,11 +207,13 @@ fn parse_foreign_mod( let mut items = Vec::new(); for foreign in &foreign_mod.items { match foreign { - ForeignItem::Type(foreign) => match parse_extern_type(cx, foreign, lang, trusted) { - Ok(ety) => items.push(ety), - Err(err) => cx.push(err), - }, - ForeignItem::Fn(foreign) => match parse_extern_fn(cx, foreign, lang) { + ForeignItem::Type(foreign) => { + match parse_extern_type(cx, foreign, lang, trusted, ns.clone()) { + Ok(ety) => items.push(ety), + Err(err) => cx.push(err), + } + } + ForeignItem::Fn(foreign) => match parse_extern_fn(cx, foreign, lang, ns.clone()) { Ok(efn) => items.push(efn), Err(err) => cx.push(err), }, @@ -216,10 +223,12 @@ fn parse_foreign_mod( Err(err) => cx.push(err), } } - ForeignItem::Verbatim(tokens) => match parse_extern_verbatim(cx, tokens, lang) { - Ok(api) => items.push(api), - Err(err) => cx.push(err), - }, + ForeignItem::Verbatim(tokens) => { + match parse_extern_verbatim(cx, tokens, lang, ns.clone()) { + Ok(api) => items.push(api), + Err(err) => cx.push(err), + } + } _ => cx.error(foreign, "unsupported foreign item"), } } @@ -234,8 +243,8 @@ fn parse_foreign_mod( for item in &mut items { if let Api::CxxFunction(efn) | Api::RustFunction(efn) = item { if let Some(receiver) = &mut efn.receiver { - if receiver.ty == "Self" { - receiver.ty = single_type.clone(); + if receiver.ty.is_self() { + receiver.ty = ResolvableName::from_pair(single_type.clone()); } } } @@ -267,8 +276,18 @@ fn parse_extern_type( foreign_type: &ForeignItemType, lang: Lang, trusted: bool, + mut ns: Namespace, ) -> Result { - let doc = attrs::parse_doc(cx, &foreign_type.attrs); + let mut doc = Doc::new(); + attrs::parse( + cx, + &foreign_type.attrs, + attrs::Parser { + doc: Some(&mut doc), + namespace: Some(&mut ns), + ..Default::default() + }, + ); let type_token = foreign_type.type_token; let ident = foreign_type.ident.clone(); let semi_token = foreign_type.semi_token; @@ -279,13 +298,18 @@ fn parse_extern_type( Ok(api_type(ExternType { doc, type_token, - ident, + ident: Pair::new(ns, ident), semi_token, trusted, })) } -fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> Result { +fn parse_extern_fn( + cx: &mut Errors, + foreign_fn: &ForeignItemFn, + lang: Lang, + mut ns: Namespace, +) -> Result { let generics = &foreign_fn.sig.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { return Err(Error::new_spanned( @@ -310,6 +334,7 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R doc: Some(&mut doc), cxx_name: Some(&mut cxx_name), rust_name: Some(&mut rust_name), + namespace: Some(&mut ns), ..Default::default() }, ); @@ -326,7 +351,7 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R lifetime: lifetime.clone(), mutability: arg.mutability, var: arg.self_token, - ty: Token![Self](arg.self_token.span).into(), + ty: ResolvableName::make_self(arg.self_token.span), shorthand: true, }); continue; @@ -341,7 +366,7 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R } _ => return Err(Error::new_spanned(arg, "unsupported signature")), }; - let ty = parse_type(&arg.ty)?; + let ty = parse_type(&arg.ty, &ns)?; if ident != "self" { args.push_value(Var { ident, ty }); if let Some(comma) = comma { @@ -355,7 +380,7 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R ampersand: reference.ampersand, lifetime: reference.lifetime, mutability: reference.mutability, - var: Token![self](ident.span()), + var: Token![self](ident.rust.span()), ty: ident, shorthand: false, }); @@ -368,12 +393,12 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R } let mut throws_tokens = None; - let ret = parse_return_type(&foreign_fn.sig.output, &mut throws_tokens)?; + let ret = parse_return_type(&foreign_fn.sig.output, &mut throws_tokens, &ns)?; let throws = throws_tokens.is_some(); let unsafety = foreign_fn.sig.unsafety; let fn_token = foreign_fn.sig.fn_token; let ident = Pair { - cxx: cxx_name.unwrap_or(foreign_fn.sig.ident.clone()), + cxx: CppName::new(ns, cxx_name.unwrap_or(foreign_fn.sig.ident.clone())), rust: rust_name.unwrap_or(foreign_fn.sig.ident.clone()), }; let paren_token = foreign_fn.sig.paren_token; @@ -401,7 +426,12 @@ fn parse_extern_fn(cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang) -> R })) } -fn parse_extern_verbatim(cx: &mut Errors, tokens: &TokenStream, lang: Lang) -> Result { +fn parse_extern_verbatim( + cx: &mut Errors, + tokens: &TokenStream, + lang: Lang, + mut ns: Namespace, +) -> Result { // type Alias = crate::path::to::Type; let parse = |input: ParseStream| -> Result { let attrs = input.call(Attribute::parse_outer)?; @@ -416,12 +446,21 @@ fn parse_extern_verbatim(cx: &mut Errors, tokens: &TokenStream, lang: Lang) -> R let eq_token: Token![=] = input.parse()?; let ty: RustType = input.parse()?; let semi_token: Token![;] = input.parse()?; - let doc = attrs::parse_doc(cx, &attrs); + let mut doc = Doc::new(); + attrs::parse( + cx, + &attrs, + attrs::Parser { + doc: Some(&mut doc), + namespace: Some(&mut ns), + ..Default::default() + }, + ); Ok(TypeAlias { doc, type_token, - ident, + ident: Pair::new(ns, ident), eq_token, ty, semi_token, @@ -440,7 +479,7 @@ fn parse_extern_verbatim(cx: &mut Errors, tokens: &TokenStream, lang: Lang) -> R } } -fn parse_impl(imp: ItemImpl) -> Result { +fn parse_impl(imp: ItemImpl, ns: &Namespace) -> Result { if !imp.items.is_empty() { let mut span = Group::new(Delimiter::Brace, TokenStream::new()); span.set_span(imp.brace_token.span); @@ -466,7 +505,7 @@ fn parse_impl(imp: ItemImpl) -> Result { Ok(Api::Impl(Impl { impl_token: imp.impl_token, - ty: parse_type(&self_ty)?, + ty: parse_type(&self_ty, ns)?, brace_token: imp.brace_token, })) } @@ -503,21 +542,21 @@ fn parse_include(input: ParseStream) -> Result { Err(input.error("expected \"quoted/path/to\" or ")) } -fn parse_type(ty: &RustType) -> Result { +fn parse_type(ty: &RustType, ns: &Namespace) -> Result { match ty { - RustType::Reference(ty) => parse_type_reference(ty), - RustType::Path(ty) => parse_type_path(ty), - RustType::Slice(ty) => parse_type_slice(ty), - RustType::BareFn(ty) => parse_type_fn(ty), + RustType::Reference(ty) => parse_type_reference(ty, ns), + RustType::Path(ty) => parse_type_path(ty, ns), + RustType::Slice(ty) => parse_type_slice(ty, ns), + RustType::BareFn(ty) => parse_type_fn(ty, ns), RustType::Tuple(ty) if ty.elems.is_empty() => Ok(Type::Void(ty.paren_token.span)), _ => Err(Error::new_spanned(ty, "unsupported type")), } } -fn parse_type_reference(ty: &TypeReference) -> Result { - let inner = parse_type(&ty.elem)?; +fn parse_type_reference(ty: &TypeReference, ns: &Namespace) -> Result { + let inner = parse_type(&ty.elem, ns)?; let which = match &inner { - Type::Ident(ident) if ident == "str" => { + Type::Ident(ident) if ident.rust == "str" => { if ty.mutability.is_some() { return Err(Error::new_spanned(ty, "unsupported type")); } else { @@ -525,7 +564,7 @@ fn parse_type_reference(ty: &TypeReference) -> Result { } } Type::Slice(slice) => match &slice.inner { - Type::Ident(ident) if ident == U8 && ty.mutability.is_none() => Type::SliceRefU8, + Type::Ident(ident) if ident.rust == U8 && ty.mutability.is_none() => Type::SliceRefU8, _ => Type::Ref, }, _ => Type::Ref, @@ -538,19 +577,20 @@ fn parse_type_reference(ty: &TypeReference) -> Result { }))) } -fn parse_type_path(ty: &TypePath) -> Result { +fn parse_type_path(ty: &TypePath, ns: &Namespace) -> Result { let path = &ty.path; if ty.qself.is_none() && path.leading_colon.is_none() && path.segments.len() == 1 { let segment = &path.segments[0]; let ident = segment.ident.clone(); + let maybe_resolved_ident = ResolvableName::new(ident.clone()); match &segment.arguments { - PathArguments::None => return Ok(Type::Ident(ident)), + PathArguments::None => return Ok(Type::Ident(maybe_resolved_ident)), PathArguments::AngleBracketed(generic) => { if ident == "UniquePtr" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { - let inner = parse_type(arg)?; + let inner = parse_type(arg, ns)?; return Ok(Type::UniquePtr(Box::new(Ty1 { - name: ident, + name: maybe_resolved_ident, langle: generic.lt_token, inner, rangle: generic.gt_token, @@ -558,9 +598,9 @@ fn parse_type_path(ty: &TypePath) -> Result { } } else if ident == "CxxVector" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { - let inner = parse_type(arg)?; + let inner = parse_type(arg, ns)?; return Ok(Type::CxxVector(Box::new(Ty1 { - name: ident, + name: maybe_resolved_ident, langle: generic.lt_token, inner, rangle: generic.gt_token, @@ -568,9 +608,9 @@ fn parse_type_path(ty: &TypePath) -> Result { } } else if ident == "Box" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { - let inner = parse_type(arg)?; + let inner = parse_type(arg, ns)?; return Ok(Type::RustBox(Box::new(Ty1 { - name: ident, + name: maybe_resolved_ident, langle: generic.lt_token, inner, rangle: generic.gt_token, @@ -578,9 +618,9 @@ fn parse_type_path(ty: &TypePath) -> Result { } } else if ident == "Vec" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { - let inner = parse_type(arg)?; + let inner = parse_type(arg, ns)?; return Ok(Type::RustVec(Box::new(Ty1 { - name: ident, + name: maybe_resolved_ident, langle: generic.lt_token, inner, rangle: generic.gt_token, @@ -594,15 +634,15 @@ fn parse_type_path(ty: &TypePath) -> Result { Err(Error::new_spanned(ty, "unsupported type")) } -fn parse_type_slice(ty: &TypeSlice) -> Result { - let inner = parse_type(&ty.elem)?; +fn parse_type_slice(ty: &TypeSlice, ns: &Namespace) -> Result { + let inner = parse_type(&ty.elem, ns)?; Ok(Type::Slice(Box::new(Slice { bracket: ty.bracket_token, inner, }))) } -fn parse_type_fn(ty: &TypeBareFn) -> Result { +fn parse_type_fn(ty: &TypeBareFn, ns: &Namespace) -> Result { if ty.lifetimes.is_some() { return Err(Error::new_spanned( ty, @@ -620,7 +660,7 @@ fn parse_type_fn(ty: &TypeBareFn) -> Result { .iter() .enumerate() .map(|(i, arg)| { - let ty = parse_type(&arg.ty)?; + let ty = parse_type(&arg.ty, ns)?; let ident = match &arg.name { Some(ident) => ident.0.clone(), None => format_ident!("_{}", i), @@ -629,7 +669,7 @@ fn parse_type_fn(ty: &TypeBareFn) -> Result { }) .collect::>()?; let mut throws_tokens = None; - let ret = parse_return_type(&ty.output, &mut throws_tokens)?; + let ret = parse_return_type(&ty.output, &mut throws_tokens, ns)?; let throws = throws_tokens.is_some(); Ok(Type::Fn(Box::new(Signature { unsafety: ty.unsafety, @@ -646,6 +686,7 @@ fn parse_type_fn(ty: &TypeBareFn) -> Result { fn parse_return_type( ty: &ReturnType, throws_tokens: &mut Option<(kw::Result, Token![<], Token![>])>, + ns: &Namespace, ) -> Result> { let mut ret = match ty { ReturnType::Default => return Ok(None), @@ -667,7 +708,7 @@ fn parse_return_type( } } } - match parse_type(ret)? { + match parse_type(ret, ns)? { Type::Void(_) => Ok(None), ty => Ok(Some(ty)), } diff --git a/syntax/qualified.rs b/syntax/qualified.rs index be9bceb43..5eefb8dbe 100644 --- a/syntax/qualified.rs +++ b/syntax/qualified.rs @@ -10,6 +10,7 @@ impl QualifiedName { pub fn parse_unquoted(input: ParseStream) -> Result { let mut segments = Vec::new(); let mut trailing_punct = true; + input.parse::>()?; while trailing_punct && input.peek(Ident::peek_any) { let ident = Ident::parse_any(input)?; segments.push(ident); diff --git a/syntax/symbol.rs b/syntax/symbol.rs index 1e5b5131d..0b79d5f9d 100644 --- a/syntax/symbol.rs +++ b/syntax/symbol.rs @@ -1,4 +1,5 @@ use crate::syntax::namespace::Namespace; +use crate::syntax::CppName; use proc_macro2::{Ident, TokenStream}; use quote::ToTokens; use std::fmt::{self, Display, Write}; @@ -19,12 +20,6 @@ impl ToTokens for Symbol { } } -impl From<&Ident> for Symbol { - fn from(ident: &Ident) -> Self { - Symbol(ident.to_string()) - } -} - impl Symbol { fn push(&mut self, segment: &dyn Display) { let len_before = self.0.len(); @@ -34,18 +29,47 @@ impl Symbol { self.0.write_fmt(format_args!("{}", segment)).unwrap(); assert!(self.0.len() > len_before); } + + pub fn from_idents<'a, T: Iterator>(it: T) -> Self { + let mut symbol = Symbol(String::new()); + for segment in it { + segment.write(&mut symbol); + } + assert!(!symbol.0.is_empty()); + symbol + } + + /// For example, for taking a symbol and then making a new symbol + /// for a vec of that symbol. + pub fn prefix_with(&self, prefix: &str) -> Symbol { + Symbol(format!("{}{}", prefix, self.to_string())) + } +} + +pub trait Segment { + fn write(&self, symbol: &mut Symbol); } -pub trait Segment: Display { +impl Segment for str { + fn write(&self, symbol: &mut Symbol) { + symbol.push(&self); + } +} +impl Segment for usize { + fn write(&self, symbol: &mut Symbol) { + symbol.push(&self); + } +} +impl Segment for Ident { + fn write(&self, symbol: &mut Symbol) { + symbol.push(&self); + } +} +impl Segment for Symbol { fn write(&self, symbol: &mut Symbol) { symbol.push(&self); } } - -impl Segment for str {} -impl Segment for usize {} -impl Segment for Ident {} -impl Segment for Symbol {} impl Segment for Namespace { fn write(&self, symbol: &mut Symbol) { @@ -55,9 +79,16 @@ impl Segment for Namespace { } } +impl Segment for CppName { + fn write(&self, symbol: &mut Symbol) { + self.ns.write(symbol); + self.ident.write(symbol); + } +} + impl Segment for &'_ T where - T: ?Sized + Segment, + T: ?Sized + Segment + Display, { fn write(&self, symbol: &mut Symbol) { (**self).write(symbol); diff --git a/syntax/tokens.rs b/syntax/tokens.rs index 7618e99da..57db8eb7e 100644 --- a/syntax/tokens.rs +++ b/syntax/tokens.rs @@ -1,7 +1,7 @@ use crate::syntax::atom::Atom::*; use crate::syntax::{ - Atom, Derive, Enum, ExternFn, ExternType, Impl, Receiver, Ref, Signature, Slice, Struct, Ty1, - Type, TypeAlias, Var, + Atom, Derive, Enum, ExternFn, ExternType, Impl, Pair, Receiver, Ref, ResolvableName, Signature, + Slice, Struct, Ty1, Type, TypeAlias, Var, }; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote_spanned, ToTokens}; @@ -11,11 +11,11 @@ impl ToTokens for Type { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Type::Ident(ident) => { - if ident == CxxString { - let span = ident.span(); + if ident.rust == CxxString { + let span = ident.rust.span(); tokens.extend(quote_spanned!(span=> ::cxx::)); } - ident.to_tokens(tokens); + ident.rust.to_tokens(tokens); } Type::RustBox(ty) | Type::UniquePtr(ty) | Type::CxxVector(ty) | Type::RustVec(ty) => { ty.to_tokens(tokens) @@ -39,7 +39,7 @@ impl ToTokens for Var { impl ToTokens for Ty1 { fn to_tokens(&self, tokens: &mut TokenStream) { let span = self.name.span(); - let name = self.name.to_string(); + let name = self.name.rust.to_string(); if let "UniquePtr" | "CxxVector" = name.as_str() { tokens.extend(quote_spanned!(span=> ::cxx::)); } else if name == "Vec" { @@ -121,6 +121,12 @@ impl ToTokens for ExternFn { } } +impl ToTokens for Pair { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.rust.to_tokens(tokens); + } +} + impl ToTokens for Impl { fn to_tokens(&self, tokens: &mut TokenStream) { self.impl_token.to_tokens(tokens); @@ -149,6 +155,12 @@ impl ToTokens for Signature { } } +impl ToTokens for ResolvableName { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.rust.to_tokens(tokens); + } +} + pub struct ReceiverType<'a>(&'a Receiver); impl Receiver { diff --git a/syntax/types.rs b/syntax/types.rs index 5bac76e42..178da3edc 100644 --- a/syntax/types.rs +++ b/syntax/types.rs @@ -1,7 +1,10 @@ use crate::syntax::atom::Atom::{self, *}; use crate::syntax::report::Errors; use crate::syntax::set::OrderedSet as Set; -use crate::syntax::{Api, Derive, Enum, ExternFn, ExternType, Impl, Struct, Type, TypeAlias}; +use crate::syntax::{ + Api, CppName, Derive, Enum, ExternFn, ExternType, Impl, Pair, ResolvableName, Struct, Type, + TypeAlias, +}; use proc_macro2::Ident; use quote::ToTokens; use std::collections::{BTreeMap as Map, HashSet as UnorderedSet}; @@ -16,6 +19,7 @@ pub struct Types<'a> { pub untrusted: Map<&'a Ident, &'a ExternType>, pub required_trivial: Map<&'a Ident, TrivialReason<'a>>, pub explicit_impls: Set<&'a Impl>, + pub resolutions: Map<&'a Ident, &'a CppName>, } impl<'a> Types<'a> { @@ -28,6 +32,7 @@ impl<'a> Types<'a> { let mut aliases = Map::new(); let mut untrusted = Map::new(); let mut explicit_impls = Set::new(); + let mut resolutions = Map::new(); fn visit<'a>(all: &mut Set<&'a Type>, ty: &'a Type) { all.insert(ty); @@ -50,6 +55,10 @@ impl<'a> Types<'a> { } } + let mut add_resolution = |pair: &'a Pair| { + resolutions.insert(&pair.rust, &pair.cxx); + }; + let mut type_names = UnorderedSet::new(); let mut function_names = UnorderedSet::new(); for api in apis { @@ -62,7 +71,7 @@ impl<'a> Types<'a> { match api { Api::Include(_) => {} Api::Struct(strct) => { - let ident = &strct.ident; + let ident = &strct.ident.rust; if !type_names.insert(ident) && (!cxx.contains(ident) || structs.contains_key(ident) @@ -73,13 +82,14 @@ impl<'a> Types<'a> { // type, then error. duplicate_name(cx, strct, ident); } - structs.insert(ident, strct); + structs.insert(&strct.ident.rust, strct); for field in &strct.fields { visit(&mut all, &field.ty); } + add_resolution(&strct.ident); } Api::Enum(enm) => { - let ident = &enm.ident; + let ident = &enm.ident.rust; if !type_names.insert(ident) && (!cxx.contains(ident) || structs.contains_key(ident) @@ -91,9 +101,10 @@ impl<'a> Types<'a> { duplicate_name(cx, enm, ident); } enums.insert(ident, enm); + add_resolution(&enm.ident); } Api::CxxType(ety) => { - let ident = &ety.ident; + let ident = &ety.ident.rust; if !type_names.insert(ident) && (cxx.contains(ident) || !structs.contains_key(ident) && !enums.contains_key(ident)) @@ -107,13 +118,15 @@ impl<'a> Types<'a> { if !ety.trusted { untrusted.insert(ident, ety); } + add_resolution(&ety.ident); } Api::RustType(ety) => { - let ident = &ety.ident; + let ident = &ety.ident.rust; if !type_names.insert(ident) { duplicate_name(cx, ety, ident); } rust.insert(ident); + add_resolution(&ety.ident); } Api::CxxFunction(efn) | Api::RustFunction(efn) => { // Note: duplication of the C++ name is fine because C++ has @@ -130,11 +143,12 @@ impl<'a> Types<'a> { } Api::TypeAlias(alias) => { let ident = &alias.ident; - if !type_names.insert(ident) { - duplicate_name(cx, alias, ident); + if !type_names.insert(&ident.rust) { + duplicate_name(cx, alias, &ident.rust); } - cxx.insert(ident); - aliases.insert(ident, alias); + cxx.insert(&ident.rust); + aliases.insert(&ident.rust, alias); + add_resolution(&alias.ident); } Api::Impl(imp) => { visit(&mut all, &imp.ty); @@ -150,8 +164,8 @@ impl<'a> Types<'a> { let mut required_trivial = Map::new(); let mut insist_alias_types_are_trivial = |ty: &'a Type, reason| { if let Type::Ident(ident) = ty { - if cxx.contains(ident) { - required_trivial.entry(ident).or_insert(reason); + if cxx.contains(&ident.rust) { + required_trivial.entry(&ident.rust).or_insert(reason); } } }; @@ -187,16 +201,17 @@ impl<'a> Types<'a> { untrusted, required_trivial, explicit_impls, + resolutions, } } pub fn needs_indirect_abi(&self, ty: &Type) -> bool { match ty { Type::Ident(ident) => { - if let Some(strct) = self.structs.get(ident) { + if let Some(strct) = self.structs.get(&ident.rust) { !self.is_pod(strct) } else { - Atom::from(ident) == Some(RustString) + Atom::from(&ident.rust) == Some(RustString) } } Type::RustVec(_) => true, @@ -212,6 +227,12 @@ impl<'a> Types<'a> { } false } + + pub fn resolve(&self, ident: &ResolvableName) -> &CppName { + self.resolutions + .get(&ident.rust) + .expect("Unable to resolve type") + } } impl<'t, 'a> IntoIterator for &'t Types<'a> { diff --git a/tests/ui/by_value_not_supported.stderr b/tests/ui/by_value_not_supported.stderr index 0a56dd48f..a860f3ddb 100644 --- a/tests/ui/by_value_not_supported.stderr +++ b/tests/ui/by_value_not_supported.stderr @@ -16,7 +16,7 @@ error: using C++ string by value is not supported 6 | s: CxxString, | ^^^^^^^^^^^^ -error: needs a cxx::ExternType impl in order to be used as a field of `S` +error: needs a cxx::ExternType impl in order to be used as a field of `::S` --> $DIR/by_value_not_supported.rs:10:9 | 10 | type C;