]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/literal.rs
e267f8cd10027d349f8dacb4a8d808cc88df76f9
[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 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};
8 use rustc_span::Span;
9 use std::ascii;
10
11 pub enum LitError {
12     NotLiteral,
13     LexerError,
14     InvalidSuffix,
15     InvalidIntSuffix,
16     InvalidFloatSuffix,
17     NonDecimalFloat(u32),
18     IntTooLarge,
19 }
20
21 impl LitKind {
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);
27         }
28
29         Ok(match kind {
30             token::Bool => {
31                 assert!(symbol.is_bool_lit());
32                 LitKind::Bool(symbol == kw::True)
33             }
34             token::Byte => {
35                 return unescape_byte(symbol.as_str())
36                     .map(LitKind::Byte)
37                     .map_err(|_| LitError::LexerError);
38             }
39             token::Char => {
40                 return unescape_char(symbol.as_str())
41                     .map(LitKind::Char)
42                     .map_err(|_| LitError::LexerError);
43             }
44
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),
49
50             token::Str => {
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.
62                     unescape_literal(
63                         &s,
64                         Mode::Str,
65                         &mut #[inline(always)]
66                         |_, unescaped_char| match unescaped_char {
67                             Ok(c) => buf.push(c),
68                             Err(err) => {
69                                 if err.is_fatal() {
70                                     error = Err(LitError::LexerError);
71                                 }
72                             }
73                         },
74                     );
75                     error?;
76                     Symbol::intern(&buf)
77                 } else {
78                     symbol
79                 };
80                 LitKind::Str(symbol, ast::StrStyle::Cooked)
81             }
82             token::StrRaw(n) => {
83                 // Ditto.
84                 let s = symbol.as_str();
85                 let symbol =
86                     if s.contains('\r') {
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 {
91                                 Ok(c) => buf.push(c),
92                                 Err(err) => {
93                                     if err.is_fatal() {
94                                         error = Err(LitError::LexerError);
95                                     }
96                                 }
97                             }
98                         });
99                         error?;
100                         Symbol::intern(&buf)
101                     } else {
102                         symbol
103                     };
104                 LitKind::Str(symbol, ast::StrStyle::Raw(n))
105             }
106             token::ByteStr => {
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)),
112                     Err(err) => {
113                         if err.is_fatal() {
114                             error = Err(LitError::LexerError);
115                         }
116                     }
117                 });
118                 error?;
119                 LitKind::ByteStr(buf.into())
120             }
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)),
128                         Err(err) => {
129                             if err.is_fatal() {
130                                 error = Err(LitError::LexerError);
131                             }
132                         }
133                     });
134                     error?;
135                     buf
136                 } else {
137                     symbol.to_string().into_bytes()
138                 };
139
140                 LitKind::ByteStr(bytes.into())
141             }
142             token::Err => LitKind::Err,
143         })
144     }
145
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)
157             }
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)
162             }
163             LitKind::Byte(byte) => {
164                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
165                 (token::Byte, Symbol::intern(&string), None)
166             }
167             LitKind::Char(ch) => {
168                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
169                 (token::Char, Symbol::intern(&string), None)
170             }
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,
176                 };
177                 (token::Integer, sym::integer(n), suffix)
178             }
179             LitKind::Float(symbol, ty) => {
180                 let suffix = match ty {
181                     ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
182                     ast::LitFloatType::Unsuffixed => None,
183                 };
184                 (token::Float, symbol, suffix)
185             }
186             LitKind::Bool(value) => {
187                 let symbol = if value { kw::True } else { kw::False };
188                 (token::Bool, symbol, None)
189             }
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),
193         };
194
195         token::Lit::new(kind, symbol, suffix)
196     }
197 }
198
199 impl Lit {
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 })
203     }
204
205     /// Converts arbitrary token into an AST literal.
206     ///
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)
212             }
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
217                 {
218                     return Ok(lit.clone());
219                 }
220                 return Err(LitError::NotLiteral);
221             }
222             _ => return Err(LitError::NotLiteral),
223         };
224
225         Lit::from_token_lit(lit, token.span)
226     }
227
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 }
233     }
234
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)
240     }
241
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),
247         };
248         Token::new(kind, self.span)
249     }
250 }
251
252 fn strip_underscores(symbol: Symbol) -> Symbol {
253     // Do not allocate a new string unless necessary.
254     let s = symbol.as_str();
255     if s.contains('_') {
256         let mut s = s.to_string();
257         s.retain(|c| c != '_');
258         return Symbol::intern(&s);
259     }
260     symbol
261 }
262
263 fn filtered_float_lit(
264     symbol: Symbol,
265     suffix: Option<Symbol>,
266     base: u32,
267 ) -> Result<LitKind, LitError> {
268     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
269     if base != 10 {
270         return Err(LitError::NonDecimalFloat(base));
271     }
272     Ok(match suffix {
273         Some(suf) => LitKind::Float(
274             symbol,
275             ast::LitFloatType::Suffixed(match suf {
276                 sym::f32 => ast::FloatTy::F32,
277                 sym::f64 => ast::FloatTy::F64,
278                 _ => return Err(LitError::InvalidFloatSuffix),
279             }),
280         ),
281         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
282     })
283 }
284
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)
288 }
289
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();
294
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,
299         _ => 10,
300     };
301
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),
320         },
321         _ => ast::LitIntType::Unsuffixed,
322     };
323
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.
329         let from_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 }
332     })
333 }