Skip to main content

xur_parser/parser/
lit.rs

1//! Turning literal tokens into values, like rustc's `LitKind::from_token_lit`.
2//!
3//! A literal that fails to decode is reported here and becomes
4//! [`LitKind::Err`], so parsing carries on as if it were valid.
5
6use xur_ast::{Lit, LitKind};
7use xur_errors::Diag;
8use xur_span::{Span, Symbol};
9
10use super::expected::Expected;
11use super::{PResult, Parser};
12use crate::token::{Keyword, TokenKind};
13use crate::unescape::unescape_str;
14
15impl Parser<'_> {
16    pub fn parse_lit(&mut self) -> PResult<Lit> {
17        match self.parse_opt_lit() {
18            Some(lit) => Ok(lit),
19            None => {
20                self.expected(Expected::Lit);
21                Err(self.unexpected())
22            }
23        }
24    }
25
26    /// Parses a literal if the current token is one.
27    pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
28        let span = self.token.span;
29        let kind = match self.token.kind {
30            TokenKind::IntLit(text) => self.decode_int(text, span),
31            TokenKind::FloatLit(text) => LitKind::Float(Symbol::intern(&text.replace('_', ""))),
32            TokenKind::StringLit(text) => self.decode_str(text, span),
33            TokenKind::Keyword(Keyword::True) => LitKind::Bool(true),
34            TokenKind::Keyword(Keyword::False) => LitKind::Bool(false),
35            _ => return None,
36        };
37        self.bump();
38        Some(Lit { kind, span })
39    }
40
41    fn decode_int(&mut self, text: &str, span: Span) -> LitKind {
42        match text.replace('_', "").parse() {
43            Ok(value) => LitKind::Int(value),
44            Err(_) => {
45                self.report(
46                    Diag::error("integer literal is too large", span)
47                        .with_label(span, "does not fit in 64 bits"),
48                );
49                LitKind::Err
50            }
51        }
52    }
53
54    /// Decodes the contents of a string literal token spanning `span`,
55    /// reporting every invalid escape.
56    fn decode_str(&mut self, contents: &str, span: Span) -> LitKind {
57        let contents_start = span.start + 1; // skip the opening quote
58        let mut value = String::with_capacity(contents.len());
59        let mut valid = true;
60        unescape_str(contents, |range, result| match result {
61            Ok(c) => value.push(c),
62            Err(error) => {
63                valid = false;
64                let span = Span::new(contents_start + range.start, contents_start + range.end);
65                self.diags
66                    .push(Diag::error(error.to_string(), span).with_label(span, error.label()));
67            }
68        });
69        if valid {
70            LitKind::Str(Symbol::intern(&value))
71        } else {
72            LitKind::Err
73        }
74    }
75}