Skip to main content

rustc_parse/lexer/
mod.rs

1use diagnostics::make_errors_for_mismatched_closing_delims;
2use rustc_ast::ast::{self, AttrStyle};
3use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
4use rustc_ast::tokenstream::TokenStream;
5use rustc_ast::util::unicode::{TEXT_FLOW_CONTROL_CHARS, contains_text_flow_control_chars};
6use rustc_errors::codes::*;
7use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, StashKey};
8use rustc_lexer::{
9    Base, Cursor, DocStyle, FrontmatterAllowed, LiteralKind, RawStrError, is_horizontal_whitespace,
10};
11use rustc_lint_defs::builtin::{
12    RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, RUST_2024_GUARDED_STRING_INCOMPATIBLE_SYNTAX,
13    TEXT_DIRECTION_CODEPOINT_IN_COMMENT, TEXT_DIRECTION_CODEPOINT_IN_LITERAL,
14};
15use rustc_literal_escaper::{EscapeError, Mode, check_for_errors};
16use rustc_session::parse::ParseSess;
17use rustc_span::edition::Edition;
18use rustc_span::{BytePos, Pos, Span, Symbol, sym};
19use tracing::debug;
20
21use crate::lexer::diagnostics::TokenTreeDiagInfo;
22use crate::lexer::unicode_chars::UNICODE_ARRAY;
23
24mod diagnostics;
25mod tokentrees;
26mod unescape_error_reporting;
27mod unicode_chars;
28
29use unescape_error_reporting::{emit_unescape_error, escaped_char};
30
31// This type is used a lot. Make sure it doesn't unintentionally get bigger.
32//
33// This assertion is in this crate, rather than in `rustc_lexer`, because that
34// crate cannot depend on `rustc_data_structures`.
35#[cfg(target_pointer_width = "64")]
36const _: [(); 12] = [(); ::std::mem::size_of::<rustc_lexer::Token>()];rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12);
37
38const INVISIBLE_CHARACTERS: [char; 8] = [
39    '\u{200b}', '\u{200c}', '\u{2060}', '\u{2061}', '\u{2062}', '\u{00ad}', '\u{034f}', '\u{061c}',
40];
41
42#[derive(#[automatically_derived]
impl ::core::clone::Clone for UnmatchedDelim {
    #[inline]
    fn clone(&self) -> UnmatchedDelim {
        UnmatchedDelim {
            found_delim: ::core::clone::Clone::clone(&self.found_delim),
            found_span: ::core::clone::Clone::clone(&self.found_span),
            unclosed_span: ::core::clone::Clone::clone(&self.unclosed_span),
            candidate_span: ::core::clone::Clone::clone(&self.candidate_span),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UnmatchedDelim {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "UnmatchedDelim", "found_delim", &self.found_delim, "found_span",
            &self.found_span, "unclosed_span", &self.unclosed_span,
            "candidate_span", &&self.candidate_span)
    }
}Debug)]
43pub(crate) struct UnmatchedDelim {
44    pub found_delim: Option<Delimiter>,
45    pub found_span: Span,
46    pub unclosed_span: Option<Span>,
47    pub candidate_span: Option<Span>,
48}
49
50/// Which tokens should be stripped before lexing the tokens.
51pub enum StripTokens {
52    /// Strip both shebang and frontmatter.
53    ShebangAndFrontmatter,
54    /// Strip the shebang but not frontmatter.
55    ///
56    /// That means that char sequences looking like frontmatter are simply
57    /// interpreted as regular Rust lexemes.
58    Shebang,
59    /// Strip nothing.
60    ///
61    /// In other words, char sequences looking like a shebang or frontmatter
62    /// are simply interpreted as regular Rust lexemes.
63    Nothing,
64}
65
66pub(crate) fn lex_token_trees<'psess, 'src>(
67    psess: &'psess ParseSess,
68    mut src: &'src str,
69    mut start_pos: BytePos,
70    override_span: Option<Span>,
71    strip_tokens: StripTokens,
72) -> Result<TokenStream, Vec<Diag<'psess>>> {
73    match strip_tokens {
74        StripTokens::Shebang | StripTokens::ShebangAndFrontmatter => {
75            if let Some(shebang_len) = rustc_lexer::strip_shebang(src) {
76                src = &src[shebang_len..];
77                start_pos = start_pos + BytePos::from_usize(shebang_len);
78            }
79        }
80        StripTokens::Nothing => {}
81    }
82
83    let frontmatter_allowed = match strip_tokens {
84        StripTokens::ShebangAndFrontmatter => FrontmatterAllowed::Yes,
85        StripTokens::Shebang | StripTokens::Nothing => FrontmatterAllowed::No,
86    };
87
88    let cursor = Cursor::new(src, frontmatter_allowed);
89    let mut lexer = Lexer {
90        psess,
91        start_pos,
92        pos: start_pos,
93        src,
94        cursor,
95        override_span,
96        nbsp_is_whitespace: false,
97        last_lifetime: None,
98        token: Token::dummy(),
99        diag_info: TokenTreeDiagInfo::default(),
100    };
101    let res = lexer.lex_token_trees(/* is_delimited */ false);
102
103    let mut unmatched_closing_delims: Vec<_> =
104        make_errors_for_mismatched_closing_delims(&lexer.diag_info.unmatched_delims, psess);
105
106    match res {
107        Ok((_open_spacing, stream)) => {
108            if unmatched_closing_delims.is_empty() {
109                Ok(stream)
110            } else {
111                // Return error if there are unmatched delimiters or unclosed delimiters.
112                Err(unmatched_closing_delims)
113            }
114        }
115        Err(errs) => {
116            // We emit delimiter mismatch errors first, then emit the unclosing delimiter mismatch
117            // because the delimiter mismatch is more likely to be the root cause of error
118            unmatched_closing_delims.push(errs);
119            Err(unmatched_closing_delims)
120        }
121    }
122}
123
124struct Lexer<'psess, 'src> {
125    psess: &'psess ParseSess,
126    /// Initial position, read-only.
127    start_pos: BytePos,
128    /// The absolute offset within the source_map of the current character.
129    pos: BytePos,
130    /// Source text to tokenize.
131    src: &'src str,
132    /// Cursor for getting lexer tokens.
133    cursor: Cursor<'src>,
134    override_span: Option<Span>,
135    /// When a "unknown start of token: \u{a0}" has already been emitted earlier
136    /// in this file, it's safe to treat further occurrences of the non-breaking
137    /// space character as whitespace.
138    nbsp_is_whitespace: bool,
139
140    /// Track the `Span` for the leading `'` of the last lifetime. Used for
141    /// diagnostics to detect possible typo where `"` was meant.
142    last_lifetime: Option<Span>,
143
144    /// The current token.
145    token: Token,
146
147    diag_info: TokenTreeDiagInfo,
148}
149
150impl<'psess, 'src> Lexer<'psess, 'src> {
151    fn dcx(&self) -> DiagCtxtHandle<'psess> {
152        self.psess.dcx()
153    }
154
155    fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
156        self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
157    }
158
159    /// Returns the next token, paired with a bool indicating if the token was
160    /// preceded by whitespace.
161    fn next_token_from_cursor(&mut self) -> (Token, bool) {
162        let mut preceded_by_whitespace = false;
163        let mut swallow_next_invalid = 0;
164        // Skip trivial (whitespace & comments) tokens
165        loop {
166            let str_before = self.cursor.as_str();
167            let token = self.cursor.advance_token();
168            let start = self.pos;
169            self.pos = self.pos + BytePos(token.len);
170
171            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/lexer/mod.rs:171",
                        "rustc_parse::lexer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/lexer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(171u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::lexer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("next_token: {0:?}({1:?})",
                                                    token.kind, self.str_from(start)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("next_token: {:?}({:?})", token.kind, self.str_from(start));
172
173            if let rustc_lexer::TokenKind::Semi
174            | rustc_lexer::TokenKind::LineComment { .. }
175            | rustc_lexer::TokenKind::BlockComment { .. }
176            | rustc_lexer::TokenKind::CloseParen
177            | rustc_lexer::TokenKind::CloseBrace
178            | rustc_lexer::TokenKind::CloseBracket = token.kind
179            {
180                // Heuristic: we assume that it is unlikely we're dealing with an unterminated
181                // string surrounded by single quotes.
182                self.last_lifetime = None;
183            }
184
185            // Now "cook" the token, converting the simple `rustc_lexer::TokenKind` enum into a
186            // rich `rustc_ast::TokenKind`. This turns strings into interned symbols and runs
187            // additional validation.
188            let kind = match token.kind {
189                rustc_lexer::TokenKind::LineComment { doc_style } => {
190                    // Skip non-doc comments
191                    let Some(doc_style) = doc_style else {
192                        self.lint_unicode_text_flow(start);
193                        preceded_by_whitespace = true;
194                        continue;
195                    };
196
197                    // Opening delimiter of the length 3 is not included into the symbol.
198                    let content_start = start + BytePos(3);
199                    let content = self.str_from(content_start);
200                    self.lint_doc_comment_unicode_text_flow(start, content);
201                    self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style)
202                }
203                rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => {
204                    if !terminated {
205                        self.report_unterminated_block_comment(start, doc_style);
206                    }
207
208                    // Skip non-doc comments
209                    let Some(doc_style) = doc_style else {
210                        self.lint_unicode_text_flow(start);
211                        preceded_by_whitespace = true;
212                        continue;
213                    };
214
215                    // Opening delimiter of the length 3 and closing delimiter of the length 2
216                    // are not included into the symbol.
217                    let content_start = start + BytePos(3);
218                    let content_end = self.pos - BytePos(if terminated { 2 } else { 0 });
219                    let content = self.str_from_to(content_start, content_end);
220                    self.lint_doc_comment_unicode_text_flow(start, content);
221                    self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style)
222                }
223                rustc_lexer::TokenKind::Frontmatter { has_invalid_preceding_whitespace, invalid_infostring } => {
224                    self.validate_frontmatter(start, has_invalid_preceding_whitespace, invalid_infostring);
225                    preceded_by_whitespace = true;
226                    continue;
227                }
228                rustc_lexer::TokenKind::Whitespace => {
229                    preceded_by_whitespace = true;
230                    continue;
231                }
232                rustc_lexer::TokenKind::Ident => self.ident(start),
233                rustc_lexer::TokenKind::RawIdent => {
234                    let sym = nfc_normalize(self.str_from(start + BytePos(2)));
235                    let span = self.mk_sp(start, self.pos);
236                    self.psess.symbol_gallery.insert(sym, span);
237                    if !sym.can_be_raw() {
238                        self.dcx().emit_err(crate::diagnostics::CannotBeRawIdent { span, ident: sym });
239                    }
240                    self.psess.raw_identifier_spans.push(span);
241                    token::Ident(sym, IdentIsRaw::Yes)
242                }
243                rustc_lexer::TokenKind::UnknownPrefix => {
244                    self.report_unknown_prefix(start);
245                    self.ident(start)
246                }
247                rustc_lexer::TokenKind::UnknownPrefixLifetime => {
248                    self.report_unknown_prefix(start);
249                    // Include the leading `'` in the real identifier, for macro
250                    // expansion purposes. See #12512 for the gory details of why
251                    // this is necessary.
252                    let lifetime_name = self.str_from(start);
253                    self.last_lifetime = Some(self.mk_sp(start, start + BytePos(1)));
254                    let ident = Symbol::intern(lifetime_name);
255                    token::Lifetime(ident, IdentIsRaw::No)
256                }
257                rustc_lexer::TokenKind::InvalidIdent
258                    // Do not recover an identifier with emoji if the codepoint is a confusable
259                    // with a recoverable substitution token, like `➖`.
260                    if !UNICODE_ARRAY.iter().any(|&(c, _, _)| {
261                        let sym = self.str_from(start);
262                        sym.chars().count() == 1 && c == sym.chars().next().unwrap()
263                    }) =>
264                {
265                    let sym = nfc_normalize(self.str_from(start));
266                    let span = self.mk_sp(start, self.pos);
267                    self.psess
268                        .bad_unicode_identifiers
269                        .borrow_mut()
270                        .entry(sym)
271                        .or_default()
272                        .push(span);
273                    token::Ident(sym, IdentIsRaw::No)
274                }
275                // split up (raw) c string literals to an ident and a string literal when edition <
276                // 2021.
277                rustc_lexer::TokenKind::Literal {
278                    kind: kind @ (LiteralKind::CStr { .. } | LiteralKind::RawCStr { .. }),
279                    suffix_start: _,
280                } if let span = self.mk_sp(start, self.pos) && !span.edition().at_least_rust_2021() => {
281                    let (prefix_len, kind) = match kind {
282                        LiteralKind::CStr { .. } => (1, "C string literal"),
283                        LiteralKind::RawCStr { .. } => (2, "raw C string literal"),
284                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
285                    };
286
287                    // reset the state so that only the prefix ("c" or "cr") was consumed.
288                    self.pos = start + BytePos(prefix_len);
289                    self.cursor = Cursor::new(&str_before[prefix_len as usize..], FrontmatterAllowed::No);
290
291                    self.psess.buffer_lint(
292                        RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
293                        span,
294                        ast::CRATE_NODE_ID,
295                        crate::diagnostics::ReservedPrefixLint {
296                            subject: "this".into(),
297                            kind,
298                            edition: Edition::Edition2021,
299                            sugg: self.mk_sp(start, self.pos).shrink_to_hi(),
300                        },
301                    );
302
303                    self.ident(start)
304                }
305                rustc_lexer::TokenKind::GuardedStrPrefix => {
306                    self.maybe_report_guarded_str(start, str_before)
307                }
308                rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
309                    let suffix_start = start + BytePos(suffix_start);
310                    let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
311                    let suffix = if suffix_start < self.pos {
312                        let string = self.str_from(suffix_start);
313                        if string == "_" {
314                            self.dcx().emit_err(crate::diagnostics::UnderscoreLiteralSuffix {
315                                span: self.mk_sp(suffix_start, self.pos),
316                            });
317                            None
318                        } else {
319                            Some(Symbol::intern(string))
320                        }
321                    } else {
322                        None
323                    };
324                    self.lint_literal_unicode_text_flow(symbol, kind, self.mk_sp(start, self.pos), "literal");
325                    token::Literal(token::Lit { kind, symbol, suffix })
326                }
327                rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
328                    // Include the leading `'` in the real identifier, for macro
329                    // expansion purposes. See #12512 for the gory details of why
330                    // this is necessary.
331                    let lifetime_name = nfc_normalize(self.str_from(start));
332                    self.last_lifetime = Some(self.mk_sp(start, start + BytePos(1)));
333                    if starts_with_number {
334                        let span = self.mk_sp(start, self.pos);
335                        self.dcx()
336                            .struct_err("lifetimes cannot start with a number")
337                            .with_span(span)
338                            .stash(span, StashKey::LifetimeIsChar);
339                    }
340                    token::Lifetime(lifetime_name, IdentIsRaw::No)
341                }
342                rustc_lexer::TokenKind::RawLifetime => {
343                    self.last_lifetime = Some(self.mk_sp(start, start + BytePos(1)));
344
345                    let ident_start = start + BytePos(3);
346                    if self.mk_sp(start, ident_start).at_least_rust_2021() {
347                        // If the raw lifetime is followed by \' then treat it a normal
348                        // lifetime followed by a \', which is to interpret it as a character
349                        // literal. In this case, it's always an invalid character literal
350                        // since the literal must necessarily have >3 characters (r#...) inside
351                        // of it, which is invalid.
352                        if self.cursor.as_str().starts_with('\'') {
353                            let lit_span = self.mk_sp(start, self.pos + BytePos(1));
354                            let contents = self.str_from_to(start + BytePos(1), self.pos);
355                            emit_unescape_error(
356                                self.dcx(),
357                                contents,
358                                lit_span,
359                                lit_span,
360                                Mode::Char,
361                                0..contents.len(),
362                                EscapeError::MoreThanOneChar,
363                            )
364                            .expect("expected error");
365                        }
366
367                        let span = self.mk_sp(start, self.pos);
368
369                        let lifetime_name_without_tick =
370                            Symbol::intern(&self.str_from(ident_start));
371                        if !lifetime_name_without_tick.can_be_raw() {
372                            self.dcx().emit_err(
373                                crate::diagnostics::CannotBeRawLifetime {
374                                    span,
375                                    ident: lifetime_name_without_tick
376                                }
377                            );
378                        }
379
380                        // Put the `'` back onto the lifetime name.
381                        let mut lifetime_name =
382                            String::with_capacity(lifetime_name_without_tick.as_str().len() + 1);
383                        lifetime_name.push('\'');
384                        lifetime_name += lifetime_name_without_tick.as_str();
385                        let sym = nfc_normalize(&lifetime_name);
386
387                        // Make sure we mark this as a raw identifier.
388                        self.psess.raw_identifier_spans.push(span);
389
390                        token::Lifetime(sym, IdentIsRaw::Yes)
391                    } else {
392                        // Reset the state so we just lex the `'r`.
393                        self.pos = start + BytePos(2);
394                        self.cursor = Cursor::new(&str_before[2 as usize..], FrontmatterAllowed::No);
395
396                        let prefix_span = self.mk_sp(start, self.pos);
397                        self.psess.buffer_lint(
398                            RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
399                            prefix_span,
400                            ast::CRATE_NODE_ID,
401                            crate::diagnostics::ReservedPrefixLint {
402                                subject: "`r`".into(),
403                                kind: "prefix",
404                                edition: Edition::Edition2021,
405                                sugg: prefix_span.shrink_to_hi(),
406                            }
407                        );
408
409                        let lifetime_name = nfc_normalize(self.str_from(start));
410                        token::Lifetime(lifetime_name, IdentIsRaw::No)
411                    }
412                }
413                rustc_lexer::TokenKind::Semi => token::Semi,
414                rustc_lexer::TokenKind::Comma => token::Comma,
415                rustc_lexer::TokenKind::Dot => token::Dot,
416                rustc_lexer::TokenKind::OpenParen => token::OpenParen,
417                rustc_lexer::TokenKind::CloseParen => token::CloseParen,
418                rustc_lexer::TokenKind::OpenBrace => token::OpenBrace,
419                rustc_lexer::TokenKind::CloseBrace => token::CloseBrace,
420                rustc_lexer::TokenKind::OpenBracket => token::OpenBracket,
421                rustc_lexer::TokenKind::CloseBracket => token::CloseBracket,
422                rustc_lexer::TokenKind::At => token::At,
423                rustc_lexer::TokenKind::Pound => token::Pound,
424                rustc_lexer::TokenKind::Tilde => token::Tilde,
425                rustc_lexer::TokenKind::Question => token::Question,
426                rustc_lexer::TokenKind::Colon => token::Colon,
427                rustc_lexer::TokenKind::Dollar => token::Dollar,
428                rustc_lexer::TokenKind::Eq => token::Eq,
429                rustc_lexer::TokenKind::Bang => token::Bang,
430                rustc_lexer::TokenKind::Lt => token::Lt,
431                rustc_lexer::TokenKind::Gt => token::Gt,
432                rustc_lexer::TokenKind::Minus => token::Minus,
433                rustc_lexer::TokenKind::And => token::And,
434                rustc_lexer::TokenKind::Or => token::Or,
435                rustc_lexer::TokenKind::Plus => token::Plus,
436                rustc_lexer::TokenKind::Star => token::Star,
437                rustc_lexer::TokenKind::Slash => token::Slash,
438                rustc_lexer::TokenKind::Caret => token::Caret,
439                rustc_lexer::TokenKind::Percent => token::Percent,
440
441                rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
442                    // Don't emit diagnostics for sequences of the same invalid token
443                    if swallow_next_invalid > 0 {
444                        swallow_next_invalid -= 1;
445                        continue;
446                    }
447                    let mut it = self.str_from_to_end(start).chars();
448                    let c = it.next().unwrap();
449                    if c == '\u{00a0}' {
450                        // If an error has already been reported on non-breaking
451                        // space characters earlier in the file, treat all
452                        // subsequent occurrences as whitespace.
453                        if self.nbsp_is_whitespace {
454                            preceded_by_whitespace = true;
455                            continue;
456                        }
457                        self.nbsp_is_whitespace = true;
458                    }
459                    let repeats = it.take_while(|c1| *c1 == c).count();
460                    // FIXME: the lexer could be used to turn the ASCII version of unicode
461                    // homoglyphs, instead of keeping a table in `check_for_substitution`into the
462                    // token. Ideally, this should be inside `rustc_lexer`. However, we should
463                    // first remove compound tokens like `<<` from `rustc_lexer`, and then add
464                    // fancier error recovery to it, as there will be less overall work to do this
465                    // way.
466                    let (token, sugg) =
467                        unicode_chars::check_for_substitution(self, start, c, repeats + 1);
468                    self.dcx().emit_err(crate::diagnostics::UnknownTokenStart {
469                        span: self.mk_sp(start, self.pos + Pos::from_usize(repeats * c.len_utf8())),
470                        escaped: escaped_char(c),
471                        sugg,
472                        null: c == '\x00',
473                        invisible: INVISIBLE_CHARACTERS.contains(&c),
474                        repeat: if repeats > 0 {
475                            swallow_next_invalid = repeats;
476                            Some(crate::diagnostics::UnknownTokenRepeat { repeats })
477                        } else {
478                            None
479                        },
480                    });
481
482                    if let Some(token) = token {
483                        token
484                    } else {
485                        preceded_by_whitespace = true;
486                        continue;
487                    }
488                }
489                rustc_lexer::TokenKind::Eof => token::Eof,
490            };
491            let span = self.mk_sp(start, self.pos);
492            return (Token::new(kind, span), preceded_by_whitespace);
493        }
494    }
495
496    fn ident(&self, start: BytePos) -> TokenKind {
497        let sym = nfc_normalize(self.str_from(start));
498        let span = self.mk_sp(start, self.pos);
499        self.psess.symbol_gallery.insert(sym, span);
500        token::Ident(sym, IdentIsRaw::No)
501    }
502
503    /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
504    /// complain about it.
505    fn lint_unicode_text_flow(&self, start: BytePos) {
506        // Opening delimiter of the length 2 is not included into the comment text.
507        let content_start = start + BytePos(2);
508        let content = self.str_from(content_start);
509        if contains_text_flow_control_chars(content) {
510            let span = self.mk_sp(start, self.pos);
511            let content = content.to_string();
512            self.psess.dyn_buffer_lint(
513                TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
514                span,
515                ast::CRATE_NODE_ID,
516                move |dcx, level| {
517                    let spans: Vec<_> = content
518                        .char_indices()
519                        .filter_map(|(i, c)| {
520                            TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
521                                let lo = span.lo() + BytePos(2 + i as u32);
522                                (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
523                            })
524                        })
525                        .collect();
526                    let characters = spans
527                        .iter()
528                        .map(|&(c, span)| crate::diagnostics::UnicodeCharNoteSub {
529                            span,
530                            c_debug: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", c))
    })format!("{c:?}"),
531                        })
532                        .collect();
533                    let suggestions = (!spans.is_empty()).then_some(
534                        crate::diagnostics::UnicodeTextFlowSuggestion {
535                            spans: spans.iter().map(|(_c, span)| *span).collect(),
536                        },
537                    );
538
539                    crate::diagnostics::UnicodeTextFlow {
540                        comment_span: span,
541                        characters,
542                        suggestions,
543                        num_codepoints: spans.len(),
544                    }
545                    .into_diag(dcx, level)
546                },
547            );
548        }
549    }
550
551    fn lint_doc_comment_unicode_text_flow(&mut self, start: BytePos, content: &str) {
552        if contains_text_flow_control_chars(content) {
553            self.report_text_direction_codepoint(
554                content,
555                self.mk_sp(start, self.pos),
556                0,
557                false,
558                true,
559                "doc comment",
560            );
561        }
562    }
563
564    fn lint_literal_unicode_text_flow(
565        &mut self,
566        text: Symbol,
567        lit_kind: token::LitKind,
568        span: Span,
569        label: &'static str,
570    ) {
571        if !contains_text_flow_control_chars(text.as_str()) {
572            return;
573        }
574        let (padding, point_at_inner_spans) = match lit_kind {
575            // account for `"` or `'`
576            token::LitKind::Str | token::LitKind::Char => (1, true),
577            // account for `c"`
578            token::LitKind::CStr => (2, true),
579            // account for `r###"`
580            token::LitKind::StrRaw(n) => (n as u32 + 2, true),
581            // account for `cr###"`
582            token::LitKind::CStrRaw(n) => (n as u32 + 3, true),
583            // suppress bad literals.
584            token::LitKind::Err(_) => return,
585            // Be conservative just in case new literals do support these.
586            _ => (0, false),
587        };
588        self.report_text_direction_codepoint(
589            text.as_str(),
590            span,
591            padding,
592            point_at_inner_spans,
593            false,
594            label,
595        );
596    }
597
598    fn report_text_direction_codepoint(
599        &self,
600        text: &str,
601        span: Span,
602        padding: u32,
603        point_at_inner_spans: bool,
604        is_doc_comment: bool,
605        label: &str,
606    ) {
607        // Obtain the `Span`s for each of the forbidden chars.
608        let spans: Vec<_> = text
609            .char_indices()
610            .filter_map(|(i, c)| {
611                TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
612                    let lo = span.lo() + BytePos(i as u32 + padding);
613                    (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
614                })
615            })
616            .collect();
617
618        let label = label.to_string();
619        let count = spans.len();
620        let labels =
621            point_at_inner_spans.then_some(crate::diagnostics::HiddenUnicodeCodepointsDiagLabels {
622                spans: spans.clone(),
623            });
624        let sub = if point_at_inner_spans && !spans.is_empty() {
625            crate::diagnostics::HiddenUnicodeCodepointsDiagSub::Escape { spans }
626        } else {
627            crate::diagnostics::HiddenUnicodeCodepointsDiagSub::NoEscape { spans, is_doc_comment }
628        };
629
630        self.psess.buffer_lint(
631            TEXT_DIRECTION_CODEPOINT_IN_LITERAL,
632            span,
633            ast::CRATE_NODE_ID,
634            crate::diagnostics::HiddenUnicodeCodepointsDiag {
635                label,
636                count,
637                span_label: span,
638                labels,
639                sub,
640            },
641        );
642    }
643
644    fn validate_frontmatter(
645        &self,
646        start: BytePos,
647        has_invalid_preceding_whitespace: bool,
648        invalid_infostring: bool,
649    ) {
650        let s = self.str_from(start);
651        let real_start = s.find("---").unwrap();
652        let frontmatter_opening_pos = BytePos(real_start as u32) + start;
653        let real_s = &s[real_start..];
654        let within = real_s.trim_start_matches('-');
655        let len_opening = real_s.len() - within.len();
656
657        let frontmatter_opening_end_pos = frontmatter_opening_pos + BytePos(len_opening as u32);
658        if has_invalid_preceding_whitespace {
659            let line_start =
660                BytePos(s[..real_start].rfind("\n").map_or(0, |i| i as u32 + 1)) + start;
661            let span = self.mk_sp(line_start, frontmatter_opening_end_pos);
662            let label_span = self.mk_sp(line_start, frontmatter_opening_pos);
663            self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidOpeningPrecedingWhitespace {
664                span,
665                note_span: label_span,
666            });
667        }
668
669        let line_end = real_s.find('\n').unwrap_or(real_s.len());
670        if invalid_infostring {
671            let span = self.mk_sp(
672                frontmatter_opening_end_pos,
673                frontmatter_opening_pos + BytePos(line_end as u32),
674            );
675            self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidInfostring { span });
676        }
677
678        let last_line_start = real_s.rfind('\n').map_or(line_end, |i| i + 1);
679
680        let content = &real_s[line_end..last_line_start];
681        if let Some(cr_offset) = content.find('\r') {
682            let cr_pos = start + BytePos((real_start + line_end + cr_offset) as u32);
683            let span = self.mk_sp(cr_pos, cr_pos + BytePos(1 as u32));
684            self.dcx().emit_err(crate::diagnostics::BareCrFrontmatter { span });
685        }
686
687        let last_line = &real_s[last_line_start..];
688        let last_line_trimmed = last_line.trim_start_matches(is_horizontal_whitespace);
689        let last_line_start_pos = frontmatter_opening_pos + BytePos(last_line_start as u32);
690
691        let frontmatter_span = self.mk_sp(frontmatter_opening_pos, self.pos);
692        self.psess.gated_spans.gate(sym::frontmatter, frontmatter_span);
693
694        if !last_line_trimmed.starts_with("---") {
695            let label_span = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos);
696            self.dcx().emit_err(crate::diagnostics::FrontmatterUnclosed {
697                span: frontmatter_span,
698                note_span: label_span,
699            });
700            return;
701        }
702
703        if last_line_trimmed.len() != last_line.len() {
704            let line_end = last_line_start_pos + BytePos(last_line.len() as u32);
705            let span = self.mk_sp(last_line_start_pos, line_end);
706            let whitespace_end =
707                last_line_start_pos + BytePos((last_line.len() - last_line_trimmed.len()) as u32);
708            let label_span = self.mk_sp(last_line_start_pos, whitespace_end);
709            self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidClosingPrecedingWhitespace {
710                span,
711                note_span: label_span,
712            });
713        }
714
715        let rest = last_line_trimmed.trim_start_matches('-');
716        let len_close = last_line_trimmed.len() - rest.len();
717        if len_close != len_opening {
718            let span = self.mk_sp(frontmatter_opening_pos, self.pos);
719            let opening = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos);
720            let last_line_close_pos = last_line_start_pos + BytePos(len_close as u32);
721            let close = self.mk_sp(last_line_start_pos, last_line_close_pos);
722            self.dcx().emit_err(crate::diagnostics::FrontmatterLengthMismatch {
723                span,
724                opening,
725                close,
726                len_opening,
727                len_close,
728            });
729        }
730
731        // Only up to 255 `-`s are allowed in code fences
732        if u8::try_from(len_opening).is_err() {
733            self.dcx().emit_err(crate::diagnostics::FrontmatterTooManyDashes { len_opening });
734        }
735
736        if !rest.trim_matches(is_horizontal_whitespace).is_empty() {
737            let span = self.mk_sp(last_line_start_pos, self.pos);
738            self.dcx().emit_err(crate::diagnostics::FrontmatterExtraCharactersAfterClose { span });
739        }
740    }
741
742    fn cook_doc_comment(
743        &self,
744        content_start: BytePos,
745        content: &str,
746        comment_kind: CommentKind,
747        doc_style: DocStyle,
748    ) -> TokenKind {
749        if content.contains('\r') {
750            for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
751                let span = self.mk_sp(
752                    content_start + BytePos(idx as u32),
753                    content_start + BytePos(idx as u32 + 1),
754                );
755                let block = #[allow(non_exhaustive_omitted_patterns)] match comment_kind {
    CommentKind::Block => true,
    _ => false,
}matches!(comment_kind, CommentKind::Block);
756                self.dcx().emit_err(crate::diagnostics::CrDocComment { span, block });
757            }
758        }
759
760        let attr_style = match doc_style {
761            DocStyle::Outer => AttrStyle::Outer,
762            DocStyle::Inner => AttrStyle::Inner,
763        };
764
765        token::DocComment(comment_kind, attr_style, Symbol::intern(content))
766    }
767
768    fn cook_lexer_literal(
769        &self,
770        start: BytePos,
771        end: BytePos,
772        kind: rustc_lexer::LiteralKind,
773    ) -> (token::LitKind, Symbol) {
774        match kind {
775            rustc_lexer::LiteralKind::Char { terminated } => {
776                if !terminated {
777                    let mut err = self
778                        .dcx()
779                        .struct_span_fatal(self.mk_sp(start, end), "unterminated character literal")
780                        .with_code(E0762);
781                    if let Some(lt_sp) = self.last_lifetime {
782                        err.multipart_suggestion(
783                            "if you meant to write a string literal, use double quotes",
784                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(lt_sp, "\"".to_string()),
                (self.mk_sp(start, start + BytePos(1)), "\"".to_string())]))vec![
785                                (lt_sp, "\"".to_string()),
786                                (self.mk_sp(start, start + BytePos(1)), "\"".to_string()),
787                            ],
788                            Applicability::MaybeIncorrect,
789                        );
790                    }
791                    err.emit()
792                }
793                self.cook_quoted(token::Char, Mode::Char, start, end, 1, 1) // ' '
794            }
795            rustc_lexer::LiteralKind::Byte { terminated } => {
796                if !terminated {
797                    self.dcx()
798                        .struct_span_fatal(
799                            self.mk_sp(start + BytePos(1), end),
800                            "unterminated byte constant",
801                        )
802                        .with_code(E0763)
803                        .emit()
804                }
805                self.cook_quoted(token::Byte, Mode::Byte, start, end, 2, 1) // b' '
806            }
807            rustc_lexer::LiteralKind::Str { terminated } => {
808                if !terminated {
809                    self.dcx()
810                        .struct_span_fatal(
811                            self.mk_sp(start, end),
812                            "unterminated double quote string",
813                        )
814                        .with_code(E0765)
815                        .emit()
816                }
817                self.cook_quoted(token::Str, Mode::Str, start, end, 1, 1) // " "
818            }
819            rustc_lexer::LiteralKind::ByteStr { terminated } => {
820                if !terminated {
821                    self.dcx()
822                        .struct_span_fatal(
823                            self.mk_sp(start + BytePos(1), end),
824                            "unterminated double quote byte string",
825                        )
826                        .with_code(E0766)
827                        .emit()
828                }
829                self.cook_quoted(token::ByteStr, Mode::ByteStr, start, end, 2, 1)
830                // b" "
831            }
832            rustc_lexer::LiteralKind::CStr { terminated } => {
833                if !terminated {
834                    self.dcx()
835                        .struct_span_fatal(
836                            self.mk_sp(start + BytePos(1), end),
837                            "unterminated C string",
838                        )
839                        .with_code(E0767)
840                        .emit()
841                }
842                self.cook_quoted(token::CStr, Mode::CStr, start, end, 2, 1) // c" "
843            }
844            rustc_lexer::LiteralKind::RawStr { n_hashes } => {
845                if let Some(n_hashes) = n_hashes {
846                    let n = u32::from(n_hashes);
847                    let kind = token::StrRaw(n_hashes);
848                    self.cook_quoted(kind, Mode::RawStr, start, end, 2 + n, 1 + n)
849                // r##" "##
850                } else {
851                    self.report_raw_str_error(start, 1);
852                }
853            }
854            rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
855                if let Some(n_hashes) = n_hashes {
856                    let n = u32::from(n_hashes);
857                    let kind = token::ByteStrRaw(n_hashes);
858                    self.cook_quoted(kind, Mode::RawByteStr, start, end, 3 + n, 1 + n)
859                // br##" "##
860                } else {
861                    self.report_raw_str_error(start, 2);
862                }
863            }
864            rustc_lexer::LiteralKind::RawCStr { n_hashes } => {
865                if let Some(n_hashes) = n_hashes {
866                    let n = u32::from(n_hashes);
867                    let kind = token::CStrRaw(n_hashes);
868                    self.cook_quoted(kind, Mode::RawCStr, start, end, 3 + n, 1 + n)
869                // cr##" "##
870                } else {
871                    self.report_raw_str_error(start, 2);
872                }
873            }
874            rustc_lexer::LiteralKind::Int { base, empty_int } => {
875                let mut kind = token::Integer;
876                if empty_int {
877                    let span = self.mk_sp(start, end);
878                    let guar = self.dcx().emit_err(crate::diagnostics::NoDigitsLiteral { span });
879                    kind = token::Err(guar);
880                } else if #[allow(non_exhaustive_omitted_patterns)] match base {
    Base::Binary | Base::Octal => true,
    _ => false,
}matches!(base, Base::Binary | Base::Octal) {
881                    let base = base as u32;
882                    let s = self.str_from_to(start + BytePos(2), end);
883                    for (idx, c) in s.char_indices() {
884                        let span = self.mk_sp(
885                            start + BytePos::from_usize(2 + idx),
886                            start + BytePos::from_usize(2 + idx + c.len_utf8()),
887                        );
888                        if c != '_' && c.to_digit(base).is_none() {
889                            let guar = self
890                                .dcx()
891                                .emit_err(crate::diagnostics::InvalidDigitLiteral { span, base });
892                            kind = token::Err(guar);
893                        }
894                    }
895                }
896                (kind, self.symbol_from_to(start, end))
897            }
898            rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
899                let mut kind = token::Float;
900                if empty_exponent {
901                    let span = self.mk_sp(start, self.pos);
902                    let guar = self.dcx().emit_err(crate::diagnostics::EmptyExponentFloat { span });
903                    kind = token::Err(guar);
904                }
905                let base = match base {
906                    Base::Hexadecimal => Some("hexadecimal"),
907                    Base::Octal => Some("octal"),
908                    Base::Binary => Some("binary"),
909                    _ => None,
910                };
911                if let Some(base) = base {
912                    let span = self.mk_sp(start, end);
913                    let guar = self
914                        .dcx()
915                        .emit_err(crate::diagnostics::FloatLiteralUnsupportedBase { span, base });
916                    kind = token::Err(guar)
917                }
918                (kind, self.symbol_from_to(start, end))
919            }
920        }
921    }
922
923    #[inline]
924    fn src_index(&self, pos: BytePos) -> usize {
925        (pos - self.start_pos).to_usize()
926    }
927
928    /// Slice of the source text from `start` up to but excluding `self.pos`,
929    /// meaning the slice does not include the character `self.ch`.
930    fn str_from(&self, start: BytePos) -> &'src str {
931        self.str_from_to(start, self.pos)
932    }
933
934    /// As symbol_from, with an explicit endpoint.
935    fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
936        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/lexer/mod.rs:936",
                        "rustc_parse::lexer", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_parse/src/lexer/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(936u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::lexer"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("taking an ident from {0:?} to {1:?}",
                                                    start, end) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("taking an ident from {:?} to {:?}", start, end);
937        Symbol::intern(self.str_from_to(start, end))
938    }
939
940    /// Slice of the source text spanning from `start` up to but excluding `end`.
941    fn str_from_to(&self, start: BytePos, end: BytePos) -> &'src str {
942        &self.src[self.src_index(start)..self.src_index(end)]
943    }
944
945    /// Slice of the source text spanning from `start` until the end
946    fn str_from_to_end(&self, start: BytePos) -> &'src str {
947        &self.src[self.src_index(start)..]
948    }
949
950    fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
951        match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
952            Err(RawStrError::InvalidStarter { bad_char }) => {
953                self.report_non_started_raw_string(start, bad_char)
954            }
955            Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
956                .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
957            Err(RawStrError::TooManyDelimiters { found }) => {
958                self.report_too_many_hashes(start, found)
959            }
960            Ok(()) => {
    ::core::panicking::panic_fmt(format_args!("no error found for supposedly invalid raw string literal"));
}panic!("no error found for supposedly invalid raw string literal"),
961        }
962    }
963
964    fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
965        self.dcx()
966            .struct_span_fatal(
967                self.mk_sp(start, self.pos),
968                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("found invalid character; only `#` is allowed in raw string delimitation: {0}",
                escaped_char(bad_char)))
    })format!(
969                    "found invalid character; only `#` is allowed in raw string delimitation: {}",
970                    escaped_char(bad_char)
971                ),
972            )
973            .emit()
974    }
975
976    fn report_unterminated_raw_string(
977        &self,
978        start: BytePos,
979        n_hashes: u32,
980        possible_offset: Option<u32>,
981        found_terminators: u32,
982    ) -> ! {
983        let mut err =
984            self.dcx().struct_span_fatal(self.mk_sp(start, start), "unterminated raw string");
985        err.code(E0748);
986        err.span_label(self.mk_sp(start, start), "unterminated raw string");
987
988        if n_hashes > 0 {
989            err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this raw string should be terminated with `\"{0}`",
                "#".repeat(n_hashes as usize)))
    })format!(
990                "this raw string should be terminated with `\"{}`",
991                "#".repeat(n_hashes as usize)
992            ));
993        }
994
995        if let Some(possible_offset) = possible_offset {
996            let lo = start + BytePos(possible_offset);
997            let hi = lo + BytePos(found_terminators);
998            let span = self.mk_sp(lo, hi);
999            err.span_suggestion_verbose(
1000                span,
1001                "consider terminating the string here",
1002                "#".repeat(n_hashes as usize),
1003                Applicability::MaybeIncorrect,
1004            );
1005        }
1006
1007        err.emit()
1008    }
1009
1010    fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) -> ! {
1011        let msg = match doc_style {
1012            Some(_) => "unterminated block doc-comment",
1013            None => "unterminated block comment",
1014        };
1015        let last_bpos = self.pos;
1016        let mut err = self.dcx().struct_span_fatal(self.mk_sp(start, last_bpos), msg);
1017        err.code(E0758);
1018        let mut nested_block_comment_open_idxs = ::alloc::vec::Vec::new()vec![];
1019        let mut last_nested_block_comment_idxs = None;
1020        let mut content_chars = self.str_from(start).char_indices().peekable();
1021
1022        while let Some((idx, current_char)) = content_chars.next() {
1023            match content_chars.peek() {
1024                Some((_, '*')) if current_char == '/' => {
1025                    nested_block_comment_open_idxs.push(idx);
1026                }
1027                Some((_, '/')) if current_char == '*' => {
1028                    last_nested_block_comment_idxs =
1029                        nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
1030                }
1031                _ => {}
1032            };
1033        }
1034
1035        if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
1036            err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
1037                .span_label(
1038                    self.mk_sp(
1039                        start + BytePos(nested_open_idx as u32),
1040                        start + BytePos(nested_open_idx as u32 + 2),
1041                    ),
1042                    "...as last nested comment starts here, maybe you want to close this instead?",
1043                )
1044                .span_label(
1045                    self.mk_sp(
1046                        start + BytePos(nested_close_idx as u32),
1047                        start + BytePos(nested_close_idx as u32 + 2),
1048                    ),
1049                    "...and last nested comment terminates here.",
1050                );
1051        }
1052
1053        err.emit();
1054    }
1055
1056    // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021,
1057    // using a (unknown) prefix is an error. In earlier editions, however, they
1058    // only result in a (allowed by default) lint, and are treated as regular
1059    // identifier tokens.
1060    fn report_unknown_prefix(&self, start: BytePos) {
1061        let prefix_span = self.mk_sp(start, self.pos);
1062        let prefix = self.str_from_to(start, self.pos);
1063        let expn_data = prefix_span.ctxt().outer_expn_data();
1064
1065        if expn_data.edition.at_least_rust_2021() {
1066            // In Rust 2021, this is a hard error.
1067            let sugg = if prefix == "rb" {
1068                Some(crate::diagnostics::UnknownPrefixSugg::UseBr(prefix_span))
1069            } else if prefix == "rc" {
1070                Some(crate::diagnostics::UnknownPrefixSugg::UseCr(prefix_span))
1071            } else if expn_data.is_root() {
1072                if self.cursor.first() == '\''
1073                    && let Some(start) = self.last_lifetime
1074                    && self.cursor.third() != '\''
1075                    && let end = self.mk_sp(self.pos, self.pos + BytePos(1))
1076                    && !self.psess.source_map().is_multiline(start.until(end))
1077                {
1078                    // FIXME: An "unclosed `char`" error will be emitted already in some cases,
1079                    // but it's hard to silence this error while not also silencing important cases
1080                    // too. We should use the error stashing machinery instead.
1081                    Some(crate::diagnostics::UnknownPrefixSugg::MeantStr { start, end })
1082                } else {
1083                    Some(crate::diagnostics::UnknownPrefixSugg::Whitespace(
1084                        prefix_span.shrink_to_hi(),
1085                    ))
1086                }
1087            } else {
1088                None
1089            };
1090            self.dcx().emit_err(crate::diagnostics::UnknownPrefix {
1091                span: prefix_span,
1092                prefix,
1093                sugg,
1094            });
1095        } else {
1096            // Before Rust 2021, only emit a lint for migration.
1097            self.psess.buffer_lint(
1098                RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
1099                prefix_span,
1100                ast::CRATE_NODE_ID,
1101                crate::diagnostics::ReservedPrefixLint {
1102                    subject: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", prefix))
    })format!("`{prefix}`"),
1103                    kind: "prefix",
1104                    edition: Edition::Edition2021,
1105                    sugg: prefix_span.shrink_to_hi(),
1106                },
1107            );
1108        }
1109    }
1110
1111    /// Detect guarded string literal syntax
1112    ///
1113    /// RFC 3593 reserved this syntax for future use. As of Rust 2024,
1114    /// using this syntax produces an error. In earlier editions, however, it
1115    /// only results in an (allowed by default) lint, and is treated as
1116    /// separate tokens.
1117    fn maybe_report_guarded_str(&mut self, start: BytePos, str_before: &'src str) -> TokenKind {
1118        let span = self.mk_sp(start, self.pos);
1119        let edition2024 = span.edition().at_least_rust_2024();
1120
1121        let space_pos = start + BytePos(1);
1122        let space_span = self.mk_sp(space_pos, space_pos);
1123
1124        let mut cursor = Cursor::new(str_before, FrontmatterAllowed::No);
1125
1126        let (is_string, span, unterminated) = match cursor.guarded_double_quoted_string() {
1127            Some(rustc_lexer::GuardedStr { n_hashes, terminated, token_len }) => {
1128                let end = start + BytePos(token_len);
1129                let span = self.mk_sp(start, end);
1130                let str_start = start + BytePos(n_hashes);
1131
1132                if edition2024 {
1133                    self.cursor = cursor;
1134                    self.pos = end;
1135                }
1136
1137                let unterminated = if terminated { None } else { Some(str_start) };
1138
1139                (true, span, unterminated)
1140            }
1141            None => {
1142                // We should only get here in the `##+` case.
1143                if true {
    {
        match (&self.str_from_to(start, start + BytePos(2)), &"##") {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(self.str_from_to(start, start + BytePos(2)), "##");
1144
1145                (false, span, None)
1146            }
1147        };
1148        if edition2024 {
1149            if let Some(str_start) = unterminated {
1150                // Only a fatal error if string is unterminated.
1151                self.dcx()
1152                    .struct_span_fatal(
1153                        self.mk_sp(str_start, self.pos),
1154                        "unterminated double quote string",
1155                    )
1156                    .with_code(E0765)
1157                    .emit()
1158            }
1159
1160            let sugg = if span.from_expansion() {
1161                None
1162            } else {
1163                Some(crate::diagnostics::GuardedStringSugg(space_span))
1164            };
1165
1166            // In Edition 2024 and later, emit a hard error.
1167            let err = if is_string {
1168                self.dcx().emit_err(crate::diagnostics::ReservedString { span, sugg })
1169            } else {
1170                self.dcx().emit_err(crate::diagnostics::ReservedMultihash { span, sugg })
1171            };
1172
1173            token::Literal(token::Lit {
1174                kind: token::Err(err),
1175                symbol: self.symbol_from_to(start, self.pos),
1176                suffix: None,
1177            })
1178        } else {
1179            // Before Rust 2024, only emit a lint for migration.
1180            self.psess.buffer_lint(
1181                RUST_2024_GUARDED_STRING_INCOMPATIBLE_SYNTAX,
1182                span,
1183                ast::CRATE_NODE_ID,
1184                crate::diagnostics::ReservedPrefixLint {
1185                    subject: "this".into(),
1186                    kind: if is_string { "guarded string literal" } else { "reserved token" },
1187                    edition: Edition::Edition2024,
1188                    sugg: space_span,
1189                },
1190            );
1191
1192            // For backwards compatibility, roll back to after just the first `#`
1193            // and return the `Pound` token.
1194            self.pos = start + BytePos(1);
1195            self.cursor = Cursor::new(&str_before[1..], FrontmatterAllowed::No);
1196            token::Pound
1197        }
1198    }
1199
1200    fn report_too_many_hashes(&self, start: BytePos, num: u32) -> ! {
1201        self.dcx().emit_fatal(crate::diagnostics::TooManyHashes {
1202            span: self.mk_sp(start, self.pos),
1203            num,
1204        });
1205    }
1206
1207    fn cook_quoted(
1208        &self,
1209        mut kind: token::LitKind,
1210        mode: Mode,
1211        start: BytePos,
1212        end: BytePos,
1213        prefix_len: u32,
1214        postfix_len: u32,
1215    ) -> (token::LitKind, Symbol) {
1216        let content_start = start + BytePos(prefix_len);
1217        let content_end = end - BytePos(postfix_len);
1218        let lit_content = self.str_from_to(content_start, content_end);
1219        check_for_errors(lit_content, mode, |range, err| {
1220            let span_with_quotes = self.mk_sp(start, end);
1221            let (start, end) = (range.start as u32, range.end as u32);
1222            let lo = content_start + BytePos(start);
1223            let hi = lo + BytePos(end - start);
1224            let span = self.mk_sp(lo, hi);
1225            let is_fatal = err.is_fatal();
1226            if let Some(guar) = emit_unescape_error(
1227                self.dcx(),
1228                lit_content,
1229                span_with_quotes,
1230                span,
1231                mode,
1232                range,
1233                err,
1234            ) {
1235                if !is_fatal { ::core::panicking::panic("assertion failed: is_fatal") };assert!(is_fatal);
1236                kind = token::Err(guar);
1237            }
1238        });
1239
1240        // We normally exclude the quotes for the symbol, but for errors we
1241        // include it because it results in clearer error messages.
1242        let sym = if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    token::Err(_) => true,
    _ => false,
}matches!(kind, token::Err(_)) {
1243            Symbol::intern(lit_content)
1244        } else {
1245            self.symbol_from_to(start, end)
1246        };
1247        (kind, sym)
1248    }
1249}
1250
1251pub fn nfc_normalize(string: &str) -> Symbol {
1252    use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfc_quick};
1253    match is_nfc_quick(string.chars()) {
1254        IsNormalized::Yes => Symbol::intern(string),
1255        _ => {
1256            let normalized_str: String = string.chars().nfc().collect();
1257            Symbol::intern(&normalized_str)
1258        }
1259    }
1260}