blob: b4c6716d54516c30be8ad94063ea387801f09de9 [file] [log] [blame]
David Tolnaydd26bd02020-09-06 23:00:17 -07001use crate::syntax::qualified::QualifiedName;
David Tolnayb6cf3142020-04-19 20:56:09 -07002use quote::IdentFragment;
David Tolnay754e21c2020-03-29 20:58:46 -07003use std::fmt::{self, Display};
4use std::slice::Iter;
David Tolnayb6cf3142020-04-19 20:56:09 -07005use syn::parse::{Parse, ParseStream, Result};
David Tolnaydd26bd02020-09-06 23:00:17 -07006use syn::{Ident, Token};
David Tolnayb6cf3142020-04-19 20:56:09 -07007
8mod kw {
9 syn::custom_keyword!(namespace);
10}
David Tolnay754e21c2020-03-29 20:58:46 -070011
12#[derive(Clone)]
13pub struct Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070014 segments: Vec<Ident>,
David Tolnay754e21c2020-03-29 20:58:46 -070015}
16
17impl Namespace {
David Tolnayb6cf3142020-04-19 20:56:09 -070018 pub fn none() -> Self {
19 Namespace {
20 segments: Vec::new(),
21 }
David Tolnay754e21c2020-03-29 20:58:46 -070022 }
23
David Tolnay63f92e82020-04-30 20:40:20 -070024 pub fn iter(&self) -> Iter<Ident> {
David Tolnay754e21c2020-03-29 20:58:46 -070025 self.segments.iter()
26 }
Adrian Taylor3e5cff42020-10-29 19:48:45 -070027
28 pub fn parse_bridge_attr_namespace(input: ParseStream) -> Result<Namespace> {
29 if input.is_empty() {
30 return Ok(Namespace::none());
31 }
32
33 input.parse::<kw::namespace>()?;
34 input.parse::<Token![=]>()?;
35 let ns = input.parse::<Namespace>()?;
36 input.parse::<Option<Token![,]>>()?;
37 Ok(ns)
38 }
David Tolnay754e21c2020-03-29 20:58:46 -070039}
40
David Tolnayb6cf3142020-04-19 20:56:09 -070041impl Parse for Namespace {
42 fn parse(input: ParseStream) -> Result<Self> {
Adrian Taylor3e5cff42020-10-29 19:48:45 -070043 let segments = QualifiedName::parse_quoted_or_unquoted(input)?.segments;
David Tolnayb6cf3142020-04-19 20:56:09 -070044 Ok(Namespace { segments })
45 }
46}
47
David Tolnay754e21c2020-03-29 20:58:46 -070048impl Display for Namespace {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 for segment in self {
David Tolnay63f92e82020-04-30 20:40:20 -070051 write!(f, "{}$", segment)?;
David Tolnay754e21c2020-03-29 20:58:46 -070052 }
53 Ok(())
54 }
55}
56
David Tolnayb6cf3142020-04-19 20:56:09 -070057impl IdentFragment for Namespace {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 Display::fmt(self, f)
60 }
61}
62
David Tolnay754e21c2020-03-29 20:58:46 -070063impl<'a> IntoIterator for &'a Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070064 type Item = &'a Ident;
65 type IntoIter = Iter<'a, Ident>;
David Tolnay754e21c2020-03-29 20:58:46 -070066 fn into_iter(self) -> Self::IntoIter {
67 self.iter()
68 }
69}