blob: 25ae9f4a0686a50e6db432f1b90d9f197af73330 [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
56 pub fn make_self(span: Span) -> Self {
57 Self {
58 rust: Token![Self](span).into(),
59 }
60 }
61
62 pub fn is_self(&self) -> bool {
63 self.rust == "Self"
64 }
65
66 pub fn span(&self) -> Span {
67 self.rust.span()
68 }
69
70 pub fn to_symbol(&self, types: &Types) -> Symbol {
71 types.resolve(self).to_symbol()
72 }
73}