1 //! Code related to parsing literals.
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};
12 use errors::{Applicability, Handler};
14 use rustc_data_structures::sync::Lrc;
30 fn report(&self, diag: &Handler, lit: token::Lit, span: Span) {
31 let token::Lit { kind, suffix, .. } = lit;
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 => {
41 diag, span, &format!("{} {} literal", kind.article(), kind.descr()), suffix
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")
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)")
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")
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`")
76 LitError::NonDecimalFloat(base) => {
77 let descr = match base {
83 diag.struct_span_err(span, &format!("{} float literal is not supported", descr))
84 .span_label(span, "not supported")
87 LitError::IntTooLarge => {
88 diag.struct_span_err(span, "integer literal is too large")
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);
105 assert!(symbol == kw::True || symbol == kw::False);
106 LitKind::Bool(symbol == kw::True)
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),
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),
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),
138 LitKind::Str(symbol, ast::StrStyle::Cooked)
140 token::StrRaw(n) => {
142 let s = symbol.as_str();
143 let symbol = if s.contains('\r') {
144 Symbol::intern(&raw_str_lit(&s))
148 LitKind::Str(symbol, ast::StrStyle::Raw(n))
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),
162 LitKind::ByteStr(Lrc::new(buf))
164 token::ByteStrRaw(_) => LitKind::ByteStr(Lrc::new(symbol.to_string().into_bytes())),
165 token::Err => LitKind::Err(symbol),
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)
181 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => {
182 (token::StrRaw(n), symbol, None)
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)
189 LitKind::Byte(byte) => {
190 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
191 (token::Byte, Symbol::intern(&string), None)
193 LitKind::Char(ch) => {
194 let string: String = ch.escape_default().map(Into::<char>::into).collect();
195 (token::Char, Symbol::intern(&string), None)
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,
203 (token::Integer, sym::integer(n), suffix)
205 LitKind::Float(symbol, ty) => {
206 (token::Float, symbol, Some(ty.to_symbol()))
208 LitKind::FloatUnsuffixed(symbol) => {
209 (token::Float, symbol, None)
211 LitKind::Bool(value) => {
212 let symbol = if value { kw::True } else { kw::False };
213 (token::Bool, symbol, None)
215 LitKind::Err(symbol) => {
216 (token::Err, symbol, None)
220 token::Lit::new(kind, symbol, suffix)
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 })
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) =>
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());
243 return Err(LitError::NotLiteral);
245 _ => return Err(LitError::NotLiteral)
248 Lit::from_lit_token(lit, token.span)
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 }
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),
264 TokenTree::token(token, self.span).into()
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 })
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)));
285 if let Some(token) = &recovered {
288 .struct_span_err(token.span, "float literals must have an integer part")
291 "must have an integer part",
292 pprust::token_to_string(token),
293 Applicability::MachineApplicable,
299 let token = recovered.as_ref().unwrap_or(&self.token);
300 match Lit::from_token(token) {
305 Err(LitError::NotLiteral) => {
306 let msg = format!("unexpected token: {}", self.this_token_descr());
307 Err(self.span_fatal(token.span, &msg))
310 let (lit, span) = (token.expect_lit(), token.span);
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!())
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(
332 &format!("suffixes on {} are invalid", kind),
335 "`{}` is *temporarily* accepted on tuple index fields as it was \
336 incorrectly accepted on stable for a few releases",
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",
345 "for more context, see https://github.com/rust-lang/rust/issues/60210",
349 diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
351 err.span_label(sp, format!("invalid suffix `{}`", suf));
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());
362 let mut chars = lit.chars().peekable();
363 while let Some(c) = chars.next() {
365 if *chars.peek().unwrap() != '\n' {
366 panic!("lexer accepted bare CR");
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())
384 fn strip_underscores(symbol: Symbol) -> Symbol {
385 // Do not allocate a new string unless necessary.
386 let s = symbol.as_str();
388 let mut s = s.to_string();
389 s.retain(|c| c != '_');
390 return Symbol::intern(&s);
395 fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32)
396 -> Result<LitKind, LitError> {
397 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
399 return Err(LitError::NonDecimalFloat(base));
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),
407 None => LitKind::FloatUnsuffixed(symbol)
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)
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();
422 if s.len() > 1 && s.as_bytes()[0] == b'0' {
423 match s.as_bytes()[1] {
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),
450 _ => ast::LitIntType::Unsuffixed
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.
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 }