]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/util/literal.rs
Remove `token::Lit` from `ast::MetaItemLit`.
[rust.git] / compiler / rustc_ast / src / util / literal.rs
1 //! Code related to parsing literals.
2
3 use crate::ast::{self, LitKind, MetaItemLit, StrStyle};
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 use std::str;
10
11 #[derive(Debug)]
12 pub enum LitError {
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(), StrStyle::Cooked)
120             }
121             token::ByteStrRaw(n) => {
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(), StrStyle::Raw(n))
141             }
142             token::Err => LitKind::Err,
143         })
144     }
145
146     /// Synthesizes a token from a 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 synthesize_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, ast::StrStyle::Cooked) => {
160                 let string = bytes.escape_ascii().to_string();
161                 (token::ByteStr, Symbol::intern(&string), None)
162             }
163             LitKind::ByteStr(ref bytes, ast::StrStyle::Raw(n)) => {
164                 // Unwrap because raw byte string literals can only contain ASCII.
165                 let string = str::from_utf8(bytes).unwrap();
166                 (token::ByteStrRaw(n), Symbol::intern(&string), None)
167             }
168             LitKind::Byte(byte) => {
169                 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
170                 (token::Byte, Symbol::intern(&string), None)
171             }
172             LitKind::Char(ch) => {
173                 let string: String = ch.escape_default().map(Into::<char>::into).collect();
174                 (token::Char, Symbol::intern(&string), None)
175             }
176             LitKind::Int(n, ty) => {
177                 let suffix = match ty {
178                     ast::LitIntType::Unsigned(ty) => Some(ty.name()),
179                     ast::LitIntType::Signed(ty) => Some(ty.name()),
180                     ast::LitIntType::Unsuffixed => None,
181                 };
182                 (token::Integer, sym::integer(n), suffix)
183             }
184             LitKind::Float(symbol, ty) => {
185                 let suffix = match ty {
186                     ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
187                     ast::LitFloatType::Unsuffixed => None,
188                 };
189                 (token::Float, symbol, suffix)
190             }
191             LitKind::Bool(value) => {
192                 let symbol = if value { kw::True } else { kw::False };
193                 (token::Bool, symbol, None)
194             }
195             // This only shows up in places like `-Zunpretty=hir` output, so we
196             // don't bother to produce something useful.
197             LitKind::Err => (token::Err, Symbol::intern("<bad-literal>"), None),
198         };
199
200         token::Lit::new(kind, symbol, suffix)
201     }
202 }
203
204 impl MetaItemLit {
205     /// Converts a token literal into a meta item literal.
206     pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<MetaItemLit, LitError> {
207         Ok(MetaItemLit {
208             symbol: token_lit.symbol,
209             suffix: token_lit.suffix,
210             kind: LitKind::from_token_lit(token_lit)?,
211             span,
212         })
213     }
214
215     /// Cheaply converts a meta item literal into a token literal.
216     pub fn as_token_lit(&self) -> token::Lit {
217         let kind = match self.kind {
218             LitKind::Bool(_) => token::Bool,
219             LitKind::Str(_, ast::StrStyle::Cooked) => token::Str,
220             LitKind::Str(_, ast::StrStyle::Raw(n)) => token::StrRaw(n),
221             LitKind::ByteStr(_, ast::StrStyle::Cooked) => token::ByteStr,
222             LitKind::ByteStr(_, ast::StrStyle::Raw(n)) => token::ByteStrRaw(n),
223             LitKind::Byte(_) => token::Byte,
224             LitKind::Char(_) => token::Char,
225             LitKind::Int(..) => token::Integer,
226             LitKind::Float(..) => token::Float,
227             LitKind::Err => token::Err,
228         };
229
230         token::Lit::new(kind, self.symbol, self.suffix)
231     }
232
233     /// Converts an arbitrary token into meta item literal.
234     pub fn from_token(token: &Token) -> Option<MetaItemLit> {
235         token::Lit::from_token(token)
236             .and_then(|token_lit| MetaItemLit::from_token_lit(token_lit, token.span).ok())
237     }
238 }
239
240 fn strip_underscores(symbol: Symbol) -> Symbol {
241     // Do not allocate a new string unless necessary.
242     let s = symbol.as_str();
243     if s.contains('_') {
244         let mut s = s.to_string();
245         s.retain(|c| c != '_');
246         return Symbol::intern(&s);
247     }
248     symbol
249 }
250
251 fn filtered_float_lit(
252     symbol: Symbol,
253     suffix: Option<Symbol>,
254     base: u32,
255 ) -> Result<LitKind, LitError> {
256     debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
257     if base != 10 {
258         return Err(LitError::NonDecimalFloat(base));
259     }
260     Ok(match suffix {
261         Some(suf) => LitKind::Float(
262             symbol,
263             ast::LitFloatType::Suffixed(match suf {
264                 sym::f32 => ast::FloatTy::F32,
265                 sym::f64 => ast::FloatTy::F64,
266                 _ => return Err(LitError::InvalidFloatSuffix),
267             }),
268         ),
269         None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
270     })
271 }
272
273 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
274     debug!("float_lit: {:?}, {:?}", symbol, suffix);
275     filtered_float_lit(strip_underscores(symbol), suffix, 10)
276 }
277
278 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
279     debug!("integer_lit: {:?}, {:?}", symbol, suffix);
280     let symbol = strip_underscores(symbol);
281     let s = symbol.as_str();
282
283     let base = match s.as_bytes() {
284         [b'0', b'x', ..] => 16,
285         [b'0', b'o', ..] => 8,
286         [b'0', b'b', ..] => 2,
287         _ => 10,
288     };
289
290     let ty = match suffix {
291         Some(suf) => match suf {
292             sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
293             sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
294             sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
295             sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
296             sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
297             sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
298             sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
299             sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
300             sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
301             sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
302             sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
303             sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
304             // `1f64` and `2f32` etc. are valid float literals, and
305             // `fxxx` looks more like an invalid float literal than invalid integer literal.
306             _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
307             _ => return Err(LitError::InvalidIntSuffix),
308         },
309         _ => ast::LitIntType::Unsuffixed,
310     };
311
312     let s = &s[if base != 10 { 2 } else { 0 }..];
313     u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
314         // Small bases are lexed as if they were base 10, e.g, the string
315         // might be `0b10201`. This will cause the conversion above to fail,
316         // but these kinds of errors are already reported by the lexer.
317         let from_lexer =
318             base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
319         if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }
320     })
321 }