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