1mod arguments;
2mod segment;
3
4pub use arguments::*;
5pub use segment::*;
6
7use moxy_token::{Ident, Span, Spanner, ToTokens, TokenStream};
8
9use crate::*;
10
11#[derive(Clone)]
13#[cfg_attr(feature = "derives", derive(Debug, PartialEq, Eq))]
14#[cfg_attr(feature = "serde", derive(serde::Serialize))]
15pub struct Path {
16 colon: Option<Token![::]>,
17 segments: List<PathSegment, Token![::]>,
18}
19
20impl Path {
21 pub fn try_from_str(value: impl AsRef<str>) -> Result<Self, ParseError> {
22 std::str::FromStr::from_str(value.as_ref())
23 }
24
25 pub fn colon(&self) -> Option<Token![::]> {
26 self.colon
27 }
28
29 pub fn as_ident(&self) -> Option<&Ident> {
30 if self.colon.is_none() && self.segments.len() == 1 {
31 return self.segments.first().map(|s| &s.ident);
32 }
33
34 None
35 }
36
37 pub fn is_ident(&self, ident: impl AsRef<str>) -> bool {
38 let Some(v) = self.as_ident() else {
39 return false;
40 };
41
42 v == ident.as_ref()
43 }
44
45 pub(crate) fn parse_rest(parser: &Parser, first: PathSegment) -> Result<Self, ParseError> {
46 let mut segments = List::new();
47 segments.push_value(first);
48
49 while <Token![::]>::peek(parser.cursor()) {
50 segments.push_punct(<_ as Parse>::parse(parser)?);
51 segments.push_value(<_ as Parse>::parse(parser)?);
52 }
53
54 Ok(Self { colon: None, segments })
55 }
56
57 pub(crate) fn skip_rest(mut cursor: Cursor<'_>) -> Option<Cursor<'_>> {
58 while <Token![::]>::skip(cursor).is_some_and(|cursor| PathSegment::peek(cursor)) {
59 cursor = <Token![::]>::skip(cursor)?;
60 cursor = PathSegment::skip(cursor)?;
61 }
62
63 Some(cursor)
64 }
65}
66
67impl Parse for Path {
68 fn peek(cursor: Cursor<'_>) -> bool {
69 <Token![::]>::peek(cursor) || PathSegment::peek(cursor)
70 }
71
72 fn parse(parser: &Parser) -> Result<Self, ParseError> {
73 let colon = <_ as Parse>::parse(parser)?;
74 let first = <_ as Parse>::parse(parser)?;
75 let mut path = Self::parse_rest(parser, first)?;
76 path.colon = colon;
77 Ok(path)
78 }
79
80 fn skip(mut cursor: Cursor<'_>) -> Option<Cursor<'_>> {
81 cursor = Option::<Token![::]>::skip(cursor)?;
82 cursor = PathSegment::skip(cursor)?;
83 Self::skip_rest(cursor)
84 }
85}
86
87impl Spanner for Path {
88 fn span(&self) -> Span {
89 match (self.colon, self.segments.last()) {
90 (Some(colon), Some(segment)) => colon.span().join(segment.span()),
91 (Some(colon), None) => colon.span(),
92 (None, Some(segment)) => segment.span(),
93 _ => Span::default(),
94 }
95 }
96}
97
98impl ToTokens for Path {
99 fn to_tokens(&self, tokens: &mut TokenStream) {
100 self.colon.to_tokens(tokens);
101 self.segments.to_tokens(tokens);
102 }
103}
104
105impl std::str::FromStr for Path {
106 type Err = ParseError;
107
108 fn from_str(s: &str) -> Result<Self, Self::Err> {
109 let parser = TokenStream::from_str(s)?;
110 Self::parse(&Parser::from_tokens(&parser))
111 }
112}
113
114impl From<Ident> for Path {
115 fn from(ident: Ident) -> Self {
116 let mut segments = List::new();
117
118 segments.push_value(PathSegment {
119 ident,
120 args: PathArguments::None,
121 });
122
123 Self { colon: None, segments }
124 }
125}
126
127impl From<Vec<PathSegment>> for Path {
128 fn from(value: Vec<PathSegment>) -> Self {
129 Self {
130 colon: None,
131 segments: List::from_iter(value),
132 }
133 }
134}
135
136impl Extend<PathSegment> for Path {
137 fn extend<T: IntoIterator<Item = PathSegment>>(&mut self, iter: T) {
138 self.segments.extend(iter);
139 }
140}
141
142impl std::ops::Deref for Path {
143 type Target = List<PathSegment, Token![::]>;
144
145 fn deref(&self) -> &Self::Target {
146 &self.segments
147 }
148}
149
150impl std::ops::DerefMut for Path {
151 fn deref_mut(&mut self) -> &mut Self::Target {
152 &mut self.segments
153 }
154}
155
156impl IntoIterator for Path {
157 type IntoIter = IntoIter<PathSegment>;
158 type Item = PathSegment;
159
160 fn into_iter(self) -> Self::IntoIter {
161 self.segments.into_iter()
162 }
163}
164
165impl std::hash::Hash for Path {
166 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
167 if let Some(colon) = &self.colon {
168 colon.hash(state);
169 }
170
171 for (seg, sep) in self.pairs().map(|v| v.into_tuple()) {
172 seg.hash(state);
173
174 if let Some(colon) = sep {
175 colon.hash(state);
176 }
177 }
178 }
179}