1 //! Code related to parsing literals.
3 use crate::ast::{self, Lit, LitKind};
4 use crate::token::{self, Token};
5 use rustc_data_structures::sync::Lrc;
6 use rustc_lexer::unescape::{byte_from_char, unescape_byte, unescape_char, unescape_literal, Mode};
7 use rustc_span::symbol::{kw, sym, Symbol};
22 /// Converts literal token into a semantic literal.
23 pub fn from_token_lit(lit: token::Lit) -> Result<LitKind, LitError> {
24 let token::Lit { kind, symbol, suffix } = lit;
25 if suffix.is_some() && !kind.may_have_suffix() {
26 return Err(LitError::InvalidSuffix);
31 assert!(symbol.is_bool_lit());
32 LitKind::Bool(symbol == kw::True)
35 return unescape_byte(symbol.as_str())
37 .map_err(|_| LitError::LexerError);
40 return unescape_char(symbol.as_str())
42 .map_err(|_| LitError::LexerError);
45 // There are some valid suffixes for integer and float literals,
46 // so all the handling is done internally.
47 token::Integer => return integer_lit(symbol, suffix),
48 token::Float => return float_lit(symbol, suffix),
51 // If there are no characters requiring special treatment we can
52 // reuse the symbol from the token. Otherwise, we must generate a
53 // new symbol because the string in the LitKind is different to the
54 // string in the token.
55 let s = symbol.as_str();
56 let symbol = if s.contains(&['\\', '\r']) {
57 let mut buf = String::with_capacity(s.len());
58 let mut error = Ok(());
59 // Force-inlining here is aggressive but the closure is
60 // called on every char in the string, so it can be
61 // hot in programs with many long strings.
65 &mut #[inline(always)]
66 |_, unescaped_char| match unescaped_char {
70 error = Err(LitError::LexerError);
80 LitKind::Str(symbol, ast::StrStyle::Cooked)
84 let s = symbol.as_str();
87 let mut buf = String::with_capacity(s.len());
88 let mut error = Ok(());
89 unescape_literal(&s, Mode::RawStr, &mut |_, unescaped_char| {
90 match unescaped_char {
94 error = Err(LitError::LexerError);
104 LitKind::Str(symbol, ast::StrStyle::Raw(n))
107 let s = symbol.as_str();
108 let mut buf = Vec::with_capacity(s.len());
109 let mut error = Ok(());
110 unescape_literal(&s, Mode::ByteStr, &mut |_, c| match c {
111 Ok(c) => buf.push(byte_from_char(c)),
114 error = Err(LitError::LexerError);
119 LitKind::ByteStr(buf.into())
121 token::ByteStrRaw(_) => {
122 let s = symbol.as_str();
123 let bytes = if s.contains('\r') {
124 let mut buf = Vec::with_capacity(s.len());
125 let mut error = Ok(());
126 unescape_literal(&s, Mode::RawByteStr, &mut |_, c| match c {
127 Ok(c) => buf.push(byte_from_char(c)),
130 error = Err(LitError::LexerError);
137 symbol.to_string().into_bytes()
140 LitKind::ByteStr(bytes.into())
142 token::Err => LitKind::Err,
146 /// Attempts to recover a token from semantic literal.
147 /// This function is used when the original token doesn't exist (e.g. the literal is created
148 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
149 pub fn to_token_lit(&self) -> token::Lit {
150 let (kind, symbol, suffix) = match *self {
151 LitKind::Str(symbol, ast::StrStyle::Cooked) => {
152 // Don't re-intern unless the escaped string is different.
153 let s = symbol.as_str();
154 let escaped = s.escape_default().to_string();
155 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
156 (token::Str, symbol, None)
158 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
159 LitKind::ByteStr(ref bytes) => {
160 let string = bytes.escape_ascii().to_string();
161 (token::ByteStr, Symbol::intern(&string), None)
163 LitKind::Byte(byte) => {
164 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
165 (token::Byte, Symbol::intern(&string), None)
167 LitKind::Char(ch) => {
168 let string: String = ch.escape_default().map(Into::<char>::into).collect();
169 (token::Char, Symbol::intern(&string), None)
171 LitKind::Int(n, ty) => {
172 let suffix = match ty {
173 ast::LitIntType::Unsigned(ty) => Some(ty.name()),
174 ast::LitIntType::Signed(ty) => Some(ty.name()),
175 ast::LitIntType::Unsuffixed => None,
177 (token::Integer, sym::integer(n), suffix)
179 LitKind::Float(symbol, ty) => {
180 let suffix = match ty {
181 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
182 ast::LitFloatType::Unsuffixed => None,
184 (token::Float, symbol, suffix)
186 LitKind::Bool(value) => {
187 let symbol = if value { kw::True } else { kw::False };
188 (token::Bool, symbol, None)
190 // This only shows up in places like `-Zunpretty=hir` output, so we
191 // don't bother to produce something useful.
192 LitKind::Err => (token::Err, Symbol::intern("<bad-literal>"), None),
195 token::Lit::new(kind, symbol, suffix)
200 /// Converts literal token into an AST literal.
201 pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<Lit, LitError> {
202 Ok(Lit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span })
205 /// Converts arbitrary token into an AST literal.
207 /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation.
208 pub fn from_token(token: &Token) -> Result<Lit, LitError> {
209 let lit = match token.uninterpolate().kind {
210 token::Ident(name, false) if name.is_bool_lit() => {
211 token::Lit::new(token::Bool, name, None)
213 token::Literal(lit) => lit,
214 token::Interpolated(ref nt) => {
215 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt
216 && let ast::ExprKind::Lit(lit) = &expr.kind
218 return Ok(lit.clone());
220 return Err(LitError::NotLiteral);
222 _ => return Err(LitError::NotLiteral),
225 Lit::from_token_lit(lit, token.span)
228 /// Attempts to recover an AST literal from semantic literal.
229 /// This function is used when the original token doesn't exist (e.g. the literal is created
230 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
231 pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
232 Lit { token_lit: kind.to_token_lit(), kind, span }
235 /// Recovers an AST literal from a string of bytes produced by `include_bytes!`.
236 /// This requires ASCII-escaping the string, which can result in poor performance
237 /// for very large strings of bytes.
238 pub fn from_included_bytes(bytes: &Lrc<[u8]>, span: Span) -> Lit {
239 Self::from_lit_kind(LitKind::ByteStr(bytes.clone()), span)
242 /// Losslessly convert an AST literal into a token.
243 pub fn to_token(&self) -> Token {
244 let kind = match self.token_lit.kind {
245 token::Bool => token::Ident(self.token_lit.symbol, false),
246 _ => token::Literal(self.token_lit),
248 Token::new(kind, self.span)
252 fn strip_underscores(symbol: Symbol) -> Symbol {
253 // Do not allocate a new string unless necessary.
254 let s = symbol.as_str();
256 let mut s = s.to_string();
257 s.retain(|c| c != '_');
258 return Symbol::intern(&s);
263 fn filtered_float_lit(
265 suffix: Option<Symbol>,
267 ) -> Result<LitKind, LitError> {
268 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
270 return Err(LitError::NonDecimalFloat(base));
273 Some(suf) => LitKind::Float(
275 ast::LitFloatType::Suffixed(match suf {
276 sym::f32 => ast::FloatTy::F32,
277 sym::f64 => ast::FloatTy::F64,
278 _ => return Err(LitError::InvalidFloatSuffix),
281 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
285 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
286 debug!("float_lit: {:?}, {:?}", symbol, suffix);
287 filtered_float_lit(strip_underscores(symbol), suffix, 10)
290 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
291 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
292 let symbol = strip_underscores(symbol);
293 let s = symbol.as_str();
295 let base = match s.as_bytes() {
296 [b'0', b'x', ..] => 16,
297 [b'0', b'o', ..] => 8,
298 [b'0', b'b', ..] => 2,
302 let ty = match suffix {
303 Some(suf) => match suf {
304 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
305 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
306 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
307 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
308 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
309 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
310 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
311 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
312 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
313 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
314 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
315 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
316 // `1f64` and `2f32` etc. are valid float literals, and
317 // `fxxx` looks more like an invalid float literal than invalid integer literal.
318 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
319 _ => return Err(LitError::InvalidIntSuffix),
321 _ => ast::LitIntType::Unsuffixed,
324 let s = &s[if base != 10 { 2 } else { 0 }..];
325 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
326 // Small bases are lexed as if they were base 10, e.g, the string
327 // might be `0b10201`. This will cause the conversion above to fail,
328 // but these kinds of errors are already reported by the lexer.
330 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
331 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }