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.
This commit is contained in:
Adrian Taylor 2020-10-21 18:20:55 -07:00
parent 0fac321939
commit c871343ac2
18 changed files with 758 additions and 449 deletions

View File

@ -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<GeneratedCode> {
.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()
},

View File

@ -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::<Vec<_>>();
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
}

View File

@ -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(),

View File

@ -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);
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);
}
if !header {
out.next_section();
write_generic_instantiations(out, types);
}
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<String>) {
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<Type>) {
fn write_return_type(out: &mut OutFile, ty: &Option<Type>, 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<uint8_t>::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<Type>, 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<uint8_t>::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<uint8_t>::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);

View File

@ -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<TokenStream> {
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<TokenStream> {
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<T> 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<T: ?#sized + #sized>() {}
__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) => {

View File

@ -81,7 +81,7 @@ impl AsRef<str> for Atom {
impl PartialEq<Atom> for Type {
fn eq(&self, atom: &Atom) -> bool {
match self {
Type::Ident(ident) => ident == atom,
Type::Ident(ident) => ident.rust == atom,
_ => false,
}
}

View File

@ -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<Atom>>,
pub cxx_name: Option<&'a mut Option<Ident>>,
pub rust_name: Option<&'a mut Option<Ident>>,
}
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<Ident> {
input.parse()
}
}
fn parse_namespace_attribute(input: ParseStream) -> Result<Namespace> {
let content;
syn::parenthesized!(content in input);
let namespace = content.parse::<Namespace>()?;
Ok(namespace)
}

View File

@ -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(),

View File

@ -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);
}
}
}

View File

@ -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<Type> 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::slice::Iter<Ident>, 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::<Vec<_>>()
.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("::"))
}
}

View File

@ -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)
}

View File

@ -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<Derive>,
pub struct_token: Token![struct],
pub ident: Ident,
pub ident: Pair,
pub brace_token: Brace,
pub fields: Vec<Var>,
}
@ -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<Variant>,
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<Lifetime>,
pub mutability: Option<Token![mut]>,
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<Expr>,
}
pub enum Type {
Ident(Ident),
Ident(ResolvableName),
RustBox(Box<Ty1>),
RustVec(Box<Ty1>),
UniquePtr(Box<Ty1>),
@ -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,
}

View File

@ -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<Item>, trusted: bool) -> Vec<Api> {
pub fn parse_items(cx: &mut Errors, items: Vec<Item>, trusted: bool, ns: &Namespace) -> Vec<Api> {
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<Item>, trusted: bool) -> Vec<Api>
apis
}
fn parse_struct(cx: &mut Errors, item: ItemStruct) -> Result<Api> {
fn parse_struct(cx: &mut Errors, item: ItemStruct, mut ns: Namespace) -> Result<Api> {
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<Api> {
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<Api> {
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<Api> {
.map(|field| {
Ok(Var {
ident: field.ident.unwrap(),
ty: parse_type(&field.ty)?,
ty: parse_type(&field.ty, &ns)?,
})
})
.collect::<Result<_>>()?,
}))
}
fn parse_enum(cx: &mut Errors, item: ItemEnum) -> Result<Api> {
fn parse_enum(cx: &mut Errors, item: ItemEnum, mut ns: Namespace) -> Result<Api> {
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<Api> {
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<Api> {
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<Api>,
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<Api> {
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<Api> {
fn parse_extern_fn(
cx: &mut Errors,
foreign_fn: &ForeignItemFn,
lang: Lang,
mut ns: Namespace,
) -> Result<Api> {
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<Api> {
fn parse_extern_verbatim(
cx: &mut Errors,
tokens: &TokenStream,
lang: Lang,
mut ns: Namespace,
) -> Result<Api> {
// type Alias = crate::path::to::Type;
let parse = |input: ParseStream| -> Result<TypeAlias> {
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<Api> {
fn parse_impl(imp: ItemImpl, ns: &Namespace) -> Result<Api> {
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<Api> {
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<String> {
Err(input.error("expected \"quoted/path/to\" or <bracketed/path/to>"))
}
fn parse_type(ty: &RustType) -> Result<Type> {
fn parse_type(ty: &RustType, ns: &Namespace) -> Result<Type> {
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<Type> {
let inner = parse_type(&ty.elem)?;
fn parse_type_reference(ty: &TypeReference, ns: &Namespace) -> Result<Type> {
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> {
}
}
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<Type> {
})))
}
fn parse_type_path(ty: &TypePath) -> Result<Type> {
fn parse_type_path(ty: &TypePath, ns: &Namespace) -> Result<Type> {
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<Type> {
}
} 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<Type> {
}
} 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<Type> {
}
} 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<Type> {
Err(Error::new_spanned(ty, "unsupported type"))
}
fn parse_type_slice(ty: &TypeSlice) -> Result<Type> {
let inner = parse_type(&ty.elem)?;
fn parse_type_slice(ty: &TypeSlice, ns: &Namespace) -> Result<Type> {
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<Type> {
fn parse_type_fn(ty: &TypeBareFn, ns: &Namespace) -> Result<Type> {
if ty.lifetimes.is_some() {
return Err(Error::new_spanned(
ty,
@ -620,7 +660,7 @@ fn parse_type_fn(ty: &TypeBareFn) -> Result<Type> {
.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<Type> {
})
.collect::<Result<_>>()?;
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<Type> {
fn parse_return_type(
ty: &ReturnType,
throws_tokens: &mut Option<(kw::Result, Token![<], Token![>])>,
ns: &Namespace,
) -> Result<Option<Type>> {
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)),
}

View File

@ -10,6 +10,7 @@ impl QualifiedName {
pub fn parse_unquoted(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
let mut trailing_punct = true;
input.parse::<Option<Token![::]>>()?;
while trailing_punct && input.peek(Ident::peek_any) {
let ident = Ident::parse_any(input)?;
segments.push(ident);

View File

@ -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<Item = &'a Ident>>(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: Display {
pub trait Segment {
fn write(&self, symbol: &mut Symbol);
}
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<T> Segment for &'_ T
where
T: ?Sized + Segment,
T: ?Sized + Segment + Display,
{
fn write(&self, symbol: &mut Symbol) {
(**self).write(symbol);

View File

@ -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 {

View File

@ -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> {

View File

@ -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;