Files
marqdo/src/value.rs
T
cflmyandCursor 8f1010f967 Ship oracle journal values, bytecode/frontend hardening, and replay-policy Lean.
Host exposes oracle journals as language values with refuse/copy gates; bytecode and foreign session paths get modularized; applications and verification replay-policy sources land with Lake builds ignored.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 15:04:27 +08:00

132 lines
4.9 KiB
Rust

//! Runtime values (Phase I).
use std::fmt;
use crate::formula::Expr as FormulaExpr;
/// An object's defining module instance, expressed as import binding segments.
/// This is ordinary copied data, not an unforgeable session capability.
pub(crate) const OBJECT_MODULE_KEY: &str = "_type_module";
pub(crate) fn instance_module(value: &Value) -> Result<Option<Vec<String>>, String> {
let Value::Map(fields) = value else { return Ok(None); };
let Some((_, module)) = fields.iter().find(|(key, _)| key == OBJECT_MODULE_KEY) else { return Ok(None); };
let Value::List(segments) = module else { return Err("object module tag must be a list of text segments".into()); };
segments.iter().map(|segment| match segment {
Value::Text(name) => Ok(name.clone()),
_ => Err("object module tag must be a list of text segments".into()),
}).collect::<Result<Vec<_>,_>>().map(Some)
}
pub(crate) fn tag_instance(type_name: &str, module: &[String], value: Value) -> Value {
let mut fields = match value {
Value::Map(fields) => fields,
Value::None => Vec::new(),
other => vec![("value".into(),other)],
};
fields.retain(|(key,_)| key != "_type" && key != OBJECT_MODULE_KEY);
fields.insert(0,("_type".into(),Value::Text(type_name.into())));
fields.insert(1,(OBJECT_MODULE_KEY.into(),Value::List(module.iter().cloned().map(Value::Text).collect())));
Value::Map(fields)
}
pub(crate) fn preserve_instance_module(receiver: &Value, value: Value) -> Value {
let Ok(Some(module)) = instance_module(receiver) else { return value; };
match value {
Value::Map(mut fields) => {
fields.retain(|(key,_)| key != OBJECT_MODULE_KEY);
fields.insert(1.min(fields.len()),(OBJECT_MODULE_KEY.into(),Value::List(module.into_iter().map(Value::Text).collect())));
Value::Map(fields)
}
other => other,
}
}
/// Bound Markdown code fence (`type` → `code`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodeBlock {
pub lang: String,
pub source: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
None,
Bool(bool),
Int(i64),
/// Floating-point number (`type` → `num`).
Num(f64),
Text(String),
/// Vertical (1-column) table rows, or nested list values in a column map.
List(Vec<Value>),
/// String-keyed map (insertion order): JSON objects / horizontal tables.
Map(Vec<(String, Value)>),
/// Parsed symbolic expression (`type` → `formula`).
Formula(FormulaExpr),
/// External language source from ```lang fence (`type` → `code`).
Code(CodeBlock),
/// Sensitive text from `${secret.*}` — Display shows `<secret>`; reveal on Text concat.
Secret(String),
/// Opaque foreign-session handle. Not JSON-serializable; not printable structure.
Handle(String),
}
impl Value {
pub fn truthy(&self) -> bool {
match self {
Value::None => false,
Value::Bool(b) => *b,
Value::Int(n) => *n != 0,
Value::Num(n) => *n != 0.0 && !n.is_nan(),
Value::Text(s) => !s.is_empty(),
Value::Secret(s) => !s.is_empty(),
Value::Handle(s) => !s.is_empty(),
Value::List(xs) => !xs.is_empty(),
Value::Map(xs) => !xs.is_empty(),
Value::Formula(_) => true,
Value::Code(c) => !c.source.is_empty(),
}
}
/// Plaintext for Text / Secret (Authorization etc.). Prefer [`as_display`] for logs.
pub fn reveal_text(&self) -> Option<&str> {
match self {
Value::Text(s) | Value::Secret(s) => Some(s.as_str()),
_ => None,
}
}
pub fn as_display(&self) -> String {
match self {
Value::None => "None".into(),
Value::Bool(true) => "True".into(),
Value::Bool(false) => "False".into(),
Value::Int(n) => n.to_string(),
Value::Num(n) => crate::formula::format_num(*n),
Value::Text(s) => s.clone(),
Value::Secret(_) => "<secret>".into(),
Value::Handle(_) => "<handle>".into(),
Value::List(xs) => {
let parts: Vec<String> = xs.iter().map(|v| v.as_display()).collect();
format!("[{}]", parts.join(", "))
}
Value::Map(pairs) => {
let parts: Vec<String> = pairs
.iter()
.filter(|(key,_)| key != OBJECT_MODULE_KEY)
.map(|(k, v)| format!("{k}: {}", v.as_display()))
.collect();
format!("{{{}}}", parts.join(", "))
}
Value::Formula(e) => e.as_display(),
Value::Code(c) => format!("```{}\n{}\n```", c.lang, c.source),
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_display())
}
}