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