1 //! Code related to parsing literals.
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, 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: &TokenKind, 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) =>
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, 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(Ident::new(self.token.symbol, self.span), false),
262 _ => token::Literal(self.token),
264 TokenTree::token(self.span, token).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, |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 = TokenKind::lit(token::Float, Symbol::intern(&s), suffix);
280 return Some((token, self.span.to(next_span)));
285 if let Some((ref token, span)) = recovered {
288 .struct_span_err(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, span) = recovered.as_ref().map_or((&self.token, self.span),
300 |(token, span)| (token, *span));
302 match Lit::from_token(token, span) {
307 Err(LitError::NotLiteral) => {
308 let msg = format!("unexpected token: {}", self.this_token_descr());
309 Err(self.span_fatal(span, &msg))
312 let lit = token.expect_lit();
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!())
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(
330 &format!("suffixes on {} are invalid", kind),
333 "`{}` is *temporarily* accepted on tuple index fields as it was \
334 incorrectly accepted on stable for a few releases",
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",
343 "for more context, see https://github.com/rust-lang/rust/issues/60210",
347 diag.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
349 err.span_label(sp, format!("invalid suffix `{}`", suf));
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());
360 let mut chars = lit.chars().peekable();
361 while let Some(c) = chars.next() {
363 if *chars.peek().unwrap() != '\n' {
364 panic!("lexer accepted bare CR");
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())
382 fn strip_underscores(symbol: Symbol) -> Symbol {
383 // Do not allocate a new string unless necessary.
384 let s = symbol.as_str();
386 let mut s = s.to_string();
387 s.retain(|c| c != '_');
388 return Symbol::intern(&s);
393 fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32)
394 -> Result<LitKind, LitError> {
395 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
397 return Err(LitError::NonDecimalFloat(base));
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),
405 None => LitKind::FloatUnsuffixed(symbol)
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)
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();
420 if s.len() > 1 && s.as_bytes()[0] == b'0' {
421 match s.as_bytes()[1] {
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),
448 _ => ast::LitIntType::Unsuffixed
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.
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 }