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_literal, unescape_literal, Mode};
10 use rustc_span::symbol::{kw, sym, Symbol};
27 /// Converts literal token into a semantic literal.
28 fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
29 let token::Lit { kind, symbol, suffix } = lit;
30 if suffix.is_some() && !kind.may_have_suffix() {
31 return Err(LitError::InvalidSuffix);
36 assert!(symbol.is_bool_lit());
37 LitKind::Bool(symbol == kw::True)
40 return unescape_byte(&symbol.as_str())
42 .map_err(|_| LitError::LexerError);
45 return unescape_char(&symbol.as_str())
47 .map_err(|_| LitError::LexerError);
50 // There are some valid suffixes for integer and float literals,
51 // so all the handling is done internally.
52 token::Integer => return integer_lit(symbol, suffix),
53 token::Float => return float_lit(symbol, suffix),
56 // If there are no characters requiring special treatment we can
57 // reuse the symbol from the token. Otherwise, we must generate a
58 // new symbol because the string in the LitKind is different to the
59 // string in the token.
60 let s = symbol.as_str();
62 if s.contains(&['\\', '\r'][..]) {
63 let mut buf = String::with_capacity(s.len());
64 let mut error = Ok(());
65 unescape_literal(&s, Mode::Str, &mut |_, unescaped_char| {
66 match unescaped_char {
68 Err(_) => error = Err(LitError::LexerError),
76 LitKind::Str(symbol, ast::StrStyle::Cooked)
80 let s = symbol.as_str();
83 let mut buf = String::with_capacity(s.len());
84 let mut error = Ok(());
85 unescape_literal(&s, Mode::RawStr, &mut |_, unescaped_char| {
86 match unescaped_char {
88 Err(_) => error = Err(LitError::LexerError),
97 LitKind::Str(symbol, ast::StrStyle::Raw(n))
100 let s = symbol.as_str();
101 let mut buf = Vec::with_capacity(s.len());
102 let mut error = Ok(());
103 unescape_byte_literal(&s, Mode::ByteStr, &mut |_, unescaped_byte| {
104 match unescaped_byte {
105 Ok(c) => buf.push(c),
106 Err(_) => error = Err(LitError::LexerError),
111 LitKind::ByteStr(Lrc::new(buf))
113 token::ByteStrRaw(_) => {
114 let s = symbol.as_str();
115 let bytes = if s.contains('\r') {
116 let mut buf = Vec::with_capacity(s.len());
117 let mut error = Ok(());
118 unescape_byte_literal(&s, Mode::RawByteStr, &mut |_, unescaped_byte| {
119 match unescaped_byte {
120 Ok(c) => buf.push(c),
121 Err(_) => error = Err(LitError::LexerError),
128 symbol.to_string().into_bytes()
131 LitKind::ByteStr(Lrc::new(bytes))
133 token::Err => LitKind::Err(symbol),
137 /// Attempts to recover a token from semantic literal.
138 /// This function is used when the original token doesn't exist (e.g. the literal is created
139 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
140 pub fn to_lit_token(&self) -> token::Lit {
141 let (kind, symbol, suffix) = match *self {
142 LitKind::Str(symbol, ast::StrStyle::Cooked) => {
143 // Don't re-intern unless the escaped string is different.
144 let s = symbol.as_str();
145 let escaped = s.escape_default().to_string();
146 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
147 (token::Str, symbol, None)
149 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
150 LitKind::ByteStr(ref bytes) => {
154 .flat_map(ascii::escape_default)
155 .map(Into::<char>::into)
156 .collect::<String>();
157 (token::ByteStr, Symbol::intern(&string), None)
159 LitKind::Byte(byte) => {
160 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
161 (token::Byte, Symbol::intern(&string), None)
163 LitKind::Char(ch) => {
164 let string: String = ch.escape_default().map(Into::<char>::into).collect();
165 (token::Char, Symbol::intern(&string), None)
167 LitKind::Int(n, ty) => {
168 let suffix = match ty {
169 ast::LitIntType::Unsigned(ty) => Some(ty.name()),
170 ast::LitIntType::Signed(ty) => Some(ty.name()),
171 ast::LitIntType::Unsuffixed => None,
173 (token::Integer, sym::integer(n), suffix)
175 LitKind::Float(symbol, ty) => {
176 let suffix = match ty {
177 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
178 ast::LitFloatType::Unsuffixed => None,
180 (token::Float, symbol, suffix)
182 LitKind::Bool(value) => {
183 let symbol = if value { kw::True } else { kw::False };
184 (token::Bool, symbol, None)
186 LitKind::Err(symbol) => (token::Err, symbol, None),
189 token::Lit::new(kind, symbol, suffix)
194 /// Converts literal token into an AST literal.
195 pub fn from_lit_token(token: token::Lit, span: Span) -> Result<Lit, LitError> {
196 Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span })
199 /// Converts arbitrary token into an AST literal.
201 /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation.
202 pub fn from_token(token: &Token) -> Result<Lit, LitError> {
203 let lit = match token.uninterpolate().kind {
204 token::Ident(name, false) if name.is_bool_lit() => {
205 token::Lit::new(token::Bool, name, None)
207 token::Literal(lit) => lit,
208 token::Interpolated(ref nt, _) => {
209 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt {
210 if let ast::ExprKind::Lit(lit) = &expr.kind {
211 return Ok(lit.clone());
214 return Err(LitError::NotLiteral);
216 _ => return Err(LitError::NotLiteral),
219 Lit::from_lit_token(lit, token.span)
222 /// Attempts to recover an AST literal from semantic literal.
223 /// This function is used when the original token doesn't exist (e.g. the literal is created
224 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
225 pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
226 Lit { token: kind.to_lit_token(), kind, span }
229 /// Losslessly convert an AST literal into a token stream.
230 pub fn token_tree(&self) -> TokenTree {
231 let token = match self.token.kind {
232 token::Bool => token::Ident(self.token.symbol, false),
233 _ => token::Literal(self.token),
235 TokenTree::token(token, self.span)
239 fn strip_underscores(symbol: Symbol) -> Symbol {
240 // Do not allocate a new string unless necessary.
241 let s = symbol.as_str();
243 let mut s = s.to_string();
244 s.retain(|c| c != '_');
245 return Symbol::intern(&s);
250 fn filtered_float_lit(
252 suffix: Option<Symbol>,
254 ) -> Result<LitKind, LitError> {
255 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
257 return Err(LitError::NonDecimalFloat(base));
260 Some(suf) => LitKind::Float(
262 ast::LitFloatType::Suffixed(match suf {
263 sym::f32 => ast::FloatTy::F32,
264 sym::f64 => ast::FloatTy::F64,
265 _ => return Err(LitError::InvalidFloatSuffix),
268 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
272 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
273 debug!("float_lit: {:?}, {:?}", symbol, suffix);
274 filtered_float_lit(strip_underscores(symbol), suffix, 10)
277 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
278 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
279 let symbol = strip_underscores(symbol);
280 let s = symbol.as_str();
282 let base = match s.as_bytes() {
283 [b'0', b'x', ..] => 16,
284 [b'0', b'o', ..] => 8,
285 [b'0', b'b', ..] => 2,
289 let ty = match suffix {
290 Some(suf) => match suf {
291 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
292 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
293 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
294 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
295 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
296 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
297 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
298 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
299 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
300 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
301 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
302 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
303 // `1f64` and `2f32` etc. are valid float literals, and
304 // `fxxx` looks more like an invalid float literal than invalid integer literal.
305 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
306 _ => return Err(LitError::InvalidIntSuffix),
308 _ => ast::LitIntType::Unsuffixed,
311 let s = &s[if base != 10 { 2 } else { 0 }..];
312 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
313 // Small bases are lexed as if they were base 10, e.g, the string
314 // might be `0b10201`. This will cause the conversion above to fail,
315 // but these kinds of errors are already reported by the lexer.
317 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
318 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }