]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/literal.rs
comments
[rust.git] / src / libsyntax / parse / literal.rs
1 //! Code related to parsing literals.
2
3 use crate::ast::{self, Lit, LitKind};
4 use crate::parse::parser::Parser;
5 use crate::parse::PResult;
6 use crate::parse::token::{self, Token, TokenKind};
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) -> Result<Lit, LitError> {
232         let lit = match token.kind {
233             token::Ident(name, false) if name == kw::True || name == kw::False =>
234                 token::Lit::new(token::Bool, 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, token.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(self.token.symbol, false),
262             _ => token::Literal(self.token),
263         };
264         TokenTree::token(token, self.span).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, |next_token| {
275                 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix })
276                         = next_token.kind {
277                     if self.token.span.hi() == next_token.span.lo() {
278                         let s = String::from("0.") + &symbol.as_str();
279                         let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
280                         return Some(Token::new(kind, self.token.span.to(next_token.span)));
281                     }
282                 }
283                 None
284             });
285             if let Some(token) = &recovered {
286                 self.bump();
287                 self.diagnostic()
288                     .struct_span_err(token.span, "float literals must have an integer part")
289                     .span_suggestion(
290                         token.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 = recovered.as_ref().unwrap_or(&self.token);
300         match Lit::from_token(token) {
301             Ok(lit) => {
302                 self.bump();
303                 Ok(lit)
304             }
305             Err(LitError::NotLiteral) => {
306                 let msg = format!("unexpected token: {}", self.this_token_descr());
307                 Err(self.span_fatal(token.span, &msg))
308             }
309             Err(err) => {
310                 let (lit, span) = (token.expect_lit(), token.span);
311                 self.bump();
312                 err.report(&self.sess.span_diagnostic, lit, span);
313                 // Pack possible quotes and prefixes from the original literal into
314                 // the error literal's symbol so they can be pretty-printed faithfully.
315                 let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None);
316                 let symbol = Symbol::intern(&pprust::literal_to_string(suffixless_lit));
317                 let lit = token::Lit::new(token::Err, symbol, lit.suffix);
318                 Lit::from_lit_token(lit, span).map_err(|_| unreachable!())
319             }
320         }
321     }
322 }
323
324 crate fn expect_no_suffix(diag: &Handler, sp: Span, kind: &str, suffix: Option<Symbol>) {
325     if let Some(suf) = suffix {
326         let mut err = if kind == "a tuple index" &&
327                          [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) {
328             // #59553: warn instead of reject out of hand to allow the fix to percolate
329             // through the ecosystem when people fix their macros
330             let mut err = diag.struct_span_warn(
331                 sp,
332                 &format!("suffixes on {} are invalid", kind),
333             );
334             err.note(&format!(
335                 "`{}` is *temporarily* accepted on tuple index fields as it was \
336                     incorrectly accepted on stable for a few releases",
337                 suf,
338             ));
339             err.help(
340                 "on proc macros, you'll want to use `syn::Index::from` or \
341                     `proc_macro::Literal::*_unsuffixed` for code that will desugar \
342                     to tuple field access",
343             );
344             err.note(
345                 "for more context, see https://github.com/rust-lang/rust/issues/60210",
346             );
347             err
348         } else {
349             diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
350         };
351         err.span_label(sp, format!("invalid suffix `{}`", suf));
352         err.emit();
353     }
354 }
355
356 /// Parses a string representing a raw string literal into its final form. The
357 /// only operation this does is convert embedded CRLF into a single LF.
358 fn raw_str_lit(lit: &str) -> String {
359     debug!("raw_str_lit: {:?}", lit);
360     let mut res = String::with_capacity(lit.len());
361
362     let mut chars = lit.chars().peekable();
363     while let Some(c) = chars.next() {
364         if c == '\r' {
365             if *chars.peek().unwrap() != '\n' {
366                 panic!("lexer accepted bare CR");
367             }
368             chars.next();
369             res.push('\n');
370         } else {
371             res.push(c);
372         }
373     }
374
375     res.shrink_to_fit();
376     res
377 }
378
379 // Checks if `s` looks like i32 or u1234 etc.
380 fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
381     s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
382 }
383
384 fn strip_underscores(symbol: Symbol) -> Symbol {
385     // Do not allocate a new string unless necessary.
386     let s = symbol.as_str();
387     if s.contains('_') {
388         let mut s = s.to_string();
389         s.retain(|c| c != '_');
390         return Symbol::intern(&s);
391     }
392     symbol
393 }
394
395 fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32)
396                       -> Result<LitKind, LitError> {
397     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
398     if base != 10 {
399         return Err(LitError::NonDecimalFloat(base));
400     }
401     Ok(match suffix {
402         Some(suf) => match suf {
403             sym::f32 => LitKind::Float(symbol, ast::FloatTy::F32),
404             sym::f64 => LitKind::Float(symbol, ast::FloatTy::F64),
405             _ => return Err(LitError::InvalidFloatSuffix),
406         }
407         None => LitKind::FloatUnsuffixed(symbol)
408     })
409 }
410
411 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
412     debug!("float_lit: {:?}, {:?}", symbol, suffix);
413     filtered_float_lit(strip_underscores(symbol), suffix, 10)
414 }
415
416 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
417     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
418     let symbol = strip_underscores(symbol);
419     let s = symbol.as_str();
420
421     let mut base = 10;
422     if s.len() > 1 && s.as_bytes()[0] == b'0' {
423         match s.as_bytes()[1] {
424             b'x' => base = 16,
425             b'o' => base = 8,
426             b'b' => base = 2,
427             _ => {}
428         }
429     }
430
431     let ty = match suffix {
432         Some(suf) => match suf {
433             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
434             sym::i8  => ast::LitIntType::Signed(ast::IntTy::I8),
435             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
436             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
437             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
438             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
439             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
440             sym::u8  => ast::LitIntType::Unsigned(ast::UintTy::U8),
441             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
442             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
443             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
444             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
445             // `1f64` and `2f32` etc. are valid float literals, and
446             // `fxxx` looks more like an invalid float literal than invalid integer literal.
447             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
448             _ => return Err(LitError::InvalidIntSuffix),
449         }
450         _ => ast::LitIntType::Unsuffixed
451     };
452
453     let s = &s[if base != 10 { 2 } else { 0 } ..];
454     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
455         // Small bases are lexed as if they were base 10, e.g, the string
456         // might be `0b10201`. This will cause the conversion above to fail,
457         // but these kinds of errors are already reported by the lexer.
458         let from_lexer =
459             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
460         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
461     })
462 }