]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/util/literal.rs
Rollup merge of #68438 - Aaron1011:fix/tait-non-defining, r=estebank
[rust.git] / src / libsyntax / 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     pub fn from_token(token: &Token) -> Result<Lit, LitError> {
192         let lit = match token.kind {
193             token::Ident(name, false) if name.is_bool_lit() => {
194                 token::Lit::new(token::Bool, name, None)
195             }
196             token::Literal(lit) => lit,
197             token::Interpolated(ref nt) => {
198                 if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt {
199                     if let ast::ExprKind::Lit(lit) = &expr.kind {
200                         return Ok(lit.clone());
201                     }
202                 }
203                 return Err(LitError::NotLiteral);
204             }
205             _ => return Err(LitError::NotLiteral),
206         };
207
208         Lit::from_lit_token(lit, token.span)
209     }
210
211     /// Attempts to recover an AST literal from semantic literal.
212     /// This function is used when the original token doesn't exist (e.g. the literal is created
213     /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
214     pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit {
215         Lit { token: kind.to_lit_token(), kind, span }
216     }
217
218     /// Losslessly convert an AST literal into a token stream.
219     pub fn token_tree(&self) -> TokenTree {
220         let token = match self.token.kind {
221             token::Bool => token::Ident(self.token.symbol, false),
222             _ => token::Literal(self.token),
223         };
224         TokenTree::token(token, self.span)
225     }
226 }
227
228 fn strip_underscores(symbol: Symbol) -> Symbol {
229     // Do not allocate a new string unless necessary.
230     let s = symbol.as_str();
231     if s.contains('_') {
232         let mut s = s.to_string();
233         s.retain(|c| c != '_');
234         return Symbol::intern(&s);
235     }
236     symbol
237 }
238
239 fn filtered_float_lit(
240     symbol: Symbol,
241     suffix: Option<Symbol>,
242     base: u32,
243 ) -> Result<LitKind, LitError> {
244     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
245     if base != 10 {
246         return Err(LitError::NonDecimalFloat(base));
247     }
248     Ok(match suffix {
249         Some(suf) => LitKind::Float(
250             symbol,
251             ast::LitFloatType::Suffixed(match suf {
252                 sym::f32 => ast::FloatTy::F32,
253                 sym::f64 => ast::FloatTy::F64,
254                 _ => return Err(LitError::InvalidFloatSuffix),
255             }),
256         ),
257         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
258     })
259 }
260
261 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
262     debug!("float_lit: {:?}, {:?}", symbol, suffix);
263     filtered_float_lit(strip_underscores(symbol), suffix, 10)
264 }
265
266 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
267     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
268     let symbol = strip_underscores(symbol);
269     let s = symbol.as_str();
270
271     let base = match s.as_bytes() {
272         [b'0', b'x', ..] => 16,
273         [b'0', b'o', ..] => 8,
274         [b'0', b'b', ..] => 2,
275         _ => 10,
276     };
277
278     let ty = match suffix {
279         Some(suf) => match suf {
280             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
281             sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
282             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
283             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
284             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
285             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
286             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
287             sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
288             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
289             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
290             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
291             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
292             // `1f64` and `2f32` etc. are valid float literals, and
293             // `fxxx` looks more like an invalid float literal than invalid integer literal.
294             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
295             _ => return Err(LitError::InvalidIntSuffix),
296         },
297         _ => ast::LitIntType::Unsuffixed,
298     };
299
300     let s = &s[if base != 10 { 2 } else { 0 }..];
301     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
302         // Small bases are lexed as if they were base 10, e.g, the string
303         // might be `0b10201`. This will cause the conversion above to fail,
304         // but these kinds of errors are already reported by the lexer.
305         let from_lexer =
306             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
307         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
308     })
309 }