use crate::value::Value;
use crate::{Error, Result};
pub const ERROR_PREFIX: &str = "ERROR";
pub fn is_error_expect(expected: &str) -> bool {
expected == ERROR_PREFIX || expected.starts_with(&format!("{ERROR_PREFIX}:"))
}
pub fn error_code(expected: &str) -> Result<String> {
error_expect(expected).map(|expectation| expectation.code)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorExpect {
pub code: String,
pub row: Option<usize>,
pub col: Option<usize>,
}
pub fn error_expect(expected: &str) -> Result<ErrorExpect> {
if !is_error_expect(expected) {
return Err(Error(format!("not an error expectation: {expected:?}")));
}
let code = if expected == ERROR_PREFIX {
""
} else {
&expected[ERROR_PREFIX.len() + 1..]
};
let Some((code, row_text, col_text)) = position_suffix(code) else {
return Ok(ErrorExpect {
code: code.to_string(),
row: None,
col: None,
});
};
let row = row_text.parse::<usize>().map_err(|error| {
Error(format!(
"invalid row in error expectation {expected:?}: {error}"
))
})?;
let col = col_text.parse::<usize>().map_err(|error| {
Error(format!(
"invalid column in error expectation {expected:?}: {error}"
))
})?;
if row < 1 || col < 1 {
return Err(Error(format!(
"position in an error expectation is 1-based, so 0 is not a position: {expected:?}"
)));
}
Ok(ErrorExpect {
code: code.to_string(),
row: Some(row),
col: Some(col),
})
}
fn position_suffix(code: &str) -> Option<(&str, &str, &str)> {
let digits_end = code.len();
let col_start = code
.rfind(|c: char| !c.is_ascii_digit())
.map_or(0, |i| i + 1);
if col_start == digits_end || !code[..col_start].ends_with(':') {
return None;
}
let colon = col_start - 1;
let row_start = code[..colon]
.rfind(|c: char| !c.is_ascii_digit())
.map_or(0, |i| i + 1);
if row_start == colon || !code[..row_start].ends_with('@') {
return None;
}
let at = row_start - 1;
Some((&code[..at], &code[row_start..colon], &code[col_start..]))
}
pub fn parse_expect(expected: &str) -> Result<Value> {
if expected.is_empty() {
return Ok(Value::Undefined);
}
Value::parse_json(expected)
.map_err(|reason| Error(format!("invalid expected JSON: {expected:?}: {reason}")))
}
pub fn lone_surrogate_at(cell: &str) -> Option<usize> {
let bytes = cell.as_bytes();
let hex4 = |at: usize| -> Option<u32> {
let text = bytes.get(at..at + 4)?;
let text = std::str::from_utf8(text).ok()?;
if !text.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(text, 16).ok()
};
let code_points_before = |at: usize| cell[..at].chars().count();
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' {
i += 1;
continue;
}
let mut j = i;
while j < bytes.len() && bytes[j] == b'\\' {
j += 1;
}
if (j - i) % 2 == 0 {
i = j;
continue;
}
let start = j - 1;
if j >= bytes.len() || bytes[j] != b'u' {
i = j + 1;
continue;
}
let Some(unit) = hex4(j + 1) else {
i = j + 1;
continue;
};
if (0xD800..=0xDBFF).contains(&unit) {
let k = j + 5;
if bytes.get(k) == Some(&b'\\') && bytes.get(k + 1) == Some(&b'u') {
if let Some(low) = hex4(k + 2) {
if (0xDC00..=0xDFFF).contains(&low) {
i = k + 6;
continue;
}
}
}
return Some(code_points_before(start));
}
if (0xDC00..=0xDFFF).contains(&unit) {
return Some(code_points_before(start));
}
i = j + 5;
}
None
}
pub fn lone_surrogate_message(cell: &str, at: usize) -> String {
format!(
"expected cell holds an unpaired surrogate escape at code point {at}: {cell:?}\n \
A shared expected column CANNOT express this: JSON.parse preserves a lone surrogate\n \
(a JavaScript string is UTF-16) and Go's encoding/json replaces it with U+FFFD\n \
(a Go string is UTF-8). The two runtimes would be asked different questions and both\n \
would pass. This is a recorded, permanent divergence - see DIVERGENCE.md.\n \
Put the case in a per-runtime register column, where each decoding is written out,\n \
or in each port's own suite with opposite assertions. A surrogate PAIR is fine here."
)
}
pub fn equal_value(got: &Value, expected: &Value) -> bool {
got == expected
}
pub fn equal_value_with(got: &Value, expected: &Value, normalize: &dyn Fn(Value) -> Value) -> bool {
let got = normalize(got.clone());
let expected = normalize(expected.clone());
match (&got, &expected) {
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len()
&& a.iter()
.zip(b)
.all(|(x, y)| equal_value_with(x, y, normalize))
}
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter().all(|(key, value)| {
b.iter()
.find(|(other_key, _)| other_key == key)
.is_some_and(|(_, other)| equal_value_with(value, other, normalize))
})
}
_ => got == expected,
}
}
pub fn format_value(value: &Value) -> String {
value.to_string()
}