]> git.lizzy.rs Git - rust.git/blob - src/librustc_ast/util/literal.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / src / librustc_ast / 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 crate::tokenstream::TokenTree;
6
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};
11 use rustc_span::Span;
12
13 use std::ascii;
14 use tracing::debug;
15
16 pub enum LitError {
17     NotLiteral,
18     LexerError,
19     InvalidSuffix,
20     InvalidIntSuffix,
21     InvalidFloatSuffix,
22     NonDecimalFloat(u32),
23     IntTooLarge,
24 }
25
26 impl LitKind {
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);
32         }
33
34         Ok(match kind {
35             token::Bool => {
36                 assert!(symbol.is_bool_lit());
37                 LitKind::Bool(symbol == kw::True)
38             }
39             token::Byte => {
40                 return unescape_byte(&symbol.as_str())
41                     .map(LitKind::Byte)
42                     .map_err(|_| LitError::LexerError);
43             }
44             token::Char => {
45                 return unescape_char(&symbol.as_str())
46                     .map(LitKind::Char)
47                     .map_err(|_| LitError::LexerError);
48             }
49
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),
54
55             token::Str => {
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();
61                 let symbol =
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 {
67                                 Ok(c) => buf.push(c),
68                                 Err(_) => error = Err(LitError::LexerError),
69                             }
70                         });
71                         error?;
72                         Symbol::intern(&buf)
73                     } else {
74                         symbol
75                     };
76                 LitKind::Str(symbol, ast::StrStyle::Cooked)
77             }
78             token::StrRaw(n) => {
79                 // Ditto.
80                 let s = symbol.as_str();
81                 let symbol =
82                     if s.contains('\r') {
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 {
87                                 Ok(c) => buf.push(c),
88                                 Err(_) => error = Err(LitError::LexerError),
89                             }
90                         });
91                         error?;
92                         buf.shrink_to_fit();
93                         Symbol::intern(&buf)
94                     } else {
95                         symbol
96                     };
97                 LitKind::Str(symbol, ast::StrStyle::Raw(n))
98             }
99             token::ByteStr => {
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),
107                     }
108                 });
109                 error?;
110                 buf.shrink_to_fit();
111                 LitKind::ByteStr(Lrc::new(buf))
112             }
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),
122                         }
123                     });
124                     error?;
125                     buf.shrink_to_fit();
126                     buf
127                 } else {
128                     symbol.to_string().into_bytes()
129                 };
130
131                 LitKind::ByteStr(Lrc::new(bytes))
132             }
133             token::Err => LitKind::Err(symbol),
134         })
135     }
136
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)
148             }
149             LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
150             LitKind::ByteStr(ref bytes) => {
151                 let string = bytes
152                     .iter()
153                     .cloned()
154                     .flat_map(ascii::escape_default)
155                     .map(Into::<char>::into)
156                     .collect::<String>();
157                 (token::ByteStr, Symbol::intern(&string), None)
158             }
159             LitKind::Byte(byte) => {
160                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
161                 (token::Byte, Symbol::intern(&string), None)
162             }
163             LitKind::Char(ch) => {
164                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
165                 (token::Char, Symbol::intern(&string), None)
166             }
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,
172                 };
173                 (token::Integer, sym::integer(n), suffix)
174             }
175             LitKind::Float(symbol, ty) => {
176                 let suffix = match ty {
177                     ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
178                     ast::LitFloatType::Unsuffixed => None,
179                 };
180                 (token::Float, symbol, suffix)
181             }
182             LitKind::Bool(value) => {
183                 let symbol = if value { kw::True } else { kw::False };
184                 (token::Bool, symbol, None)
185             }
186             LitKind::Err(symbol) => (token::Err, symbol, None),
187         };
188
189         token::Lit::new(kind, symbol, suffix)
190     }
191 }
192
193 impl Lit {
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 })
197     }
198
199     /// Converts arbitrary token into an AST literal.
200     ///
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)
206             }
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());
212                     }
213                 }
214                 return Err(LitError::NotLiteral);
215             }
216             _ => return Err(LitError::NotLiteral),
217         };
218
219         Lit::from_lit_token(lit, token.span)
220     }
221
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 }
227     }
228
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),
234         };
235         TokenTree::token(token, self.span)
236     }
237 }
238
239 fn strip_underscores(symbol: Symbol) -> Symbol {
240     // Do not allocate a new string unless necessary.
241     let s = symbol.as_str();
242     if s.contains('_') {
243         let mut s = s.to_string();
244         s.retain(|c| c != '_');
245         return Symbol::intern(&s);
246     }
247     symbol
248 }
249
250 fn filtered_float_lit(
251     symbol: Symbol,
252     suffix: Option<Symbol>,
253     base: u32,
254 ) -> Result<LitKind, LitError> {
255     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
256     if base != 10 {
257         return Err(LitError::NonDecimalFloat(base));
258     }
259     Ok(match suffix {
260         Some(suf) => LitKind::Float(
261             symbol,
262             ast::LitFloatType::Suffixed(match suf {
263                 sym::f32 => ast::FloatTy::F32,
264                 sym::f64 => ast::FloatTy::F64,
265                 _ => return Err(LitError::InvalidFloatSuffix),
266             }),
267         ),
268         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
269     })
270 }
271
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)
275 }
276
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();
281
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,
286         _ => 10,
287     };
288
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),
307         },
308         _ => ast::LitIntType::Unsuffixed,
309     };
310
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.
316         let from_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 }
319     })
320 }