use std::borrow::Cow;
use std::sync::LazyLock;
use proptest::prelude::*;
use regex::Regex;
use crate::convert::{self, ConvertError, Width, java};
use crate::number::{Number, NumberReading};
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
use crate::record::{Json, Kind, Record, Typed, Walk};
use crate::shared_tests::corpus::for_each_record_of;
const COLUMNS: [&str; 10] = [
"Exact",
"Cel",
"Exact, Int hint",
"Exact, Float hint",
"parse_int",
"java::parse_int",
"parse_float",
"java::parse_float",
"cel int()",
"cel double()",
];
static WHOLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[+-]?[0-9]+$").unwrap());
static DECIMAL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$").unwrap());
static SPECIAL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)^[+-]?(inf|infinity|nan)$").unwrap());
static JSON_NUMBER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$").unwrap());
static CEL_INT: LazyLock<cel::Program> = LazyLock::new(|| cel::Program::compile("int(s)").unwrap());
static CEL_DOUBLE: LazyLock<cel::Program> =
LazyLock::new(|| cel::Program::compile("double(s)").unwrap());
fn show_number(number: Option<Number>) -> String {
match number {
None => "None".into(),
Some(Number::Int(n)) => format!("Int({n})"),
Some(Number::UInt(n)) => format!("UInt({n})"),
Some(Number::Float(n)) => format!("Float({n:?})"),
}
}
fn show_int(result: Result<i64, ConvertError>) -> String {
match result {
Ok(n) => format!("Ok({n})"),
Err(e) => format!("{e:?}"),
}
}
fn show_float(result: Result<f64, ConvertError>) -> String {
match result {
Ok(n) => format!("Ok({n:?})"),
Err(e) => format!("{e:?}"),
}
}
fn show_cel(value: Option<cel::Value>) -> String {
match value {
Some(cel::Value::Int(n)) => format!("Ok({n})"),
Some(cel::Value::Float(n)) => format!("Ok({n:?})"),
Some(other) => panic!("cel gave {other:?}"),
None => "error".into(),
}
}
fn run_cel(program: &cel::Program, text: &str) -> Option<cel::Value> {
let mut ctx = cel::Context::default();
ctx.add_variable_from_value("s", cel::Value::String(text.to_owned().into()));
program.execute(&ctx).ok()
}
fn cells(text: &str) -> [String; 10] {
let hinted = |hint| FieldValue::borrowed(text.as_bytes(), hint).number();
[
show_number(NumberReading::Exact.read(text)),
show_number(NumberReading::Cel.read(text)),
show_number(hinted(Hint::Int)),
show_number(hinted(Hint::Float)),
show_int(convert::parse_int(text)),
show_int(java::parse_int(text)),
show_float(convert::parse_float(text, Width::Double)),
show_float(java::parse_float(text, Width::Double)),
show_cel(run_cel(&CEL_INT, text)),
show_cel(run_cel(&CEL_DOUBLE, text)),
]
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Wide {
Int(i64),
UInt(u64),
Past,
}
fn wide(text: &str) -> Wide {
let (negative, digits) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
let digits = digits.trim_start_matches('0');
if digits.len() > 38 {
return Wide::Past;
}
let magnitude: i128 = if digits.is_empty() {
0
} else {
digits.parse().unwrap()
};
let value = if negative { -magnitude } else { magnitude };
i64::try_from(value)
.map(Wide::Int)
.or_else(|_| u64::try_from(value).map(Wide::UInt))
.unwrap_or(Wide::Past)
}
fn finite_float(text: &str) -> Option<Number> {
text.parse::<f64>()
.ok()
.filter(|n| n.is_finite())
.map(Number::Float)
}
fn whole_number(text: &str) -> Option<Number> {
match wide(text) {
Wide::Int(n) => Some(Number::Int(n)),
Wide::UInt(n) => Some(Number::UInt(n)),
Wide::Past => None,
}
}
fn spelled_float(text: &str) -> bool {
text.contains(['.', 'e', 'E'])
}
fn model_exact(text: &str) -> Option<Number> {
if spelled_float(text) {
DECIMAL.is_match(text).then(|| finite_float(text)).flatten()
} else if WHOLE.is_match(text) {
whole_number(text)
} else {
None
}
}
fn model_cel(text: &str) -> Option<Number> {
if !spelled_float(text) && WHOLE.is_match(text) {
match wide(text) {
Wide::Past => return finite_float(text),
Wide::Int(0) if text.starts_with('-') => return Some(Number::Float(-0.0)),
_ => {}
}
}
model_exact(text)
}
fn model_exact_int(text: &str) -> Option<Number> {
WHOLE.is_match(text).then(|| whole_number(text)).flatten()
}
fn model_exact_float(text: &str) -> Option<Number> {
DECIMAL.is_match(text).then(|| finite_float(text)).flatten()
}
fn hex_value(hex: &str, negative: bool) -> Result<i64, ConvertError> {
if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(ConvertError::NotInteger);
}
let magnitude = u128::from_str_radix(hex, 16).map_err(|_| ConvertError::OutOfRange)?;
let value = i128::try_from(magnitude).map_err(|_| ConvertError::OutOfRange)?;
i64::try_from(if negative { -value } else { value }).map_err(|_| ConvertError::OutOfRange)
}
fn decimal_int(text: &str) -> Result<i64, ConvertError> {
if !WHOLE.is_match(text) {
return Err(ConvertError::NotInteger);
}
match wide(text) {
Wide::Int(n) => Ok(n),
_ => Err(ConvertError::OutOfRange),
}
}
fn model_parse_int(text: &str) -> Result<i64, ConvertError> {
let text = text.trim();
text.strip_prefix("0x")
.map_or_else(|| decimal_int(text), |hex| hex_value(hex, false))
}
fn model_java_int(text: &str) -> Result<i64, ConvertError> {
match (text.strip_prefix("0x"), text.strip_prefix("-0x")) {
(Some(hex), _) => hex_value(hex, false),
(_, Some(hex)) => hex_value(hex, true),
_ => decimal_int(text),
}
}
fn float_of(text: &str) -> Result<f64, ConvertError> {
if DECIMAL.is_match(text) || SPECIAL.is_match(text) {
Ok(text.parse::<f64>().unwrap())
} else {
Err(ConvertError::NotFloat)
}
}
fn model_parse_float(text: &str) -> Result<f64, ConvertError> {
float_of(text.trim())
}
fn model_java_float(text: &str) -> Result<f64, ConvertError> {
let text = text.trim_matches(|c: char| c <= ' ');
let body = text.strip_prefix(['+', '-']).unwrap_or(text);
match body {
"NaN" => Ok(f64::NAN),
"Infinity" if text.starts_with('-') => Ok(f64::NEG_INFINITY),
"Infinity" => Ok(f64::INFINITY),
_ if body.starts_with(|c: char| c.is_ascii_alphabetic()) => Err(ConvertError::NotFloat),
_ => {
let number = text.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(text);
if DECIMAL.is_match(number) {
Ok(number.parse::<f64>().unwrap())
} else {
Err(ConvertError::NotFloat)
}
}
}
}
fn model_cel_int(text: &str) -> Option<cel::Value> {
(WHOLE.is_match(text))
.then(|| match wide(text) {
Wide::Int(n) => Some(cel::Value::Int(n)),
_ => None,
})
.flatten()
}
fn model_cel_double(text: &str) -> Option<cel::Value> {
float_of(text).ok().map(cel::Value::Float)
}
fn model(text: &str) -> [String; 10] {
[
show_number(model_exact(text)),
show_number(model_cel(text)),
show_number(model_exact_int(text)),
show_number(model_exact_float(text)),
show_int(model_parse_int(text)),
show_int(model_java_int(text)),
show_float(model_parse_float(text)),
show_float(model_java_float(text)),
show_cel(model_cel_int(text)),
show_cel(model_cel_double(text)),
]
}
fn json_to_cel(number: &serde_json::Number) -> cel::Value {
number.as_i64().map_or_else(
|| {
number.as_u64().map_or_else(
|| cel::Value::Float(number.as_f64().unwrap_or(0.0)),
cel::Value::UInt,
)
},
cel::Value::Int,
)
}
fn as_cel(number: Number) -> cel::Value {
match number {
Number::Int(n) => cel::Value::Int(n),
Number::UInt(n) => cel::Value::UInt(n),
Number::Float(n) => cel::Value::Float(n),
}
}
fn near(a: f64, b: f64) -> bool {
a.is_sign_negative() == b.is_sign_negative()
&& (a.to_bits() == b.to_bits()
|| (a - b).abs() <= 8.0 * f64::EPSILON * a.abs().max(b.abs()))
}
fn same_cel(a: &cel::Value, b: &cel::Value) -> bool {
match (a, b) {
(cel::Value::Int(a), cel::Value::Int(b)) => a == b,
(cel::Value::UInt(a), cel::Value::UInt(b)) => a == b,
(cel::Value::Float(a), cel::Value::Float(b)) => near(*a, *b),
_ => false,
}
}
fn typed_of(number: Option<Number>, text: &str) -> Typed<'_> {
match number {
Some(Number::Int(n)) => Typed::Int(n),
Some(Number::UInt(n)) => Typed::Uint(n),
Some(Number::Float(n)) => Typed::Double(n),
None => Typed::Str(Cow::Borrowed(text)),
}
}
fn field_readings(text: &str, hint: Hint) -> [String; 2] {
let mut fields = Fields::new();
fields.field("n", FieldValue::borrowed(text.as_bytes(), hint));
let record = &fields;
let at = record.find(&["n"]).unwrap();
[
format!("{:?}", record.typed(at)),
format!("{:?}", record.typed_exact(at)),
]
}
fn object_text(text: &str) -> String {
let mut fields = Fields::new();
fields.field("a.b", FieldValue::borrowed(text.as_bytes(), Hint::Int));
let record = &fields;
let at = record.find(&["a"]).unwrap();
record.text(at).unwrap().into_owned()
}
fn model_whole_json(text: &str) -> String {
let digits = text.trim_start_matches(['+', '-']).trim_start_matches('0');
match wide(text) {
Wide::Past if digits.len() > 38 => {
format!("{}{digits}", if text.starts_with('-') { "-" } else { "" })
}
Wide::Past => {
let magnitude: i128 = digits.parse().unwrap();
(if text.starts_with('-') {
-magnitude
} else {
magnitude
})
.to_string()
}
Wide::Int(n) => n.to_string(),
Wide::UInt(n) => n.to_string(),
}
}
fn json_readings(text: &str) -> [String; 2] {
let bytes = format!(r#"{{"n":{text}}}"#);
let record = Json::new(bytes.as_bytes());
let at = record.find(&["n"]).unwrap();
assert_eq!(record.text(at).as_deref(), Ok(text));
[
format!("{:?}", record.typed(at)),
format!("{:?}", record.typed_exact(at)),
]
}
fn check(text: &str) {
let got = cells(text);
let want = model(text);
for ((column, got), want) in COLUMNS.iter().zip(&got).zip(&want) {
assert_eq!(got, want, "{column} of {text:?}");
}
let cel = model_cel(text);
let exact_int = model_exact_int(text);
let exact_float = model_exact_float(text);
let ok = |number: Option<Number>| format!("Ok({:?})", typed_of(number, text));
for (hint, exact) in [(Hint::Int, exact_int), (Hint::Float, exact_float)] {
assert_eq!(
field_readings(text, hint),
[ok(cel), ok(exact)],
"a {hint:?} field of {text:?}"
);
}
if WHOLE.is_match(text) {
assert_eq!(
object_text(text),
format!(r#"{{"b":{}}}"#, model_whole_json(text)),
"the object text of an Int field {text:?}"
);
}
if JSON_NUMBER.is_match(text) {
let typed = if cel.is_some() {
ok(cel)
} else {
"Err(Malformed)".to_owned()
};
assert_eq!(
json_readings(text),
[typed, ok(model_exact(text))],
"a JSON number {text:?}"
);
match serde_json::from_str::<serde_json::Number>(text) {
Ok(number) => {
let oracle = json_to_cel(&number);
let ours = cel.map(as_cel);
assert!(
ours.as_ref().is_some_and(|ours| same_cel(ours, &oracle)),
"{text:?}: cel is given {oracle:?}, Cel reads {ours:?}"
);
}
Err(_) => assert_eq!(cel, None, "{text:?} is out of range for the JSON reader"),
}
}
}
fn unquote(cell: &str) -> &str {
cell.trim().trim_matches('`')
}
fn row_text(cell: &str) -> String {
let quoted = unquote(cell);
let inner = quoted
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or_else(|| panic!("a row's text is quoted: {cell}"));
let mut out = String::new();
let mut chars = inner.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('u') => {
let hex: String = chars.by_ref().skip(1).take_while(|&c| c != '}').collect();
out.push(char::from_u32(u32::from_str_radix(&hex, 16).unwrap()).unwrap());
}
other => panic!("unknown escape {other:?} in {cell}"),
}
}
out
}
#[test]
fn the_documented_table_is_what_each_call_gives() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/convert.md");
let Ok(doc) = std::fs::read_to_string(&path) else {
eprintln!(
"{} isn't here, so there is no table to hold",
path.display()
);
return;
};
let mut header = false;
let mut rows = 0;
for line in doc.lines().filter(|l| l.starts_with('|')) {
let cells: Vec<&str> = line
.trim()
.trim_matches('|')
.split('|')
.map(str::trim)
.collect();
if cells.len() == COLUMNS.len() + 1 && cells[0] == "Text" {
assert_eq!(&cells[1..], &COLUMNS, "the table's columns");
header = true;
} else if cells.len() == COLUMNS.len() + 1 && cells[0].starts_with("`\"") {
let text = row_text(cells[0]);
let want: Vec<&str> = cells[1..].iter().map(|c| unquote(c)).collect();
assert_eq!(cells_of(&text), want, "the row for {text:?}");
check(&text);
rows += 1;
}
}
assert!(header, "docs/convert.md has no readings table");
assert!(rows >= 40, "only {rows} rows in the table");
}
fn cells_of(text: &str) -> Vec<String> {
cells(text).to_vec()
}
fn edges() -> impl Strategy<Value = String> {
(
-3_i128..=3,
prop::sample::select(vec![
i128::from(i64::MIN),
i128::from(i64::MAX),
i128::from(u64::MAX),
0,
]),
)
.prop_map(|(step, edge)| (edge + step).to_string())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4_000))]
#[test]
fn whole_text_is_held_to_the_table(
text in prop_oneof![
"[+-]?[0-9]{1,24}",
"[+-]?0{0,3}[0-9]{1,20}",
edges(),
],
) {
check(&text);
}
#[test]
fn decimal_text_is_held_to_the_table(
text in prop_oneof![
"[+-]?[0-9]{0,6}\\.?[0-9]{0,4}([eE][-+]?[0-9]{0,3})?",
"-?(0|[1-9][0-9]{0,24})(\\.[0-9]{1,12})?([eE][-+]?[0-9]{1,3})?",
"[+-]?[0-9]{1,5}(\\.[0-9]{0,4})?[fFdD]?",
],
) {
check(&text);
}
#[test]
fn other_text_is_held_to_the_table(
text in prop_oneof![
"[ \\t\\n]{0,2}[+-]?[0-9]{1,6}[ \\t\\n]{0,2}",
"[+-]?0[xX][0-9a-fA-F]{0,18}",
"(?i)[+-]?(inf|infinity|nan)[fd]?",
"[-+.eE0-9 xXa-fINnTy_,]{0,16}",
],
) {
check(&text);
}
}
fn corpus_text() -> (Vec<String>, Vec<String>) {
use std::collections::BTreeSet;
let mut tokens = BTreeSet::new();
let mut json = BTreeSet::new();
for_each_record_of(&CORPUS_TAGS, |r| {
if let Ok(text) = std::str::from_utf8(r.bytes) {
let word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-' | '_');
for token in text.split(|c: char| !word(c)) {
if token.len() <= 40 && token.bytes().any(|b| b.is_ascii_digit()) {
tokens.insert(token.to_owned());
}
}
}
let record = Json::new(r.bytes);
let _ = record.walk(|node| {
if node.kind == Kind::Number
&& let Ok(text) = record.text(node.at)
{
json.insert(text.into_owned());
}
});
});
(tokens.into_iter().collect(), json.into_iter().collect())
}
const CORPUS_TAGS: [&str; 22] = [
"json",
"ndjson",
"json-suite",
"syslog",
"cef",
"leef",
"mixed",
"access",
"kv",
"csv",
"tsv",
"w3c",
"prometheus",
"cloud-vpc",
"cloud-alb",
"cloud-s3",
"text",
"naughty",
"cri",
"ini",
"http",
"time",
];
#[test]
fn the_text_of_real_records_is_held_to_the_table() {
let (tokens, json) = corpus_text();
eprintln!("{} tokens, {} json numbers", tokens.len(), json.len());
assert!(tokens.len() > 1_000, "{} tokens", tokens.len());
assert!(json.len() > 100, "{} JSON numbers", json.len());
let past = tokens
.iter()
.filter(|t| WHOLE.is_match(t) && wide(t) == Wide::Past)
.count();
assert!(past > 0, "the corpus has no whole number past u64");
for text in tokens.iter().chain(&json) {
check(text);
}
}