blob: e2dce183176ec0a8888ba122f3c145288c5cea61 [file] [log] [blame]
David Tolnayb6cf3142020-04-19 20:56:09 -07001use quote::IdentFragment;
David Tolnay754e21c2020-03-29 20:58:46 -07002use std::fmt::{self, Display};
3use std::slice::Iter;
David Tolnayb6cf3142020-04-19 20:56:09 -07004use syn::parse::{Parse, ParseStream, Result};
David Tolnay63f92e82020-04-30 20:40:20 -07005use syn::{Ident, Path, Token};
David Tolnayb6cf3142020-04-19 20:56:09 -07006
7mod kw {
8 syn::custom_keyword!(namespace);
9}
David Tolnay754e21c2020-03-29 20:58:46 -070010
11#[derive(Clone)]
12pub struct Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070013 segments: Vec<Ident>,
David Tolnay754e21c2020-03-29 20:58:46 -070014}
15
16impl Namespace {
David Tolnayb6cf3142020-04-19 20:56:09 -070017 pub fn none() -> Self {
18 Namespace {
19 segments: Vec::new(),
20 }
David Tolnay754e21c2020-03-29 20:58:46 -070021 }
22
David Tolnay63f92e82020-04-30 20:40:20 -070023 pub fn iter(&self) -> Iter<Ident> {
David Tolnay754e21c2020-03-29 20:58:46 -070024 self.segments.iter()
25 }
26}
27
David Tolnayb6cf3142020-04-19 20:56:09 -070028impl Parse for Namespace {
29 fn parse(input: ParseStream) -> Result<Self> {
30 let mut segments = Vec::new();
31 if !input.is_empty() {
32 input.parse::<kw::namespace>()?;
33 input.parse::<Token![=]>()?;
34 let path = input.call(Path::parse_mod_style)?;
35 for segment in path.segments {
David Tolnay63f92e82020-04-30 20:40:20 -070036 segments.push(segment.ident);
David Tolnayb6cf3142020-04-19 20:56:09 -070037 }
38 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}