use serde_json::Value;
use std::path::Path;
#[derive(Default, Debug)]
struct RelationOptions {
normalize_newlines: bool,
trim_whitespace: bool,
ignore_ansi: bool,
ignore_case: bool,
stop_on_first_mismatch: bool,
required_degree: Option<f64>,
}
fn strip_ansi(s: &str) -> String {
let re = regex::Regex::new(r"\x1B\[[0-9;]*m").unwrap_or_else(|_| regex::Regex::new(r"").unwrap());
re.replace_all(s, "").into_owned()
}
fn normalize_output(s: &str, opts: &RelationOptions) -> String {
let mut out = s.to_string();
if opts.normalize_newlines {
out = out.replace("\r\n", "\n").replace('\r', "\n");
}
if opts.trim_whitespace {
out = out.trim().to_string();
}
if opts.ignore_ansi {
out = strip_ansi(&out);
}
if opts.ignore_case {
out = out.to_lowercase();
}
out
}
fn find_divergence(a: &str, b: &str) -> Option<(usize, char, char)> {
let a_chars: Vec<char> = a.chars().collect();
let b_chars: Vec<char> = b.chars().collect();
for i in 0..a_chars.len().min(b_chars.len()) {
if a_chars[i] != b_chars[i] {
return Some((i, a_chars[i], b_chars[i]));
}
}
if a_chars.len() != b_chars.len() {
let idx = a_chars.len().max(b_chars.len()) - 1;
let ac = a_chars.get(idx).copied().unwrap_or('\0');
let bc = b_chars.get(idx).copied().unwrap_or('\0');
return Some((idx, ac, bc));
}
None
}
pub fn parse_expression(expr: &str) -> Result<(String, String, Vec<String>), String> {
let expr = expr.trim();
let colon_idx = expr.find(':')
.ok_or_else(|| format!("Invalid expression format (missing prefix): {}", expr))?;
let prefix = expr[0..colon_idx].trim().to_string();
let rest = &expr[colon_idx + 1..].trim();
if let Some(paren_start) = rest.find('(') {
let paren_end = rest.rfind(')')
.ok_or_else(|| format!("Missing closing parenthesis in expression: {}", expr))?;
let func_name = rest[0..paren_start].trim().to_string();
let args_str = rest[paren_start + 1..paren_end].trim();
let mut args = Vec::new();
if !args_str.is_empty() {
for arg in args_str.split(',') {
args.push(arg.trim().to_string());
}
}
Ok((prefix, func_name, args))
} else {
let func_name = rest.to_string();
Ok((prefix, func_name, Vec::new()))
}
}
pub fn evaluate_invariant(expr: &str, clm_root: &str, context: &Value) -> Result<bool, String> {
let expr = expr.trim();
if expr.is_empty() {
return Ok(true);
}
let is_prefix = expr.contains(':')
&& !expr.contains('>')
&& !expr.contains('<')
&& !expr.contains("==")
&& !expr.contains("!=")
&& !expr.contains('%');
if is_prefix {
let (prefix, func_name, args) = parse_expression(expr)?;
let mut resolved_args = Vec::new();
for arg in &args {
if arg.starts_with('"') && arg.ends_with('"') {
resolved_args.push(arg[1..arg.len() - 1].to_string());
} else if arg.starts_with("inputs.") || arg.starts_with("outputs.") {
let val = resolve_value(arg, context)
.ok_or_else(|| format!("Could not resolve path reference: {}", arg))?;
resolved_args.push(val.as_str().map(|s| s.to_string()).unwrap_or_else(|| val.to_string()));
} else {
if let Some(val) = resolve_value(arg, context) {
resolved_args.push(val.as_str().map(|s| s.to_string()).unwrap_or_else(|| val.to_string()));
} else {
resolved_args.push(arg.clone());
}
}
}
match (prefix.as_str(), func_name.as_str()) {
("gate", "file_exists") => {
if resolved_args.is_empty() {
return Err("gate:file_exists requires at least 1 argument".to_string());
}
let path_str = &resolved_args[0];
let path = Path::new(path_str);
let resolved_path = if path.is_absolute() {
path.to_path_buf()
} else {
Path::new(clm_root).join(path_str)
};
Ok(resolved_path.exists())
}
("gate", "is_sha256") => {
if resolved_args.is_empty() {
return Err("gate:is_sha256 requires at least 1 argument".to_string());
}
let hash_str = &resolved_args[0];
if !hash_str.starts_with(crate::hash::DEFAULT_HASH_PREFIX) || hash_str.len() != 71 {
return Ok(false);
}
let hex_part = crate::hash::strip_prefix(hash_str);
Ok(hex_part.chars().all(|c| c.is_ascii_hexdigit()))
}
("gate", "payload_nonempty") => {
let payload = if resolved_args.is_empty() {
std::env::var("CLM_PAYLOAD").unwrap_or_default()
} else {
resolved_args[0].clone()
};
Ok(!payload.trim().is_empty())
}
("gate", "result_sealed") => {
let hash = if resolved_args.is_empty() {
if let Some(v) = resolve_value("outputs.a_hash", context) {
v.as_str().unwrap_or("").to_string()
} else if let Some(v) = resolve_value("outputs.c_hash", context) {
v.as_str().unwrap_or("").to_string()
} else {
std::env::var("CLM_ACTIVE_C_HASH").unwrap_or_default()
}
} else {
resolved_args[0].clone()
};
if hash.is_empty() {
return Ok(false);
}
let exists = crate::db::card_exists("content_memory", clm_root, &hash)
.map_err(|e| format!("Database check failed: {}", e))?;
Ok(exists)
}
("conservation", "noetherian_check") => {
for hash in &resolved_args {
let exists = crate::db::card_exists("content_memory", clm_root, hash)
.map_err(|e| format!("Database check failed: {}", e))?;
if !exists {
return Ok(false);
}
}
Ok(true)
}
_ => Err(format!("Unknown invariant function: {}:{}", prefix, func_name)),
}
} else {
evaluate_infix_expression(expr, context)
}
}
fn evaluate_infix_expression(expr: &str, context: &Value) -> Result<bool, String> {
let expr = expr.trim();
let operators = vec!["==", "!=", ">=", "<=", ">", "<"];
let mut found_op = None;
for op in &operators {
if let Some(idx) = expr.find(op) {
found_op = Some((*op, idx));
break;
}
}
if let Some((op, idx)) = found_op {
let lhs_str = expr[0..idx].trim();
let rhs_str = expr[idx + op.len()..].trim();
let lhs_val = evaluate_arithmetic(lhs_str, context)?;
let rhs_val = evaluate_arithmetic(rhs_str, context)?;
match op {
"==" => Ok(lhs_val == rhs_val),
"!=" => Ok(lhs_val != rhs_val),
">" => {
let l = lhs_val.as_f64().ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
let r = rhs_val.as_f64().ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
Ok(l > r)
}
">=" => {
let l = lhs_val.as_f64().ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
let r = rhs_val.as_f64().ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
Ok(l >= r)
}
"<" => {
let l = lhs_val.as_f64().ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
let r = rhs_val.as_f64().ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
Ok(l < r)
}
"<=" => {
let l = lhs_val.as_f64().ok_or_else(|| format!("LHS is not a number: {}", lhs_str))?;
let r = rhs_val.as_f64().ok_or_else(|| format!("RHS is not a number: {}", rhs_str))?;
Ok(l <= r)
}
_ => unreachable!(),
}
} else {
let val = evaluate_arithmetic(expr, context)?;
if let Some(b) = val.as_bool() {
Ok(b)
} else if let Some(n) = val.as_i64() {
Ok(n != 0)
} else if let Some(s) = val.as_str() {
Ok(!s.is_empty())
} else {
Ok(!val.is_null())
}
}
}
fn evaluate_arithmetic(expr: &str, context: &Value) -> Result<Value, String> {
let expr = expr.trim();
if let Some(idx) = expr.find('%') {
let lhs_str = expr[0..idx].trim();
let rhs_str = expr[idx + 1..].trim();
let lhs_val = evaluate_arithmetic(lhs_str, context)?;
let rhs_val = evaluate_arithmetic(rhs_str, context)?;
let l = lhs_val.as_i64().ok_or_else(|| format!("LHS of % is not an integer: {}", lhs_str))?;
let r = rhs_val.as_i64().ok_or_else(|| format!("RHS of % is not an integer: {}", rhs_str))?;
if r == 0 {
return Err("Modulo by zero".to_string());
}
return Ok(Value::from(l % r));
}
if expr.starts_with('"') && expr.ends_with('"') {
return Ok(Value::String(expr[1..expr.len() - 1].to_string()));
}
if let Ok(n) = expr.parse::<i64>() {
return Ok(Value::from(n));
}
if let Ok(f) = expr.parse::<f64>() {
return Ok(Value::from(f));
}
if expr == "true" {
return Ok(Value::Bool(true));
}
if expr == "false" {
return Ok(Value::Bool(false));
}
if let Some(val) = resolve_value(expr, context) {
return Ok(val.clone());
}
Err(format!("Could not resolve token or value: {}", expr))
}
fn resolve_value<'a>(path: &str, context: &'a Value) -> Option<&'a Value> {
let parts: Vec<&str> = path.split('.').collect();
let mut current = context;
for part in parts {
{
let val = current.get(part)?;
current = val;
}
}
Some(current)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_parse_expression() {
let (p, f, args) = parse_expression("gate:file_exists(inputs.clm_file)").unwrap();
assert_eq!(p, "gate");
assert_eq!(f, "file_exists");
assert_eq!(args, vec!["inputs.clm_file"]);
let (p2, f2, args2) = parse_expression("gate:payload_nonempty").unwrap();
assert_eq!(p2, "gate");
assert_eq!(f2, "payload_nonempty");
assert_eq!(args2.len(), 0);
}
#[test]
fn test_evaluate_invariant_prefix() {
let context = json!({
"inputs": {
"clm_file": "Cargo.toml"
}
});
let res = evaluate_invariant("gate:file_exists(inputs.clm_file)", ".", &context).unwrap();
assert!(res);
let res2 = evaluate_invariant("gate:file_exists(\"non_existent_file.yaml\")", ".", &context).unwrap();
assert!(!res2);
}
#[test]
fn test_evaluate_invariant_infix_math() {
let context = json!({
"inputs": {
"val": 5
},
"outputs": {
"result": 8
}
});
let res1 = evaluate_invariant("inputs.val > 0", ".", &context).unwrap();
assert!(res1);
let res2 = evaluate_invariant("inputs.val < 0", ".", &context).unwrap();
assert!(!res2);
let res3 = evaluate_invariant("outputs.result % 2 == 0", ".", &context).unwrap();
assert!(res3);
let res4 = evaluate_invariant("outputs.result % 3 == 0", ".", &context).unwrap();
assert!(!res4);
}
}
#[path = "invariants_equivalence.rs"]
mod invariants_equivalence;
#[allow(unused_imports)]
pub use invariants_equivalence::*;
#[path = "invariants_pcard.rs"]
mod invariants_pcard;
#[allow(unused_imports)]
pub use invariants_pcard::*;