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