Merge pull request 370 from adetaylor/allow-namespace-override
diff --git a/gen/src/mod.rs b/gen/src/mod.rs
index 236fece..e6e2c7c 100644
--- a/gen/src/mod.rs
+++ b/gen/src/mod.rs
@@ -6,6 +6,7 @@
 mod file;
 pub(super) mod fs;
 pub(super) mod include;
+mod namespace_organizer;
 pub(super) mod out;
 mod write;
 
@@ -113,23 +114,23 @@
         .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);
     check::precheck(errors, apis, opt);
     errors.propagate()?;
-    check::typecheck(errors, namespace, apis, types);
+    check::typecheck(errors, apis, types);
     errors.propagate()?;
     // Some callers may wish to generate both header and C++
     // from the same token stream to avoid parsing twice. But others
     // only need to generate one or the other.
     Ok(GeneratedCode {
         header: if opt.gen_header {
-            write::gen(namespace, apis, types, opt, true).content()
+            write::gen(apis, types, opt, true).content()
         } else {
             Vec::new()
         },
         implementation: if opt.gen_implementation {
-            write::gen(namespace, apis, types, opt, false).content()
+            write::gen(apis, types, opt, false).content()
         } else {
             Vec::new()
         },
diff --git a/gen/src/namespace_organizer.rs b/gen/src/namespace_organizer.rs
new file mode 100644
index 0000000..c54e784
--- /dev/null
+++ b/gen/src/namespace_organizer.rs
@@ -0,0 +1,40 @@
+use crate::syntax::Api;
+use proc_macro2::Ident;
+use std::collections::BTreeMap;
+
+pub(crate) struct NamespaceEntries<'a> {
+    pub(crate) entries: Vec<&'a Api>,
+    pub(crate) children: BTreeMap<&'a Ident, NamespaceEntries<'a>>,
+}
+
+pub(crate) fn sort_by_namespace(apis: &[Api]) -> NamespaceEntries {
+    let api_refs = apis.iter().collect::<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
+}
diff --git a/gen/src/out.rs b/gen/src/out.rs
index d42ea74..8a6bd86 100644
--- a/gen/src/out.rs
+++ b/gen/src/out.rs
@@ -1,10 +1,8 @@
 use crate::gen::include::Includes;
-use crate::syntax::namespace::Namespace;
 use std::cell::RefCell;
 use std::fmt::{self, Arguments, Write};
 
 pub(crate) struct OutFile {
-    pub namespace: Namespace,
     pub header: bool,
     pub include: Includes,
     pub front: Content,
@@ -18,9 +16,8 @@
 }
 
 impl OutFile {
-    pub fn new(namespace: Namespace, header: bool) -> Self {
+    pub fn new(header: bool) -> Self {
         OutFile {
-            namespace,
             header,
             include: Includes::new(),
             front: Content::new(),
diff --git a/gen/src/write.rs b/gen/src/write.rs
index 01617ca..967d4ff 100644
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -1,20 +1,17 @@
+use crate::gen::namespace_organizer::{sort_by_namespace, NamespaceEntries};
 use crate::gen::out::OutFile;
 use crate::gen::{include, Opt};
 use crate::syntax::atom::Atom::{self, *};
-use crate::syntax::namespace::Namespace;
 use crate::syntax::symbol::Symbol;
-use crate::syntax::{mangle, Api, Enum, ExternFn, ExternType, Signature, Struct, Type, Types, Var};
+use crate::syntax::{
+    mangle, Api, CppName, Enum, ExternFn, ExternType, ResolvableName, Signature, Struct, Type,
+    Types, Var,
+};
 use proc_macro2::Ident;
 use std::collections::HashMap;
 
-pub(super) fn gen(
-    namespace: &Namespace,
-    apis: &[Api],
-    types: &Types,
-    opt: &Opt,
-    header: bool,
-) -> OutFile {
-    let mut out_file = OutFile::new(namespace.clone(), header);
+pub(super) fn gen(apis: &[Api], types: &Types, opt: &Opt, header: bool) -> OutFile {
+    let mut out_file = OutFile::new(header);
     let out = &mut out_file;
 
     if header {
@@ -32,16 +29,36 @@
     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 @@
         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 @@
         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 @@
     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 @@
     }
 
     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 @@
     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 @@
     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_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 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 @@
         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 @@
     // 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 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 @@
     } 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 @@
         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 @@
     }
     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 @@
     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 @@
             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 @@
                 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 @@
     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 @@
         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 @@
         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 @@
         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 @@
     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 @@
         // 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 @@
         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 @@
     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 @@
     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 @@
         .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_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 @@
     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 @@
         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 @@
                 if i > 0 {
                     write!(out, ", ");
                 }
-                write_type(out, &arg.ty);
+                write_type(out, &arg.ty, types);
             }
             write!(out, ")>");
         }
@@ -1003,8 +1056,8 @@
     }
 }
 
-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 @@
 
 // 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 @@
         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 @@
             }
         } 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 @@
     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 @@
     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 @@
     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 @@
     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 @@
     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 @@
     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_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 @@
         // 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 @@
     writeln!(out, "}}");
 }
 
-fn write_cxx_vector(out: &mut OutFile, vector_ty: &Type, element: &Ident, types: &Types) {
+fn write_cxx_vector(out: &mut OutFile, vector_ty: &Type, element: &ResolvableName, types: &Types) {
     let element = Type::Ident(element.clone());
-    let inner = to_typename(&out.namespace, &element);
-    let instance = to_mangled(&out.namespace, &element);
+    let inner = to_typename(&element, types);
+    let instance = to_mangled(&element, types);
 
     writeln!(out, "#ifndef CXXBRIDGE05_VECTOR_{}", instance);
     writeln!(out, "#define CXXBRIDGE05_VECTOR_{}", instance);
diff --git a/macro/src/expand.rs b/macro/src/expand.rs
index 4a4ec64..1bcaa1e 100644
--- a/macro/src/expand.rs
+++ b/macro/src/expand.rs
@@ -1,12 +1,11 @@
 use crate::derive::DeriveAttribute;
 use crate::syntax::atom::Atom::{self, *};
 use crate::syntax::file::Module;
-use crate::syntax::namespace::Namespace;
 use crate::syntax::report::Errors;
 use crate::syntax::symbol::Symbol;
 use crate::syntax::{
-    self, check, mangle, Api, Enum, ExternFn, ExternType, Impl, Signature, Struct, Type, TypeAlias,
-    Types,
+    self, check, mangle, Api, CppName, Enum, ExternFn, ExternType, Impl, ResolvableName, Signature,
+    Struct, Type, TypeAlias, Types,
 };
 use proc_macro2::{Ident, Span, TokenStream};
 use quote::{format_ident, quote, quote_spanned, ToTokens};
@@ -17,11 +16,11 @@
     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 @@
 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 @@
     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));
+                expanded.extend(expand_cxx_function_shim(efn, types));
             }
-            Api::RustFunction(efn) => {
-                hidden.extend(expand_rust_function_shim(namespace, 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 @@
         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_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_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_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_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 @@
         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_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 @@
     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 @@
         .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 @@
     };
     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 @@
             }
             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 @@
         })
     } 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 @@
             }
             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_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 @@
     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_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 @@
     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 @@
             }
             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 @@
     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 @@
         }
         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_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 @@
         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 @@
     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_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_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 @@
     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_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 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 @@
         Type::Ref(ty) => {
             let mutability = ty.mutability;
             match &ty.inner {
-                Type::Ident(ident) if ident == RustString => {
+                Type::Ident(ident) if ident.rust == RustString => {
                     quote!(&#mutability ::cxx::private::RustString)
                 }
                 Type::RustVec(ty) => {
diff --git a/syntax/atom.rs b/syntax/atom.rs
index 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> {
diff --git a/tests/BUCK b/tests/BUCK
index 5bbe500..f51be09 100644
--- a/tests/BUCK
+++ b/tests/BUCK
@@ -15,6 +15,7 @@
         "ffi/extra.rs",
         "ffi/lib.rs",
         "ffi/module.rs",
+        "ffi/class_in_ns.rs",
     ],
     crate = "cxx_test_suite",
     deps = [
@@ -30,6 +31,7 @@
         ":bridge/source",
         ":extra/source",
         ":module/source",
+        ":class_in_ns/source",
     ],
     headers = {
         "ffi/lib.rs.h": ":bridge/header",
@@ -52,3 +54,8 @@
     name = "module",
     src = "ffi/module.rs",
 )
+
+rust_cxx_bridge(
+    name = "class_in_ns",
+    src = "ffi/class_in_ns.rs",
+)
diff --git a/tests/BUILD b/tests/BUILD
index 57ffab9..a400f47 100644
--- a/tests/BUILD
+++ b/tests/BUILD
@@ -18,6 +18,7 @@
         "ffi/extra.rs",
         "ffi/lib.rs",
         "ffi/module.rs",
+        "ffi/class_in_ns.rs",
     ],
     deps = [
         ":impl",
@@ -32,6 +33,7 @@
         ":bridge/source",
         ":extra/source",
         ":module/source",
+        ":class_in_ns/source",
     ],
     hdrs = ["ffi/tests.h"],
     deps = [
@@ -57,3 +59,9 @@
     src = "ffi/module.rs",
     deps = [":impl"],
 )
+
+rust_cxx_bridge(
+    name = "class_in_ns",
+    src = "ffi/class_in_ns.rs",
+    deps = [":impl"],
+)
\ No newline at end of file
diff --git a/tests/ffi/build.rs b/tests/ffi/build.rs
index 4b2cbdf..9bdb711 100644
--- a/tests/ffi/build.rs
+++ b/tests/ffi/build.rs
@@ -6,7 +6,7 @@
     }
 
     CFG.include_prefix = "tests/ffi";
-    let sources = vec!["lib.rs", "extra.rs", "module.rs"];
+    let sources = vec!["lib.rs", "extra.rs", "module.rs", "class_in_ns.rs"];
     cxx_build::bridges(sources)
         .file("tests.cc")
         .flag_if_supported(cxxbridge_flags::STD)
diff --git a/tests/ffi/class_in_ns.rs b/tests/ffi/class_in_ns.rs
new file mode 100644
index 0000000..8b50561
--- /dev/null
+++ b/tests/ffi/class_in_ns.rs
@@ -0,0 +1,21 @@
+// To test receivers on a type in a namespace outide
+// the default. cxx::bridge blocks can only have a single
+// receiver type, and there can only be one such block per,
+// which is why this is outside.
+
+#[rustfmt::skip]
+#[cxx::bridge(namespace = tests)]
+pub mod ffi3 {
+
+    extern "C" {
+        include!("tests/ffi/tests.h");
+
+        #[namespace (namespace = I)]
+        type I;
+
+        fn get(self: &I) -> u32;
+
+        #[namespace (namespace = I)]
+        fn ns_c_return_unique_ptr_ns() -> UniquePtr<I>;
+    }
+}
diff --git a/tests/ffi/extra.rs b/tests/ffi/extra.rs
index a809ea4..633cf93 100644
--- a/tests/ffi/extra.rs
+++ b/tests/ffi/extra.rs
@@ -12,20 +12,44 @@
 pub mod ffi2 {
     impl UniquePtr<D> {}
     impl UniquePtr<E> {}
+    impl UniquePtr<F> {}
+    impl UniquePtr<G> {}
 
     extern "C" {
         include!("tests/ffi/tests.h");
 
         type D = crate::other::D;
         type E = crate::other::E;
+        #[namespace (namespace = F)]
+        type F = crate::other::f::F;
+        #[namespace (namespace = G)]
+        type G = crate::other::G;
+
+        #[namespace(namespace = H)]
+        type H;
 
         fn c_take_trivial_ptr(d: UniquePtr<D>);
         fn c_take_trivial_ref(d: &D);
         fn c_take_trivial(d: D);
+        fn c_take_trivial_ns_ptr(g: UniquePtr<G>);
+        fn c_take_trivial_ns_ref(g: &G);
+        fn c_take_trivial_ns(g: G);
         fn c_take_opaque_ptr(e: UniquePtr<E>);
         fn c_take_opaque_ref(e: &E);
+        fn c_take_opaque_ns_ptr(e: UniquePtr<F>);
+        fn c_take_opaque_ns_ref(e: &F);
         fn c_return_trivial_ptr() -> UniquePtr<D>;
         fn c_return_trivial() -> D;
+        fn c_return_trivial_ns_ptr() -> UniquePtr<G>;
+        fn c_return_trivial_ns() -> G;
         fn c_return_opaque_ptr() -> UniquePtr<E>;
+        fn c_return_ns_opaque_ptr() -> UniquePtr<F>;  
+        fn c_return_ns_unique_ptr() -> UniquePtr<H>;
+        fn c_take_ref_ns_c(h: &H);
+
+        #[namespace (namespace = other)]
+        fn ns_c_take_trivial(d: D);
+        #[namespace (namespace = other)]
+        fn ns_c_return_trivial() -> D;
     }
 }
diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs
index 4078b37..be145f3 100644
--- a/tests/ffi/lib.rs
+++ b/tests/ffi/lib.rs
@@ -4,6 +4,7 @@
     clippy::trivially_copy_pass_by_ref
 )]
 
+pub mod class_in_ns;
 pub mod extra;
 pub mod module;
 
@@ -25,6 +26,32 @@
         e_str: CxxString,
     }
 
+    pub mod f {
+        use cxx::kind::Opaque;
+        use cxx::{type_id, CxxString, ExternType};
+
+        #[repr(C)]
+        pub struct F {
+            e: u64,
+            e_str: CxxString,
+        }
+
+        unsafe impl ExternType for F {
+            type Id = type_id!("F::F");
+            type Kind = Opaque;
+        }
+    }
+
+    #[repr(C)]
+    pub struct G {
+        pub g: u64,
+    }
+
+    unsafe impl ExternType for G {
+        type Id = type_id!("G::G");
+        type Kind = Trivial;
+    }
+
     unsafe impl ExternType for D {
         type Id = type_id!("tests::D");
         type Kind = Trivial;
@@ -49,6 +76,32 @@
         CVal,
     }
 
+    #[namespace(namespace = A)]
+    #[derive(Clone)]
+    struct AShared {
+        z: usize,
+    }
+
+    #[namespace(namespace = A)]
+    enum AEnum {
+        AAVal,
+        ABVal = 2020,
+        ACVal,
+    }
+
+    #[namespace(namespace = A::B)]
+    enum ABEnum {
+        ABAVal,
+        ABBVal = 2020,
+        ABCVal,
+    }
+
+    #[namespace(namespace = A::B)]
+    #[derive(Clone)]
+    struct ABShared {
+        z: usize,
+    }
+
     extern "C" {
         include!("tests/ffi/tests.h");
 
@@ -78,6 +131,10 @@
         fn c_return_identity(_: usize) -> usize;
         fn c_return_sum(_: usize, _: usize) -> usize;
         fn c_return_enum(n: u16) -> Enum;
+        fn c_return_ns_ref(shared: &AShared) -> &usize;
+        fn c_return_nested_ns_ref(shared: &ABShared) -> &usize;
+        fn c_return_ns_enum(n: u16) -> AEnum;
+        fn c_return_nested_ns_enum(n: u16) -> ABEnum;
 
         fn c_take_primitive(n: usize);
         fn c_take_shared(shared: Shared);
@@ -108,6 +165,12 @@
         fn c_take_callback(callback: fn(String) -> usize);
         */
         fn c_take_enum(e: Enum);
+        fn c_take_ns_enum(e: AEnum);
+        fn c_take_nested_ns_enum(e: ABEnum);
+        fn c_take_ns_shared(shared: AShared);
+        fn c_take_nested_ns_shared(shared: ABShared);
+        fn c_take_rust_vec_ns_shared(v: Vec<AShared>);
+        fn c_take_rust_vec_nested_ns_shared(v: Vec<ABShared>);
 
         fn c_try_return_void() -> Result<()>;
         fn c_try_return_primitive() -> Result<usize>;
@@ -137,6 +200,9 @@
         fn cOverloadedFunction(x: i32) -> String;
         #[rust_name = "str_overloaded_function"]
         fn cOverloadedFunction(x: &str) -> String;
+
+        #[namespace (namespace = other)]
+        fn ns_c_take_ns_shared(shared: AShared);
     }
 
     extern "C" {
diff --git a/tests/ffi/tests.cc b/tests/ffi/tests.cc
index 983cf95..05bf5fb 100644
--- a/tests/ffi/tests.cc
+++ b/tests/ffi/tests.cc
@@ -43,6 +43,10 @@
 
 Shared c_return_shared() { return Shared{2020}; }
 
+::A::AShared c_return_ns_shared() { return ::A::AShared{2020}; }
+
+::A::B::ABShared c_return_nested_ns_shared() { return ::A::B::ABShared{2020}; }
+
 rust::Box<R> c_return_box() {
   return rust::Box<R>::from_raw(cxx_test_suite_get_box());
 }
@@ -51,8 +55,16 @@
   return std::unique_ptr<C>(new C{2020});
 }
 
+std::unique_ptr<::H::H> c_return_ns_unique_ptr() {
+  return std::unique_ptr<::H::H>(new ::H::H{"hello"});
+}
+
 const size_t &c_return_ref(const Shared &shared) { return shared.z; }
 
+const size_t &c_return_ns_ref(const ::A::AShared &shared) { return shared.z; }
+
+const size_t &c_return_nested_ns_ref(const ::A::B::ABShared &shared) { return shared.z; }
+
 size_t &c_return_mut(Shared &shared) { return shared.z; }
 
 rust::Str c_return_str(const Shared &shared) {
@@ -144,6 +156,26 @@
   }
 }
 
+::A::AEnum c_return_ns_enum(uint16_t n) {
+  if (n <= static_cast<uint16_t>(::A::AEnum::AAVal)) {
+    return ::A::AEnum::AAVal;
+  } else if (n <= static_cast<uint16_t>(::A::AEnum::ABVal)) {
+    return ::A::AEnum::ABVal;
+  } else {
+    return ::A::AEnum::ACVal;
+  }
+}
+
+::A::B::ABEnum c_return_nested_ns_enum(uint16_t n) {
+  if (n <= static_cast<uint16_t>(::A::B::ABEnum::ABAVal)) {
+    return ::A::B::ABEnum::ABAVal;
+  } else if (n <= static_cast<uint16_t>(::A::B::ABEnum::ABBVal)) {
+    return ::A::B::ABEnum::ABBVal;
+  } else {
+    return ::A::B::ABEnum::ABCVal;
+  }
+}
+
 void c_take_primitive(size_t n) {
   if (n == 2020) {
     cxx_test_suite_set_correct();
@@ -156,6 +188,18 @@
   }
 }
 
+void c_take_ns_shared(::A::AShared shared) {
+  if (shared.z == 2020) {
+    cxx_test_suite_set_correct();
+  }
+}
+
+void c_take_nested_ns_shared(::A::B::ABShared shared) {
+  if (shared.z == 2020) {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_take_box(rust::Box<R> r) {
   if (cxx_test_suite_r_is_correct(&*r)) {
     cxx_test_suite_set_correct();
@@ -180,6 +224,12 @@
   }
 }
 
+void c_take_ref_ns_c(const ::H::H &h) {
+  if (h.h == "hello") {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_take_str(rust::Str s) {
   if (std::string(s) == "2020") {
     cxx_test_suite_set_correct();
@@ -258,6 +308,26 @@
   }
 }
 
+void c_take_rust_vec_ns_shared(rust::Vec<::A::AShared> v) {
+  uint32_t sum = 0;
+  for (auto i : v) {
+    sum += i.z;
+  }
+  if (sum == 2021) {
+    cxx_test_suite_set_correct();
+  }
+}
+
+void c_take_rust_vec_nested_ns_shared(rust::Vec<::A::B::ABShared> v) {
+  uint32_t sum = 0;
+  for (auto i : v) {
+    sum += i.z;
+  }
+  if (sum == 2021) {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_take_rust_vec_string(rust::Vec<rust::String> v) {
   (void)v;
   cxx_test_suite_set_correct();
@@ -326,6 +396,18 @@
   }
 }
 
+void c_take_ns_enum(::A::AEnum e) {
+  if (e == ::A::AEnum::AAVal) {
+    cxx_test_suite_set_correct();
+  }
+}
+
+void c_take_nested_ns_enum(::A::B::ABEnum e) {
+  if (e == ::A::B::ABEnum::ABAVal) {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_try_return_void() {}
 
 size_t c_try_return_primitive() { return 2020; }
@@ -394,24 +476,56 @@
     cxx_test_suite_set_correct();
   }
 }
+
 void c_take_trivial(D d) {
   if (d.d == 30) {
     cxx_test_suite_set_correct();
   }
 }
 
+
+void c_take_trivial_ns_ptr(std::unique_ptr<::G::G> g) {
+  if (g->g == 30) {
+    cxx_test_suite_set_correct();
+  }
+}
+
+void c_take_trivial_ns_ref(const ::G::G& g) {
+  if (g.g == 30) {
+    cxx_test_suite_set_correct();
+  }
+}
+
+void c_take_trivial_ns(::G::G g) {
+  if (g.g == 30) {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_take_opaque_ptr(std::unique_ptr<E> e) {
   if (e->e == 40) {
     cxx_test_suite_set_correct();
   }
 }
 
+void c_take_opaque_ns_ptr(std::unique_ptr<::F::F> f) {
+  if (f->f == 40) {
+    cxx_test_suite_set_correct();
+  }
+}
+
 void c_take_opaque_ref(const E& e) {
   if (e.e == 40 && e.e_str == "hello") {
     cxx_test_suite_set_correct();
   }
 }
 
+void c_take_opaque_ns_ref(const ::F::F& f) {
+  if (f.f == 40 && f.f_str == "hello") {
+    cxx_test_suite_set_correct();
+  }
+}
+
 std::unique_ptr<D> c_return_trivial_ptr() {
   auto d = std::unique_ptr<D>(new D());
   d->d = 30;
@@ -424,6 +538,18 @@
   return d;
 }
 
+std::unique_ptr<::G::G> c_return_trivial_ns_ptr() {
+  auto g = std::unique_ptr<::G::G>(new ::G::G());
+  g->g = 30;
+  return g;
+}
+
+::G::G c_return_trivial_ns() {
+  ::G::G g;
+  g.g = 30;
+  return g;
+}
+
 std::unique_ptr<E> c_return_opaque_ptr() {
   auto e = std::unique_ptr<E>(new E());
   e->e = 40;
@@ -431,6 +557,13 @@
   return e;
 }
 
+std::unique_ptr<::F::F> c_return_ns_opaque_ptr() {
+  auto f = std::unique_ptr<::F::F>(new ::F::F());
+  f->f = 40;
+  f->f_str = std::string("hello");
+  return f;
+}
+
 extern "C" const char *cxx_run_test() noexcept {
 #define STRINGIFY(x) #x
 #define TOSTRING(x) STRINGIFY(x)
@@ -494,3 +627,34 @@
 }
 
 } // namespace tests
+
+namespace other {
+
+  void ns_c_take_trivial(::tests::D d) {
+    if (d.d == 30) {
+      cxx_test_suite_set_correct();
+    }
+  }
+
+  ::tests::D ns_c_return_trivial() {
+    ::tests::D d;
+    d.d = 30;
+    return d;
+  }
+
+  void ns_c_take_ns_shared(::A::AShared shared) {
+    if (shared.z == 2020) {
+      cxx_test_suite_set_correct();
+    }
+  }
+} // namespace other
+
+namespace I {
+  uint32_t I::get() const {
+    return a;
+  }
+
+  std::unique_ptr<I> ns_c_return_unique_ptr_ns() {
+    return std::unique_ptr<I>(new I());
+  }
+} // namespace I
diff --git a/tests/ffi/tests.h b/tests/ffi/tests.h
index b3f547e..3835660 100644
--- a/tests/ffi/tests.h
+++ b/tests/ffi/tests.h
@@ -3,6 +3,35 @@
 #include <memory>
 #include <string>
 
+namespace A {
+  struct AShared;
+  enum class AEnum : uint16_t;
+  namespace B {
+    struct ABShared;
+    enum class ABEnum : uint16_t;
+  } // namespace B
+} // namespace A
+
+namespace F {
+  struct F {
+    uint64_t f;
+    std::string f_str;
+  };
+}
+
+namespace G {
+  struct G {
+    uint64_t g;
+  };
+}
+
+namespace H {
+  class H {
+  public:
+    std::string h;
+  };
+}
+
 namespace tests {
 
 struct R;
@@ -44,9 +73,14 @@
 
 size_t c_return_primitive();
 Shared c_return_shared();
+::A::AShared c_return_ns_shared();
+::A::B::ABShared c_return_nested_ns_shared();
 rust::Box<R> c_return_box();
 std::unique_ptr<C> c_return_unique_ptr();
+std::unique_ptr<::H::H> c_return_ns_unique_ptr();
 const size_t &c_return_ref(const Shared &shared);
+const size_t &c_return_ns_ref(const ::A::AShared &shared);
+const size_t &c_return_nested_ns_ref(const ::A::B::ABShared &shared);
 size_t &c_return_mut(Shared &shared);
 rust::Str c_return_str(const Shared &shared);
 rust::Slice<uint8_t> c_return_sliceu8(const Shared &shared);
@@ -66,13 +100,18 @@
 size_t c_return_identity(size_t n);
 size_t c_return_sum(size_t n1, size_t n2);
 Enum c_return_enum(uint16_t n);
+::A::AEnum c_return_ns_enum(uint16_t n);
+::A::B::ABEnum c_return_nested_ns_enum(uint16_t n);
 
 void c_take_primitive(size_t n);
 void c_take_shared(Shared shared);
+void c_take_ns_shared(::A::AShared shared);
+void c_take_nested_ns_shared(::A::B::ABShared shared);
 void c_take_box(rust::Box<R> r);
 void c_take_unique_ptr(std::unique_ptr<C> c);
 void c_take_ref_r(const R &r);
 void c_take_ref_c(const C &c);
+void c_take_ref_ns_c(const ::H::H &h);
 void c_take_str(rust::Str s);
 void c_take_sliceu8(rust::Slice<uint8_t> s);
 void c_take_rust_string(rust::String s);
@@ -86,6 +125,8 @@
 void c_take_rust_vec(rust::Vec<uint8_t> v);
 void c_take_rust_vec_index(rust::Vec<uint8_t> v);
 void c_take_rust_vec_shared(rust::Vec<Shared> v);
+void c_take_rust_vec_ns_shared(rust::Vec<::A::AShared> v);
+void c_take_rust_vec_nested_ns_shared(rust::Vec<::A::B::ABShared> v);
 void c_take_rust_vec_string(rust::Vec<rust::String> v);
 void c_take_rust_vec_shared_index(rust::Vec<Shared> v);
 void c_take_rust_vec_shared_forward_iterator(rust::Vec<Shared> v);
@@ -98,6 +139,8 @@
 void c_take_callback(rust::Fn<size_t(rust::String)> callback);
 */
 void c_take_enum(Enum e);
+void c_take_ns_enum(::A::AEnum e);
+void c_take_nested_ns_enum(::A::B::ABEnum e);
 
 void c_try_return_void();
 size_t c_try_return_primitive();
@@ -115,13 +158,40 @@
 void c_take_trivial_ptr(std::unique_ptr<D> d);
 void c_take_trivial_ref(const D& d);
 void c_take_trivial(D d);
+
+void c_take_trivial_ns_ptr(std::unique_ptr<::G::G> g);
+void c_take_trivial_ns_ref(const ::G::G& g);
+void c_take_trivial_ns(::G::G g);
 void c_take_opaque_ptr(std::unique_ptr<E> e);
+void c_take_opaque_ns_ptr(std::unique_ptr<::F::F> f);
 void c_take_opaque_ref(const E& e);
+void c_take_opaque_ns_ref(const ::F::F& f);
 std::unique_ptr<D> c_return_trivial_ptr();
 D c_return_trivial();
+std::unique_ptr<::G::G> c_return_trivial_ns_ptr();
+::G::G c_return_trivial_ns();
 std::unique_ptr<E> c_return_opaque_ptr();
+std::unique_ptr<::F::F> c_return_ns_opaque_ptr();
 
 rust::String cOverloadedFunction(int32_t x);
 rust::String cOverloadedFunction(rust::Str x);
 
 } // namespace tests
+
+namespace other {
+  void ns_c_take_trivial(::tests::D d);
+  ::tests::D ns_c_return_trivial();
+  void ns_c_take_ns_shared(::A::AShared shared);
+} // namespace other
+
+namespace I {
+  class I {
+  private:
+    uint32_t a;
+  public:
+    I() : a(1000) {}
+    uint32_t get() const;
+  };
+
+  std::unique_ptr<I> ns_c_return_unique_ptr_ns();
+} // namespace I
diff --git a/tests/test.rs b/tests/test.rs
index b92eebf..20b23ac 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1,3 +1,4 @@
+use cxx_test_suite::class_in_ns::ffi3;
 use cxx_test_suite::extra::ffi2;
 use cxx_test_suite::ffi;
 use std::cell::Cell;
@@ -23,12 +24,17 @@
 #[test]
 fn test_c_return() {
     let shared = ffi::Shared { z: 2020 };
+    let ns_shared = ffi::AShared { z: 2020 };
+    let nested_ns_shared = ffi::ABShared { z: 2020 };
 
     assert_eq!(2020, ffi::c_return_primitive());
     assert_eq!(2020, ffi::c_return_shared().z);
     assert_eq!(2020, *ffi::c_return_box());
     ffi::c_return_unique_ptr();
+    ffi2::c_return_ns_unique_ptr();
     assert_eq!(2020, *ffi::c_return_ref(&shared));
+    assert_eq!(2020, *ffi::c_return_ns_ref(&ns_shared));
+    assert_eq!(2020, *ffi::c_return_nested_ns_ref(&nested_ns_shared));
     assert_eq!("2020", ffi::c_return_str(&shared));
     assert_eq!(b"2020\0", ffi::c_return_sliceu8(&shared));
     assert_eq!("2020", ffi::c_return_rust_string());
@@ -64,6 +70,14 @@
         enm @ ffi::Enum::CVal => assert_eq!(2021, enm.repr),
         _ => assert!(false),
     }
+    match ffi::c_return_ns_enum(0) {
+        enm @ ffi::AEnum::AAVal => assert_eq!(0, enm.repr),
+        _ => assert!(false),
+    }
+    match ffi::c_return_nested_ns_enum(0) {
+        enm @ ffi::ABEnum::ABAVal => assert_eq!(0, enm.repr),
+        _ => assert!(false),
+    }
 }
 
 #[test]
@@ -85,11 +99,16 @@
 #[test]
 fn test_c_take() {
     let unique_ptr = ffi::c_return_unique_ptr();
+    let unique_ptr_ns = ffi2::c_return_ns_unique_ptr();
 
     check!(ffi::c_take_primitive(2020));
     check!(ffi::c_take_shared(ffi::Shared { z: 2020 }));
+    check!(ffi::c_take_ns_shared(ffi::AShared { z: 2020 }));
+    check!(ffi::ns_c_take_ns_shared(ffi::AShared { z: 2020 }));
+    check!(ffi::c_take_nested_ns_shared(ffi::ABShared { z: 2020 }));
     check!(ffi::c_take_box(Box::new(2020)));
     check!(ffi::c_take_ref_c(&unique_ptr));
+    check!(ffi2::c_take_ref_ns_c(&unique_ptr_ns));
     check!(cxx_test_suite::module::ffi::c_take_unique_ptr(unique_ptr));
     check!(ffi::c_take_str("2020"));
     check!(ffi::c_take_sliceu8(b"2020"));
@@ -119,7 +138,16 @@
     check!(ffi::c_take_ref_rust_vec(&test_vec));
     check!(ffi::c_take_ref_rust_vec_index(&test_vec));
     check!(ffi::c_take_ref_rust_vec_copy(&test_vec));
+    let ns_shared_test_vec = vec![ffi::AShared { z: 1010 }, ffi::AShared { z: 1011 }];
+    check!(ffi::c_take_rust_vec_ns_shared(ns_shared_test_vec));
+    let nested_ns_shared_test_vec = vec![ffi::ABShared { z: 1010 }, ffi::ABShared { z: 1011 }];
+    check!(ffi::c_take_rust_vec_nested_ns_shared(
+        nested_ns_shared_test_vec
+    ));
+
     check!(ffi::c_take_enum(ffi::Enum::AVal));
+    check!(ffi::c_take_ns_enum(ffi::AEnum::AAVal));
+    check!(ffi::c_take_nested_ns_enum(ffi::ABEnum::ABAVal));
 }
 
 /*
@@ -167,6 +195,14 @@
 }
 
 #[test]
+fn test_c_ns_method_calls() {
+    let unique_ptr = ffi3::ns_c_return_unique_ptr_ns();
+
+    let old_value = unique_ptr.get();
+    assert_eq!(1000, old_value);
+}
+
+#[test]
 fn test_enum_representations() {
     assert_eq!(0, ffi::Enum::AVal.repr);
     assert_eq!(2020, ffi::Enum::BVal.repr);
@@ -200,6 +236,15 @@
     let d = ffi2::c_return_trivial_ptr();
     check!(ffi2::c_take_trivial_ptr(d));
     cxx::UniquePtr::new(ffi2::D { d: 42 });
+    let d = ffi2::ns_c_return_trivial();
+    check!(ffi2::ns_c_take_trivial(d));
+
+    let g = ffi2::c_return_trivial_ns();
+    check!(ffi2::c_take_trivial_ns_ref(&g));
+    check!(ffi2::c_take_trivial_ns(g));
+    let g = ffi2::c_return_trivial_ns_ptr();
+    check!(ffi2::c_take_trivial_ns_ptr(g));
+    cxx::UniquePtr::new(ffi2::G { g: 42 });
 }
 
 #[test]
@@ -207,4 +252,8 @@
     let e = ffi2::c_return_opaque_ptr();
     check!(ffi2::c_take_opaque_ref(e.as_ref().unwrap()));
     check!(ffi2::c_take_opaque_ptr(e));
+
+    let f = ffi2::c_return_ns_opaque_ptr();
+    check!(ffi2::c_take_opaque_ns_ref(f.as_ref().unwrap()));
+    check!(ffi2::c_take_opaque_ns_ptr(f));
 }
diff --git a/tests/ui/by_value_not_supported.stderr b/tests/ui/by_value_not_supported.stderr
index 0a56dd4..a860f3d 100644
--- a/tests/ui/by_value_not_supported.stderr
+++ b/tests/ui/by_value_not_supported.stderr
@@ -16,7 +16,7 @@
 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;