Skip to main content

naga/front/wgsl/parse/
number.rs

1use alloc::format;
2
3use crate::front::wgsl::error::NumberError;
4use crate::front::wgsl::parse::directive::enable_extension::ImplementedEnableExtension;
5use crate::front::wgsl::parse::lexer::Token;
6use half::f16;
7
8/// When using this type assume no Abstract Int/Float for now
9#[derive(Copy, Clone, Debug, PartialEq)]
10pub enum Number {
11    /// Abstract Int (-2^63 ≤ i < 2^63)
12    AbstractInt(i64),
13    /// Abstract Float (IEEE-754 binary64)
14    AbstractFloat(f64),
15    /// Concrete i32
16    I32(i32),
17    /// Concrete u32
18    U32(u32),
19    /// Concrete i64
20    I64(i64),
21    /// Concrete u64
22    U64(u64),
23    /// Concrete f16
24    F16(f16),
25    /// Concrete f32
26    F32(f32),
27    /// Concrete f64
28    F64(f64),
29}
30
31impl Number {
32    pub(super) const fn requires_enable_extension(&self) -> Option<ImplementedEnableExtension> {
33        match *self {
34            Number::F16(_) => Some(ImplementedEnableExtension::F16),
35            Number::F64(_) => Some(ImplementedEnableExtension::WgpuF64),
36            _ => None,
37        }
38    }
39}
40
41pub(in crate::front::wgsl) fn consume_number(input: &str) -> (Token<'_>, &str) {
42    let (result, rest) = parse(input);
43    (Token::Number(result), rest)
44}
45
46enum Kind {
47    Int(IntKind),
48    Float(FloatKind),
49}
50
51enum IntKind {
52    I32,
53    U32,
54    I64,
55    U64,
56}
57
58#[derive(Debug)]
59enum FloatKind {
60    F16,
61    F32,
62    F64,
63}
64
65// The following regexes (from the WGSL spec) will be matched:
66
67// int_literal:
68// | / 0                                                                [iu]?   /
69// | / [1-9][0-9]*                                                      [iu]?   /
70// | / 0[xX][0-9a-fA-F]+                                                [iu]?   /
71
72// decimal_float_literal:
73// | / 0                                                                [fh]    /
74// | / [1-9][0-9]*                                                      [fh]    /
75// | / [0-9]*               \.[0-9]+            ([eE][+-]?[0-9]+)?      [fh]?   /
76// | / [0-9]+               \.[0-9]*            ([eE][+-]?[0-9]+)?      [fh]?   /
77// | / [0-9]+                                    [eE][+-]?[0-9]+        [fh]?   /
78
79// hex_float_literal:
80// | / 0[xX][0-9a-fA-F]*    \.[0-9a-fA-F]+      ([pP][+-]?[0-9]+        [fh]?)? /
81// | / 0[xX][0-9a-fA-F]+    \.[0-9a-fA-F]*      ([pP][+-]?[0-9]+        [fh]?)? /
82// | / 0[xX][0-9a-fA-F]+                         [pP][+-]?[0-9]+        [fh]?   /
83
84// You could visualize the regex below via https://debuggex.com to get a rough idea what `parse` is doing
85// (?:0[xX](?:([0-9a-fA-F]+\.[0-9a-fA-F]*|[0-9a-fA-F]*\.[0-9a-fA-F]+)(?:([pP][+-]?[0-9]+)([fh]?))?|([0-9a-fA-F]+)([pP][+-]?[0-9]+)([fh]?)|([0-9a-fA-F]+)([iu]?))|((?:[0-9]+[eE][+-]?[0-9]+|(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?))([fh]?)|((?:[0-9]|[1-9][0-9]+))([iufh]?))
86
87// Leading signs are handled as unary operators.
88
89fn parse(input: &str) -> (Result<Number, NumberError>, &str) {
90    /// returns `true` and consumes `X` bytes from the given byte buffer
91    /// if the given `X` nr of patterns are found at the start of the buffer
92    macro_rules! consume {
93        ($bytes:ident, $($pattern:pat),*) => {
94            match $bytes {
95                &[$($pattern),*, ref rest @ ..] => { $bytes = rest; true },
96                _ => false,
97            }
98        };
99    }
100
101    /// consumes one byte from the given byte buffer
102    /// if one of the given patterns are found at the start of the buffer
103    /// returning the corresponding expr for the matched pattern
104    macro_rules! consume_map {
105        ($bytes:ident, [$( $($pattern:pat_param),* => $to:expr),* $(,)?]) => {
106            match $bytes {
107                $( &[ $($pattern),*, ref rest @ ..] => { $bytes = rest; Some($to) }, )*
108                _ => None,
109            }
110        };
111    }
112
113    /// consumes all consecutive bytes matched by the `0-9` pattern from the given byte buffer
114    /// returning the number of consumed bytes
115    macro_rules! consume_dec_digits {
116        ($bytes:ident) => {{
117            let start_len = $bytes.len();
118            while let &[b'0'..=b'9', ref rest @ ..] = $bytes {
119                $bytes = rest;
120            }
121            start_len - $bytes.len()
122        }};
123    }
124
125    /// consumes all consecutive bytes matched by the `0-9 | a-f | A-F` pattern from the given byte buffer
126    /// returning the number of consumed bytes
127    macro_rules! consume_hex_digits {
128        ($bytes:ident) => {{
129            let start_len = $bytes.len();
130            while let &[b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F', ref rest @ ..] = $bytes {
131                $bytes = rest;
132            }
133            start_len - $bytes.len()
134        }};
135    }
136
137    macro_rules! consume_float_suffix {
138        ($bytes:ident) => {
139            consume_map!($bytes, [
140                b'h' => FloatKind::F16,
141                b'f' => FloatKind::F32,
142                b'l', b'f' => FloatKind::F64,
143            ])
144        };
145    }
146
147    /// maps the given `&[u8]` (tail of the initial `input: &str`) to a `&str`
148    macro_rules! rest_to_str {
149        ($bytes:ident) => {
150            &input[input.len() - $bytes.len()..]
151        };
152    }
153
154    struct ExtractSubStr<'a>(&'a str);
155
156    impl<'a> ExtractSubStr<'a> {
157        /// given an `input` and a `start` (tail of the `input`)
158        /// creates a new [`ExtractSubStr`](`Self`)
159        fn start(input: &'a str, start: &'a [u8]) -> Self {
160            let start = input.len() - start.len();
161            Self(&input[start..])
162        }
163        /// given an `end` (tail of the initial `input`)
164        /// returns a substring of `input`
165        fn end(&self, end: &'a [u8]) -> &'a str {
166            let end = self.0.len() - end.len();
167            &self.0[..end]
168        }
169    }
170
171    let mut bytes = input.as_bytes();
172
173    let general_extract = ExtractSubStr::start(input, bytes);
174
175    if consume!(bytes, b'0', b'x' | b'X') {
176        let digits_extract = ExtractSubStr::start(input, bytes);
177
178        let consumed = consume_hex_digits!(bytes);
179
180        if consume!(bytes, b'.') {
181            let consumed_after_period = consume_hex_digits!(bytes);
182
183            if consumed + consumed_after_period == 0 {
184                return (Err(NumberError::Invalid), rest_to_str!(bytes));
185            }
186
187            let significand = general_extract.end(bytes);
188
189            if consume!(bytes, b'p' | b'P') {
190                consume!(bytes, b'+' | b'-');
191                let consumed = consume_dec_digits!(bytes);
192
193                if consumed == 0 {
194                    return (Err(NumberError::Invalid), rest_to_str!(bytes));
195                }
196
197                let number = general_extract.end(bytes);
198
199                let kind = consume_float_suffix!(bytes);
200
201                (parse_hex_float(number, kind), rest_to_str!(bytes))
202            } else {
203                (
204                    parse_hex_float_missing_exponent(significand, None),
205                    rest_to_str!(bytes),
206                )
207            }
208        } else {
209            if consumed == 0 {
210                return (Err(NumberError::Invalid), rest_to_str!(bytes));
211            }
212
213            let significand = general_extract.end(bytes);
214            let digits = digits_extract.end(bytes);
215
216            let exp_extract = ExtractSubStr::start(input, bytes);
217
218            if consume!(bytes, b'p' | b'P') {
219                consume!(bytes, b'+' | b'-');
220                let consumed = consume_dec_digits!(bytes);
221
222                if consumed == 0 {
223                    return (Err(NumberError::Invalid), rest_to_str!(bytes));
224                }
225
226                let exponent = exp_extract.end(bytes);
227
228                let kind = consume_float_suffix!(bytes);
229
230                (
231                    parse_hex_float_missing_period(significand, exponent, kind),
232                    rest_to_str!(bytes),
233                )
234            } else {
235                let kind = consume_map!(bytes, [
236                    b'i' => IntKind::I32,
237                    b'u' => IntKind::U32,
238                    b'l', b'i' => IntKind::I64,
239                    b'l', b'u' => IntKind::U64,
240                ]);
241
242                (parse_hex_int(digits, kind), rest_to_str!(bytes))
243            }
244        }
245    } else {
246        let is_first_zero = bytes.first() == Some(&b'0');
247
248        let consumed = consume_dec_digits!(bytes);
249
250        if consume!(bytes, b'.') {
251            let consumed_after_period = consume_dec_digits!(bytes);
252
253            if consumed + consumed_after_period == 0 {
254                return (Err(NumberError::Invalid), rest_to_str!(bytes));
255            }
256
257            if consume!(bytes, b'e' | b'E') {
258                consume!(bytes, b'+' | b'-');
259                let consumed = consume_dec_digits!(bytes);
260
261                if consumed == 0 {
262                    return (Err(NumberError::Invalid), rest_to_str!(bytes));
263                }
264            }
265
266            let number = general_extract.end(bytes);
267
268            let kind = consume_float_suffix!(bytes);
269
270            (parse_dec_float(number, kind), rest_to_str!(bytes))
271        } else {
272            if consumed == 0 {
273                return (Err(NumberError::Invalid), rest_to_str!(bytes));
274            }
275
276            if consume!(bytes, b'e' | b'E') {
277                consume!(bytes, b'+' | b'-');
278                let consumed = consume_dec_digits!(bytes);
279
280                if consumed == 0 {
281                    return (Err(NumberError::Invalid), rest_to_str!(bytes));
282                }
283
284                let number = general_extract.end(bytes);
285
286                let kind = consume_float_suffix!(bytes);
287
288                (parse_dec_float(number, kind), rest_to_str!(bytes))
289            } else {
290                // make sure the multi-digit numbers don't start with zero
291                if consumed > 1 && is_first_zero {
292                    return (Err(NumberError::Invalid), rest_to_str!(bytes));
293                }
294
295                let digits = general_extract.end(bytes);
296
297                let kind = consume_map!(bytes, [
298                    b'i' => Kind::Int(IntKind::I32),
299                    b'u' => Kind::Int(IntKind::U32),
300                    b'l', b'i' => Kind::Int(IntKind::I64),
301                    b'l', b'u' => Kind::Int(IntKind::U64),
302                    b'h' => Kind::Float(FloatKind::F16),
303                    b'f' => Kind::Float(FloatKind::F32),
304                    b'l', b'f' => Kind::Float(FloatKind::F64),
305                ]);
306
307                (parse_dec(digits, kind), rest_to_str!(bytes))
308            }
309        }
310    }
311}
312
313fn parse_hex_float_missing_exponent(
314    // format: 0[xX] ( [0-9a-fA-F]+\.[0-9a-fA-F]* | [0-9a-fA-F]*\.[0-9a-fA-F]+ )
315    significand: &str,
316    kind: Option<FloatKind>,
317) -> Result<Number, NumberError> {
318    let hexf_input = format!("{}{}", significand, "p0");
319    parse_hex_float(&hexf_input, kind)
320}
321
322fn parse_hex_float_missing_period(
323    // format: 0[xX] [0-9a-fA-F]+
324    significand: &str,
325    // format: [pP][+-]?[0-9]+
326    exponent: &str,
327    kind: Option<FloatKind>,
328) -> Result<Number, NumberError> {
329    let hexf_input = format!("{significand}.{exponent}");
330    parse_hex_float(&hexf_input, kind)
331}
332
333fn parse_hex_int(
334    // format: [0-9a-fA-F]+
335    digits: &str,
336    kind: Option<IntKind>,
337) -> Result<Number, NumberError> {
338    parse_int(digits, kind, 16)
339}
340
341fn parse_dec(
342    // format: ( [0-9] | [1-9][0-9]+ )
343    digits: &str,
344    kind: Option<Kind>,
345) -> Result<Number, NumberError> {
346    match kind {
347        None => parse_int(digits, None, 10),
348        Some(Kind::Int(kind)) => parse_int(digits, Some(kind), 10),
349        Some(Kind::Float(kind)) => parse_dec_float(digits, Some(kind)),
350    }
351}
352
353// Float parsing notes
354
355// The following chapters of IEEE 754-2019 are relevant:
356//
357// 7.4 Overflow (largest finite number is exceeded by what would have been
358//     the rounded floating-point result were the exponent range unbounded)
359//
360// 7.5 Underflow (tiny non-zero result is detected;
361//     for decimal formats tininess is detected before rounding when a non-zero result
362//     computed as though both the exponent range and the precision were unbounded
363//     would lie strictly between 2^−126)
364//
365// 7.6 Inexact (rounded result differs from what would have been computed
366//     were both exponent range and precision unbounded)
367
368// The WGSL spec requires us to error:
369//   on overflow for decimal floating point literals
370//   on overflow and inexact for hexadecimal floating point literals
371// (underflow is not mentioned)
372
373// rust std lib float from str handles overflow, underflow, inexact transparently (rounds and will not error)
374
375// Therefore we only check for overflow manually for decimal floating point literals
376
377// input format: 0[xX] ( [0-9a-fA-F]+\.[0-9a-fA-F]* | [0-9a-fA-F]*\.[0-9a-fA-F]+ ) [pP][+-]?[0-9]+
378fn parse_hex_float(input: &str, kind: Option<FloatKind>) -> Result<Number, NumberError> {
379    match kind {
380        None => {
381            let (neg, mant, exp) = parse_hex_float_parts(input.as_bytes())?;
382            let bits = convert_hex_float(neg, mant, exp, F64)?;
383            let num = f64::from_bits(bits);
384
385            Ok(Number::AbstractFloat(num))
386        }
387        // TODO: f16 is not supported
388        Some(FloatKind::F16) => Err(NumberError::NotRepresentable),
389        Some(FloatKind::F32) => {
390            let (neg, mant, exp) = parse_hex_float_parts(input.as_bytes())?;
391            let bits = convert_hex_float(neg, mant, exp, F32)?;
392            let num = f32::from_bits(bits as u32);
393
394            Ok(Number::F32(num))
395        }
396        Some(FloatKind::F64) => {
397            let (neg, mant, exp) = parse_hex_float_parts(input.as_bytes())?;
398            let bits = convert_hex_float(neg, mant, exp, F64)?;
399            let num = f64::from_bits(bits);
400
401            Ok(Number::F64(num))
402        }
403    }
404}
405
406// a config for representing a hexadecimal floating-point
407struct HexFloatFormat {
408    mant_bits: usize,  // number of bits in the mantissa (excluding implicit leading 1)
409    precision: usize,  // total precision in bits including implicit bit
410    bias: i32,         // exponent bias
411    max_exp: i32,      // max exponent before overflow
412    exp_bits: usize,   // number of bits in exponent
413    min_norm_exp: i32, // smallest exponent for normalized numbers
414}
415
416const F32: HexFloatFormat = HexFloatFormat {
417    mant_bits: 23,
418    precision: 24,
419    bias: 127,
420    max_exp: 127,
421    exp_bits: 8,
422    min_norm_exp: -126,
423};
424
425const F64: HexFloatFormat = HexFloatFormat {
426    mant_bits: 52,
427    precision: 53,
428    bias: 1023,
429    max_exp: 1023,
430    exp_bits: 11,
431    min_norm_exp: -1022,
432};
433
434// derived from hexf-parse module: https://github.com/lifthrasiir/hexf (0BSD)
435// parses a hexadecimal floating-point string into its sign, mantissa, and exponent
436// input format: 0[xX] ( [0-9a-fA-F]+\.[0-9a-fA-F]* | [0-9a-fA-F]*\.[0-9a-fA-F]+ ) [pP][+-]?[0-9]+
437fn parse_hex_float_parts(s: &[u8]) -> Result<(bool, u64, i32), NumberError> {
438    let (s, negative) = match s.split_first() {
439        Some((&b'+', s)) => (s, false),
440        Some((&b'-', s)) => (s, true),
441        Some(_) => (s, false),
442        // empty
443        None => return Err(NumberError::Invalid),
444    };
445
446    if !(s.starts_with(b"0x") || s.starts_with(b"0X")) {
447        return Err(NumberError::Invalid);
448    }
449
450    let mut s = &s[2..];
451    let mut acc: u128 = 0;
452    let mut digit_seen = false;
453
454    // integer part: [0-9a-fA-F]+
455    loop {
456        let (rest, digit) = match s.split_first() {
457            Some((&c @ b'0'..=b'9', s)) => (s, c - b'0'),
458            Some((&c @ b'a'..=b'f', s)) => (s, c - b'a' + 10),
459            Some((&c @ b'A'..=b'F', s)) => (s, c - b'A' + 10),
460            _ => break,
461        };
462        s = rest;
463        digit_seen = true;
464        acc = acc.checked_shl(4).ok_or(NumberError::NotRepresentable)? | digit as u128;
465    }
466
467    // fractional part: \.[0-9a-fA-F]+
468    let mut nfracs: i32 = 0;
469    let mut frac_digit_seen = false;
470    if s.starts_with(b".") {
471        s = &s[1..];
472        loop {
473            let (rest, digit) = match s.split_first() {
474                Some((&c @ b'0'..=b'9', s)) => (s, c - b'0'),
475                Some((&c @ b'a'..=b'f', s)) => (s, c - b'a' + 10),
476                Some((&c @ b'A'..=b'F', s)) => (s, c - b'A' + 10),
477                _ => break,
478            };
479            s = rest;
480            frac_digit_seen = true;
481            acc = acc.checked_shl(4).ok_or(NumberError::NotRepresentable)? | digit as u128;
482            nfracs = nfracs.checked_add(1).ok_or(NumberError::NotRepresentable)?;
483        }
484    }
485
486    if !(digit_seen || frac_digit_seen) {
487        return Err(NumberError::Invalid);
488    }
489
490    // exponent marker 'p' or 'P'
491    let s = match s.split_first() {
492        Some((&b'P', s)) | Some((&b'p', s)) => s,
493        _ => return Err(NumberError::Invalid),
494    };
495
496    // exponent sign
497    let (mut s, negative_exponent) = match s.split_first() {
498        Some((&b'+', s)) => (s, false),
499        Some((&b'-', s)) => (s, true),
500        Some(_) => (s, false),
501        None => return Err(NumberError::Invalid),
502    };
503
504    // exponent digits: [0-9]+
505    let mut digit_seen = false;
506    let mut exponent: i32 = 0;
507    loop {
508        let (rest, digit) = match s.split_first() {
509            Some((&c @ b'0'..=b'9', s)) => (s, c - b'0'),
510            None if digit_seen => break,
511            _ => return Err(NumberError::Invalid),
512        };
513        s = rest;
514        digit_seen = true;
515
516        // only update exponent if non‑zero mantissa
517        if acc != 0 {
518            exponent = exponent
519                .checked_mul(10)
520                .and_then(|v| v.checked_add(digit as i32))
521                .ok_or(NumberError::NotRepresentable)?;
522        }
523    }
524
525    if negative_exponent {
526        exponent = -exponent;
527    }
528
529    if acc == 0 {
530        return Ok((negative, 0, 0));
531    }
532
533    // adjust exponent by 4 per fractional digit
534    let exp_adj = nfracs.checked_mul(4).ok_or(NumberError::NotRepresentable)?;
535    let exponent = exponent
536        .checked_sub(exp_adj)
537        .ok_or(NumberError::NotRepresentable)?;
538
539    // remove trailing hex zeros
540    let mut mant = acc;
541    let mut extra_shift = 0i32;
542    while mant > 0 && (mant & 0xF) == 0 {
543        mant >>= 4;
544        extra_shift = extra_shift
545            .checked_add(4)
546            .ok_or(NumberError::NotRepresentable)?;
547    }
548
549    // final mantissa must fit in 64 bits
550    if mant > u64::MAX as u128 {
551        return Err(NumberError::NotRepresentable);
552    }
553
554    let exponent = exponent
555        .checked_add(extra_shift)
556        .ok_or(NumberError::NotRepresentable)?;
557
558    Ok((negative, mant as u64, exponent))
559}
560
561fn convert_hex_float(
562    negative: bool,
563    mant: u64,
564    exp: i32,
565    fmt: HexFloatFormat,
566) -> Result<u64, NumberError> {
567    let sign_shift = fmt.mant_bits + fmt.exp_bits;
568    let sign = (negative as u64) << sign_shift;
569
570    if mant == 0 {
571        return Ok(sign);
572    }
573
574    let k = 63usize - mant.leading_zeros() as usize;
575    let normalexp = exp
576        .checked_add(k as i32)
577        .ok_or(NumberError::NotRepresentable)?;
578
579    if normalexp > fmt.max_exp {
580        return Err(NumberError::NotRepresentable);
581    }
582
583    // shift to align mantissa
584    let shift = k as i32 - ((fmt.precision as i32) - 1);
585    let mut mant_field: u64;
586
587    if normalexp >= fmt.min_norm_exp {
588        // normalized
589        if shift > 0 {
590            if shift >= 64 || (mant & ((1u64 << shift) - 1)) != 0 {
591                return Err(NumberError::NotRepresentable);
592            }
593            mant_field = mant >> shift;
594        } else {
595            mant_field = mant << -shift;
596        }
597
598        mant_field &= (1u64 << fmt.mant_bits) - 1;
599        let expo_field = (normalexp + fmt.bias) as u64;
600
601        Ok(sign | (expo_field << fmt.mant_bits) | mant_field)
602    } else {
603        // subnormal
604        let shift_sub = exp - (fmt.min_norm_exp - ((fmt.precision as i32) - 1));
605        if shift_sub < 0 {
606            let rs = (-shift_sub) as usize;
607            if rs >= 64 || (mant & ((1u64 << rs) - 1)) != 0 {
608                return Err(NumberError::NotRepresentable);
609            }
610            mant_field = mant >> rs;
611        } else {
612            mant_field = mant << shift_sub as u32;
613            if (mant_field >> fmt.mant_bits) != 0 {
614                return Err(NumberError::NotRepresentable);
615            }
616        }
617
618        if mant_field == 0 {
619            return Err(NumberError::NotRepresentable);
620        }
621
622        Ok(sign | (mant_field & ((1u64 << fmt.mant_bits) - 1)))
623    }
624}
625
626// input format: ( [0-9]+\.[0-9]* | [0-9]*\.[0-9]+ ) ([eE][+-]?[0-9]+)?
627//             | [0-9]+ [eE][+-]?[0-9]+
628fn parse_dec_float(input: &str, kind: Option<FloatKind>) -> Result<Number, NumberError> {
629    match kind {
630        None => {
631            let num = input.parse::<f64>().unwrap(); // will never fail
632            num.is_finite()
633                .then_some(Number::AbstractFloat(num))
634                .ok_or(NumberError::NotRepresentable)
635        }
636        Some(FloatKind::F32) => {
637            let num = input.parse::<f32>().unwrap(); // will never fail
638            num.is_finite()
639                .then_some(Number::F32(num))
640                .ok_or(NumberError::NotRepresentable)
641        }
642        Some(FloatKind::F64) => {
643            let num = input.parse::<f64>().unwrap(); // will never fail
644            num.is_finite()
645                .then_some(Number::F64(num))
646                .ok_or(NumberError::NotRepresentable)
647        }
648        Some(FloatKind::F16) => {
649            let num = input.parse::<f16>().unwrap(); // will never fail
650            num.is_finite()
651                .then_some(Number::F16(num))
652                .ok_or(NumberError::NotRepresentable)
653        }
654    }
655}
656
657fn parse_int(input: &str, kind: Option<IntKind>, radix: u32) -> Result<Number, NumberError> {
658    fn map_err(e: core::num::ParseIntError) -> NumberError {
659        match *e.kind() {
660            core::num::IntErrorKind::PosOverflow | core::num::IntErrorKind::NegOverflow => {
661                NumberError::NotRepresentable
662            }
663            _ => unreachable!(),
664        }
665    }
666    match kind {
667        None => match i64::from_str_radix(input, radix) {
668            Ok(num) => Ok(Number::AbstractInt(num)),
669            Err(e) => Err(map_err(e)),
670        },
671        Some(IntKind::I32) => match i32::from_str_radix(input, radix) {
672            Ok(num) => Ok(Number::I32(num)),
673            Err(e) => Err(map_err(e)),
674        },
675        Some(IntKind::U32) => match u32::from_str_radix(input, radix) {
676            Ok(num) => Ok(Number::U32(num)),
677            Err(e) => Err(map_err(e)),
678        },
679        Some(IntKind::I64) => match i64::from_str_radix(input, radix) {
680            Ok(num) => Ok(Number::I64(num)),
681            Err(e) => Err(map_err(e)),
682        },
683        Some(IntKind::U64) => match u64::from_str_radix(input, radix) {
684            Ok(num) => Ok(Number::U64(num)),
685            Err(e) => Err(map_err(e)),
686        },
687    }
688}