ifc_lite_core/parser/
numeric_literal.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The one STEP numeric-literal grammar every Rust raw-byte reader shares
6//! (#5266): the Rust twin of `isCompleteStepNumericLiteral` in
7//! `packages/data/src/step-numeric-literal.ts` (#5193). Keep the two
8//! grammars identical.
9//!
10//! `fast_float2::parse_partial` is not a STEP reader. It returns the longest
11//! prefix it can read and leaves the caller to decide what the rest means,
12//! so a dropped comma (`1.52.3`) read as `1.52` and then `.3` became the next
13//! coordinate. It also accepts `nan`, `inf` and `infinity`, which are not
14//! STEP literals at all. So no reader hands bytes to `fast_float2` until
15//! [`step_numeric_literal_len`] has said exactly which bytes form one whole
16//! literal.
17
18use super::lexical::is_step_space;
19
20/// Length of the STEP `REAL`/`INTEGER` literal at the start of `bytes`, when
21/// the bytes there are exactly one literal followed by something that may
22/// legally follow a list item: end of input, `,`, `)`, STEP whitespace, or a
23/// `/*` comment. `None` otherwise.
24///
25/// Grammar (ISO 10303-21 ยง5.3, as `isCompleteStepNumericLiteral` reads it):
26/// optional sign, digits with an optional `.` and fraction digits or a
27/// bare-dot fraction (`1`, `1.`, `1.5`, `.5`), at least one digit overall,
28/// then an optional exponent (`e`/`E`, optional sign, at least one digit).
29///
30/// A hand-rolled forward scan with no allocation: it runs once per number on
31/// the geometry hot path.
32#[inline]
33pub fn step_numeric_literal_len(bytes: &[u8]) -> Option<usize> {
34    scan_step_numeric_literal(bytes).map(|(len, _)| len)
35}
36
37/// Keep the kind found by the grammar walk so the number reader does not
38/// scan the admitted literal again to distinguish INTEGER from REAL (#7779).
39#[inline]
40fn scan_step_numeric_literal(bytes: &[u8]) -> Option<(usize, bool)> {
41    scan::<false>(bytes).map(|literal| (literal.len, literal.real))
42}
43
44/// One admitted literal as the grammar walk saw it. With `VALUE`, the walk
45/// also folds every digit into `mantissa` (wrapping: it is only read when
46/// `digits <= 19`, where it cannot wrap) and reads the exponent (saturated
47/// far beyond any exponent the exact path accepts), so the reader need not
48/// walk the literal a second time to value it.
49struct Literal {
50    len: usize,
51    real: bool,
52    /// Integer and fraction digits, leading zeros included.
53    digits: usize,
54    fraction_digits: usize,
55    mantissa: u64,
56    exponent: i64,
57}
58
59/// Saturation for the exponent read by [`scan`]: far outside both the exact
60/// path's range and `f64`'s, so a saturated exponent always falls back.
61const EXPONENT_CAP: i64 = 1 << 20;
62
63/// The grammar walk of [`scan_step_numeric_literal`]: the one grammar, with
64/// the value accumulation compiled in only for [`read_step_number`].
65#[inline(always)]
66fn scan<const VALUE: bool>(bytes: &[u8]) -> Option<Literal> {
67    let mut mantissa = 0u64;
68    let mut digits_from = |mut i: usize| {
69        while let Some(&b) = bytes.get(i).filter(|b| b.is_ascii_digit()) {
70            if VALUE {
71                mantissa = mantissa.wrapping_mul(10).wrapping_add(u64::from(b - b'0'));
72            }
73            i += 1;
74        }
75        i
76    };
77    let mut i = usize::from(matches!(bytes.first(), Some(b'+' | b'-')));
78    let int_end = digits_from(i);
79    let mut digits = int_end - i;
80    i = int_end;
81    let mut real = bytes.get(i) == Some(&b'.');
82    let mut fraction_digits = 0;
83    if real {
84        let frac_end = digits_from(i + 1);
85        fraction_digits = frac_end - (i + 1);
86        digits += fraction_digits;
87        i = frac_end;
88    }
89    if digits == 0 {
90        return None;
91    }
92    let mut exponent = 0i64;
93    if matches!(bytes.get(i), Some(b'e' | b'E')) {
94        real = true;
95        let negative = bytes.get(i + 1) == Some(&b'-');
96        let exp_start = i + 1 + usize::from(matches!(bytes.get(i + 1), Some(b'+' | b'-')));
97        let mut exp_end = exp_start;
98        while let Some(&b) = bytes.get(exp_end).filter(|b| b.is_ascii_digit()) {
99            if VALUE {
100                exponent = (exponent * 10 + i64::from(b - b'0')).min(EXPONENT_CAP);
101            }
102            exp_end += 1;
103        }
104        if exp_end == exp_start {
105            return None;
106        }
107        if negative {
108            exponent = -exponent;
109        }
110        i = exp_end;
111    }
112    let literal = Literal { len: i, real, digits, fraction_digits, mantissa, exponent };
113    match bytes.get(i) {
114        None => Some(literal),
115        Some(&b) if b == b',' || b == b')' || is_step_space(b) => Some(literal),
116        Some(&b'/') if bytes.get(i + 1) == Some(&b'*') => Some(literal),
117        _ => None,
118    }
119}
120
121/// Exact powers of ten: every one up to 1e22 is an `f64` exactly.
122const POW10: [f64; 23] = [
123    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
124    1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
125];
126
127/// The literal's magnitude when it is exact in one IEEE operation (Clinger's
128/// fast path): a mantissa of at most 2^53 is an exact `f64`, as is 10^k for
129/// k <= 22, so `m * 10^k` and `m / 10^k` are each the correctly rounded value
130/// of the decimal, the value `fast_float2` returns for it. `None` otherwise;
131/// the caller then asks `fast_float2`. The sign is the caller's (-0. stays
132/// -0.).
133#[inline(always)]
134fn exact_magnitude(literal: &Literal) -> Option<f64> {
135    if literal.digits > 19 || literal.mantissa > 1 << 53 {
136        return None;
137    }
138    let power = literal.exponent - literal.fraction_digits as i64;
139    let m = literal.mantissa as f64;
140    match power {
141        0..=22 => Some(m * POW10[power as usize]),
142        -22..=-1 => Some(m / POW10[(-power) as usize]),
143        _ => None,
144    }
145}
146
147/// The one admission rule for a decoded STEP `REAL` (#7678): the value must be
148/// finite in the type it is read into. Every Rust reader that turns STEP
149/// bytes into a float goes through this, the nom [`super::tokenizer`] and
150/// [`parse_step_numeric`] alike, so no reader admits what another refuses.
151///
152/// STEP has no spelling for NaN or infinity (the grammar above refuses `nan`
153/// and `inf`), so the only way to get one is a literal the type cannot hold:
154/// `1.E400` overflows `f64`, and `1.E39` overflows the `f32` the coordinate
155/// fast paths read into. A refused literal has two consumers:
156///
157/// - geometry refuses it. The fast paths answer `None` in every mode; the
158///   tokenizer yields `Token::UnrepresentableReal`, and a geometry decoder
159///   (`EntityDecoder::with_strict_reals`) refuses the record with
160///   `Error::UnrepresentableReal`, so the element fails closed and is
161///   counted. An object definition (a product's own record) is admitted:
162///   its reals are descriptive, never geometry;
163/// - everything else keeps it: the default decoder is lossless and reads
164///   the record as before, the literal as a signed infinity, so the data
165///   model, exporters and georeferencing never lose an entity to it.
166///
167/// Only overflow is refused. `-0.` stays `-0.0`, sign bit included, and an
168/// underflowing literal (`1.E-400`) still reads as the zero it rounds to.
169#[inline]
170pub(crate) fn admit_step_real<T: Copy + Into<f64>>(value: T) -> Option<T> {
171    value.into().is_finite().then_some(value)
172}
173
174/// Read the one STEP numeric literal at the start of `bytes`: its value and
175/// the number of bytes it spans. `None` when [`step_numeric_literal_len`]
176/// refuses it, so a malformed token is never read as its parseable prefix,
177/// and when [`admit_step_real`] refuses the value, so an overflowing one is
178/// never read as an infinity.
179#[inline]
180pub fn parse_step_numeric<T: fast_float2::FastFloat + Into<f64>>(
181    bytes: &[u8],
182) -> Option<(T, usize)> {
183    let len = step_numeric_literal_len(bytes)?;
184    let value = fast_float2::parse::<T, _>(&bytes[..len]).ok()?;
185    admit_step_real(value).map(|v| (v, len))
186}
187
188/// [`parse_step_numeric`] for a token that must be exactly one literal: the
189/// whole of `token`, STEP whitespace trimmed, read as an admitted `f64`.
190/// For readers that already split a record into attribute tokens, which used
191/// `str::parse::<f64>` and so read `inf`, `NaN` and `1.E400` as numbers.
192#[inline]
193pub fn parse_step_real(token: &[u8]) -> Option<f64> {
194    let start = token.iter().position(|&b| !is_step_space(b))?;
195    let end = token.iter().rposition(|&b| !is_step_space(b))? + 1;
196    let token = &token[start..end];
197    let (value, len) = parse_step_numeric::<f64>(token)?;
198    (len == token.len()).then_some(value)
199}
200
201/// One STEP number as the tokenizer and every byte reader see it (F4-1).
202#[derive(Debug, Clone, Copy, PartialEq)]
203pub enum StepNumber<'a> {
204    /// An `INTEGER`: no `.` and no exponent.
205    Integer(i64),
206    /// A `REAL` that `f64` holds. `-0.` keeps its sign bit.
207    Real(f64),
208    /// A complete `REAL` literal `f64` cannot hold (`1.E400`), as its raw
209    /// text; [`admit_step_real`] decides (#7678).
210    Unrepresentable(&'a [u8]),
211}
212
213/// Read the one STEP number at the start of `bytes` and the bytes it spans.
214///
215/// The one number reader: the nom tokenizer's number branch and the raw-byte
216/// readers share it, so the grammar is [`step_numeric_literal_len`] alone
217/// (`.5`, `1E5`, `+1`, `1.`, `-0.`). A literal is a `REAL` iff it has a `.`
218/// or an exponent (`1E5` is `Real(100000.0)`). `None` for anything that is
219/// not exactly one literal, and for an `INTEGER` beyond `i64`.
220#[inline]
221pub fn read_step_number(bytes: &[u8]) -> Option<(StepNumber<'_>, usize)> {
222    let scanned = scan::<true>(bytes)?;
223    let len = scanned.len;
224    let literal = &bytes[..len];
225    let negative = literal[0] == b'-';
226    if scanned.real {
227        // The grammar walk already valued the literal when it is exact in one
228        // operation (#7880's `N.` case among them); else it already validated
229        // the entire literal for `fast_float2` (#7779).
230        let value = match exact_magnitude(&scanned) {
231            Some(magnitude) => {
232                #[cfg(test)]
233                tests::note_valuation(true);
234                if negative { -magnitude } else { magnitude }
235            }
236            None => {
237                #[cfg(test)]
238                tests::note_valuation(false);
239                fast_float2::parse_partial::<f64, _>(literal).ok()?.0
240            }
241        };
242        let number = admit_step_real(value)
243            .map_or(StepNumber::Unrepresentable(literal), StepNumber::Real);
244        return Some((number, len));
245    }
246    // At most 18 digits cannot leave `i64`, so the walk's mantissa is the
247    // value; a longer integer takes the checked walk.
248    if scanned.digits <= 18 {
249        let magnitude = scanned.mantissa as i64;
250        return Some((StepNumber::Integer(if negative { -magnitude } else { magnitude }), len));
251    }
252    let digits = match literal[0] {
253        b'-' | b'+' => &literal[1..],
254        _ => literal,
255    };
256    // Accumulate negatively so `i64::MIN` is representable.
257    let mut value: i64 = 0;
258    for &d in digits {
259        value = value.checked_mul(10)?.checked_sub(i64::from(d - b'0'))?;
260    }
261    let value = if negative { value } else { value.checked_neg()? };
262    Some((StepNumber::Integer(value), len))
263}
264
265#[cfg(test)]
266#[path = "numeric_literal_tests.rs"]
267mod tests;