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 an arbitrary token into an AST literal.
206 pub fn from_token(token: &Token) -> Option<Lit> {
207 token::Lit::from_token(token)
208 .and_then(|token_lit| Lit::from_token_lit(token_lit, token.span).ok())
211 /// Attempts to recover an AST literal from semantic literal.
212 /// This function is used when the original token doesn't exist (e.g. the literal is created
213 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
214 pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
215 Lit { token_lit: kind.to_token_lit(), kind, span }
218 /// Recovers an AST literal from a string of bytes produced by `include_bytes!`.
219 /// This requires ASCII-escaping the string, which can result in poor performance
220 /// for very large strings of bytes.
221 pub fn from_included_bytes(bytes: &Lrc<[u8]>, span: Span) -> Lit {
222 Self::from_lit_kind(LitKind::ByteStr(bytes.clone()), span)
225 /// Losslessly convert an AST literal into a token.
226 pub fn to_token(&self) -> Token {
227 let kind = match self.token_lit.kind {
228 token::Bool => token::Ident(self.token_lit.symbol, false),
229 _ => token::Literal(self.token_lit),
231 Token::new(kind, self.span)
235 fn strip_underscores(symbol: Symbol) -> Symbol {
236 // Do not allocate a new string unless necessary.
237 let s = symbol.as_str();
239 let mut s = s.to_string();
240 s.retain(|c| c != '_');
241 return Symbol::intern(&s);
246 fn filtered_float_lit(
248 suffix: Option<Symbol>,
250 ) -> Result<LitKind, LitError> {
251 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
253 return Err(LitError::NonDecimalFloat(base));
256 Some(suf) => LitKind::Float(
258 ast::LitFloatType::Suffixed(match suf {
259 sym::f32 => ast::FloatTy::F32,
260 sym::f64 => ast::FloatTy::F64,
261 _ => return Err(LitError::InvalidFloatSuffix),
264 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
268 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
269 debug!("float_lit: {:?}, {:?}", symbol, suffix);
270 filtered_float_lit(strip_underscores(symbol), suffix, 10)
273 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
274 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
275 let symbol = strip_underscores(symbol);
276 let s = symbol.as_str();
278 let base = match s.as_bytes() {
279 [b'0', b'x', ..] => 16,
280 [b'0', b'o', ..] => 8,
281 [b'0', b'b', ..] => 2,
285 let ty = match suffix {
286 Some(suf) => match suf {
287 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
288 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
289 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
290 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
291 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
292 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
293 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
294 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
295 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
296 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
297 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
298 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
299 // `1f64` and `2f32` etc. are valid float literals, and
300 // `fxxx` looks more like an invalid float literal than invalid integer literal.
301 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
302 _ => return Err(LitError::InvalidIntSuffix),
304 _ => ast::LitIntType::Unsuffixed,
307 let s = &s[if base != 10 { 2 } else { 0 }..];
308 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
309 // Small bases are lexed as if they were base 10, e.g, the string
310 // might be `0b10201`. This will cause the conversion above to fail,
311 // but these kinds of errors are already reported by the lexer.
313 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
314 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }