feat(value): value model, structured diagnostics and wire format

Implements the shared data contract from blueprint sections 3.4, 7.2 and 10.3:

- Value: Unit/None/Bool/Int(BigInt)/Float/Text/List/Map/Table/Formula/Code/
  FunctionRef/PluginHandle; Unit and None stay distinct and there is no
  implicit string/number coercion.
- Diagnostic with stable machine-readable codes (markdown.invalid_construct,
  expr.parse, symbol.unknown, permission.denied, ...) and span/related/hints.
- RuntimeError with category codes and call frames; renders to a Diagnostic.
- Versioned, type-tagged JSON wire format (wire_version = 1) that keeps
  arbitrary-precision integers as decimal strings, tags NaN/Infinity, enforces
  depth/size limits on untrusted input and never trusts JSON numbers for Int.
- Byte spans and line/column mapping live in the new marqdo-span crate.
This commit is contained in:
cflmy committed 2026-11-20 10:24:13 +08:00
1 parent df878b434a
commit 1520244923
6 files changed
+1968

No files matched your search

+187
View File
@@ -0,0 +1,187 @@
//! Machine readable diagnostics shared by `check`, `inspect` and `run`.
use marqdo_span::Span;
use serde::{Deserialize, Serialize};
/// Stable diagnostic codes. CI may depend on these strings; they must not be
/// renamed without an ADR because they are part of the CLI contract.
pub mod codes {
/// A Markdown AST node occupies an executable position but has an invalid shape.
pub const MARKDOWN_INVALID_CONSTRUCT: &str = "markdown.invalid_construct";
/// Front matter is malformed or appears somewhere other than the document start.
pub const FRONTMATTER_INVALID: &str = "frontmatter.invalid";
/// An executable payload failed to parse as an expression or statement.
pub const EXPR_PARSE: &str = "expr.parse";
/// A function name is referenced but no such function exists.
pub const SYMBOL_UNKNOWN: &str = "symbol.unknown";
/// A variable is read before any binding is guaranteed to exist.
pub const SYMBOL_UNINITIALIZED: &str = "symbol.uninitialized";
/// A call supplies the wrong number of arguments.
pub const CALL_ARITY: &str = "call.arity";
/// A call supplies an argument of the wrong type.
pub const CALL_TYPE: &str = "call.type";
/// An imported module cannot be resolved or loaded.
pub const MODULE_UNRESOLVED: &str = "module.unresolved";
/// A module import cycle was detected.
pub const MODULE_CYCLE: &str = "module.cycle";
/// A Markdown reference or link target cannot be resolved.
pub const REF_UNRESOLVED: &str = "ref.unresolved";
/// The requested math operation is outside the supported subset.
pub const MATH_UNSUPPORTED: &str = "math.unsupported";
/// A foreign language kernel is not available on this machine.
pub const KERNEL_UNAVAILABLE: &str = "kernel.unavailable";
/// A capability check rejected the requested operation.
pub const PERMISSION_DENIED: &str = "permission.denied";
/// A plugin artifact does not match the supported ABI version.
pub const PLUGIN_ABI_MISMATCH: &str = "plugin.abi_mismatch";
/// A resource budget (fuel, stack, memory, time) was exhausted.
pub const RESOURCE_EXHAUSTED: &str = "resource.exhausted";
/// A runtime type error that is not better described by a more specific code.
pub const RUNTIME_TYPE: &str = "runtime.type";
/// A runtime index or key error.
pub const RUNTIME_INDEX: &str = "runtime.index";
/// Invalid project manifest.
pub const PROJECT_MANIFEST: &str = "project.manifest";
/// Invalid project lockfile.
pub const PROJECT_LOCK: &str = "project.lock";
/// Dependency resolution failed.
pub const PROJECT_DEPENDENCY: &str = "project.dependency";
/// Internal invariant violation; never expected in normal operation.
pub const INTERNAL: &str = "internal.error";
}
/// Severity level of a [`Diagnostic`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
/// The input is invalid and execution/checking cannot proceed.
Error,
/// The input is valid but suspicious or potentially non-portable.
Warning,
/// Informational note attached to another diagnostic.
Info,
}
impl Severity {
/// Lowercase name used in JSON output.
pub const fn as_str(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
}
}
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Secondary source location attached to a diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Related {
/// Optional span of the related location.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Why this location is relevant.
pub message: String,
}
/// A structured, machine readable diagnostic.
///
/// The JSON shape is part of the CLI contract:
/// `{ code, severity, span, message, related, hints }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
/// Stable code from [`codes`].
pub code: String,
/// Severity of the diagnostic.
pub severity: Severity,
/// Source span (byte offsets into the file), if known.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Human readable message. Not part of the compatibility contract.
pub message: String,
/// Related locations, e.g. a conflicting declaration.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub related: Vec<Related>,
/// Suggested fixes or authoring hints.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hints: Vec<String>,
}
impl Diagnostic {
/// Create an error diagnostic.
pub fn error(code: impl Into<String>, span: Option<Span>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
severity: Severity::Error,
span,
message: message.into(),
related: Vec::new(),
hints: Vec::new(),
}
}
/// Create a warning diagnostic.
pub fn warning(
code: impl Into<String>,
span: Option<Span>,
message: impl Into<String>,
) -> Self {
Self {
severity: Severity::Warning,
..Self::error(code, span, message)
}
}
/// Add an authoring hint.
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hints.push(hint.into());
self
}
/// Add a related source location.
pub fn with_related(mut self, span: Option<Span>, message: impl Into<String>) -> Self {
self.related.push(Related {
span,
message: message.into(),
});
self
}
/// Add a related span that is a suitable fix location.
pub fn with_help_span(self, span: Span, message: impl Into<String>) -> Self {
self.with_related(Some(span), message)
}
/// Whether this diagnostic is fatal.
pub fn is_error(&self) -> bool {
self.severity == Severity::Error
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn diagnostic_json_shape_is_stable() {
let diag = Diagnostic::error(codes::EXPR_PARSE, Some(Span::new(3, 9)), "bad expression")
.with_hint("use a code span")
.with_related(None, "declared here");
let json = serde_json::to_value(&diag).unwrap();
assert_eq!(json["code"], "expr.parse");
assert_eq!(json["severity"], "error");
assert_eq!(json["span"]["start"], 3);
assert_eq!(json["hints"][0], "use a code span");
assert_eq!(json["related"][0]["message"], "declared here");
// Absent optional fields are omitted rather than null.
let minimal = Diagnostic::error(codes::INTERNAL, None, "oops");
let json = serde_json::to_value(&minimal).unwrap();
assert!(json.get("span").is_none());
assert!(json.get("related").is_none());
}
}
+175
View File
@@ -0,0 +1,175 @@
//! Structured runtime errors with source spans and call frames.
use crate::codes;
use crate::diagnostic::Diagnostic;
use marqdo_span::Span;
/// Category of a runtime failure. Each category maps to a stable diagnostic
/// code so that CI and agents can branch on codes instead of message wording.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCategory {
/// A value had the wrong type for the operation.
Type,
/// A call supplied the wrong number of arguments.
Arity,
/// A name is not bound in any reachable scope.
UnknownSymbol,
/// A name is bound but may be read before assignment.
Uninitialized,
/// Division or modulo by zero.
DivisionByZero,
/// A value was used as a function but is not callable.
NotCallable,
/// A map key or record field does not exist.
UnknownField,
/// A list/map index is out of bounds.
IndexOutOfBounds,
/// A resource budget was exhausted (fuel, stack, output size).
ResourceExhausted,
/// A capability check denied the operation.
PermissionDenied,
/// A foreign language kernel is unavailable.
KernelUnavailable,
/// The requested math operation is unsupported.
MathUnsupported,
/// Plugin ABI negotiation failed.
PluginAbi,
/// A plugin reported an execution failure.
PluginFailure,
/// A foreign kernel failed (non-zero exit, protocol violation).
ForeignFailure,
/// A host operation failed for an environmental reason.
HostError,
/// Internal invariant violation.
Internal,
}
impl ErrorCategory {
/// Stable diagnostic code for this category.
pub const fn code(self) -> &'static str {
match self {
ErrorCategory::Type => codes::RUNTIME_TYPE,
ErrorCategory::Arity => codes::CALL_ARITY,
ErrorCategory::UnknownSymbol => codes::SYMBOL_UNKNOWN,
ErrorCategory::Uninitialized => codes::SYMBOL_UNINITIALIZED,
ErrorCategory::DivisionByZero => "runtime.division_by_zero",
ErrorCategory::NotCallable => "call.not_callable",
ErrorCategory::UnknownField => "runtime.unknown_field",
ErrorCategory::IndexOutOfBounds => codes::RUNTIME_INDEX,
ErrorCategory::ResourceExhausted => codes::RESOURCE_EXHAUSTED,
ErrorCategory::PermissionDenied => codes::PERMISSION_DENIED,
ErrorCategory::KernelUnavailable => codes::KERNEL_UNAVAILABLE,
ErrorCategory::MathUnsupported => codes::MATH_UNSUPPORTED,
ErrorCategory::PluginAbi => codes::PLUGIN_ABI_MISMATCH,
ErrorCategory::PluginFailure => "plugin.failure",
ErrorCategory::ForeignFailure => "foreign.failure",
ErrorCategory::HostError => "host.error",
ErrorCategory::Internal => codes::INTERNAL,
}
}
}
/// One entry of the Marqdo call stack.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CallFrame {
/// Canonical function name (or `<main>` for the entry function).
pub function: String,
/// Source location of the call site in the caller.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
}
/// A structured runtime failure.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RuntimeError {
/// Failure category.
pub category: ErrorCategory,
/// Location in the source that caused the failure.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Human readable message.
pub message: String,
/// Call frames from innermost to outermost.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub frames: Vec<CallFrame>,
/// Underlying cause (e.g. a host or foreign kernel error).
#[serde(skip_serializing_if = "Option::is_none")]
pub cause: Option<Box<RuntimeError>>,
/// Effect trace recorded by the host, when available.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub effect_trace: Vec<String>,
}
impl RuntimeError {
/// Create a new runtime error.
pub fn new(category: ErrorCategory, span: Option<Span>, message: impl Into<String>) -> Self {
Self {
category,
span,
message: message.into(),
frames: Vec::new(),
cause: None,
effect_trace: Vec::new(),
}
}
/// Convenience constructor for type errors.
pub fn type_error(span: Option<Span>, message: impl Into<String>) -> Self {
Self::new(ErrorCategory::Type, span, message)
}
/// Record a call frame (called while unwinding).
pub fn push_frame(&mut self, function: impl Into<String>, span: Option<Span>) {
self.frames.push(CallFrame {
function: function.into(),
span,
});
}
/// Add a cause.
pub fn with_cause(mut self, cause: RuntimeError) -> Self {
self.cause = Some(Box::new(cause));
self
}
/// The stable diagnostic code for this failure.
pub fn code(&self) -> &'static str {
self.category.code()
}
/// Render as a user facing diagnostic.
pub fn to_diagnostic(&self) -> Diagnostic {
let mut diag = Diagnostic::error(self.code(), self.span, self.message.clone());
for frame in &self.frames {
diag = diag.with_related(frame.span, format!("in function `{}`", frame.function));
}
if let Some(cause) = &self.cause {
diag = diag.with_related(cause.span, format!("caused by: {}", cause.message));
}
diag
}
}
impl std::fmt::Display for RuntimeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code(), self.message)
}
}
impl std::error::Error for RuntimeError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_are_rendered_as_related_diagnostics() {
let mut err = RuntimeError::type_error(Some(Span::new(1, 2)), "expected Bool");
err.push_frame("阶乘", None);
let diag = err.to_diagnostic();
assert_eq!(diag.code, "runtime.type");
assert_eq!(diag.related.len(), 1);
assert_eq!(diag.related[0].message, "in function `阶乘`");
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Marqdo language values, diagnostics and errors.
//!
//! This crate is the shared data contract between the frontend, the IR, the
//! runtime and the host boundary. It has no dependency on Markdown parsing,
//! process execution or the CLI so that every layer can agree on values and
//! structured failures without creating dependency cycles.
pub mod diagnostic;
pub mod error;
pub mod value;
pub mod wire;
pub use diagnostic::{codes, Diagnostic, Related, Severity};
pub use error::{CallFrame, ErrorCategory, RuntimeError};
pub use marqdo_span::{LineCol, Span};
pub use value::{CodeValue, FormulaValue, FunctionRef, Table, Value};
pub use wire::{from_wire, to_wire, WireError, WIRE_VERSION};
+352
View File
@@ -0,0 +1,352 @@
//! The Marqdo value model.
//!
//! Values are deliberately explicit: there is no truthiness and no implicit
//! string/number conversion. `Unit` (no result) and `None` (explicit empty
//! value) are distinct, as required by the language specification.
use std::collections::BTreeMap;
use num_bigint::BigInt;
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use marqdo_span::Span;
/// A structured GFM table value.
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
/// Column headers in order.
pub header: Vec<String>,
/// Data rows; every row has exactly `header.len()` cells.
pub rows: Vec<Vec<Value>>,
}
/// An inert `Formula` value: LaTeX source plus provenance. Parsing and
/// evaluation are separate, explicit operations performed by the math kernel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FormulaValue {
/// Raw LaTeX (or math extension) source, without delimiters.
pub latex: String,
/// Canonical owning unit, when the formula came from a document heading range.
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
/// Whether the formula was display math (`$$...$$`).
pub display: bool,
/// Source location of the formula node.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
}
/// An inert `Code` value: a fenced code block plus provenance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CodeValue {
/// Fence info string language (empty for plain fences).
pub language: String,
/// Raw source inside the fence.
pub source: String,
/// Canonical owning unit, when the fence came from a document heading range.
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>,
/// Lowercase hex SHA-256 of `source`.
pub content_hash: String,
/// Source location of the code block.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
}
/// A reference to a named function in a module.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionRef {
/// Canonical module identity (project relative path or imported alias).
pub module: String,
/// Canonical function name within the module.
pub name: String,
}
/// A host-owned handle to a loaded plugin export. Handles are opaque; they
/// cannot be forged from wire data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginHandle {
/// Plugin identifier from its manifest.
pub plugin: String,
/// Export name within the plugin.
pub export: String,
/// Host-assigned generation number.
pub id: u64,
}
/// A Marqdo runtime value.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
/// No result (a function that fell through its body).
Unit,
/// Explicit empty value.
None,
/// Boolean.
Bool(bool),
/// Arbitrary precision integer.
Int(BigInt),
/// IEEE-754 double.
Float(f64),
/// Unicode text.
Text(String),
/// Ordered sequence.
List(Vec<Value>),
/// String-keyed record with deterministic key order.
Map(BTreeMap<String, Value>),
/// Structured table.
Table(Table),
/// Inert formula.
Formula(FormulaValue),
/// Inert code fence.
Code(CodeValue),
/// Reference to a named function.
FunctionRef(FunctionRef),
/// Host-owned plugin handle.
PluginHandle(PluginHandle),
}
impl Value {
/// Stable type name used by diagnostics and wire messages.
pub const fn type_name(&self) -> &'static str {
match self {
Value::Unit => "Unit",
Value::None => "None",
Value::Bool(_) => "Bool",
Value::Int(_) => "Int",
Value::Float(_) => "Float",
Value::Text(_) => "Text",
Value::List(_) => "List",
Value::Map(_) => "Map",
Value::Table(_) => "Table",
Value::Formula(_) => "Formula",
Value::Code(_) => "Code",
Value::FunctionRef(_) => "FunctionRef",
Value::PluginHandle(_) => "PluginHandle",
}
}
/// Construct an integer from an `i64`.
pub fn int(value: i64) -> Self {
Value::Int(BigInt::from(value))
}
/// Construct a text value.
pub fn text(value: impl Into<String>) -> Self {
Value::Text(value.into())
}
/// Whether the value is the boolean `true`.
pub fn is_true(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
/// User-facing rendering used by the host `print` operation.
///
/// Strings print unquoted (like a scripting language), collections use a
/// deterministic Rust-like representation so that output is reproducible.
pub fn display(&self) -> String {
match self {
Value::Unit => "Unit".to_string(),
Value::None => "None".to_string(),
Value::Bool(b) => b.to_string(),
Value::Int(i) => i.to_string(),
Value::Float(f) => format_float(*f),
Value::Text(t) => t.clone(),
other => other.repr(),
}
}
/// Debug-style rendering with type-faithful literals.
pub fn repr(&self) -> String {
match self {
Value::Unit => "Unit".to_string(),
Value::None => "None".to_string(),
Value::Bool(b) => b.to_string(),
Value::Int(i) => i.to_string(),
Value::Float(f) => format_float(*f),
Value::Text(t) => format!("{t:?}"),
Value::List(items) => {
let inner = items.iter().map(Value::repr).collect::<Vec<_>>().join(", ");
format!("[{inner}]")
}
Value::Map(map) => {
let inner = map
.iter()
.map(|(k, v)| format!("{}: {}", k, v.repr()))
.collect::<Vec<_>>()
.join(", ");
format!("{{{inner}}}")
}
Value::Table(table) => {
let header = table.header.join(" | ");
let rows = table
.rows
.iter()
.map(|row| {
row.iter()
.map(Value::display)
.collect::<Vec<_>>()
.join(" | ")
})
.collect::<Vec<_>>()
.join("; ");
format!("Table[{header}]{{{rows}}}")
}
Value::Formula(f) => format!("Formula({:?})", f.latex),
Value::Code(c) => format!("Code({:?}, {} bytes)", c.language, c.source.len()),
Value::FunctionRef(r) => format!("FunctionRef({}::{})", r.module, r.name),
Value::PluginHandle(h) => format!("PluginHandle({}::{})", h.plugin, h.export),
}
}
/// Structural equality that treats `Float` NaN as unequal to itself while
/// keeping `Int`/`Float` distinct.
pub fn same_value(&self, other: &Value) -> bool {
self == other
}
}
/// Format a float without exposing the internal `f64` Debug formatting
/// (`1.0` vs `1`); NaN and infinities get explicit spellings.
pub fn format_float(f: f64) -> String {
if f.is_nan() {
"NaN".to_string()
} else if f.is_infinite() {
if f.is_sign_negative() {
"-Infinity".to_string()
} else {
"Infinity".to_string()
}
} else if f == 0.0 && f.is_sign_negative() {
"-0.0".to_string()
} else {
// Rust's Display for f64 produces the shortest representation that
// round-trips, and always keeps a decimal point for integral values
// when using `{:?}`; we use `{}` to keep the common case short but
// preserve `.0` so that the value still reads as a Float.
let s = format!("{f}");
if s.contains('.') || s.contains('e') || s.contains('E') {
s
} else {
format!("{s}.0")
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.display())
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Value::Bool(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Value::Text(value.to_string())
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Value::Text(value)
}
}
impl From<i64> for Value {
fn from(value: i64) -> Self {
Value::int(value)
}
}
impl From<Vec<Value>> for Value {
fn from(value: Vec<Value>) -> Self {
Value::List(value)
}
}
impl FromIterator<Value> for Value {
fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
Value::List(iter.into_iter().collect())
}
}
/// Convert a float to an exact integer when it is integral; used by explicit
/// math coercions, never implicitly by the evaluator.
pub fn float_to_bigint(f: f64) -> Option<BigInt> {
if f.is_finite() && f.fract() == 0.0 {
// Route through the decimal string so that values beyond i64 range do
// not lose precision.
let s = format!("{f:.0}");
s.parse().ok()
} else {
None
}
}
/// Convert an integer to `f64` when it round-trips exactly.
pub fn bigint_to_exact_f64(i: &BigInt) -> Option<f64> {
let f = i.to_f64()?;
if float_to_bigint(f).as_ref() == Some(i) {
Some(f)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unit_and_none_are_distinct() {
assert_ne!(Value::Unit, Value::None);
assert_eq!(Value::Unit.type_name(), "Unit");
assert_eq!(Value::None.type_name(), "None");
}
#[test]
fn display_is_stable() {
assert_eq!(Value::int(42).display(), "42");
assert_eq!(Value::Float(2.0).display(), "2.0");
assert_eq!(Value::Text("hi".into()).display(), "hi");
assert_eq!(Value::Text("hi".into()).repr(), "\"hi\"");
assert_eq!(
Value::List(vec![Value::int(1), Value::Unit]).display(),
"[1, Unit]"
);
}
#[test]
fn big_integers_are_arbitrary_precision() {
let big: BigInt = "123456789012345678901234567890".parse().unwrap();
let value = Value::Int(big.clone());
assert_eq!(value.display(), "123456789012345678901234567890");
assert_eq!(
big + BigInt::from(1),
"123456789012345678901234567891".parse().unwrap()
);
}
#[test]
fn float_to_bigint_requires_integral_value() {
assert_eq!(float_to_bigint(2.0), Some(BigInt::from(2)));
assert_eq!(float_to_bigint(2.5), None);
assert_eq!(
bigint_to_exact_f64(&BigInt::from(9007199254740992i64)),
Some(9007199254740992.0)
);
assert_eq!(
bigint_to_exact_f64(&BigInt::from(9007199254740993i64)),
None
);
}
}
+415
View File
@@ -0,0 +1,415 @@
//! Versioned, type-tagged JSON wire format for values crossing ABI, worker IPC
//! and foreign-kernel boundaries.
//!
//! JSON numbers cannot represent arbitrary precision integers or special
//! floats faithfully, so every value carries an explicit `type` tag and
//! integers are encoded as decimal strings. This is the single canonical
//! exchange format required by the specification (`spec/value-wire.md`).
use std::collections::BTreeMap;
use num_bigint::BigInt;
use serde_json::{json, Map, Value as Json};
use crate::value::{CodeValue, FormulaValue, FunctionRef, PluginHandle, Table, Value};
use marqdo_span::Span;
/// Current wire protocol version.
pub const WIRE_VERSION: u32 = 1;
/// Limits applied while decoding untrusted wire data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireLimits {
/// Maximum nesting depth.
pub max_depth: usize,
/// Maximum number of elements in a list.
pub max_items: usize,
/// Maximum number of bytes in a single string.
pub max_string_bytes: usize,
}
impl Default for WireLimits {
fn default() -> Self {
Self {
max_depth: 64,
max_items: 1_000_000,
max_string_bytes: 16 * 1024 * 1024,
}
}
}
/// Failure while decoding or encoding wire data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WireError {
/// The `type` tag is missing or unknown.
UnknownType(String),
/// A required field is missing.
MissingField(&'static str),
/// A field has the wrong JSON type or an invalid value.
Invalid(String),
/// Nesting or size limits were exceeded.
LimitExceeded(&'static str),
}
impl std::fmt::Display for WireError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
WireError::UnknownType(t) => write!(f, "unknown wire value type `{t}`"),
WireError::MissingField(field) => write!(f, "missing wire field `{field}`"),
WireError::Invalid(msg) => write!(f, "invalid wire value: {msg}"),
WireError::LimitExceeded(what) => write!(f, "wire limit exceeded: {what}"),
}
}
}
impl std::error::Error for WireError {}
/// Encode a value as the canonical wire representation.
pub fn to_wire(value: &Value) -> Json {
encode(value)
}
fn encode(value: &Value) -> Json {
match value {
Value::Unit => json!({"type": "unit"}),
Value::None => json!({"type": "none"}),
Value::Bool(b) => json!({"type": "bool", "value": b}),
Value::Int(i) => json!({"type": "int", "decimal": i.to_string()}),
Value::Float(f) => {
if f.is_nan() {
json!({"type": "float", "special": "nan"})
} else if f.is_infinite() {
json!({"type": "float", "special": if f.is_sign_negative() { "-infinity" } else { "infinity" }})
} else {
json!({"type": "float", "value": f})
}
}
Value::Text(t) => json!({"type": "text", "value": t}),
Value::List(items) => json!({
"type": "list",
"items": items.iter().map(encode).collect::<Vec<_>>(),
}),
Value::Map(entries) => {
let mut map = Map::new();
for (key, val) in entries {
map.insert(key.clone(), encode(val));
}
json!({"type": "map", "entries": Json::Object(map)})
}
Value::Table(table) => json!({
"type": "table",
"header": table.header,
"rows": table
.rows
.iter()
.map(|row| row.iter().map(encode).collect::<Vec<_>>())
.collect::<Vec<_>>(),
}),
Value::Formula(formula) => {
let mut obj = json!({
"type": "formula",
"latex": formula.latex,
"display": formula.display,
});
if let Some(unit) = &formula.unit {
obj["unit"] = Json::String(unit.clone());
}
if let Some(span) = formula.span {
obj["span"] = encode_span(span);
}
obj
}
Value::Code(code) => {
let mut obj = json!({
"type": "code",
"language": code.language,
"source": code.source,
"content_hash": code.content_hash,
});
if let Some(unit) = &code.unit {
obj["unit"] = Json::String(unit.clone());
}
if let Some(span) = code.span {
obj["span"] = encode_span(span);
}
obj
}
Value::FunctionRef(func) => json!({
"type": "function_ref",
"module": func.module,
"name": func.name,
}),
Value::PluginHandle(handle) => json!({
"type": "plugin_handle",
"plugin": handle.plugin,
"export": handle.export,
"id": handle.id,
}),
}
}
fn encode_span(span: Span) -> Json {
json!({"start": span.start, "end": span.end})
}
/// Decode a value from wire data using default limits.
pub fn from_wire(json: &Json) -> Result<Value, WireError> {
from_wire_with_limits(json, WireLimits::default())
}
/// Decode a value from wire data with explicit limits.
pub fn from_wire_with_limits(json: &Json, limits: WireLimits) -> Result<Value, WireError> {
decode(json, 0, &limits)
}
fn decode(json: &Json, depth: usize, limits: &WireLimits) -> Result<Value, WireError> {
if depth > limits.max_depth {
return Err(WireError::LimitExceeded("nesting depth"));
}
let obj = json
.as_object()
.ok_or_else(|| WireError::Invalid("value must be a JSON object".into()))?;
let type_tag = obj
.get("type")
.and_then(Json::as_str)
.ok_or_else(|| WireError::MissingField("type"))?;
let require = |field: &'static str| obj.get(field).ok_or(WireError::MissingField(field));
match type_tag {
"unit" => Ok(Value::Unit),
"none" => Ok(Value::None),
"bool" => require("value")?
.as_bool()
.map(Value::Bool)
.ok_or_else(|| WireError::Invalid("bool.value must be a boolean".into())),
"int" => {
let decimal = require("decimal")?
.as_str()
.ok_or_else(|| WireError::Invalid("int.decimal must be a string".into()))?;
decimal
.parse::<BigInt>()
.map(Value::Int)
.map_err(|_| WireError::Invalid(format!("invalid integer `{decimal}`")))
}
"float" => {
if let Some(special) = obj.get("special").and_then(Json::as_str) {
let f = match special {
"nan" => f64::NAN,
"infinity" => f64::INFINITY,
"-infinity" => f64::NEG_INFINITY,
other => {
return Err(WireError::Invalid(format!(
"unknown float special `{other}`"
)))
}
};
return Ok(Value::Float(f));
}
require("value")?
.as_f64()
.map(Value::Float)
.ok_or_else(|| WireError::Invalid("float.value must be a number".into()))
}
"text" => {
let text = require("value")?
.as_str()
.ok_or_else(|| WireError::Invalid("text.value must be a string".into()))?;
if text.len() > limits.max_string_bytes {
return Err(WireError::LimitExceeded("text length"));
}
Ok(Value::Text(text.to_string()))
}
"list" => {
let items = require("items")?
.as_array()
.ok_or_else(|| WireError::Invalid("list.items must be an array".into()))?;
if items.len() > limits.max_items {
return Err(WireError::LimitExceeded("list length"));
}
let decoded = items
.iter()
.map(|item| decode(item, depth + 1, limits))
.collect::<Result<Vec<_>, _>>()?;
Ok(Value::List(decoded))
}
"map" => {
let entries = require("entries")?
.as_object()
.ok_or_else(|| WireError::Invalid("map.entries must be an object".into()))?;
if entries.len() > limits.max_items {
return Err(WireError::LimitExceeded("map length"));
}
let mut map = BTreeMap::new();
for (key, val) in entries {
if key.len() > limits.max_string_bytes {
return Err(WireError::LimitExceeded("map key length"));
}
map.insert(key.clone(), decode(val, depth + 1, limits)?);
}
Ok(Value::Map(map))
}
"table" => {
let header = require("header")?
.as_array()
.ok_or_else(|| WireError::Invalid("table.header must be an array".into()))?
.iter()
.map(|cell| {
cell.as_str().map(str::to_string).ok_or_else(|| {
WireError::Invalid("table.header cells must be strings".into())
})
})
.collect::<Result<Vec<_>, _>>()?;
let rows = require("rows")?
.as_array()
.ok_or_else(|| WireError::Invalid("table.rows must be an array".into()))?
.iter()
.map(|row| {
let cells = row
.as_array()
.ok_or_else(|| WireError::Invalid("table rows must be arrays".into()))?;
if cells.len() != header.len() {
return Err(WireError::Invalid(
"table row length does not match header".into(),
));
}
cells
.iter()
.map(|cell| decode(cell, depth + 1, limits))
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Value::Table(Table { header, rows }))
}
"formula" => Ok(Value::Formula(FormulaValue {
latex: require("latex")?
.as_str()
.ok_or_else(|| WireError::Invalid("formula.latex must be a string".into()))?
.to_string(),
display: obj.get("display").and_then(Json::as_bool).unwrap_or(false),
unit: optional_string(obj, "unit")?,
span: optional_span(obj)?,
})),
"code" => Ok(Value::Code(CodeValue {
language: optional_string(obj, "language")?.unwrap_or_default(),
source: require("source")?
.as_str()
.ok_or_else(|| WireError::Invalid("code.source must be a string".into()))?
.to_string(),
unit: optional_string(obj, "unit")?,
content_hash: optional_string(obj, "content_hash")?.unwrap_or_default(),
span: optional_span(obj)?,
})),
"function_ref" => Ok(Value::FunctionRef(FunctionRef {
module: require("module")?
.as_str()
.ok_or_else(|| WireError::Invalid("function_ref.module must be a string".into()))?
.to_string(),
name: require("name")?
.as_str()
.ok_or_else(|| WireError::Invalid("function_ref.name must be a string".into()))?
.to_string(),
})),
"plugin_handle" => Ok(Value::PluginHandle(PluginHandle {
plugin: require("plugin")?
.as_str()
.ok_or_else(|| WireError::Invalid("plugin_handle.plugin must be a string".into()))?
.to_string(),
export: require("export")?
.as_str()
.ok_or_else(|| WireError::Invalid("plugin_handle.export must be a string".into()))?
.to_string(),
id: require("id")?
.as_u64()
.ok_or_else(|| WireError::Invalid("plugin_handle.id must be an integer".into()))?,
})),
other => Err(WireError::UnknownType(other.to_string())),
}
}
fn optional_string(obj: &Map<String, Json>, field: &str) -> Result<Option<String>, WireError> {
match obj.get(field) {
None | Some(Json::Null) => Ok(None),
Some(Json::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(WireError::Invalid(format!("{field} must be a string"))),
}
}
fn optional_span(obj: &Map<String, Json>) -> Result<Option<Span>, WireError> {
let Some(span) = obj.get("span") else {
return Ok(None);
};
let start = span
.get("start")
.and_then(Json::as_u64)
.ok_or_else(|| WireError::Invalid("span.start must be an integer".into()))?;
let end = span
.get("end")
.and_then(Json::as_u64)
.ok_or_else(|| WireError::Invalid("span.end must be an integer".into()))?;
Ok(Some(Span::new(start as usize, end as usize)))
}
#[cfg(test)]
mod tests {
use super::*;
fn roundtrip(value: Value) {
let wire = to_wire(&value);
let decoded = from_wire(&wire).expect("decode");
assert_eq!(decoded, value);
}
#[test]
fn scalar_roundtrip() {
roundtrip(Value::Unit);
roundtrip(Value::None);
roundtrip(Value::Bool(true));
roundtrip(Value::int(-7));
roundtrip(Value::Float(1.5));
roundtrip(Value::Float(-0.0));
roundtrip(Value::Text("你好\n".into()));
roundtrip(Value::List(vec![Value::int(1), Value::text("x")]));
let mut map = BTreeMap::new();
map.insert("a".to_string(), Value::Bool(false));
roundtrip(Value::Map(map));
roundtrip(Value::Table(Table {
header: vec!["x".into()],
rows: vec![vec![Value::int(1)]],
}));
}
#[test]
fn big_integers_keep_all_digits() {
let big: BigInt = "123456789012345678901234567890123456789".parse().unwrap();
let wire = to_wire(&Value::Int(big));
assert_eq!(wire["decimal"], "123456789012345678901234567890123456789");
assert!(matches!(from_wire(&wire), Ok(Value::Int(_))));
}
#[test]
fn special_floats_are_tagged() {
assert_eq!(to_wire(&Value::Float(f64::NAN))["special"], "nan");
assert_eq!(to_wire(&Value::Float(f64::INFINITY))["special"], "infinity");
let decoded = from_wire(&to_wire(&Value::Float(f64::NEG_INFINITY))).unwrap();
assert!(matches!(decoded, Value::Float(f) if f == f64::NEG_INFINITY));
}
#[test]
fn untrusted_wire_is_validated() {
assert_eq!(
from_wire(&json!({"type": "int", "decimal": "not-a-number"})),
Err(WireError::Invalid("invalid integer `not-a-number`".into()))
);
assert_eq!(
from_wire(&json!({"type": "mystery"})),
Err(WireError::UnknownType("mystery".into()))
);
let deep = (0..100).fold(
json!({"type": "unit"}),
|acc, _| json!({"type": "list", "items": [acc]}),
);
assert_eq!(
from_wire(&deep),
Err(WireError::LimitExceeded("nesting depth"))
);
}
}