blob: 523850e4360c4da0faebbf675db58d5d560c6865 [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 {
35 format!("::{}", self.join("::"))
36 }
37
38 fn iter_all_segments(&self) -> impl Iterator<Item = &Ident> {
39 self.namespace.iter().chain(iter::once(&self.cxx))
40 }
41
42 fn join(&self, sep: &str) -> String {
43 self.iter_all_segments()
44 .map(|s| s.to_string())
45 .collect::<Vec<_>>()
46 .join(sep)
47 }
David Tolnay60e7aa62020-11-01 12:34:51 -080048}
49
David Tolnay75ea17c2020-12-06 21:08:34 -080050impl RustName {
David Tolnay60e7aa62020-11-01 12:34:51 -080051 pub fn new(ident: Ident) -> Self {
52 Self { rust: ident }
53 }
54
David Tolnay5804bb72020-12-06 21:06:15 -080055 pub fn from_ref(ident: &Ident) -> &Self {
56 unsafe { &*(ident as *const Ident as *const Self) }
57 }
58
David Tolnay60e7aa62020-11-01 12:34:51 -080059 pub fn span(&self) -> Span {
60 self.rust.span()
61 }
62
63 pub fn to_symbol(&self, types: &Types) -> Symbol {
64 types.resolve(self).to_symbol()
65 }
66}