blob: a61ffc3ad60f53aee679d289c7e0095728068362 [file] [log] [blame]
David Tolnay60e7aa62020-11-01 12:34:51 -08001use crate::syntax::{CppName, Namespace, Pair, ResolvableName, Symbol, Types};
2use proc_macro2::{Ident, Span};
3use syn::Token;
4
5impl Pair {
6 /// Use this constructor when the item can't have a different
7 /// name in Rust and C++.
8 pub fn new(ns: Namespace, ident: Ident) -> Self {
9 Self {
10 rust: ident.clone(),
11 cxx: CppName::new(ns, ident),
12 }
13 }
14
15 /// Use this constructor when attributes such as #[rust_name]
16 /// can be used to potentially give a different name in Rust vs C++.
17 pub fn new_from_differing_names(ns: Namespace, cxx_ident: Ident, rust_ident: Ident) -> Self {
18 Self {
19 rust: rust_ident,
20 cxx: CppName::new(ns, cxx_ident),
21 }
22 }
23}
24
25impl ResolvableName {
26 pub fn new(ident: Ident) -> Self {
27 Self { rust: ident }
28 }
29
30 pub fn make_self(span: Span) -> Self {
31 Self {
32 rust: Token![Self](span).into(),
33 }
34 }
35
36 pub fn is_self(&self) -> bool {
37 self.rust == "Self"
38 }
39
40 pub fn span(&self) -> Span {
41 self.rust.span()
42 }
43
44 pub fn to_symbol(&self, types: &Types) -> Symbol {
45 types.resolve(self).to_symbol()
46 }
47}
48
49impl CppName {
50 pub fn new(ns: Namespace, ident: Ident) -> Self {
51 Self { ns, ident }
52 }
53
54 fn iter_all_segments(&self) -> impl Iterator<Item = &Ident> {
55 self.ns.iter().chain(std::iter::once(&self.ident))
56 }
57
58 fn join(&self, sep: &str) -> String {
59 self.iter_all_segments()
60 .map(|s| s.to_string())
61 .collect::<Vec<_>>()
62 .join(sep)
63 }
64
65 pub fn to_symbol(&self) -> Symbol {
66 Symbol::from_idents(self.iter_all_segments())
67 }
68
69 pub fn to_fully_qualified(&self) -> String {
70 format!("::{}", self.join("::"))
71 }
72}