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#[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
47pub(crate) enum StripTokens {
49 ShebangAndFrontmatter,
51 Shebang,
56 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(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 Err(unmatched_closing_delims)
110 }
111 }
112 Err(errs) => {
113 unmatched_closing_delims.extend(errs);
116 Err(unmatched_closing_delims)
117 }
118 }
119}
120
121struct Lexer<'psess, 'src> {
122 psess: &'psess ParseSess,
123 start_pos: BytePos,
125 pos: BytePos,
127 src: &'src str,
129 cursor: Cursor<'src>,
131 override_span: Option<Span>,
132 nbsp_is_whitespace: bool,
136
137 last_lifetime: Option<Span>,
140
141 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 fn next_token_from_cursor(&mut self) -> (Token, bool) {
159 let mut preceded_by_whitespace = false;
160 let mut swallow_next_invalid = 0;
161 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 self.last_lifetime = None;
180 }
181
182 let kind = match token.kind {
186 rustc_lexer::TokenKind::LineComment { doc_style } => {
187 let Some(doc_style) = doc_style else {
189 self.lint_unicode_text_flow(start);
190 preceded_by_whitespace = true;
191 continue;
192 };
193
194 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 let Some(doc_style) = doc_style else {
207 self.lint_unicode_text_flow(start);
208 preceded_by_whitespace = true;
209 continue;
210 };
211
212 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 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 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 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 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 let lifetime_name = 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 let ident = Symbol::intern(lifetime_name);
329 token::Lifetime(ident, IdentIsRaw::No)
330 }
331 rustc_lexer::TokenKind::RawLifetime => {
332 self.last_lifetime = Some(self.mk_sp(start, start + BytePos(1)));
333
334 let ident_start = start + BytePos(3);
335 let prefix_span = self.mk_sp(start, ident_start);
336
337 if prefix_span.at_least_rust_2021() {
338 if self.cursor.as_str().starts_with('\'') {
344 let lit_span = self.mk_sp(start, self.pos + BytePos(1));
345 let contents = self.str_from_to(start + BytePos(1), self.pos);
346 emit_unescape_error(
347 self.dcx(),
348 contents,
349 lit_span,
350 lit_span,
351 Mode::Char,
352 0..contents.len(),
353 EscapeError::MoreThanOneChar,
354 )
355 .expect("expected error");
356 }
357
358 let span = self.mk_sp(start, self.pos);
359
360 let lifetime_name_without_tick =
361 Symbol::intern(&self.str_from(ident_start));
362 if !lifetime_name_without_tick.can_be_raw() {
363 self.dcx().emit_err(
364 errors::CannotBeRawLifetime {
365 span,
366 ident: lifetime_name_without_tick
367 }
368 );
369 }
370
371 let mut lifetime_name =
373 String::with_capacity(lifetime_name_without_tick.as_str().len() + 1);
374 lifetime_name.push('\'');
375 lifetime_name += lifetime_name_without_tick.as_str();
376 let sym = Symbol::intern(&lifetime_name);
377
378 self.psess.raw_identifier_spans.push(span);
380
381 token::Lifetime(sym, IdentIsRaw::Yes)
382 } else {
383 self.psess.buffer_lint(
385 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
386 prefix_span,
387 ast::CRATE_NODE_ID,
388 BuiltinLintDiag::RawPrefix(prefix_span),
389 );
390
391 let lt_start = start + BytePos(2);
393 self.pos = lt_start;
394 self.cursor = Cursor::new(&str_before[2 as usize..], FrontmatterAllowed::No);
395
396 let lifetime_name = self.str_from(start);
397 let ident = Symbol::intern(lifetime_name);
398 token::Lifetime(ident, IdentIsRaw::No)
399 }
400 }
401 rustc_lexer::TokenKind::Semi => token::Semi,
402 rustc_lexer::TokenKind::Comma => token::Comma,
403 rustc_lexer::TokenKind::Dot => token::Dot,
404 rustc_lexer::TokenKind::OpenParen => token::OpenParen,
405 rustc_lexer::TokenKind::CloseParen => token::CloseParen,
406 rustc_lexer::TokenKind::OpenBrace => token::OpenBrace,
407 rustc_lexer::TokenKind::CloseBrace => token::CloseBrace,
408 rustc_lexer::TokenKind::OpenBracket => token::OpenBracket,
409 rustc_lexer::TokenKind::CloseBracket => token::CloseBracket,
410 rustc_lexer::TokenKind::At => token::At,
411 rustc_lexer::TokenKind::Pound => token::Pound,
412 rustc_lexer::TokenKind::Tilde => token::Tilde,
413 rustc_lexer::TokenKind::Question => token::Question,
414 rustc_lexer::TokenKind::Colon => token::Colon,
415 rustc_lexer::TokenKind::Dollar => token::Dollar,
416 rustc_lexer::TokenKind::Eq => token::Eq,
417 rustc_lexer::TokenKind::Bang => token::Bang,
418 rustc_lexer::TokenKind::Lt => token::Lt,
419 rustc_lexer::TokenKind::Gt => token::Gt,
420 rustc_lexer::TokenKind::Minus => token::Minus,
421 rustc_lexer::TokenKind::And => token::And,
422 rustc_lexer::TokenKind::Or => token::Or,
423 rustc_lexer::TokenKind::Plus => token::Plus,
424 rustc_lexer::TokenKind::Star => token::Star,
425 rustc_lexer::TokenKind::Slash => token::Slash,
426 rustc_lexer::TokenKind::Caret => token::Caret,
427 rustc_lexer::TokenKind::Percent => token::Percent,
428
429 rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => {
430 if swallow_next_invalid > 0 {
432 swallow_next_invalid -= 1;
433 continue;
434 }
435 let mut it = self.str_from_to_end(start).chars();
436 let c = it.next().unwrap();
437 if c == '\u{00a0}' {
438 if self.nbsp_is_whitespace {
442 preceded_by_whitespace = true;
443 continue;
444 }
445 self.nbsp_is_whitespace = true;
446 }
447 let repeats = it.take_while(|c1| *c1 == c).count();
448 let (token, sugg) =
455 unicode_chars::check_for_substitution(self, start, c, repeats + 1);
456 self.dcx().emit_err(errors::UnknownTokenStart {
457 span: self.mk_sp(start, self.pos + Pos::from_usize(repeats * c.len_utf8())),
458 escaped: escaped_char(c),
459 sugg,
460 null: if c == '\x00' { Some(errors::UnknownTokenNull) } else { None },
461 repeat: if repeats > 0 {
462 swallow_next_invalid = repeats;
463 Some(errors::UnknownTokenRepeat { repeats })
464 } else {
465 None
466 },
467 });
468
469 if let Some(token) = token {
470 token
471 } else {
472 preceded_by_whitespace = true;
473 continue;
474 }
475 }
476 rustc_lexer::TokenKind::Eof => token::Eof,
477 };
478 let span = self.mk_sp(start, self.pos);
479 return (Token::new(kind, span), preceded_by_whitespace);
480 }
481 }
482
483 fn ident(&self, start: BytePos) -> TokenKind {
484 let sym = nfc_normalize(self.str_from(start));
485 let span = self.mk_sp(start, self.pos);
486 self.psess.symbol_gallery.insert(sym, span);
487 token::Ident(sym, IdentIsRaw::No)
488 }
489
490 fn lint_unicode_text_flow(&self, start: BytePos) {
493 let content_start = start + BytePos(2);
495 let content = self.str_from(content_start);
496 if contains_text_flow_control_chars(content) {
497 let span = self.mk_sp(start, self.pos);
498 self.psess.buffer_lint(
499 TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
500 span,
501 ast::CRATE_NODE_ID,
502 BuiltinLintDiag::UnicodeTextFlow(span, content.to_string()),
503 );
504 }
505 }
506
507 fn lint_doc_comment_unicode_text_flow(&mut self, start: BytePos, content: &str) {
508 if contains_text_flow_control_chars(content) {
509 self.report_text_direction_codepoint(
510 content,
511 self.mk_sp(start, self.pos),
512 0,
513 false,
514 "doc comment",
515 );
516 }
517 }
518
519 fn lint_literal_unicode_text_flow(
520 &mut self,
521 text: Symbol,
522 lit_kind: token::LitKind,
523 span: Span,
524 label: &'static str,
525 ) {
526 if !contains_text_flow_control_chars(text.as_str()) {
527 return;
528 }
529 let (padding, point_at_inner_spans) = match lit_kind {
530 token::LitKind::Str | token::LitKind::Char => (1, true),
532 token::LitKind::CStr => (2, true),
534 token::LitKind::StrRaw(n) => (n as u32 + 2, true),
536 token::LitKind::CStrRaw(n) => (n as u32 + 3, true),
538 token::LitKind::Err(_) => return,
540 _ => (0, false),
542 };
543 self.report_text_direction_codepoint(
544 text.as_str(),
545 span,
546 padding,
547 point_at_inner_spans,
548 label,
549 );
550 }
551
552 fn report_text_direction_codepoint(
553 &self,
554 text: &str,
555 span: Span,
556 padding: u32,
557 point_at_inner_spans: bool,
558 label: &str,
559 ) {
560 let spans: Vec<_> = text
562 .char_indices()
563 .filter_map(|(i, c)| {
564 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
565 let lo = span.lo() + BytePos(i as u32 + padding);
566 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
567 })
568 })
569 .collect();
570
571 let label = label.to_string();
572 let count = spans.len();
573 let labels = point_at_inner_spans
574 .then_some(errors::HiddenUnicodeCodepointsDiagLabels { spans: spans.clone() });
575 let sub = if point_at_inner_spans && !spans.is_empty() {
576 errors::HiddenUnicodeCodepointsDiagSub::Escape { spans }
577 } else {
578 errors::HiddenUnicodeCodepointsDiagSub::NoEscape { spans }
579 };
580
581 self.psess.buffer_lint(
582 TEXT_DIRECTION_CODEPOINT_IN_LITERAL,
583 span,
584 ast::CRATE_NODE_ID,
585 errors::HiddenUnicodeCodepointsDiag { label, count, span_label: span, labels, sub },
586 );
587 }
588
589 fn validate_frontmatter(
590 &self,
591 start: BytePos,
592 has_invalid_preceding_whitespace: bool,
593 invalid_infostring: bool,
594 ) {
595 let s = self.str_from(start);
596 let real_start = s.find("---").unwrap();
597 let frontmatter_opening_pos = BytePos(real_start as u32) + start;
598 let s_new = &s[real_start..];
599 let within = s_new.trim_start_matches('-');
600 let len_opening = s_new.len() - within.len();
601
602 let frontmatter_opening_end_pos = frontmatter_opening_pos + BytePos(len_opening as u32);
603 if has_invalid_preceding_whitespace {
604 let line_start =
605 BytePos(s[..real_start].rfind("\n").map_or(0, |i| i as u32 + 1)) + start;
606 let span = self.mk_sp(line_start, frontmatter_opening_end_pos);
607 let label_span = self.mk_sp(line_start, frontmatter_opening_pos);
608 self.dcx().emit_err(errors::FrontmatterInvalidOpeningPrecedingWhitespace {
609 span,
610 note_span: label_span,
611 });
612 }
613
614 if invalid_infostring {
615 let line_end = s[real_start..].find('\n').unwrap_or(s[real_start..].len());
616 let span = self.mk_sp(
617 frontmatter_opening_end_pos,
618 frontmatter_opening_pos + BytePos(line_end as u32),
619 );
620 self.dcx().emit_err(errors::FrontmatterInvalidInfostring { span });
621 }
622
623 let last_line_start = within.rfind('\n').map_or(0, |i| i + 1);
624 let last_line = &within[last_line_start..];
625 let last_line_trimmed = last_line.trim_start_matches(is_horizontal_whitespace);
626 let last_line_start_pos = frontmatter_opening_end_pos + BytePos(last_line_start as u32);
627
628 let frontmatter_span = self.mk_sp(frontmatter_opening_pos, self.pos);
629 self.psess.gated_spans.gate(sym::frontmatter, frontmatter_span);
630
631 if !last_line_trimmed.starts_with("---") {
632 let label_span = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos);
633 self.dcx().emit_err(errors::FrontmatterUnclosed {
634 span: frontmatter_span,
635 note_span: label_span,
636 });
637 return;
638 }
639
640 if last_line_trimmed.len() != last_line.len() {
641 let line_end = last_line_start_pos + BytePos(last_line.len() as u32);
642 let span = self.mk_sp(last_line_start_pos, line_end);
643 let whitespace_end =
644 last_line_start_pos + BytePos((last_line.len() - last_line_trimmed.len()) as u32);
645 let label_span = self.mk_sp(last_line_start_pos, whitespace_end);
646 self.dcx().emit_err(errors::FrontmatterInvalidClosingPrecedingWhitespace {
647 span,
648 note_span: label_span,
649 });
650 }
651
652 let rest = last_line_trimmed.trim_start_matches('-');
653 let len_close = last_line_trimmed.len() - rest.len();
654 if len_close != len_opening {
655 let span = self.mk_sp(frontmatter_opening_pos, self.pos);
656 let opening = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos);
657 let last_line_close_pos = last_line_start_pos + BytePos(len_close as u32);
658 let close = self.mk_sp(last_line_start_pos, last_line_close_pos);
659 self.dcx().emit_err(errors::FrontmatterLengthMismatch {
660 span,
661 opening,
662 close,
663 len_opening,
664 len_close,
665 });
666 }
667
668 if !rest.trim_matches(is_horizontal_whitespace).is_empty() {
669 let span = self.mk_sp(last_line_start_pos, self.pos);
670 self.dcx().emit_err(errors::FrontmatterExtraCharactersAfterClose { span });
671 }
672 }
673
674 fn cook_doc_comment(
675 &self,
676 content_start: BytePos,
677 content: &str,
678 comment_kind: CommentKind,
679 doc_style: DocStyle,
680 ) -> TokenKind {
681 if content.contains('\r') {
682 for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') {
683 let span = self.mk_sp(
684 content_start + BytePos(idx as u32),
685 content_start + BytePos(idx as u32 + 1),
686 );
687 let block = matches!(comment_kind, CommentKind::Block);
688 self.dcx().emit_err(errors::CrDocComment { span, block });
689 }
690 }
691
692 let attr_style = match doc_style {
693 DocStyle::Outer => AttrStyle::Outer,
694 DocStyle::Inner => AttrStyle::Inner,
695 };
696
697 token::DocComment(comment_kind, attr_style, Symbol::intern(content))
698 }
699
700 fn cook_lexer_literal(
701 &self,
702 start: BytePos,
703 end: BytePos,
704 kind: rustc_lexer::LiteralKind,
705 ) -> (token::LitKind, Symbol) {
706 match kind {
707 rustc_lexer::LiteralKind::Char { terminated } => {
708 if !terminated {
709 let mut err = self
710 .dcx()
711 .struct_span_fatal(self.mk_sp(start, end), "unterminated character literal")
712 .with_code(E0762);
713 if let Some(lt_sp) = self.last_lifetime {
714 err.multipart_suggestion(
715 "if you meant to write a string literal, use double quotes",
716 vec![
717 (lt_sp, "\"".to_string()),
718 (self.mk_sp(start, start + BytePos(1)), "\"".to_string()),
719 ],
720 Applicability::MaybeIncorrect,
721 );
722 }
723 err.emit()
724 }
725 self.cook_quoted(token::Char, Mode::Char, start, end, 1, 1) }
727 rustc_lexer::LiteralKind::Byte { terminated } => {
728 if !terminated {
729 self.dcx()
730 .struct_span_fatal(
731 self.mk_sp(start + BytePos(1), end),
732 "unterminated byte constant",
733 )
734 .with_code(E0763)
735 .emit()
736 }
737 self.cook_quoted(token::Byte, Mode::Byte, start, end, 2, 1) }
739 rustc_lexer::LiteralKind::Str { terminated } => {
740 if !terminated {
741 self.dcx()
742 .struct_span_fatal(
743 self.mk_sp(start, end),
744 "unterminated double quote string",
745 )
746 .with_code(E0765)
747 .emit()
748 }
749 self.cook_quoted(token::Str, Mode::Str, start, end, 1, 1) }
751 rustc_lexer::LiteralKind::ByteStr { terminated } => {
752 if !terminated {
753 self.dcx()
754 .struct_span_fatal(
755 self.mk_sp(start + BytePos(1), end),
756 "unterminated double quote byte string",
757 )
758 .with_code(E0766)
759 .emit()
760 }
761 self.cook_quoted(token::ByteStr, Mode::ByteStr, start, end, 2, 1)
762 }
764 rustc_lexer::LiteralKind::CStr { terminated } => {
765 if !terminated {
766 self.dcx()
767 .struct_span_fatal(
768 self.mk_sp(start + BytePos(1), end),
769 "unterminated C string",
770 )
771 .with_code(E0767)
772 .emit()
773 }
774 self.cook_quoted(token::CStr, Mode::CStr, start, end, 2, 1) }
776 rustc_lexer::LiteralKind::RawStr { n_hashes } => {
777 if let Some(n_hashes) = n_hashes {
778 let n = u32::from(n_hashes);
779 let kind = token::StrRaw(n_hashes);
780 self.cook_quoted(kind, Mode::RawStr, start, end, 2 + n, 1 + n)
781 } else {
783 self.report_raw_str_error(start, 1);
784 }
785 }
786 rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
787 if let Some(n_hashes) = n_hashes {
788 let n = u32::from(n_hashes);
789 let kind = token::ByteStrRaw(n_hashes);
790 self.cook_quoted(kind, Mode::RawByteStr, start, end, 3 + n, 1 + n)
791 } else {
793 self.report_raw_str_error(start, 2);
794 }
795 }
796 rustc_lexer::LiteralKind::RawCStr { n_hashes } => {
797 if let Some(n_hashes) = n_hashes {
798 let n = u32::from(n_hashes);
799 let kind = token::CStrRaw(n_hashes);
800 self.cook_quoted(kind, Mode::RawCStr, start, end, 3 + n, 1 + n)
801 } else {
803 self.report_raw_str_error(start, 2);
804 }
805 }
806 rustc_lexer::LiteralKind::Int { base, empty_int } => {
807 let mut kind = token::Integer;
808 if empty_int {
809 let span = self.mk_sp(start, end);
810 let guar = self.dcx().emit_err(errors::NoDigitsLiteral { span });
811 kind = token::Err(guar);
812 } else if matches!(base, Base::Binary | Base::Octal) {
813 let base = base as u32;
814 let s = self.str_from_to(start + BytePos(2), end);
815 for (idx, c) in s.char_indices() {
816 let span = self.mk_sp(
817 start + BytePos::from_usize(2 + idx),
818 start + BytePos::from_usize(2 + idx + c.len_utf8()),
819 );
820 if c != '_' && c.to_digit(base).is_none() {
821 let guar =
822 self.dcx().emit_err(errors::InvalidDigitLiteral { span, base });
823 kind = token::Err(guar);
824 }
825 }
826 }
827 (kind, self.symbol_from_to(start, end))
828 }
829 rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
830 let mut kind = token::Float;
831 if empty_exponent {
832 let span = self.mk_sp(start, self.pos);
833 let guar = self.dcx().emit_err(errors::EmptyExponentFloat { span });
834 kind = token::Err(guar);
835 }
836 let base = match base {
837 Base::Hexadecimal => Some("hexadecimal"),
838 Base::Octal => Some("octal"),
839 Base::Binary => Some("binary"),
840 _ => None,
841 };
842 if let Some(base) = base {
843 let span = self.mk_sp(start, end);
844 let guar =
845 self.dcx().emit_err(errors::FloatLiteralUnsupportedBase { span, base });
846 kind = token::Err(guar)
847 }
848 (kind, self.symbol_from_to(start, end))
849 }
850 }
851 }
852
853 #[inline]
854 fn src_index(&self, pos: BytePos) -> usize {
855 (pos - self.start_pos).to_usize()
856 }
857
858 fn str_from(&self, start: BytePos) -> &'src str {
861 self.str_from_to(start, self.pos)
862 }
863
864 fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
866 debug!("taking an ident from {:?} to {:?}", start, end);
867 Symbol::intern(self.str_from_to(start, end))
868 }
869
870 fn str_from_to(&self, start: BytePos, end: BytePos) -> &'src str {
872 &self.src[self.src_index(start)..self.src_index(end)]
873 }
874
875 fn str_from_to_end(&self, start: BytePos) -> &'src str {
877 &self.src[self.src_index(start)..]
878 }
879
880 fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! {
881 match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) {
882 Err(RawStrError::InvalidStarter { bad_char }) => {
883 self.report_non_started_raw_string(start, bad_char)
884 }
885 Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
886 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
887 Err(RawStrError::TooManyDelimiters { found }) => {
888 self.report_too_many_hashes(start, found)
889 }
890 Ok(()) => panic!("no error found for supposedly invalid raw string literal"),
891 }
892 }
893
894 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
895 self.dcx()
896 .struct_span_fatal(
897 self.mk_sp(start, self.pos),
898 format!(
899 "found invalid character; only `#` is allowed in raw string delimitation: {}",
900 escaped_char(bad_char)
901 ),
902 )
903 .emit()
904 }
905
906 fn report_unterminated_raw_string(
907 &self,
908 start: BytePos,
909 n_hashes: u32,
910 possible_offset: Option<u32>,
911 found_terminators: u32,
912 ) -> ! {
913 let mut err =
914 self.dcx().struct_span_fatal(self.mk_sp(start, start), "unterminated raw string");
915 err.code(E0748);
916 err.span_label(self.mk_sp(start, start), "unterminated raw string");
917
918 if n_hashes > 0 {
919 err.note(format!(
920 "this raw string should be terminated with `\"{}`",
921 "#".repeat(n_hashes as usize)
922 ));
923 }
924
925 if let Some(possible_offset) = possible_offset {
926 let lo = start + BytePos(possible_offset);
927 let hi = lo + BytePos(found_terminators);
928 let span = self.mk_sp(lo, hi);
929 err.span_suggestion(
930 span,
931 "consider terminating the string here",
932 "#".repeat(n_hashes as usize),
933 Applicability::MaybeIncorrect,
934 );
935 }
936
937 err.emit()
938 }
939
940 fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) {
941 let msg = match doc_style {
942 Some(_) => "unterminated block doc-comment",
943 None => "unterminated block comment",
944 };
945 let last_bpos = self.pos;
946 let mut err = self.dcx().struct_span_fatal(self.mk_sp(start, last_bpos), msg);
947 err.code(E0758);
948 let mut nested_block_comment_open_idxs = vec![];
949 let mut last_nested_block_comment_idxs = None;
950 let mut content_chars = self.str_from(start).char_indices().peekable();
951
952 while let Some((idx, current_char)) = content_chars.next() {
953 match content_chars.peek() {
954 Some((_, '*')) if current_char == '/' => {
955 nested_block_comment_open_idxs.push(idx);
956 }
957 Some((_, '/')) if current_char == '*' => {
958 last_nested_block_comment_idxs =
959 nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx));
960 }
961 _ => {}
962 };
963 }
964
965 if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs {
966 err.span_label(self.mk_sp(start, start + BytePos(2)), msg)
967 .span_label(
968 self.mk_sp(
969 start + BytePos(nested_open_idx as u32),
970 start + BytePos(nested_open_idx as u32 + 2),
971 ),
972 "...as last nested comment starts here, maybe you want to close this instead?",
973 )
974 .span_label(
975 self.mk_sp(
976 start + BytePos(nested_close_idx as u32),
977 start + BytePos(nested_close_idx as u32 + 2),
978 ),
979 "...and last nested comment terminates here.",
980 );
981 }
982
983 err.emit();
984 }
985
986 fn report_unknown_prefix(&self, start: BytePos) {
991 let prefix_span = self.mk_sp(start, self.pos);
992 let prefix = self.str_from_to(start, self.pos);
993 let expn_data = prefix_span.ctxt().outer_expn_data();
994
995 if expn_data.edition.at_least_rust_2021() {
996 let sugg = if prefix == "rb" {
998 Some(errors::UnknownPrefixSugg::UseBr(prefix_span))
999 } else if prefix == "rc" {
1000 Some(errors::UnknownPrefixSugg::UseCr(prefix_span))
1001 } else if expn_data.is_root() {
1002 if self.cursor.first() == '\''
1003 && let Some(start) = self.last_lifetime
1004 && self.cursor.third() != '\''
1005 && let end = self.mk_sp(self.pos, self.pos + BytePos(1))
1006 && !self.psess.source_map().is_multiline(start.until(end))
1007 {
1008 Some(errors::UnknownPrefixSugg::MeantStr { start, end })
1012 } else {
1013 Some(errors::UnknownPrefixSugg::Whitespace(prefix_span.shrink_to_hi()))
1014 }
1015 } else {
1016 None
1017 };
1018 self.dcx().emit_err(errors::UnknownPrefix { span: prefix_span, prefix, sugg });
1019 } else {
1020 self.psess.buffer_lint(
1022 RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX,
1023 prefix_span,
1024 ast::CRATE_NODE_ID,
1025 BuiltinLintDiag::ReservedPrefix(prefix_span, prefix.to_string()),
1026 );
1027 }
1028 }
1029
1030 fn maybe_report_guarded_str(&mut self, start: BytePos, str_before: &'src str) -> TokenKind {
1037 let span = self.mk_sp(start, self.pos);
1038 let edition2024 = span.edition().at_least_rust_2024();
1039
1040 let space_pos = start + BytePos(1);
1041 let space_span = self.mk_sp(space_pos, space_pos);
1042
1043 let mut cursor = Cursor::new(str_before, FrontmatterAllowed::No);
1044
1045 let (is_string, span, unterminated) = match cursor.guarded_double_quoted_string() {
1046 Some(rustc_lexer::GuardedStr { n_hashes, terminated, token_len }) => {
1047 let end = start + BytePos(token_len);
1048 let span = self.mk_sp(start, end);
1049 let str_start = start + BytePos(n_hashes);
1050
1051 if edition2024 {
1052 self.cursor = cursor;
1053 self.pos = end;
1054 }
1055
1056 let unterminated = if terminated { None } else { Some(str_start) };
1057
1058 (true, span, unterminated)
1059 }
1060 None => {
1061 debug_assert_eq!(self.str_from_to(start, start + BytePos(2)), "##");
1063
1064 (false, span, None)
1065 }
1066 };
1067 if edition2024 {
1068 if let Some(str_start) = unterminated {
1069 self.dcx()
1071 .struct_span_fatal(
1072 self.mk_sp(str_start, self.pos),
1073 "unterminated double quote string",
1074 )
1075 .with_code(E0765)
1076 .emit()
1077 }
1078
1079 let sugg = if span.from_expansion() {
1080 None
1081 } else {
1082 Some(errors::GuardedStringSugg(space_span))
1083 };
1084
1085 let err = if is_string {
1087 self.dcx().emit_err(errors::ReservedString { span, sugg })
1088 } else {
1089 self.dcx().emit_err(errors::ReservedMultihash { span, sugg })
1090 };
1091
1092 token::Literal(token::Lit {
1093 kind: token::Err(err),
1094 symbol: self.symbol_from_to(start, self.pos),
1095 suffix: None,
1096 })
1097 } else {
1098 self.psess.buffer_lint(
1100 RUST_2024_GUARDED_STRING_INCOMPATIBLE_SYNTAX,
1101 span,
1102 ast::CRATE_NODE_ID,
1103 BuiltinLintDiag::ReservedString { is_string, suggestion: space_span },
1104 );
1105
1106 self.pos = start + BytePos(1);
1109 self.cursor = Cursor::new(&str_before[1..], FrontmatterAllowed::No);
1110 token::Pound
1111 }
1112 }
1113
1114 fn report_too_many_hashes(&self, start: BytePos, num: u32) -> ! {
1115 self.dcx().emit_fatal(errors::TooManyHashes { span: self.mk_sp(start, self.pos), num });
1116 }
1117
1118 fn cook_quoted(
1119 &self,
1120 mut kind: token::LitKind,
1121 mode: Mode,
1122 start: BytePos,
1123 end: BytePos,
1124 prefix_len: u32,
1125 postfix_len: u32,
1126 ) -> (token::LitKind, Symbol) {
1127 let content_start = start + BytePos(prefix_len);
1128 let content_end = end - BytePos(postfix_len);
1129 let lit_content = self.str_from_to(content_start, content_end);
1130 check_for_errors(lit_content, mode, |range, err| {
1131 let span_with_quotes = self.mk_sp(start, end);
1132 let (start, end) = (range.start as u32, range.end as u32);
1133 let lo = content_start + BytePos(start);
1134 let hi = lo + BytePos(end - start);
1135 let span = self.mk_sp(lo, hi);
1136 let is_fatal = err.is_fatal();
1137 if let Some(guar) = emit_unescape_error(
1138 self.dcx(),
1139 lit_content,
1140 span_with_quotes,
1141 span,
1142 mode,
1143 range,
1144 err,
1145 ) {
1146 assert!(is_fatal);
1147 kind = token::Err(guar);
1148 }
1149 });
1150
1151 let sym = if !matches!(kind, token::Err(_)) {
1154 Symbol::intern(lit_content)
1155 } else {
1156 self.symbol_from_to(start, end)
1157 };
1158 (kind, sym)
1159 }
1160}
1161
1162pub fn nfc_normalize(string: &str) -> Symbol {
1163 use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfc_quick};
1164 match is_nfc_quick(string.chars()) {
1165 IsNormalized::Yes => Symbol::intern(string),
1166 _ => {
1167 let normalized_str: String = string.chars().nfc().collect();
1168 Symbol::intern(&normalized_str)
1169 }
1170 }
1171}