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 std::num::IntErrorKind;
7
8use xur_ast::{Lit, LitKind};
9use xur_errors::Diag;
10use xur_span::{Span, Symbol};
11
12use super::expected::Expected;
13use super::{PResult, Parser};
14use crate::token::{Keyword, TokenKind};
15use crate::unescape::{unescape_bytes, unescape_str};
16
17impl Parser<'_> {
18    pub fn parse_lit(&mut self) -> PResult<Lit> {
19        match self.parse_opt_lit() {
20            Some(lit) => Ok(lit),
21            None => {
22                self.expected(Expected::Lit);
23                Err(self.unexpected())
24            }
25        }
26    }
27
28    /// Parses a literal if the current token is one.
29    pub(super) fn parse_opt_lit(&mut self) -> Option<Lit> {
30        let span = self.token.span;
31        let kind = match self.token.kind {
32            TokenKind::IntLit(text) => self.decode_int(text, span),
33            TokenKind::FloatLit(text) => LitKind::Float(Symbol::intern(&text.replace('_', ""))),
34            TokenKind::StringLit(text) => self.decode_str(text, span),
35            TokenKind::ByteStrLit(text) => self.decode_bytes(text, span),
36            TokenKind::Keyword(Keyword::True) => LitKind::Bool(true),
37            TokenKind::Keyword(Keyword::False) => LitKind::Bool(false),
38            _ => return None,
39        };
40        self.bump();
41        Some(Lit { kind, span })
42    }
43
44    /// Decodes a decimal, hex (`0x`), octal (`0o`) or binary (`0b`) integer.
45    fn decode_int(&mut self, text: &str, span: Span) -> LitKind {
46        let digits = text.replace('_', "");
47        let (radix, digits) = match digits.get(..2) {
48            Some("0x") => (16, &digits[2..]),
49            Some("0o") => (8, &digits[2..]),
50            Some("0b") => (2, &digits[2..]),
51            _ => (10, &digits[..]),
52        };
53        let error = match u64::from_str_radix(digits, radix) {
54            Ok(value) => return LitKind::Int(value),
55            Err(error) => error,
56        };
57        let (message, label) = match error.kind() {
58            IntErrorKind::Empty => (
59                "missing digits after the integer base prefix",
60                "expected digits".to_owned(),
61            ),
62            IntErrorKind::InvalidDigit => (
63                "invalid digit in integer literal",
64                format!("not a base {radix} digit"),
65            ),
66            _ => (
67                "integer literal is too large",
68                "does not fit in 64 bits".to_owned(),
69            ),
70        };
71        self.report(Diag::error(message, span).with_label(span, label));
72        LitKind::Err
73    }
74
75    /// Decodes the contents of a byte string literal token spanning `span`,
76    /// reporting every invalid escape.
77    fn decode_bytes(&mut self, contents: &str, span: Span) -> LitKind {
78        let contents_start = span.start + 2; // skip the `b"`
79        let mut value = Vec::with_capacity(contents.len());
80        let mut valid = true;
81        unescape_bytes(contents, |range, result| match result {
82            Ok(byte) => value.push(byte),
83            Err(error) => {
84                valid = false;
85                let span = Span::new(contents_start + range.start, contents_start + range.end);
86                self.diags
87                    .push(Diag::error(error.to_string(), span).with_label(span, error.label()));
88            }
89        });
90        if valid {
91            LitKind::ByteStr(value.into())
92        } else {
93            LitKind::Err
94        }
95    }
96
97    /// Decodes the contents of a string literal token spanning `span`,
98    /// reporting every invalid escape.
99    fn decode_str(&mut self, contents: &str, span: Span) -> LitKind {
100        let contents_start = span.start + 1; // skip the opening quote
101        let mut value = String::with_capacity(contents.len());
102        let mut valid = true;
103        unescape_str(contents, |range, result| match result {
104            Ok(c) => value.push(c),
105            Err(error) => {
106                valid = false;
107                let span = Span::new(contents_start + range.start, contents_start + range.end);
108                self.diags
109                    .push(Diag::error(error.to_string(), span).with_label(span, error.label()));
110            }
111        });
112        if valid {
113            LitKind::Str(Symbol::intern(&value))
114        } else {
115            LitKind::Err
116        }
117    }
118}