Merge pull request 370 from adetaylor/allow-namespace-override
diff --git a/syntax/atom.rs b/syntax/atom.rs
index 6e5fa88..7d0ef6b 100644
--- a/syntax/atom.rs
+++ b/syntax/atom.rs
@@ -81,7 +81,7 @@
 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,
         }
     }
diff --git a/syntax/attrs.rs b/syntax/attrs.rs
index 4c8a3e5..25af229 100644
--- a/syntax/attrs.rs
+++ b/syntax/attrs.rs
@@ -1,3 +1,4 @@
+use crate::syntax::namespace::Namespace;
 use crate::syntax::report::Errors;
 use crate::syntax::Atom::{self, *};
 use crate::syntax::{Derive, Doc};
@@ -12,19 +13,7 @@
     pub 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 @@
                 }
                 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 @@
         input.parse()
     }
 }
+
+fn parse_namespace_attribute(input: ParseStream) -> Result<Namespace> {
+    let content;
+    syn::parenthesized!(content in input);
+    let namespace = content.parse::<Namespace>()?;
+    Ok(namespace)
+}
diff --git a/syntax/check.rs b/syntax/check.rs
index 25183c9..08e0dfa 100644
--- a/syntax/check.rs
+++ b/syntax/check.rs
@@ -1,5 +1,4 @@
 use crate::syntax::atom::Atom::{self, *};
-use crate::syntax::namespace::Namespace;
 use crate::syntax::report::Errors;
 use crate::syntax::types::TrivialReason;
 use crate::syntax::{
@@ -11,15 +10,13 @@
 use 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 @@
 }
 
 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),
@@ -74,14 +71,14 @@
 
 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;
         }
     }
@@ -91,15 +88,15 @@
 
 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,
@@ -113,11 +110,11 @@
 
 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,
             _ => {}
         }
@@ -130,14 +127,14 @@
 
 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,
@@ -171,15 +168,15 @@
 
 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);
         }
@@ -201,7 +198,7 @@
 }
 
 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);
@@ -210,11 +207,13 @@
 }
 
 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),
         };
@@ -230,7 +229,7 @@
     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 => "",
@@ -242,9 +241,9 @@
                 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");
         }
@@ -291,7 +290,7 @@
 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;
             }
         }
@@ -358,7 +357,7 @@
 
 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,
     };
@@ -401,20 +400,20 @@
 fn describe(cx: &mut Check, ty: &Type) -> String {
     match ty {
         Type::Ident(ident) => {
-            if cx.types.structs.contains_key(ident) {
+            if cx.types.structs.contains_key(&ident.rust) {
                 "struct".to_owned()
-            } else if cx.types.enums.contains_key(ident) {
+            } else if cx.types.enums.contains_key(&ident.rust) {
                 "enum".to_owned()
-            } else if cx.types.aliases.contains_key(ident) {
+            } else if cx.types.aliases.contains_key(&ident.rust) {
                 "C++ type".to_owned()
-            } else if cx.types.cxx.contains(ident) {
+            } else if cx.types.cxx.contains(&ident.rust) {
                 "opaque C++ type".to_owned()
-            } else if cx.types.rust.contains(ident) {
+            } else if cx.types.rust.contains(&ident.rust) {
                 "opaque Rust type".to_owned()
-            } else if Atom::from(ident) == Some(CxxString) {
+            } else if Atom::from(&ident.rust) == Some(CxxString) {
                 "C++ string".to_owned()
             } else {
-                ident.to_string()
+                ident.rust.to_string()
             }
         }
         Type::RustBox(_) => "Box".to_owned(),
diff --git a/syntax/ident.rs b/syntax/ident.rs
index 66f7365..354790a 100644
--- a/syntax/ident.rs
+++ b/syntax/ident.rs
@@ -1,6 +1,5 @@
 use crate::syntax::check::Check;
-use crate::syntax::namespace::Namespace;
-use crate::syntax::{error, Api};
+use crate::syntax::{error, Api, CppName};
 use proc_macro2::Ident;
 
 fn check(cx: &mut Check, ident: &Ident) {
@@ -13,28 +12,31 @@
     }
 }
 
-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 @@
                 }
             }
             Api::TypeAlias(alias) => {
-                check(cx, &alias.ident);
+                check_ident(cx, &alias.ident.cxx);
             }
         }
     }
diff --git a/syntax/impls.rs b/syntax/impls.rs
index a4b393a..424ad9d 100644
--- a/syntax/impls.rs
+++ b/syntax/impls.rs
@@ -1,8 +1,13 @@
-use crate::syntax::{ExternFn, Impl, Include, Receiver, Ref, Signature, Slice, Ty1, Type};
+use crate::syntax::{
+    Api, CppName, ExternFn, Impl, Include, 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 PartialEq for Include {
     fn eq(&self, other: &Include) -> bool {
@@ -292,3 +297,84 @@
         &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("::"))
+    }
+}
diff --git a/syntax/mangle.rs b/syntax/mangle.rs
index e461887..9255feb 100644
--- a/syntax/mangle.rs
+++ b/syntax/mangle.rs
@@ -1,6 +1,5 @@
-use crate::syntax::namespace::Namespace;
 use crate::syntax::symbol::{self, Symbol};
-use crate::syntax::ExternFn;
+use crate::syntax::{ExternFn, Types};
 use proc_macro2::Ident;
 
 const CXXBRIDGE: &str = "cxxbridge05";
@@ -11,19 +10,27 @@
     };
 }
 
-pub fn extern_fn(namespace: &Namespace, efn: &ExternFn) -> Symbol {
+pub fn extern_fn(efn: &ExternFn, types: &Types) -> Symbol {
     match &efn.receiver {
-        Some(receiver) => join!(namespace, CXXBRIDGE, receiver.ty, efn.ident.rust),
-        None => join!(namespace, CXXBRIDGE, efn.ident.rust),
+        Some(receiver) => {
+            let receiver_ident = types.resolve(&receiver.ty);
+            join!(
+                efn.ident.cxx.ns,
+                CXXBRIDGE,
+                receiver_ident.ident,
+                efn.ident.rust
+            )
+        }
+        None => join!(efn.ident.cxx.ns, CXXBRIDGE, efn.ident.rust),
     }
 }
 
 // The C half of a function pointer trampoline.
-pub fn c_trampoline(namespace: &Namespace, efn: &ExternFn, var: &Ident) -> Symbol {
-    join!(extern_fn(namespace, efn), var, 0)
+pub fn c_trampoline(efn: &ExternFn, var: &Ident, types: &Types) -> Symbol {
+    join!(extern_fn(efn, types), var, 0)
 }
 
 // The Rust half of a function pointer trampoline.
-pub fn r_trampoline(namespace: &Namespace, efn: &ExternFn, var: &Ident) -> Symbol {
-    join!(extern_fn(namespace, efn), var, 1)
+pub fn r_trampoline(efn: &ExternFn, var: &Ident, types: &Types) -> Symbol {
+    join!(extern_fn(efn, types), var, 1)
 }
diff --git a/syntax/mod.rs b/syntax/mod.rs
index 180c40a..6498d74 100644
--- a/syntax/mod.rs
+++ b/syntax/mod.rs
@@ -21,7 +21,9 @@
 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::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(Include),
     Struct(Struct),
@@ -64,7 +89,7 @@
 pub struct ExternType {
     pub doc: Doc,
     pub type_token: Token![type],
-    pub ident: Ident,
+    pub ident: Pair,
     pub semi_token: Token![;],
     pub trusted: bool,
 }
@@ -73,7 +98,7 @@
     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>,
 }
@@ -81,15 +106,18 @@
 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 {
@@ -103,7 +131,7 @@
 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![;],
@@ -128,7 +156,7 @@
 
 #[derive(Eq, PartialEq, Hash)]
 pub struct Var {
-    pub ident: Ident,
+    pub ident: RsIdent, // fields and variables are not namespaced
     pub ty: Type,
 }
 
@@ -137,18 +165,18 @@
     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>),
@@ -162,7 +190,7 @@
 }
 
 pub struct Ty1 {
-    pub name: Ident,
+    pub name: ResolvableName,
     pub langle: Token![<],
     pub inner: Type,
     pub rangle: Token![>],
@@ -185,3 +213,10 @@
     Cxx,
     Rust,
 }
+
+/// Wrapper for a type which needs to be resolved
+/// before it can be printed in C++.
+#[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
+pub struct ResolvableName {
+    pub rust: RsName,
+}
diff --git a/syntax/parse.rs b/syntax/parse.rs
index 3f579a1..7a56ab8 100644
--- a/syntax/parse.rs
+++ b/syntax/parse.rs
@@ -3,8 +3,9 @@
 use crate::syntax::report::Errors;
 use crate::syntax::Atom::*;
 use crate::syntax::{
-    attrs, error, Api, Doc, Enum, ExternFn, ExternType, Impl, Include, IncludeKind, Lang, Pair,
-    Receiver, Ref, Signature, Slice, Struct, Ty1, Type, TypeAlias, Var, Variant,
+    attrs, error, Api, CppName, Doc, Enum, ExternFn, ExternType, Impl, Include, IncludeKind, 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 +21,22 @@
     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 +47,7 @@
     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 +68,7 @@
         attrs::Parser {
             doc: Some(&mut doc),
             derives: Some(&mut derives),
+            namespace: Some(&mut ns),
             ..Default::default()
         },
     );
@@ -81,7 +85,7 @@
         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 +93,14 @@
             .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 +121,7 @@
         attrs::Parser {
             doc: Some(&mut doc),
             repr: Some(&mut repr),
+            namespace: Some(&mut ns),
             ..Default::default()
         },
     );
@@ -167,7 +172,7 @@
     Ok(Api::Enum(Enum {
         doc,
         enum_token,
-        ident: item.ident,
+        ident: Pair::new(ns, item.ident),
         brace_token,
         variants,
         repr,
@@ -179,6 +184,7 @@
     foreign_mod: ItemForeignMod,
     out: &mut Vec<Api>,
     trusted: bool,
+    ns: &Namespace,
 ) {
     let lang = match parse_lang(&foreign_mod.abi) {
         Ok(lang) => lang,
@@ -202,11 +208,13 @@
     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 +224,12 @@
                     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 +244,8 @@
         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 +277,18 @@
     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 +299,18 @@
     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 +335,7 @@
             doc: Some(&mut doc),
             cxx_name: Some(&mut cxx_name),
             rust_name: Some(&mut rust_name),
+            namespace: Some(&mut ns),
             ..Default::default()
         },
     );
@@ -326,7 +352,7 @@
                         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 +367,7 @@
                     }
                     _ => 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 +381,7 @@
                             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 +394,12 @@
     }
 
     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 +427,12 @@
     }))
 }
 
-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 +447,21 @@
         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 +480,7 @@
     }
 }
 
-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 +506,7 @@
 
     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,
     }))
 }
@@ -515,21 +555,21 @@
     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 {
@@ -537,7 +577,7 @@
             }
         }
         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,
@@ -550,19 +590,20 @@
     })))
 }
 
-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,
@@ -570,9 +611,9 @@
                     }
                 } 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,
@@ -580,9 +621,9 @@
                     }
                 } 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,
@@ -590,9 +631,9 @@
                     }
                 } 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,
@@ -606,15 +647,15 @@
     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,
@@ -632,7 +673,7 @@
         .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),
@@ -641,7 +682,7 @@
         })
         .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,
@@ -658,6 +699,7 @@
 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),
@@ -679,7 +721,7 @@
             }
         }
     }
-    match parse_type(ret)? {
+    match parse_type(ret, ns)? {
         Type::Void(_) => Ok(None),
         ty => Ok(Some(ty)),
     }
diff --git a/syntax/qualified.rs b/syntax/qualified.rs
index be9bceb..5eefb8d 100644
--- a/syntax/qualified.rs
+++ b/syntax/qualified.rs
@@ -10,6 +10,7 @@
     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);
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);
diff --git a/syntax/tokens.rs b/syntax/tokens.rs
index 7618e99..57db8eb 100644
--- a/syntax/tokens.rs
+++ b/syntax/tokens.rs
@@ -1,7 +1,7 @@
 use crate::syntax::atom::Atom::*;
 use crate::syntax::{
-    Atom, Derive, Enum, ExternFn, ExternType, Impl, Receiver, Ref, Signature, Slice, Struct, Ty1,
-    Type, TypeAlias, Var,
+    Atom, Derive, Enum, ExternFn, ExternType, Impl, Pair, Receiver, Ref, ResolvableName, Signature,
+    Slice, Struct, Ty1, Type, TypeAlias, Var,
 };
 use proc_macro2::{Ident, Span, TokenStream};
 use quote::{quote_spanned, ToTokens};
@@ -11,11 +11,11 @@
     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 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 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 ResolvableName {
+    fn to_tokens(&self, tokens: &mut TokenStream) {
+        self.rust.to_tokens(tokens);
+    }
+}
+
 pub struct ReceiverType<'a>(&'a Receiver);
 
 impl Receiver {
diff --git a/syntax/types.rs b/syntax/types.rs
index 5bac76e..178da3e 100644
--- a/syntax/types.rs
+++ b/syntax/types.rs
@@ -1,7 +1,10 @@
 use crate::syntax::atom::Atom::{self, *};
 use crate::syntax::report::Errors;
 use crate::syntax::set::OrderedSet as Set;
-use crate::syntax::{Api, Derive, Enum, ExternFn, ExternType, Impl, Struct, Type, TypeAlias};
+use crate::syntax::{
+    Api, CppName, Derive, Enum, ExternFn, ExternType, Impl, Pair, ResolvableName, Struct, Type,
+    TypeAlias,
+};
 use proc_macro2::Ident;
 use quote::ToTokens;
 use std::collections::{BTreeMap as Map, HashSet as UnorderedSet};
@@ -16,6 +19,7 @@
     pub 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 @@
         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 @@
             }
         }
 
+        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 @@
             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 @@
                         // 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 @@
                         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 @@
                     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 @@
                 }
                 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 @@
         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 @@
             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 @@
         }
         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> {