blob: 586c017ace46fa3207c6b23bca5eb7918368d29a [file] [log] [blame]
David Tolnay75ea17c2020-12-06 21:08:34 -08001use crate::syntax::{Namespace, Pair, RustName, 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 -08004
5impl Pair {
David Tolnay8faec772020-11-02 00:18:19 -08006 // Use this constructor when the item can't have a different name in Rust
7 // 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 {
David Tolnay8faec772020-11-02 00:18:19 -080010 namespace,
11 cxx: ident.clone(),
12 rust: ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080013 }
14 }
15
David Tolnay8faec772020-11-02 00:18:19 -080016 // Use this constructor when attributes such as #[rust_name] can be used to
17 // potentially give a different name in Rust vs C++.
David Tolnayd7a3a182020-11-01 20:45:14 -080018 pub fn new_from_differing_names(
19 namespace: Namespace,
20 cxx_ident: Ident,
21 rust_ident: Ident,
22 ) -> Self {
David Tolnay60e7aa62020-11-01 12:34:51 -080023 Self {
David Tolnay8faec772020-11-02 00:18:19 -080024 namespace,
25 cxx: cxx_ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080026 rust: rust_ident,
David Tolnay60e7aa62020-11-01 12:34:51 -080027 }
28 }
David Tolnay8faec772020-11-02 00:18:19 -080029
30 pub fn to_symbol(&self) -> Symbol {
31 Symbol::from_idents(self.iter_all_segments())
32 }
33
34 pub fn to_fully_qualified(&self) -> String {
David Tolnaydee9fa32020-12-21 14:40:50 -080035 let mut fully_qualified = String::new();
36 for segment in self.iter_all_segments() {
37 fully_qualified += "::";
38 fully_qualified += &segment.to_string();
39 }
40 fully_qualified
David Tolnay8faec772020-11-02 00:18:19 -080041 }
42
43 fn iter_all_segments(&self) -> impl Iterator<Item = &Ident> {
44 self.namespace.iter().chain(iter::once(&self.cxx))
45 }
David Tolnay60e7aa62020-11-01 12:34:51 -080046}
47
David Tolnay75ea17c2020-12-06 21:08:34 -080048impl RustName {
David Tolnay60e7aa62020-11-01 12:34:51 -080049 pub fn new(ident: Ident) -> Self {
50 Self { rust: ident }
51 }
52
David Tolnay5804bb72020-12-06 21:06:15 -080053 pub fn from_ref(ident: &Ident) -> &Self {
54 unsafe { &*(ident as *const Ident as *const Self) }
55 }
56
David Tolnay60e7aa62020-11-01 12:34:51 -080057 pub fn span(&self) -> Span {
58 self.rust.span()
59 }
60
61 pub fn to_symbol(&self, types: &Types) -> Symbol {
62 types.resolve(self).to_symbol()
63 }
64}