1 //! Code related to parsing literals.
3 use crate::ast::{self, LitKind, MetaItemLit};
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};
21 /// Converts literal token into a semantic literal.
22 pub fn from_token_lit(lit: token::Lit) -> Result<LitKind, LitError> {
23 let token::Lit { kind, symbol, suffix } = lit;
24 if suffix.is_some() && !kind.may_have_suffix() {
25 return Err(LitError::InvalidSuffix);
30 assert!(symbol.is_bool_lit());
31 LitKind::Bool(symbol == kw::True)
34 return unescape_byte(symbol.as_str())
36 .map_err(|_| LitError::LexerError);
39 return unescape_char(symbol.as_str())
41 .map_err(|_| LitError::LexerError);
44 // There are some valid suffixes for integer and float literals,
45 // so all the handling is done internally.
46 token::Integer => return integer_lit(symbol, suffix),
47 token::Float => return float_lit(symbol, suffix),
50 // If there are no characters requiring special treatment we can
51 // reuse the symbol from the token. Otherwise, we must generate a
52 // new symbol because the string in the LitKind is different to the
53 // string in the token.
54 let s = symbol.as_str();
55 let symbol = if s.contains(['\\', '\r']) {
56 let mut buf = String::with_capacity(s.len());
57 let mut error = Ok(());
58 // Force-inlining here is aggressive but the closure is
59 // called on every char in the string, so it can be
60 // hot in programs with many long strings.
64 &mut #[inline(always)]
65 |_, unescaped_char| match unescaped_char {
69 error = Err(LitError::LexerError);
79 LitKind::Str(symbol, ast::StrStyle::Cooked)
83 let s = symbol.as_str();
86 let mut buf = String::with_capacity(s.len());
87 let mut error = Ok(());
88 unescape_literal(s, Mode::RawStr, &mut |_, unescaped_char| {
89 match unescaped_char {
93 error = Err(LitError::LexerError);
103 LitKind::Str(symbol, ast::StrStyle::Raw(n))
106 let s = symbol.as_str();
107 let mut buf = Vec::with_capacity(s.len());
108 let mut error = Ok(());
109 unescape_literal(s, Mode::ByteStr, &mut |_, c| match c {
110 Ok(c) => buf.push(byte_from_char(c)),
113 error = Err(LitError::LexerError);
118 LitKind::ByteStr(buf.into())
120 token::ByteStrRaw(_) => {
121 let s = symbol.as_str();
122 let bytes = if s.contains('\r') {
123 let mut buf = Vec::with_capacity(s.len());
124 let mut error = Ok(());
125 unescape_literal(s, Mode::RawByteStr, &mut |_, c| match c {
126 Ok(c) => buf.push(byte_from_char(c)),
129 error = Err(LitError::LexerError);
136 symbol.to_string().into_bytes()
139 LitKind::ByteStr(bytes.into())
141 token::Err => LitKind::Err,
145 /// Attempts to recover a token from semantic literal.
146 /// This function is used when the original token doesn't exist (e.g. the literal is created
147 /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing).
148 pub fn to_token_lit(&self) -> token::Lit {
149 let (kind, symbol, suffix) = match *self {
150 LitKind::Str(symbol, ast::StrStyle::Cooked) => {
151 // Don't re-intern unless the escaped string is different.
152 let s = symbol.as_str();
153 let escaped = s.escape_default().to_string();
154 let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
155 (token::Str, symbol, None)
157 LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
158 LitKind::ByteStr(ref bytes) => {
159 let string = bytes.escape_ascii().to_string();
160 (token::ByteStr, Symbol::intern(&string), None)
162 LitKind::Byte(byte) => {
163 let string: String = ascii::escape_default(byte).map(Into::<char>::into).collect();
164 (token::Byte, Symbol::intern(&string), None)
166 LitKind::Char(ch) => {
167 let string: String = ch.escape_default().map(Into::<char>::into).collect();
168 (token::Char, Symbol::intern(&string), None)
170 LitKind::Int(n, ty) => {
171 let suffix = match ty {
172 ast::LitIntType::Unsigned(ty) => Some(ty.name()),
173 ast::LitIntType::Signed(ty) => Some(ty.name()),
174 ast::LitIntType::Unsuffixed => None,
176 (token::Integer, sym::integer(n), suffix)
178 LitKind::Float(symbol, ty) => {
179 let suffix = match ty {
180 ast::LitFloatType::Suffixed(ty) => Some(ty.name()),
181 ast::LitFloatType::Unsuffixed => None,
183 (token::Float, symbol, suffix)
185 LitKind::Bool(value) => {
186 let symbol = if value { kw::True } else { kw::False };
187 (token::Bool, symbol, None)
189 // This only shows up in places like `-Zunpretty=hir` output, so we
190 // don't bother to produce something useful.
191 LitKind::Err => (token::Err, Symbol::intern("<bad-literal>"), None),
194 token::Lit::new(kind, symbol, suffix)
199 /// Converts token literal into a meta item literal.
200 pub fn from_token_lit(token_lit: token::Lit, span: Span) -> Result<MetaItemLit, LitError> {
201 Ok(MetaItemLit { token_lit, kind: LitKind::from_token_lit(token_lit)?, span })
204 /// Converts an arbitrary token into meta item literal.
205 pub fn from_token(token: &Token) -> Option<MetaItemLit> {
206 token::Lit::from_token(token)
207 .and_then(|token_lit| MetaItemLit::from_token_lit(token_lit, token.span).ok())
211 fn strip_underscores(symbol: Symbol) -> Symbol {
212 // Do not allocate a new string unless necessary.
213 let s = symbol.as_str();
215 let mut s = s.to_string();
216 s.retain(|c| c != '_');
217 return Symbol::intern(&s);
222 fn filtered_float_lit(
224 suffix: Option<Symbol>,
226 ) -> Result<LitKind, LitError> {
227 debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base);
229 return Err(LitError::NonDecimalFloat(base));
232 Some(suf) => LitKind::Float(
234 ast::LitFloatType::Suffixed(match suf {
235 sym::f32 => ast::FloatTy::F32,
236 sym::f64 => ast::FloatTy::F64,
237 _ => return Err(LitError::InvalidFloatSuffix),
240 None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed),
244 fn float_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
245 debug!("float_lit: {:?}, {:?}", symbol, suffix);
246 filtered_float_lit(strip_underscores(symbol), suffix, 10)
249 fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitError> {
250 debug!("integer_lit: {:?}, {:?}", symbol, suffix);
251 let symbol = strip_underscores(symbol);
252 let s = symbol.as_str();
254 let base = match s.as_bytes() {
255 [b'0', b'x', ..] => 16,
256 [b'0', b'o', ..] => 8,
257 [b'0', b'b', ..] => 2,
261 let ty = match suffix {
262 Some(suf) => match suf {
263 sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize),
264 sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8),
265 sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16),
266 sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32),
267 sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64),
268 sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128),
269 sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
270 sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
271 sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
272 sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32),
273 sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64),
274 sym::u128 => ast::LitIntType::Unsigned(ast::UintTy::U128),
275 // `1f64` and `2f32` etc. are valid float literals, and
276 // `fxxx` looks more like an invalid float literal than invalid integer literal.
277 _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base),
278 _ => return Err(LitError::InvalidIntSuffix),
280 _ => ast::LitIntType::Unsuffixed,
283 let s = &s[if base != 10 { 2 } else { 0 }..];
284 u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
285 // Small bases are lexed as if they were base 10, e.g, the string
286 // might be `0b10201`. This will cause the conversion above to fail,
287 // but these kinds of errors are already reported by the lexer.
289 base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base));
290 if from_lexer { LitError::LexerError } else { LitError::IntTooLarge }