]>
Commit | Line | Data |
---|---|---|
3c0e092e | 1 | use crate::lexer::unicode_chars::UNICODE_ARRAY; |
136023e0 | 2 | use rustc_ast::ast::{self, AttrStyle}; |
04454e1e | 3 | use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind}; |
1b1a35ee | 4 | use rustc_ast::tokenstream::{Spacing, TokenStream}; |
3c0e092e | 5 | use rustc_ast::util::unicode::contains_text_flow_control_chars; |
5e7ed085 | 6 | use rustc_errors::{error_code, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult}; |
1b1a35ee XL |
7 | use rustc_lexer::unescape::{self, Mode}; |
8 | use rustc_lexer::{Base, DocStyle, RawStrError}; | |
c295e0f8 | 9 | use rustc_session::lint::builtin::{ |
3c0e092e | 10 | RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT, |
c295e0f8 | 11 | }; |
136023e0 | 12 | use rustc_session::lint::BuiltinLintDiagnostics; |
74b04a01 | 13 | use rustc_session::parse::ParseSess; |
dfeec247 | 14 | use rustc_span::symbol::{sym, Symbol}; |
136023e0 | 15 | use rustc_span::{edition::Edition, BytePos, Pos, Span}; |
1a4d82fc | 16 | |
3dfed10e | 17 | use tracing::debug; |
1a4d82fc | 18 | |
32a655c1 | 19 | mod tokentrees; |
60c5eb7d | 20 | mod unescape_error_reporting; |
dfeec247 | 21 | mod unicode_chars; |
ba9703b0 | 22 | |
5869c6ff | 23 | use unescape_error_reporting::{emit_unescape_error, escaped_char}; |
1a4d82fc | 24 | |
064997fb FG |
25 | // This type is used a lot. Make sure it doesn't unintentionally get bigger. |
26 | // | |
27 | // This assertion is in this crate, rather than in `rustc_lexer`, because that | |
28 | // crate cannot depend on `rustc_data_structures`. | |
29 | #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] | |
30 | rustc_data_structures::static_assert_size!(rustc_lexer::Token, 12); | |
31 | ||
9fa01778 XL |
32 | #[derive(Clone, Debug)] |
33 | pub struct UnmatchedBrace { | |
04454e1e FG |
34 | pub expected_delim: Delimiter, |
35 | pub found_delim: Option<Delimiter>, | |
9fa01778 XL |
36 | pub found_span: Span, |
37 | pub unclosed_span: Option<Span>, | |
38 | pub candidate_span: Option<Span>, | |
39 | } | |
40 | ||
923072b8 | 41 | pub(crate) fn parse_token_trees<'a>( |
1b1a35ee XL |
42 | sess: &'a ParseSess, |
43 | src: &'a str, | |
44 | start_pos: BytePos, | |
45 | override_span: Option<Span>, | |
46 | ) -> (PResult<'a, TokenStream>, Vec<UnmatchedBrace>) { | |
064997fb | 47 | StringReader { sess, start_pos, pos: start_pos, src, override_span }.into_token_trees() |
1b1a35ee XL |
48 | } |
49 | ||
50 | struct StringReader<'a> { | |
416331ca XL |
51 | sess: &'a ParseSess, |
52 | /// Initial position, read-only. | |
53 | start_pos: BytePos, | |
54 | /// The absolute offset within the source_map of the current character. | |
f9f354fc | 55 | pos: BytePos, |
416331ca | 56 | /// Source text to tokenize. |
1b1a35ee | 57 | src: &'a str, |
48663c56 | 58 | override_span: Option<Span>, |
cc61c64b XL |
59 | } |
60 | ||
32a655c1 | 61 | impl<'a> StringReader<'a> { |
416331ca | 62 | fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { |
e1599b0c | 63 | self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) |
8bb4bdeb XL |
64 | } |
65 | ||
1b1a35ee XL |
66 | /// Returns the next token, and info about preceding whitespace, if any. |
67 | fn next_token(&mut self) -> (Spacing, Token) { | |
68 | let mut spacing = Spacing::Joint; | |
69 | ||
70 | // Skip `#!` at the start of the file | |
064997fb FG |
71 | if self.pos == self.start_pos |
72 | && let Some(shebang_len) = rustc_lexer::strip_shebang(self.src) | |
73 | { | |
74 | self.pos = self.pos + BytePos::from_usize(shebang_len); | |
75 | spacing = Spacing::Alone; | |
416331ca XL |
76 | } |
77 | ||
1b1a35ee XL |
78 | // Skip trivial (whitespace & comments) tokens |
79 | loop { | |
80 | let start_src_index = self.src_index(self.pos); | |
064997fb | 81 | let text: &str = &self.src[start_src_index..]; |
416331ca | 82 | |
1b1a35ee XL |
83 | if text.is_empty() { |
84 | let span = self.mk_sp(self.pos, self.pos); | |
85 | return (spacing, Token::new(token::Eof, span)); | |
416331ca | 86 | } |
416331ca | 87 | |
1b1a35ee | 88 | let token = rustc_lexer::first_token(text); |
416331ca | 89 | |
1b1a35ee | 90 | let start = self.pos; |
064997fb | 91 | self.pos = self.pos + BytePos(token.len); |
416331ca | 92 | |
1b1a35ee | 93 | debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); |
416331ca | 94 | |
1b1a35ee XL |
95 | match self.cook_lexer_token(token.kind, start) { |
96 | Some(kind) => { | |
97 | let span = self.mk_sp(start, self.pos); | |
98 | return (spacing, Token::new(kind, span)); | |
99 | } | |
100 | None => spacing = Spacing::Alone, | |
101 | } | |
102 | } | |
1a4d82fc JJ |
103 | } |
104 | ||
105 | /// Report a fatal lexical error with a given span. | |
5e7ed085 | 106 | fn fatal_span(&self, sp: Span, m: &str) -> ! { |
32a655c1 | 107 | self.sess.span_diagnostic.span_fatal(sp, m) |
1a4d82fc JJ |
108 | } |
109 | ||
110 | /// Report a lexical error with a given span. | |
94b46f34 | 111 | fn err_span(&self, sp: Span, m: &str) { |
0731742a | 112 | self.sess.span_diagnostic.struct_span_err(sp, m).emit(); |
1a4d82fc JJ |
113 | } |
114 | ||
115 | /// Report a fatal error spanning [`from_pos`, `to_pos`). | |
5e7ed085 | 116 | fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! { |
041b39d2 | 117 | self.fatal_span(self.mk_sp(from_pos, to_pos), m) |
1a4d82fc JJ |
118 | } |
119 | ||
120 | /// Report a lexical error spanning [`from_pos`, `to_pos`). | |
121 | fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) { | |
041b39d2 | 122 | self.err_span(self.mk_sp(from_pos, to_pos), m) |
1a4d82fc JJ |
123 | } |
124 | ||
dfeec247 XL |
125 | fn struct_fatal_span_char( |
126 | &self, | |
127 | from_pos: BytePos, | |
128 | to_pos: BytePos, | |
129 | m: &str, | |
130 | c: char, | |
5e7ed085 | 131 | ) -> DiagnosticBuilder<'a, !> { |
5869c6ff XL |
132 | self.sess |
133 | .span_diagnostic | |
134 | .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) | |
9cc50fc6 | 135 | } |
1a4d82fc | 136 | |
5e7ed085 FG |
137 | fn struct_err_span_char( |
138 | &self, | |
139 | from_pos: BytePos, | |
140 | to_pos: BytePos, | |
141 | m: &str, | |
142 | c: char, | |
143 | ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { | |
144 | self.sess | |
145 | .span_diagnostic | |
146 | .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) | |
147 | } | |
148 | ||
c295e0f8 XL |
149 | /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly |
150 | /// complain about it. | |
151 | fn lint_unicode_text_flow(&self, start: BytePos) { | |
152 | // Opening delimiter of the length 2 is not included into the comment text. | |
153 | let content_start = start + BytePos(2); | |
154 | let content = self.str_from(content_start); | |
3c0e092e XL |
155 | if contains_text_flow_control_chars(content) { |
156 | let span = self.mk_sp(start, self.pos); | |
c295e0f8 XL |
157 | self.sess.buffer_lint_with_diagnostic( |
158 | &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, | |
159 | span, | |
160 | ast::CRATE_NODE_ID, | |
161 | "unicode codepoint changing visible direction of text present in comment", | |
162 | BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), | |
163 | ); | |
164 | } | |
165 | } | |
166 | ||
416331ca | 167 | /// Turns simple `rustc_lexer::TokenKind` enum into a rich |
cdc7bbd5 | 168 | /// `rustc_ast::TokenKind`. This turns strings into interned |
416331ca | 169 | /// symbols and runs additional validation. |
1b1a35ee XL |
170 | fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option<TokenKind> { |
171 | Some(match token { | |
3dfed10e | 172 | rustc_lexer::TokenKind::LineComment { doc_style } => { |
1b1a35ee | 173 | // Skip non-doc comments |
5099ac24 | 174 | let Some(doc_style) = doc_style else { |
c295e0f8 XL |
175 | self.lint_unicode_text_flow(start); |
176 | return None; | |
177 | }; | |
3dfed10e | 178 | |
1b1a35ee XL |
179 | // Opening delimiter of the length 3 is not included into the symbol. |
180 | let content_start = start + BytePos(3); | |
181 | let content = self.str_from(content_start); | |
182 | self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) | |
416331ca | 183 | } |
3dfed10e | 184 | rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { |
416331ca | 185 | if !terminated { |
04454e1e | 186 | self.report_unterminated_block_comment(start, doc_style); |
416331ca | 187 | } |
1b1a35ee XL |
188 | |
189 | // Skip non-doc comments | |
5099ac24 | 190 | let Some(doc_style) = doc_style else { |
c295e0f8 XL |
191 | self.lint_unicode_text_flow(start); |
192 | return None; | |
193 | }; | |
1b1a35ee XL |
194 | |
195 | // Opening delimiter of the length 3 and closing delimiter of the length 2 | |
196 | // are not included into the symbol. | |
197 | let content_start = start + BytePos(3); | |
198 | let content_end = self.pos - BytePos(if terminated { 2 } else { 0 }); | |
199 | let content = self.str_from_to(content_start, content_end); | |
200 | self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style) | |
9cc50fc6 | 201 | } |
1b1a35ee | 202 | rustc_lexer::TokenKind::Whitespace => return None, |
136023e0 XL |
203 | rustc_lexer::TokenKind::Ident |
204 | | rustc_lexer::TokenKind::RawIdent | |
205 | | rustc_lexer::TokenKind::UnknownPrefix => { | |
416331ca | 206 | let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; |
136023e0 | 207 | let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; |
416331ca XL |
208 | let mut ident_start = start; |
209 | if is_raw_ident { | |
210 | ident_start = ident_start + BytePos(2); | |
211 | } | |
136023e0 XL |
212 | if is_unknown_prefix { |
213 | self.report_unknown_prefix(start); | |
214 | } | |
dfeec247 | 215 | let sym = nfc_normalize(self.str_from(ident_start)); |
f9f354fc XL |
216 | let span = self.mk_sp(start, self.pos); |
217 | self.sess.symbol_gallery.insert(sym, span); | |
416331ca | 218 | if is_raw_ident { |
416331ca XL |
219 | if !sym.can_be_raw() { |
220 | self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); | |
221 | } | |
222 | self.sess.raw_identifier_spans.borrow_mut().push(span); | |
223 | } | |
224 | token::Ident(sym, is_raw_ident) | |
225 | } | |
3c0e092e XL |
226 | rustc_lexer::TokenKind::InvalidIdent |
227 | // Do not recover an identifier with emoji if the codepoint is a confusable | |
228 | // with a recoverable substitution token, like `➖`. | |
04454e1e | 229 | if !UNICODE_ARRAY |
3c0e092e | 230 | .iter() |
04454e1e | 231 | .any(|&(c, _, _)| { |
3c0e092e XL |
232 | let sym = self.str_from(start); |
233 | sym.chars().count() == 1 && c == sym.chars().next().unwrap() | |
234 | }) | |
04454e1e | 235 | => |
3c0e092e XL |
236 | { |
237 | let sym = nfc_normalize(self.str_from(start)); | |
238 | let span = self.mk_sp(start, self.pos); | |
239 | self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); | |
240 | token::Ident(sym, false) | |
241 | } | |
416331ca | 242 | rustc_lexer::TokenKind::Literal { kind, suffix_start } => { |
064997fb | 243 | let suffix_start = start + BytePos(suffix_start); |
416331ca XL |
244 | let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); |
245 | let suffix = if suffix_start < self.pos { | |
246 | let string = self.str_from(suffix_start); | |
247 | if string == "_" { | |
dfeec247 XL |
248 | self.sess |
249 | .span_diagnostic | |
250 | .struct_span_warn( | |
251 | self.mk_sp(suffix_start, self.pos), | |
252 | "underscore literal suffix is not allowed", | |
253 | ) | |
254 | .warn( | |
255 | "this was previously accepted by the compiler but is \ | |
416331ca | 256 | being phased out; it will become a hard error in \ |
dfeec247 XL |
257 | a future release!", |
258 | ) | |
259 | .note( | |
74b04a01 XL |
260 | "see issue #42326 \ |
261 | <https://github.com/rust-lang/rust/issues/42326> \ | |
262 | for more information", | |
dfeec247 | 263 | ) |
416331ca XL |
264 | .emit(); |
265 | None | |
266 | } else { | |
267 | Some(Symbol::intern(string)) | |
268 | } | |
1a4d82fc | 269 | } else { |
416331ca | 270 | None |
1a4d82fc | 271 | }; |
416331ca XL |
272 | token::Literal(token::Lit { kind, symbol, suffix }) |
273 | } | |
274 | rustc_lexer::TokenKind::Lifetime { starts_with_number } => { | |
275 | // Include the leading `'` in the real identifier, for macro | |
276 | // expansion purposes. See #12512 for the gory details of why | |
277 | // this is necessary. | |
278 | let lifetime_name = self.str_from(start); | |
279 | if starts_with_number { | |
dfeec247 | 280 | self.err_span_(start, self.pos, "lifetimes cannot start with a number"); |
416331ca XL |
281 | } |
282 | let ident = Symbol::intern(lifetime_name); | |
283 | token::Lifetime(ident) | |
284 | } | |
285 | rustc_lexer::TokenKind::Semi => token::Semi, | |
286 | rustc_lexer::TokenKind::Comma => token::Comma, | |
416331ca | 287 | rustc_lexer::TokenKind::Dot => token::Dot, |
04454e1e FG |
288 | rustc_lexer::TokenKind::OpenParen => token::OpenDelim(Delimiter::Parenthesis), |
289 | rustc_lexer::TokenKind::CloseParen => token::CloseDelim(Delimiter::Parenthesis), | |
290 | rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(Delimiter::Brace), | |
291 | rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(Delimiter::Brace), | |
292 | rustc_lexer::TokenKind::OpenBracket => token::OpenDelim(Delimiter::Bracket), | |
293 | rustc_lexer::TokenKind::CloseBracket => token::CloseDelim(Delimiter::Bracket), | |
416331ca XL |
294 | rustc_lexer::TokenKind::At => token::At, |
295 | rustc_lexer::TokenKind::Pound => token::Pound, | |
296 | rustc_lexer::TokenKind::Tilde => token::Tilde, | |
297 | rustc_lexer::TokenKind::Question => token::Question, | |
416331ca XL |
298 | rustc_lexer::TokenKind::Colon => token::Colon, |
299 | rustc_lexer::TokenKind::Dollar => token::Dollar, | |
416331ca | 300 | rustc_lexer::TokenKind::Eq => token::Eq, |
3dfed10e | 301 | rustc_lexer::TokenKind::Bang => token::Not, |
416331ca | 302 | rustc_lexer::TokenKind::Lt => token::Lt, |
416331ca | 303 | rustc_lexer::TokenKind::Gt => token::Gt, |
416331ca | 304 | rustc_lexer::TokenKind::Minus => token::BinOp(token::Minus), |
416331ca | 305 | rustc_lexer::TokenKind::And => token::BinOp(token::And), |
416331ca | 306 | rustc_lexer::TokenKind::Or => token::BinOp(token::Or), |
416331ca | 307 | rustc_lexer::TokenKind::Plus => token::BinOp(token::Plus), |
416331ca | 308 | rustc_lexer::TokenKind::Star => token::BinOp(token::Star), |
416331ca | 309 | rustc_lexer::TokenKind::Slash => token::BinOp(token::Slash), |
416331ca | 310 | rustc_lexer::TokenKind::Caret => token::BinOp(token::Caret), |
416331ca | 311 | rustc_lexer::TokenKind::Percent => token::BinOp(token::Percent), |
416331ca | 312 | |
3c0e092e | 313 | rustc_lexer::TokenKind::Unknown | rustc_lexer::TokenKind::InvalidIdent => { |
416331ca | 314 | let c = self.str_from(start).chars().next().unwrap(); |
dfeec247 | 315 | let mut err = |
5e7ed085 | 316 | self.struct_err_span_char(start, self.pos, "unknown start of token", c); |
416331ca XL |
317 | // FIXME: the lexer could be used to turn the ASCII version of unicode homoglyphs, |
318 | // instead of keeping a table in `check_for_substitution`into the token. Ideally, | |
319 | // this should be inside `rustc_lexer`. However, we should first remove compound | |
320 | // tokens like `<<` from `rustc_lexer`, and then add fancier error recovery to it, | |
321 | // as there will be less overall work to do this way. | |
1b1a35ee | 322 | let token = unicode_chars::check_for_substitution(self, start, c, &mut err); |
6a06907d XL |
323 | if c == '\x00' { |
324 | err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); | |
325 | } | |
416331ca | 326 | err.emit(); |
1b1a35ee | 327 | token? |
1a4d82fc | 328 | } |
1b1a35ee | 329 | }) |
416331ca | 330 | } |
b7449926 | 331 | |
3dfed10e XL |
332 | fn cook_doc_comment( |
333 | &self, | |
334 | content_start: BytePos, | |
335 | content: &str, | |
336 | comment_kind: CommentKind, | |
337 | doc_style: DocStyle, | |
338 | ) -> TokenKind { | |
339 | if content.contains('\r') { | |
340 | for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { | |
341 | self.err_span_( | |
342 | content_start + BytePos(idx as u32), | |
343 | content_start + BytePos(idx as u32 + 1), | |
344 | match comment_kind { | |
345 | CommentKind::Line => "bare CR not allowed in doc-comment", | |
346 | CommentKind::Block => "bare CR not allowed in block doc-comment", | |
347 | }, | |
348 | ); | |
349 | } | |
350 | } | |
351 | ||
352 | let attr_style = match doc_style { | |
353 | DocStyle::Outer => AttrStyle::Outer, | |
354 | DocStyle::Inner => AttrStyle::Inner, | |
355 | }; | |
356 | ||
357 | token::DocComment(comment_kind, attr_style, Symbol::intern(content)) | |
358 | } | |
359 | ||
416331ca XL |
360 | fn cook_lexer_literal( |
361 | &self, | |
362 | start: BytePos, | |
363 | suffix_start: BytePos, | |
dfeec247 | 364 | kind: rustc_lexer::LiteralKind, |
416331ca | 365 | ) -> (token::LitKind, Symbol) { |
f9f354fc XL |
366 | // prefix means `"` or `br"` or `r###"`, ... |
367 | let (lit_kind, mode, prefix_len, postfix_len) = match kind { | |
416331ca XL |
368 | rustc_lexer::LiteralKind::Char { terminated } => { |
369 | if !terminated { | |
17df50a5 XL |
370 | self.sess.span_diagnostic.span_fatal_with_code( |
371 | self.mk_sp(start, suffix_start), | |
372 | "unterminated character literal", | |
373 | error_code!(E0762), | |
374 | ) | |
416331ca | 375 | } |
f9f354fc | 376 | (token::Char, Mode::Char, 1, 1) // ' ' |
dfeec247 | 377 | } |
416331ca XL |
378 | rustc_lexer::LiteralKind::Byte { terminated } => { |
379 | if !terminated { | |
17df50a5 XL |
380 | self.sess.span_diagnostic.span_fatal_with_code( |
381 | self.mk_sp(start + BytePos(1), suffix_start), | |
382 | "unterminated byte constant", | |
383 | error_code!(E0763), | |
384 | ) | |
416331ca | 385 | } |
f9f354fc | 386 | (token::Byte, Mode::Byte, 2, 1) // b' ' |
dfeec247 | 387 | } |
416331ca XL |
388 | rustc_lexer::LiteralKind::Str { terminated } => { |
389 | if !terminated { | |
17df50a5 XL |
390 | self.sess.span_diagnostic.span_fatal_with_code( |
391 | self.mk_sp(start, suffix_start), | |
392 | "unterminated double quote string", | |
393 | error_code!(E0765), | |
394 | ) | |
416331ca | 395 | } |
f9f354fc | 396 | (token::Str, Mode::Str, 1, 1) // " " |
416331ca XL |
397 | } |
398 | rustc_lexer::LiteralKind::ByteStr { terminated } => { | |
399 | if !terminated { | |
17df50a5 XL |
400 | self.sess.span_diagnostic.span_fatal_with_code( |
401 | self.mk_sp(start + BytePos(1), suffix_start), | |
402 | "unterminated double quote byte string", | |
403 | error_code!(E0766), | |
404 | ) | |
416331ca | 405 | } |
f9f354fc | 406 | (token::ByteStr, Mode::ByteStr, 2, 1) // b" " |
416331ca | 407 | } |
064997fb FG |
408 | rustc_lexer::LiteralKind::RawStr { n_hashes } => { |
409 | if let Some(n_hashes) = n_hashes { | |
410 | let n = u32::from(n_hashes); | |
411 | (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## | |
412 | } else { | |
413 | self.report_raw_str_error(start, 1); | |
414 | } | |
416331ca | 415 | } |
064997fb FG |
416 | rustc_lexer::LiteralKind::RawByteStr { n_hashes } => { |
417 | if let Some(n_hashes) = n_hashes { | |
418 | let n = u32::from(n_hashes); | |
419 | (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## | |
420 | } else { | |
421 | self.report_raw_str_error(start, 2); | |
422 | } | |
416331ca XL |
423 | } |
424 | rustc_lexer::LiteralKind::Int { base, empty_int } => { | |
f9f354fc | 425 | return if empty_int { |
f035d41b XL |
426 | self.sess |
427 | .span_diagnostic | |
428 | .struct_span_err_with_code( | |
429 | self.mk_sp(start, suffix_start), | |
430 | "no valid digits found for number", | |
431 | error_code!(E0768), | |
432 | ) | |
433 | .emit(); | |
416331ca XL |
434 | (token::Integer, sym::integer(0)) |
435 | } else { | |
436 | self.validate_int_literal(base, start, suffix_start); | |
437 | (token::Integer, self.symbol_from_to(start, suffix_start)) | |
f9f354fc | 438 | }; |
dfeec247 | 439 | } |
416331ca XL |
440 | rustc_lexer::LiteralKind::Float { base, empty_exponent } => { |
441 | if empty_exponent { | |
f035d41b | 442 | self.err_span_(start, self.pos, "expected at least one digit in exponent"); |
416331ca XL |
443 | } |
444 | ||
445 | match base { | |
dfeec247 XL |
446 | Base::Hexadecimal => self.err_span_( |
447 | start, | |
448 | suffix_start, | |
449 | "hexadecimal float literal is not supported", | |
450 | ), | |
416331ca | 451 | Base::Octal => { |
dfeec247 | 452 | self.err_span_(start, suffix_start, "octal float literal is not supported") |
416331ca XL |
453 | } |
454 | Base::Binary => { | |
dfeec247 | 455 | self.err_span_(start, suffix_start, "binary float literal is not supported") |
416331ca | 456 | } |
dfeec247 | 457 | _ => (), |
416331ca XL |
458 | } |
459 | ||
460 | let id = self.symbol_from_to(start, suffix_start); | |
f9f354fc | 461 | return (token::Float, id); |
dfeec247 | 462 | } |
f9f354fc XL |
463 | }; |
464 | let content_start = start + BytePos(prefix_len); | |
465 | let content_end = suffix_start - BytePos(postfix_len); | |
466 | let id = self.symbol_from_to(content_start, content_end); | |
5869c6ff | 467 | self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); |
f035d41b | 468 | (lit_kind, id) |
f9f354fc XL |
469 | } |
470 | ||
94b46f34 XL |
471 | #[inline] |
472 | fn src_index(&self, pos: BytePos) -> usize { | |
416331ca | 473 | (pos - self.start_pos).to_usize() |
1a4d82fc JJ |
474 | } |
475 | ||
dc9dc135 XL |
476 | /// Slice of the source text from `start` up to but excluding `self.pos`, |
477 | /// meaning the slice does not include the character `self.ch`. | |
dfeec247 | 478 | fn str_from(&self, start: BytePos) -> &str { |
dc9dc135 | 479 | self.str_from_to(start, self.pos) |
1a4d82fc JJ |
480 | } |
481 | ||
dc9dc135 XL |
482 | /// As symbol_from, with an explicit endpoint. |
483 | fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { | |
1a4d82fc | 484 | debug!("taking an ident from {:?} to {:?}", start, end); |
dc9dc135 | 485 | Symbol::intern(self.str_from_to(start, end)) |
1a4d82fc JJ |
486 | } |
487 | ||
dc9dc135 | 488 | /// Slice of the source text spanning from `start` up to but excluding `end`. |
dfeec247 | 489 | fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { |
dc9dc135 | 490 | &self.src[self.src_index(start)..self.src_index(end)] |
1a4d82fc JJ |
491 | } |
492 | ||
064997fb FG |
493 | fn report_raw_str_error(&self, start: BytePos, prefix_len: u32) -> ! { |
494 | match rustc_lexer::validate_raw_str(self.str_from(start), prefix_len) { | |
495 | Err(RawStrError::InvalidStarter { bad_char }) => { | |
f035d41b XL |
496 | self.report_non_started_raw_string(start, bad_char) |
497 | } | |
064997fb | 498 | Err(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self |
f035d41b | 499 | .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), |
064997fb | 500 | Err(RawStrError::TooManyDelimiters { found }) => { |
f035d41b | 501 | self.report_too_many_hashes(start, found) |
ba9703b0 | 502 | } |
064997fb | 503 | Ok(()) => panic!("no error found for supposedly invalid raw string literal"), |
ba9703b0 XL |
504 | } |
505 | } | |
506 | ||
f035d41b | 507 | fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! { |
dfeec247 XL |
508 | self.struct_fatal_span_char( |
509 | start, | |
510 | self.pos, | |
f035d41b | 511 | "found invalid character; only `#` is allowed in raw string delimitation", |
dfeec247 XL |
512 | bad_char, |
513 | ) | |
5e7ed085 | 514 | .emit() |
1a4d82fc JJ |
515 | } |
516 | ||
ba9703b0 XL |
517 | fn report_unterminated_raw_string( |
518 | &self, | |
519 | start: BytePos, | |
064997fb FG |
520 | n_hashes: u32, |
521 | possible_offset: Option<u32>, | |
522 | found_terminators: u32, | |
ba9703b0 | 523 | ) -> ! { |
74b04a01 XL |
524 | let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code( |
525 | self.mk_sp(start, start), | |
526 | "unterminated raw string", | |
527 | error_code!(E0748), | |
528 | ); | |
ba9703b0 | 529 | |
dfeec247 | 530 | err.span_label(self.mk_sp(start, start), "unterminated raw string"); |
1a4d82fc | 531 | |
416331ca | 532 | if n_hashes > 0 { |
dfeec247 XL |
533 | err.note(&format!( |
534 | "this raw string should be terminated with `\"{}`", | |
064997fb | 535 | "#".repeat(n_hashes as usize) |
dfeec247 | 536 | )); |
48663c56 | 537 | } |
1a4d82fc | 538 | |
ba9703b0 XL |
539 | if let Some(possible_offset) = possible_offset { |
540 | let lo = start + BytePos(possible_offset as u32); | |
541 | let hi = lo + BytePos(found_terminators as u32); | |
542 | let span = self.mk_sp(lo, hi); | |
543 | err.span_suggestion( | |
544 | span, | |
545 | "consider terminating the string here", | |
064997fb | 546 | "#".repeat(n_hashes as usize), |
ba9703b0 XL |
547 | Applicability::MaybeIncorrect, |
548 | ); | |
549 | } | |
550 | ||
5e7ed085 | 551 | err.emit() |
1a4d82fc JJ |
552 | } |
553 | ||
04454e1e FG |
554 | fn report_unterminated_block_comment(&self, start: BytePos, doc_style: Option<DocStyle>) { |
555 | let msg = match doc_style { | |
556 | Some(_) => "unterminated block doc-comment", | |
557 | None => "unterminated block comment", | |
558 | }; | |
559 | let last_bpos = self.pos; | |
560 | let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code( | |
561 | self.mk_sp(start, last_bpos), | |
562 | msg, | |
563 | error_code!(E0758), | |
564 | ); | |
565 | let mut nested_block_comment_open_idxs = vec![]; | |
566 | let mut last_nested_block_comment_idxs = None; | |
567 | let mut content_chars = self.str_from(start).char_indices().peekable(); | |
568 | ||
569 | while let Some((idx, current_char)) = content_chars.next() { | |
570 | match content_chars.peek() { | |
571 | Some((_, '*')) if current_char == '/' => { | |
572 | nested_block_comment_open_idxs.push(idx); | |
573 | } | |
574 | Some((_, '/')) if current_char == '*' => { | |
575 | last_nested_block_comment_idxs = | |
576 | nested_block_comment_open_idxs.pop().map(|open_idx| (open_idx, idx)); | |
577 | } | |
578 | _ => {} | |
579 | }; | |
580 | } | |
581 | ||
582 | if let Some((nested_open_idx, nested_close_idx)) = last_nested_block_comment_idxs { | |
583 | err.span_label(self.mk_sp(start, start + BytePos(2)), msg) | |
584 | .span_label( | |
585 | self.mk_sp( | |
586 | start + BytePos(nested_open_idx as u32), | |
587 | start + BytePos(nested_open_idx as u32 + 2), | |
588 | ), | |
589 | "...as last nested comment starts here, maybe you want to close this instead?", | |
590 | ) | |
591 | .span_label( | |
592 | self.mk_sp( | |
593 | start + BytePos(nested_close_idx as u32), | |
594 | start + BytePos(nested_close_idx as u32 + 2), | |
595 | ), | |
596 | "...and last nested comment terminates here.", | |
597 | ); | |
598 | } | |
599 | ||
600 | err.emit(); | |
601 | } | |
602 | ||
136023e0 XL |
603 | // RFC 3101 introduced the idea of (reserved) prefixes. As of Rust 2021, |
604 | // using a (unknown) prefix is an error. In earlier editions, however, they | |
605 | // only result in a (allowed by default) lint, and are treated as regular | |
606 | // identifier tokens. | |
607 | fn report_unknown_prefix(&self, start: BytePos) { | |
608 | let prefix_span = self.mk_sp(start, self.pos); | |
94222f64 XL |
609 | let prefix_str = self.str_from_to(start, self.pos); |
610 | let msg = format!("prefix `{}` is unknown", prefix_str); | |
136023e0 XL |
611 | |
612 | let expn_data = prefix_span.ctxt().outer_expn_data(); | |
613 | ||
614 | if expn_data.edition >= Edition::Edition2021 { | |
615 | // In Rust 2021, this is a hard error. | |
616 | let mut err = self.sess.span_diagnostic.struct_span_err(prefix_span, &msg); | |
617 | err.span_label(prefix_span, "unknown prefix"); | |
94222f64 XL |
618 | if prefix_str == "rb" { |
619 | err.span_suggestion_verbose( | |
620 | prefix_span, | |
621 | "use `br` for a raw byte string", | |
04454e1e | 622 | "br", |
94222f64 XL |
623 | Applicability::MaybeIncorrect, |
624 | ); | |
625 | } else if expn_data.is_root() { | |
136023e0 XL |
626 | err.span_suggestion_verbose( |
627 | prefix_span.shrink_to_hi(), | |
628 | "consider inserting whitespace here", | |
04454e1e | 629 | " ", |
94222f64 | 630 | Applicability::MaybeIncorrect, |
136023e0 XL |
631 | ); |
632 | } | |
633 | err.note("prefixed identifiers and literals are reserved since Rust 2021"); | |
634 | err.emit(); | |
635 | } else { | |
636 | // Before Rust 2021, only emit a lint for migration. | |
637 | self.sess.buffer_lint_with_diagnostic( | |
638 | &RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, | |
639 | prefix_span, | |
640 | ast::CRATE_NODE_ID, | |
641 | &msg, | |
642 | BuiltinLintDiagnostics::ReservedPrefix(prefix_span), | |
643 | ); | |
644 | } | |
645 | } | |
646 | ||
064997fb | 647 | fn report_too_many_hashes(&self, start: BytePos, found: u32) -> ! { |
ba9703b0 XL |
648 | self.fatal_span_( |
649 | start, | |
650 | self.pos, | |
f035d41b XL |
651 | &format!( |
652 | "too many `#` symbols: raw strings may be delimited \ | |
5e7ed085 | 653 | by up to 255 `#` symbols, but found {}", |
f035d41b XL |
654 | found |
655 | ), | |
ba9703b0 | 656 | ) |
1a4d82fc | 657 | } |
48663c56 | 658 | |
5869c6ff XL |
659 | fn validate_literal_escape( |
660 | &self, | |
661 | mode: Mode, | |
662 | content_start: BytePos, | |
663 | content_end: BytePos, | |
664 | prefix_len: u32, | |
665 | postfix_len: u32, | |
666 | ) { | |
f9f354fc XL |
667 | let lit_content = self.str_from_to(content_start, content_end); |
668 | unescape::unescape_literal(lit_content, mode, &mut |range, result| { | |
669 | // Here we only check for errors. The actual unescaping is done later. | |
670 | if let Err(err) = result { | |
5869c6ff XL |
671 | let span_with_quotes = self |
672 | .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); | |
fc512014 XL |
673 | let (start, end) = (range.start as u32, range.end as u32); |
674 | let lo = content_start + BytePos(start); | |
675 | let hi = lo + BytePos(end - start); | |
676 | let span = self.mk_sp(lo, hi); | |
dc9dc135 XL |
677 | emit_unescape_error( |
678 | &self.sess.span_diagnostic, | |
f9f354fc XL |
679 | lit_content, |
680 | span_with_quotes, | |
fc512014 | 681 | span, |
f9f354fc | 682 | mode, |
dc9dc135 XL |
683 | range, |
684 | err, | |
f9f354fc | 685 | ); |
dc9dc135 | 686 | } |
f9f354fc | 687 | }); |
48663c56 | 688 | } |
1a4d82fc | 689 | |
416331ca XL |
690 | fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { |
691 | let base = match base { | |
692 | Base::Binary => 2, | |
693 | Base::Octal => 8, | |
694 | _ => return, | |
695 | }; | |
696 | let s = self.str_from_to(content_start + BytePos(2), content_end); | |
697 | for (idx, c) in s.char_indices() { | |
698 | let idx = idx as u32; | |
699 | if c != '_' && c.to_digit(base).is_none() { | |
700 | let lo = content_start + BytePos(2 + idx); | |
701 | let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); | |
dfeec247 | 702 | self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); |
416331ca XL |
703 | } |
704 | } | |
705 | } | |
9cc50fc6 | 706 | } |
dfeec247 XL |
707 | |
708 | pub fn nfc_normalize(string: &str) -> Symbol { | |
709 | use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; | |
710 | match is_nfc_quick(string.chars()) { | |
711 | IsNormalized::Yes => Symbol::intern(string), | |
712 | _ => { | |
713 | let normalized_str: String = string.chars().nfc().collect(); | |
714 | Symbol::intern(&normalized_str) | |
715 | } | |
716 | } | |
717 | } |