blob: ee010a944a77445b7ff1ea106f9d9d7d5d7f2906 [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++.
David Tolnayd7a3a182020-11-01 20:45:14 -08008 pub fn new(namespace: Namespace, ident: Ident) -> Self {
David Tolnay60e7aa62020-11-01 12:34:51 -08009 Self {
10 rust: ident.clone(),
David Tolnayd7a3a182020-11-01 20:45:14 -080011 cxx: CppName::new(namespace, ident),
David Tolnay60e7aa62020-11-01 12:34:51 -080012 }
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++.
David Tolnayd7a3a182020-11-01 20:45:14 -080017 pub fn new_from_differing_names(
18 namespace: Namespace,
19 cxx_ident: Ident,
20 rust_ident: Ident,
21 ) -> Self {
David Tolnay60e7aa62020-11-01 12:34:51 -080022 Self {
23 rust: rust_ident,
David Tolnayd7a3a182020-11-01 20:45:14 -080024 cxx: CppName::new(namespace, cxx_ident),
David Tolnay60e7aa62020-11-01 12:34:51 -080025 }
26 }
27}
28
29impl ResolvableName {
30 pub fn new(ident: Ident) -> Self {
31 Self { rust: ident }
32 }
33
34 pub fn make_self(span: Span) -> Self {
35 Self {
36 rust: Token![Self](span).into(),
37 }
38 }
39
40 pub fn is_self(&self) -> bool {
41 self.rust == "Self"
42 }
43
44 pub fn span(&self) -> Span {
45 self.rust.span()
46 }
47
48 pub fn to_symbol(&self, types: &Types) -> Symbol {
49 types.resolve(self).to_symbol()
50 }
51}
52
53impl CppName {
David Tolnayd7a3a182020-11-01 20:45:14 -080054 pub fn new(namespace: Namespace, ident: Ident) -> Self {
55 Self { namespace, ident }
David Tolnay60e7aa62020-11-01 12:34:51 -080056 }
57
58 fn iter_all_segments(&self) -> impl Iterator<Item = &Ident> {
David Tolnayd7a3a182020-11-01 20:45:14 -080059 self.namespace.iter().chain(std::iter::once(&self.ident))
David Tolnay60e7aa62020-11-01 12:34:51 -080060 }
61
62 fn join(&self, sep: &str) -> String {
63 self.iter_all_segments()
64 .map(|s| s.to_string())
65 .collect::<Vec<_>>()
66 .join(sep)
67 }
68
69 pub fn to_symbol(&self) -> Symbol {
70 Symbol::from_idents(self.iter_all_segments())
71 }
72
73 pub fn to_fully_qualified(&self) -> String {
74 format!("::{}", self.join("::"))
75 }
76}