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