1 //! Code related to parsing literals.
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};
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);
31 assert!(symbol.is_bool_lit());
32 LitKind::Bool(symbol == kw::True)
35 return unescape_byte(symbol.as_str())
37 .map_err(|_| LitError::LexerError);
40 return unescape_char(symbol.as_str())
42 .map_err(|_| LitError::LexerError);
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),
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.
65 &mut #[inline(always)]
66 |_, unescaped_char| match unescaped_char {
70 error = Err(LitError::LexerError);
80 LitKind::Str(symbol, ast::StrStyle::Cooked)
84 let s = symbol.as_str();
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 {
94 error = Err(LitError::LexerError);
104 LitKind::Str(symbol, ast::StrStyle::Raw(n))
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)),
114 error = Err(LitError::LexerError);
119 LitKind::ByteStr(buf.into(), StrStyle::Cooked)
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)),
130 error = Err(LitError::LexerError);
137 symbol.to_string().into_bytes()
140 LitKind::ByteStr(bytes.into(), StrStyle::Raw(n))
142 token::Err => LitKind::Err,
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)
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)
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)
168 LitKind::Byte(byte) => {
169 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
170 (token::Byte, Symbol::intern(&string), None)
172 LitKind::Char(ch) => {
173 let string: String = ch.escape_default().map(Into::<char>::into).collect();
174 (token::Char, Symbol::intern(&string), None)
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,
182 (token::Integer, sym::integer(n), suffix)
184 LitKind::Float(symbol, ty) => {
185 let suffix = match ty {
186 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
187 ast::LitFloatType::Unsuffixed => None,
189 (token::Float, symbol, suffix)
191 LitKind::Bool(value) => {
192 let symbol = if value { kw::True } else { kw::False };
193 (token::Bool, symbol, None)
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),
200 token::Lit::new(kind, symbol, suffix)
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> {
208 symbol: token_lit.symbol,
209 suffix: token_lit.suffix,
210 kind: LitKind::from_token_lit(token_lit)?,
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,
230 token::Lit::new(kind, self.symbol, self.suffix)
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())
240 fn strip_underscores(symbol: Symbol) -> Symbol {
241 // Do not allocate a new string unless necessary.
242 let s = symbol.as_str();
244 let mut s = s.to_string();
245 s.retain(|c| c != '_');
246 return Symbol::intern(&s);
251 fn filtered_float_lit(
253 suffix: Option<Symbol>,
255 ) -> Result<LitKind, LitError> {
256 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
258 return Err(LitError::NonDecimalFloat(base));
261 Some(suf) => LitKind::Float(
263 ast::LitFloatType::Suffixed(match suf {
264 sym::f32 => ast::FloatTy::F32,
265 sym::f64 => ast::FloatTy::F64,
266 _ => return Err(LitError::InvalidFloatSuffix),
269 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
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)
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();
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,
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),
309 _ => ast::LitIntType::Unsuffixed,
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.
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 }