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