Skip to main content

adam_lang/checking/
metadata.rs

1//! Exports and imports an application's whole, callback-free checking environment.
2//!
3//! The host explicitly exports after registration. Save the returned UTF-8 JSON
4//! using your application's file-replacement policy; no editor launches the host.
5//! Pin both identity fields when importing, and regenerate the saved artifact and
6//! update its revision whenever the checking contract changes. An offline reader
7//! cannot detect an unexported registration change under an unchanged revision.
8//!
9//! ```rust
10//! use adam_lang::{TypeRegistry, checking::metadata::{
11//!     EnvironmentIdentity, export_checking_metadata, import_checking_metadata,
12//! }};
13//! let identity = EnvironmentIdentity {
14//!     application: "my.application".into(),
15//!     revision: "1".into(),
16//! };
17//! let text = export_checking_metadata(
18//!     &TypeRegistry::new(), &cel_parser::OpLookup::new(), &identity,
19//! )?;
20//! let environment = import_checking_metadata(&text, &identity)?;
21//! assert!(environment.cel().resolve_type("i32").is_some());
22//! # Ok::<(), Box<dyn std::error::Error>>(())
23//! ```
24//!
25//! Imports replace, rather than extend, bundled library environments. Artifacts
26//! contain catalog-local IDs, never native bindings, callbacks, or runtime type
27//! descriptors. Nominal record recursion is valid; structural shapes are trees.
28//! Artifacts require schema version 2, checker contract `cel-adam-checking/2`,
29//! and `environment: { cel: ..., cellTypes: [...] }`. The CEL description requires
30//! explicit `typeFunctions` signatures; `cellTypes` lists Adam-registered leaf
31//! IDs from that catalog. Regenerate older artifacts; import never infers type
32//! applications or storage membership.
33
34use crate::{TypeRegistry, checking::AdamCheckingEnvironment, checking_environment};
35use cel_parser::{
36    OpLookup,
37    checking::{
38        Capabilities, CheckingDescription, CheckingEnvironment, CheckingType, FunctionDescription,
39        MetadataError, OperationDescription, RecordDescription, TypeDescription,
40        TypeFunctionDescription,
41    },
42};
43use serde::{Deserialize, Serialize};
44
45/// The supported whole-environment schema version.
46const SCHEMA_VERSION: u32 = 2;
47/// The compatible CEL and Adam static-checking contract.
48const CHECKER_CONTRACT: &str = "cel-adam-checking/2";
49/// The maximum UTF-8 artifact size, in bytes.
50const MAX_BYTES: usize = 8 * 1024 * 1024;
51/// The maximum JSON container nesting, including the envelope.
52const MAX_DEPTH: usize = 64;
53
54/// An application-owned, nonempty identity and checking-contract revision.
55///
56/// Import compares both strings exactly. Whitespace-only identities are invalid.
57///
58/// # Examples
59/// See the [module example](self).
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct EnvironmentIdentity {
62    /// The stable application identifier.
63    pub application: String,
64    /// The application-supplied checking-contract revision.
65    pub revision: String,
66}
67
68/// Exports effective registrations without invoking application callbacks.
69///
70/// Identical effective registrations in the same process produce identical bytes.
71/// The catalog's documented host-identity tie-break does not promise identical
72/// bytes across independently built executables.
73///
74/// # Errors
75/// Rejects empty identities, opaque registrations lacking complete metadata,
76/// invalid descriptions, and artifacts exceeding 8 MiB or 64 JSON containers
77/// of nesting. Errors identify the category and a corrective action.
78///
79/// - Complexity: Environment projection costs plus O(n) time and space for
80///   description and JSON size n.
81///
82/// # Examples
83/// See the [module example](self).
84pub fn export_checking_metadata(
85    types: &TypeRegistry,
86    lookup: &OpLookup,
87    identity: &EnvironmentIdentity,
88) -> Result<String, MetadataError> {
89    validate_identity(identity)?;
90    let environment = checking_environment(types, lookup).map_err(|error| {
91        MetadataError(format!(
92            "environment registration: {error}; use complete persistent type, operation, \
93             function and record registrations, then regenerate metadata"
94        ))
95    })?;
96    let artifact = Artifact {
97        schema_version: SCHEMA_VERSION,
98        checker_contract: CHECKER_CONTRACT.into(),
99        application: Application {
100            id: identity.application.clone(),
101            revision: identity.revision.clone(),
102        },
103        environment: WireAdamEnvironment {
104            cel: WireEnvironment::from(environment.cel().description()),
105            cell_types: environment.cell_types().to_vec(),
106        },
107    };
108    let text = serde_json::to_string_pretty(&artifact).map_err(|error| json_error(&error))?;
109    validate_bounds(&text)?;
110    Ok(text)
111}
112
113/// Imports a fully validated environment pinned to the expected application contract.
114///
115/// The result contains no executable registrations and supplies the whole
116/// effective environment, without adding standard or geometry libraries.
117/// Unknown fields, duplicate fields, and incomplete shapes are errors.
118///
119/// # Errors
120/// Rejects malformed JSON, artifacts exceeding 8 MiB or 64 nested JSON
121/// containers, unsupported schema/checker contracts, empty or mismatched
122/// application identities/revisions, and invalid shared checking descriptions.
123/// No environment is published on failure.
124///
125/// - Complexity: Expected O(n + m log m) time and O(n) space for combined
126///   artifact/expected-identity size n and m cell membership IDs.
127///
128/// # Examples
129/// See the [module example](self).
130pub fn import_checking_metadata(
131    text: &str,
132    expected: &EnvironmentIdentity,
133) -> Result<AdamCheckingEnvironment, MetadataError> {
134    validate_identity(expected)?;
135    validate_bounds(text)?;
136    let artifact: Artifact = serde_json::from_str(text).map_err(|error| json_error(&error))?;
137    if artifact.schema_version != SCHEMA_VERSION {
138        return Err(MetadataError(format!(
139            "schemaVersion: expected {SCHEMA_VERSION}, received {}; regenerate metadata \
140             or use a compatible server",
141            artifact.schema_version
142        )));
143    }
144    if artifact.checker_contract != CHECKER_CONTRACT {
145        return Err(MetadataError(format!(
146            "checkerContract: expected {CHECKER_CONTRACT:?}, received {:?}; regenerate \
147             metadata or use a compatible server",
148            artifact.checker_contract
149        )));
150    }
151    if artifact.application.id.trim().is_empty() || artifact.application.id != expected.application
152    {
153        return Err(MetadataError(format!(
154            "application.id: expected {:?}, received {:?}; correct the expected application \
155             setting or regenerate metadata",
156            expected.application, artifact.application.id
157        )));
158    }
159    if artifact.application.revision.trim().is_empty()
160        || artifact.application.revision != expected.revision
161    {
162        return Err(MetadataError(format!(
163            "application.revision: expected {:?}, received {:?}; correct the expected revision \
164             setting or regenerate stale metadata",
165            expected.revision, artifact.application.revision
166        )));
167    }
168    let cel = CheckingEnvironment::from_description(artifact.environment.cel.into()).map_err(|error| {
169        MetadataError(format!(
170            "environment description: {error}; correct host registrations and regenerate metadata"
171        ))
172    })?;
173    AdamCheckingEnvironment::from_parts(cel, artifact.environment.cell_types).map_err(|error| {
174        MetadataError(format!(
175            "environment membership: {error}; correct host registrations and regenerate metadata"
176        ))
177    })
178}
179
180/// Rejects empty application identity settings.
181///
182/// - Complexity: O(n) time for the identity's n bytes.
183fn validate_identity(identity: &EnvironmentIdentity) -> Result<(), MetadataError> {
184    for (field, value) in [
185        ("application", identity.application.as_str()),
186        ("revision", identity.revision.as_str()),
187    ] {
188        if value.trim().is_empty() {
189            return Err(MetadataError(format!(
190                "expected.{field}: must be nonempty; correct the identity setting and regenerate metadata"
191            )));
192        }
193    }
194    Ok(())
195}
196
197/// Formats JSON schema failures with the decoder's field and line information.
198///
199/// - Complexity: O(n) time and result space for n error-message bytes.
200fn json_error(error: &serde_json::Error) -> MetadataError {
201    MetadataError(format!(
202        "JSON/schema: {error}; correct the artifact or regenerate metadata with a compatible exporter"
203    ))
204}
205
206/// Bounds input before recursive JSON decoding, ignoring delimiters inside strings.
207///
208/// Syntax validity remains the JSON decoder's responsibility.
209///
210/// - Complexity: O(n) time and O(1) space for n text bytes.
211fn validate_bounds(text: &str) -> Result<(), MetadataError> {
212    if text.len() > MAX_BYTES {
213        return Err(MetadataError(format!(
214            "JSON size: exceeds {MAX_BYTES} bytes; reduce registrations and regenerate metadata"
215        )));
216    }
217    let mut depth = 0usize;
218    let mut in_string = false;
219    let mut escaped = false;
220    // Count JSON containers before allowing the recursive decoder to allocate.
221    for byte in text.bytes() {
222        if in_string {
223            if escaped {
224                escaped = false;
225            } else if byte == b'\\' {
226                escaped = true;
227            } else if byte == b'"' {
228                in_string = false;
229            }
230        } else {
231            match byte {
232                b'"' => in_string = true,
233                b'{' | b'[' => {
234                    depth += 1;
235                    if depth > MAX_DEPTH {
236                        return Err(MetadataError(format!(
237                            "JSON depth: exceeds {MAX_DEPTH} containers; simplify shapes and regenerate metadata"
238                        )));
239                    }
240                }
241                b'}' | b']' => depth = depth.saturating_sub(1),
242                _ => {}
243            }
244        }
245    }
246    Ok(())
247}
248
249/// Owns the strict versioned whole-environment wire envelope.
250#[derive(Serialize, Deserialize)]
251#[serde(rename_all = "camelCase", deny_unknown_fields)]
252struct Artifact {
253    schema_version: u32,
254    checker_contract: String,
255    application: Application,
256    environment: WireAdamEnvironment,
257}
258
259/// Owns the artifact header's application identity.
260#[derive(Serialize, Deserialize)]
261#[serde(deny_unknown_fields)]
262struct Application {
263    id: String,
264    revision: String,
265}
266
267/// Encodes the required CEL catalog and explicit Adam storage membership.
268#[derive(Serialize, Deserialize)]
269#[serde(deny_unknown_fields)]
270struct WireAdamEnvironment {
271    cel: WireEnvironment,
272    #[serde(rename = "cellTypes")]
273    cell_types: Vec<u32>,
274}
275
276/// Encodes shared descriptions with explicit shape tags and strict field checking.
277///
278/// This transport representation has no checking or type-resolution semantics.
279#[derive(Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281struct WireEnvironment {
282    builtin_contract: u32,
283    types: Vec<WireLeaf>,
284    operations: Vec<WireOperation>,
285    records: Vec<WireRecord>,
286    functions: Vec<WireFunction>,
287    #[serde(rename = "typeFunctions")]
288    type_functions: Vec<WireTypeFunction>,
289}
290
291/// Encodes an explicit nominal type application with complete argument shapes.
292#[derive(Serialize, Deserialize)]
293#[serde(deny_unknown_fields)]
294struct WireTypeFunction {
295    name: String,
296    arguments: Vec<WireShape>,
297    result: WireShape,
298}
299
300/// Encodes one nominal identity and its shared capabilities.
301#[derive(Serialize, Deserialize)]
302#[serde(deny_unknown_fields)]
303struct WireLeaf {
304    id: u32,
305    name: String,
306    aliases: Vec<String>,
307    #[serde(deserialize_with = "required_option")]
308    primitive: Option<String>,
309    capabilities: WireCapabilities,
310    #[serde(deserialize_with = "required_option")]
311    range_element: Option<u32>,
312}
313
314/// Decodes an explicit nullable fact without accepting an omitted field.
315///
316/// - Complexity: The held type's deserialization time and space.
317fn required_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
318where
319    D: serde::Deserializer<'de>,
320    T: Deserialize<'de>,
321{
322    Option::deserialize(deserializer)
323}
324
325/// Encodes callback-free value capabilities without defaulting missing facts.
326#[derive(Serialize, Deserialize)]
327#[serde(deny_unknown_fields)]
328struct WireCapabilities {
329    default_available: bool,
330    cloneable: bool,
331    comparable: bool,
332    debuggable: bool,
333}
334
335/// Encodes an ordered overload, including receiver-first member operands.
336#[derive(Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338struct WireOperation {
339    name: String,
340    operands: Vec<WireShape>,
341    result: WireShape,
342}
343
344/// Encodes the required fields and nominal result of a record constructor.
345#[derive(Serialize, Deserialize)]
346#[serde(deny_unknown_fields)]
347struct WireRecord {
348    name: String,
349    ty: u32,
350    fields: Vec<(String, WireShape)>,
351}
352
353/// Encodes a named function value's nominal marker.
354#[derive(Serialize, Deserialize)]
355#[serde(deny_unknown_fields)]
356struct WireFunction {
357    name: String,
358    marker: u32,
359}
360
361/// Encodes only complete owned shapes, never `Any` or runtime descriptors.
362#[derive(Serialize, Deserialize)]
363#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
364enum WireShape {
365    Leaf {
366        id: u32,
367    },
368    Array {
369        element: Box<WireShape>,
370    },
371    Tuple {
372        elements: Vec<WireShape>,
373    },
374    Callable {
375        parameters: Vec<WireShape>,
376        result: Box<WireShape>,
377    },
378}
379
380impl From<&CheckingType> for WireShape {
381    /// Copies a shared shape into its explicitly tagged transport representation.
382    ///
383    /// - Complexity: O(n) time and result space for n shape nodes.
384    fn from(shape: &CheckingType) -> Self {
385        match shape {
386            CheckingType::Leaf(id) => Self::Leaf { id: *id },
387            CheckingType::Array(element) => Self::Array {
388                element: Box::new(Self::from(element.as_ref())),
389            },
390            CheckingType::Tuple(elements) => Self::Tuple {
391                elements: elements.iter().map(Self::from).collect(),
392            },
393            CheckingType::Callable(parameters, result) => Self::Callable {
394                parameters: parameters.iter().map(Self::from).collect(),
395                result: Box::new(Self::from(result.as_ref())),
396            },
397        }
398    }
399}
400
401impl From<WireShape> for CheckingType {
402    /// Transfers a transport shape to the shared validator without assigning runtime identity.
403    ///
404    /// - Complexity: O(n) time and result space for n shape nodes.
405    fn from(shape: WireShape) -> Self {
406        match shape {
407            WireShape::Leaf { id } => Self::Leaf(id),
408            WireShape::Array { element } => Self::Array(Box::new(Self::from(*element))),
409            WireShape::Tuple { elements } => {
410                Self::Tuple(elements.into_iter().map(Self::from).collect())
411            }
412            WireShape::Callable { parameters, result } => Self::Callable(
413                parameters.into_iter().map(Self::from).collect(),
414                Box::new(Self::from(*result)),
415            ),
416        }
417    }
418}
419
420impl From<&CheckingDescription> for WireEnvironment {
421    /// Copies shared facts into an independently owned wire document.
422    ///
423    /// - Complexity: O(n) time and space for description size n.
424    fn from(description: &CheckingDescription) -> Self {
425        Self {
426            builtin_contract: description.builtin_contract,
427            types: description
428                .types
429                .iter()
430                .map(|leaf| WireLeaf {
431                    id: leaf.id,
432                    name: leaf.name.clone(),
433                    aliases: leaf.aliases.clone(),
434                    primitive: leaf.primitive.clone(),
435                    capabilities: WireCapabilities {
436                        default_available: leaf.capabilities.default_available,
437                        cloneable: leaf.capabilities.cloneable,
438                        comparable: leaf.capabilities.comparable,
439                        debuggable: leaf.capabilities.debuggable,
440                    },
441                    range_element: leaf.range_element,
442                })
443                .collect(),
444            operations: description
445                .operations
446                .iter()
447                .map(|operation| WireOperation {
448                    name: operation.name.clone(),
449                    operands: operation.operands.iter().map(WireShape::from).collect(),
450                    result: WireShape::from(&operation.result),
451                })
452                .collect(),
453            records: description
454                .records
455                .iter()
456                .map(|record| WireRecord {
457                    name: record.name.clone(),
458                    ty: record.ty,
459                    fields: record
460                        .fields
461                        .iter()
462                        .map(|(name, shape)| (name.clone(), WireShape::from(shape)))
463                        .collect(),
464                })
465                .collect(),
466            functions: description
467                .functions
468                .iter()
469                .map(|function| WireFunction {
470                    name: function.name.clone(),
471                    marker: function.marker,
472                })
473                .collect(),
474            type_functions: description
475                .type_functions
476                .iter()
477                .map(|signature| WireTypeFunction {
478                    name: signature.name.clone(),
479                    arguments: signature.arguments.iter().map(WireShape::from).collect(),
480                    result: WireShape::from(&signature.result),
481                })
482                .collect(),
483        }
484    }
485}
486
487impl From<WireEnvironment> for CheckingDescription {
488    /// Transfers all wire facts to the single shared description validator.
489    ///
490    /// - Complexity: O(n) time and space for description size n.
491    fn from(wire: WireEnvironment) -> Self {
492        Self {
493            builtin_contract: wire.builtin_contract,
494            types: wire
495                .types
496                .into_iter()
497                .map(|leaf| TypeDescription {
498                    id: leaf.id,
499                    name: leaf.name,
500                    aliases: leaf.aliases,
501                    primitive: leaf.primitive,
502                    capabilities: Capabilities {
503                        default_available: leaf.capabilities.default_available,
504                        cloneable: leaf.capabilities.cloneable,
505                        comparable: leaf.capabilities.comparable,
506                        debuggable: leaf.capabilities.debuggable,
507                    },
508                    range_element: leaf.range_element,
509                })
510                .collect(),
511            operations: wire
512                .operations
513                .into_iter()
514                .map(|operation| OperationDescription {
515                    name: operation.name,
516                    operands: operation
517                        .operands
518                        .into_iter()
519                        .map(CheckingType::from)
520                        .collect(),
521                    result: operation.result.into(),
522                })
523                .collect(),
524            records: wire
525                .records
526                .into_iter()
527                .map(|record| RecordDescription {
528                    name: record.name,
529                    ty: record.ty,
530                    fields: record
531                        .fields
532                        .into_iter()
533                        .map(|(name, shape)| (name, shape.into()))
534                        .collect(),
535                })
536                .collect(),
537            functions: wire
538                .functions
539                .into_iter()
540                .map(|function| FunctionDescription {
541                    name: function.name,
542                    marker: function.marker,
543                })
544                .collect(),
545            type_functions: wire
546                .type_functions
547                .into_iter()
548                .map(|signature| TypeFunctionDescription {
549                    name: signature.name,
550                    arguments: signature
551                        .arguments
552                        .into_iter()
553                        .map(CheckingType::from)
554                        .collect(),
555                    result: signature.result.into(),
556                })
557                .collect(),
558        }
559    }
560}