use std::borrow::Cow;
use std::num::IntErrorKind;
use relate_parser::lexer::CommentSkip;
use crate::eval::numeric::float_to_i64;
#[derive(Debug, PartialEq, Eq)]
pub(super) enum IntegerString {
InRange(i64),
OutOfRange,
NotANumber,
}
pub(super) fn integer_from_string(s: &str) -> IntegerString {
let trimmed = trim_java(s);
if let Ok(i) = trimmed.parse::<i64>() {
return IntegerString::InRange(i);
}
match parse_decimal_integer(trimmed) {
Some(DecimalInteger::InRange(i)) => IntegerString::InRange(i),
Some(DecimalInteger::OutOfRange) => IntegerString::OutOfRange,
None => match cypher25_number_literal(trimmed) {
Some(NumberLiteral::Int(i)) => IntegerString::InRange(i),
Some(NumberLiteral::Double(d)) => IntegerString::InRange(float_to_i64(d)),
None => IntegerString::NotANumber,
},
}
}
pub(super) fn float_from_string(s: &str) -> Option<f64> {
if let Some(d) = parse_double_java(s) {
return Some(d);
}
match cypher25_number_literal(s) {
Some(NumberLiteral::Int(i)) => Some(i as f64),
Some(NumberLiteral::Double(d)) => Some(d),
None => None,
}
}
pub(super) fn trim_java(s: &str) -> &str {
s.trim_matches(|c: char| c <= '\u{0020}')
}
fn trim_cypher25(s: &str) -> &str {
s.trim_matches(|c: char| c.is_whitespace() || ('\u{001C}'..='\u{001F}').contains(&c))
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum DecimalInteger {
InRange(i64),
OutOfRange,
}
pub(super) fn parse_decimal_integer(s: &str) -> Option<DecimalInteger> {
let (negative, unsigned) = match s.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, s.strip_prefix('+').unwrap_or(s)),
};
let (mantissa, exponent) = match unsigned.split_once(['e', 'E']) {
Some((mantissa, exponent)) => (mantissa, parse_decimal_exponent(exponent)?),
None => (unsigned, 0),
};
if i32::try_from(exponent).is_err() {
return None;
}
let (int_digits, frac_digits) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let all_digits = |d: &str| d.bytes().all(|b| b.is_ascii_digit());
if (int_digits.is_empty() && frac_digits.is_empty())
|| !all_digits(int_digits)
|| !all_digits(frac_digits)
{
return None;
}
let digits: Vec<u8> = int_digits
.bytes()
.chain(frac_digits.bytes())
.map(|b| b - b'0')
.collect();
let leading_zeros = digits.iter().take_while(|&&d| d == 0).count();
let significant = &digits[leading_zeros..];
if significant.is_empty() {
return Some(DecimalInteger::InRange(0));
}
let len = |n: usize| n as i128;
let int_len = len(int_digits.len()) + i128::from(exponent) - len(leading_zeros);
if int_len <= 0 {
return Some(DecimalInteger::InRange(0));
}
let Some(int_len) = usize::try_from(int_len).ok().filter(|&n| n <= 19) else {
return Some(DecimalInteger::OutOfRange);
};
let magnitude = significant
.iter()
.chain(std::iter::repeat(&0))
.take(int_len)
.fold(0u64, |acc, &d| acc * 10 + u64::from(d));
let has_fraction = significant
.get(int_len..)
.is_some_and(|rest| rest.iter().any(|&d| d != 0));
let truncated = if negative {
0i64.checked_sub_unsigned(magnitude)
} else {
i64::try_from(magnitude).ok()
};
Some(match truncated {
Some(i) if !(has_fraction && (i == i64::MAX || i == i64::MIN)) => {
DecimalInteger::InRange(i)
}
_ => DecimalInteger::OutOfRange,
})
}
fn parse_decimal_exponent(s: &str) -> Option<i64> {
let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
if !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
match s.parse::<i64>() {
Ok(e) => Some(e),
Err(e) => match e.kind() {
IntErrorKind::PosOverflow => Some(i64::MAX),
IntErrorKind::NegOverflow => Some(i64::MIN),
_ => None,
},
}
}
fn parse_double_java(s: &str) -> Option<f64> {
let s = trim_java(s);
if s.is_empty() {
return None;
}
let (negative, body) = match s.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, s.strip_prefix('+').unwrap_or(s)),
};
if body == "NaN" {
return Some(f64::NAN);
}
if body == "Infinity" {
return Some(if negative {
f64::NEG_INFINITY
} else {
f64::INFINITY
});
}
if body.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
let value = if let Some(hex) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
parse_hex_float(hex)?
} else {
let core = body.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(body);
core.parse::<f64>().ok()?
};
Some(if negative { -value } else { value })
}
fn parse_hex_float(s: &str) -> Option<f64> {
let (significand, rest) = s.split_once(['p', 'P'])?;
let rest = rest.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(rest);
let exponent = parse_decimal_exponent(rest)?;
let (int_part, frac_part) = significand.split_once('.').unwrap_or((significand, ""));
let is_hex = |b: u8| b.is_ascii_hexdigit();
if (int_part.is_empty() && frac_part.is_empty())
|| !int_part.bytes().all(is_hex)
|| !frac_part.bytes().all(is_hex)
{
return None;
}
let mut value = 0.0f64;
let mut adjust = 0i64;
for b in int_part.bytes().chain(frac_part.bytes()) {
let digit = match b {
b'0'..=b'9' => b - b'0',
b'a'..=b'f' => b - b'a' + 10,
_ => b - b'A' + 10,
};
value = value * 16.0 + f64::from(digit);
if value >= 281_474_976_710_656.0 {
value *= 0.0625;
adjust += 4;
}
}
if value == 0.0 {
return Some(0.0);
}
let exp = exponent
.saturating_add(adjust)
.saturating_sub(4 * frac_part.len() as i64)
.clamp(-2200, 2200);
Some(value * 2f64.powi(exp as i32))
}
#[derive(Debug, PartialEq)]
enum NumberLiteral {
Int(i64),
Double(f64),
}
fn strip_cypher_comments(s: &str) -> Option<Cow<'_, str>> {
if !s.contains("//") && !s.contains("/*") {
return Some(Cow::Borrowed(s));
}
let bytes = s.as_bytes();
let mut out = String::with_capacity(s.len());
let mut pos = 0;
while pos < bytes.len() {
match relate_parser::lexer::skip_comment(bytes, pos) {
CommentSkip::Skipped(end) => {
out.push(' ');
pos = end;
}
CommentSkip::NotComment => {
let ch = s[pos..]
.chars()
.next()
.expect("pos stays on a character boundary");
out.push(ch);
pos += ch.len_utf8();
}
CommentSkip::Unterminated => return None,
}
}
Some(Cow::Owned(out))
}
fn cypher25_number_literal(s: &str) -> Option<NumberLiteral> {
let stripped = strip_cypher_comments(s)?;
let s = trim_cypher25(&stripped);
let (negative, body) = match s.strip_prefix('-') {
Some(rest) => (true, trim_cypher25(rest)),
None => (false, s),
};
if body.is_empty() {
return None;
}
if let Some(hex) = body.strip_prefix("0x") {
return parse_radix_literal(negative, hex, 16).map(NumberLiteral::Int);
}
if let Some(oct) = body.strip_prefix("0o") {
return parse_radix_literal(negative, oct, 8).map(NumberLiteral::Int);
}
cypher25_decimal(negative, body)
}
fn cypher25_decimal(negative: bool, body: &str) -> Option<NumberLiteral> {
let bytes = body.as_bytes();
let len = bytes.len();
let run = |mut i: usize| -> usize {
while i < len {
if bytes[i].is_ascii_digit() {
i += 1;
} else if bytes[i] == b'_' && i + 1 < len && bytes[i + 1].is_ascii_digit() {
i += 2;
} else {
break;
}
}
i
};
let int_end = run(0);
let has_int = int_end > 0;
let mut i = int_end;
let mut has_dot = false;
let mut has_frac = false;
if i < len && bytes[i] == b'.' {
has_dot = true;
i += 1;
let frac_end = run(i);
has_frac = frac_end > i;
i = frac_end;
}
let mut has_exp = false;
if i < len && matches!(bytes[i], b'e' | b'E') {
let mut j = i + 1;
if j < len && matches!(bytes[j], b'+' | b'-') {
j += 1;
}
let exp_end = run(j);
if exp_end > j {
has_exp = true;
i = exp_end;
}
}
let suffix = &body[i..];
let is_double = (has_dot && has_frac) || (has_int && !has_dot && has_exp);
if is_double {
let d = if body.contains('_') {
if !suffix.is_empty() {
return None;
}
body.replace('_', "").parse::<f64>().ok()?
} else {
let core = suffix
.strip_prefix(['f', 'F', 'd', 'D'])
.filter(|rest| rest.is_empty())
.map_or(body, |_| &body[..i]);
core.parse::<f64>().ok()?
};
return Some(NumberLiteral::Double(if negative { -d } else { d }));
}
let joined = join_underscored(body, 10)?;
let signed = if negative {
format!("-{joined}")
} else {
joined
};
signed.parse::<i64>().ok().map(NumberLiteral::Int)
}
fn join_underscored(digits: &str, radix: u32) -> Option<String> {
let ok = |t: &str| !t.is_empty() && t.bytes().all(|b| (b as char).is_digit(radix));
let parts: Vec<&str> = digits.split('_').collect();
if parts.iter().all(|p| ok(p)) {
Some(parts.concat())
} else {
None
}
}
fn parse_radix_literal(negative: bool, digits: &str, radix: u32) -> Option<i64> {
let digits = digits.strip_prefix('_').unwrap_or(digits);
let joined = join_underscored(digits, radix)?;
let magnitude = u128::from_str_radix(&joined, radix).ok()?;
let limit = if negative {
(i64::MAX as u128) + 1
} else {
i64::MAX as u128
};
if magnitude > limit {
return None;
}
let value = magnitude as i128;
Some(if negative { -value } else { value } as i64)
}