1 //! Code related to parsing literals.
3 use crate::ast::{self, Lit, LitKind};
4 use crate::token::{self, Token};
5 use crate::tokenstream::TokenTree;
7 use rustc_data_structures::sync::Lrc;
8 use rustc_lexer::unescape::{unescape_byte, unescape_char};
9 use rustc_lexer::unescape::{unescape_byte_str, unescape_str};
10 use rustc_lexer::unescape::{unescape_raw_byte_str, unescape_raw_str};
11 use rustc_span::symbol::{kw, sym, Symbol};
28 /// Converts literal token into a semantic literal.
29 fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
30 let token::Lit { kind, symbol, suffix } = lit;
31 if suffix.is_some() && !kind.may_have_suffix() {
32 return Err(LitError::InvalidSuffix);
37 assert!(symbol.is_bool_lit());
38 LitKind::Bool(symbol == kw::True)
41 return unescape_byte(&symbol.as_str())
43 .map_err(|_| LitError::LexerError);
46 return unescape_char(&symbol.as_str())
48 .map_err(|_| LitError::LexerError);
51 // There are some valid suffixes for integer and float literals,
52 // so all the handling is done internally.
53 token::Integer => return integer_lit(symbol, suffix),
54 token::Float => return float_lit(symbol, suffix),
57 // If there are no characters requiring special treatment we can
58 // reuse the symbol from the token. Otherwise, we must generate a
59 // new symbol because the string in the LitKind is different to the
60 // string in the token.
61 let s = symbol.as_str();
62 let symbol = if s.contains(&['\\', '\r'][..]) {
63 let mut buf = String::with_capacity(s.len());
64 let mut error = Ok(());
65 unescape_str(&s, &mut |_, unescaped_char| match unescaped_char {
67 Err(_) => error = Err(LitError::LexerError),
74 LitKind::Str(symbol, ast::StrStyle::Cooked)
78 let s = symbol.as_str();
79 let symbol = if s.contains('\r') {
80 let mut buf = String::with_capacity(s.len());
81 let mut error = Ok(());
82 unescape_raw_str(&s, &mut |_, unescaped_char| match unescaped_char {
84 Err(_) => error = Err(LitError::LexerError),
92 LitKind::Str(symbol, ast::StrStyle::Raw(n))
95 let s = symbol.as_str();
96 let mut buf = Vec::with_capacity(s.len());
97 let mut error = Ok(());
98 unescape_byte_str(&s, &mut |_, unescaped_byte| match unescaped_byte {
100 Err(_) => error = Err(LitError::LexerError),
104 LitKind::ByteStr(Lrc::new(buf))
106 token::ByteStrRaw(_) => {
107 let s = symbol.as_str();
108 let bytes = if s.contains('\r') {
109 let mut buf = Vec::with_capacity(s.len());
110 let mut error = Ok(());
111 unescape_raw_byte_str(&s, &mut |_, unescaped_byte| match unescaped_byte {
112 Ok(c) => buf.push(c),
113 Err(_) => error = Err(LitError::LexerError),
119 symbol.to_string().into_bytes()
122 LitKind::ByteStr(Lrc::new(bytes))
124 token::Err => LitKind::Err(symbol),
128 /// Attempts to recover a token from semantic literal.
129 /// This function is used when the original token doesn't exist (e.g. the literal is created
130 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
131 pub fn to_lit_token(&self) -> token::Lit {
132 let (kind, symbol, suffix) = match *self {
133 LitKind::Str(symbol, ast::StrStyle::Cooked) => {
134 // Don't re-intern unless the escaped string is different.
135 let s = symbol.as_str();
136 let escaped = s.escape_default().to_string();
137 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
138 (token::Str, symbol, None)
140 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
141 LitKind::ByteStr(ref bytes) => {
145 .flat_map(ascii::escape_default)
146 .map(Into::<char>::into)
147 .collect::<String>();
148 (token::ByteStr, Symbol::intern(&string), None)
150 LitKind::Byte(byte) => {
151 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
152 (token::Byte, Symbol::intern(&string), None)
154 LitKind::Char(ch) => {
155 let string: String = ch.escape_default().map(Into::<char>::into).collect();
156 (token::Char, Symbol::intern(&string), None)
158 LitKind::Int(n, ty) => {
159 let suffix = match ty {
160 ast::LitIntType::Unsigned(ty) => Some(ty.name()),
161 ast::LitIntType::Signed(ty) => Some(ty.name()),
162 ast::LitIntType::Unsuffixed => None,
164 (token::Integer, sym::integer(n), suffix)
166 LitKind::Float(symbol, ty) => {
167 let suffix = match ty {
168 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
169 ast::LitFloatType::Unsuffixed => None,
171 (token::Float, symbol, suffix)
173 LitKind::Bool(value) => {
174 let symbol = if value { kw::True } else { kw::False };
175 (token::Bool, symbol, None)
177 LitKind::Err(symbol) => (token::Err, symbol, None),
180 token::Lit::new(kind, symbol, suffix)
185 /// Converts literal token into an AST literal.
186 pub fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> {
187 Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span })
190 /// Converts arbitrary token into an AST literal.
191 pub fn from_token(token: &Token) -> Result<Lit, LitError> {
192 let lit = match token.kind {
193 token::Ident(name, false) if name.is_bool_lit() => {
194 token::Lit::new(token::Bool, name, None)
196 token::Literal(lit) => lit,
197 token::Interpolated(ref nt) => {
198 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt {
199 if let ast::ExprKind::Lit(lit) = &expr.kind {
200 return Ok(lit.clone());
203 return Err(LitError::NotLiteral);
205 _ => return Err(LitError::NotLiteral),
208 Lit::from_lit_token(lit, token.span)
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: kind.to_lit_token(), kind, span }
218 /// Losslessly convert an AST literal into a token stream.
219 pub fn token_tree(&self) -> TokenTree {
220 let token = match self.token.kind {
221 token::Bool => token::Ident(self.token.symbol, false),
222 _ => token::Literal(self.token),
224 TokenTree::token(token, self.span)
228 fn strip_underscores(symbol: Symbol) -> Symbol {
229 // Do not allocate a new string unless necessary.
230 let s = symbol.as_str();
232 let mut s = s.to_string();
233 s.retain(|c| c != '_');
234 return Symbol::intern(&s);
239 fn filtered_float_lit(
241 suffix: Option<Symbol>,
243 ) -> Result<LitKind, LitError> {
244 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
246 return Err(LitError::NonDecimalFloat(base));
249 Some(suf) => LitKind::Float(
251 ast::LitFloatType::Suffixed(match suf {
252 sym::f32 => ast::FloatTy::F32,
253 sym::f64 => ast::FloatTy::F64,
254 _ => return Err(LitError::InvalidFloatSuffix),
257 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
261 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
262 debug!("float_lit: {:?}, {:?}", symbol, suffix);
263 filtered_float_lit(strip_underscores(symbol), suffix, 10)
266 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
267 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
268 let symbol = strip_underscores(symbol);
269 let s = symbol.as_str();
271 let base = match s.as_bytes() {
272 [b'0', b'x', ..] => 16,
273 [b'0', b'o', ..] => 8,
274 [b'0', b'b', ..] => 2,
278 let ty = match suffix {
279 Some(suf) => match suf {
280 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
281 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
282 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
283 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
284 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
285 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
286 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
287 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
288 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
289 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
290 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
291 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
292 // `1f64` and `2f32` etc. are valid float literals, and
293 // `fxxx` looks more like an invalid float literal than invalid integer literal.
294 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
295 _ => return Err(LitError::InvalidIntSuffix),
297 _ => ast::LitIntType::Unsuffixed,
300 let s = &s[if base != 10 { 2 } else { 0 }..];
301 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
302 // Small bases are lexed as if they were base 10, e.g, the string
303 // might be `0b10201`. This will cause the conversion above to fail,
304 // but these kinds of errors are already reported by the lexer.
306 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
307 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }