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.
diff --git a/syntax/symbol.rs b/syntax/symbol.rs
index 1e5b513..0b79d5f 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 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 @@
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 str {}
-impl Segment for usize {}
-impl Segment for Ident {}
-impl Segment for Symbol {}
+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 Namespace {
fn write(&self, symbol: &mut Symbol) {
@@ -55,9 +79,16 @@
}
}
+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);