Skip to main content

rustev_eval/
doc.rs

1//! Implements the contract's document protocol for eval-owned documents.
2
3/// `Document` (and optionally `Identified`) for a type with a `schema`
4/// field, as the contract's own documents do.
5macro_rules! eval_document {
6    ($ty:ty, $schema:expr, $limits:expr) => {
7        impl rustev_contract::Document for $ty {
8            const SCHEMA: &'static str = $schema;
9            const LIMITS: rustev_contract::bounded::ParseLimits = $limits;
10            fn schema(&self) -> &str {
11                &self.schema
12            }
13        }
14    };
15    ($ty:ty, $schema:expr, $limits:expr, $id:ty) => {
16        $crate::doc::eval_document!($ty, $schema, $limits);
17        impl rustev_contract::Identified for $ty {
18            type Id = $id;
19            fn wrap(digest: String) -> $id {
20                <$id>::parse(&digest).expect("a tagged digest is an identity")
21            }
22        }
23    };
24}
25
26pub(crate) use eval_document;
27
28/// One emitted schema: the file name it is committed under and its
29/// canonical bytes.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct EmittedSchema {
32    pub file: String,
33    pub bytes: Vec<u8>,
34}
35
36/// What every emitted schema says about itself (spec 072, 3.3).
37const COMMENT: &str = "Descriptive, derived from the types the bounded parser reads; the parser \
38is the only authority on validity. Byte, depth and count bounds are recorded in \
39x-rustev-parse-limits (a string length here counts characters, the parser counts bytes), and \
40rules the document's own checks apply (ranges, names, declared metrics) are stated in field \
41descriptions, not enforced here.";
42
43/// The JSON Schema of `T` for its document version, as spec 027 3.2.2
44/// emits the contract's documents: draft 2020-12, `schema` fixed to the
45/// version, the parse limits the bounded parser enforces recorded as
46/// `x-rustev-parse-limits`, canonical bytes.
47fn emit<T: schemars::JsonSchema + rustev_contract::Document>() -> EmittedSchema {
48    let generator = schemars::generate::SchemaSettings::draft2020_12().into_generator();
49    let root = generator.into_root_schema_for::<T>();
50    let mut v = serde_json::to_value(&root).expect("a schema is JSON");
51    v["title"] = T::SCHEMA.into();
52    v["$comment"] = COMMENT.into();
53    // Every document is an object with a `schema` member; a schema without
54    // `properties` is a defect in the derivation, which the committed-bytes
55    // test reports by name.
56    v.get_mut("properties")
57        .and_then(|p| p.as_object_mut())
58        .unwrap_or_else(|| panic!("{}: the derived schema has no properties", T::SCHEMA))
59        .insert(
60            "schema".into(),
61            serde_json::json!({ "type": "string", "const": T::SCHEMA }),
62        );
63    let l = T::LIMITS;
64    v["x-rustev-parse-limits"] = serde_json::json!({
65        "max_bytes": l.max_bytes,
66        "max_depth": l.max_depth,
67        "max_string_bytes": l.max_string_bytes,
68        "max_collection_len": l.max_collection_len,
69        "max_total_values": l.max_total_values,
70        "max_number_bytes": l.max_number_bytes,
71        "allow_fractional_numbers": l.allow_fractional_numbers,
72    });
73    let file = format!("{}.schema.json", T::SCHEMA.replace('/', "-"));
74    let bytes = rustev_contract::canonical::canonical_value_bytes(&v)
75        .expect("a schema has canonical bytes");
76    EmittedSchema { file, bytes }
77}
78
79/// The JSON Schemas (draft 2020-12) of spec 029's host documents,
80/// `rustev.repeat-config/1`, `rustev.baseline/1`, `rustev.selection-gate/1`
81/// and `rustev.selection/1` (spec 072, 3.3), sorted by file name. Emission is
82/// pure and deterministic; the schemas are descriptive and the bounded
83/// parsers stay the only authority on validity.
84pub fn document_schemas() -> Vec<EmittedSchema> {
85    let mut out = vec![
86        emit::<crate::repeat_config::RepeatConfig>(),
87        emit::<crate::baseline::Baseline>(),
88        emit::<crate::selection::SelectionGate>(),
89        emit::<crate::selection::Selection>(),
90    ];
91    out.sort_by(|a, b| a.file.cmp(&b.file));
92    out
93}