blob: 49b31d14f882aa540f76707e1a0983b53fc3324a [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 }
27}
28
David Tolnayb6cf3142020-04-19 20:56:09 -070029impl Parse for Namespace {
30 fn parse(input: ParseStream) -> Result<Self> {
31 let mut segments = Vec::new();
32 if !input.is_empty() {
33 input.parse::<kw::namespace>()?;
34 input.parse::<Token![=]>()?;
David Tolnaybef9e6d2020-09-06 23:20:52 -070035 segments = input
36 .call(QualifiedName::parse_quoted_or_unquoted)?
37 .segments;
David Tolnayb6cf3142020-04-19 20:56:09 -070038 input.parse::<Option<Token![,]>>()?;
39 }
40 Ok(Namespace { segments })
41 }
42}
43
David Tolnay754e21c2020-03-29 20:58:46 -070044impl Display for Namespace {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 for segment in self {
David Tolnay63f92e82020-04-30 20:40:20 -070047 write!(f, "{}$", segment)?;
David Tolnay754e21c2020-03-29 20:58:46 -070048 }
49 Ok(())
50 }
51}
52
David Tolnayb6cf3142020-04-19 20:56:09 -070053impl IdentFragment for Namespace {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 Display::fmt(self, f)
56 }
57}
58
David Tolnay754e21c2020-03-29 20:58:46 -070059impl<'a> IntoIterator for &'a Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070060 type Item = &'a Ident;
61 type IntoIter = Iter<'a, Ident>;
David Tolnay754e21c2020-03-29 20:58:46 -070062 fn into_iter(self) -> Self::IntoIter {
63 self.iter()
64 }
65}