]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/literal.rs
Auto merge of #99918 - WaffleLapkin:fnFnfun, r=estebank
[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_lexer::unescape::{byte_from_char, unescape_byte, unescape_char, unescape_literal, Mode};
6 use rustc_span::symbol::{kw, sym, Symbol};
7 use rustc_span::Span;
8 use std::ascii;
9
10 pub enum LitError {
11     NotLiteral,
12     LexerError,
13     InvalidSuffix,
14     InvalidIntSuffix,
15     InvalidFloatSuffix,
16     NonDecimalFloat(u32),
17     IntTooLarge,
18 }
19
20 impl LitKind {
21     /// Converts literal token into a semantic literal.
22     pub fn from_token_lit(lit: token::Lit) -> Result<LitKind, LitError> {
23         let token::Lit { kind, symbol, suffix } = lit;
24         if suffix.is_some() && !kind.may_have_suffix() {
25             return Err(LitError::InvalidSuffix);
26         }
27
28         Ok(match kind {
29             token::Bool => {
30                 assert!(symbol.is_bool_lit());
31                 LitKind::Bool(symbol == kw::True)
32             }
33             token::Byte => {
34                 return unescape_byte(symbol.as_str())
35                     .map(LitKind::Byte)
36                     .map_err(|_| LitError::LexerError);
37             }
38             token::Char => {
39                 return unescape_char(symbol.as_str())
40                     .map(LitKind::Char)
41                     .map_err(|_| LitError::LexerError);
42             }
43
44             // There are some valid suffixes for integer and float literals,
45             // so all the handling is done internally.
46             token::Integer => return integer_lit(symbol, suffix),
47             token::Float => return float_lit(symbol, suffix),
48
49             token::Str => {
50                 // If there are no characters requiring special treatment we can
51                 // reuse the symbol from the token. Otherwise, we must generate a
52                 // new symbol because the string in the LitKind is different to the
53                 // string in the token.
54                 let s = symbol.as_str();
55                 let symbol = if s.contains(&['\\', '\r']) {
56                     let mut buf = String::with_capacity(s.len());
57                     let mut error = Ok(());
58                     // Force-inlining here is aggressive but the closure is
59                     // called on every char in the string, so it can be
60                     // hot in programs with many long strings.
61                     unescape_literal(
62                         &s,
63                         Mode::Str,
64                         &mut #[inline(always)]
65                         |_, unescaped_char| match unescaped_char {
66                             Ok(c) => buf.push(c),
67                             Err(err) => {
68                                 if err.is_fatal() {
69                                     error = Err(LitError::LexerError);
70                                 }
71                             }
72                         },
73                     );
74                     error?;
75                     Symbol::intern(&buf)
76                 } else {
77                     symbol
78                 };
79                 LitKind::Str(symbol, ast::StrStyle::Cooked)
80             }
81             token::StrRaw(n) => {
82                 // Ditto.
83                 let s = symbol.as_str();
84                 let symbol =
85                     if s.contains('\r') {
86                         let mut buf = String::with_capacity(s.len());
87                         let mut error = Ok(());
88                         unescape_literal(&s, Mode::RawStr, &mut |_, unescaped_char| {
89                             match unescaped_char {
90                                 Ok(c) => buf.push(c),
91                                 Err(err) => {
92                                     if err.is_fatal() {
93                                         error = Err(LitError::LexerError);
94                                     }
95                                 }
96                             }
97                         });
98                         error?;
99                         Symbol::intern(&buf)
100                     } else {
101                         symbol
102                     };
103                 LitKind::Str(symbol, ast::StrStyle::Raw(n))
104             }
105             token::ByteStr => {
106                 let s = symbol.as_str();
107                 let mut buf = Vec::with_capacity(s.len());
108                 let mut error = Ok(());
109                 unescape_literal(&s, Mode::ByteStr, &mut |_, c| match c {
110                     Ok(c) => buf.push(byte_from_char(c)),
111                     Err(err) => {
112                         if err.is_fatal() {
113                             error = Err(LitError::LexerError);
114                         }
115                     }
116                 });
117                 error?;
118                 LitKind::ByteStr(buf.into())
119             }
120             token::ByteStrRaw(_) => {
121                 let s = symbol.as_str();
122                 let bytes = if s.contains('\r') {
123                     let mut buf = Vec::with_capacity(s.len());
124                     let mut error = Ok(());
125                     unescape_literal(&s, Mode::RawByteStr, &mut |_, c| match c {
126                         Ok(c) => buf.push(byte_from_char(c)),
127                         Err(err) => {
128                             if err.is_fatal() {
129                                 error = Err(LitError::LexerError);
130                             }
131                         }
132                     });
133                     error?;
134                     buf
135                 } else {
136                     symbol.to_string().into_bytes()
137                 };
138
139                 LitKind::ByteStr(bytes.into())
140             }
141             token::Err => LitKind::Err,
142         })
143     }
144
145     /// Attempts to recover a token from semantic literal.
146     /// This function is used when the original token doesn't exist (e.g. the literal is created
147     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
148     pub fn to_token_lit(&self) -> token::Lit {
149         let (kind, symbol, suffix) = match *self {
150             LitKind::Str(symbol, ast::StrStyle::Cooked) => {
151                 // Don't re-intern unless the escaped string is different.
152                 let s = symbol.as_str();
153                 let escaped = s.escape_default().to_string();
154                 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
155                 (token::Str, symbol, None)
156             }
157             LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
158             LitKind::ByteStr(ref bytes) => {
159                 let string = bytes.escape_ascii().to_string();
160                 (token::ByteStr, Symbol::intern(&string), None)
161             }
162             LitKind::Byte(byte) => {
163                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
164                 (token::Byte, Symbol::intern(&string), None)
165             }
166             LitKind::Char(ch) => {
167                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
168                 (token::Char, Symbol::intern(&string), None)
169             }
170             LitKind::Int(n, ty) => {
171                 let suffix = match ty {
172                     ast::LitIntType::Unsigned(ty) => Some(ty.name()),
173                     ast::LitIntType::Signed(ty) => Some(ty.name()),
174                     ast::LitIntType::Unsuffixed => None,
175                 };
176                 (token::Integer, sym::integer(n), suffix)
177             }
178             LitKind::Float(symbol, ty) => {
179                 let suffix = match ty {
180                     ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
181                     ast::LitFloatType::Unsuffixed => None,
182                 };
183                 (token::Float, symbol, suffix)
184             }
185             LitKind::Bool(value) => {
186                 let symbol = if value { kw::True } else { kw::False };
187                 (token::Bool, symbol, None)
188             }
189             // This only shows up in places like `-Zunpretty=hir` output, so we
190             // don't bother to produce something useful.
191             LitKind::Err => (token::Err, Symbol::intern("<bad-literal>"), None),
192         };
193
194         token::Lit::new(kind, symbol, suffix)
195     }
196 }
197
198 impl Lit {
199     /// Converts literal token into an AST literal.
200     pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<Lit, LitError> {
201         Ok(Lit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span })
202     }
203
204     /// Converts arbitrary token into an AST literal.
205     ///
206     /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation.
207     pub fn from_token(token: &Token) -> Result<Lit, LitError> {
208         let lit = match token.uninterpolate().kind {
209             token::Ident(name, false) if name.is_bool_lit() => {
210                 token::Lit::new(token::Bool, name, None)
211             }
212             token::Literal(lit) => lit,
213             token::Interpolated(ref nt) => {
214                 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt
215                     && let ast::ExprKind::Lit(lit) = &expr.kind
216                 {
217                     return Ok(lit.clone());
218                 }
219                 return Err(LitError::NotLiteral);
220             }
221             _ => return Err(LitError::NotLiteral),
222         };
223
224         Lit::from_token_lit(lit, token.span)
225     }
226
227     /// Attempts to recover an AST literal from semantic literal.
228     /// This function is used when the original token doesn't exist (e.g. the literal is created
229     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
230     pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
231         Lit { token_lit: kind.to_token_lit(), kind, span }
232     }
233
234     /// Losslessly convert an AST literal into a token.
235     pub fn to_token(&self) -> Token {
236         let kind = match self.token_lit.kind {
237             token::Bool => token::Ident(self.token_lit.symbol, false),
238             _ => token::Literal(self.token_lit),
239         };
240         Token::new(kind, self.span)
241     }
242 }
243
244 fn strip_underscores(symbol: Symbol) -> Symbol {
245     // Do not allocate a new string unless necessary.
246     let s = symbol.as_str();
247     if s.contains('_') {
248         let mut s = s.to_string();
249         s.retain(|c| c != '_');
250         return Symbol::intern(&s);
251     }
252     symbol
253 }
254
255 fn filtered_float_lit(
256     symbol: Symbol,
257     suffix: Option<Symbol>,
258     base: u32,
259 ) -> Result<LitKind, LitError> {
260     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
261     if base != 10 {
262         return Err(LitError::NonDecimalFloat(base));
263     }
264     Ok(match suffix {
265         Some(suf) => LitKind::Float(
266             symbol,
267             ast::LitFloatType::Suffixed(match suf {
268                 sym::f32 => ast::FloatTy::F32,
269                 sym::f64 => ast::FloatTy::F64,
270                 _ => return Err(LitError::InvalidFloatSuffix),
271             }),
272         ),
273         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
274     })
275 }
276
277 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
278     debug!("float_lit: {:?}, {:?}", symbol, suffix);
279     filtered_float_lit(strip_underscores(symbol), suffix, 10)
280 }
281
282 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
283     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
284     let symbol = strip_underscores(symbol);
285     let s = symbol.as_str();
286
287     let base = match s.as_bytes() {
288         [b'0', b'x', ..] => 16,
289         [b'0', b'o', ..] => 8,
290         [b'0', b'b', ..] => 2,
291         _ => 10,
292     };
293
294     let ty = match suffix {
295         Some(suf) => match suf {
296             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
297             sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
298             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
299             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
300             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
301             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
302             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
303             sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
304             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
305             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
306             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
307             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
308             // `1f64` and `2f32` etc. are valid float literals, and
309             // `fxxx` looks more like an invalid float literal than invalid integer literal.
310             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
311             _ => return Err(LitError::InvalidIntSuffix),
312         },
313         _ => ast::LitIntType::Unsuffixed,
314     };
315
316     let s = &s[if base != 10 { 2 } else { 0 }..];
317     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
318         // Small bases are lexed as if they were base 10, e.g, the string
319         // might be `0b10201`. This will cause the conversion above to fail,
320         // but these kinds of errors are already reported by the lexer.
321         let from_lexer =
322             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
323         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
324     })
325 }