]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/literal.rs
Rollup merge of #61217 - estebank:issue-52820, r=Centril
[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(symbol, ast::StrStyle::Cooked) => {
175                 // Don't re-intern unless the escaped string is different.
176                 let s = &symbol.as_str();
177                 let escaped = s.escape_default().to_string();
178                 let symbol = if escaped == *s { symbol } else { Symbol::intern(&escaped) };
179                 (token::Str, symbol, None)
180             }
181             LitKind::Str(symbol, ast::StrStyle::Raw(n)) => {
182                 (token::StrRaw(n), symbol, None)
183             }
184             LitKind::ByteStr(ref bytes) => {
185                 let string = bytes.iter().cloned().flat_map(ascii::escape_default)
186                     .map(Into::<char>::into).collect::<String>();
187                 (token::ByteStr, Symbol::intern(&string), None)
188             }
189             LitKind::Byte(byte) => {
190                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
191                 (token::Byte, Symbol::intern(&string), None)
192             }
193             LitKind::Char(ch) => {
194                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
195                 (token::Char, Symbol::intern(&string), None)
196             }
197             LitKind::Int(n, ty) => {
198                 let suffix = match ty {
199                     ast::LitIntType::Unsigned(ty) => Some(ty.to_symbol()),
200                     ast::LitIntType::Signed(ty) => Some(ty.to_symbol()),
201                     ast::LitIntType::Unsuffixed => None,
202                 };
203                 (token::Integer, sym::integer(n), suffix)
204             }
205             LitKind::Float(symbol, ty) => {
206                 (token::Float, symbol, Some(ty.to_symbol()))
207             }
208             LitKind::FloatUnsuffixed(symbol) => {
209                 (token::Float, symbol, None)
210             }
211             LitKind::Bool(value) => {
212                 let symbol = if value { kw::True } else { kw::False };
213                 (token::Bool, symbol, None)
214             }
215             LitKind::Err(symbol) => {
216                 (token::Err, symbol, None)
217             }
218         };
219
220         token::Lit::new(kind, symbol, suffix)
221     }
222 }
223
224 impl Lit {
225     /// Converts literal token into an AST literal.
226     fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> {
227         Ok(Lit { token, node: LitKind::from_lit_token(token)?, span })
228     }
229
230     /// Converts arbitrary token into an AST literal.
231     crate fn from_token(token: &Token, span: Span) -> Result<Lit, LitError> {
232         let lit = match *token {
233             token::Ident(ident, false) if ident.name == kw::True || ident.name == kw::False =>
234                 token::Lit::new(token::Bool, ident.name, None),
235             token::Literal(lit) =>
236                 lit,
237             token::Interpolated(ref nt) => {
238                 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt {
239                     if let ast::ExprKind::Lit(lit) = &expr.node {
240                         return Ok(lit.clone());
241                     }
242                 }
243                 return Err(LitError::NotLiteral);
244             }
245             _ => return Err(LitError::NotLiteral)
246         };
247
248         Lit::from_lit_token(lit, span)
249     }
250
251     /// Attempts to recover an AST literal from semantic literal.
252     /// This function is used when the original token doesn't exist (e.g. the literal is created
253     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
254     pub fn from_lit_kind(node: LitKind, span: Span) -> Lit {
255         Lit { token: node.to_lit_token(), node, span }
256     }
257
258     /// Losslessly convert an AST literal into a token stream.
259     crate fn tokens(&self) -> TokenStream {
260         let token = match self.token.kind {
261             token::Bool => token::Ident(Ident::new(self.token.symbol, self.span), false),
262             _ => token::Literal(self.token),
263         };
264         TokenTree::Token(self.span, token).into()
265     }
266 }
267
268 impl<'a> Parser<'a> {
269     /// Matches `lit = true | false | token_lit`.
270     crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
271         let mut recovered = None;
272         if self.token == token::Dot {
273             // Attempt to recover `.4` as `0.4`.
274             recovered = self.look_ahead(1, |t| {
275                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = *t {
276                     let next_span = self.look_ahead_span(1);
277                     if self.span.hi() == next_span.lo() {
278                         let s = String::from("0.") + &symbol.as_str();
279                         let token = Token::lit(token::Float, Symbol::intern(&s), suffix);
280                         return Some((token, self.span.to(next_span)));
281                     }
282                 }
283                 None
284             });
285             if let Some((ref token, span)) = recovered {
286                 self.bump();
287                 self.diagnostic()
288                     .struct_span_err(span, "float literals must have an integer part")
289                     .span_suggestion(
290                         span,
291                         "must have an integer part",
292                         pprust::token_to_string(&token),
293                         Applicability::MachineApplicable,
294                     )
295                     .emit();
296             }
297         }
298
299         let (token, span) = recovered.as_ref().map_or((&self.token, self.span),
300                                                       |(token, span)| (token, *span));
301
302         match Lit::from_token(token, span) {
303             Ok(lit) => {
304                 self.bump();
305                 Ok(lit)
306             }
307             Err(LitError::NotLiteral) => {
308                 let msg = format!("unexpected token: {}", self.this_token_descr());
309                 Err(self.span_fatal(span, &msg))
310             }
311             Err(err) => {
312                 let lit = token.expect_lit();
313                 self.bump();
314                 err.report(&self.sess.span_diagnostic, lit, span);
315                 let lit = token::Lit::new(token::Err, lit.symbol, lit.suffix);
316                 Lit::from_lit_token(lit, span).map_err(|_| unreachable!())
317             }
318         }
319     }
320 }
321
322 crate fn expect_no_suffix(diag: &Handler, sp: Span, kind: &str, suffix: Option<Symbol>) {
323     if let Some(suf) = suffix {
324         let mut err = if kind == "a tuple index" &&
325                          [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) {
326             // #59553: warn instead of reject out of hand to allow the fix to percolate
327             // through the ecosystem when people fix their macros
328             let mut err = diag.struct_span_warn(
329                 sp,
330                 &format!("suffixes on {} are invalid", kind),
331             );
332             err.note(&format!(
333                 "`{}` is *temporarily* accepted on tuple index fields as it was \
334                     incorrectly accepted on stable for a few releases",
335                 suf,
336             ));
337             err.help(
338                 "on proc macros, you'll want to use `syn::Index::from` or \
339                     `proc_macro::Literal::*_unsuffixed` for code that will desugar \
340                     to tuple field access",
341             );
342             err.note(
343                 "for more context, see https://github.com/rust-lang/rust/issues/60210",
344             );
345             err
346         } else {
347             diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
348         };
349         err.span_label(sp, format!("invalid suffix `{}`", suf));
350         err.emit();
351     }
352 }
353
354 /// Parses a string representing a raw string literal into its final form. The
355 /// only operation this does is convert embedded CRLF into a single LF.
356 fn raw_str_lit(lit: &str) -> String {
357     debug!("raw_str_lit: {:?}", lit);
358     let mut res = String::with_capacity(lit.len());
359
360     let mut chars = lit.chars().peekable();
361     while let Some(c) = chars.next() {
362         if c == '\r' {
363             if *chars.peek().unwrap() != '\n' {
364                 panic!("lexer accepted bare CR");
365             }
366             chars.next();
367             res.push('\n');
368         } else {
369             res.push(c);
370         }
371     }
372
373     res.shrink_to_fit();
374     res
375 }
376
377 // Checks if `s` looks like i32 or u1234 etc.
378 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
379     s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
380 }
381
382 fn strip_underscores(symbol: Symbol) -> Symbol {
383     // Do not allocate a new string unless necessary.
384     let s = symbol.as_str();
385     if s.contains('_') {
386         let mut s = s.to_string();
387         s.retain(|c| c != '_');
388         return Symbol::intern(&s);
389     }
390     symbol
391 }
392
393 fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32)
394                       -> Result<LitKind, LitError> {
395     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
396     if base != 10 {
397         return Err(LitError::NonDecimalFloat(base));
398     }
399     Ok(match suffix {
400         Some(suf) => match suf {
401             sym::f32 => LitKind::Float(symbol, ast::FloatTy::F32),
402             sym::f64 => LitKind::Float(symbol, ast::FloatTy::F64),
403             _ => return Err(LitError::InvalidFloatSuffix),
404         }
405         None => LitKind::FloatUnsuffixed(symbol)
406     })
407 }
408
409 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
410     debug!("float_lit: {:?}, {:?}", symbol, suffix);
411     filtered_float_lit(strip_underscores(symbol), suffix, 10)
412 }
413
414 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
415     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
416     let symbol = strip_underscores(symbol);
417     let s = symbol.as_str();
418
419     let mut base = 10;
420     if s.len() > 1 && s.as_bytes()[0] == b'0' {
421         match s.as_bytes()[1] {
422             b'x' => base = 16,
423             b'o' => base = 8,
424             b'b' => base = 2,
425             _ => {}
426         }
427     }
428
429     let ty = match suffix {
430         Some(suf) => match suf {
431             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
432             sym::i8  => ast::LitIntType::Signed(ast::IntTy::I8),
433             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
434             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
435             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
436             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
437             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
438             sym::u8  => ast::LitIntType::Unsigned(ast::UintTy::U8),
439             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
440             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
441             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
442             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
443             // `1f64` and `2f32` etc. are valid float literals, and
444             // `fxxx` looks more like an invalid float literal than invalid integer literal.
445             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
446             _ => return Err(LitError::InvalidIntSuffix),
447         }
448         _ => ast::LitIntType::Unsuffixed
449     };
450
451     let s = &s[if base != 10 { 2 } else { 0 } ..];
452     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
453         // Small bases are lexed as if they were base 10, e.g, the string
454         // might be `0b10201`. This will cause the conversion above to fail,
455         // but these kinds of errors are already reported by the lexer.
456         let from_lexer =
457             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
458         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
459     })
460 }