Skip to main content

cel_parser/
lex_lexer.rs

1//! Flattens Rust token trees into CEL tokens while preserving source spans.
2//!
3//! Construct a [`LexLexer`] from a `proc_macro2::TokenStream` iterator and consume
4//! it as an iterator of [`Token`] values. Groups emit matching opening and closing
5//! delimiters, booleans become literals, and adjacent punctuation combines into
6//! the supported operators. Documentation attributes become comment tokens.
7//! Decimal literals suffixed `f32` or `f64`, including `1f64`, become floating
8//! literals without changing their spelling or span. A floating exponent's
9//! optional sign follows `e` or `E` before any underscores.
10//!
11//! ```
12//! use cel_parser::lex_lexer::{LexLexer, Token};
13//!
14//! let input: proc_macro2::TokenStream = "value && true".parse()?;
15//! let mut lexer = LexLexer::new(input.into_iter());
16//! assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "value"));
17//! assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == "&&"));
18//! assert!(matches!(lexer.next(), Some(Token::Literal(_))));
19//! assert!(lexer.next().is_none());
20//! # Ok::<(), proc_macro2::LexError>(())
21//! ```
22//!
23//! # Error Handling
24//!
25//! A `#` commits to a documentation attribute: `#[doc = "..."]` or `#![doc = "..."]`.
26//! Other attribute shapes, literals Syn cannot parse, and exponent signs after
27//! underscores produce [`Token::Error`]. Errors consume the inspected token
28//! trees; iteration may continue with the remaining input, but does not roll
29//! back a malformed attribute.
30
31use proc_macro2::{Delimiter, Ident, Spacing, Span, TokenTree};
32use syn::Lit;
33
34/// Provides a token's source span for diagnostics.
35///
36/// # Examples
37///
38/// ```
39/// use cel_parser::lex_lexer::HasSpan;
40///
41/// let input: proc_macro2::TokenStream = "name".parse()?;
42/// let token = input.into_iter().next().unwrap();
43/// assert_eq!(HasSpan::span(&token).source_text().as_deref(), Some("name"));
44/// # Ok::<(), proc_macro2::LexError>(())
45/// ```
46pub trait HasSpan {
47    /// Returns the source span associated with this token.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use cel_parser::lex_lexer::HasSpan;
53    ///
54    /// let input: proc_macro2::TokenStream = "42".parse()?;
55    /// let token = input.into_iter().next().unwrap();
56    /// assert_eq!(HasSpan::span(&token).source_text().as_deref(), Some("42"));
57    /// # Ok::<(), proc_macro2::LexError>(())
58    /// ```
59    fn span(&self) -> Span;
60}
61
62/// Owns the unconsumed contents and matching close delimiter of one open group.
63struct GroupLevel {
64    iter: TokenStreamIter,
65    delimiter: Delimiter,
66    span: Span,
67}
68
69/// Owns a token stream's consuming iterator.
70///
71/// # Examples
72///
73/// ```
74/// use cel_parser::lex_lexer::TokenStreamIter;
75///
76/// let input: proc_macro2::TokenStream = "42".parse()?;
77/// let mut iter: TokenStreamIter = input.into_iter();
78/// assert!(iter.next().is_some());
79/// assert!(iter.next().is_none());
80/// # Ok::<(), proc_macro2::LexError>(())
81/// ```
82pub type TokenStreamIter = proc_macro2::token_stream::IntoIter;
83
84/// Stores one to three operator characters inline.
85///
86/// Equality with a string compares the complete character sequence, not a prefix.
87///
88/// # Examples
89///
90/// ```
91/// use cel_parser::lex_lexer::PunctOp;
92///
93/// let op = PunctOp::Two(['&', '&']);
94/// assert!(op == "&&");
95/// assert!(op != "&");
96/// assert!(op != "&&&");
97/// ```
98#[derive(Clone, Debug)]
99pub enum PunctOp {
100    /// Single character (e.g. `+`, `-`).
101    One(char),
102    /// Two characters (e.g. `&&`, `<=`, `..`).
103    Two([char; 2]),
104    /// Three characters (e.g. `..=`).
105    Three([char; 3]),
106}
107
108impl PartialEq<str> for PunctOp {
109    /// Returns whether the string contains exactly this operator's characters.
110    fn eq(&self, other: &str) -> bool {
111        let chars: &[char] = match self {
112            PunctOp::One(c) => std::slice::from_ref(c),
113            PunctOp::Two(chars) => chars,
114            PunctOp::Three(chars) => chars,
115        };
116        chars.iter().copied().eq(other.chars())
117    }
118}
119
120impl PartialEq<&str> for PunctOp {
121    /// Returns whether the borrowed string equals this operator's characters.
122    fn eq(&self, other: &&str) -> bool {
123        self.eq(*other)
124    }
125}
126
127/// Lazily flattens token trees and combines adjacent supported punctuation.
128///
129/// Each group emits matching delimiters, including `Delimiter::None`. Operators
130/// combine only across joint punctuation within the same group. Combined tokens
131/// retain the first punctuation's span; delimiters retain their group's span.
132/// The lexer is forward-only and non-cloneable; parsers use a single-token
133/// [`std::iter::Peekable`] cursor, not indexed lookahead or speculative copies.
134///
135/// - Invariant: The group stack owns open groups in nesting order; lookahead and
136///   pending close tokens precede any further tokens from their parent iterator.
137/// - Complexity: Traversal visits O(n) token trees and retains O(d) group levels
138///   for nesting depth d, excluding token payloads and upstream iterator storage.
139///
140/// # Examples
141///
142/// ```
143/// use cel_parser::lex_lexer::{LexLexer, Token};
144///
145/// let input: proc_macro2::TokenStream = "(true)".parse()?;
146/// let mut lexer = LexLexer::new(input.into_iter());
147/// assert!(matches!(lexer.next(), Some(Token::OpenDelim { .. })));
148/// assert!(matches!(lexer.next(), Some(Token::Literal(syn::Lit::Bool(b))) if b.value));
149/// assert!(matches!(lexer.next(), Some(Token::CloseDelim { .. })));
150/// assert!(lexer.next().is_none());
151/// # Ok::<(), proc_macro2::LexError>(())
152/// ```
153pub struct LexLexer {
154    input: TokenStreamIter,
155    /// Stack of iterators for nested groups - allows lazy flattening.
156    /// Each entry tracks the iterator and its close delimiter info.
157    group_stack: Vec<GroupLevel>,
158    /// Pending close delimiter to emit when we've just exhausted a group iterator.
159    pending_close: Option<(Delimiter, Span)>,
160    /// Pending token that was consumed while looking ahead.
161    pending_token: Option<TokenTree>,
162}
163
164impl LexLexer {
165    /// Takes ownership of an iterator without consuming any tokens.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use cel_parser::lex_lexer::LexLexer;
171    ///
172    /// let lexer = LexLexer::new(proc_macro2::TokenStream::new().into_iter());
173    /// assert_eq!(lexer.count(), 0);
174    /// ```
175    pub fn new(input: TokenStreamIter) -> Self {
176        Self {
177            input,
178            group_stack: Vec::new(),
179            pending_close: None,
180            pending_token: None,
181        }
182    }
183
184    /// Parses a literal while preserving its span.
185    ///
186    /// Returns `Token::Error` if the literal is malformed.
187    ///
188    /// - Complexity: O(n) time and space for a literal of n characters.
189    fn convert_literal(literal: proc_macro2::Literal) -> Token {
190        let span = literal.span();
191        match syn::parse2(TokenTree::Literal(literal).into()).and_then(normalize_literal) {
192            Ok(literal) => Token::Literal(literal),
193            Err(error) => Token::Error {
194                message: error.to_string(),
195                span,
196            },
197        }
198    }
199
200    /// Converts boolean keywords to literals and preserves every other identifier.
201    ///
202    /// - Complexity: O(n) time for an identifier of n characters.
203    fn convert_identifier(ident: Ident) -> Token {
204        if ident == "true" || ident == "false" {
205            Token::Literal(Lit::Bool(syn::LitBool::new(ident == "true", ident.span())))
206        } else {
207            Token::Identifier(ident)
208        }
209    }
210
211    /// Returns whether two characters form a supported compound operator.
212    fn is_compound_operator(first: char, second: char) -> bool {
213        matches!(
214            (first, second),
215            ('&', '&')
216                | ('|', '|')
217                | ('=', '=')
218                | ('!', '=')
219                | ('<', '=')
220                | ('>', '=')
221                | ('<', '<')
222                | ('>', '>')
223                | ('-', '>')
224                | ('=', '>')
225                | (':', '=')
226                | ('.', '.')
227        )
228    }
229
230    /// Returns the next lookahead, innermost group, or root token, in that order.
231    ///
232    /// On group exhaustion, returns `None` and schedules its closing delimiter
233    /// before any further parent tokens.
234    fn next_token_tree(&mut self) -> Option<TokenTree> {
235        if let Some(token) = self.pending_token.take() {
236            return Some(token);
237        }
238
239        if let Some(level) = self.group_stack.last_mut() {
240            if let Some(tt) = level.iter.next() {
241                return Some(tt);
242            }
243            let level = self.group_stack.pop().unwrap();
244            self.pending_close = Some((level.delimiter, level.span));
245            return None;
246        }
247
248        self.input.next()
249    }
250
251    /// Consumes the longest supported operator beginning with `first`.
252    ///
253    /// Preserves the first punctuation's span and retains unmatched lookahead.
254    /// Only joint punctuation within the current group can extend the operator.
255    fn combine_punctuation(&mut self, first: proc_macro2::Punct) -> Token {
256        let ch = first.as_char();
257        let mut op = PunctOp::One(ch);
258        if first.spacing() == Spacing::Joint {
259            match self.next_token_tree() {
260                Some(TokenTree::Punct(second))
261                    if Self::is_compound_operator(ch, second.as_char()) =>
262                {
263                    let next_ch = second.as_char();
264                    op = PunctOp::Two([ch, next_ch]);
265                    if [ch, next_ch] == ['.', '.'] && second.spacing() == Spacing::Joint {
266                        match self.next_token_tree() {
267                            Some(TokenTree::Punct(third)) if third.as_char() == '=' => {
268                                op = PunctOp::Three(['.', '.', '=']);
269                            }
270                            other => self.pending_token = other,
271                        }
272                    }
273                }
274                other => self.pending_token = other,
275            }
276        }
277        Token::Punct {
278            op,
279            span: first.span(),
280        }
281    }
282
283    /// `doc_attribute_tail = ["!"] "[" "doc" "=" string_literal "]".`
284    ///
285    /// Returns a documentation token or `Token::Error` for any mismatch, consuming
286    /// the inspected token trees without rolling back.
287    ///
288    /// - Complexity: O(n) time and space for an attribute containing n characters.
289    fn parse_doc_comment_attribute(&mut self, hash_span: Span) -> Token {
290        let next = self.next_token_tree();
291        let (inner, group_token) = match next {
292            Some(TokenTree::Punct(p)) if p.as_char() == '!' => (true, self.next_token_tree()),
293            other => (false, other),
294        };
295        let group = match group_token {
296            Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => g,
297            Some(other) => {
298                return Token::Error {
299                    message: "expected `[` after `#`".to_string(),
300                    span: other.span(),
301                };
302            }
303            None => {
304                return Token::Error {
305                    message: "expected `[` after `#`".to_string(),
306                    span: hash_span,
307                };
308            }
309        };
310        let mut inner_tokens = group.stream().into_iter();
311        let ident_ok = match inner_tokens.next() {
312            Some(TokenTree::Ident(id)) => id == "doc",
313            _ => false,
314        };
315        if !ident_ok {
316            return Token::Error {
317                message: "expected `doc` after `#[`".to_string(),
318                span: group.span(),
319            };
320        }
321        let eq_ok = matches!(
322            inner_tokens.next(),
323            Some(TokenTree::Punct(p)) if p.as_char() == '='
324        );
325        if !eq_ok {
326            return Token::Error {
327                message: "expected `=` after `doc`".to_string(),
328                span: group.span(),
329            };
330        }
331        let text = match inner_tokens.next() {
332            Some(TokenTree::Literal(lit)) => {
333                let token_stream: proc_macro2::TokenStream = TokenTree::Literal(lit).into();
334                match syn::parse2::<Lit>(token_stream) {
335                    Ok(Lit::Str(s)) => s.value(),
336                    _ => {
337                        return Token::Error {
338                            message: "expected a string literal after `doc =`".to_string(),
339                            span: group.span(),
340                        };
341                    }
342                }
343            }
344            _ => {
345                return Token::Error {
346                    message: "expected a string literal after `doc =`".to_string(),
347                    span: group.span(),
348                };
349            }
350        };
351        if inner_tokens.next().is_some() {
352            return Token::Error {
353                message: "unexpected token after `doc = \"...\"`".to_string(),
354                span: group.span(),
355            };
356        }
357        Token::DocComment {
358            text,
359            inner,
360            span: hash_span,
361        }
362    }
363}
364
365/// Represents a parsed literal, including boolean keywords.
366///
367/// # Examples
368///
369/// ```
370/// use cel_parser::lex_lexer::{HasSpan, Literal};
371///
372/// let literal: Literal = syn::parse_str("true")?;
373/// assert!(matches!(literal, Literal::Bool(ref b) if b.value));
374/// let span = HasSpan::span(&literal);
375/// # Ok::<(), syn::Error>(())
376/// ```
377pub type Literal = Lit;
378
379/// Classifies decimal integer-form floats and validates exponent sign placement.
380///
381/// # Errors
382///
383/// Returns an error when an exponent sign follows an underscore.
384///
385/// - Complexity: O(n) time for a literal with n characters, with O(n) auxiliary
386///   space for an exponent or integer-form float.
387pub(crate) fn normalize_literal(literal: Literal) -> syn::Result<Literal> {
388    let literal = match literal {
389        Lit::Int(integer) if matches!(integer.suffix(), "f32" | "f64") => {
390            // Syn classifies `1f64` as an integer, but radix-prefixed integers are not floats.
391            let spelling = integer.to_string();
392            let unsigned = spelling.strip_prefix('-').unwrap_or(&spelling);
393            if unsigned.starts_with("0b")
394                || unsigned.starts_with("0o")
395                || unsigned.starts_with("0x")
396            {
397                Lit::Int(integer)
398            } else {
399                Lit::Float(syn::LitFloat::new(&spelling, integer.span()))
400            }
401        }
402        other => other,
403    };
404    if let Lit::Float(float) = &literal
405        && float.base10_digits().contains('e')
406    {
407        let spelling = float.to_string();
408        if let Some((_, exponent)) = spelling.split_once(['e', 'E']) {
409            let mut chars = exponent.chars();
410            if chars.next() == Some('_') && matches!(chars.find(|ch| *ch != '_'), Some('+' | '-')) {
411                return Err(syn::Error::new(
412                    float.span(),
413                    "an exponent sign must immediately follow `e` or `E`",
414                ));
415            }
416        }
417    }
418    Ok(literal)
419}
420
421impl HasSpan for Literal {
422    /// Returns the literal's span, including uninterpreted verbatim literals.
423    fn span(&self) -> Span {
424        syn::spanned::Spanned::span(self)
425    }
426}
427
428/// A flattened token that represents elements from a TokenTree stream.
429///
430/// Groups are flattened into OpenDelim and CloseDelim tokens, making parsing
431/// simpler by removing nesting from the token stream.
432///
433/// # Examples
434///
435/// ```
436/// use cel_parser::lex_lexer::{LexLexer, Token};
437///
438/// let input: proc_macro2::TokenStream = "name".parse()?;
439/// let token = LexLexer::new(input.into_iter()).next().unwrap();
440/// assert!(matches!(token, Token::Identifier(id) if id == "name"));
441/// # Ok::<(), proc_macro2::LexError>(())
442/// ```
443#[derive(Debug)]
444pub enum Token {
445    /// A literal value (integer, string, boolean, or float) with eager discrimination.
446    Literal(Literal),
447
448    /// An identifier.
449    Identifier(Ident),
450
451    /// A punctuation operator storing all one to three characters inline.
452    Punct {
453        /// The operator (e.g., "+", "&&", "<=").
454        op: PunctOp,
455        /// Span for error reporting.
456        span: Span,
457    },
458
459    /// Opening delimiter (flattened from Group).
460    OpenDelim {
461        /// The type of delimiter (Parenthesis, Brace, Bracket).
462        delimiter: Delimiter,
463        /// Span for error reporting.
464        span: Span,
465    },
466
467    /// Closing delimiter (flattened from Group).
468    CloseDelim {
469        /// The type of delimiter (Parenthesis, Brace, Bracket).
470        delimiter: Delimiter,
471        /// Span for error reporting.
472        span: Span,
473    },
474
475    /// A recognized `///`/`//!` doc comment, unwrapped from the `#[doc = "..."]`/
476    /// `#![doc = "..."]` attribute-shaped token sequence `proc_macro2` produces for it. General
477    /// `#[...]` attribute syntax is not supported — see `Token::Error`.
478    DocComment {
479        /// The comment's text: the doc-attribute string literal's value verbatim (including its
480        /// leading space), e.g. `" the total"` for `/// the total`.
481        text: String,
482        /// `true` for `//!`/`#![doc]` (inner), `false` for `///`/`#[doc]` (outer).
483        inner: bool,
484        /// The `#` token's span.
485        span: Span,
486    },
487
488    /// An unsupported attribute shape or a literal Syn cannot parse.
489    Error {
490        /// A description of what was expected instead.
491        message: String,
492        /// Where the mismatch was detected.
493        span: Span,
494    },
495}
496
497impl HasSpan for Token {
498    /// Returns the token's preserved source or diagnostic span.
499    fn span(&self) -> Span {
500        match self {
501            Token::Literal(lit) => lit.span(),
502            Token::Identifier(ident) => ident.span(),
503            Token::Punct { span, .. } => *span,
504            Token::OpenDelim { span, .. } => *span,
505            Token::CloseDelim { span, .. } => *span,
506            Token::DocComment { span, .. } => *span,
507            Token::Error { span, .. } => *span,
508        }
509    }
510}
511
512impl HasSpan for TokenTree {
513    /// Returns the source span of any token-tree variant.
514    fn span(&self) -> Span {
515        TokenTree::span(self)
516    }
517}
518
519impl Iterator for LexLexer {
520    type Item = Token;
521
522    /// Returns the next flattened token or `None` after exhausting the input.
523    ///
524    /// - Complexity: O(n) time and space for the consumed token payload; entering
525    ///   a group also retains its iterator and may grow the O(d) nesting stack.
526    fn next(&mut self) -> Option<Self::Item> {
527        if let Some((delimiter, span)) = self.pending_close.take() {
528            return Some(Token::CloseDelim { delimiter, span });
529        }
530
531        let token = match self.next_token_tree() {
532            Some(token) => token,
533            None => {
534                return self
535                    .pending_close
536                    .take()
537                    .map(|(delimiter, span)| Token::CloseDelim { delimiter, span });
538            }
539        };
540
541        Some(match token {
542            TokenTree::Group(group) => {
543                let delimiter = group.delimiter();
544                let span = group.span();
545                self.group_stack.push(GroupLevel {
546                    iter: group.stream().into_iter(),
547                    delimiter,
548                    span,
549                });
550                Token::OpenDelim { delimiter, span }
551            }
552            TokenTree::Punct(punct) if punct.as_char() == '#' => {
553                self.parse_doc_comment_attribute(punct.span())
554            }
555            TokenTree::Punct(punct) => self.combine_punctuation(punct),
556            TokenTree::Literal(literal) => Self::convert_literal(literal),
557            TokenTree::Ident(ident) => Self::convert_identifier(ident),
558        })
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565    use proc_macro2::TokenStream;
566    use std::str::FromStr;
567
568    /// Compares complete character sequences, including non-ASCII characters.
569    #[test]
570    fn punctuation_equality_compares_characters_without_prefix_matches() {
571        let cases = [
572            (PunctOp::One('+'), "+", true),
573            (PunctOp::One('+'), "++", false),
574            (PunctOp::One('+'), "", false),
575            (PunctOp::One('\u{a7}'), "\u{a7}", true),
576            (PunctOp::Two(['&', '&']), "&&", true),
577            (PunctOp::Two(['&', '&']), "&", false),
578            (PunctOp::Two(['&', '&']), "&&&", false),
579            (PunctOp::Two(['&', '&']), "&|", false),
580            (PunctOp::Three(['.', '.', '=']), "..=", true),
581            (PunctOp::Three(['.', '.', '=']), "..", false),
582            (PunctOp::Three(['.', '.', '=']), "..==", false),
583            (PunctOp::Three(['.', '.', '=']), "...", false),
584        ];
585        // Check both supported string comparison interfaces against the same contract.
586        for (op, text, expected) in cases {
587            assert_eq!(op == *text, expected, "{op:?} versus {text:?}");
588            assert_eq!(op == text, expected, "{op:?} versus {text:?}");
589        }
590    }
591
592    /// Preserves the source span of a literal not interpreted by Syn.
593    #[test]
594    fn verbatim_literal_retains_its_span() {
595        let literal = proc_macro2::Literal::from_str("42").unwrap();
596        let literal = Lit::Verbatim(literal);
597        assert_eq!(HasSpan::span(&literal).source_text().as_deref(), Some("42"));
598    }
599
600    /// Clones punctuation values without sharing mutable character storage.
601    #[test]
602    fn punctuation_clones_are_independent_values() {
603        let cases = [
604            (PunctOp::One('+'), "+"),
605            (PunctOp::Two(['&', '&']), "&&"),
606            (PunctOp::Three(['.', '.', '=']), "..="),
607        ];
608        // Mutate each original and its copy independently through their public variants.
609        for (mut original, text) in cases {
610            let mut copied = original.clone();
611            assert!(copied == text);
612            match &mut original {
613                PunctOp::One(c) => *c = '!',
614                PunctOp::Two(chars) => chars[0] = '!',
615                PunctOp::Three(chars) => chars[0] = '!',
616            }
617            assert!(copied == text);
618            copied = PunctOp::One('?');
619            assert!(copied == "?");
620            assert!(original != "?");
621            assert!(original != text);
622        }
623    }
624
625    /// Preserves literal values and spans across every supported literal category.
626    #[test]
627    fn literal_spans_preserve_the_source() {
628        // All literal variants use the same source-span contract.
629        for source in [
630            "42",
631            "1.5",
632            "\"text\"",
633            "b\"bytes\"",
634            "c\"cstr\"",
635            "'x'",
636            "b'x'",
637            "true",
638            "false",
639        ] {
640            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
641            let Some(Token::Literal(literal)) = lexer.next() else {
642                panic!("expected literal for {source}");
643            };
644            assert_eq!(
645                HasSpan::span(&literal).source_text().as_deref(),
646                Some(source)
647            );
648            assert_eq!(
649                HasSpan::span(&Token::Literal(literal))
650                    .source_text()
651                    .as_deref(),
652                Some(source)
653            );
654            assert!(lexer.next().is_none());
655        }
656    }
657
658    /// Preserves token-tree spans for groups, identifiers, punctuation, and literals.
659    #[test]
660    fn token_tree_spans_cover_each_variant() {
661        // Verify delegation for every token-tree variant.
662        for source in ["(x)", "name", "+", "42"] {
663            let tree = TokenStream::from_str(source)
664                .unwrap()
665                .into_iter()
666                .next()
667                .unwrap();
668            assert_eq!(HasSpan::span(&tree).source_text().as_deref(), Some(source));
669        }
670    }
671
672    /// Preserves diagnostic and delimiter spans rather than substituting call-site spans.
673    #[test]
674    fn flattened_tokens_preserve_their_associated_spans() {
675        let cases: &[(&str, &[&str])] = &[
676            ("(x)", &["(x)", "x", "(x)"]),
677            ("&&", &["&"]),
678            ("#[bad]", &["[bad]"]),
679        ];
680        // Group delimiters use group spans; combined punctuation uses its first character.
681        for &(source, spans) in cases {
682            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
683            for &expected in spans {
684                let token = lexer.next().unwrap();
685                assert_eq!(
686                    HasSpan::span(&token).source_text().as_deref(),
687                    Some(expected)
688                );
689            }
690            assert!(lexer.next().is_none());
691        }
692    }
693
694    /// Produces no tokens for empty input, including repeated exhaustion checks.
695    #[test]
696    fn empty_input_remains_exhausted() {
697        let mut lexer = LexLexer::new(TokenStream::new().into_iter());
698        assert!(lexer.next().is_none());
699        assert!(lexer.next().is_none());
700    }
701
702    /// Combines exactly the supported adjacent operators.
703    #[test]
704    fn combines_each_supported_operator() {
705        // Each operator must consume its complete spelling, but not the following identifier.
706        for text in [
707            "&&", "||", "==", "!=", "<=", ">=", "<<", ">>", "->", "=>", ":=", "..", "..=",
708        ] {
709            let input = TokenStream::from_str(&format!("{text} tail")).unwrap();
710            let mut lexer = LexLexer::new(input.into_iter());
711            assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == text));
712            assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "tail"));
713            assert!(lexer.next().is_none());
714        }
715    }
716
717    /// Preserves uncombined lookahead tokens and respects punctuation spacing.
718    #[test]
719    fn punctuation_lookahead_preserves_the_remaining_stream() {
720        let cases: &[(&str, &[&str])] = &[
721            ("& &", &["&", "&"]),
722            (".. =", &["..", "="]),
723            ("..+", &["..", "+"]),
724            ("&&=", &["&&", "="]),
725            ("+=", &["+", "="]),
726            ("...", &["..", "."]),
727        ];
728        // Compare the entire punctuation stream so no lookahead token can disappear.
729        for &(input, expected) in cases {
730            let mut lexer = LexLexer::new(TokenStream::from_str(input).unwrap().into_iter());
731            for &text in expected {
732                assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == text));
733            }
734            assert!(lexer.next().is_none(), "{input}");
735        }
736    }
737
738    /// Emits every empty group's matching delimiters before resuming its parent.
739    #[test]
740    fn empty_groups_preserve_delimiter_order() {
741        let mut lexer = LexLexer::new(TokenStream::from_str("([]{}) tail").unwrap().into_iter());
742        let expected = [
743            (true, Delimiter::Parenthesis),
744            (true, Delimiter::Bracket),
745            (false, Delimiter::Bracket),
746            (true, Delimiter::Brace),
747            (false, Delimiter::Brace),
748            (false, Delimiter::Parenthesis),
749        ];
750        // Verify both delimiter kind and nesting order.
751        for (open, expected_delimiter) in expected {
752            match lexer.next() {
753                Some(Token::OpenDelim { delimiter, .. }) if open => {
754                    assert_eq!(delimiter, expected_delimiter);
755                }
756                Some(Token::CloseDelim { delimiter, .. }) if !open => {
757                    assert_eq!(delimiter, expected_delimiter);
758                }
759                other => panic!("expected delimiter, got {other:?}"),
760            }
761        }
762        assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "tail"));
763        assert!(lexer.next().is_none());
764    }
765
766    /// Emits a group close after punctuation lookahead or an incomplete attribute.
767    #[test]
768    fn lookahead_does_not_consume_a_group_close() {
769        // Joint punctuation is constructible even when no following token exists.
770        for punctuation in ["&", "..", "#", "#!"] {
771            let group = proc_macro2::Group::new(
772                Delimiter::Parenthesis,
773                punctuation
774                    .chars()
775                    .map(|ch| TokenTree::Punct(proc_macro2::Punct::new(ch, Spacing::Joint)))
776                    .collect(),
777            );
778            let input: TokenStream = [
779                TokenTree::Group(group),
780                TokenTree::Ident(Ident::new("tail", Span::call_site())),
781            ]
782            .into_iter()
783            .collect();
784            let mut lexer = LexLexer::new(input.into_iter());
785            assert!(matches!(lexer.next(), Some(Token::OpenDelim { .. })));
786            match lexer.next() {
787                Some(Token::Punct { op, .. }) if !punctuation.starts_with('#') => {
788                    assert!(op == punctuation);
789                }
790                Some(Token::Error { message, .. }) if punctuation.starts_with('#') => {
791                    assert!(!message.is_empty());
792                }
793                other => panic!("expected punctuation or attribute error, got {other:?}"),
794            }
795            assert!(matches!(lexer.next(), Some(Token::CloseDelim { .. })));
796            assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "tail"));
797            assert!(lexer.next().is_none());
798        }
799    }
800
801    /// Emits delimiters for invisible groups without combining across their boundaries.
802    #[test]
803    fn invisible_groups_bound_operator_combining() {
804        let contents = [
805            TokenTree::Punct(proc_macro2::Punct::new('.', Spacing::Joint)),
806            TokenTree::Punct(proc_macro2::Punct::new('.', Spacing::Joint)),
807        ]
808        .into_iter()
809        .collect();
810        let input: TokenStream = [
811            TokenTree::Group(proc_macro2::Group::new(Delimiter::None, contents)),
812            TokenTree::Punct(proc_macro2::Punct::new('=', Spacing::Alone)),
813        ]
814        .into_iter()
815        .collect();
816        let mut lexer = LexLexer::new(input.into_iter());
817        assert!(matches!(
818            lexer.next(),
819            Some(Token::OpenDelim {
820                delimiter: Delimiter::None,
821                ..
822            })
823        ));
824        assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == ".."));
825        assert!(matches!(
826            lexer.next(),
827            Some(Token::CloseDelim {
828                delimiter: Delimiter::None,
829                ..
830            })
831        ));
832        assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == "="));
833        assert!(lexer.next().is_none());
834    }
835
836    /// Reports incomplete attributes at end of input without terminating iteration early.
837    #[test]
838    fn incomplete_attributes_at_end_of_input_report_errors() {
839        // Neither form supplies the required bracket group.
840        for source in ["#", "#!"] {
841            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
842            assert!(
843                matches!(lexer.next(), Some(Token::Error { message, .. }) if !message.is_empty())
844            );
845            assert!(lexer.next().is_none());
846            assert!(lexer.next().is_none());
847        }
848    }
849
850    /// Decodes explicit documentation strings while preserving the inner marker.
851    #[test]
852    fn explicit_documentation_attributes_decode_string_values() {
853        let input =
854            TokenStream::from_str(r##"#[doc = "line\nnext"] #![doc = r#" raw "#]"##).unwrap();
855        let mut lexer = LexLexer::new(input.into_iter());
856        assert!(
857            matches!(lexer.next(), Some(Token::DocComment { text, inner: false, .. })
858                if text == "line\nnext")
859        );
860        assert!(
861            matches!(lexer.next(), Some(Token::DocComment { text, inner: true, .. })
862                if text == " raw ")
863        );
864        assert!(lexer.next().is_none());
865    }
866
867    /// Reports each malformed attribute shape without losing the next outer token.
868    #[test]
869    fn malformed_attributes_report_errors_and_resume() {
870        // Attribute contents are untrusted input, not caller preconditions.
871        for input in [
872            "#[] tail",
873            "#[doc] tail",
874            "#[doc \"x\"] tail",
875            "#[doc =] tail",
876            "#[doc = value] tail",
877            "#[doc = b\"x\"] tail",
878            "#![doc = 1] tail",
879            "#[doc = \"x\" extra] tail",
880        ] {
881            let mut lexer = LexLexer::new(TokenStream::from_str(input).unwrap().into_iter());
882            assert!(
883                matches!(lexer.next(), Some(Token::Error { message, .. }) if !message.is_empty()),
884                "{input}"
885            );
886            assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "tail"));
887            assert!(lexer.next().is_none());
888        }
889    }
890
891    /// Recognizes booleans without treating raw or longer identifiers as literals.
892    #[test]
893    fn boolean_recognition_preserves_other_identifiers() {
894        let input = TokenStream::from_str("true false r#true true_value").unwrap();
895        let mut lexer = LexLexer::new(input.into_iter());
896        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Bool(lit))) if lit.value));
897        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Bool(lit))) if !lit.value));
898        assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "r#true"));
899        assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "true_value"));
900        assert!(lexer.next().is_none());
901    }
902
903    /// Recognizes an integer literal.
904    #[test]
905    fn test_literal_integer() {
906        let input = TokenStream::from_str("42").unwrap();
907        let mut lexer = LexLexer::new(input.into_iter());
908
909        let token = lexer.next().unwrap();
910        match token {
911            Token::Literal(Lit::Int(..)) => {}
912            _ => panic!("Expected integer literal, got {:?}", token),
913        }
914    }
915
916    /// Recognizes a string literal.
917    #[test]
918    fn test_literal_string() {
919        let input = TokenStream::from_str(r#""hello""#).unwrap();
920        let mut lexer = LexLexer::new(input.into_iter());
921
922        let token = lexer.next().unwrap();
923        match token {
924            Token::Literal(Lit::Str(..)) => {}
925            _ => panic!("Expected string literal"),
926        }
927    }
928
929    /// Recognizes both boolean keyword values.
930    #[test]
931    fn test_literal_boolean() {
932        // Test 'true' boolean literal
933        let input = TokenStream::from_str("true").unwrap();
934        let mut lexer = LexLexer::new(input.into_iter());
935
936        let token = lexer.next().unwrap();
937        match token {
938            Token::Literal(Lit::Bool(lit_bool)) => {
939                assert!(lit_bool.value);
940            }
941            _ => panic!("Expected boolean literal for 'true', got {:?}", token),
942        }
943
944        // Test 'false' boolean literal
945        let input = TokenStream::from_str("false").unwrap();
946        let mut lexer = LexLexer::new(input.into_iter());
947
948        let token = lexer.next().unwrap();
949        match token {
950            Token::Literal(Lit::Bool(lit_bool)) => {
951                assert!(!lit_bool.value);
952            }
953            _ => panic!("Expected boolean literal for 'false', got {:?}", token),
954        }
955    }
956
957    /// Recognizes a floating-point literal.
958    #[test]
959    fn test_literal_float() {
960        let input = TokenStream::from_str("3.14").unwrap();
961        let mut lexer = LexLexer::new(input.into_iter());
962
963        let token = lexer.next().unwrap();
964        match token {
965            Token::Literal(Lit::Float(..)) => {}
966            _ => panic!("Expected float literal"),
967        }
968    }
969
970    /// Preserves valid signed and unsigned exponent spellings and spans.
971    #[test]
972    fn exponent_sign_precedes_underscores_in_float_tokens() {
973        for (source, expected) in [
974            ("1e+_2f64", 100.0),
975            ("1e__2f64", 100.0),
976            ("1e-__2f64", 0.01),
977            ("1.0E+__2f64", 100.0),
978            ("1e+_2f32", 100.0),
979        ] {
980            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
981            let Some(Token::Literal(Lit::Float(literal))) = lexer.next() else {
982                panic!("{source} must lex as a float");
983            };
984            assert_eq!(literal.base10_parse::<f64>().unwrap(), expected, "{source}");
985            assert_eq!(literal.to_string(), source);
986            assert_eq!(literal.span().source_text().as_deref(), Some(source));
987            assert!(lexer.next().is_none());
988        }
989    }
990
991    /// Rejects exponent signs preceded by underscores without losing the source span.
992    #[test]
993    fn exponent_sign_after_underscores_is_not_a_float_token() {
994        for source in [
995            "1e_+2f64",
996            "1e__-2f64",
997            "1e_+_2f64",
998            "1.0e_+2f64",
999            "1E__+2f64",
1000            "1e_+2f32",
1001            "1_e_+_2",
1002        ] {
1003            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
1004            let Some(Token::Error { span, .. }) = lexer.next() else {
1005                panic!("{source} must be a lexical error");
1006            };
1007            assert_eq!(span.source_text().as_deref(), Some(source));
1008        }
1009    }
1010
1011    /// Recognizes suffixed decimal float tokens without changing their source.
1012    #[test]
1013    fn integer_form_float_tokens_preserve_spelling_and_span() {
1014        for (source, suffix, expected) in [
1015            ("1f64", "f64", 1.0),
1016            ("1_f64", "f64", 1.0),
1017            ("0f64", "f64", 0.0),
1018            ("1__f64", "f64", 1.0),
1019            ("1_000f64", "f64", 1000.0),
1020            ("9007199254740993f64", "f64", 9007199254740992.0),
1021            (
1022                "340_282_366_920_938_463_463_374_607_431_768_211_456f64",
1023                "f64",
1024                2.0f64.powi(128),
1025            ),
1026            ("1f32", "f32", 1.0),
1027        ] {
1028            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
1029            let Some(Token::Literal(Lit::Float(literal))) = lexer.next() else {
1030                panic!("{source} must lex as a float");
1031            };
1032            assert_eq!(literal.suffix(), suffix, "{source}");
1033            assert_eq!(literal.base10_parse::<f64>().unwrap(), expected, "{source}");
1034            assert_eq!(literal.to_string(), source);
1035            assert_eq!(literal.span().source_text().as_deref(), Some(source));
1036            assert!(lexer.next().is_none());
1037        }
1038    }
1039
1040    /// Leaves nondecimal and differently suffixed tokens classified as integers.
1041    #[test]
1042    fn integer_form_float_tokens_preserve_integer_boundaries() {
1043        for (source, suffix) in [
1044            ("0x1f64", ""),
1045            ("0b1f64", "f64"),
1046            ("0o7_f64", "f64"),
1047            ("0b1f32", "f32"),
1048            ("0o7_f32", "f32"),
1049            ("1f64x", "f64x"),
1050            ("1f64_", "f64_"),
1051            ("1f640", "f640"),
1052            ("1f32x", "f32x"),
1053        ] {
1054            let mut lexer = LexLexer::new(TokenStream::from_str(source).unwrap().into_iter());
1055            let Some(Token::Literal(Lit::Int(literal))) = lexer.next() else {
1056                panic!("{source} must remain an integer token");
1057            };
1058            assert_eq!(literal.suffix(), suffix, "{source}");
1059            assert_eq!(literal.to_string(), source);
1060            assert_eq!(literal.span().source_text().as_deref(), Some(source));
1061            assert!(lexer.next().is_none());
1062        }
1063    }
1064
1065    /// Keeps range punctuation separate from adjacent suffixed float tokens.
1066    #[test]
1067    fn integer_form_float_tokens_preserve_adjacent_range_punctuation() {
1068        let input = TokenStream::from_str("1f64..=2f64").unwrap();
1069        let mut lexer = LexLexer::new(input.into_iter());
1070        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Float(lit)))
1071            if lit.to_string() == "1f64" && lit.span().source_text().as_deref() == Some("1f64")));
1072        assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == "..="));
1073        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Float(lit)))
1074            if lit.to_string() == "2f64" && lit.span().source_text().as_deref() == Some("2f64")));
1075        assert!(lexer.next().is_none());
1076    }
1077
1078    /// Preserves an identifier's spelling.
1079    #[test]
1080    fn test_identifier() {
1081        let input = TokenStream::from_str("foo").unwrap();
1082        let mut lexer = LexLexer::new(input.into_iter());
1083
1084        let token = lexer.next().unwrap();
1085        match token {
1086            Token::Identifier(ident) => {
1087                assert_eq!(ident.to_string(), "foo");
1088            }
1089            _ => panic!("Expected identifier"),
1090        }
1091    }
1092
1093    /// Emits a single punctuation character.
1094    #[test]
1095    fn test_punct() {
1096        let input = TokenStream::from_str("+").unwrap();
1097        let mut lexer = LexLexer::new(input.into_iter());
1098
1099        let token = lexer.next().unwrap();
1100        match token {
1101            Token::Punct { op, .. } => {
1102                assert!(op == "+");
1103            }
1104            _ => panic!("Expected punctuation"),
1105        }
1106    }
1107
1108    /// Combines a logical operator between identifiers.
1109    #[test]
1110    fn test_compound_operator() {
1111        let input = TokenStream::from_str("a && b").unwrap();
1112        let lexer = LexLexer::new(input.into_iter());
1113
1114        let tokens: Vec<_> = lexer.collect();
1115        assert_eq!(tokens.len(), 3);
1116
1117        match &tokens[1] {
1118            Token::Punct { op, .. } => {
1119                assert!(op == "&&");
1120            }
1121            _ => panic!("Expected && operator"),
1122        }
1123    }
1124
1125    /// Emits matching delimiters around a group's flattened contents.
1126    #[test]
1127    fn test_group_flattening() {
1128        let input = TokenStream::from_str("(10 + 20)").unwrap();
1129        let lexer = LexLexer::new(input.into_iter());
1130
1131        // Should get: OpenDelim, Integer, Punct, Integer, CloseDelim
1132        let tokens: Vec<_> = lexer.collect();
1133        assert_eq!(tokens.len(), 5);
1134
1135        assert!(matches!(
1136            tokens[0],
1137            Token::OpenDelim {
1138                delimiter: Delimiter::Parenthesis,
1139                ..
1140            }
1141        ));
1142        assert!(matches!(tokens[1], Token::Literal(Lit::Int(..))));
1143        assert!(matches!(&tokens[2], Token::Punct { op, .. } if op == "+"));
1144        assert!(matches!(tokens[3], Token::Literal(Lit::Int(..))));
1145        assert!(matches!(
1146            tokens[4],
1147            Token::CloseDelim {
1148                delimiter: Delimiter::Parenthesis,
1149                ..
1150            }
1151        ));
1152    }
1153
1154    /// Preserves the nesting order of groups and their contents.
1155    #[test]
1156    fn test_nested_groups() {
1157        let input = TokenStream::from_str("(10 + (20 * 30))").unwrap();
1158        let lexer = LexLexer::new(input.into_iter());
1159
1160        let tokens: Vec<_> = lexer.collect();
1161
1162        // Should have: OpenDelim, 10, +, OpenDelim, 20, *, 30, CloseDelim, CloseDelim
1163        assert_eq!(tokens.len(), 9);
1164
1165        // Verify structure
1166        assert!(matches!(tokens[0], Token::OpenDelim { .. }));
1167        assert!(matches!(tokens[1], Token::Literal(Lit::Int(..))));
1168        assert!(matches!(&tokens[2], Token::Punct { op, .. } if op == "+"));
1169        assert!(matches!(tokens[3], Token::OpenDelim { .. }));
1170        assert!(matches!(tokens[4], Token::Literal(Lit::Int(..))));
1171        assert!(matches!(&tokens[5], Token::Punct { op, .. } if op == "*"));
1172        assert!(matches!(tokens[6], Token::Literal(Lit::Int(..))));
1173        assert!(matches!(tokens[7], Token::CloseDelim { .. }));
1174        assert!(matches!(tokens[8], Token::CloseDelim { .. }));
1175    }
1176
1177    /// Retains an identifier's source span.
1178    #[test]
1179    fn test_span_preservation() {
1180        let input = TokenStream::from_str("foo").unwrap();
1181        let mut lexer = LexLexer::new(input.into_iter());
1182
1183        let token = lexer.next().unwrap();
1184
1185        // HasSpan trait should provide span
1186        let span = HasSpan::span(&token);
1187        assert!(!span.source_text().unwrap_or_default().is_empty());
1188    }
1189
1190    /// Preserves the order of identifiers, punctuation, and literals.
1191    #[test]
1192    fn test_mixed_tokens() {
1193        let input = TokenStream::from_str("foo + 42").unwrap();
1194        let lexer = LexLexer::new(input.into_iter());
1195
1196        let tokens: Vec<_> = lexer.collect();
1197        assert_eq!(tokens.len(), 3);
1198
1199        assert!(matches!(tokens[0], Token::Identifier(_)));
1200        assert!(matches!(&tokens[1], Token::Punct { op, .. } if op == "+"));
1201        assert!(matches!(tokens[2], Token::Literal(Lit::Int(..))));
1202    }
1203
1204    /// Emits an arrow as one operator.
1205    #[test]
1206    fn arrow_is_two_char_punct() {
1207        let stream: TokenStream = "->".parse().unwrap();
1208        let mut lexer = LexLexer::new(stream.into_iter());
1209        let tok = lexer.next().expect("one token");
1210        assert!(
1211            matches!(
1212                tok,
1213                Token::Punct {
1214                    op: PunctOp::Two(['-', '>']),
1215                    ..
1216                }
1217            ),
1218            "expected PunctOp::Two([\"->\"])), got {tok:?}"
1219        );
1220        assert!(lexer.next().is_none(), "expected no more tokens");
1221    }
1222
1223    /// Emits a fat arrow as one operator.
1224    #[test]
1225    fn fat_arrow_is_two_char_punct() {
1226        let stream: TokenStream = "=>".parse().unwrap();
1227        let mut lexer = LexLexer::new(stream.into_iter());
1228        let tok = lexer.next().expect("one token");
1229        assert!(
1230            matches!(
1231                tok,
1232                Token::Punct {
1233                    op: PunctOp::Two(['=', '>']),
1234                    ..
1235                }
1236            ),
1237            "expected PunctOp::Two([\"=>\"]), got {tok:?}"
1238        );
1239        assert!(lexer.next().is_none(), "expected no more tokens");
1240    }
1241
1242    /// Preserves outer documentation text and its outer marker.
1243    #[test]
1244    fn recognizes_an_outer_doc_comment() {
1245        let input = TokenStream::from_str("/// the total").unwrap();
1246        let mut lexer = LexLexer::new(input.into_iter());
1247        let token = lexer.next().unwrap();
1248        match token {
1249            Token::DocComment { text, inner, .. } => {
1250                assert_eq!(text, " the total");
1251                assert!(!inner);
1252            }
1253            other => panic!("expected DocComment, got {other:?}"),
1254        }
1255        assert!(lexer.next().is_none());
1256    }
1257
1258    /// Preserves inner documentation text and its inner marker.
1259    #[test]
1260    fn recognizes_an_inner_doc_comment() {
1261        let input = TokenStream::from_str("//! module docs").unwrap();
1262        let mut lexer = LexLexer::new(input.into_iter());
1263        let token = lexer.next().unwrap();
1264        match token {
1265            Token::DocComment { text, inner, .. } => {
1266                assert_eq!(text, " module docs");
1267                assert!(inner);
1268            }
1269            other => panic!("expected DocComment, got {other:?}"),
1270        }
1271    }
1272
1273    /// Resumes ordinary tokenization after documentation.
1274    #[test]
1275    fn doc_comment_run_is_followed_by_the_next_real_token() {
1276        let input = TokenStream::from_str("/// x\ncell").unwrap();
1277        let mut lexer = LexLexer::new(input.into_iter());
1278        assert!(matches!(lexer.next(), Some(Token::DocComment { .. })));
1279        match lexer.next() {
1280            Some(Token::Identifier(ident)) => assert_eq!(ident.to_string(), "cell"),
1281            other => panic!("expected Identifier(cell), got {other:?}"),
1282        }
1283    }
1284
1285    /// Rejects a non-documentation attribute.
1286    #[test]
1287    fn a_non_doc_attribute_is_a_lex_error() {
1288        let input = TokenStream::from_str("#[foo]").unwrap();
1289        let mut lexer = LexLexer::new(input.into_iter());
1290        let token = lexer.next().unwrap();
1291        assert!(
1292            matches!(token, Token::Error { .. }),
1293            "expected Error, got {token:?}"
1294        );
1295    }
1296
1297    /// Rejects a numeric documentation value.
1298    #[test]
1299    fn a_non_string_doc_value_is_a_lex_error() {
1300        let input = TokenStream::from_str("#[doc = 5]").unwrap();
1301        let mut lexer = LexLexer::new(input.into_iter());
1302        let token = lexer.next().unwrap();
1303        assert!(
1304            matches!(token, Token::Error { .. }),
1305            "expected Error, got {token:?}"
1306        );
1307    }
1308
1309    /// Rejects an attribute marker followed by an identifier instead of a group.
1310    #[test]
1311    fn a_bare_hash_with_no_group_is_a_lex_error() {
1312        let input = TokenStream::from_str("# foo").unwrap();
1313        let mut lexer = LexLexer::new(input.into_iter());
1314        let token = lexer.next().unwrap();
1315        assert!(
1316            matches!(token, Token::Error { .. }),
1317            "expected Error, got {token:?}"
1318        );
1319    }
1320
1321    /// Rejects an attribute group with parentheses instead of brackets.
1322    #[test]
1323    fn a_hash_led_group_with_the_wrong_delimiter_is_a_lex_error() {
1324        let input = TokenStream::from_str("#(foo)").unwrap();
1325        let mut lexer = LexLexer::new(input.into_iter());
1326        let token = lexer.next().unwrap();
1327        assert!(
1328            matches!(token, Token::Error { .. }),
1329            "expected Error, got {token:?}"
1330        );
1331    }
1332
1333    /// Rejects trailing tokens in a documentation attribute.
1334    #[test]
1335    fn extra_tokens_after_the_doc_string_are_a_lex_error() {
1336        let input = TokenStream::from_str("#[doc = \"x\", extra]").unwrap();
1337        let mut lexer = LexLexer::new(input.into_iter());
1338        let token = lexer.next().unwrap();
1339        assert!(
1340            matches!(token, Token::Error { .. }),
1341            "expected Error, got {token:?}"
1342        );
1343    }
1344
1345    /// Retains a documentation comment's source span.
1346    #[test]
1347    fn doc_comment_token_has_a_span() {
1348        let input = TokenStream::from_str("/// x").unwrap();
1349        let mut lexer = LexLexer::new(input.into_iter());
1350        let token = lexer.next().unwrap();
1351        let span = HasSpan::span(&token);
1352        assert!(!span.source_text().unwrap_or_default().is_empty());
1353    }
1354
1355    /// Emits the assignment operator as one token.
1356    #[test]
1357    fn walrus_operator_lexes_as_one_compound_token() {
1358        let stream: TokenStream = ":=".parse().unwrap();
1359        let mut lexer = LexLexer::new(stream.into_iter());
1360        let token = lexer.next().expect("one token");
1361        assert!(matches!(
1362            token,
1363            Token::Punct { ref op, .. } if op == ":="
1364        ));
1365        assert!(lexer.next().is_none());
1366    }
1367
1368    /// Preserves an identifier following a lone colon.
1369    #[test]
1370    fn colon_followed_by_non_equals_stays_two_separate_tokens() {
1371        let stream: TokenStream = ": x".parse().unwrap();
1372        let mut lexer = LexLexer::new(stream.into_iter());
1373        let first = lexer.next().expect("colon token");
1374        assert!(matches!(first, Token::Punct { ref op, .. } if op == ":"));
1375        assert!(matches!(lexer.next(), Some(Token::Identifier(id)) if id == "x"));
1376        assert!(lexer.next().is_none());
1377    }
1378
1379    /// Keeps the endpoints of a range as integer literals.
1380    #[test]
1381    fn digit_followed_by_double_dot_does_not_lex_as_a_float_literal() {
1382        let input = TokenStream::from_str("5..10").unwrap();
1383        let mut lexer = LexLexer::new(input.into_iter());
1384        match lexer.next() {
1385            Some(Token::Literal(Lit::Int(lit))) => {
1386                assert_eq!(lit.base10_parse::<i32>().unwrap(), 5)
1387            }
1388            other => panic!("expected an integer literal, got {other:?}"),
1389        }
1390        assert!(matches!(lexer.next(), Some(Token::Punct { op, .. }) if op == ".."));
1391        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Int(lit)))
1392                if lit.base10_parse::<i32>().unwrap() == 10));
1393        assert!(lexer.next().is_none());
1394    }
1395
1396    /// Emits an exclusive range operator as one token.
1397    #[test]
1398    fn double_dot_combines_into_two_char_punct() {
1399        let stream: TokenStream = "..".parse().unwrap();
1400        let mut lexer = LexLexer::new(stream.into_iter());
1401        let tok = lexer.next().expect("one token");
1402        assert!(
1403            matches!(
1404                tok,
1405                Token::Punct {
1406                    op: PunctOp::Two(['.', '.']),
1407                    ..
1408                }
1409            ),
1410            "expected PunctOp::Two(['.', '.']), got {tok:?}"
1411        );
1412        assert!(lexer.next().is_none(), "expected no more tokens");
1413    }
1414
1415    /// Emits an inclusive range operator as one token.
1416    #[test]
1417    fn double_dot_equals_combines_into_three_char_punct() {
1418        let stream: TokenStream = "..=".parse().unwrap();
1419        let mut lexer = LexLexer::new(stream.into_iter());
1420        let tok = lexer.next().expect("one token");
1421        assert!(
1422            matches!(
1423                tok,
1424                Token::Punct {
1425                    op: PunctOp::Three(['.', '.', '=']),
1426                    ..
1427                }
1428            ),
1429            "expected PunctOp::Three(['.', '.', '=']), got {tok:?}"
1430        );
1431        assert!(lexer.next().is_none(), "expected no more tokens");
1432    }
1433
1434    /// Preserves the literal after an exclusive range operator.
1435    #[test]
1436    fn double_dot_not_followed_by_equals_stays_two_char_and_does_not_consume_the_next_token() {
1437        let stream: TokenStream = "..5".parse().unwrap();
1438        let mut lexer = LexLexer::new(stream.into_iter());
1439        let first = lexer.next().expect("dot-dot token");
1440        assert!(
1441            matches!(
1442                first,
1443                Token::Punct {
1444                    op: PunctOp::Two(['.', '.']),
1445                    ..
1446                }
1447            ),
1448            "expected PunctOp::Two(['.', '.']), got {first:?}"
1449        );
1450        match lexer.next() {
1451            Some(Token::Literal(Lit::Int(lit))) => {
1452                assert_eq!(lit.base10_parse::<i32>().unwrap(), 5)
1453            }
1454            other => panic!("expected integer literal 5, got {other:?}"),
1455        }
1456    }
1457
1458    /// Preserves an integer field index after a single dot.
1459    #[test]
1460    fn single_dot_before_a_digit_is_unaffected_by_range_combining() {
1461        // Regression guard: tuple field access (`x.0`) must still lex as a lone `.` Punct
1462        // followed by an integer literal, not get swept into the new `..`/`..=` combining.
1463        let stream: TokenStream = ".0".parse().unwrap();
1464        let mut lexer = LexLexer::new(stream.into_iter());
1465        let first = lexer.next().expect("dot token");
1466        assert!(
1467            matches!(
1468                first,
1469                Token::Punct {
1470                    op: PunctOp::One('.'),
1471                    ..
1472                }
1473            ),
1474            "expected PunctOp::One('.'), got {first:?}"
1475        );
1476        assert!(matches!(lexer.next(), Some(Token::Literal(Lit::Int(lit)))
1477                if lit.base10_parse::<i32>().unwrap() == 0));
1478        assert!(lexer.next().is_none());
1479    }
1480}