Skip to main content

time_macros/format_description/
lexer.rs

1use core::iter;
2
3use super::{Error, Location, Spanned, SpannedValue};
4use crate::FormatDescriptionVersion;
5
6pub(super) struct Lexed<I: Iterator> {
7    iter: iter::Peekable<I>,
8}
9
10impl<I: Iterator> Iterator for Lexed<I> {
11    type Item = I::Item;
12
13    fn next(&mut self) -> Option<Self::Item> {
14        self.iter.next()
15    }
16}
17
18impl<'iter, 'token: 'iter, I: Iterator<Item = Result<Token<'token>, Error>> + 'iter> Lexed<I> {
19    pub(super) fn peek(&mut self) -> Option<&I::Item> {
20        self.iter.peek()
21    }
22
23    pub(super) fn next_if_whitespace(&mut self) -> Option<Spanned<&'token [u8]>> {
24        if let Some(&Ok(Token::ComponentPart {
25            kind: ComponentKind::Whitespace,
26            value,
27        })) = self.peek()
28        {
29            self.next(); // consume
30            Some(value)
31        } else {
32            None
33        }
34    }
35
36    pub(super) fn next_if_not_whitespace(&mut self) -> Option<Spanned<&'token [u8]>> {
37        if let Some(&Ok(Token::ComponentPart {
38            kind: ComponentKind::NotWhitespace,
39            value,
40        })) = self.peek()
41        {
42            self.next();
43            Some(value)
44        } else {
45            None
46        }
47    }
48
49    pub(super) fn next_if_opening_bracket(&mut self) -> Option<Location> {
50        if let Some(&Ok(Token::Bracket {
51            kind: BracketKind::Opening,
52            location,
53        })) = self.peek()
54        {
55            self.next();
56            Some(location)
57        } else {
58            None
59        }
60    }
61
62    pub(super) fn peek_closing_bracket(&'iter mut self) -> Option<&'iter Location> {
63        if let Some(Ok(Token::Bracket {
64            kind: BracketKind::Closing,
65            location,
66        })) = self.peek()
67        {
68            Some(location)
69        } else {
70            None
71        }
72    }
73
74    pub(super) fn next_if_closing_bracket(&mut self) -> Option<Location> {
75        if let Some(&Ok(Token::Bracket {
76            kind: BracketKind::Closing,
77            location,
78        })) = self.peek()
79        {
80            self.next();
81            Some(location)
82        } else {
83            None
84        }
85    }
86}
87
88pub(super) enum Token<'a> {
89    Literal(Spanned<&'a [u8]>),
90    Bracket {
91        kind: BracketKind,
92        location: Location,
93    },
94    ComponentPart {
95        kind: ComponentKind,
96        value: Spanned<&'a [u8]>,
97    },
98}
99
100impl std::fmt::Debug for Token<'_> {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        match self {
103            Self::Literal(arg0) => f
104                .debug_tuple("Literal")
105                .field(&String::from_utf8_lossy(arg0))
106                .finish(),
107            Self::Bracket { kind, location } => f
108                .debug_struct("Bracket")
109                .field("kind", kind)
110                .field("location", location)
111                .finish(),
112            Self::ComponentPart { kind, value } => f
113                .debug_struct("ComponentPart")
114                .field("kind", kind)
115                .field("value", &String::from_utf8_lossy(value))
116                .finish(),
117        }
118    }
119}
120
121#[derive(Debug)]
122pub(super) enum BracketKind {
123    Opening,
124    Closing,
125}
126
127#[derive(Debug)]
128pub(super) enum ComponentKind {
129    Whitespace,
130    NotWhitespace,
131}
132
133fn attach_location<'item>(
134    iter: impl Iterator<Item = &'item u8>,
135    proc_span: proc_macro::Span,
136) -> impl Iterator<Item = (&'item u8, Location)> {
137    let mut byte_pos = 0;
138
139    iter.map(move |byte| {
140        let location = Location {
141            byte: byte_pos,
142            proc_span,
143        };
144        byte_pos += 1;
145        (byte, location)
146    })
147}
148
149pub(super) fn lex(
150    version: FormatDescriptionVersion,
151    mut input: &[u8],
152    proc_span: proc_macro::Span,
153) -> Lexed<impl Iterator<Item = Result<Token<'_>, Error>>> {
154    let mut depth: u32 = 0;
155    let mut iter = attach_location(input.iter(), proc_span).peekable();
156    let mut second_bracket_location = None;
157
158    let iter = iter::from_fn(move || {
159        if version.is_v1()
160            && let Some(location) = second_bracket_location.take()
161        {
162            return Some(Ok(Token::Bracket {
163                kind: BracketKind::Opening,
164                location,
165            }));
166        }
167
168        Some(Ok(match iter.next()? {
169            (b'\\', backslash_loc) if version.is_at_least_v2() => match iter.next() {
170                Some((b'\\' | b'[' | b']', char_loc)) => {
171                    let char = &input[1..2];
172                    input = &input[2..];
173                    if depth == 0 {
174                        Token::Literal(char.spanned(backslash_loc.to(char_loc)))
175                    } else {
176                        Token::ComponentPart {
177                            kind: ComponentKind::NotWhitespace,
178                            value: char.spanned(backslash_loc.to(char_loc)),
179                        }
180                    }
181                }
182                Some((_, loc)) => {
183                    return Some(Err(loc.error("invalid escape sequence")));
184                }
185                None => {
186                    return Some(Err(backslash_loc.error("unexpected end of input")));
187                }
188            },
189            (b'[', location) if version.is_v1() => {
190                if let Some((_, second_location)) = iter.next_if(|&(&byte, _)| byte == b'[') {
191                    second_bracket_location = Some(second_location);
192                    input = &input[2..];
193                } else {
194                    depth += 1;
195                    input = &input[1..];
196                }
197
198                Token::Bracket {
199                    kind: BracketKind::Opening,
200                    location,
201                }
202            }
203            (b'[', location) => {
204                depth += 1;
205                input = &input[1..];
206
207                Token::Bracket {
208                    kind: BracketKind::Opening,
209                    location,
210                }
211            }
212            (b']', location) if depth > 0 => {
213                depth -= 1;
214                input = &input[1..];
215
216                Token::Bracket {
217                    kind: BracketKind::Closing,
218                    location,
219                }
220            }
221            (_, start_location) if depth == 0 => {
222                let mut bytes = 1;
223                let mut end_location = start_location;
224
225                while let Some((_, location)) = iter.next_if(|&(&byte, _)| {
226                    !(version.is_at_least_v2() && byte == b'\\' || byte == b'[')
227                }) {
228                    end_location = location;
229                    bytes += 1;
230                }
231
232                let value = &input[..bytes];
233                input = &input[bytes..];
234
235                Token::Literal(value.spanned(start_location.to(end_location)))
236            }
237            (byte, start_location) => {
238                let mut bytes = 1;
239                let mut end_location = start_location;
240                let is_whitespace = byte.is_ascii_whitespace();
241
242                while let Some((_, location)) = iter.next_if(|&(byte, _)| {
243                    !matches!(byte, b'\\' | b'[' | b']')
244                        && is_whitespace == byte.is_ascii_whitespace()
245                }) {
246                    end_location = location;
247                    bytes += 1;
248                }
249
250                let value = &input[..bytes];
251                input = &input[bytes..];
252
253                Token::ComponentPart {
254                    kind: if is_whitespace {
255                        ComponentKind::Whitespace
256                    } else {
257                        ComponentKind::NotWhitespace
258                    },
259                    value: value.spanned(start_location.to(end_location)),
260                }
261            }
262        }))
263    });
264
265    Lexed {
266        iter: iter.peekable(),
267    }
268}