1 use crate::syntax::symbol::Segment; 2 use crate::syntax::{Lifetimes, NamedType, Pair, Symbol}; 3 use proc_macro2::{Ident, Span}; 4 use std::fmt::{self, Display}; 5 use std::iter; 6 use syn::parse::{Error, Result}; 7 use syn::punctuated::Punctuated; 8 9 #[derive(Clone)] 10 pub struct ForeignName { 11 text: String, 12 } 13 14 impl Pair { to_symbol(&self) -> Symbol15 pub fn to_symbol(&self) -> Symbol { 16 let segments = self 17 .namespace 18 .iter() 19 .map(|ident| ident as &dyn Segment) 20 .chain(iter::once(&self.cxx as &dyn Segment)); 21 Symbol::from_idents(segments) 22 } 23 } 24 25 impl NamedType { new(rust: Ident) -> Self26 pub fn new(rust: Ident) -> Self { 27 let generics = Lifetimes { 28 lt_token: None, 29 lifetimes: Punctuated::new(), 30 gt_token: None, 31 }; 32 NamedType { rust, generics } 33 } 34 span(&self) -> Span35 pub fn span(&self) -> Span { 36 self.rust.span() 37 } 38 } 39 40 impl ForeignName { parse(text: &str, span: Span) -> Result<Self>41 pub fn parse(text: &str, span: Span) -> Result<Self> { 42 // TODO: support C++ names containing whitespace (`unsigned int`) or 43 // non-alphanumeric characters (`operator++`). 44 match syn::parse_str::<Ident>(text) { 45 Ok(ident) => { 46 let text = ident.to_string(); 47 Ok(ForeignName { text }) 48 } 49 Err(err) => Err(Error::new(span, err)), 50 } 51 } 52 } 53 54 impl Display for ForeignName { fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result55 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 56 formatter.write_str(&self.text) 57 } 58 } 59 60 impl PartialEq<str> for ForeignName { eq(&self, rhs: &str) -> bool61 fn eq(&self, rhs: &str) -> bool { 62 self.text == rhs 63 } 64 } 65