Skip to main content

moonproof_runtime_ir/
loader.rs

1//! Load + parse `contract.mpir` into typed [`crate::ir::MoonIr`].
2//!
3//! Wire format is RFC 8949 CBOR.  See the patched compactc fork's
4//! `compiler/cbor.ss` and `compiler/runtime-ir-passes.ss` for the
5//! emitter side; the schema itself is unchanged from the JSON era and
6//! is documented in `compact/doc/runtime-ir.md`.
7
8use std::path::Path;
9
10use crate::error::{IrError, Result};
11use crate::ir::MoonIr;
12
13/// Canonical filename for a compiled Moonproof IR artifact inside a contract
14/// build directory (`<out>/contract.mpir` or `<out>/compiler/contract.mpir`).
15pub const MOON_IR_FILENAME: &str = "contract.mpir";
16
17/// The newest schema version this consumer understands.
18///
19/// - 2 added the curve-typed fields and points, the operand type on the
20///   arithmetic binops, the `cast-to-field` / `cast-from-field` / `emit`
21///   expressions, and the `contracts` section.
22/// - 3 added optional language-agnostic contract metadata (`frontend`,
23///   `debug-info`, `capabilities`, `workflows`, `privacy`, `type-roles`)
24///   and `Native.intrinsic`. All schema-3 additions are omitted on the
25///   wire when absent/empty, so schema-1 and schema-2 files stay readable
26///   and round-trip byte-for-byte identically.
27pub const SUPPORTED_SCHEMA_VERSION: u32 = 3;
28
29/// The oldest schema version this consumer understands. Contracts
30/// compiled by a pre-0.33 toolchain stay readable.
31pub const MIN_SCHEMA_VERSION: u32 = 1;
32
33/// Parse a runtime-ir CBOR byte slice using the zero-copy single-pass decoder.
34pub fn from_cbor_slice(bytes: &[u8]) -> Result<MoonIr> {
35    let ir = crate::cbor_fast::decode_runtime_ir_slice(bytes)?;
36    check_schema_version(&ir)?;
37    Ok(ir)
38}
39
40/// Encode a [`MoonIr`] into RFC 8949 CBOR bytes using the direct fast encoder.
41#[must_use]
42pub fn to_cbor_vec(ir: &MoonIr) -> Vec<u8> {
43    crate::cbor_fast::encode_runtime_ir_vec(ir)
44}
45
46/// Append a [`MoonIr`]'s RFC 8949 CBOR bytes into `out`.
47pub fn write_cbor(ir: &MoonIr, out: &mut Vec<u8>) {
48    crate::cbor_fast::encode_runtime_ir_into(ir, out);
49}
50
51/// Read + parse a runtime-ir CBOR file.
52pub fn from_path(path: impl AsRef<Path>) -> Result<MoonIr> {
53    let bytes = std::fs::read(path.as_ref())?;
54    from_cbor_slice(&bytes)
55}
56
57fn check_schema_version(ir: &MoonIr) -> Result<()> {
58    if (MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION).contains(&ir.schema_version) {
59        Ok(())
60    } else {
61        Err(IrError::UnsupportedSchemaVersion {
62            actual: ir.schema_version,
63            supported: SUPPORTED_SCHEMA_VERSION,
64        })
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    fn ir_with_version(v: u32) -> MoonIr {
73        let mut ir: MoonIr = serde_json::from_str(
74            r#"{"schema-version":1,"compiler-version":"x","language-version":"x",
75                "runtime-version":"x","constructor":{"arguments":[],"initial-state":
76                {"kind":"null"},"init-ops":[],"register-operations":[],
77                "body":{"stmt":"seq","items":[]}}}"#,
78        )
79        .expect("fixture parses");
80        ir.schema_version = v;
81        ir
82    }
83
84    #[test]
85    fn accepts_every_released_schema_version() {
86        for v in MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION {
87            assert!(
88                check_schema_version(&ir_with_version(v)).is_ok(),
89                "schema {v} must stay readable"
90            );
91        }
92    }
93
94    #[test]
95    fn rejects_a_newer_schema_than_this_build_knows() {
96        let err = check_schema_version(&ir_with_version(SUPPORTED_SCHEMA_VERSION + 1));
97        assert!(err.is_err(), "a future schema must not be read as if known");
98    }
99}