]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/literal.rs
Auto merge of #60984 - matthewjasper:borrowck-error-reporting-cleanup, r=pnkfelix
[rust.git] / src / libsyntax / parse / literal.rs
1 //! Code related to parsing literals.
2
3 use crate::ast::{self, Ident, Lit, LitKind};
4 use crate::parse::parser::Parser;
5 use crate::parse::PResult;
6 use crate::parse::token::{self, Token};
7 use crate::parse::unescape::{unescape_str, unescape_char, unescape_byte_str, unescape_byte};
8 use crate::print::pprust;
9 use crate::symbol::{kw, sym, Symbol};
10 use crate::tokenstream::{TokenStream, TokenTree};
11
12 use errors::{Applicability, Handler};
13 use log::debug;
14 use rustc_data_structures::sync::Lrc;
15 use syntax_pos::Span;
16
17 use std::ascii;
18
19 crate enum LitError {
20     NotLiteral,
21     LexerError,
22     InvalidSuffix,
23     InvalidIntSuffix,
24     InvalidFloatSuffix,
25     NonDecimalFloat(u32),
26     IntTooLarge,
27 }
28
29 impl LitError {
30     fn report(&self, diag: &Handler, lit: token::Lit, span: Span) {
31         let token::Lit { kind, suffix, .. } = lit;
32         match *self {
33             // `NotLiteral` is not an error by itself, so we don't report
34             // it and give the parser opportunity to try something else.
35             LitError::NotLiteral => {}
36             // `LexerError` *is* an error, but it was already reported
37             // by lexer, so here we don't report it the second time.
38             LitError::LexerError => {}
39             LitError::InvalidSuffix => {
40                 expect_no_suffix(
41                     diag, span, &format!("{} {} literal", kind.article(), kind.descr()), suffix
42                 );
43             }
44             LitError::InvalidIntSuffix => {
45                 let suf = suffix.expect("suffix error with no suffix").as_str();
46                 if looks_like_width_suffix(&['i', 'u'], &suf) {
47                     // If it looks like a width, try to be helpful.
48                     let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
49                     diag.struct_span_err(span, &msg)
50                         .help("valid widths are 8, 16, 32, 64 and 128")
51                         .emit();
52                 } else {
53                     let msg = format!("invalid suffix `{}` for integer literal", suf);
54                     diag.struct_span_err(span, &msg)
55                         .span_label(span, format!("invalid suffix `{}`", suf))
56                         .help("the suffix must be one of the integral types (`u32`, `isize`, etc)")
57                         .emit();
58                 }
59             }
60             LitError::InvalidFloatSuffix => {
61                 let suf = suffix.expect("suffix error with no suffix").as_str();
62                 if looks_like_width_suffix(&['f'], &suf) {
63                     // If it looks like a width, try to be helpful.
64                     let msg = format!("invalid width `{}` for float literal", &suf[1..]);
65                     diag.struct_span_err(span, &msg)
66                         .help("valid widths are 32 and 64")
67                         .emit();
68                 } else {
69                     let msg = format!("invalid suffix `{}` for float literal", suf);
70                     diag.struct_span_err(span, &msg)
71                         .span_label(span, format!("invalid suffix `{}`", suf))
72                         .help("valid suffixes are `f32` and `f64`")
73                         .emit();
74                 }
75             }
76             LitError::NonDecimalFloat(base) => {
77                 let descr = match base {
78                     16 => "hexadecimal",
79                     8 => "octal",
80                     2 => "binary",
81                     _ => unreachable!(),
82                 };
83                 diag.struct_span_err(span, &format!("{} float literal is not supported", descr))
84                     .span_label(span, "not supported")
85                     .emit();
86             }
87             LitError::IntTooLarge => {
88                 diag.struct_span_err(span, "integer literal is too large")
89                     .emit();
90             }
91         }
92     }
93 }
94
95 impl LitKind {
96     /// Converts literal token into a semantic literal.
97     fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
98         let token::Lit { kind, symbol, suffix } = lit;
99         if suffix.is_some() && !kind.may_have_suffix() {
100             return Err(LitError::InvalidSuffix);
101         }
102
103         Ok(match kind {
104             token::Bool => {
105                 assert!(symbol == kw::True || symbol == kw::False);
106                 LitKind::Bool(symbol == kw::True)
107             }
108             token::Byte => return unescape_byte(&symbol.as_str())
109                 .map(LitKind::Byte).map_err(|_| LitError::LexerError),
110             token::Char => return unescape_char(&symbol.as_str())
111                 .map(LitKind::Char).map_err(|_| LitError::LexerError),
112
113             // There are some valid suffixes for integer and float literals,
114             // so all the handling is done internally.
115             token::Integer => return integer_lit(symbol, suffix),
116             token::Float => return float_lit(symbol, suffix),
117
118             token::Str => {
119                 // If there are no characters requiring special treatment we can
120                 // reuse the symbol from the token. Otherwise, we must generate a
121                 // new symbol because the string in the LitKind is different to the
122                 // string in the token.
123                 let s = symbol.as_str();
124                 let symbol = if s.contains(&['\\', '\r'][..]) {
125                     let mut buf = String::with_capacity(s.len());
126                     let mut error = Ok(());
127                     unescape_str(&s, &mut |_, unescaped_char| {
128                         match unescaped_char {
129                             Ok(c) => buf.push(c),
130                             Err(_) => error = Err(LitError::LexerError),
131                         }
132                     });
133                     error?;
134                     Symbol::intern(&buf)
135                 } else {
136                     symbol
137                 };
138                 LitKind::Str(symbol, ast::StrStyle::Cooked)
139             }
140             token::StrRaw(n) => {
141                 // Ditto.
142                 let s = symbol.as_str();
143                 let symbol = if s.contains('\r') {
144                     Symbol::intern(&raw_str_lit(&s))
145                 } else {
146                     symbol
147                 };
148                 LitKind::Str(symbol, ast::StrStyle::Raw(n))
149             }
150             token::ByteStr => {
151                 let s = symbol.as_str();
152                 let mut buf = Vec::with_capacity(s.len());
153                 let mut error = Ok(());
154                 unescape_byte_str(&s, &mut |_, unescaped_byte| {
155                     match unescaped_byte {
156                         Ok(c) => buf.push(c),
157                         Err(_) => error = Err(LitError::LexerError),
158                     }
159                 });
160                 error?;
161                 buf.shrink_to_fit();
162                 LitKind::ByteStr(Lrc::new(buf))
163             }
164             token::ByteStrRaw(_) => LitKind::ByteStr(Lrc::new(symbol.to_string().into_bytes())),
165             token::Err => LitKind::Err(symbol),
166         })
167     }
168
169     /// Attempts to recover a token from semantic literal.
170     /// This function is used when the original token doesn't exist (e.g. the literal is created
171     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
172     pub fn to_lit_token(&self) -> token::Lit {
173         let (kind, symbol, suffix) = match *self {
174             LitKind::Str(string, ast::StrStyle::Cooked) => {
175                 let escaped = string.as_str().escape_default().to_string();
176                 (token::Str, Symbol::intern(&escaped), None)
177             }
178             LitKind::Str(string, ast::StrStyle::Raw(n)) => {
179                 (token::StrRaw(n), string, None)
180             }
181             LitKind::ByteStr(ref bytes) => {
182                 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
183                     .map(Into::<char>::into).collect::<String>();
184                 (token::ByteStr, Symbol::intern(&string), None)
185             }
186             LitKind::Byte(byte) => {
187                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
188                 (token::Byte, Symbol::intern(&string), None)
189             }
190             LitKind::Char(ch) => {
191                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
192                 (token::Char, Symbol::intern(&string), None)
193             }
194             LitKind::Int(n, ty) => {
195                 let suffix = match ty {
196                     ast::LitIntType::Unsigned(ty) => Some(Symbol::intern(ty.ty_to_string())),
197                     ast::LitIntType::Signed(ty) => Some(Symbol::intern(ty.ty_to_string())),
198                     ast::LitIntType::Unsuffixed => None,
199                 };
200                 (token::Integer, Symbol::intern(&n.to_string()), suffix)
201             }
202             LitKind::Float(symbol, ty) => {
203                 (token::Float, symbol, Some(Symbol::intern(ty.ty_to_string())))
204             }
205             LitKind::FloatUnsuffixed(symbol) => {
206                 (token::Float, symbol, None)
207             }
208             LitKind::Bool(value) => {
209                 let symbol = if value { kw::True } else { kw::False };
210                 (token::Bool, symbol, None)
211             }
212             LitKind::Err(symbol) => {
213                 (token::Err, symbol, None)
214             }
215         };
216
217         token::Lit::new(kind, symbol, suffix)
218     }
219 }
220
221 impl Lit {
222     /// Converts literal token into an AST literal.
223     fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> {
224         Ok(Lit { token, node: LitKind::from_lit_token(token)?, span })
225     }
226
227     /// Converts arbitrary token into an AST literal.
228     crate fn from_token(token: &Token, span: Span) -> Result<Lit, LitError> {
229         let lit = match *token {
230             token::Ident(ident, false) if ident.name == kw::True || ident.name == kw::False =>
231                 token::Lit::new(token::Bool, ident.name, None),
232             token::Literal(lit) =>
233                 lit,
234             token::Interpolated(ref nt) => {
235                 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt {
236                     if let ast::ExprKind::Lit(lit) = &expr.node {
237                         return Ok(lit.clone());
238                     }
239                 }
240                 return Err(LitError::NotLiteral);
241             }
242             _ => return Err(LitError::NotLiteral)
243         };
244
245         Lit::from_lit_token(lit, span)
246     }
247
248     /// Attempts to recover an AST literal from semantic literal.
249     /// This function is used when the original token doesn't exist (e.g. the literal is created
250     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
251     pub fn from_lit_kind(node: LitKind, span: Span) -> Lit {
252         Lit { token: node.to_lit_token(), node, span }
253     }
254
255     /// Losslessly convert an AST literal into a token stream.
256     crate fn tokens(&self) -> TokenStream {
257         let token = match self.token.kind {
258             token::Bool => token::Ident(Ident::new(self.token.symbol, self.span), false),
259             _ => token::Literal(self.token),
260         };
261         TokenTree::Token(self.span, token).into()
262     }
263 }
264
265 impl<'a> Parser<'a> {
266     /// Matches `lit = true | false | token_lit`.
267     crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
268         let mut recovered = None;
269         if self.token == token::Dot {
270             // Attempt to recover `.4` as `0.4`.
271             recovered = self.look_ahead(1, |t| {
272                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = *t {
273                     let next_span = self.look_ahead_span(1);
274                     if self.span.hi() == next_span.lo() {
275                         let s = String::from("0.") + &symbol.as_str();
276                         let token = Token::lit(token::Float, Symbol::intern(&s), suffix);
277                         return Some((token, self.span.to(next_span)));
278                     }
279                 }
280                 None
281             });
282             if let Some((ref token, span)) = recovered {
283                 self.bump();
284                 self.diagnostic()
285                     .struct_span_err(span, "float literals must have an integer part")
286                     .span_suggestion(
287                         span,
288                         "must have an integer part",
289                         pprust::token_to_string(&token),
290                         Applicability::MachineApplicable,
291                     )
292                     .emit();
293             }
294         }
295
296         let (token, span) = recovered.as_ref().map_or((&self.token, self.span),
297                                                       |(token, span)| (token, *span));
298
299         match Lit::from_token(token, span) {
300             Ok(lit) => {
301                 self.bump();
302                 Ok(lit)
303             }
304             Err(LitError::NotLiteral) => {
305                 let msg = format!("unexpected token: {}", self.this_token_descr());
306                 Err(self.span_fatal(span, &msg))
307             }
308             Err(err) => {
309                 let lit = token.expect_lit();
310                 self.bump();
311                 err.report(&self.sess.span_diagnostic, lit, span);
312                 let lit = token::Lit::new(token::Err, lit.symbol, lit.suffix);
313                 Lit::from_lit_token(lit, span).map_err(|_| unreachable!())
314             }
315         }
316     }
317 }
318
319 crate fn expect_no_suffix(diag: &Handler, sp: Span, kind: &str, suffix: Option<Symbol>) {
320     if let Some(suf) = suffix {
321         let mut err = if kind == "a tuple index" &&
322                          [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) {
323             // #59553: warn instead of reject out of hand to allow the fix to percolate
324             // through the ecosystem when people fix their macros
325             let mut err = diag.struct_span_warn(
326                 sp,
327                 &format!("suffixes on {} are invalid", kind),
328             );
329             err.note(&format!(
330                 "`{}` is *temporarily* accepted on tuple index fields as it was \
331                     incorrectly accepted on stable for a few releases",
332                 suf,
333             ));
334             err.help(
335                 "on proc macros, you'll want to use `syn::Index::from` or \
336                     `proc_macro::Literal::*_unsuffixed` for code that will desugar \
337                     to tuple field access",
338             );
339             err.note(
340                 "for more context, see https://github.com/rust-lang/rust/issues/60210",
341             );
342             err
343         } else {
344             diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
345         };
346         err.span_label(sp, format!("invalid suffix `{}`", suf));
347         err.emit();
348     }
349 }
350
351 /// Parses a string representing a raw string literal into its final form. The
352 /// only operation this does is convert embedded CRLF into a single LF.
353 fn raw_str_lit(lit: &str) -> String {
354     debug!("raw_str_lit: {:?}", lit);
355     let mut res = String::with_capacity(lit.len());
356
357     let mut chars = lit.chars().peekable();
358     while let Some(c) = chars.next() {
359         if c == '\r' {
360             if *chars.peek().unwrap() != '\n' {
361                 panic!("lexer accepted bare CR");
362             }
363             chars.next();
364             res.push('\n');
365         } else {
366             res.push(c);
367         }
368     }
369
370     res.shrink_to_fit();
371     res
372 }
373
374 // Checks if `s` looks like i32 or u1234 etc.
375 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
376     s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
377 }
378
379 fn strip_underscores(symbol: Symbol) -> Symbol {
380     // Do not allocate a new string unless necessary.
381     let s = symbol.as_str();
382     if s.contains('_') {
383         let mut s = s.to_string();
384         s.retain(|c| c != '_');
385         return Symbol::intern(&s);
386     }
387     symbol
388 }
389
390 fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32)
391                       -> Result<LitKind, LitError> {
392     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
393     if base != 10 {
394         return Err(LitError::NonDecimalFloat(base));
395     }
396     Ok(match suffix {
397         Some(suf) => match suf {
398             sym::f32 => LitKind::Float(symbol, ast::FloatTy::F32),
399             sym::f64 => LitKind::Float(symbol, ast::FloatTy::F64),
400             _ => return Err(LitError::InvalidFloatSuffix),
401         }
402         None => LitKind::FloatUnsuffixed(symbol)
403     })
404 }
405
406 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
407     debug!("float_lit: {:?}, {:?}", symbol, suffix);
408     filtered_float_lit(strip_underscores(symbol), suffix, 10)
409 }
410
411 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
412     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
413     let symbol = strip_underscores(symbol);
414     let s = symbol.as_str();
415
416     let mut base = 10;
417     if s.len() > 1 && s.as_bytes()[0] == b'0' {
418         match s.as_bytes()[1] {
419             b'x' => base = 16,
420             b'o' => base = 8,
421             b'b' => base = 2,
422             _ => {}
423         }
424     }
425
426     let ty = match suffix {
427         Some(suf) => match suf {
428             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
429             sym::i8  => ast::LitIntType::Signed(ast::IntTy::I8),
430             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
431             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
432             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
433             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
434             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
435             sym::u8  => ast::LitIntType::Unsigned(ast::UintTy::U8),
436             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
437             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
438             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
439             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
440             // `1f64` and `2f32` etc. are valid float literals, and
441             // `fxxx` looks more like an invalid float literal than invalid integer literal.
442             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
443             _ => return Err(LitError::InvalidIntSuffix),
444         }
445         _ => ast::LitIntType::Unsuffixed
446     };
447
448     let s = &s[if base != 10 { 2 } else { 0 } ..];
449     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
450         // Small bases are lexed as if they were base 10, e.g, the string
451         // might be `0b10201`. This will cause the conversion above to fail,
452         // but these kinds of errors are already reported by the lexer.
453         let from_lexer =
454             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
455         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
456     })
457 }