1
//! Numbers (integer / decimal / rational), `#u8(...)` byte vectors,
2
//! `#"..."` base64-tagged byte literals, and the rejection of the Scheme
3
//! boolean literals `#t` / `#f`.
4

            
5
use std::fmt;
6

            
7
use base64::Engine;
8
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
9
use winnow::ascii::{digit1, space0};
10
use winnow::combinator::{alt, cut_err, opt, preceded};
11
use winnow::error::{
12
    AddContext, ContextError, ErrMode, FromExternalError, ModalResult, StrContext, StrContextValue,
13
};
14
use winnow::prelude::*;
15
use winnow::token::take_till;
16

            
17
use crate::ast::{Expr, Fraction, Number};
18

            
19
use super::atoms::is_delimiter;
20

            
21
1107441595
pub(super) fn parse_hash_literal(input: &mut &str) -> ModalResult<Expr> {
22
1107441595
    alt((
23
1107441595
        parse_byte_vector_literal,
24
1107441595
        parse_base64_literal,
25
1107441595
        reject_scheme_boolean,
26
1107441595
    ))
27
1107441595
    .parse_next(input)
28
1107441595
}
29

            
30
#[derive(Debug, Clone)]
31
struct SchemeBoolean {
32
    literal: &'static str,
33
    replacement: &'static str,
34
}
35

            
36
impl fmt::Display for SchemeBoolean {
37
630
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38
630
        write!(
39
630
            f,
40
            "{} is not nomiscript syntax; use {}",
41
630
            self.literal, self.replacement
42
        )
43
630
    }
44
}
45

            
46
impl std::error::Error for SchemeBoolean {}
47

            
48
1107430972
fn reject_scheme_boolean(input: &mut &str) -> ModalResult<Expr> {
49
1107430972
    let scheme = alt((
50
1107430972
        alt(("#t", "#T")).value(SchemeBoolean {
51
1107430972
            literal: "#t",
52
1107430972
            replacement: "t",
53
1107430972
        }),
54
1107430972
        alt(("#f", "#F")).value(SchemeBoolean {
55
1107430972
            literal: "#f",
56
1107430972
            replacement: "nil",
57
1107430972
        }),
58
1107430972
    ))
59
1107430972
    .parse_next(input)?;
60
630
    if input.starts_with(|c: char| !is_delimiter(c)) {
61
        return Err(ErrMode::Backtrack(ContextError::new()));
62
630
    }
63
630
    Err(ErrMode::Cut(ContextError::from_external_error(
64
630
        input, scheme,
65
630
    )))
66
1107430972
}
67

            
68
1107441595
fn parse_byte_vector_literal(input: &mut &str) -> ModalResult<Expr> {
69
1107441595
    let _ = "#u8(".parse_next(input)?;
70
2296
    let mut bytes: Vec<u8> = Vec::new();
71
    loop {
72
8348
        let _ = space0.parse_next(input)?;
73
8348
        if input.starts_with(')') {
74
1670
            let _ = ')'.parse_next(input)?;
75
1670
            return Ok(Expr::Bytes(bytes));
76
6678
        }
77
6678
        if input.is_empty() {
78
1
            return Err(ErrMode::Cut(
79
1
                ContextError::new()
80
1
                    .add_context(input, &input.checkpoint(), StrContext::Label("byte vector"))
81
1
                    .add_context(
82
1
                        input,
83
1
                        &input.checkpoint(),
84
1
                        StrContext::Expected(StrContextValue::Description("closing paren")),
85
1
                    ),
86
1
            ));
87
6677
        }
88
6677
        let digits: &str = cut_err(digit1)
89
6677
            .context(StrContext::Label("byte"))
90
6677
            .context(StrContext::Expected(StrContextValue::Description(
91
6677
                "0..255 integer",
92
6677
            )))
93
6677
            .parse_next(input)?;
94
6469
        let val: u8 = digits.parse().map_err(|_| {
95
417
            ErrMode::Cut(ContextError::new().add_context(
96
417
                input,
97
417
                &input.checkpoint(),
98
417
                StrContext::Expected(StrContextValue::Description("byte must fit in 0..255")),
99
417
            ))
100
417
        })?;
101
6052
        bytes.push(val);
102
    }
103
1107441595
}
104

            
105
1107439299
fn parse_base64_literal(input: &mut &str) -> ModalResult<Expr> {
106
1107439299
    let _ = "#\"".parse_next(input)?;
107
76927293
    let payload: &str = take_till(0.., |c| c == '"').parse_next(input)?;
108
8327
    let _ = cut_err('"')
109
8327
        .context(StrContext::Label("base64 string"))
110
8327
        .context(StrContext::Expected(StrContextValue::Description(
111
8327
            "closing quote",
112
8327
        )))
113
8327
        .parse_next(input)?;
114
8326
    let bytes = BASE64_STANDARD.decode(payload).map_err(|_| {
115
1
        ErrMode::Cut(ContextError::new().add_context(
116
1
            input,
117
1
            &input.checkpoint(),
118
1
            StrContext::Expected(StrContextValue::Description("valid base64 payload")),
119
1
        ))
120
1
    })?;
121
8325
    Ok(Expr::Bytes(bytes))
122
1107439299
}
123

            
124
/// A hard (`Cut`) parse error for a numeric literal that is well-formed but
125
/// outside the `i64`-backed `Fraction` range. `Cut` (not `Backtrack`) because
126
/// the token is unambiguously a number — it must not fall back to a symbol.
127
627
fn range_cut(input: &mut &str, what: &'static str) -> ErrMode<ContextError> {
128
627
    ErrMode::Cut(ContextError::new().add_context(
129
627
        input,
130
627
        &input.checkpoint(),
131
627
        StrContext::Expected(StrContextValue::Description(what)),
132
627
    ))
133
627
}
134

            
135
/// The signed value as an `i64`: the sign is applied before the range check so
136
/// `i64::MIN`, whose magnitude has no positive `i64`, still reads.
137
861527092
fn signed_i64(
138
861527092
    input: &mut &str,
139
861527092
    sign: i128,
140
861527092
    magnitude: i128,
141
861527092
    what: &'static str,
142
861527092
) -> Result<i64, ErrMode<ContextError>> {
143
861527092
    sign.checked_mul(magnitude)
144
861527092
        .and_then(|value| i64::try_from(value).ok())
145
210
        .ok_or_else(|| range_cut(input, what))
146
861527092
}
147

            
148
862307195
fn parse_digits(input: &mut &str, digits: &str) -> Result<i128, ErrMode<ContextError>> {
149
862307195
    digits
150
862307195
        .parse()
151
        .map_err(|_| range_cut(input, "number out of i64 range"))
152
862307195
}
153

            
154
1107404961
pub(super) fn parse_number(input: &mut &str) -> ModalResult<Expr> {
155
1107404961
    let sign = opt(alt(("-".value(-1i128), "+".value(1i128))))
156
1107404961
        .map(|s| s.unwrap_or(1))
157
1107404961
        .parse_next(input)?;
158

            
159
1107404961
    let int_part: &str = digit1.parse_next(input)?;
160
862112945
    let int_val = parse_digits(input, int_part)?;
161

            
162
862112945
    let frac_part = opt(preceded('.', digit1)).parse_next(input)?;
163
862112945
    let denom_part = if frac_part.is_none() {
164
862107921
        opt(preceded('/', digit1)).parse_next(input)?
165
    } else {
166
5024
        None
167
    };
168

            
169
    // Optional trailing `%`: `15%` reads as `15/100`. Consumed BEFORE the
170
    // delimiter check so the `%` never leaks out as a stray token.
171
862112945
    let percent = opt('%').parse_next(input)?.is_some();
172

            
173
862112945
    if input.starts_with(|c: char| !is_delimiter(c)) {
174
774870
        return Err(ErrMode::Backtrack(ContextError::new()));
175
861338075
    }
176

            
177
861338075
    let integer_spelling = frac_part.is_none() && denom_part.is_none() && !percent;
178
861338075
    let fraction = match (frac_part, denom_part) {
179
        (Some(decimals), _) => {
180
5024
            let decimal_val = parse_digits(input, decimals)?;
181
5024
            let denom = u32::try_from(decimals.len())
182
5024
                .ok()
183
5024
                .and_then(|places| 10i64.checked_pow(places))
184
208
                .ok_or_else(|| range_cut(input, "decimal literal: too many fractional digits"))?;
185
4816
            let scaled = int_val
186
4816
                .checked_mul(i128::from(denom))
187
4816
                .and_then(|v| v.checked_add(decimal_val))
188
                .ok_or_else(|| range_cut(input, "decimal literal out of i64 range"))?;
189
4816
            let numer = signed_i64(input, sign, scaled, "decimal literal out of i64 range")?;
190
4608
            Fraction::new(numer, denom)
191
        }
192
        (None, Some(denom_str)) => {
193
189226
            let magnitude = parse_digits(input, denom_str)?;
194
189226
            let denom = signed_i64(input, 1, magnitude, "denominator within i64 range")?;
195
189226
            if denom == 0 {
196
1
                return Err(range_cut(input, "non-zero denominator in rational literal"));
197
189225
            }
198
189225
            Fraction::new(
199
189225
                signed_i64(input, sign, int_val, "numerator within i64 range")?,
200
189225
                denom,
201
            )
202
        }
203
861143825
        (None, None) => Fraction::from_integer(signed_i64(
204
861143825
            input,
205
861143825
            sign,
206
861143825
            int_val,
207
861143825
            "integer literal out of i64 range",
208
861143825
        )?),
209
    };
210

            
211
861337656
    let fraction = if percent {
212
        // Divide by 100 = scale the denominator by 100. Checked, so a
213
        // pathological literal (`1/9223372036854775807%`) is a structured parse
214
        // error, not an `i64` overflow panic (debug) / silent wrap (release) in
215
        // num-rational's unchecked `Div`.
216
1898
        let denom = fraction
217
1898
            .denom()
218
1898
            .checked_mul(100)
219
208
            .ok_or_else(|| range_cut(input, "percent literal denominator within i64 range"))?;
220
1690
        Fraction::new(*fraction.numer(), denom)
221
    } else {
222
861335758
        fraction
223
    };
224

            
225
861337448
    Ok(Expr::Number(match integer_spelling {
226
861142549
        true => Number::Index(*fraction.numer()),
227
194899
        false => Number::Scalar(fraction),
228
    }))
229
1107404961
}