blob: 5230eb6f907c6cd942381b1deea2f1fe98be03d9 [file] [log] [blame]
David Tolnayb6cf3142020-04-19 20:56:09 -07001use crate::syntax::ident;
2use 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 Tolnay63f92e82020-04-30 20:40:20 -07006use syn::{Ident, Path, 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![=]>()?;
35 let path = input.call(Path::parse_mod_style)?;
36 for segment in path.segments {
37 ident::check(&segment.ident)?;
David Tolnay63f92e82020-04-30 20:40:20 -070038 segments.push(segment.ident);
David Tolnayb6cf3142020-04-19 20:56:09 -070039 }
40 input.parse::<Option<Token![,]>>()?;
41 }
42 Ok(Namespace { segments })
43 }
44}
45
David Tolnay754e21c2020-03-29 20:58:46 -070046impl Display for Namespace {
47 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48 for segment in self {
David Tolnay63f92e82020-04-30 20:40:20 -070049 write!(f, "{}$", segment)?;
David Tolnay754e21c2020-03-29 20:58:46 -070050 }
51 Ok(())
52 }
53}
54
David Tolnayb6cf3142020-04-19 20:56:09 -070055impl IdentFragment for Namespace {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 Display::fmt(self, f)
58 }
59}
60
David Tolnay754e21c2020-03-29 20:58:46 -070061impl<'a> IntoIterator for &'a Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070062 type Item = &'a Ident;
63 type IntoIter = Iter<'a, Ident>;
David Tolnay754e21c2020-03-29 20:58:46 -070064 fn into_iter(self) -> Self::IntoIter {
65 self.iter()
66 }
67}