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    /// Dimension declaration for units
402    Dimension { name: String },
403
404    /// Unit declaration - custom unit definition
405    UnitDeclaration {
406        symbol: String,
407        dimension: String,
408        /// Decimal conversion factor as string
409        factor: String,
410        base_unit: String,
411    },
412
413    /// Policy declaration - validation rule or constraint
414    Policy {
415        name: String,
416        #[serde(skip_serializing_if = "Option::is_none")]
417        version: Option<String>,
418        metadata: PolicyMetadata,
419        expression: Expression,
420    },
421
422    /// Instance declaration - entity instance with field values
423    Instance {
424        name: String,
425        entity_type: String,
426        #[serde(default)]
427        fields: HashMap<String, Expression>,
428    },
429
430    /// ConceptChange declaration - version migration
431    ConceptChange {
432        name: String,
433        from_version: String,
434        to_version: String,
435        migration_policy: String,
436        breaking_change: bool,
437    },
438
439    /// Metric declaration - observable metric
440    Metric {
441        name: String,
442        expression: Expression,
443        metadata: MetricMetadata,
444    },
445
446    /// Mapping declaration - format mapping rules
447    MappingDecl {
448        name: String,
449        target: TargetFormat,
450        rules: Vec<MappingRule>,
451    },
452
453    /// Projection declaration - output configuration
454    ProjectionDecl {
455        name: String,
456        target: TargetFormat,
457        overrides: Vec<ProjectionOverride>,
458    },
459
460    /// Cell declaration - isolated agent execution unit (cell-environment projection)
461    Cell {
462        name: String,
463        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
464        annotations: HashMap<String, serde_json::Value>,
465    },
466
467    /// SystemDependency declaration - OS package or native library
468    SystemDependency {
469        name: String,
470        #[serde(skip_serializing_if = "Option::is_none")]
471        version: Option<String>,
472        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
473        annotations: HashMap<String, serde_json::Value>,
474    },
475
476    /// Runtime declaration - language runtime or compiler toolchain
477    Runtime {
478        name: String,
479        version: String,
480        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
481        annotations: HashMap<String, serde_json::Value>,
482    },
483
484    /// Tool declaration - package manager, task runner, or developer CLI
485    Tool {
486        name: String,
487        version: String,
488        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
489        annotations: HashMap<String, serde_json::Value>,
490    },
491
492    /// DependencySet declaration - application dependency closure
493    DependencySet {
494        name: String,
495        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
496        annotations: HashMap<String, serde_json::Value>,
497    },
498
499    /// Service declaration - background or attached service
500    Service {
501        name: String,
502        #[serde(skip_serializing_if = "Option::is_none")]
503        version: Option<String>,
504        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
505        annotations: HashMap<String, serde_json::Value>,
506    },
507
508    /// Mount declaration - filesystem exposure
509    Mount {
510        name: String,
511        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
512        annotations: HashMap<String, serde_json::Value>,
513    },
514
515    /// Endpoint declaration - declared network destination
516    Endpoint {
517        name: String,
518        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
519        annotations: HashMap<String, serde_json::Value>,
520    },
521
522    /// NetworkFlow declaration - allowed communication relation
523    NetworkFlow {
524        name: String,
525        from_ref: String,
526        to_ref: String,
527        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
528        annotations: HashMap<String, serde_json::Value>,
529    },
530
531    /// Credential declaration - scoped secret requirement
532    Credential {
533        name: String,
534        #[serde(default, skip_serializing_if = "HashMap::is_empty")]
535        annotations: HashMap<String, serde_json::Value>,
536    },
537
538    // ---- SEA application contract declarations (ADR-013) ----
539    /// Record declaration - structured DTO input/output
540    Record { declaration: RecordDecl },
541
542    /// Enum declaration - closed set of named wires
543    Enum { declaration: EnumDecl },
544
545    /// Operation declaration - inbound command/query contract
546    Operation { declaration: OperationDecl },
547}
548
549/// Typed body of an `entity` declaration (ADR-013).
550#[derive(Debug, Clone, Serialize, Deserialize)]
551#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
552pub struct EntityBody {
553    pub fields: Vec<FieldDecl>,
554}
555
556#[derive(Debug, Clone, Serialize, Deserialize)]
557#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
558pub struct FieldDecl {
559    pub is_key: bool,
560    pub name: String,
561    pub field_type: FieldType,
562    pub is_optional: bool,
563    #[serde(default, skip_serializing_if = "Vec::is_empty")]
564    pub constraints: Vec<FieldConstraintDecl>,
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub default: Option<Expression>,
567}
568
569#[derive(Debug, Clone, Serialize, Deserialize)]
570#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
571#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
572pub enum FieldType {
573    Scalar { symbol: FieldTypeRef },
574    Quantity { symbol: FieldTypeRef },
575    Ref { symbol: FieldTypeRef },
576    List { element: Box<FieldType> },
577    Named { symbol: FieldTypeRef },
578}
579
580/// Alias-qualified symbol reference inside a field type. Stored verbatim
581/// until application resolution (Task 7).
582#[derive(Debug, Clone, Serialize, Deserialize)]
583#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
584pub struct FieldTypeRef {
585    #[serde(skip_serializing_if = "Option::is_none")]
586    pub alias: Option<String>,
587    pub symbol: String,
588}
589
590#[derive(Debug, Clone, Serialize, Deserialize)]
591#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
592#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
593pub enum FieldConstraintDecl {
594    MinLength { value: u64 },
595    MaxLength { value: u64 },
596    MinItems { value: u64 },
597    MaxItems { value: u64 },
598    ExclusiveMin { value: String },
599    ExclusiveMax { value: String },
600    Min { value: String },
601    Max { value: String },
602    Pattern { symbol: String },
603}
604
605#[derive(Debug, Clone, Serialize, Deserialize)]
606#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
607pub struct RecordDecl {
608    pub name: String,
609    pub fields: Vec<FieldDecl>,
610}
611
612#[derive(Debug, Clone, Serialize, Deserialize)]
613#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
614pub struct EnumDecl {
615    pub name: String,
616    pub members: Vec<EnumMember>,
617}
618
619#[derive(Debug, Clone, Serialize, Deserialize)]
620#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
621pub struct EnumMember {
622    pub name: String,
623    pub wire: String,
624}
625
626#[derive(Debug, Clone, Serialize, Deserialize)]
627#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
628pub struct OperationDecl {
629    pub name: String,
630    pub clauses: Vec<OperationClause>,
631}
632
633/// Authored operation clause. Stored verbatim; the application module
634/// resolves and lowers each clause.
635#[derive(Debug, Clone, Serialize, Deserialize)]
636#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
637#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
638pub enum OperationClause {
639    Intent {
640        text: String,
641    },
642    Direction {
643        kind: String,
644    },
645    Actor {
646        actor: String,
647    },
648    AccessPublic,
649    AccessPolicyGoverned {
650        bindings: Vec<PolicyBinding>,
651    },
652    Input {
653        reference: String,
654    },
655    Output {
656        reference: String,
657    },
658    State {
659        reference: String,
660    },
661    Effect {
662        kind: String,
663        reference: String,
664    },
665    Transaction {
666        kind: String,
667    },
668    Failure {
669        code: String,
670        kinds: Vec<String>,
671        message: String,
672    },
673    IdempotencyKeyed {
674        field: String,
675    },
676    IdempotencyInherent,
677    IdempotencyNotApplicable {
678        reason: String,
679        explanation: String,
680    },
681    ConcurrencyUnique {
682        field: String,
683    },
684    ConcurrencyOptimistic {
685        field: String,
686    },
687    ConcurrencyReadSnapshot,
688    EvidenceOperationTrace,
689    LifecycleSynchronousRequestResponse,
690}
691
692#[derive(Debug, Clone, Serialize, Deserialize)]
693#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
694pub struct PolicyBinding {
695    pub policy: String,
696    pub enforcement_point: String,
697    pub failure_code: String,
698}
699
700// =========================================================================
701// Root AST Structure
702// =========================================================================
703
704/// Abstract Syntax Tree for SEA DSL
705#[derive(Debug, Clone, Serialize, Deserialize)]
706#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
707pub struct Ast {
708    pub metadata: FileMetadata,
709    pub declarations: Vec<SpannedAstNode>,
710}
711
712// =========================================================================
713// Schema Generation (test-only)
714// =========================================================================
715
716#[cfg(all(test, feature = "json-schema"))]
717mod tests {
718    use super::*;
719    use schemars::schema_for;
720
721    #[test]
722    #[ignore] // Run manually: cargo test generate_ast_schema -- --ignored --nocapture
723    fn generate_ast_schema() {
724        let schema = schema_for!(Ast);
725        let json = serde_json::to_string_pretty(&schema).expect("Failed to serialize schema");
726
727        // Write to schemas directory
728        let schema_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
729            .parent()
730            .unwrap()
731            .join("schemas")
732            .join("ast-v3.schema.json");
733
734        std::fs::write(&schema_path, &json).expect("Failed to write schema file");
735
736        println!("Schema written to: {}", schema_path.display());
737        println!("\n{}", json);
738    }
739}