blob: b4d8ef189d3ea2b8e7a40078deff28191ca6f92c [file] [log] [blame]
David Tolnay8faec772020-11-02 00:18:19 -08001use crate::syntax::{Namespace, Pair, ResolvableName, Symbol, Types};
David Tolnay60e7aa62020-11-01 12:34:51 -08002use proc_macro2::{Ident, Span};
David Tolnay8faec772020-11-02 00:18:19 -08003use std::iter;
David Tolnay60e7aa62020-11-01 12:34:51 -08004use syn::Token;
5
6impl Pair {
David Tolnay8faec772020-11-02 00:18:19 -08007 // Use this constructor when the item can't have a different name in Rust
8 // and C++.
David Tolnayd7a3a182020-11-01 20:45:14 -08009 pub fn new(namespace: Namespace, ident: Ident) -> Self {
David Tolnay60e7aa62020-11-01 12:34:51 -080010 Self {
David Tolnay8faec772020-11-02 00:18:19 -080011 namespace,
12 cxx: ident.clone(),
13 rust: ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080014 }
15 }
16
David Tolnay8faec772020-11-02 00:18:19 -080017 // Use this constructor when attributes such as #[rust_name] can be used to
18 // potentially give a different name in Rust vs C++.
David Tolnayd7a3a182020-11-01 20:45:14 -080019 pub fn new_from_differing_names(
20 namespace: Namespace,
21 cxx_ident: Ident,
22 rust_ident: Ident,
23 ) -> Self {
David Tolnay60e7aa62020-11-01 12:34:51 -080024 Self {
David Tolnay8faec772020-11-02 00:18:19 -080025 namespace,
26 cxx: cxx_ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080027 rust: rust_ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080028 }
29 }
David Tolnay8faec772020-11-02 00:18:19 -080030
31 pub fn to_symbol(&self) -> Symbol {
32 Symbol::from_idents(self.iter_all_segments())
33 }
34
35 pub fn to_fully_qualified(&self) -> String {
36 format!("::{}", self.join("::"))
37 }
38
39 fn iter_all_segments(&self) -> impl Iterator<Item = &Ident> {
40 self.namespace.iter().chain(iter::once(&self.cxx))
41 }
42
43 fn join(&self, sep: &str) -> String {
44 self.iter_all_segments()
45 .map(|s| s.to_string())
46 .collect::<Vec<_>>()
47 .join(sep)
48 }
David Tolnay60e7aa62020-11-01 12:34:51 -080049}
50
51impl ResolvableName {
52 pub fn new(ident: Ident) -> Self {
53 Self { rust: ident }
54 }
55
David Tolnay5804bb72020-12-06 21:06:15 -080056 pub fn from_ref(ident: &Ident) -> &Self {
57 unsafe { &*(ident as *const Ident as *const Self) }
58 }
59
David Tolnay60e7aa62020-11-01 12:34:51 -080060 pub fn make_self(span: Span) -> Self {
61 Self {
62 rust: Token![Self](span).into(),
63 }
64 }
65
66 pub fn is_self(&self) -> bool {
67 self.rust == "Self"
68 }
69
70 pub fn span(&self) -> Span {
71 self.rust.span()
72 }
73
74 pub fn to_symbol(&self, types: &Types) -> Symbol {
75 types.resolve(self).to_symbol()
76 }
77}