1 //! Code related to parsing literals.
3 use crate::ast::{self, Lit, LitKind};
4 use crate::token::{self, Token};
6 use rustc_lexer::unescape::{unescape_byte, unescape_char};
7 use rustc_lexer::unescape::{unescape_byte_literal, unescape_literal, Mode};
8 use rustc_span::symbol::{kw, sym, Symbol};
25 /// Converts literal token into a semantic literal.
26 fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
27 let token::Lit { kind, symbol, suffix } = lit;
28 if suffix.is_some() && !kind.may_have_suffix() {
29 return Err(LitError::InvalidSuffix);
34 assert!(symbol.is_bool_lit());
35 LitKind::Bool(symbol == kw::True)
38 return unescape_byte(symbol.as_str())
40 .map_err(|_| LitError::LexerError);
43 return unescape_char(symbol.as_str())
45 .map_err(|_| LitError::LexerError);
48 // There are some valid suffixes for integer and float literals,
49 // so all the handling is done internally.
50 token::Integer => return integer_lit(symbol, suffix),
51 token::Float => return float_lit(symbol, suffix),
54 // If there are no characters requiring special treatment we can
55 // reuse the symbol from the token. Otherwise, we must generate a
56 // new symbol because the string in the LitKind is different to the
57 // string in the token.
58 let s = symbol.as_str();
59 let symbol = if s.contains(&['\\', '\r']) {
60 let mut buf = String::with_capacity(s.len());
61 let mut error = Ok(());
62 // Force-inlining here is aggressive but the closure is
63 // called on every char in the string, so it can be
64 // hot in programs with many long strings.
68 &mut #[inline(always)]
69 |_, unescaped_char| match unescaped_char {
73 error = Err(LitError::LexerError);
83 LitKind::Str(symbol, ast::StrStyle::Cooked)
87 let s = symbol.as_str();
90 let mut buf = String::with_capacity(s.len());
91 let mut error = Ok(());
92 unescape_literal(&s, Mode::RawStr, &mut |_, unescaped_char| {
93 match unescaped_char {
97 error = Err(LitError::LexerError);
107 LitKind::Str(symbol, ast::StrStyle::Raw(n))
110 let s = symbol.as_str();
111 let mut buf = Vec::with_capacity(s.len());
112 let mut error = Ok(());
113 unescape_byte_literal(&s, Mode::ByteStr, &mut |_, unescaped_byte| {
114 match unescaped_byte {
115 Ok(c) => buf.push(c),
118 error = Err(LitError::LexerError);
124 LitKind::ByteStr(buf.into())
126 token::ByteStrRaw(_) => {
127 let s = symbol.as_str();
128 let bytes = if s.contains('\r') {
129 let mut buf = Vec::with_capacity(s.len());
130 let mut error = Ok(());
131 unescape_byte_literal(&s, Mode::RawByteStr, &mut |_, unescaped_byte| {
132 match unescaped_byte {
133 Ok(c) => buf.push(c),
136 error = Err(LitError::LexerError);
144 symbol.to_string().into_bytes()
147 LitKind::ByteStr(bytes.into())
149 token::Err => LitKind::Err(symbol),
153 /// Attempts to recover a token from semantic literal.
154 /// This function is used when the original token doesn't exist (e.g. the literal is created
155 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
156 pub fn to_lit_token(&self) -> token::Lit {
157 let (kind, symbol, suffix) = match *self {
158 LitKind::Str(symbol, ast::StrStyle::Cooked) => {
159 // Don't re-intern unless the escaped string is different.
160 let s = symbol.as_str();
161 let escaped = s.escape_default().to_string();
162 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
163 (token::Str, symbol, None)
165 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
166 LitKind::ByteStr(ref bytes) => {
170 .flat_map(ascii::escape_default)
171 .map(Into::<char>::into)
172 .collect::<String>();
173 (token::ByteStr, Symbol::intern(&string), None)
175 LitKind::Byte(byte) => {
176 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
177 (token::Byte, Symbol::intern(&string), None)
179 LitKind::Char(ch) => {
180 let string: String = ch.escape_default().map(Into::<char>::into).collect();
181 (token::Char, Symbol::intern(&string), None)
183 LitKind::Int(n, ty) => {
184 let suffix = match ty {
185 ast::LitIntType::Unsigned(ty) => Some(ty.name()),
186 ast::LitIntType::Signed(ty) => Some(ty.name()),
187 ast::LitIntType::Unsuffixed => None,
189 (token::Integer, sym::integer(n), suffix)
191 LitKind::Float(symbol, ty) => {
192 let suffix = match ty {
193 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
194 ast::LitFloatType::Unsuffixed => None,
196 (token::Float, symbol, suffix)
198 LitKind::Bool(value) => {
199 let symbol = if value { kw::True } else { kw::False };
200 (token::Bool, symbol, None)
202 LitKind::Err(symbol) => (token::Err, symbol, None),
205 token::Lit::new(kind, symbol, suffix)
210 /// Converts literal token into an AST literal.
211 pub fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> {
212 Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span })
215 /// Converts arbitrary token into an AST literal.
217 /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation.
218 pub fn from_token(token: &Token) -> Result<Lit, LitError> {
219 let lit = match token.uninterpolate().kind {
220 token::Ident(name, false) if name.is_bool_lit() => {
221 token::Lit::new(token::Bool, name, None)
223 token::Literal(lit) => lit,
224 token::Interpolated(ref nt) => {
225 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt
226 && let ast::ExprKind::Lit(lit) = &expr.kind
228 return Ok(lit.clone());
230 return Err(LitError::NotLiteral);
232 _ => return Err(LitError::NotLiteral),
235 Lit::from_lit_token(lit, token.span)
238 /// Attempts to recover an AST literal from semantic literal.
239 /// This function is used when the original token doesn't exist (e.g. the literal is created
240 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
241 pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
242 Lit { token: kind.to_lit_token(), kind, span }
245 /// Losslessly convert an AST literal into a token.
246 pub fn to_token(&self) -> Token {
247 let kind = match self.token.kind {
248 token::Bool => token::Ident(self.token.symbol, false),
249 _ => token::Literal(self.token),
251 Token::new(kind, self.span)
255 fn strip_underscores(symbol: Symbol) -> Symbol {
256 // Do not allocate a new string unless necessary.
257 let s = symbol.as_str();
259 let mut s = s.to_string();
260 s.retain(|c| c != '_');
261 return Symbol::intern(&s);
266 fn filtered_float_lit(
268 suffix: Option<Symbol>,
270 ) -> Result<LitKind, LitError> {
271 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
273 return Err(LitError::NonDecimalFloat(base));
276 Some(suf) => LitKind::Float(
278 ast::LitFloatType::Suffixed(match suf {
279 sym::f32 => ast::FloatTy::F32,
280 sym::f64 => ast::FloatTy::F64,
281 _ => return Err(LitError::InvalidFloatSuffix),
284 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
288 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
289 debug!("float_lit: {:?}, {:?}", symbol, suffix);
290 filtered_float_lit(strip_underscores(symbol), suffix, 10)
293 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
294 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
295 let symbol = strip_underscores(symbol);
296 let s = symbol.as_str();
298 let base = match s.as_bytes() {
299 [b'0', b'x', ..] => 16,
300 [b'0', b'o', ..] => 8,
301 [b'0', b'b', ..] => 2,
305 let ty = match suffix {
306 Some(suf) => match suf {
307 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
308 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
309 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
310 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
311 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
312 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
313 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
314 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
315 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
316 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
317 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
318 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
319 // `1f64` and `2f32` etc. are valid float literals, and
320 // `fxxx` looks more like an invalid float literal than invalid integer literal.
321 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
322 _ => return Err(LitError::InvalidIntSuffix),
324 _ => ast::LitIntType::Unsuffixed,
327 let s = &s[if base != 10 { 2 } else { 0 }..];
328 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
329 // Small bases are lexed as if they were base 10, e.g, the string
330 // might be `0b10201`. This will cause the conversion above to fail,
331 // but these kinds of errors are already reported by the lexer.
333 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
334 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }