moonproof-runtime-ir 0.2.1

Rust consumer for compactc's contract.mpir — language-agnostic Compact contract IR. Loads, validates, and (eventually) interprets the IR to drive moonproof's contract runtime.
Documentation
//! Load + parse `contract.mpir` into typed [`crate::ir::MoonIr`].
//!
//! Wire format is RFC 8949 CBOR.  See the patched compactc fork's
//! `compiler/cbor.ss` and `compiler/runtime-ir-passes.ss` for the
//! emitter side; the schema itself is unchanged from the JSON era and
//! is documented in `compact/doc/runtime-ir.md`.

use std::path::Path;

use crate::error::{IrError, Result};
use crate::ir::MoonIr;

/// Canonical filename for a compiled Moonproof IR artifact inside a contract
/// build directory (`<out>/contract.mpir` or `<out>/compiler/contract.mpir`).
pub const MOON_IR_FILENAME: &str = "contract.mpir";

/// The newest schema version this consumer understands.
///
/// - 2 added the curve-typed fields and points, the operand type on the
///   arithmetic binops, the `cast-to-field` / `cast-from-field` / `emit`
///   expressions, and the `contracts` section.
/// - 3 added optional language-agnostic contract metadata (`frontend`,
///   `debug-info`, `capabilities`, `workflows`, `privacy`, `type-roles`)
///   and `Native.intrinsic`. All schema-3 additions are omitted on the
///   wire when absent/empty, so schema-1 and schema-2 files stay readable
///   and round-trip byte-for-byte identically.
pub const SUPPORTED_SCHEMA_VERSION: u32 = 3;

/// The oldest schema version this consumer understands. Contracts
/// compiled by a pre-0.33 toolchain stay readable.
pub const MIN_SCHEMA_VERSION: u32 = 1;

/// Parse a runtime-ir CBOR byte slice using the zero-copy single-pass decoder.
pub fn from_cbor_slice(bytes: &[u8]) -> Result<MoonIr> {
    let ir = crate::cbor_fast::decode_runtime_ir_slice(bytes)?;
    check_schema_version(&ir)?;
    Ok(ir)
}

/// Encode a [`MoonIr`] into RFC 8949 CBOR bytes using the direct fast encoder.
#[must_use]
pub fn to_cbor_vec(ir: &MoonIr) -> Vec<u8> {
    crate::cbor_fast::encode_runtime_ir_vec(ir)
}

/// Append a [`MoonIr`]'s RFC 8949 CBOR bytes into `out`.
pub fn write_cbor(ir: &MoonIr, out: &mut Vec<u8>) {
    crate::cbor_fast::encode_runtime_ir_into(ir, out);
}

/// Read + parse a runtime-ir CBOR file.
pub fn from_path(path: impl AsRef<Path>) -> Result<MoonIr> {
    let bytes = std::fs::read(path.as_ref())?;
    from_cbor_slice(&bytes)
}

fn check_schema_version(ir: &MoonIr) -> Result<()> {
    if (MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION).contains(&ir.schema_version) {
        Ok(())
    } else {
        Err(IrError::UnsupportedSchemaVersion {
            actual: ir.schema_version,
            supported: SUPPORTED_SCHEMA_VERSION,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ir_with_version(v: u32) -> MoonIr {
        let mut ir: MoonIr = serde_json::from_str(
            r#"{"schema-version":1,"compiler-version":"x","language-version":"x",
                "runtime-version":"x","constructor":{"arguments":[],"initial-state":
                {"kind":"null"},"init-ops":[],"register-operations":[],
                "body":{"stmt":"seq","items":[]}}}"#,
        )
        .expect("fixture parses");
        ir.schema_version = v;
        ir
    }

    #[test]
    fn accepts_every_released_schema_version() {
        for v in MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION {
            assert!(
                check_schema_version(&ir_with_version(v)).is_ok(),
                "schema {v} must stay readable"
            );
        }
    }

    #[test]
    fn rejects_a_newer_schema_than_this_build_knows() {
        let err = check_schema_version(&ir_with_version(SUPPORTED_SCHEMA_VERSION + 1));
        assert!(err.is_err(), "a future schema must not be read as if known");
    }
}