use tabnas::{Token, Value};
use crate::parser_abnf::{record_num_err, span_of};
fn object(fields: Vec<(&str, Option<Value>)>) -> Value {
let mut map = indexmap::IndexMap::new();
for (key, value) in fields {
if let Some(value) = value {
map.insert(key.to_string(), value);
}
}
Value::object(map)
}
fn parse_int(text: &str, radix: u32) -> f64 {
let end = text
.char_indices()
.find(|(_, character)| character.to_digit(radix).is_none())
.map_or(text.len(), |(index, _)| index);
let digits = &text[..end];
if digits.is_empty() {
return f64::NAN;
}
let mut exact: u128 = 0;
for character in digits.chars() {
let digit = u128::from(character.to_digit(radix).unwrap_or(0));
match exact
.checked_mul(u128::from(radix))
.and_then(|value| value.checked_add(digit))
{
Some(value) => exact = value,
None => return parse_int_wide(digits, radix),
}
}
exact as f64
}
fn parse_int_wide(digits: &str, radix: u32) -> f64 {
if 10 == radix {
return digits.parse::<f64>().unwrap_or(f64::INFINITY);
}
let significant = digits.trim_start_matches('0').len() as f64;
if 1100.0 < significant * f64::from(radix).log2() {
return f64::INFINITY;
}
let mut decimal: Vec<u8> = vec![0];
for character in digits.chars() {
let mut carry = character.to_digit(radix).unwrap_or(0);
for slot in &mut decimal {
let value = u32::from(*slot) * radix + carry;
*slot = (value % 10) as u8;
carry = value / 10;
}
while 0 < carry {
decimal.push((carry % 10) as u8);
carry /= 10;
}
}
let text: String = decimal
.iter()
.rev()
.map(|digit| char::from(b'0' + digit))
.collect();
text.parse::<f64>().unwrap_or(f64::INFINITY)
}
fn number_to_string(value: f64) -> String {
if value.is_nan() {
return "NaN".to_string();
}
if value.is_infinite() {
return if 0.0 < value { "Infinity" } else { "-Infinity" }.to_string();
}
if 0.0 == value {
return "0".to_string();
}
let magnitude = value.abs();
let (digits, exponent) = (0..17usize)
.map(|places| format!("{magnitude:.places$e}"))
.find(|text| text.parse::<f64>() == Ok(magnitude))
.map(|text| {
let (mantissa, exponent) = text.split_once('e').expect("{:e} emits an exponent");
(
mantissa.chars().filter(|c| '.' != *c).collect::<String>(),
exponent
.parse::<i32>()
.expect("{:e} emits an integer exponent"),
)
})
.expect("17 significant digits round-trip every finite double");
let count = digits.len() as i32;
let point = exponent + 1;
let body = if count <= point && point <= 21 {
format!("{}{}", digits, "0".repeat((point - count) as usize))
} else if 0 < point && point <= 21 {
format!(
"{}.{}",
&digits[..point as usize],
&digits[point as usize..]
)
} else if -6 < point && point <= 0 {
format!("0.{}{}", "0".repeat(-point as usize), digits)
} else {
let places = point - 1;
let head = if 1 == count {
digits.clone()
} else {
format!("{}.{}", &digits[..1], &digits[1..])
};
format!(
"{head}e{}{}",
if places < 0 { '-' } else { '+' },
places.abs()
)
};
if value < 0.0 {
format!("-{body}")
} else {
body
}
}
fn character(code: f64) -> char {
u32::try_from(code as i64)
.ok()
.and_then(char::from_u32)
.unwrap_or('\u{FFFD}')
}
fn push_utf16(units: &mut Vec<u16>, code: f64) {
let code = code.max(0.0) as u32;
match char::from_u32(code) {
Some(character) => {
let mut buffer = [0u16; 2];
units.extend_from_slice(character.encode_utf16(&mut buffer));
}
None => units.push(code as u16),
}
}
pub(crate) fn parse_numeric_value(src: &str, token: Option<&Token>) -> Value {
let span = span_of(token);
let base_char = src.chars().nth(1).unwrap_or('x');
let base = base_char.to_ascii_lowercase();
let radix = match base {
'd' => 10,
'b' => 2,
_ => 16,
};
let body: String = src.chars().skip(2).collect();
let code_point = |text: &str| -> f64 {
let value = parse_int(text, radix);
if !value.is_finite() || value < 0.0 || (0x10FFFF as f64) < value {
record_num_err(format!(
"numeric value '%{base_char}{text}' is {}, which is not a Unicode code point \
(the maximum is %x10FFFF).",
number_to_string(value)
));
return 0.0;
}
value
};
if body.contains('-') {
let mut parts = body.split('-');
let low = code_point(parts.next().unwrap_or_default());
let high = code_point(parts.next().unwrap_or_default());
if low == high {
return object(vec![
("kind", Some(Value::String("term".into()))),
("literal", Some(Value::String(character(low).to_string()))),
("caseSensitive", Some(Value::Bool(true))),
("sp", span),
]);
}
let astral = (0xFFFF as f64) < low || (0xFFFF as f64) < high;
let escape = |value: f64| -> String {
let code = value as u64;
if astral {
format!("\\u{{{code:x}}}")
} else {
format!("\\u{code:04x}")
}
};
return object(vec![
("kind", Some(Value::String("regex".into()))),
(
"pattern",
Some(Value::String(format!("[{}-{}]", escape(low), escape(high)))),
),
(
"flags",
Some(Value::String(if astral { "u" } else { "" }.to_string())),
),
("sp", span),
]);
}
let mut units: Vec<u16> = Vec::new();
for part in body.split('.') {
push_utf16(&mut units, code_point(part));
}
let literal = String::from_utf16_lossy(&units);
object(vec![
("kind", Some(Value::String("term".into()))),
("literal", Some(Value::String(literal))),
("caseSensitive", Some(Value::Bool(true))),
("sp", span),
])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn number_to_string_is_the_specifications_algorithm() {
assert_eq!(number_to_string(1e-6), "0.000001");
assert_eq!(number_to_string(1e-7), "1e-7");
assert_eq!(number_to_string(1e21), "1e+21");
assert_eq!(number_to_string(1e20), "100000000000000000000");
assert_eq!(number_to_string(1e-21), "1e-21");
assert_eq!(number_to_string(0.5), "0.5");
assert_eq!(number_to_string(1.5), "1.5");
assert_eq!(number_to_string(0.1), "0.1");
assert_eq!(number_to_string(123.456), "123.456");
assert_eq!(number_to_string(-0.0), "0");
assert_eq!(number_to_string(0.0), "0");
assert_eq!(number_to_string(-1.5), "-1.5");
assert_eq!(number_to_string(5e-324), "5e-324");
assert_eq!(number_to_string(f64::MAX), "1.7976931348623157e+308");
assert_eq!(number_to_string(f64::INFINITY), "Infinity");
assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
assert_eq!(number_to_string(f64::NAN), "NaN");
assert_eq!(number_to_string(9007199254740992.0), "9007199254740992");
assert_eq!(number_to_string(1e23), "1e+23");
assert_eq!(number_to_string(1114112.0), "1114112");
}
#[test]
fn parse_int_rounds_once() {
assert_eq!(parse_int("12345678901234567890", 10), 1.2345678901234567e19);
assert_eq!(parse_int("9007199254740993", 10), 9007199254740992.0);
assert_eq!(parse_int("99999999999999999999999", 10), 1e23);
assert_eq!(parse_int("111", 2), 7.0);
assert_eq!(parse_int("ff", 16), 255.0);
assert_eq!(
parse_int("5A", 10),
5.0,
"truncates at the first invalid digit"
);
assert!(parse_int("", 10).is_nan());
assert!(parse_int("zz", 10).is_nan());
assert_eq!(parse_int(&"9".repeat(400), 10), f64::INFINITY);
assert_eq!(parse_int(&"f".repeat(400), 16), f64::INFINITY);
}
}