Skip to main content

domainforge_core/parser/
ast_schema.rs

1//! AST Schema types for JSON serialization and schema generation.
2//!
3//! This module provides serializable versions of the AST types with JsonSchema
4//! derives for programmatic JSON Schema generation. These mirror the types in
5//! `ast.rs` but are specifically designed for schema export and JSON serialization.
6//!
7//! ## Design Rationale
8//!
9//! The schema types are separate from the internal AST types to:
10//! - Provide a stable JSON API contract that doesn't change with internal refactoring
11//! - Allow the internal AST to evolve without breaking downstream tools
12//! - Enable precise control over JSON serialization format (e.g., tagged enums)
13//! - Support JSON Schema generation via `schemars`
14//!
15//! ## Usage
16//!
17//! Convert from internal AST to schema types:
18//! ```rust,ignore
19//! use domainforge_core::parser::{parse, ast_schema};
20//!
21//! let internal_ast = parse(source)?;
22//! let schema_ast: ast_schema::Ast = internal_ast.into();
23//! let json = serde_json::to_string_pretty(&schema_ast)?;
24//! ```
25//!
26//! ## Schema Generation
27//!
28//! To regenerate the schema, run:
29//! ```bash
30//! cargo test generate_ast_schema -- --ignored --nocapture
31//! ```
32
33use serde::{Deserialize, Serialize};
34use std::collections::HashMap;
35
36#[cfg(feature = "json-schema")]
37use schemars::JsonSchema;
38
39// =========================================================================
40// File Metadata
41// =========================================================================
42
43/// Import declaration for a module file
44#[derive(Debug, Clone, Serialize, Deserialize)]
45#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
46pub struct ImportDecl {
47    pub specifier: ImportSpecifier,
48    pub from_module: String,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
53#[serde(tag = "type")]
54pub enum ImportSpecifier {
55    Named { items: Vec<ImportItem> },
56    Wildcard { alias: String },
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
61pub struct ImportItem {
62    pub name: String,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub alias: Option<String>,
65}
66
67/// File-level metadata from header annotations
68#[derive(Debug, Clone, Serialize, Deserialize, Default)]
69#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
70pub struct FileMetadata {
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub namespace: Option<String>,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub version: Option<String>,
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub owner: Option<String>,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub profile: Option<String>,
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub imports: Vec<ImportDecl>,
81}
82
83// =========================================================================
84// Policy Metadata
85// =========================================================================
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
89pub enum PolicyKind {
90    Constraint,
91    Derivation,
92    Obligation,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
97pub enum PolicyModality {
98    Obligation,
99    Prohibition,
100    Permission,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
104#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
105pub struct PolicyMetadata {
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub kind: Option<PolicyKind>,
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub modality: Option<PolicyModality>,
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub priority: Option<i32>,
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub rationale: Option<String>,
114    #[serde(default, skip_serializing_if = "Vec::is_empty")]
115    pub tags: Vec<String>,
116}
117
118// =========================================================================
119// Metric Metadata
120// =========================================================================
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
123#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
124pub enum Severity {
125    Info,
126    Warning,
127    Error,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
131#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
132pub struct MetricMetadata {
133    /// Refresh interval in ISO 8601 duration format (e.g., "PT1H")
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub refresh_interval: Option<String>,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub unit: Option<String>,
138    /// Decimal value as string for precision
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub threshold: Option<String>,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub severity: Option<Severity>,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub target: Option<String>,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub window: Option<String>,
147}
148
149// =========================================================================
150// Mapping and Projection
151// =========================================================================
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
154#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
155pub enum TargetFormat {
156    Calm,
157    Kg,
158    Sbvr,
159    Protobuf,
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
164pub struct MappingRule {
165    pub primitive_type: String,
166    pub primitive_name: String,
167    pub target_type: String,
168    #[serde(default)]
169    pub fields: HashMap<String, serde_json::Value>,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
173#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
174pub struct ProjectionOverride {
175    pub primitive_type: String,
176    pub primitive_name: String,
177    #[serde(default)]
178    pub fields: HashMap<String, serde_json::Value>,
179}
180
181// =========================================================================
182// Expression Types (for Policy and Metric)
183// =========================================================================
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
187pub struct WindowSpec {
188    pub duration: u64,
189    pub unit: String,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
194pub enum BinaryOp {
195    And,
196    Or,
197    Equal,
198    NotEqual,
199    GreaterThan,
200    LessThan,
201    GreaterThanOrEqual,
202    LessThanOrEqual,
203    Plus,
204    Minus,
205    Multiply,
206    Divide,
207    Contains,
208    StartsWith,
209    EndsWith,
210    Matches,
211    HasRole,
212    Before,
213    After,
214    During,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
219pub enum UnaryOp {
220    Not,
221    Negate,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
226pub enum Quantifier {
227    ForAll,
228    Exists,
229    ExistsUnique,
230}
231
232#[derive(Debug, Clone, Serialize, Deserialize)]
233#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
234pub enum AggregateFunction {
235    Count,
236    Sum,
237    Min,
238    Max,
239    Avg,
240}
241
242#[derive(Debug, Clone, Serialize, Deserialize)]
243#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
244#[serde(tag = "type")]
245pub enum Expression {
246    Literal {
247        value: serde_json::Value,
248    },
249    QuantityLiteral {
250        /// Decimal value as string for precision
251        value: String,
252        unit: String,
253    },
254    TimeLiteral {
255        timestamp: String,
256    },
257    IntervalLiteral {
258        start: String,
259        end: String,
260    },
261    Variable {
262        name: String,
263    },
264    GroupBy {
265        variable: String,
266        collection: Box<Expression>,
267        #[serde(skip_serializing_if = "Option::is_none")]
268        filter: Option<Box<Expression>>,
269        key: Box<Expression>,
270        condition: Box<Expression>,
271    },
272    Binary {
273        op: BinaryOp,
274        left: Box<Expression>,
275        right: Box<Expression>,
276    },
277    Unary {
278        op: UnaryOp,
279        operand: Box<Expression>,
280    },
281    Cast {
282        operand: Box<Expression>,
283        target_type: String,
284    },
285    Quantifier {
286        quantifier: Quantifier,
287        variable: String,
288        collection: Box<Expression>,
289        condition: Box<Expression>,
290    },
291    MemberAccess {
292        object: String,
293        member: String,
294    },
295    Aggregation {
296        function: AggregateFunction,
297        collection: Box<Expression>,
298        #[serde(skip_serializing_if = "Option::is_none")]
299        field: Option<String>,
300        #[serde(skip_serializing_if = "Option::is_none")]
301        filter: Option<Box<Expression>>,
302    },
303    AggregationComprehension {
304        function: AggregateFunction,
305        variable: String,
306        collection: Box<Expression>,
307        #[serde(skip_serializing_if = "Option::is_none")]
308        window: Option<WindowSpec>,
309        predicate: Box<Expression>,
310        projection: Box<Expression>,
311        #[serde(skip_serializing_if = "Option::is_none")]
312        target_unit: Option<String>,
313    },
314    /// Contextual `role<SymbolRef>` leaf (ADR-013 ยง2). Opaque until
315    /// application policy evaluation resolves it.
316    RoleReference {
317        role: String,
318    },
319}
320
321// =========================================================================
322// AST Node Types
323// =========================================================================
324
325/// Spanned AST node with source location information
326#[derive(Debug, Clone, Serialize, Deserialize)]
327#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
328pub struct SpannedAstNode {
329    pub node: AstNode,
330    /// 1-indexed line number
331    pub line: usize,
332    /// 1-indexed column number
333    pub column: usize,
334}
335
336/// AST Node types representing all SEA DSL declarations
337#[derive(Debug, Clone, Serialize, Deserialize)]
338#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
339#[serde(tag = "type")]
340pub enum AstNode {
341    /// Export wrapper for public declarations
342    Export { declaration: Box<SpannedAstNode> },
343
344    /// Entity declaration
345    Entity {
346        name: String,
347        #[serde(skip_serializing_if = "Option::is_none")]
348        version: Option<String>,
349        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
350        annotations: HashMap<String, serde_json::Value>,
351        #[serde(skip_serializing_if = "Option::is_none")]
352        domain: Option<String>,
353        /// Optional typed body `entity "X" { ... }`. Absent on legacy
354        /// bodyless entities so existing AST JSON stays byte-identical.
355        #[serde(skip_serializing_if = "Option::is_none")]
356        body: Option<EntityBody>,
357    },
358
359    /// Resource declaration
360    Resource {
361        name: String,
362        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
363        annotations: HashMap<String, serde_json::Value>,
364        #[serde(skip_serializing_if = "Option::is_none")]
365        unit_name: Option<String>,
366        #[serde(skip_serializing_if = "Option::is_none")]
367        domain: Option<String>,
368    },
369
370    /// Flow declaration - resource transfer between entities
371    Flow {
372        resource_name: String,
373        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
374        annotations: HashMap<String, serde_json::Value>,
375        from_entity: String,
376        to_entity: String,
377        #[serde(skip_serializing_if = "Option::is_none")]
378        quantity: Option<String>,
379    },
380
381    /// Pattern declaration - named regex for string validation
382    Pattern { name: String, regex: String },
383
384    /// Role declaration - participant category
385    Role {
386        name: String,
387        #[serde(skip_serializing_if = "Option::is_none")]
388        domain: Option<String>,
389    },
390
391    /// Relation declaration - predicate connecting roles
392    Relation {
393        name: String,
394        subject_role: String,
395        predicate: String,
396        object_role: String,
397        #[serde(skip_serializing_if = "Option::is_none")]
398        via_flow: Option<String>,
399    },
400
401    /// Role binding declaration - binds a previously-declared role to a
402    /// previously-declared entity
403    RoleBinding { role: String, entity: String },
404
405    /// Dimension declaration for units
406    Dimension { name: String },
407
408    /// Unit declaration - custom unit definition
409    UnitDeclaration {
410        symbol: String,
411        dimension: String,
412        /// Decimal conversion factor as string
413        factor: String,
414        base_unit: String,
415    },
416
417    /// Policy declaration - validation rule or constraint
418    Policy {
419        name: String,
420        #[serde(skip_serializing_if = "Option::is_none")]
421        version: Option<String>,
422        metadata: PolicyMetadata,
423        expression: Expression,
424    },
425
426    /// Instance declaration - entity instance with field values
427    Instance {
428        name: String,
429        entity_type: String,
430        #[serde(default)]
431        fields: HashMap<String, Expression>,
432    },
433
434    /// ConceptChange declaration - version migration
435    ConceptChange {
436        name: String,
437        from_version: String,
438        to_version: String,
439        migration_policy: String,
440        breaking_change: bool,
441    },
442
443    /// Metric declaration - observable metric
444    Metric {
445        name: String,
446        expression: Expression,
447        metadata: MetricMetadata,
448    },
449
450    /// Mapping declaration - format mapping rules
451    MappingDecl {
452        name: String,
453        target: TargetFormat,
454        rules: Vec<MappingRule>,
455    },
456
457    /// Projection declaration - output configuration
458    ProjectionDecl {
459        name: String,
460        target: TargetFormat,
461        overrides: Vec<ProjectionOverride>,
462    },
463
464    /// Cell declaration - isolated agent execution unit (cell-environment projection)
465    Cell {
466        name: String,
467        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
468        annotations: HashMap<String, serde_json::Value>,
469    },
470
471    /// SystemDependency declaration - OS package or native library
472    SystemDependency {
473        name: String,
474        #[serde(skip_serializing_if = "Option::is_none")]
475        version: Option<String>,
476        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
477        annotations: HashMap<String, serde_json::Value>,
478    },
479
480    /// Runtime declaration - language runtime or compiler toolchain
481    Runtime {
482        name: String,
483        version: String,
484        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
485        annotations: HashMap<String, serde_json::Value>,
486    },
487
488    /// Tool declaration - package manager, task runner, or developer CLI
489    Tool {
490        name: String,
491        version: String,
492        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
493        annotations: HashMap<String, serde_json::Value>,
494    },
495
496    /// DependencySet declaration - application dependency closure
497    DependencySet {
498        name: String,
499        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
500        annotations: HashMap<String, serde_json::Value>,
501    },
502
503    /// Service declaration - background or attached service
504    Service {
505        name: String,
506        #[serde(skip_serializing_if = "Option::is_none")]
507        version: Option<String>,
508        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
509        annotations: HashMap<String, serde_json::Value>,
510    },
511
512    /// Mount declaration - filesystem exposure
513    Mount {
514        name: String,
515        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
516        annotations: HashMap<String, serde_json::Value>,
517    },
518
519    /// Endpoint declaration - declared network destination
520    Endpoint {
521        name: String,
522        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
523        annotations: HashMap<String, serde_json::Value>,
524    },
525
526    /// NetworkFlow declaration - allowed communication relation
527    NetworkFlow {
528        name: String,
529        from_ref: String,
530        to_ref: String,
531        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
532        annotations: HashMap<String, serde_json::Value>,
533    },
534
535    /// Credential declaration - scoped secret requirement
536    Credential {
537        name: String,
538        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
539        annotations: HashMap<String, serde_json::Value>,
540    },
541
542    // ---- SEA application contract declarations (ADR-013) ----
543    /// Record declaration - structured DTO input/output
544    Record { declaration: RecordDecl },
545
546    /// Enum declaration - closed set of named wires
547    Enum { declaration: EnumDecl },
548
549    /// Operation declaration - inbound command/query contract
550    Operation { declaration: OperationDecl },
551}
552
553/// Typed body of an `entity` declaration (ADR-013).
554#[derive(Debug, Clone, Serialize, Deserialize)]
555#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
556pub struct EntityBody {
557    pub fields: Vec<FieldDecl>,
558}
559
560#[derive(Debug, Clone, Serialize, Deserialize)]
561#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
562pub struct FieldDecl {
563    pub is_key: bool,
564    pub name: String,
565    pub field_type: FieldType,
566    pub is_optional: bool,
567    #[serde(default, skip_serializing_if = "Vec::is_empty")]
568    pub constraints: Vec<FieldConstraintDecl>,
569    #[serde(skip_serializing_if = "Option::is_none")]
570    pub default: Option<Expression>,
571}
572
573#[derive(Debug, Clone, Serialize, Deserialize)]
574#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
575#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
576pub enum FieldType {
577    Scalar { symbol: FieldTypeRef },
578    Quantity { symbol: FieldTypeRef },
579    Ref { symbol: FieldTypeRef },
580    List { element: Box<FieldType> },
581    Named { symbol: FieldTypeRef },
582}
583
584/// Alias-qualified symbol reference inside a field type. Stored verbatim
585/// until application resolution (Task 7).
586#[derive(Debug, Clone, Serialize, Deserialize)]
587#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
588pub struct FieldTypeRef {
589    #[serde(skip_serializing_if = "Option::is_none")]
590    pub alias: Option<String>,
591    pub symbol: String,
592}
593
594#[derive(Debug, Clone, Serialize, Deserialize)]
595#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
596#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
597pub enum FieldConstraintDecl {
598    MinLength { value: u64 },
599    MaxLength { value: u64 },
600    MinItems { value: u64 },
601    MaxItems { value: u64 },
602    ExclusiveMin { value: String },
603    ExclusiveMax { value: String },
604    Min { value: String },
605    Max { value: String },
606    Pattern { symbol: String },
607}
608
609#[derive(Debug, Clone, Serialize, Deserialize)]
610#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
611pub struct RecordDecl {
612    pub name: String,
613    pub fields: Vec<FieldDecl>,
614}
615
616#[derive(Debug, Clone, Serialize, Deserialize)]
617#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
618pub struct EnumDecl {
619    pub name: String,
620    pub members: Vec<EnumMember>,
621}
622
623#[derive(Debug, Clone, Serialize, Deserialize)]
624#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
625pub struct EnumMember {
626    pub name: String,
627    pub wire: String,
628}
629
630#[derive(Debug, Clone, Serialize, Deserialize)]
631#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
632pub struct OperationDecl {
633    pub name: String,
634    pub clauses: Vec<OperationClause>,
635}
636
637/// Authored operation clause. Stored verbatim; the application module
638/// resolves and lowers each clause.
639#[derive(Debug, Clone, Serialize, Deserialize)]
640#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
641#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
642pub enum OperationClause {
643    Intent {
644        text: String,
645    },
646    Direction {
647        kind: String,
648    },
649    Actor {
650        actor: String,
651    },
652    AccessPublic,
653    AccessPolicyGoverned {
654        bindings: Vec<PolicyBinding>,
655    },
656    Input {
657        reference: String,
658    },
659    Output {
660        reference: String,
661    },
662    State {
663        reference: String,
664    },
665    Effect {
666        kind: String,
667        reference: String,
668    },
669    Transaction {
670        kind: String,
671    },
672    Failure {
673        code: String,
674        kinds: Vec<String>,
675        message: String,
676    },
677    IdempotencyKeyed {
678        field: String,
679    },
680    IdempotencyInherent,
681    IdempotencyNotApplicable {
682        reason: String,
683        explanation: String,
684    },
685    ConcurrencyUnique {
686        field: String,
687    },
688    ConcurrencyOptimistic {
689        field: String,
690    },
691    ConcurrencyReadSnapshot,
692    EvidenceOperationTrace,
693    LifecycleSynchronousRequestResponse,
694}
695
696#[derive(Debug, Clone, Serialize, Deserialize)]
697#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
698pub struct PolicyBinding {
699    pub policy: String,
700    pub enforcement_point: String,
701    pub failure_code: String,
702}
703
704// =========================================================================
705// Root AST Structure
706// =========================================================================
707
708/// Abstract Syntax Tree for SEA DSL
709#[derive(Debug, Clone, Serialize, Deserialize)]
710#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
711pub struct Ast {
712    pub metadata: FileMetadata,
713    pub declarations: Vec<SpannedAstNode>,
714}
715
716// =========================================================================
717// Schema Generation (test-only)
718// =========================================================================
719
720#[cfg(all(test, feature = "json-schema"))]
721mod tests {
722    use super::*;
723    use schemars::schema_for;
724
725    #[test]
726    #[ignore] // Run manually: cargo test generate_ast_schema -- --ignored --nocapture
727    fn generate_ast_schema() {
728        let schema = schema_for!(Ast);
729        let json = serde_json::to_string_pretty(&schema).expect("Failed to serialize schema");
730
731        // Write to schemas directory
732        let schema_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
733            .parent()
734            .unwrap()
735            .join("schemas")
736            .join("ast-v3.schema.json");
737
738        std::fs::write(&schema_path, &json).expect("Failed to write schema file");
739
740        println!("Schema written to: {}", schema_path.display());
741        println!("\n{}", json);
742    }
743}