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