]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/lexer/mod.rs
Fix font color for help button in ayu and dark themes
[rust.git] / src / librustc_parse / lexer / mod.rs
1 use rustc_ast::token::{self, CommentKind, Token, TokenKind};
2 use rustc_ast::util::comments;
3 use rustc_data_structures::sync::Lrc;
4 use rustc_errors::{error_code, Applicability, DiagnosticBuilder, FatalError};
5 use rustc_lexer::Base;
6 use rustc_lexer::{unescape, RawStrError};
7 use rustc_session::parse::ParseSess;
8 use rustc_span::symbol::{sym, Symbol};
9 use rustc_span::{BytePos, Pos, Span};
10
11 use std::char;
12 use tracing::debug;
13
14 mod tokentrees;
15 mod unescape_error_reporting;
16 mod unicode_chars;
17
18 use rustc_lexer::unescape::Mode;
19 use unescape_error_reporting::{emit_unescape_error, push_escaped_char};
20
21 #[derive(Clone, Debug)]
22 pub struct UnmatchedBrace {
23     pub expected_delim: token::DelimToken,
24     pub found_delim: Option<token::DelimToken>,
25     pub found_span: Span,
26     pub unclosed_span: Option<Span>,
27     pub candidate_span: Option<Span>,
28 }
29
30 pub struct StringReader<'a> {
31     sess: &'a ParseSess,
32     /// Initial position, read-only.
33     start_pos: BytePos,
34     /// The absolute offset within the source_map of the current character.
35     pos: BytePos,
36     /// Stop reading src at this index.
37     end_src_index: usize,
38     /// Source text to tokenize.
39     src: Lrc<String>,
40     override_span: Option<Span>,
41 }
42
43 impl<'a> StringReader<'a> {
44     pub fn new(
45         sess: &'a ParseSess,
46         source_file: Lrc<rustc_span::SourceFile>,
47         override_span: Option<Span>,
48     ) -> Self {
49         // Make sure external source is loaded first, before accessing it.
50         // While this can't show up during normal parsing, `retokenize` may
51         // be called with a source file from an external crate.
52         sess.source_map().ensure_source_file_source_present(Lrc::clone(&source_file));
53
54         let src = if let Some(src) = &source_file.src {
55             Lrc::clone(&src)
56         } else if let Some(src) = source_file.external_src.borrow().get_source() {
57             Lrc::clone(&src)
58         } else {
59             sess.span_diagnostic
60                 .bug(&format!("cannot lex `source_file` without source: {}", source_file.name));
61         };
62
63         StringReader {
64             sess,
65             start_pos: source_file.start_pos,
66             pos: source_file.start_pos,
67             end_src_index: src.len(),
68             src,
69             override_span,
70         }
71     }
72
73     pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self {
74         let begin = sess.source_map().lookup_byte_offset(span.lo());
75         let end = sess.source_map().lookup_byte_offset(span.hi());
76
77         // Make the range zero-length if the span is invalid.
78         if begin.sf.start_pos != end.sf.start_pos {
79             span = span.shrink_to_lo();
80         }
81
82         let mut sr = StringReader::new(sess, begin.sf, None);
83
84         // Seek the lexer to the right byte range.
85         sr.end_src_index = sr.src_index(span.hi());
86
87         sr
88     }
89
90     fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
91         self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
92     }
93
94     /// Returns the next token, including trivia like whitespace or comments.
95     pub fn next_token(&mut self) -> Token {
96         let start_src_index = self.src_index(self.pos);
97         let text: &str = &self.src[start_src_index..self.end_src_index];
98
99         if text.is_empty() {
100             let span = self.mk_sp(self.pos, self.pos);
101             return Token::new(token::Eof, span);
102         }
103
104         {
105             let is_beginning_of_file = self.pos == self.start_pos;
106             if is_beginning_of_file {
107                 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
108                     let start = self.pos;
109                     self.pos = self.pos + BytePos::from_usize(shebang_len);
110
111                     let sym = self.symbol_from(start + BytePos::from_usize("#!".len()));
112                     let kind = token::Shebang(sym);
113
114                     let span = self.mk_sp(start, self.pos);
115                     return Token::new(kind, span);
116                 }
117             }
118         }
119
120         let token = rustc_lexer::first_token(text);
121
122         let start = self.pos;
123         self.pos = self.pos + BytePos::from_usize(token.len);
124
125         debug!("try_next_token: {:?}({:?})", token.kind, self.str_from(start));
126
127         let kind = self.cook_lexer_token(token.kind, start);
128         let span = self.mk_sp(start, self.pos);
129         Token::new(kind, span)
130     }
131
132     /// Report a fatal lexical error with a given span.
133     fn fatal_span(&self, sp: Span, m: &str) -> FatalError {
134         self.sess.span_diagnostic.span_fatal(sp, m)
135     }
136
137     /// Report a lexical error with a given span.
138     fn err_span(&self, sp: Span, m: &str) {
139         self.sess.span_diagnostic.struct_span_err(sp, m).emit();
140     }
141
142     /// Report a fatal error spanning [`from_pos`, `to_pos`).
143     fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError {
144         self.fatal_span(self.mk_sp(from_pos, to_pos), m)
145     }
146
147     /// Report a lexical error spanning [`from_pos`, `to_pos`).
148     fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
149         self.err_span(self.mk_sp(from_pos, to_pos), m)
150     }
151
152     fn struct_fatal_span_char(
153         &self,
154         from_pos: BytePos,
155         to_pos: BytePos,
156         m: &str,
157         c: char,
158     ) -> DiagnosticBuilder<'a> {
159         let mut m = m.to_string();
160         m.push_str(": ");
161         push_escaped_char(&mut m, c);
162
163         self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..])
164     }
165
166     /// Turns simple `rustc_lexer::TokenKind` enum into a rich
167     /// `librustc_ast::TokenKind`. This turns strings into interned
168     /// symbols and runs additional validation.
169     fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> TokenKind {
170         match token {
171             rustc_lexer::TokenKind::LineComment => {
172                 let string = self.str_from(start);
173                 if let Some(attr_style) = comments::line_doc_comment_style(string) {
174                     self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment");
175                     // Opening delimiter of the length 3 is not included into the symbol.
176                     token::DocComment(CommentKind::Line, attr_style, Symbol::intern(&string[3..]))
177                 } else {
178                     token::Comment
179                 }
180             }
181             rustc_lexer::TokenKind::BlockComment { terminated } => {
182                 let string = self.str_from(start);
183                 let attr_style = comments::block_doc_comment_style(string, terminated);
184
185                 if !terminated {
186                     let msg = if attr_style.is_some() {
187                         "unterminated block doc-comment"
188                     } else {
189                         "unterminated block comment"
190                     };
191                     let last_bpos = self.pos;
192                     self.sess
193                         .span_diagnostic
194                         .struct_span_fatal_with_code(
195                             self.mk_sp(start, last_bpos),
196                             msg,
197                             error_code!(E0758),
198                         )
199                         .emit();
200                     FatalError.raise();
201                 }
202
203                 if let Some(attr_style) = attr_style {
204                     self.forbid_bare_cr(start, string, "bare CR not allowed in block doc-comment");
205                     // Opening delimiter of the length 3 and closing delimiter of the length 2
206                     // are not included into the symbol.
207                     token::DocComment(
208                         CommentKind::Block,
209                         attr_style,
210                         Symbol::intern(&string[3..string.len() - if terminated { 2 } else { 0 }]),
211                     )
212                 } else {
213                     token::Comment
214                 }
215             }
216             rustc_lexer::TokenKind::Whitespace => token::Whitespace,
217             rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => {
218                 let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent;
219                 let mut ident_start = start;
220                 if is_raw_ident {
221                     ident_start = ident_start + BytePos(2);
222                 }
223                 let sym = nfc_normalize(self.str_from(ident_start));
224                 let span = self.mk_sp(start, self.pos);
225                 self.sess.symbol_gallery.insert(sym, span);
226                 if is_raw_ident {
227                     if !sym.can_be_raw() {
228                         self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
229                     }
230                     self.sess.raw_identifier_spans.borrow_mut().push(span);
231                 }
232                 token::Ident(sym, is_raw_ident)
233             }
234             rustc_lexer::TokenKind::Literal { kind, suffix_start } => {
235                 let suffix_start = start + BytePos(suffix_start as u32);
236                 let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind);
237                 let suffix = if suffix_start < self.pos {
238                     let string = self.str_from(suffix_start);
239                     if string == "_" {
240                         self.sess
241                             .span_diagnostic
242                             .struct_span_warn(
243                                 self.mk_sp(suffix_start, self.pos),
244                                 "underscore literal suffix is not allowed",
245                             )
246                             .warn(
247                                 "this was previously accepted by the compiler but is \
248                                    being phased out; it will become a hard error in \
249                                    a future release!",
250                             )
251                             .note(
252                                 "see issue #42326 \
253                                  <https://github.com/rust-lang/rust/issues/42326> \
254                                  for more information",
255                             )
256                             .emit();
257                         None
258                     } else {
259                         Some(Symbol::intern(string))
260                     }
261                 } else {
262                     None
263                 };
264                 token::Literal(token::Lit { kind, symbol, suffix })
265             }
266             rustc_lexer::TokenKind::Lifetime { starts_with_number } => {
267                 // Include the leading `'` in the real identifier, for macro
268                 // expansion purposes. See #12512 for the gory details of why
269                 // this is necessary.
270                 let lifetime_name = self.str_from(start);
271                 if starts_with_number {
272                     self.err_span_(start, self.pos, "lifetimes cannot start with a number");
273                 }
274                 let ident = Symbol::intern(lifetime_name);
275                 token::Lifetime(ident)
276             }
277             rustc_lexer::TokenKind::Semi => token::Semi,
278             rustc_lexer::TokenKind::Comma => token::Comma,
279             rustc_lexer::TokenKind::Dot => token::Dot,
280             rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren),
281             rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren),
282             rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace),
283             rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace),
284             rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(token::Bracket),
285             rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(token::Bracket),
286             rustc_lexer::TokenKind::At => token::At,
287             rustc_lexer::TokenKind::Pound => token::Pound,
288             rustc_lexer::TokenKind::Tilde => token::Tilde,
289             rustc_lexer::TokenKind::Question => token::Question,
290             rustc_lexer::TokenKind::Colon => token::Colon,
291             rustc_lexer::TokenKind::Dollar => token::Dollar,
292             rustc_lexer::TokenKind::Eq => token::Eq,
293             rustc_lexer::TokenKind::Not => token::Not,
294             rustc_lexer::TokenKind::Lt => token::Lt,
295             rustc_lexer::TokenKind::Gt => token::Gt,
296             rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus),
297             rustc_lexer::TokenKind::And => token::BinOp(token::And),
298             rustc_lexer::TokenKind::Or => token::BinOp(token::Or),
299             rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus),
300             rustc_lexer::TokenKind::Star => token::BinOp(token::Star),
301             rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash),
302             rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret),
303             rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent),
304
305             rustc_lexer::TokenKind::Unknown => {
306                 let c = self.str_from(start).chars().next().unwrap();
307                 let mut err =
308                     self.struct_fatal_span_char(start, self.pos, "unknown start of token", c);
309                 // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs,
310                 // instead of keeping a table in `check_for_substitution`into the token. Ideally,
311                 // this should be inside `rustc_lexer`. However, we should first remove compound
312                 // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it,
313                 // as there will be less overall work to do this way.
314                 let token = unicode_chars::check_for_substitution(self, start, c, &mut err)
315                     .unwrap_or_else(|| token::Unknown(self.symbol_from(start)));
316                 err.emit();
317                 token
318             }
319         }
320     }
321
322     fn cook_lexer_literal(
323         &self,
324         start: BytePos,
325         suffix_start: BytePos,
326         kind: rustc_lexer::LiteralKind,
327     ) -> (token::LitKind, Symbol) {
328         // prefix means `"` or `br"` or `r###"`, ...
329         let (lit_kind, mode, prefix_len, postfix_len) = match kind {
330             rustc_lexer::LiteralKind::Char { terminated } => {
331                 if !terminated {
332                     self.sess
333                         .span_diagnostic
334                         .struct_span_fatal_with_code(
335                             self.mk_sp(start, suffix_start),
336                             "unterminated character literal",
337                             error_code!(E0762),
338                         )
339                         .emit();
340                     FatalError.raise();
341                 }
342                 (token::Char, Mode::Char, 1, 1) // ' '
343             }
344             rustc_lexer::LiteralKind::Byte { terminated } => {
345                 if !terminated {
346                     self.sess
347                         .span_diagnostic
348                         .struct_span_fatal_with_code(
349                             self.mk_sp(start + BytePos(1), suffix_start),
350                             "unterminated byte constant",
351                             error_code!(E0763),
352                         )
353                         .emit();
354                     FatalError.raise();
355                 }
356                 (token::Byte, Mode::Byte, 2, 1) // b' '
357             }
358             rustc_lexer::LiteralKind::Str { terminated } => {
359                 if !terminated {
360                     self.sess
361                         .span_diagnostic
362                         .struct_span_fatal_with_code(
363                             self.mk_sp(start, suffix_start),
364                             "unterminated double quote string",
365                             error_code!(E0765),
366                         )
367                         .emit();
368                     FatalError.raise();
369                 }
370                 (token::Str, Mode::Str, 1, 1) // " "
371             }
372             rustc_lexer::LiteralKind::ByteStr { terminated } => {
373                 if !terminated {
374                     self.sess
375                         .span_diagnostic
376                         .struct_span_fatal_with_code(
377                             self.mk_sp(start + BytePos(1), suffix_start),
378                             "unterminated double quote byte string",
379                             error_code!(E0766),
380                         )
381                         .emit();
382                     FatalError.raise();
383                 }
384                 (token::ByteStr, Mode::ByteStr, 2, 1) // b" "
385             }
386             rustc_lexer::LiteralKind::RawStr { n_hashes, err } => {
387                 self.report_raw_str_error(start, err);
388                 let n = u32::from(n_hashes);
389                 (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "##
390             }
391             rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => {
392                 self.report_raw_str_error(start, err);
393                 let n = u32::from(n_hashes);
394                 (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "##
395             }
396             rustc_lexer::LiteralKind::Int { base, empty_int } => {
397                 return if empty_int {
398                     self.sess
399                         .span_diagnostic
400                         .struct_span_err_with_code(
401                             self.mk_sp(start, suffix_start),
402                             "no valid digits found for number",
403                             error_code!(E0768),
404                         )
405                         .emit();
406                     (token::Integer, sym::integer(0))
407                 } else {
408                     self.validate_int_literal(base, start, suffix_start);
409                     (token::Integer, self.symbol_from_to(start, suffix_start))
410                 };
411             }
412             rustc_lexer::LiteralKind::Float { base, empty_exponent } => {
413                 if empty_exponent {
414                     self.err_span_(start, self.pos, "expected at least one digit in exponent");
415                 }
416
417                 match base {
418                     Base::Hexadecimal => self.err_span_(
419                         start,
420                         suffix_start,
421                         "hexadecimal float literal is not supported",
422                     ),
423                     Base::Octal => {
424                         self.err_span_(start, suffix_start, "octal float literal is not supported")
425                     }
426                     Base::Binary => {
427                         self.err_span_(start, suffix_start, "binary float literal is not supported")
428                     }
429                     _ => (),
430                 }
431
432                 let id = self.symbol_from_to(start, suffix_start);
433                 return (token::Float, id);
434             }
435         };
436         let content_start = start + BytePos(prefix_len);
437         let content_end = suffix_start - BytePos(postfix_len);
438         let id = self.symbol_from_to(content_start, content_end);
439         self.validate_literal_escape(mode, content_start, content_end);
440         (lit_kind, id)
441     }
442
443     pub fn pos(&self) -> BytePos {
444         self.pos
445     }
446
447     #[inline]
448     fn src_index(&self, pos: BytePos) -> usize {
449         (pos - self.start_pos).to_usize()
450     }
451
452     /// Slice of the source text from `start` up to but excluding `self.pos`,
453     /// meaning the slice does not include the character `self.ch`.
454     fn str_from(&self, start: BytePos) -> &str {
455         self.str_from_to(start, self.pos)
456     }
457
458     /// Creates a Symbol from a given offset to the current offset.
459     fn symbol_from(&self, start: BytePos) -> Symbol {
460         debug!("taking an ident from {:?} to {:?}", start, self.pos);
461         Symbol::intern(self.str_from(start))
462     }
463
464     /// As symbol_from, with an explicit endpoint.
465     fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
466         debug!("taking an ident from {:?} to {:?}", start, end);
467         Symbol::intern(self.str_from_to(start, end))
468     }
469
470     /// Slice of the source text spanning from `start` up to but excluding `end`.
471     fn str_from_to(&self, start: BytePos, end: BytePos) -> &str {
472         &self.src[self.src_index(start)..self.src_index(end)]
473     }
474
475     fn forbid_bare_cr(&self, start: BytePos, s: &str, errmsg: &str) {
476         let mut idx = 0;
477         loop {
478             idx = match s[idx..].find('\r') {
479                 None => break,
480                 Some(it) => idx + it + 1,
481             };
482             self.err_span_(start + BytePos(idx as u32 - 1), start + BytePos(idx as u32), errmsg);
483         }
484     }
485
486     fn report_raw_str_error(&self, start: BytePos, opt_err: Option<RawStrError>) {
487         match opt_err {
488             Some(RawStrError::InvalidStarter { bad_char }) => {
489                 self.report_non_started_raw_string(start, bad_char)
490             }
491             Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self
492                 .report_unterminated_raw_string(start, expected, possible_terminator_offset, found),
493             Some(RawStrError::TooManyDelimiters { found }) => {
494                 self.report_too_many_hashes(start, found)
495             }
496             None => (),
497         }
498     }
499
500     fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
501         self.struct_fatal_span_char(
502             start,
503             self.pos,
504             "found invalid character; only `#` is allowed in raw string delimitation",
505             bad_char,
506         )
507         .emit();
508         FatalError.raise()
509     }
510
511     fn report_unterminated_raw_string(
512         &self,
513         start: BytePos,
514         n_hashes: usize,
515         possible_offset: Option<usize>,
516         found_terminators: usize,
517     ) -> ! {
518         let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code(
519             self.mk_sp(start, start),
520             "unterminated raw string",
521             error_code!(E0748),
522         );
523
524         err.span_label(self.mk_sp(start, start), "unterminated raw string");
525
526         if n_hashes > 0 {
527             err.note(&format!(
528                 "this raw string should be terminated with `\"{}`",
529                 "#".repeat(n_hashes)
530             ));
531         }
532
533         if let Some(possible_offset) = possible_offset {
534             let lo = start + BytePos(possible_offset as u32);
535             let hi = lo + BytePos(found_terminators as u32);
536             let span = self.mk_sp(lo, hi);
537             err.span_suggestion(
538                 span,
539                 "consider terminating the string here",
540                 "#".repeat(n_hashes),
541                 Applicability::MaybeIncorrect,
542             );
543         }
544
545         err.emit();
546         FatalError.raise()
547     }
548
549     /// Note: It was decided to not add a test case, because it would be to big.
550     /// https://github.com/rust-lang/rust/pull/50296#issuecomment-392135180
551     fn report_too_many_hashes(&self, start: BytePos, found: usize) -> ! {
552         self.fatal_span_(
553             start,
554             self.pos,
555             &format!(
556                 "too many `#` symbols: raw strings may be delimited \
557                 by up to 65535 `#` symbols, but found {}",
558                 found
559             ),
560         )
561         .raise();
562     }
563
564     fn validate_literal_escape(&self, mode: Mode, content_start: BytePos, content_end: BytePos) {
565         let lit_content = self.str_from_to(content_start, content_end);
566         unescape::unescape_literal(lit_content, mode, &mut |range, result| {
567             // Here we only check for errors. The actual unescaping is done later.
568             if let Err(err) = result {
569                 let span_with_quotes =
570                     self.mk_sp(content_start - BytePos(1), content_end + BytePos(1));
571                 emit_unescape_error(
572                     &self.sess.span_diagnostic,
573                     lit_content,
574                     span_with_quotes,
575                     mode,
576                     range,
577                     err,
578                 );
579             }
580         });
581     }
582
583     fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) {
584         let base = match base {
585             Base::Binary => 2,
586             Base::Octal => 8,
587             _ => return,
588         };
589         let s = self.str_from_to(content_start + BytePos(2), content_end);
590         for (idx, c) in s.char_indices() {
591             let idx = idx as u32;
592             if c != '_' && c.to_digit(base).is_none() {
593                 let lo = content_start + BytePos(2 + idx);
594                 let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
595                 self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
596             }
597         }
598     }
599 }
600
601 pub fn nfc_normalize(string: &str) -> Symbol {
602     use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};
603     match is_nfc_quick(string.chars()) {
604         IsNormalized::Yes => Symbol::intern(string),
605         _ => {
606             let normalized_str: String = string.chars().nfc().collect();
607             Symbol::intern(&normalized_str)
608         }
609     }
610 }