blob: bdfb8453052740f3c2c0c32c3dfd82e30d28c68b [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 Tolnaydd26bd02020-09-06 23:00:17 -070035 segments = input.call(QualifiedName::parse_unquoted)?.segments;
David Tolnayb6cf3142020-04-19 20:56:09 -070036 input.parse::<Option<Token![,]>>()?;
37 }
38 Ok(Namespace { segments })
39 }
40}
41
David Tolnay754e21c2020-03-29 20:58:46 -070042impl Display for Namespace {
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 for segment in self {
David Tolnay63f92e82020-04-30 20:40:20 -070045 write!(f, "{}$", segment)?;
David Tolnay754e21c2020-03-29 20:58:46 -070046 }
47 Ok(())
48 }
49}
50
David Tolnayb6cf3142020-04-19 20:56:09 -070051impl IdentFragment for Namespace {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 Display::fmt(self, f)
54 }
55}
56
David Tolnay754e21c2020-03-29 20:58:46 -070057impl<'a> IntoIterator for &'a Namespace {
David Tolnay63f92e82020-04-30 20:40:20 -070058 type Item = &'a Ident;
59 type IntoIter = Iter<'a, Ident>;
David Tolnay754e21c2020-03-29 20:58:46 -070060 fn into_iter(self) -> Self::IntoIter {
61 self.iter()
62 }
63}