]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/literal.rs
e6351d89c6c31055e73608ddb392b92327dcbe2e
[rust.git] / compiler / rustc_ast / src / util / literal.rs
1 //! Code related to parsing literals.
2
3 use crate::ast::{self, Lit, LitKind};
4 use crate::token::{self, Token};
5
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};
9 use rustc_span::Span;
10
11 use std::ascii;
12 use tracing::debug;
13
14 pub enum LitError {
15     NotLiteral,
16     LexerError,
17     InvalidSuffix,
18     InvalidIntSuffix,
19     InvalidFloatSuffix,
20     NonDecimalFloat(u32),
21     IntTooLarge,
22 }
23
24 impl LitKind {
25     /// Converts literal token into a semantic literal.
26     pub fn from_token_lit(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);
30         }
31
32         Ok(match kind {
33             token::Bool => {
34                 assert!(symbol.is_bool_lit());
35                 LitKind::Bool(symbol == kw::True)
36             }
37             token::Byte => {
38                 return unescape_byte(symbol.as_str())
39                     .map(LitKind::Byte)
40                     .map_err(|_| LitError::LexerError);
41             }
42             token::Char => {
43                 return unescape_char(symbol.as_str())
44                     .map(LitKind::Char)
45                     .map_err(|_| LitError::LexerError);
46             }
47
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),
52
53             token::Str => {
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.
65                     unescape_literal(
66                         &s,
67                         Mode::Str,
68                         &mut #[inline(always)]
69                         |_, unescaped_char| match unescaped_char {
70                             Ok(c) => buf.push(c),
71                             Err(err) => {
72                                 if err.is_fatal() {
73                                     error = Err(LitError::LexerError);
74                                 }
75                             }
76                         },
77                     );
78                     error?;
79                     Symbol::intern(&buf)
80                 } else {
81                     symbol
82                 };
83                 LitKind::Str(symbol, ast::StrStyle::Cooked)
84             }
85             token::StrRaw(n) => {
86                 // Ditto.
87                 let s = symbol.as_str();
88                 let symbol =
89                     if s.contains('\r') {
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 {
94                                 Ok(c) => buf.push(c),
95                                 Err(err) => {
96                                     if err.is_fatal() {
97                                         error = Err(LitError::LexerError);
98                                     }
99                                 }
100                             }
101                         });
102                         error?;
103                         Symbol::intern(&buf)
104                     } else {
105                         symbol
106                     };
107                 LitKind::Str(symbol, ast::StrStyle::Raw(n))
108             }
109             token::ByteStr => {
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),
116                         Err(err) => {
117                             if err.is_fatal() {
118                                 error = Err(LitError::LexerError);
119                             }
120                         }
121                     }
122                 });
123                 error?;
124                 LitKind::ByteStr(buf.into())
125             }
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),
134                             Err(err) => {
135                                 if err.is_fatal() {
136                                     error = Err(LitError::LexerError);
137                                 }
138                             }
139                         }
140                     });
141                     error?;
142                     buf
143                 } else {
144                     symbol.to_string().into_bytes()
145                 };
146
147                 LitKind::ByteStr(bytes.into())
148             }
149             token::Err => LitKind::Err(symbol),
150         })
151     }
152
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_token_lit(&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)
164             }
165             LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
166             LitKind::ByteStr(ref bytes) => {
167                 let string = bytes
168                     .iter()
169                     .cloned()
170                     .flat_map(ascii::escape_default)
171                     .map(Into::<char>::into)
172                     .collect::<String>();
173                 (token::ByteStr, Symbol::intern(&string), None)
174             }
175             LitKind::Byte(byte) => {
176                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
177                 (token::Byte, Symbol::intern(&string), None)
178             }
179             LitKind::Char(ch) => {
180                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
181                 (token::Char, Symbol::intern(&string), None)
182             }
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,
188                 };
189                 (token::Integer, sym::integer(n), suffix)
190             }
191             LitKind::Float(symbol, ty) => {
192                 let suffix = match ty {
193                     ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
194                     ast::LitFloatType::Unsuffixed => None,
195                 };
196                 (token::Float, symbol, suffix)
197             }
198             LitKind::Bool(value) => {
199                 let symbol = if value { kw::True } else { kw::False };
200                 (token::Bool, symbol, None)
201             }
202             LitKind::Err(symbol) => (token::Err, symbol, None),
203         };
204
205         token::Lit::new(kind, symbol, suffix)
206     }
207 }
208
209 impl Lit {
210     /// Converts literal token into an AST literal.
211     pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<Lit, LitError> {
212         Ok(Lit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span })
213     }
214
215     /// Converts arbitrary token into an AST literal.
216     ///
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)
222             }
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
227                 {
228                     return Ok(lit.clone());
229                 }
230                 return Err(LitError::NotLiteral);
231             }
232             _ => return Err(LitError::NotLiteral),
233         };
234
235         Lit::from_token_lit(lit, token.span)
236     }
237
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_lit: kind.to_token_lit(), kind, span }
243     }
244
245     /// Losslessly convert an AST literal into a token.
246     pub fn to_token(&self) -> Token {
247         let kind = match self.token_lit.kind {
248             token::Bool => token::Ident(self.token_lit.symbol, false),
249             _ => token::Literal(self.token_lit),
250         };
251         Token::new(kind, self.span)
252     }
253 }
254
255 fn strip_underscores(symbol: Symbol) -> Symbol {
256     // Do not allocate a new string unless necessary.
257     let s = symbol.as_str();
258     if s.contains('_') {
259         let mut s = s.to_string();
260         s.retain(|c| c != '_');
261         return Symbol::intern(&s);
262     }
263     symbol
264 }
265
266 fn filtered_float_lit(
267     symbol: Symbol,
268     suffix: Option<Symbol>,
269     base: u32,
270 ) -> Result<LitKind, LitError> {
271     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
272     if base != 10 {
273         return Err(LitError::NonDecimalFloat(base));
274     }
275     Ok(match suffix {
276         Some(suf) => LitKind::Float(
277             symbol,
278             ast::LitFloatType::Suffixed(match suf {
279                 sym::f32 => ast::FloatTy::F32,
280                 sym::f64 => ast::FloatTy::F64,
281                 _ => return Err(LitError::InvalidFloatSuffix),
282             }),
283         ),
284         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
285     })
286 }
287
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)
291 }
292
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();
297
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,
302         _ => 10,
303     };
304
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),
323         },
324         _ => ast::LitIntType::Unsuffixed,
325     };
326
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.
332         let from_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 }
335     })
336 }