Skip to main content

domainforge_core/parser/
ast.rs

1use crate::graph::Graph;
2use crate::parser::error::{ParseError, ParseResult};
3use crate::parser::{ParseOptions, Rule, SeaParser};
4use crate::patterns::Pattern;
5use crate::policy::{
6    AggregateFunction, BinaryOp, Expression, Policy, PolicyKind as CorePolicyKind,
7    PolicyModality as CorePolicyModality, Quantifier as PolicyQuantifier, UnaryOp, WindowSpec,
8};
9use crate::primitives::{ConceptChange, Entity, Flow, RelationType, Resource, Role, Severity};
10use crate::units::unit_from_string;
11use crate::SemanticVersion;
12use chrono::Duration;
13use pest::iterators::{Pair, Pairs};
14use pest::{Parser, Span};
15use rust_decimal::prelude::ToPrimitive;
16use rust_decimal::Decimal;
17use serde::{Deserialize, Serialize};
18use serde_json::json;
19use serde_json::Value as JsonValue;
20use std::collections::HashMap;
21
22/// File-level metadata from header annotations
23#[derive(Debug, Clone, PartialEq, Default)]
24pub struct FileMetadata {
25    pub namespace: Option<String>,
26    pub version: Option<String>,
27    pub owner: Option<String>,
28    pub profile: Option<String>,
29    pub imports: Vec<ImportDecl>,
30}
31
32/// Import declaration for a module file
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct ImportDecl {
35    pub specifier: ImportSpecifier,
36    pub from_module: String,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub enum ImportSpecifier {
41    Named(Vec<ImportItem>),
42    Wildcard(String),
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct ImportItem {
47    pub name: String,
48    pub alias: Option<String>,
49}
50
51/// Policy metadata
52#[derive(Debug, Clone, PartialEq)]
53pub struct PolicyMetadata {
54    pub kind: Option<PolicyKind>,
55    pub modality: Option<PolicyModality>,
56    pub priority: Option<i32>,
57    pub rationale: Option<String>,
58    pub tags: Vec<String>,
59}
60
61#[derive(Debug, Clone, PartialEq)]
62pub enum PolicyKind {
63    Constraint,
64    Derivation,
65    Obligation,
66}
67
68impl std::fmt::Display for PolicyKind {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            PolicyKind::Constraint => write!(f, "Constraint"),
72            PolicyKind::Derivation => write!(f, "Derivation"),
73            PolicyKind::Obligation => write!(f, "Obligation"),
74        }
75    }
76}
77
78#[derive(Debug, Clone, PartialEq)]
79pub enum PolicyModality {
80    Obligation,
81    Prohibition,
82    Permission,
83}
84
85impl std::fmt::Display for PolicyModality {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        match self {
88            PolicyModality::Obligation => write!(f, "Obligation"),
89            PolicyModality::Prohibition => write!(f, "Prohibition"),
90            PolicyModality::Permission => write!(f, "Permission"),
91        }
92    }
93}
94
95/// Metric declaration AST node
96#[derive(Debug, Clone, PartialEq)]
97pub struct MetricMetadata {
98    pub refresh_interval: Option<Duration>,
99    pub unit: Option<String>,
100    pub threshold: Option<Decimal>,
101    pub severity: Option<Severity>,
102    pub target: Option<Decimal>,
103    pub window: Option<Duration>,
104}
105
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107pub enum TargetFormat {
108    Calm,
109    Kg,
110    Sbvr,
111    Protobuf,
112}
113
114impl std::fmt::Display for TargetFormat {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            TargetFormat::Calm => write!(f, "CALM"),
118            TargetFormat::Kg => write!(f, "KG"),
119            TargetFormat::Sbvr => write!(f, "SBVR"),
120            TargetFormat::Protobuf => write!(f, "Protobuf"),
121        }
122    }
123}
124
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub struct MappingRule {
127    pub primitive_type: String,
128    pub primitive_name: String,
129    pub target_type: String,
130    pub fields: HashMap<String, JsonValue>,
131}
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct ProjectionOverride {
135    pub primitive_type: String,
136    pub primitive_name: String,
137    pub fields: HashMap<String, JsonValue>,
138}
139
140#[derive(Debug, Clone, PartialEq)]
141pub struct Spanned<T> {
142    pub node: T,
143    pub line: usize,
144    pub column: usize,
145}
146
147#[derive(Debug, Clone, PartialEq)]
148pub struct Ast {
149    pub metadata: FileMetadata,
150    pub declarations: Vec<Spanned<AstNode>>,
151}
152
153// ---- SEA application contract AST extensions (ADR-013) ----
154// These types carry authored application declarations verbatim; semantic
155// resolution and validation happen in the application module. Field clauses
156// are stored in authored order so partial operations preserve evidence for
157// APP001 diagnostic construction.
158
159/// Typed body of an `entity` declaration: a sequence of fields.
160#[derive(Debug, Clone, PartialEq)]
161pub struct EntityBody {
162    pub fields: Vec<FieldDecl>,
163}
164
165/// One field of a `record` or typed `entity` body.
166#[derive(Debug, Clone, PartialEq)]
167pub struct FieldDecl {
168    pub is_key: bool,
169    pub name: String,
170    pub field_type: FieldType,
171    pub is_optional: bool,
172    pub constraints: Vec<FieldConstraintDecl>,
173    /// Authored `default <literal>` value, type-checked during application
174    /// validation. Stored as an `Expression` for round-trip parity, though
175    /// only the `literal` grammar branch is accepted.
176    pub default: Option<Expression>,
177}
178
179/// Type of a record/entity field. Closes the v0.1 type model: scalars,
180/// `quantity<Unit>`, `ref<Target>`, `list<...>`, and named symbol references.
181#[derive(Debug, Clone, PartialEq)]
182pub enum FieldType {
183    Scalar(FieldTypeRef),
184    Quantity(FieldTypeRef),
185    Ref(FieldTypeRef),
186    List(Box<FieldType>),
187    Named(FieldTypeRef),
188}
189
190/// A possibly alias-qualified symbol reference: `Order` or `alias.Order`.
191/// Used by `quantity<>`, `ref<>`, and named field types.
192#[derive(Debug, Clone, PartialEq, Eq, Hash)]
193pub struct FieldTypeRef {
194    pub alias: Option<String>,
195    pub symbol: String,
196}
197
198/// Authored field constraint; validation maps these to the closed enum and
199/// type-checks the operand against the field type.
200#[derive(Debug, Clone, PartialEq)]
201pub enum FieldConstraintDecl {
202    MinLength(u64),
203    MaxLength(u64),
204    MinItems(u64),
205    MaxItems(u64),
206    ExclusiveMin(Decimal),
207    ExclusiveMax(Decimal),
208    Min(Decimal),
209    Max(Decimal),
210    /// `pattern <symbol_ref>` - the symbol reference text is stored verbatim
211    /// and resolved against the closure's pattern declarations.
212    Pattern(String),
213}
214
215#[derive(Debug, Clone, PartialEq)]
216pub struct RecordDecl {
217    pub name: String,
218    pub fields: Vec<FieldDecl>,
219}
220
221#[derive(Debug, Clone, PartialEq)]
222pub struct EnumDecl {
223    pub name: String,
224    pub members: Vec<EnumMember>,
225}
226
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct EnumMember {
229    pub name: String,
230    pub wire: String,
231}
232
233#[derive(Debug, Clone, PartialEq)]
234pub struct OperationDecl {
235    pub name: String,
236    /// Authored clauses in source order. Validation (APP001) reports missing,
237    /// duplicate, or out-of-order clauses against this list; it never
238    /// re-orders it.
239    pub clauses: Vec<OperationClause>,
240}
241
242/// One authored operation clause. Strings carry the raw symbol_ref / kind
243/// text; the application module resolves and lowers them.
244#[derive(Debug, Clone, PartialEq)]
245pub enum OperationClause {
246    Intent(String),
247    Direction {
248        kind: String,
249    },
250    Actor {
251        actor: String,
252    },
253    AccessPublic,
254    AccessPolicyGoverned {
255        bindings: Vec<PolicyBinding>,
256    },
257    Input {
258        reference: String,
259    },
260    Output {
261        reference: String,
262    },
263    State {
264        reference: String,
265    },
266    Effect {
267        kind: String,
268        reference: String,
269    },
270    Transaction {
271        kind: String,
272    },
273    Failure {
274        code: String,
275        kinds: Vec<String>,
276        message: String,
277    },
278    IdempotencyKeyed {
279        field: String,
280    },
281    IdempotencyInherent,
282    IdempotencyNotApplicable {
283        reason: String,
284        explanation: String,
285    },
286    ConcurrencyUnique {
287        field: String,
288    },
289    ConcurrencyOptimistic {
290        field: String,
291    },
292    ConcurrencyReadSnapshot,
293    EvidenceOperationTrace,
294    LifecycleSynchronousRequestResponse,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct PolicyBinding {
299    /// Raw symbol_ref text (`order_total_within_limit` or `alias.foo`).
300    pub policy: String,
301    /// `precondition` | `invariant` | `postcondition` (validated in APP007).
302    pub enforcement_point: String,
303    pub failure_code: String,
304}
305
306/// AST Node types
307#[derive(Debug, Clone, PartialEq)]
308pub enum AstNode {
309    Export(Box<Spanned<AstNode>>),
310    Entity {
311        name: String,
312        version: Option<String>,
313        annotations: HashMap<String, JsonValue>,
314        domain: Option<String>,
315        /// Optional typed body `entity "X" { ... }`. Absent for legacy
316        /// bodyless entities.
317        body: Option<EntityBody>,
318    },
319    Resource {
320        name: String,
321        annotations: HashMap<String, JsonValue>,
322        unit_name: Option<String>,
323        domain: Option<String>,
324    },
325    Record(RecordDecl),
326    Enum(EnumDecl),
327    Operation(OperationDecl),
328    Flow {
329        resource_name: String,
330        annotations: HashMap<String, JsonValue>,
331        from_entity: String,
332        to_entity: String,
333        quantity: Option<Decimal>,
334    },
335    Pattern {
336        name: String,
337        regex: String,
338    },
339    Role {
340        name: String,
341        domain: Option<String>,
342    },
343    Relation {
344        name: String,
345        subject_role: String,
346        predicate: String,
347        object_role: String,
348        via_flow: Option<String>,
349    },
350    RoleBinding {
351        role: String,
352        entity: String,
353    },
354    Dimension {
355        name: String,
356    },
357    UnitDeclaration {
358        symbol: String,
359        dimension: String,
360        factor: Decimal,
361        base_unit: String,
362    },
363    Policy {
364        name: String,
365        version: Option<String>,
366        metadata: PolicyMetadata,
367        expression: Expression,
368    },
369    Instance {
370        name: String,
371        entity_type: String,
372        fields: HashMap<String, Expression>,
373    },
374    ConceptChange {
375        name: String,
376        from_version: String,
377        to_version: String,
378        migration_policy: String,
379        breaking_change: bool,
380    },
381    Metric {
382        name: String,
383        expression: Expression,
384        metadata: MetricMetadata,
385    },
386    MappingDecl {
387        name: String,
388        target: TargetFormat,
389        rules: Vec<MappingRule>,
390    },
391    ProjectionDecl {
392        name: String,
393        target: TargetFormat,
394        overrides: Vec<ProjectionOverride>,
395    },
396    Cell {
397        name: String,
398        annotations: HashMap<String, JsonValue>,
399    },
400    SystemDependency {
401        name: String,
402        version: Option<String>,
403        annotations: HashMap<String, JsonValue>,
404    },
405    Runtime {
406        name: String,
407        version: String,
408        annotations: HashMap<String, JsonValue>,
409    },
410    Tool {
411        name: String,
412        version: String,
413        annotations: HashMap<String, JsonValue>,
414    },
415    DependencySet {
416        name: String,
417        annotations: HashMap<String, JsonValue>,
418    },
419    Service {
420        name: String,
421        version: Option<String>,
422        annotations: HashMap<String, JsonValue>,
423    },
424    Mount {
425        name: String,
426        annotations: HashMap<String, JsonValue>,
427    },
428    Endpoint {
429        name: String,
430        annotations: HashMap<String, JsonValue>,
431    },
432    NetworkFlow {
433        name: String,
434        from_ref: String,
435        to_ref: String,
436        annotations: HashMap<String, JsonValue>,
437    },
438    Credential {
439        name: String,
440        annotations: HashMap<String, JsonValue>,
441    },
442}
443
444/// Parse source code into an AST
445pub fn parse_source(source: &str) -> ParseResult<Ast> {
446    let pairs = SeaParser::parse(Rule::program, source)?;
447    build_ast(pairs)
448}
449
450/// Build AST from pest pairs
451fn build_ast(pairs: Pairs<Rule>) -> ParseResult<Ast> {
452    let mut metadata = FileMetadata::default();
453    let mut declarations = Vec::new();
454
455    for pair in pairs {
456        match pair.as_rule() {
457            Rule::program => {
458                for inner in pair.into_inner() {
459                    match inner.as_rule() {
460                        Rule::file_header => {
461                            metadata = parse_file_header(inner)?;
462                        }
463                        Rule::declaration => {
464                            for decl in inner.into_inner() {
465                                let node = parse_declaration(decl)?;
466                                declarations.push(node);
467                            }
468                        }
469                        Rule::EOI => {}
470                        _ => {}
471                    }
472                }
473            }
474            Rule::EOI => {}
475            _ => {}
476        }
477    }
478
479    Ok(Ast {
480        metadata,
481        declarations,
482    })
483}
484
485/// Parse file header annotations
486fn parse_file_header(pair: Pair<Rule>) -> ParseResult<FileMetadata> {
487    let mut metadata = FileMetadata::default();
488
489    for annotation in pair.into_inner() {
490        match annotation.as_rule() {
491            Rule::annotation => {
492                let mut inner = annotation.into_inner();
493                let name = inner.next().ok_or_else(|| {
494                    ParseError::GrammarError("Expected annotation name".to_string())
495                })?;
496                let value = inner.next().ok_or_else(|| {
497                    ParseError::GrammarError("Expected annotation value".to_string())
498                })?;
499
500                let name_str = name.as_str().to_lowercase();
501                let value_str = parse_string_literal(value)?;
502
503                match name_str.as_str() {
504                    "namespace" => metadata.namespace = Some(value_str),
505                    "version" => metadata.version = Some(value_str),
506                    "owner" => metadata.owner = Some(value_str),
507                    "profile" => metadata.profile = Some(value_str),
508                    _ => {
509                        return Err(ParseError::GrammarError(format!(
510                            "Unknown annotation: {}",
511                            name_str
512                        )))
513                    }
514                }
515            }
516            Rule::import_decl => {
517                metadata.imports.push(parse_import_decl(annotation)?);
518            }
519            _ => {}
520        }
521    }
522
523    Ok(metadata)
524}
525
526/// Parse a single declaration
527fn parse_declaration(pair: Pair<Rule>) -> ParseResult<Spanned<AstNode>> {
528    let (line, column) = pair.line_col();
529    let node = match pair.as_rule() {
530        Rule::export_decl => {
531            let mut inner = pair.into_inner();
532            let wrapped = inner.next().ok_or_else(|| {
533                ParseError::GrammarError("Expected declaration after export".to_string())
534            })?;
535            let node = parse_declaration(wrapped)?;
536            Ok(AstNode::Export(Box::new(node)))
537        }
538        Rule::declaration_inner => {
539            let inner = pair
540                .into_inner()
541                .next()
542                .ok_or_else(|| ParseError::GrammarError("Empty declaration".to_string()))?;
543            // Recursively call parse_declaration, but we need to unwrap the result if we want to avoid double spanning?
544            // Actually declaration_inner is just a wrapper. The inner parse_declaration returns Spanned<AstNode>.
545            // We should just return that directly.
546            return parse_declaration(inner);
547        }
548        Rule::dimension_decl => parse_dimension(pair),
549        Rule::unit_decl => parse_unit_declaration(pair),
550        Rule::record_decl => parse_record(pair),
551        Rule::enum_decl => parse_enum(pair),
552        Rule::operation_decl => parse_operation(pair),
553        Rule::entity_decl => parse_entity(pair),
554        Rule::resource_decl => parse_resource(pair),
555        Rule::flow_decl => parse_flow(pair),
556        Rule::pattern_decl => parse_pattern(pair),
557        Rule::role_decl => parse_role(pair),
558        Rule::role_binding_decl => parse_role_binding(pair),
559        Rule::relation_decl => parse_relation(pair),
560        Rule::instance_decl => parse_instance(pair),
561        Rule::policy_decl => parse_policy(pair),
562        Rule::concept_change_decl => parse_concept_change(pair),
563        Rule::metric_decl => parse_metric(pair),
564        Rule::mapping_decl => parse_mapping(pair),
565        Rule::projection_decl => parse_projection(pair),
566        Rule::cell_decl => parse_cell(pair),
567        Rule::system_dependency_decl => parse_system_dependency(pair),
568        Rule::runtime_decl => parse_runtime(pair),
569        Rule::tool_decl => parse_tool(pair),
570        Rule::dependency_set_decl => parse_dependency_set(pair),
571        Rule::service_decl => parse_service(pair),
572        Rule::mount_decl => parse_mount(pair),
573        Rule::endpoint_decl => parse_endpoint(pair),
574        Rule::network_flow_decl => parse_network_flow(pair),
575        Rule::credential_decl => parse_credential(pair),
576        _ => Err(ParseError::GrammarError(format!(
577            "Unexpected rule: {:?}",
578            pair.as_rule()
579        ))),
580    }?;
581
582    Ok(Spanned { node, line, column })
583}
584
585fn parse_import_decl(pair: Pair<Rule>) -> ParseResult<ImportDecl> {
586    let mut inner = pair.into_inner();
587    let specifier_pair = inner
588        .next()
589        .ok_or_else(|| ParseError::GrammarError("Missing import specifier".to_string()))?;
590    let from_pair = inner
591        .next()
592        .ok_or_else(|| ParseError::GrammarError("Missing import source".to_string()))?;
593
594    let specifier = match specifier_pair.as_rule() {
595        Rule::import_specifier | Rule::import_named | Rule::import_wildcard => {
596            parse_import_specifier(specifier_pair)?
597        }
598        _ => {
599            return Err(ParseError::GrammarError(format!(
600                "Unexpected import specifier: {:?}",
601                specifier_pair.as_rule()
602            )))
603        }
604    };
605
606    Ok(ImportDecl {
607        specifier,
608        from_module: parse_string_literal(from_pair)?,
609    })
610}
611
612fn parse_import_specifier(pair: Pair<Rule>) -> ParseResult<ImportSpecifier> {
613    match pair.as_rule() {
614        Rule::import_wildcard => {
615            let mut inner = pair.into_inner();
616            let alias = parse_identifier(inner.next().ok_or_else(|| {
617                ParseError::GrammarError("Expected alias for wildcard import".to_string())
618            })?)?;
619            Ok(ImportSpecifier::Wildcard(alias))
620        }
621        // `import_specifier` wraps exactly one of `import_named` /
622        // `import_wildcard`; descend one level so we iterate the actual
623        // `import_item` pairs (or the wildcard alias) below.
624        Rule::import_specifier => {
625            let inner = pair
626                .into_inner()
627                .next()
628                .ok_or_else(|| ParseError::GrammarError("Empty import specifier".to_string()))?;
629            parse_import_specifier(inner)
630        }
631        Rule::import_named => {
632            let mut items = Vec::new();
633            for item in pair.into_inner() {
634                if item.as_rule() == Rule::import_item {
635                    items.push(parse_import_item(item)?);
636                }
637            }
638            Ok(ImportSpecifier::Named(items))
639        }
640        _ => Err(ParseError::GrammarError(
641            "Invalid import specifier".to_string(),
642        )),
643    }
644}
645
646fn parse_import_item(pair: Pair<Rule>) -> ParseResult<ImportItem> {
647    let mut inner = pair.into_inner();
648    let name_pair = inner
649        .next()
650        .ok_or_else(|| ParseError::GrammarError("Expected import item name".to_string()))?;
651    let alias = inner.next().map(parse_identifier).transpose()?;
652
653    Ok(ImportItem {
654        name: parse_identifier(name_pair)?,
655        alias,
656    })
657}
658
659/// Parse dimension declaration
660fn parse_dimension(pair: Pair<Rule>) -> ParseResult<AstNode> {
661    let mut inner = pair.into_inner();
662    let name = parse_string_literal(
663        inner
664            .next()
665            .ok_or_else(|| ParseError::GrammarError("Expected dimension name".to_string()))?,
666    )?;
667
668    Ok(AstNode::Dimension { name })
669}
670
671/// Parse unit declaration
672fn parse_unit_declaration(pair: Pair<Rule>) -> ParseResult<AstNode> {
673    let mut inner = pair.into_inner();
674
675    let symbol = parse_string_literal(
676        inner
677            .next()
678            .ok_or_else(|| ParseError::GrammarError("Expected unit symbol".to_string()))?,
679    )?;
680
681    let dimension = parse_string_literal(
682        inner
683            .next()
684            .ok_or_else(|| ParseError::GrammarError("Expected dimension name".to_string()))?,
685    )?;
686
687    let factor_pair = inner
688        .next()
689        .ok_or_else(|| ParseError::GrammarError("Expected factor".to_string()))?;
690    let factor = parse_decimal(factor_pair)?;
691
692    let base_unit = parse_string_literal(
693        inner
694            .next()
695            .ok_or_else(|| ParseError::GrammarError("Expected base unit".to_string()))?,
696    )?;
697
698    Ok(AstNode::UnitDeclaration {
699        symbol,
700        dimension,
701        factor,
702        base_unit,
703    })
704}
705
706// ---- SEA application contract parsers (ADR-013 §2) ----
707
708fn parse_entity_body(pair: Pair<Rule>) -> ParseResult<EntityBody> {
709    let mut fields = Vec::new();
710    for inner in pair.into_inner() {
711        if inner.as_rule() == Rule::entity_field {
712            let mut field_inner = inner.into_inner();
713            let mut is_key = false;
714            let mut next = field_inner.next().ok_or_else(|| {
715                ParseError::GrammarError("Expected entity_field content".to_string())
716            })?;
717            if next.as_rule() == Rule::key_marker {
718                is_key = true;
719                next = field_inner.next().ok_or_else(|| {
720                    ParseError::GrammarError("Expected field_decl after key".to_string())
721                })?;
722            }
723            if next.as_rule() != Rule::field_decl {
724                return Err(ParseError::GrammarError(format!(
725                    "Expected field_decl in entity body, got {:?}",
726                    next.as_rule()
727                )));
728            }
729            fields.push(parse_field_decl(next, is_key)?);
730        }
731    }
732    Ok(EntityBody { fields })
733}
734
735fn parse_record(pair: Pair<Rule>) -> ParseResult<AstNode> {
736    let mut inner = pair.into_inner();
737    let name = parse_identifier(
738        inner
739            .next()
740            .ok_or_else(|| ParseError::GrammarError("Expected record name".to_string()))?,
741    )?;
742    let body_pair = inner
743        .next()
744        .ok_or_else(|| ParseError::GrammarError("Expected record body".to_string()))?;
745    let mut fields = Vec::new();
746    for field_pair in body_pair.into_inner() {
747        if field_pair.as_rule() == Rule::field_decl {
748            fields.push(parse_field_decl(field_pair, false)?);
749        }
750    }
751    Ok(AstNode::Record(RecordDecl { name, fields }))
752}
753
754fn parse_enum(pair: Pair<Rule>) -> ParseResult<AstNode> {
755    let mut inner = pair.into_inner();
756    let name = parse_identifier(
757        inner
758            .next()
759            .ok_or_else(|| ParseError::GrammarError("Expected enum name".to_string()))?,
760    )?;
761    let mut members = Vec::new();
762    for member_pair in inner {
763        if member_pair.as_rule() != Rule::enum_member {
764            continue;
765        }
766        let mut member_inner = member_pair.into_inner();
767        let member_name =
768            parse_identifier(member_inner.next().ok_or_else(|| {
769                ParseError::GrammarError("Expected enum member name".to_string())
770            })?)?;
771        let wire = parse_string_literal(member_inner.next().ok_or_else(|| {
772            ParseError::GrammarError("Expected enum member wire value".to_string())
773        })?)?;
774        members.push(EnumMember {
775            name: member_name,
776            wire,
777        });
778    }
779    Ok(AstNode::Enum(EnumDecl { name, members }))
780}
781
782fn parse_operation(pair: Pair<Rule>) -> ParseResult<AstNode> {
783    let mut inner = pair.into_inner();
784    let name = parse_identifier(
785        inner
786            .next()
787            .ok_or_else(|| ParseError::GrammarError("Expected operation name".to_string()))?,
788    )?;
789    let body_pair = inner
790        .next()
791        .ok_or_else(|| ParseError::GrammarError("Expected operation body".to_string()))?;
792    let mut clauses = Vec::new();
793    for clause_pair in body_pair.into_inner() {
794        if let Some(clause) = parse_operation_clause(clause_pair)? {
795            clauses.push(clause);
796        }
797    }
798    Ok(AstNode::Operation(OperationDecl { name, clauses }))
799}
800
801fn parse_operation_clause(pair: Pair<Rule>) -> ParseResult<Option<OperationClause>> {
802    let inner = pair
803        .into_inner()
804        .next()
805        .ok_or_else(|| ParseError::GrammarError("Empty operation clause".to_string()))?;
806    let clause = match inner.as_rule() {
807        Rule::intent_clause => {
808            let text =
809                parse_string_literal(inner.into_inner().next().ok_or_else(|| {
810                    ParseError::GrammarError("Expected intent text".to_string())
811                })?)?;
812            OperationClause::Intent(text)
813        }
814        Rule::direction_clause => {
815            let kind = inner
816                .into_inner()
817                .next()
818                .ok_or_else(|| ParseError::GrammarError("Expected direction kind".to_string()))?
819                .as_str()
820                .trim()
821                .to_string();
822            OperationClause::Direction { kind }
823        }
824        Rule::actor_clause => {
825            // `^"anonymous"` is a literal and produces no sub-pair; only
826            // the `symbol_ref` branch yields an inner pair.
827            let actor = match inner.into_inner().next() {
828                Some(p) => parse_symbol_ref_text(p)?.trim().to_string(),
829                None => "anonymous".to_string(),
830            };
831            OperationClause::Actor { actor }
832        }
833        Rule::access_clause => {
834            // `^"public"` is a literal and produces no sub-pair; only the
835            // `policy_governed_clause` branch yields an inner pair.
836            let access_inner = match inner.into_inner().next() {
837                Some(p) => p,
838                None => return Ok(Some(OperationClause::AccessPublic)),
839            };
840            match access_inner.as_rule() {
841                Rule::policy_governed_clause => {
842                    let mut bindings = Vec::new();
843                    for binding_pair in access_inner.into_inner() {
844                        if binding_pair.as_rule() != Rule::policy_binding {
845                            continue;
846                        }
847                        let mut b = binding_pair.into_inner();
848                        let policy = parse_symbol_ref_text(b.next().ok_or_else(|| {
849                            ParseError::GrammarError("Expected policy in binding".to_string())
850                        })?)?
851                        .trim()
852                        .to_string();
853                        let enforcement_point = b
854                            .next()
855                            .ok_or_else(|| {
856                                ParseError::GrammarError("Expected enforcement point".to_string())
857                            })?
858                            .as_str()
859                            .trim()
860                            .to_string();
861                        // skip `fails with`
862                        let failure_code = parse_identifier(b.next().ok_or_else(|| {
863                            ParseError::GrammarError("Expected failure code".to_string())
864                        })?)?;
865                        bindings.push(PolicyBinding {
866                            policy,
867                            enforcement_point,
868                            failure_code,
869                        });
870                    }
871                    OperationClause::AccessPolicyGoverned { bindings }
872                }
873                _ => OperationClause::AccessPublic,
874            }
875        }
876        Rule::input_clause => OperationClause::Input {
877            reference: parse_symbol_ref_text(inner.into_inner().next().ok_or_else(|| {
878                ParseError::GrammarError("Expected input reference".to_string())
879            })?)?
880            .trim()
881            .to_string(),
882        },
883        Rule::output_clause => OperationClause::Output {
884            reference: parse_symbol_ref_text(inner.into_inner().next().ok_or_else(|| {
885                ParseError::GrammarError("Expected output reference".to_string())
886            })?)?
887            .trim()
888            .to_string(),
889        },
890        Rule::state_clause => OperationClause::State {
891            reference: parse_symbol_ref_text(inner.into_inner().next().ok_or_else(|| {
892                ParseError::GrammarError("Expected state reference".to_string())
893            })?)?
894            .trim()
895            .to_string(),
896        },
897        Rule::effect_clause => {
898            let mut e = inner.into_inner();
899            let kind = e
900                .next()
901                .ok_or_else(|| ParseError::GrammarError("Expected effect kind".to_string()))?
902                .as_str()
903                .trim()
904                .to_string();
905            let reference =
906                parse_symbol_ref_text(e.next().ok_or_else(|| {
907                    ParseError::GrammarError("Expected effect target".to_string())
908                })?)?
909                .trim()
910                .to_string();
911            OperationClause::Effect { kind, reference }
912        }
913        Rule::transaction_clause => OperationClause::Transaction {
914            kind: inner
915                .into_inner()
916                .next()
917                .ok_or_else(|| ParseError::GrammarError("Expected transaction kind".to_string()))?
918                .as_str()
919                .trim()
920                .to_string(),
921        },
922        Rule::failure_clause => {
923            let mut f = inner.into_inner();
924            let code =
925                parse_identifier(f.next().ok_or_else(|| {
926                    ParseError::GrammarError("Expected failure code".to_string())
927                })?)?;
928            // skip `for`
929            let mut kinds = Vec::new();
930            let mut message = String::new();
931            for part in f {
932                match part.as_rule() {
933                    Rule::failure_kind => kinds.push(part.as_str().trim().to_string()),
934                    Rule::string_literal => {
935                        message = parse_string_literal(part)?;
936                    }
937                    _ => {}
938                }
939            }
940            OperationClause::Failure {
941                code,
942                kinds,
943                message,
944            }
945        }
946        Rule::idempotency_clause => {
947            // `^"inherent"` is a literal and produces no sub-pair.
948            let body = match inner.into_inner().next() {
949                Some(p) => p,
950                None => return Ok(Some(OperationClause::IdempotencyInherent)),
951            };
952            match body.as_rule() {
953                Rule::idempotency_keyed => OperationClause::IdempotencyKeyed {
954                    field: parse_identifier(body.into_inner().next().ok_or_else(|| {
955                        ParseError::GrammarError("Expected keyed_by field".to_string())
956                    })?)?,
957                },
958                Rule::not_applicable_value => {
959                    let mut n = body.into_inner();
960                    let reason = n
961                        .next()
962                        .ok_or_else(|| ParseError::GrammarError("Expected na_reason".to_string()))?
963                        .as_str()
964                        .trim()
965                        .to_string();
966                    let explanation = parse_string_literal(n.next().ok_or_else(|| {
967                        ParseError::GrammarError("Expected na explanation".to_string())
968                    })?)?;
969                    OperationClause::IdempotencyNotApplicable {
970                        reason,
971                        explanation,
972                    }
973                }
974                _ => OperationClause::IdempotencyInherent,
975            }
976        }
977        Rule::concurrency_clause => {
978            // `^"read_snapshot"` is a literal and produces no sub-pair.
979            let body = match inner.into_inner().next() {
980                Some(p) => p,
981                None => return Ok(Some(OperationClause::ConcurrencyReadSnapshot)),
982            };
983            match body.as_rule() {
984                Rule::concurrency_unique => OperationClause::ConcurrencyUnique {
985                    field: parse_identifier(body.into_inner().next().ok_or_else(|| {
986                        ParseError::GrammarError("Expected unique_key field".to_string())
987                    })?)?,
988                },
989                Rule::concurrency_optimistic => OperationClause::ConcurrencyOptimistic {
990                    field: parse_identifier(body.into_inner().next().ok_or_else(|| {
991                        ParseError::GrammarError("Expected optimistic_version field".to_string())
992                    })?)?,
993                },
994                _ => OperationClause::ConcurrencyReadSnapshot,
995            }
996        }
997        Rule::evidence_clause => OperationClause::EvidenceOperationTrace,
998        Rule::lifecycle_clause => OperationClause::LifecycleSynchronousRequestResponse,
999        other => {
1000            return Err(ParseError::GrammarError(format!(
1001                "Unexpected operation clause rule: {:?}",
1002                other
1003            )))
1004        }
1005    };
1006    Ok(Some(clause))
1007}
1008
1009fn parse_field_decl(pair: Pair<Rule>, is_key: bool) -> ParseResult<FieldDecl> {
1010    let mut inner = pair.into_inner();
1011    let name = parse_identifier(
1012        inner
1013            .next()
1014            .ok_or_else(|| ParseError::GrammarError("Expected field name".to_string()))?,
1015    )?;
1016    let field_type_pair = inner
1017        .next()
1018        .ok_or_else(|| ParseError::GrammarError("Expected field type".to_string()))?;
1019    let field_type = parse_field_type(field_type_pair)?;
1020
1021    let mut is_optional = false;
1022    let mut constraints: Vec<FieldConstraintDecl> = Vec::new();
1023    let mut default: Option<Expression> = None;
1024
1025    for part in inner {
1026        match part.as_rule() {
1027            Rule::optional_marker => is_optional = true,
1028            Rule::field_constraints => {
1029                for c in part.into_inner() {
1030                    if c.as_rule() == Rule::field_constraint {
1031                        constraints.push(parse_field_constraint(c)?);
1032                    }
1033                }
1034            }
1035            Rule::field_default => {
1036                let lit = c_to_lit(part.into_inner().next().ok_or_else(|| {
1037                    ParseError::GrammarError("Expected default literal".to_string())
1038                })?)?;
1039                default = Some(lit);
1040            }
1041            _ => {}
1042        }
1043    }
1044
1045    Ok(FieldDecl {
1046        is_key,
1047        name,
1048        field_type,
1049        is_optional,
1050        constraints,
1051        default,
1052    })
1053}
1054
1055fn parse_field_type(pair: Pair<Rule>) -> ParseResult<FieldType> {
1056    let inner = pair
1057        .into_inner()
1058        .next()
1059        .ok_or_else(|| ParseError::GrammarError("Empty field type".to_string()))?;
1060    Ok(match inner.as_rule() {
1061        Rule::scalar_type => FieldType::Scalar(FieldTypeRef {
1062            alias: None,
1063            symbol: inner.as_str().to_string(),
1064        }),
1065        Rule::quantity_type => FieldType::Quantity(parse_symbol_ref_pair(
1066            inner.into_inner().next().ok_or_else(|| {
1067                ParseError::GrammarError("Expected unit in quantity<>".to_string())
1068            })?,
1069        )?),
1070        Rule::ref_type => FieldType::Ref(parse_symbol_ref_pair(
1071            inner
1072                .into_inner()
1073                .next()
1074                .ok_or_else(|| ParseError::GrammarError("Expected target in ref<>".to_string()))?,
1075        )?),
1076        Rule::list_type => {
1077            let elem = inner.into_inner().next().ok_or_else(|| {
1078                ParseError::GrammarError("Expected list element type".to_string())
1079            })?;
1080            FieldType::List(Box::new(parse_element_type(elem)?))
1081        }
1082        Rule::named_type => FieldType::Named(parse_symbol_ref_pair(
1083            inner
1084                .into_inner()
1085                .next()
1086                .ok_or_else(|| ParseError::GrammarError("Expected named type".to_string()))?,
1087        )?),
1088        other => {
1089            return Err(ParseError::GrammarError(format!(
1090                "Unexpected field_type rule: {:?}",
1091                other
1092            )))
1093        }
1094    })
1095}
1096
1097fn parse_element_type(pair: Pair<Rule>) -> ParseResult<FieldType> {
1098    let inner = pair
1099        .into_inner()
1100        .next()
1101        .ok_or_else(|| ParseError::GrammarError("Empty element type".to_string()))?;
1102    Ok(match inner.as_rule() {
1103        Rule::scalar_type => FieldType::Scalar(FieldTypeRef {
1104            alias: None,
1105            symbol: inner.as_str().to_string(),
1106        }),
1107        Rule::quantity_type => FieldType::Quantity(parse_symbol_ref_pair(
1108            inner.into_inner().next().ok_or_else(|| {
1109                ParseError::GrammarError("Expected unit in quantity<>".to_string())
1110            })?,
1111        )?),
1112        Rule::ref_type => FieldType::Ref(parse_symbol_ref_pair(
1113            inner
1114                .into_inner()
1115                .next()
1116                .ok_or_else(|| ParseError::GrammarError("Expected target in ref<>".to_string()))?,
1117        )?),
1118        Rule::named_type => FieldType::Named(parse_symbol_ref_pair(
1119            inner
1120                .into_inner()
1121                .next()
1122                .ok_or_else(|| ParseError::GrammarError("Expected named type".to_string()))?,
1123        )?),
1124        other => {
1125            return Err(ParseError::GrammarError(format!(
1126                "Unexpected element_type rule: {:?}",
1127                other
1128            )))
1129        }
1130    })
1131}
1132
1133fn parse_field_constraint(pair: Pair<Rule>) -> ParseResult<FieldConstraintDecl> {
1134    let mut inner = pair.into_inner();
1135    let head = inner
1136        .next()
1137        .ok_or_else(|| ParseError::GrammarError("Empty field constraint".to_string()))?;
1138    let value_pair = inner
1139        .next()
1140        .ok_or_else(|| ParseError::GrammarError("Expected constraint operand".to_string()))?;
1141    Ok(match head.as_rule() {
1142        Rule::fc_min_length => FieldConstraintDecl::MinLength(parse_unsigned_int(value_pair)?),
1143        Rule::fc_max_length => FieldConstraintDecl::MaxLength(parse_unsigned_int(value_pair)?),
1144        Rule::fc_min_items => FieldConstraintDecl::MinItems(parse_unsigned_int(value_pair)?),
1145        Rule::fc_max_items => FieldConstraintDecl::MaxItems(parse_unsigned_int(value_pair)?),
1146        Rule::fc_exclusive_min => FieldConstraintDecl::ExclusiveMin(parse_decimal(value_pair)?),
1147        Rule::fc_exclusive_max => FieldConstraintDecl::ExclusiveMax(parse_decimal(value_pair)?),
1148        Rule::fc_min => FieldConstraintDecl::Min(parse_decimal(value_pair)?),
1149        Rule::fc_max => FieldConstraintDecl::Max(parse_decimal(value_pair)?),
1150        Rule::fc_pattern => FieldConstraintDecl::Pattern(parse_symbol_ref_text(value_pair)?),
1151        other => {
1152            return Err(ParseError::GrammarError(format!(
1153                "Unexpected field constraint head rule: {:?}",
1154                other
1155            )))
1156        }
1157    })
1158}
1159
1160fn parse_unsigned_int(pair: Pair<Rule>) -> ParseResult<u64> {
1161    pair.as_str().parse::<u64>().map_err(|_| {
1162        ParseError::GrammarError(format!("Invalid unsigned integer: {}", pair.as_str()))
1163    })
1164}
1165
1166/// Reconstruct the raw text of a `symbol_ref` (`Order` or `alias.Order`).
1167/// Stored verbatim until resolution; the application module resolves it.
1168/// We reconstruct from inner atomic `identifier` pairs because `symbol_ref`'s
1169/// `as_str()` can include trailing implicit whitespace in some contexts.
1170fn parse_symbol_ref_text(pair: Pair<Rule>) -> ParseResult<String> {
1171    match pair.as_rule() {
1172        Rule::symbol_ref => {
1173            let mut parts: Vec<String> = Vec::new();
1174            for p in pair.into_inner() {
1175                if p.as_rule() == Rule::identifier {
1176                    parts.push(p.as_str().to_string());
1177                }
1178            }
1179            Ok(parts.join("."))
1180        }
1181        Rule::identifier => Ok(pair.as_str().to_string()),
1182        other => Err(ParseError::GrammarError(format!(
1183            "Unexpected symbol_ref rule: {:?}",
1184            other
1185        ))),
1186    }
1187}
1188
1189/// Parse a `symbol_ref` pair into an `alias.symbol` (or bare `symbol`).
1190fn parse_symbol_ref_pair(pair: Pair<Rule>) -> ParseResult<FieldTypeRef> {
1191    let mut inner = pair.into_inner();
1192    let first = parse_identifier(inner.next().ok_or_else(|| {
1193        ParseError::GrammarError("Expected identifier in symbol_ref".to_string())
1194    })?)?;
1195    if let Some(second) = inner.next() {
1196        Ok(FieldTypeRef {
1197            alias: Some(first),
1198            symbol: parse_identifier(second)?,
1199        })
1200    } else {
1201        Ok(FieldTypeRef {
1202            alias: None,
1203            symbol: first,
1204        })
1205    }
1206}
1207
1208/// Map a `Rule::literal` pair to a literal-shaped `Expression`. Only the
1209/// grammar's `literal` branch is accepted for field defaults.
1210fn c_to_lit(pair: Pair<Rule>) -> ParseResult<Expression> {
1211    parse_literal_expr(pair)
1212}
1213
1214/// Parse entity declaration
1215fn parse_entity(pair: Pair<Rule>) -> ParseResult<AstNode> {
1216    let mut inner = pair.into_inner();
1217
1218    let name = parse_name(
1219        inner
1220            .next()
1221            .ok_or_else(|| ParseError::GrammarError("Expected entity name".to_string()))?,
1222    )?;
1223
1224    let mut version = None;
1225    let mut annotations = HashMap::new();
1226    let mut domain = None;
1227    let mut body: Option<EntityBody> = None;
1228
1229    for part in inner {
1230        match part.as_rule() {
1231            Rule::version => {
1232                version = Some(part.as_str().to_string());
1233            }
1234            Rule::entity_body => {
1235                body = Some(parse_entity_body(part)?);
1236            }
1237            Rule::entity_annotation => {
1238                let mut annotation_inner = part.into_inner();
1239                let key_pair = annotation_inner
1240                    .next()
1241                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;
1242
1243                match key_pair.as_rule() {
1244                    Rule::ea_replaces => {
1245                        let target_name =
1246                            parse_name(annotation_inner.next().ok_or_else(|| {
1247                                ParseError::GrammarError("Expected name in replaces".to_string())
1248                            })?)?;
1249                        // Check for optional version
1250                        let mut target_version = None;
1251                        if let Some(next) = annotation_inner.next() {
1252                            if next.as_rule() == Rule::version {
1253                                target_version = Some(next.as_str().to_string());
1254                            }
1255                        }
1256
1257                        let value = if let Some(v) = target_version {
1258                            format!("{} v{}", target_name, v)
1259                        } else {
1260                            target_name
1261                        };
1262                        annotations.insert("replaces".to_string(), JsonValue::String(value));
1263                    }
1264                    Rule::ea_changes => {
1265                        let array_pair = annotation_inner.next().ok_or_else(|| {
1266                            ParseError::GrammarError("Expected string array in changes".to_string())
1267                        })?;
1268                        let mut changes = Vec::new();
1269                        for item in array_pair.into_inner() {
1270                            changes.push(parse_string_literal(item)?);
1271                        }
1272                        annotations.insert(
1273                            "changes".to_string(),
1274                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
1275                        );
1276                    }
1277                    Rule::identifier => {
1278                        let key = parse_identifier(key_pair)?.to_lowercase();
1279                        let value_pair = annotation_inner.next().ok_or_else(|| {
1280                            ParseError::GrammarError("Expected annotation value".to_string())
1281                        })?;
1282                        let value = parse_annotation_value(value_pair)?;
1283                        annotations.insert(key, value);
1284                    }
1285                    _ => {
1286                        return Err(ParseError::GrammarError(format!(
1287                            "Unexpected flow annotation: {}",
1288                            key_pair.as_str()
1289                        )));
1290                    }
1291                }
1292            }
1293            Rule::in_keyword => {
1294                // Skip "in"
1295            }
1296            Rule::identifier => {
1297                // This must be the domain
1298                domain = Some(parse_identifier(part)?);
1299            }
1300            _ => {}
1301        }
1302    }
1303
1304    Ok(AstNode::Entity {
1305        name,
1306        version,
1307        annotations,
1308        domain,
1309        body,
1310    })
1311}
1312
1313/// Parse concept change declaration
1314fn parse_concept_change(pair: Pair<Rule>) -> ParseResult<AstNode> {
1315    let mut inner = pair.into_inner();
1316
1317    let name =
1318        parse_name(inner.next().ok_or_else(|| {
1319            ParseError::GrammarError("Expected concept change name".to_string())
1320        })?)?;
1321
1322    let mut from_version = String::new();
1323    let mut to_version = String::new();
1324    let mut migration_policy = String::new();
1325    let mut breaking_change = false;
1326
1327    for part in inner {
1328        if part.as_rule() == Rule::concept_change_annotation {
1329            let mut annotation_inner = part.into_inner();
1330
1331            let key_pair = annotation_inner
1332                .next()
1333                .ok_or_else(|| ParseError::GrammarError("Expected annotation key".to_string()))?;
1334            let value_pair = annotation_inner
1335                .next()
1336                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
1337
1338            match key_pair.as_rule() {
1339                Rule::cc_from_version => from_version = parse_version(value_pair)?,
1340                Rule::cc_to_version => to_version = parse_version(value_pair)?,
1341                Rule::cc_migration_policy => migration_policy = parse_identifier(value_pair)?,
1342                Rule::cc_breaking_change => {
1343                    breaking_change = value_pair.as_str() == "true";
1344                }
1345                _ => {}
1346            }
1347        }
1348    }
1349
1350    if from_version.is_empty() {
1351        return Err(ParseError::GrammarError(
1352            "Missing cc_from_version annotation".to_string(),
1353        ));
1354    }
1355
1356    if to_version.is_empty() {
1357        return Err(ParseError::GrammarError(
1358            "Missing cc_to_version annotation".to_string(),
1359        ));
1360    }
1361
1362    if migration_policy.is_empty() {
1363        return Err(ParseError::GrammarError(
1364            "Missing cc_migration_policy annotation".to_string(),
1365        ));
1366    }
1367
1368    Ok(AstNode::ConceptChange {
1369        name,
1370        from_version,
1371        to_version,
1372        migration_policy,
1373        breaking_change,
1374    })
1375}
1376
1377/// Parse resource declaration
1378fn parse_resource(pair: Pair<Rule>) -> ParseResult<AstNode> {
1379    let mut inner = pair.into_inner();
1380
1381    let name = parse_name(
1382        inner
1383            .next()
1384            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
1385    )?;
1386
1387    let mut annotations = HashMap::new();
1388    let mut unit_name = None;
1389    let mut domain = None;
1390    let mut saw_in_keyword = false;
1391
1392    for part in inner {
1393        match part.as_rule() {
1394            Rule::resource_annotation => {
1395                let mut annotation_inner = part.into_inner();
1396                let key_pair = annotation_inner
1397                    .next()
1398                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;
1399
1400                match key_pair.as_rule() {
1401                    Rule::ea_replaces => {
1402                        let target_name =
1403                            parse_name(annotation_inner.next().ok_or_else(|| {
1404                                ParseError::GrammarError("Expected name in replaces".to_string())
1405                            })?)?;
1406                        // Check for optional version
1407                        let mut target_version = None;
1408                        if let Some(next) = annotation_inner.next() {
1409                            if next.as_rule() == Rule::version {
1410                                target_version = Some(next.as_str().to_string());
1411                            }
1412                        }
1413
1414                        let value = if let Some(v) = target_version {
1415                            format!("{} v{}", target_name, v)
1416                        } else {
1417                            target_name
1418                        };
1419                        annotations.insert("replaces".to_string(), JsonValue::String(value));
1420                    }
1421                    Rule::ea_changes => {
1422                        let array_pair = annotation_inner.next().ok_or_else(|| {
1423                            ParseError::GrammarError("Expected string array in changes".to_string())
1424                        })?;
1425                        let mut changes = Vec::new();
1426                        for item in array_pair.into_inner() {
1427                            changes.push(parse_string_literal(item)?);
1428                        }
1429                        annotations.insert(
1430                            "changes".to_string(),
1431                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
1432                        );
1433                    }
1434                    Rule::identifier => {
1435                        let key = parse_identifier(key_pair)?.to_lowercase();
1436                        let value_pair = annotation_inner.next().ok_or_else(|| {
1437                            ParseError::GrammarError("Expected annotation value".to_string())
1438                        })?;
1439                        let value = parse_annotation_value(value_pair)?;
1440                        annotations.insert(key, value);
1441                    }
1442                    _ => {
1443                        return Err(ParseError::GrammarError(format!(
1444                            "Unexpected flow annotation: {}",
1445                            key_pair.as_str()
1446                        )));
1447                    }
1448                }
1449            }
1450            Rule::in_keyword => {
1451                // Mark that we've seen 'in', next identifier is domain
1452                saw_in_keyword = true;
1453            }
1454            Rule::identifier => {
1455                // If we've seen 'in' keyword, this is domain; otherwise it's unit
1456                if saw_in_keyword {
1457                    domain = Some(parse_identifier(part)?);
1458                    saw_in_keyword = false; // Reset for safety
1459                } else {
1460                    unit_name = Some(parse_identifier(part)?);
1461                }
1462            }
1463            _ => {}
1464        }
1465    }
1466
1467    Ok(AstNode::Resource {
1468        name,
1469        annotations,
1470        unit_name,
1471        domain,
1472    })
1473}
1474
1475/// Parse flow declaration
1476fn parse_flow(pair: Pair<Rule>) -> ParseResult<AstNode> {
1477    let mut inner = pair.into_inner();
1478
1479    let resource_name = parse_string_literal(
1480        inner
1481            .next()
1482            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
1483    )?;
1484
1485    let mut annotations = HashMap::new();
1486    let mut from_entity = None;
1487    let mut to_entity = None;
1488    let mut quantity = None;
1489    let mut pending_annotation_key: Option<String> = None;
1490
1491    for part in inner {
1492        match part.as_rule() {
1493            Rule::flow_annotation => {
1494                let mut annotation_inner = part.into_inner();
1495                let key_pair = annotation_inner
1496                    .next()
1497                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;
1498
1499                match key_pair.as_rule() {
1500                    Rule::ea_replaces => {
1501                        let target_name =
1502                            parse_name(annotation_inner.next().ok_or_else(|| {
1503                                ParseError::GrammarError("Expected name in replaces".to_string())
1504                            })?)?;
1505                        // Check for optional version
1506                        let mut target_version = None;
1507                        if let Some(next) = annotation_inner.next() {
1508                            if next.as_rule() == Rule::version {
1509                                target_version = Some(next.as_str().to_string());
1510                            }
1511                        }
1512
1513                        let value = if let Some(v) = target_version {
1514                            format!("{} v{}", target_name, v)
1515                        } else {
1516                            target_name
1517                        };
1518                        annotations.insert("replaces".to_string(), JsonValue::String(value));
1519                    }
1520                    Rule::ea_changes => {
1521                        let array_pair = annotation_inner.next().ok_or_else(|| {
1522                            ParseError::GrammarError("Expected string array in changes".to_string())
1523                        })?;
1524                        let mut changes = Vec::new();
1525                        for item in array_pair.into_inner() {
1526                            changes.push(parse_string_literal(item)?);
1527                        }
1528                        annotations.insert(
1529                            "changes".to_string(),
1530                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
1531                        );
1532                    }
1533                    Rule::identifier => {
1534                        let key = parse_identifier(key_pair)?.to_lowercase();
1535                        let value_pair = annotation_inner.next().ok_or_else(|| {
1536                            ParseError::GrammarError("Expected annotation value".to_string())
1537                        })?;
1538                        let value = parse_annotation_value(value_pair)?;
1539                        annotations.insert(key, value);
1540                    }
1541                    _ => {
1542                        return Err(ParseError::GrammarError(format!(
1543                            "Unexpected flow annotation: {}",
1544                            key_pair.as_str()
1545                        )));
1546                    }
1547                }
1548            }
1549            Rule::identifier => {
1550                if pending_annotation_key.is_some() {
1551                    return Err(ParseError::GrammarError(
1552                        "Unexpected annotation key without value".to_string(),
1553                    ));
1554                }
1555                pending_annotation_key = Some(parse_identifier(part)?.to_lowercase());
1556            }
1557            Rule::annotation_value
1558            | Rule::object_literal
1559            | Rule::string_array
1560            | Rule::boolean
1561            | Rule::number
1562            | Rule::string_literal => {
1563                if let Some(key) = pending_annotation_key.take() {
1564                    let value = parse_annotation_value(part)?;
1565                    annotations.insert(key, value);
1566                    continue;
1567                }
1568
1569                if part.as_rule() == Rule::string_literal {
1570                    // These are from_entity and to_entity in order
1571                    let parsed = parse_string_literal(part)?;
1572                    if from_entity.is_none() {
1573                        from_entity = Some(parsed);
1574                    } else if to_entity.is_none() {
1575                        to_entity = Some(parsed);
1576                    }
1577                } else if part.as_rule() == Rule::number {
1578                    quantity = Some(parse_decimal(part)?);
1579                }
1580            }
1581            _ => {}
1582        }
1583    }
1584
1585    Ok(AstNode::Flow {
1586        resource_name,
1587        annotations,
1588        from_entity: from_entity
1589            .ok_or_else(|| ParseError::GrammarError("Expected from entity".to_string()))?,
1590        to_entity: to_entity
1591            .ok_or_else(|| ParseError::GrammarError("Expected to entity".to_string()))?,
1592        quantity,
1593    })
1594}
1595
1596/// Parse pattern declaration
1597fn parse_pattern(pair: Pair<Rule>) -> ParseResult<AstNode> {
1598    let mut inner = pair.into_inner();
1599
1600    let name = parse_name(
1601        inner
1602            .next()
1603            .ok_or_else(|| ParseError::GrammarError("Expected pattern name".to_string()))?,
1604    )?;
1605
1606    let regex_literal = inner
1607        .next()
1608        .ok_or_else(|| ParseError::GrammarError("Expected regex for pattern".to_string()))?;
1609    let regex = parse_string_literal(regex_literal)?;
1610
1611    Ok(AstNode::Pattern { name, regex })
1612}
1613
1614/// Parse role declaration
1615fn parse_role(pair: Pair<Rule>) -> ParseResult<AstNode> {
1616    let mut inner = pair.into_inner();
1617
1618    let name = parse_name(
1619        inner
1620            .next()
1621            .ok_or_else(|| ParseError::GrammarError("Expected role name".to_string()))?,
1622    )?;
1623
1624    let mut domain = None;
1625    for part in inner {
1626        match part.as_rule() {
1627            Rule::in_keyword => {
1628                // Skip "in"
1629            }
1630            Rule::identifier => {
1631                domain = Some(parse_identifier(part)?);
1632            }
1633            _ => {}
1634        }
1635    }
1636
1637    Ok(AstNode::Role { name, domain })
1638}
1639
1640/// Parse relation declaration
1641fn parse_relation(pair: Pair<Rule>) -> ParseResult<AstNode> {
1642    let mut inner = pair.into_inner();
1643
1644    let name = parse_name(
1645        inner
1646            .next()
1647            .ok_or_else(|| ParseError::GrammarError("Expected relation name".to_string()))?,
1648    )?;
1649
1650    let subject_literal = inner
1651        .next()
1652        .ok_or_else(|| ParseError::GrammarError("Expected subject role in relation".to_string()))?;
1653    let subject_role = parse_string_literal(subject_literal)?;
1654
1655    let predicate_literal = inner
1656        .next()
1657        .ok_or_else(|| ParseError::GrammarError("Expected predicate in relation".to_string()))?;
1658    let predicate = parse_string_literal(predicate_literal)?;
1659
1660    let object_literal = inner
1661        .next()
1662        .ok_or_else(|| ParseError::GrammarError("Expected object role in relation".to_string()))?;
1663    let object_role = parse_string_literal(object_literal)?;
1664
1665    let via_flow = if let Some(via_pair) = inner.next() {
1666        match via_pair.as_rule() {
1667            Rule::string_literal => Some(parse_string_literal(via_pair)?),
1668            _ => {
1669                let mut via_inner = via_pair.into_inner();
1670                let flow_literal = via_inner.next().ok_or_else(|| {
1671                    ParseError::GrammarError("Expected flow name after via".to_string())
1672                })?;
1673                Some(parse_string_literal(flow_literal)?)
1674            }
1675        }
1676    } else {
1677        None
1678    };
1679
1680    Ok(AstNode::Relation {
1681        name,
1682        subject_role,
1683        predicate,
1684        object_role,
1685        via_flow,
1686    })
1687}
1688
1689fn parse_role_binding(pair: Pair<Rule>) -> ParseResult<AstNode> {
1690    let mut inner = pair.into_inner();
1691    let role = parse_string_literal(inner.next().ok_or_else(|| {
1692        ParseError::GrammarError("Expected role name in role_binding".to_string())
1693    })?)?;
1694    let entity = parse_string_literal(inner.next().ok_or_else(|| {
1695        ParseError::GrammarError("Expected entity name in role_binding".to_string())
1696    })?)?;
1697    Ok(AstNode::RoleBinding { role, entity })
1698}
1699
1700/// Parse instance declaration
1701fn parse_instance(pair: Pair<Rule>) -> ParseResult<AstNode> {
1702    let mut inner = pair.into_inner();
1703
1704    let name = parse_identifier(
1705        inner
1706            .next()
1707            .ok_or_else(|| ParseError::GrammarError("Expected instance name".to_string()))?,
1708    )?;
1709
1710    let entity_type = parse_string_literal(
1711        inner
1712            .next()
1713            .ok_or_else(|| ParseError::GrammarError("Expected entity type".to_string()))?,
1714    )?;
1715
1716    let mut fields = HashMap::new();
1717
1718    // Parse optional instance body
1719    if let Some(body_pair) = inner.next() {
1720        if body_pair.as_rule() == Rule::instance_body {
1721            for field_pair in body_pair.into_inner() {
1722                if field_pair.as_rule() == Rule::instance_field {
1723                    let span = field_pair.as_span();
1724                    let mut field_inner = field_pair.into_inner();
1725
1726                    let field_name = parse_identifier(field_inner.next().ok_or_else(|| {
1727                        ParseError::GrammarError("Expected field name".to_string())
1728                    })?)?;
1729
1730                    if fields.contains_key(&field_name) {
1731                        let (line, column) = span.start_pos().line_col();
1732                        return Err(ParseError::GrammarError(format!(
1733                            "Duplicate field name '{}' at line {}, column {}",
1734                            field_name, line, column
1735                        )));
1736                    }
1737
1738                    let field_value = parse_expression(field_inner.next().ok_or_else(|| {
1739                        ParseError::GrammarError("Expected field value".to_string())
1740                    })?)?;
1741
1742                    fields.insert(field_name, field_value);
1743                }
1744            }
1745        }
1746    }
1747
1748    Ok(AstNode::Instance {
1749        name,
1750        entity_type,
1751        fields,
1752    })
1753}
1754
1755/// Parse policy declaration
1756fn parse_policy(pair: Pair<Rule>) -> ParseResult<AstNode> {
1757    let mut inner = pair.into_inner();
1758
1759    let name = parse_identifier(
1760        inner
1761            .next()
1762            .ok_or_else(|| ParseError::GrammarError("Expected policy name".to_string()))?,
1763    )?;
1764
1765    let mut metadata = PolicyMetadata {
1766        kind: None,
1767        modality: None,
1768        priority: None,
1769        rationale: None,
1770        tags: Vec::new(),
1771    };
1772    let mut version: Option<String> = None;
1773
1774    for next_pair in inner {
1775        match next_pair.as_rule() {
1776            Rule::policy_kind => {
1777                metadata.kind = Some(match next_pair.as_str().to_lowercase().as_str() {
1778                    "constraint" => PolicyKind::Constraint,
1779                    "derivation" => PolicyKind::Derivation,
1780                    "obligation" => PolicyKind::Obligation,
1781                    _ => {
1782                        return Err(ParseError::GrammarError(format!(
1783                            "Unknown policy kind: {}",
1784                            next_pair.as_str()
1785                        )))
1786                    }
1787                });
1788            }
1789            Rule::policy_modality => {
1790                metadata.modality = Some(match next_pair.as_str().to_lowercase().as_str() {
1791                    "obligation" => PolicyModality::Obligation,
1792                    "prohibition" => PolicyModality::Prohibition,
1793                    "permission" => PolicyModality::Permission,
1794                    _ => {
1795                        return Err(ParseError::GrammarError(format!(
1796                            "Unknown policy modality: {}",
1797                            next_pair.as_str()
1798                        )))
1799                    }
1800                });
1801            }
1802            Rule::number => {
1803                metadata.priority = Some(parse_number(next_pair)?);
1804            }
1805            Rule::policy_annotation => {
1806                parse_policy_annotation(next_pair, &mut metadata)?;
1807            }
1808            Rule::version => {
1809                version = Some(next_pair.as_str().to_string());
1810            }
1811            Rule::expression => {
1812                let expression = parse_expression(next_pair)?;
1813                return Ok(AstNode::Policy {
1814                    name,
1815                    version,
1816                    metadata,
1817                    expression,
1818                });
1819            }
1820            _ => {}
1821        }
1822    }
1823
1824    Err(ParseError::GrammarError(
1825        "Policy missing expression".to_string(),
1826    ))
1827}
1828
1829fn parse_policy_annotation(pair: Pair<Rule>, metadata: &mut PolicyMetadata) -> ParseResult<()> {
1830    let mut inner = pair.into_inner();
1831
1832    let name = inner
1833        .next()
1834        .ok_or_else(|| ParseError::GrammarError("Expected annotation name".to_string()))?;
1835    let value = inner
1836        .next()
1837        .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
1838
1839    let name_str = name.as_str().to_lowercase();
1840
1841    match name_str.as_str() {
1842        "rationale" => {
1843            metadata.rationale = Some(parse_string_literal(value)?);
1844        }
1845        "tags" => {
1846            if value.as_rule() == Rule::string_array {
1847                for tag_pair in value.into_inner() {
1848                    if tag_pair.as_rule() == Rule::string_literal {
1849                        metadata.tags.push(parse_string_literal(tag_pair)?);
1850                    }
1851                }
1852            } else {
1853                metadata.tags.push(parse_string_literal(value)?);
1854            }
1855        }
1856        _ => {
1857            return Err(ParseError::GrammarError(format!(
1858                "Unknown policy annotation: {}",
1859                name_str
1860            )))
1861        }
1862    }
1863
1864    Ok(())
1865}
1866
1867/// Parse expression
1868fn parse_expression(pair: Pair<Rule>) -> ParseResult<Expression> {
1869    match pair.as_rule() {
1870        Rule::expression => {
1871            let inner = pair
1872                .into_inner()
1873                .next()
1874                .ok_or_else(|| ParseError::GrammarError("Empty expression".to_string()))?;
1875            parse_expression(inner)
1876        }
1877        Rule::or_expr => parse_or_expr(pair),
1878        Rule::and_expr => parse_and_expr(pair),
1879        Rule::not_expr => parse_not_expr(pair),
1880        Rule::comparison_expr => parse_comparison_expr(pair),
1881        Rule::additive_expr => parse_additive_expr(pair),
1882        Rule::multiplicative_expr => parse_multiplicative_expr(pair),
1883        Rule::unary_expr => parse_unary_expr(pair),
1884        Rule::cast_expr => parse_cast_expr(pair),
1885        Rule::primary_expr => parse_primary_expr(pair),
1886        _ => Err(ParseError::InvalidExpression(format!(
1887            "Unexpected expression rule: {:?}",
1888            pair.as_rule()
1889        ))),
1890    }
1891}
1892
1893/// Parse a single expression string into an Expression AST node.
1894pub fn parse_expression_from_str(source: &str) -> ParseResult<Expression> {
1895    let pairs = SeaParser::parse(Rule::expression, source)
1896        .map_err(|e| ParseError::GrammarError(format!("Parse error: {}", e)))?;
1897    let parsed_pairs: Vec<_> = pairs.collect();
1898
1899    if parsed_pairs.is_empty() {
1900        return Err(ParseError::GrammarError("Empty expression".to_string()));
1901    }
1902    if parsed_pairs.len() > 1 {
1903        return Err(ParseError::GrammarError(
1904            "Trailing input detected after expression".to_string(),
1905        ));
1906    }
1907
1908    let pair = parsed_pairs.into_iter().next().unwrap();
1909
1910    // Check that the entire input was consumed (no trailing characters)
1911    let consumed = pair.as_span().end();
1912    let trimmed_source = source.trim_end();
1913    if consumed < trimmed_source.len() {
1914        return Err(ParseError::GrammarError(format!(
1915            "Trailing input after expression: '{}'",
1916            &source[consumed..]
1917        )));
1918    }
1919
1920    parse_expression(pair)
1921}
1922
1923/// Parse OR expression
1924fn parse_or_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1925    let mut inner = pair.into_inner();
1926    let mut left =
1927        parse_expression(inner.next().ok_or_else(|| {
1928            ParseError::GrammarError("Expected left expression in OR".to_string())
1929        })?)?;
1930
1931    for right_pair in inner {
1932        let right = parse_expression(right_pair)?;
1933        left = Expression::Binary {
1934            left: Box::new(left),
1935            op: BinaryOp::Or,
1936            right: Box::new(right),
1937        };
1938    }
1939
1940    Ok(left)
1941}
1942
1943/// Parse AND expression
1944fn parse_and_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1945    let mut inner = pair.into_inner();
1946    let mut left =
1947        parse_expression(inner.next().ok_or_else(|| {
1948            ParseError::GrammarError("Expected left expression in AND".to_string())
1949        })?)?;
1950
1951    for right_pair in inner {
1952        let right = parse_expression(right_pair)?;
1953        left = Expression::Binary {
1954            left: Box::new(left),
1955            op: BinaryOp::And,
1956            right: Box::new(right),
1957        };
1958    }
1959
1960    Ok(left)
1961}
1962
1963/// Parse NOT expression
1964fn parse_not_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1965    let mut inner = pair.into_inner();
1966    let first = inner
1967        .next()
1968        .ok_or_else(|| ParseError::GrammarError("Expected expression in NOT".to_string()))?;
1969
1970    // Check if this is actually a NOT expression or just a comparison_expr
1971    if first.as_rule() == Rule::not_expr {
1972        // This is a recursive NOT, parse it
1973        let expr = parse_expression(first)?;
1974        Ok(Expression::Unary {
1975            op: UnaryOp::Not,
1976            operand: Box::new(expr),
1977        })
1978    } else {
1979        // This is just a comparison_expr, parse it directly
1980        parse_expression(first)
1981    }
1982}
1983
1984/// Parse comparison expression
1985fn parse_comparison_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1986    let mut inner = pair.into_inner();
1987    let mut left = parse_expression(inner.next().ok_or_else(|| {
1988        ParseError::GrammarError("Expected left expression in comparison".to_string())
1989    })?)?;
1990
1991    if let Some(op_pair) = inner.next() {
1992        let op = parse_comparison_op(op_pair)?;
1993        let right = parse_expression(inner.next().ok_or_else(|| {
1994            ParseError::GrammarError("Expected right expression in comparison".to_string())
1995        })?)?;
1996        left = Expression::Binary {
1997            left: Box::new(left),
1998            op,
1999            right: Box::new(right),
2000        };
2001    }
2002
2003    Ok(left)
2004}
2005
2006/// Parse comparison operator
2007fn parse_comparison_op(pair: Pair<Rule>) -> ParseResult<BinaryOp> {
2008    let op_str = pair.as_str();
2009    match op_str {
2010        "=" => Ok(BinaryOp::Equal),
2011        "!=" => Ok(BinaryOp::NotEqual),
2012        ">" => Ok(BinaryOp::GreaterThan),
2013        "<" => Ok(BinaryOp::LessThan),
2014        ">=" => Ok(BinaryOp::GreaterThanOrEqual),
2015        "<=" => Ok(BinaryOp::LessThanOrEqual),
2016        _ if op_str.eq_ignore_ascii_case("contains") => Ok(BinaryOp::Contains),
2017        _ if op_str.eq_ignore_ascii_case("startswith") => Ok(BinaryOp::StartsWith),
2018        _ if op_str.eq_ignore_ascii_case("endswith") => Ok(BinaryOp::EndsWith),
2019        _ if op_str.eq_ignore_ascii_case("matches") => Ok(BinaryOp::Matches),
2020        _ if op_str.eq_ignore_ascii_case("before") => Ok(BinaryOp::Before),
2021        _ if op_str.eq_ignore_ascii_case("after") => Ok(BinaryOp::After),
2022        _ if op_str.eq_ignore_ascii_case("during") => Ok(BinaryOp::During),
2023        _ if op_str.eq_ignore_ascii_case("has_role") => Ok(BinaryOp::HasRole),
2024        _ => Err(ParseError::InvalidExpression(format!(
2025            "Unknown comparison operator: {}",
2026            op_str
2027        ))),
2028    }
2029}
2030
2031/// Parse additive expression
2032fn parse_additive_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2033    let mut inner = pair.into_inner();
2034    let mut left = parse_expression(inner.next().ok_or_else(|| {
2035        ParseError::GrammarError("Expected left expression in additive".to_string())
2036    })?)?;
2037
2038    while let Some(op_pair) = inner.next() {
2039        let op = match op_pair.as_str() {
2040            "+" => BinaryOp::Plus,
2041            "-" => BinaryOp::Minus,
2042            _ => {
2043                return Err(ParseError::InvalidExpression(
2044                    "Invalid additive operator".to_string(),
2045                ))
2046            }
2047        };
2048        let right = parse_expression(inner.next().ok_or_else(|| {
2049            ParseError::GrammarError("Expected right expression in additive".to_string())
2050        })?)?;
2051        left = Expression::Binary {
2052            left: Box::new(left),
2053            op,
2054            right: Box::new(right),
2055        };
2056    }
2057
2058    Ok(left)
2059}
2060
2061/// Parse multiplicative expression
2062fn parse_multiplicative_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2063    let mut inner = pair.into_inner();
2064    let mut left = parse_expression(inner.next().ok_or_else(|| {
2065        ParseError::GrammarError("Expected left expression in multiplicative".to_string())
2066    })?)?;
2067
2068    while let Some(op_pair) = inner.next() {
2069        let op = match op_pair.as_str() {
2070            "*" => BinaryOp::Multiply,
2071            "/" => BinaryOp::Divide,
2072            _ => {
2073                return Err(ParseError::InvalidExpression(
2074                    "Invalid multiplicative operator".to_string(),
2075                ))
2076            }
2077        };
2078        let right = parse_expression(inner.next().ok_or_else(|| {
2079            ParseError::GrammarError("Expected right expression in multiplicative".to_string())
2080        })?)?;
2081        left = Expression::Binary {
2082            left: Box::new(left),
2083            op,
2084            right: Box::new(right),
2085        };
2086    }
2087
2088    Ok(left)
2089}
2090
2091/// Parse cast expression
2092fn parse_cast_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2093    let mut inner = pair.into_inner();
2094    let primary = parse_expression(inner.next().ok_or_else(|| {
2095        ParseError::GrammarError("Expected primary expression in cast".to_string())
2096    })?)?;
2097
2098    if let Some(as_pair) = inner.next() {
2099        let target_type = parse_string_literal(as_pair)?;
2100        Ok(Expression::cast(primary, target_type))
2101    } else {
2102        Ok(primary)
2103    }
2104}
2105
2106/// Parse unary expression
2107fn parse_unary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2108    let mut inner = pair.into_inner();
2109    let first = inner
2110        .next()
2111        .ok_or_else(|| ParseError::GrammarError("Expected expression in unary".to_string()))?;
2112
2113    if first.as_str() == "-" {
2114        // Unary minus
2115        let expr = parse_expression(inner.next().ok_or_else(|| {
2116            ParseError::GrammarError("Expected expression after unary minus".to_string())
2117        })?)?;
2118        Ok(Expression::Unary {
2119            op: UnaryOp::Negate,
2120            operand: Box::new(expr),
2121        })
2122    } else {
2123        parse_expression(first)
2124    }
2125}
2126
2127/// Parse primary expression
2128fn parse_primary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2129    let inner = pair.into_inner().next().ok_or_else(|| {
2130        ParseError::GrammarError("Expected inner expression in primary".to_string())
2131    })?;
2132
2133    match inner.as_rule() {
2134        Rule::expression => parse_expression(inner),
2135        Rule::group_by_expr => parse_group_by_expr(inner),
2136        Rule::aggregation_expr => parse_aggregation_expr(inner),
2137        Rule::quantified_expr => parse_quantified_expr(inner),
2138        Rule::member_access => parse_member_access(inner),
2139        Rule::application_role_ref => parse_application_role_ref(inner),
2140        Rule::literal => parse_literal_expr(inner),
2141        Rule::identifier => {
2142            let name = parse_identifier(inner)?;
2143            Ok(Expression::Variable(name))
2144        }
2145        _ => Err(ParseError::InvalidExpression(format!(
2146            "Unexpected primary expression: {:?}",
2147            inner.as_rule()
2148        ))),
2149    }
2150}
2151
2152fn parse_application_role_ref(pair: Pair<Rule>) -> ParseResult<Expression> {
2153    let mut inner = pair.into_inner();
2154    let sym_pair = inner
2155        .next()
2156        .ok_or_else(|| ParseError::GrammarError("Expected symbol in role<...>".to_string()))?;
2157    let mut sym_inner = sym_pair.into_inner();
2158    let first = parse_identifier(sym_inner.next().ok_or_else(|| {
2159        ParseError::GrammarError("Expected identifier in role symbol_ref".to_string())
2160    })?)?;
2161    let role = match sym_inner.next() {
2162        Some(second) => format!("{}.{}", first, parse_identifier(second)?),
2163        None => first,
2164    };
2165    Ok(Expression::RoleReference { role })
2166}
2167
2168/// Parse aggregation expression
2169fn parse_aggregation_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2170    let mut inner = pair.into_inner();
2171
2172    let function_pair = inner.next().ok_or_else(|| {
2173        ParseError::GrammarError(
2174            "Expected aggregate function in aggregation expression".to_string(),
2175        )
2176    })?;
2177    let function = parse_aggregate_fn(function_pair)?;
2178
2179    let collection_pair = inner.next().ok_or_else(|| {
2180        ParseError::GrammarError("Expected collection in aggregation expression".to_string())
2181    })?;
2182
2183    // Aggregation can be a simple form (e.g., sum(flows), sum(flows.quantity))
2184    // or the comprehension form (e.g., sum(f in flows where f.resource = "Money": f.quantity as "USD")).
2185    if collection_pair.as_rule() == Rule::aggregation_comprehension {
2186        // Parse aggregation comprehension
2187        let mut comp_inner = collection_pair.into_inner();
2188        let variable_pair = comp_inner.next().ok_or_else(|| {
2189            ParseError::GrammarError("Expected variable in aggregation comprehension".to_string())
2190        })?;
2191        let variable = parse_identifier(variable_pair)?;
2192        // Next token should be collection
2193        let collection_token = comp_inner.next().ok_or_else(|| {
2194            ParseError::GrammarError("Expected collection in aggregation comprehension".to_string())
2195        })?;
2196        let collection_name = parse_collection(collection_token)?;
2197        let collection = Box::new(Expression::Variable(collection_name));
2198
2199        let mut next_pair = comp_inner.next().ok_or_else(|| {
2200            ParseError::GrammarError(
2201                "Expected predicate expression, projection, or window in aggregation comprehension"
2202                    .to_string(),
2203            )
2204        })?;
2205
2206        let mut window = None;
2207        if next_pair.as_rule() == Rule::window_clause {
2208            window = Some(parse_window_clause(next_pair)?);
2209            next_pair = comp_inner.next().ok_or_else(|| {
2210                ParseError::GrammarError(
2211                    "Expected predicate or projection expression in aggregation comprehension"
2212                        .to_string(),
2213                )
2214            })?;
2215        }
2216
2217        let remaining_pairs: Vec<Pair<Rule>> =
2218            std::iter::once(next_pair).chain(comp_inner).collect();
2219
2220        let mut expr_pairs: Vec<Pair<Rule>> = Vec::new();
2221        let mut target_unit: Option<String> = None;
2222        for pair in remaining_pairs {
2223            match pair.as_rule() {
2224                Rule::expression => expr_pairs.push(pair),
2225                Rule::string_literal => {
2226                    target_unit = Some(parse_string_literal(pair)?);
2227                }
2228                Rule::identifier if pair.as_str().eq_ignore_ascii_case("as") => {
2229                    // skip explicit AS token
2230                }
2231                other => {
2232                    return Err(ParseError::GrammarError(format!(
2233                        "Unexpected token {:?} in aggregation comprehension",
2234                        other
2235                    )))
2236                }
2237            }
2238        }
2239
2240        let (predicate, projection) = match expr_pairs.len() {
2241            2 => {
2242                let mut expr_iter = expr_pairs.into_iter();
2243                let predicate_expr = parse_expression(expr_iter.next().ok_or_else(|| {
2244                    ParseError::GrammarError(
2245                        "Expected predicate expression in aggregation comprehension".to_string(),
2246                    )
2247                })?)?;
2248                let projection_expr = parse_expression(expr_iter.next().ok_or_else(|| {
2249                    ParseError::GrammarError(
2250                        "Expected projection expression in aggregation comprehension".to_string(),
2251                    )
2252                })?)?;
2253                (predicate_expr, projection_expr)
2254            }
2255            1 => {
2256                let projection_expr =
2257                    parse_expression(expr_pairs.into_iter().next().ok_or_else(|| {
2258                        ParseError::GrammarError(
2259                            "Expected projection expression in aggregation comprehension"
2260                                .to_string(),
2261                        )
2262                    })?)?;
2263                (Expression::Literal(JsonValue::Bool(true)), projection_expr)
2264            }
2265            other => {
2266                return Err(ParseError::GrammarError(format!(
2267                    "Unexpected number of expressions in aggregation comprehension: {}",
2268                    other
2269                )))
2270            }
2271        };
2272
2273        return Ok(Expression::AggregationComprehension {
2274            function,
2275            variable,
2276            collection,
2277            window,
2278            predicate: Box::new(predicate),
2279            projection: Box::new(projection),
2280            target_unit,
2281        });
2282    }
2283
2284    // Parse aggregation_simple
2285    let mut simple_inner = collection_pair.into_inner();
2286
2287    // First item is either collection or identifier
2288    let first_pair = simple_inner.next().ok_or_else(|| {
2289        ParseError::GrammarError(
2290            "Expected collection or identifier in aggregation_simple".to_string(),
2291        )
2292    })?;
2293
2294    let collection = match first_pair.as_rule() {
2295        Rule::collection => parse_collection(first_pair)?,
2296        Rule::identifier => parse_identifier(first_pair)?,
2297        _ => {
2298            return Err(ParseError::GrammarError(format!(
2299                "Expected collection or identifier, got {:?}",
2300                first_pair.as_rule()
2301            )))
2302        }
2303    };
2304
2305    let mut field: Option<String> = None;
2306    let mut filter: Option<Expression> = None;
2307
2308    // Parse optional field and filter
2309    for item in simple_inner {
2310        match item.as_rule() {
2311            Rule::identifier => {
2312                field = Some(parse_identifier(item)?);
2313            }
2314            Rule::expression => {
2315                filter = Some(parse_expression(item)?);
2316            }
2317            _ => {}
2318        }
2319    }
2320
2321    Ok(Expression::aggregation(
2322        function,
2323        Expression::Variable(collection),
2324        field,
2325        filter,
2326    ))
2327}
2328
2329/// Parse aggregate function
2330fn parse_aggregate_fn(pair: Pair<Rule>) -> ParseResult<AggregateFunction> {
2331    let fn_str = pair.as_str();
2332    match fn_str.to_lowercase().as_str() {
2333        "count" => Ok(AggregateFunction::Count),
2334        "sum" => Ok(AggregateFunction::Sum),
2335        "min" => Ok(AggregateFunction::Min),
2336        "max" => Ok(AggregateFunction::Max),
2337        "avg" => Ok(AggregateFunction::Avg),
2338        _ => Err(ParseError::InvalidExpression(format!(
2339            "Unknown aggregate function: {}",
2340            fn_str
2341        ))),
2342    }
2343}
2344
2345/// Parse quantified expression
2346fn parse_quantified_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2347    let mut inner = pair.into_inner();
2348
2349    let quantifier = parse_quantifier(inner.next().ok_or_else(|| {
2350        ParseError::GrammarError("Expected quantifier in quantified expression".to_string())
2351    })?)?;
2352    let variable = parse_identifier(inner.next().ok_or_else(|| {
2353        ParseError::GrammarError(
2354            "Expected variable identifier in quantified expression".to_string(),
2355        )
2356    })?)?;
2357    let collection = parse_collection(inner.next().ok_or_else(|| {
2358        ParseError::GrammarError(
2359            "Expected collection identifier in quantified expression".to_string(),
2360        )
2361    })?)?;
2362    let condition = parse_expression(inner.next().ok_or_else(|| {
2363        ParseError::GrammarError("Expected quantified condition expression".to_string())
2364    })?)?;
2365
2366    Ok(Expression::Quantifier {
2367        quantifier,
2368        variable,
2369        collection: Box::new(Expression::Variable(collection)),
2370        condition: Box::new(condition),
2371    })
2372}
2373
2374/// Parse quantifier
2375fn parse_quantifier(pair: Pair<Rule>) -> ParseResult<PolicyQuantifier> {
2376    let q_str = pair.as_str();
2377    match q_str.to_lowercase().as_str() {
2378        "forall" => Ok(PolicyQuantifier::ForAll),
2379        "exists" => Ok(PolicyQuantifier::Exists),
2380        "exists_unique" => Ok(PolicyQuantifier::ExistsUnique),
2381        _ => Err(ParseError::InvalidExpression(format!(
2382            "Unknown quantifier: {}",
2383            q_str
2384        ))),
2385    }
2386}
2387
2388/// Parse collection type. `entity_instances of "EntityType"` carries an
2389/// inner `string_literal`; encode it as `entity_instances:EntityType` in
2390/// the returned name (matching how a bound-variable member access is
2391/// already encoded as `variable.field` — see `Expression::substitute`), so
2392/// every existing site that keys on a plain `Expression::Variable(String)`
2393/// collection name needs no new AST variant.
2394fn parse_collection(pair: Pair<Rule>) -> ParseResult<String> {
2395    // `.trim()`: the optional `of "EntityType"` suffix means pest's implicit
2396    // whitespace-skip between it and the base keyword can end up inside this
2397    // rule's span even when the suffix itself does not match (bare
2398    // `entity_instances`), so the untrimmed text can carry trailing
2399    // whitespace that would otherwise defeat the exact-match lookups below.
2400    let text = pair.as_str().trim().to_lowercase();
2401    for inner in pair.into_inner() {
2402        if inner.as_rule() == Rule::string_literal {
2403            let entity_type = parse_string_literal(inner)?;
2404            return Ok(format!("entity_instances:{entity_type}"));
2405        }
2406    }
2407    Ok(text)
2408}
2409
2410/// Parse member access
2411fn parse_member_access(pair: Pair<Rule>) -> ParseResult<Expression> {
2412    let mut inner = pair.into_inner();
2413    let object = parse_identifier(inner.next().ok_or_else(|| {
2414        ParseError::GrammarError("Expected object identifier in member access".to_string())
2415    })?)?;
2416    let member = parse_identifier(inner.next().ok_or_else(|| {
2417        ParseError::GrammarError("Expected member identifier in member access".to_string())
2418    })?)?;
2419
2420    Ok(Expression::MemberAccess { object, member })
2421}
2422
2423/// Parse literal expression
2424fn parse_literal_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2425    let inner = pair
2426        .into_inner()
2427        .next()
2428        .ok_or_else(|| ParseError::GrammarError("Expected literal content".to_string()))?;
2429
2430    match inner.as_rule() {
2431        Rule::string_literal => {
2432            let s = parse_string_literal(inner)?;
2433            Ok(Expression::Literal(JsonValue::String(s)))
2434        }
2435        Rule::multiline_string => {
2436            let s = parse_multiline_string(inner)?;
2437            Ok(Expression::Literal(JsonValue::String(s)))
2438        }
2439        Rule::quantity_literal => {
2440            let mut parts = inner.into_inner();
2441            let number_part = parts.next().ok_or_else(|| {
2442                ParseError::GrammarError("Expected number in quantity literal".to_string())
2443            })?;
2444            let unit_part = parts.next().ok_or_else(|| {
2445                ParseError::GrammarError("Expected unit string in quantity literal".to_string())
2446            })?;
2447            let value = parse_decimal(number_part)?;
2448            let unit = parse_string_literal(unit_part)?;
2449            Ok(Expression::QuantityLiteral { value, unit })
2450        }
2451        Rule::time_literal => {
2452            // Parse ISO 8601 timestamp (already includes quotes in grammar)
2453            let timestamp = inner.as_str();
2454            // Remove surrounding quotes
2455            let timestamp = timestamp.trim_start_matches('"').trim_end_matches('"');
2456            Ok(Expression::TimeLiteral(timestamp.to_string()))
2457        }
2458        Rule::interval_literal => {
2459            // Parse interval("start", "end")
2460            let mut parts = inner.into_inner();
2461            let start_part = parts.next().ok_or_else(|| {
2462                ParseError::GrammarError("Expected start time in interval literal".to_string())
2463            })?;
2464            let end_part = parts.next().ok_or_else(|| {
2465                ParseError::GrammarError("Expected end time in interval literal".to_string())
2466            })?;
2467            let start = parse_string_literal(start_part)?;
2468            let end = parse_string_literal(end_part)?;
2469            Ok(Expression::IntervalLiteral { start, end })
2470        }
2471        Rule::number => {
2472            let n = parse_decimal(inner)?;
2473            // Convert Decimal to f64 for JSON Number representation
2474            let f = n.to_f64().ok_or_else(|| {
2475                ParseError::InvalidQuantity(format!(
2476                    "Decimal value {} cannot be represented as f64",
2477                    n
2478                ))
2479            })?;
2480            // Ensure the value is finite
2481            if !f.is_finite() {
2482                return Err(ParseError::InvalidQuantity(format!(
2483                    "Decimal value {} converts to non-finite f64: {}",
2484                    n, f
2485                )));
2486            }
2487            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
2488                ParseError::InvalidQuantity(format!(
2489                    "Cannot create JSON Number from f64 value: {}",
2490                    f
2491                ))
2492            })?;
2493            Ok(Expression::Literal(JsonValue::Number(num)))
2494        }
2495        Rule::boolean => {
2496            let b = inner.as_str().eq_ignore_ascii_case("true");
2497            Ok(Expression::Literal(JsonValue::Bool(b)))
2498        }
2499        Rule::array_literal => {
2500            let mut values = Vec::new();
2501            for element in inner.into_inner() {
2502                if element.as_rule() != Rule::literal {
2503                    continue;
2504                }
2505                match parse_literal_expr(element)? {
2506                    Expression::Literal(v) => values.push(v),
2507                    other => {
2508                        return Err(ParseError::GrammarError(format!(
2509                            "Array literal elements must be plain literals, got {:?}",
2510                            other
2511                        )))
2512                    }
2513                }
2514            }
2515            Ok(Expression::Literal(JsonValue::Array(values)))
2516        }
2517        _ => Err(ParseError::InvalidExpression(format!(
2518            "Unknown literal type: {:?}",
2519            inner.as_rule()
2520        ))),
2521    }
2522}
2523
2524/// Parse name (handles both string_literal and multiline_string)
2525fn parse_name(pair: Pair<Rule>) -> ParseResult<String> {
2526    let inner = pair.into_inner().next().ok_or_else(|| {
2527        ParseError::GrammarError("Expected inner token for name but got empty pair".to_string())
2528    })?;
2529    match inner.as_rule() {
2530        Rule::string_literal => parse_string_literal(inner),
2531        Rule::multiline_string => parse_multiline_string(inner),
2532        _ => Err(ParseError::GrammarError(format!(
2533            "Expected string or multiline string for name, got {:?}",
2534            inner.as_rule()
2535        ))),
2536    }
2537}
2538
2539/// Parse string literal (handles escape sequences)
2540fn parse_string_literal(pair: Pair<Rule>) -> ParseResult<String> {
2541    let s = pair.as_str();
2542    if s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') {
2543        return Err(ParseError::GrammarError(format!(
2544            "Invalid string literal: {}",
2545            s
2546        )));
2547    }
2548
2549    // Use serde_json to properly parse and unescape the string
2550    // The string already has quotes, so pass it directly
2551    match serde_json::from_str(s) {
2552        Ok(unescaped) => Ok(unescaped),
2553        Err(e) => Err(ParseError::GrammarError(format!(
2554            "Invalid string literal escape sequences: {} - {}",
2555            s, e
2556        ))),
2557    }
2558}
2559
2560/// Parse multiline string (removes triple quotes and handles escape sequences)
2561fn parse_multiline_string(pair: Pair<Rule>) -> ParseResult<String> {
2562    let s = pair.as_str();
2563    if s.len() < 6 || !s.starts_with("\"\"\"") || !s.ends_with("\"\"\"") {
2564        return Err(ParseError::GrammarError(format!(
2565            "Invalid multiline string: {}",
2566            s
2567        )));
2568    }
2569
2570    let content = &s[3..s.len() - 3];
2571
2572    // Escape special characters for JSON compatibility
2573    let escaped = content
2574        .replace('\\', "\\\\") // Backslash must be first
2575        .replace('"', "\\\"") // Double quotes
2576        .replace('\n', "\\n") // Newlines
2577        .replace('\r', "\\r") // Carriage returns
2578        .replace('\t', "\\t"); // Tabs
2579
2580    // Create a JSON string and parse it to handle escape sequences
2581    let json_string = format!("\"{}\"", escaped);
2582    match serde_json::from_str(&json_string) {
2583        Ok(unescaped) => Ok(unescaped),
2584        Err(e) => Err(ParseError::GrammarError(format!(
2585            "Invalid multiline string escape sequences in '{}': {}",
2586            s, e
2587        ))),
2588    }
2589}
2590
2591/// Parse identifier
2592fn parse_identifier(pair: Pair<Rule>) -> ParseResult<String> {
2593    Ok(pair.as_str().to_string())
2594}
2595
2596/// Parse semantic version (validated by grammar)
2597fn parse_version(pair: Pair<Rule>) -> ParseResult<String> {
2598    Ok(pair.as_str().to_string())
2599}
2600
2601/// Parse number as i32
2602fn parse_number(pair: Pair<Rule>) -> ParseResult<i32> {
2603    pair.as_str()
2604        .parse()
2605        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid number: {}", pair.as_str())))
2606}
2607
2608/// Parse number as Decimal
2609fn parse_decimal(pair: Pair<Rule>) -> ParseResult<Decimal> {
2610    pair.as_str()
2611        .parse()
2612        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid decimal: {}", pair.as_str())))
2613}
2614
2615/// Parse group_by expression
2616fn parse_group_by_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2617    let mut inner = pair.into_inner();
2618
2619    let variable_pair = inner
2620        .next()
2621        .ok_or_else(|| ParseError::GrammarError("Expected variable in group_by".to_string()))?;
2622    let variable = parse_identifier(variable_pair)?;
2623
2624    let collection_pair = inner
2625        .next()
2626        .ok_or_else(|| ParseError::GrammarError("Expected collection in group_by".to_string()))?;
2627    let collection_name = parse_collection(collection_pair)?;
2628    let collection = Box::new(Expression::Variable(collection_name));
2629
2630    let next_pair = inner.next().ok_or_else(|| {
2631        ParseError::GrammarError("Expected key or where clause in group_by".to_string())
2632    })?;
2633
2634    // Collect remaining pairs to determine structure without cloning
2635    let remaining: Vec<Pair<Rule>> = std::iter::once(next_pair).chain(inner).collect();
2636
2637    let (filter_expr, key_expr, condition_expr) = match remaining.len() {
2638        3 => {
2639            let mut iter = remaining.into_iter();
2640            let filter = parse_expression(iter.next().ok_or_else(|| {
2641                ParseError::GrammarError("Expected filter expression in group_by".to_string())
2642            })?)?;
2643            let key = parse_expression(iter.next().ok_or_else(|| {
2644                ParseError::GrammarError("Expected key expression in group_by".to_string())
2645            })?)?;
2646            let condition = parse_expression(iter.next().ok_or_else(|| {
2647                ParseError::GrammarError("Expected condition expression in group_by".to_string())
2648            })?)?;
2649            (Some(filter), key, condition)
2650        }
2651        2 => {
2652            let mut iter = remaining.into_iter();
2653            let key = parse_expression(iter.next().ok_or_else(|| {
2654                ParseError::GrammarError("Expected key expression in group_by".to_string())
2655            })?)?;
2656            let condition = parse_expression(iter.next().ok_or_else(|| {
2657                ParseError::GrammarError("Expected condition expression in group_by".to_string())
2658            })?)?;
2659            (None, key, condition)
2660        }
2661        other => {
2662            return Err(ParseError::GrammarError(format!(
2663                "Unexpected number of expressions in group_by: {}",
2664                other
2665            )))
2666        }
2667    };
2668
2669    Ok(Expression::GroupBy {
2670        variable,
2671        collection,
2672        filter: filter_expr.map(Box::new),
2673        key: Box::new(key_expr),
2674        condition: Box::new(condition_expr),
2675    })
2676}
2677
2678/// Parse window clause
2679fn parse_window_clause(pair: Pair<Rule>) -> ParseResult<WindowSpec> {
2680    let mut inner = pair.into_inner();
2681
2682    let duration_pair = inner.next().ok_or_else(|| {
2683        ParseError::GrammarError("Expected duration in window clause".to_string())
2684    })?;
2685    let duration_i32 = parse_number(duration_pair)?;
2686    if duration_i32 < 0 {
2687        return Err(ParseError::InvalidQuantity(
2688            "Window duration must be non-negative".to_string(),
2689        ));
2690    }
2691    let duration = duration_i32 as u64;
2692
2693    let unit_pair = inner
2694        .next()
2695        .ok_or_else(|| ParseError::GrammarError("Expected unit in window clause".to_string()))?;
2696    let unit = parse_string_literal(unit_pair)?;
2697
2698    Ok(WindowSpec { duration, unit })
2699}
2700
2701fn expression_kind(expr: &Expression) -> &'static str {
2702    match expr {
2703        Expression::Literal(_) => "literal",
2704        Expression::QuantityLiteral { .. } => "quantity_literal",
2705        Expression::TimeLiteral(_) => "time_literal",
2706        Expression::IntervalLiteral { .. } => "interval_literal",
2707        Expression::Variable(_) => "variable",
2708        Expression::GroupBy { .. } => "group_by",
2709        Expression::Binary { .. } => "binary",
2710        Expression::Unary { .. } => "unary",
2711        Expression::Cast { .. } => "cast",
2712        Expression::Quantifier { .. } => "quantifier",
2713        Expression::MemberAccess { .. } => "member_access",
2714        Expression::Aggregation { .. } => "aggregation",
2715        Expression::AggregationComprehension { .. } => "aggregation_comprehension",
2716        Expression::RoleReference { .. } => "role_reference",
2717    }
2718}
2719
2720/// Convert an Expression to a JSON Value for instance fields
2721fn expression_to_json(expr: &Expression) -> ParseResult<JsonValue> {
2722    match expr {
2723        Expression::Literal(v) => Ok(v.clone()),
2724        Expression::Variable(name) => Ok(JsonValue::String(name.clone())),
2725        Expression::QuantityLiteral { value, unit } => Ok(json!({
2726            "value": value.to_string(),
2727            "unit": unit
2728        })),
2729        Expression::TimeLiteral(timestamp) => Ok(JsonValue::String(timestamp.clone())),
2730        _ => Err(ParseError::UnsupportedExpression {
2731            kind: expression_kind(expr).to_string(),
2732            span: None,
2733        }),
2734    }
2735}
2736
2737/// Parse mapping declaration
2738fn parse_mapping(pair: Pair<Rule>) -> ParseResult<AstNode> {
2739    let mut inner = pair.into_inner();
2740
2741    let name = parse_string_literal(
2742        inner
2743            .next()
2744            .ok_or_else(|| ParseError::GrammarError("Expected mapping name".to_string()))?,
2745    )?;
2746
2747    let target_pair = inner
2748        .next()
2749        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
2750    let target = parse_target_format(target_pair)?;
2751
2752    let mut rules = Vec::new();
2753
2754    for rule_pair in inner {
2755        if rule_pair.as_rule() == Rule::mapping_rule {
2756            rules.push(parse_mapping_rule(rule_pair)?);
2757        }
2758    }
2759
2760    Ok(AstNode::MappingDecl {
2761        name,
2762        target,
2763        rules,
2764    })
2765}
2766
2767fn parse_target_format(pair: Pair<Rule>) -> ParseResult<TargetFormat> {
2768    match pair.as_str().to_lowercase().as_str() {
2769        "calm" => Ok(TargetFormat::Calm),
2770        "kg" => Ok(TargetFormat::Kg),
2771        "sbvr" => Ok(TargetFormat::Sbvr),
2772        "protobuf" | "proto" => Ok(TargetFormat::Protobuf),
2773        _ => Err(ParseError::GrammarError(format!(
2774            "Unknown target format: {}",
2775            pair.as_str()
2776        ))),
2777    }
2778}
2779
2780fn parse_mapping_rule(pair: Pair<Rule>) -> ParseResult<MappingRule> {
2781    let mut inner = pair.into_inner();
2782
2783    let primitive_type = inner
2784        .next()
2785        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
2786        .as_str()
2787        .to_string();
2788
2789    let primitive_name = parse_string_literal(
2790        inner
2791            .next()
2792            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
2793    )?;
2794
2795    let target_structure = inner
2796        .next()
2797        .ok_or_else(|| ParseError::GrammarError("Expected target structure".to_string()))?;
2798
2799    let mut target_inner = target_structure.into_inner();
2800    let target_type = parse_identifier(
2801        target_inner
2802            .next()
2803            .ok_or_else(|| ParseError::GrammarError("Expected target type".to_string()))?,
2804    )?;
2805
2806    let mut fields = HashMap::new();
2807    for field_pair in target_inner {
2808        if field_pair.as_rule() == Rule::mapping_field {
2809            let mut field_inner = field_pair.into_inner();
2810            let key = parse_identifier(
2811                field_inner
2812                    .next()
2813                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
2814            )?;
2815            let value_pair = field_inner
2816                .next()
2817                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;
2818
2819            let value = match value_pair.as_rule() {
2820                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
2821                Rule::boolean => JsonValue::Bool(value_pair.as_str().eq_ignore_ascii_case("true")),
2822                Rule::object_literal => parse_object_literal(value_pair)?,
2823                _ => {
2824                    return Err(ParseError::GrammarError(
2825                        "Unexpected mapping field value".to_string(),
2826                    ))
2827                }
2828            };
2829            fields.insert(key, value);
2830        }
2831    }
2832
2833    Ok(MappingRule {
2834        primitive_type,
2835        primitive_name,
2836        target_type,
2837        fields,
2838    })
2839}
2840
2841fn parse_object_literal(pair: Pair<Rule>) -> ParseResult<JsonValue> {
2842    let mut map = serde_json::Map::new();
2843    let mut inner = pair.into_inner();
2844    while let Some(key_pair) = inner.next() {
2845        let key = parse_string_literal(key_pair)?;
2846        let value_pair = inner.next().ok_or_else(|| {
2847            ParseError::GrammarError("Expected value in object literal".to_string())
2848        })?;
2849        let value = parse_annotation_value(value_pair)?;
2850        map.insert(key, value);
2851    }
2852    Ok(JsonValue::Object(map))
2853}
2854
2855fn parse_annotation_value(pair: Pair<Rule>) -> ParseResult<JsonValue> {
2856    match pair.as_rule() {
2857        Rule::annotation_value => {
2858            let mut inner = pair.into_inner();
2859            let value_pair = inner
2860                .next()
2861                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
2862            parse_annotation_value(value_pair)
2863        }
2864        Rule::string_literal => Ok(JsonValue::String(parse_string_literal(pair)?)),
2865        Rule::string_array => {
2866            let mut values = Vec::new();
2867            for item in pair.into_inner() {
2868                values.push(JsonValue::String(parse_string_literal(item)?));
2869            }
2870            Ok(JsonValue::Array(values))
2871        }
2872        Rule::boolean => Ok(JsonValue::Bool(pair.as_str().eq_ignore_ascii_case("true"))),
2873        Rule::number => {
2874            let d = parse_decimal(pair)?;
2875            let f = d.to_f64().ok_or_else(|| {
2876                ParseError::InvalidQuantity(format!(
2877                    "Decimal value {} cannot be represented as f64",
2878                    d
2879                ))
2880            })?;
2881            if !f.is_finite() {
2882                return Err(ParseError::InvalidQuantity(format!(
2883                    "Decimal value {} converts to non-finite f64",
2884                    d
2885                )));
2886            }
2887            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
2888                ParseError::InvalidQuantity(format!("Cannot create JSON Number from decimal {}", d))
2889            })?;
2890            Ok(JsonValue::Number(num))
2891        }
2892        Rule::object_literal => parse_object_literal(pair),
2893        _ => Err(ParseError::GrammarError(format!(
2894            "Unexpected annotation value: {}",
2895            pair.as_str()
2896        ))),
2897    }
2898}
2899
2900/// Parse projection declaration
2901fn parse_projection(pair: Pair<Rule>) -> ParseResult<AstNode> {
2902    let mut inner = pair.into_inner();
2903
2904    let name = parse_string_literal(
2905        inner
2906            .next()
2907            .ok_or_else(|| ParseError::GrammarError("Expected projection name".to_string()))?,
2908    )?;
2909
2910    let target_pair = inner
2911        .next()
2912        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
2913    let target = parse_target_format(target_pair)?;
2914
2915    let mut overrides = Vec::new();
2916
2917    for rule_pair in inner {
2918        if rule_pair.as_rule() == Rule::projection_rule {
2919            overrides.push(parse_projection_rule(rule_pair)?);
2920        }
2921    }
2922
2923    Ok(AstNode::ProjectionDecl {
2924        name,
2925        target,
2926        overrides,
2927    })
2928}
2929
2930fn parse_projection_rule(pair: Pair<Rule>) -> ParseResult<ProjectionOverride> {
2931    let mut inner = pair.into_inner();
2932
2933    let primitive_type = inner
2934        .next()
2935        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
2936        .as_str()
2937        .to_string();
2938
2939    let primitive_name = parse_string_literal(
2940        inner
2941            .next()
2942            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
2943    )?;
2944
2945    let mut fields = HashMap::new();
2946    for field_pair in inner {
2947        if field_pair.as_rule() == Rule::projection_field {
2948            let mut field_inner = field_pair.into_inner();
2949            let key = parse_identifier(
2950                field_inner
2951                    .next()
2952                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
2953            )?;
2954            let value_pair = field_inner
2955                .next()
2956                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;
2957
2958            let value = match value_pair.as_rule() {
2959                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
2960                Rule::property_mapping => parse_property_mapping(value_pair)?,
2961                _ => {
2962                    return Err(ParseError::GrammarError(
2963                        "Unexpected projection field value".to_string(),
2964                    ))
2965                }
2966            };
2967            fields.insert(key, value);
2968        }
2969    }
2970
2971    Ok(ProjectionOverride {
2972        primitive_type,
2973        primitive_name,
2974        fields,
2975    })
2976}
2977
2978/// Parse a `generic_annotation*` sequence (`"@" key value`) shared by all
2979/// cell-environment declarations into a flat annotation map. Duplicate keys
2980/// (after lowercasing) on the same declaration are an authoring error and are
2981/// rejected, including case-insensitive collisions (e.g. `@Host` after
2982/// `@host`).
2983fn parse_generic_annotations<'a>(
2984    pairs: impl Iterator<Item = Pair<'a, Rule>>,
2985) -> ParseResult<HashMap<String, JsonValue>> {
2986    let mut annotations = HashMap::new();
2987    for part in pairs {
2988        if part.as_rule() == Rule::generic_annotation {
2989            let mut inner = part.into_inner();
2990            let key =
2991                parse_identifier(inner.next().ok_or_else(|| {
2992                    ParseError::GrammarError("Expected annotation key".to_string())
2993                })?)?
2994                .to_lowercase();
2995            let value_pair = inner
2996                .next()
2997                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
2998            if annotations.contains_key(&key) {
2999                return Err(ParseError::GrammarError(format!(
3000                    "Duplicate annotation '@{key}' on the same declaration"
3001                )));
3002            }
3003            annotations.insert(key, parse_annotation_value(value_pair)?);
3004        }
3005    }
3006    Ok(annotations)
3007}
3008
3009fn parse_cell(pair: Pair<Rule>) -> ParseResult<AstNode> {
3010    let mut inner = pair.into_inner();
3011    let name = parse_name(
3012        inner
3013            .next()
3014            .ok_or_else(|| ParseError::GrammarError("Expected cell name".to_string()))?,
3015    )?;
3016    let annotations = parse_generic_annotations(inner)?;
3017    Ok(AstNode::Cell { name, annotations })
3018}
3019
3020fn parse_system_dependency(pair: Pair<Rule>) -> ParseResult<AstNode> {
3021    let mut inner = pair.into_inner().peekable();
3022    let name =
3023        parse_name(inner.next().ok_or_else(|| {
3024            ParseError::GrammarError("Expected system dependency name".to_string())
3025        })?)?;
3026    let mut version = None;
3027    if let Some(peeked) = inner.peek() {
3028        if peeked.as_rule() == Rule::string_literal {
3029            version = Some(parse_string_literal(inner.next().unwrap())?);
3030        }
3031    }
3032    let annotations = parse_generic_annotations(inner)?;
3033    Ok(AstNode::SystemDependency {
3034        name,
3035        version,
3036        annotations,
3037    })
3038}
3039
3040fn parse_runtime(pair: Pair<Rule>) -> ParseResult<AstNode> {
3041    let mut inner = pair.into_inner();
3042    let name = parse_name(
3043        inner
3044            .next()
3045            .ok_or_else(|| ParseError::GrammarError("Expected runtime name".to_string()))?,
3046    )?;
3047    let version_pair = inner
3048        .next()
3049        .ok_or_else(|| ParseError::GrammarError("Expected runtime version".to_string()))?;
3050    let version = parse_string_literal(version_pair)?;
3051    let annotations = parse_generic_annotations(inner)?;
3052    Ok(AstNode::Runtime {
3053        name,
3054        version,
3055        annotations,
3056    })
3057}
3058
3059fn parse_tool(pair: Pair<Rule>) -> ParseResult<AstNode> {
3060    let mut inner = pair.into_inner();
3061    let name = parse_name(
3062        inner
3063            .next()
3064            .ok_or_else(|| ParseError::GrammarError("Expected tool name".to_string()))?,
3065    )?;
3066    let version_pair = inner
3067        .next()
3068        .ok_or_else(|| ParseError::GrammarError("Expected tool version".to_string()))?;
3069    let version = parse_string_literal(version_pair)?;
3070    let annotations = parse_generic_annotations(inner)?;
3071    Ok(AstNode::Tool {
3072        name,
3073        version,
3074        annotations,
3075    })
3076}
3077
3078fn parse_dependency_set(pair: Pair<Rule>) -> ParseResult<AstNode> {
3079    let mut inner = pair.into_inner();
3080    let name =
3081        parse_name(inner.next().ok_or_else(|| {
3082            ParseError::GrammarError("Expected dependency set name".to_string())
3083        })?)?;
3084    let annotations = parse_generic_annotations(inner)?;
3085    Ok(AstNode::DependencySet { name, annotations })
3086}
3087
3088fn parse_service(pair: Pair<Rule>) -> ParseResult<AstNode> {
3089    let mut inner = pair.into_inner().peekable();
3090    let name = parse_name(
3091        inner
3092            .next()
3093            .ok_or_else(|| ParseError::GrammarError("Expected service name".to_string()))?,
3094    )?;
3095    let mut version = None;
3096    if let Some(peeked) = inner.peek() {
3097        if peeked.as_rule() == Rule::string_literal {
3098            version = Some(parse_string_literal(inner.next().unwrap())?);
3099        }
3100    }
3101    let annotations = parse_generic_annotations(inner)?;
3102    Ok(AstNode::Service {
3103        name,
3104        version,
3105        annotations,
3106    })
3107}
3108
3109fn parse_mount(pair: Pair<Rule>) -> ParseResult<AstNode> {
3110    let mut inner = pair.into_inner();
3111    let name = parse_name(
3112        inner
3113            .next()
3114            .ok_or_else(|| ParseError::GrammarError("Expected mount name".to_string()))?,
3115    )?;
3116    let annotations = parse_generic_annotations(inner)?;
3117    Ok(AstNode::Mount { name, annotations })
3118}
3119
3120fn parse_endpoint(pair: Pair<Rule>) -> ParseResult<AstNode> {
3121    let mut inner = pair.into_inner();
3122    let name = parse_name(
3123        inner
3124            .next()
3125            .ok_or_else(|| ParseError::GrammarError("Expected endpoint name".to_string()))?,
3126    )?;
3127    let annotations = parse_generic_annotations(inner)?;
3128    Ok(AstNode::Endpoint { name, annotations })
3129}
3130
3131fn parse_network_flow(pair: Pair<Rule>) -> ParseResult<AstNode> {
3132    let mut inner = pair.into_inner();
3133    let name = parse_name(
3134        inner
3135            .next()
3136            .ok_or_else(|| ParseError::GrammarError("Expected network flow name".to_string()))?,
3137    )?;
3138    let from_ref = parse_string_literal(inner.next().ok_or_else(|| {
3139        ParseError::GrammarError("Expected network flow 'from' reference".to_string())
3140    })?)?;
3141    let to_ref = parse_string_literal(inner.next().ok_or_else(|| {
3142        ParseError::GrammarError("Expected network flow 'to' reference".to_string())
3143    })?)?;
3144    let annotations = parse_generic_annotations(inner)?;
3145    Ok(AstNode::NetworkFlow {
3146        name,
3147        from_ref,
3148        to_ref,
3149        annotations,
3150    })
3151}
3152
3153fn parse_credential(pair: Pair<Rule>) -> ParseResult<AstNode> {
3154    let mut inner = pair.into_inner();
3155    let name = parse_name(
3156        inner
3157            .next()
3158            .ok_or_else(|| ParseError::GrammarError("Expected credential name".to_string()))?,
3159    )?;
3160    let annotations = parse_generic_annotations(inner)?;
3161    Ok(AstNode::Credential { name, annotations })
3162}
3163
3164fn parse_property_mapping(pair: Pair<Rule>) -> ParseResult<JsonValue> {
3165    let mut map = serde_json::Map::new();
3166    let mut inner = pair.into_inner();
3167    while let Some(key_pair) = inner.next() {
3168        let key = parse_string_literal(key_pair)?;
3169        let value_pair = inner.next().ok_or_else(|| {
3170            ParseError::GrammarError("Expected value in property mapping".to_string())
3171        })?;
3172        let value = parse_string_literal(value_pair)?;
3173        map.insert(key, JsonValue::String(value));
3174    }
3175    Ok(JsonValue::Object(map))
3176}
3177
3178fn unwrap_export(spanned: &Spanned<AstNode>) -> &AstNode {
3179    match &spanned.node {
3180        AstNode::Export(inner) => &inner.node,
3181        other => other,
3182    }
3183}
3184
3185/// Resolve a name in a namespace-keyed map.
3186/// Tries (default_namespace, name) first, then scans all namespaces for an unqualified match.
3187/// Returns None if not found, or the concept ID if exactly one match exists.
3188fn resolve_by_name(
3189    map: &HashMap<(String, String), crate::ConceptId>,
3190    name: &str,
3191    default_namespace: &str,
3192) -> Result<Option<crate::ConceptId>, ParseError> {
3193    // Try exact match in default namespace first
3194    if let Some(id) = map.get(&(default_namespace.to_string(), name.to_string())) {
3195        return Ok(Some(id.clone()));
3196    }
3197    // Fall back to any namespace with this name
3198    let matches: Vec<(&str, &crate::ConceptId)> = map
3199        .iter()
3200        .filter(|((_, n), _)| n == name)
3201        .map(|((namespace, _), id)| (namespace.as_str(), id))
3202        .collect();
3203    if matches.len() == 1 {
3204        return Ok(Some(matches[0].1.clone()));
3205    }
3206    if matches.len() > 1 {
3207        let mut namespaces: Vec<&str> = matches
3208            .into_iter()
3209            .map(|(namespace, _)| namespace)
3210            .collect();
3211        namespaces.sort_unstable();
3212        namespaces.dedup();
3213        return Err(ParseError::Validation(format!(
3214            "Ambiguous reference '{}' found in namespaces: {}",
3215            name,
3216            namespaces.join(", ")
3217        )));
3218    }
3219    Ok(None)
3220}
3221
3222/// Convert AST to Graph
3223pub fn ast_to_graph(ast: Ast) -> ParseResult<Graph> {
3224    ast_to_graph_with_options(ast, &ParseOptions::default())
3225}
3226
3227pub fn ast_to_graph_with_options(mut ast: Ast, options: &ParseOptions) -> ParseResult<Graph> {
3228    use crate::parser::profiles::ProfileRegistry;
3229    let registry = ProfileRegistry::global();
3230    let active_profile = ast
3231        .metadata
3232        .profile
3233        .clone()
3234        .or_else(|| options.active_profile.clone())
3235        .unwrap_or_else(|| "default".to_string());
3236    ast.metadata.profile.get_or_insert(active_profile.clone());
3237
3238    if registry.get(&active_profile).is_none() {
3239        let available = registry.list_names().join(", ");
3240        let message = format!(
3241            "Unknown profile: '{}'. Available profiles: {}",
3242            active_profile, available
3243        );
3244        if options.tolerate_profile_warnings {
3245            log::warn!("{}", message);
3246        } else {
3247            return Err(ParseError::Validation(message));
3248        }
3249    }
3250
3251    let mut graph = Graph::new();
3252    graph.set_version(ast.metadata.version.clone());
3253    let mut entity_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
3254    let mut role_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
3255    let mut resource_map: HashMap<(String, String), crate::ConceptId> = HashMap::new();
3256    let mut relation_map: HashMap<String, crate::ConceptId> = HashMap::new();
3257
3258    let default_namespace = ast
3259        .metadata
3260        .namespace
3261        .clone()
3262        .or_else(|| options.default_namespace.clone())
3263        .unwrap_or_else(|| "default".to_string());
3264
3265    // First pass: Register dimensions and units
3266    {
3267        use crate::units::{Dimension, Unit, UnitError, UnitRegistry};
3268        let registry = UnitRegistry::global();
3269        let mut registry = registry.write().map_err(|e| {
3270            ParseError::GrammarError(format!("Failed to lock unit registry: {}", e))
3271        })?;
3272
3273        for node in &ast.declarations {
3274            let node = unwrap_export(node);
3275            match node {
3276                AstNode::Dimension { name } => {
3277                    let dim = Dimension::parse(name);
3278                    registry.register_dimension(dim);
3279                    graph.add_declared_dimension(name.clone(), default_namespace.clone());
3280                }
3281                AstNode::UnitDeclaration {
3282                    symbol,
3283                    dimension,
3284                    factor,
3285                    base_unit,
3286                } => {
3287                    let dim = Dimension::parse(dimension);
3288                    let unit = Unit::new(
3289                        symbol.clone(),
3290                        symbol.clone(),
3291                        dim,
3292                        *factor,
3293                        base_unit.clone(),
3294                    );
3295                    graph.add_declared_unit(
3296                        symbol.clone(),
3297                        default_namespace.clone(),
3298                        dimension.clone(),
3299                        factor.to_string(),
3300                        base_unit.clone(),
3301                    );
3302                    match registry.get_unit(symbol) {
3303                        Ok(existing) => {
3304                            // Conflict on semantic fields only; a redeclaration
3305                            // matching a preloaded unit's dimension/factor/base
3306                            // is compatible even if display names differ.
3307                            if existing.dimension() != unit.dimension()
3308                                || existing.base_factor() != unit.base_factor()
3309                                || existing.base_unit() != unit.base_unit()
3310                            {
3311                                return Err(ParseError::GrammarError(format!(
3312                                    "Conflicting unit '{}' already registered (existing: dimension={}, base_factor={}, base_unit={}; new: dimension={}, base_factor={}, base_unit={})",
3313                                    symbol,
3314                                    existing.dimension(),
3315                                    existing.base_factor(),
3316                                    existing.base_unit(),
3317                                    unit.dimension(),
3318                                    unit.base_factor(),
3319                                    unit.base_unit(),
3320                                )));
3321                            }
3322                        }
3323                        Err(UnitError::UnitNotFound(_)) => {
3324                            registry.register(unit).map_err(|e| {
3325                                ParseError::GrammarError(format!("Failed to register unit: {}", e))
3326                            })?;
3327                        }
3328                        Err(err) => {
3329                            return Err(ParseError::GrammarError(format!(
3330                                "Failed to inspect unit '{}': {}",
3331                                symbol, err
3332                            )));
3333                        }
3334                    }
3335                }
3336                _ => {}
3337            }
3338        }
3339    }
3340
3341    // Register patterns with eager regex validation
3342    for node in &ast.declarations {
3343        let node = unwrap_export(node);
3344        if let AstNode::Pattern { name, regex } = node {
3345            let namespace = default_namespace.clone();
3346            let pattern = Pattern::new(name.clone(), namespace, regex.clone())
3347                .map_err(ParseError::GrammarError)?;
3348
3349            graph
3350                .add_pattern(pattern)
3351                .map_err(ParseError::GrammarError)?;
3352        }
3353    }
3354
3355    // Register concept changes
3356    for node in &ast.declarations {
3357        let node = unwrap_export(node);
3358        if let AstNode::ConceptChange {
3359            name,
3360            from_version,
3361            to_version,
3362            migration_policy,
3363            breaking_change,
3364        } = node
3365        {
3366            let change = ConceptChange::new_with_namespace(
3367                name.clone(),
3368                default_namespace.clone(),
3369                from_version.clone(),
3370                to_version.clone(),
3371                migration_policy.clone(),
3372                *breaking_change,
3373            );
3374            graph.add_concept_change(change).map_err(|e| {
3375                ParseError::GrammarError(format!("Failed to add concept change: {}", e))
3376            })?;
3377        }
3378    }
3379
3380    // Second pass: Add roles, entities, and resources
3381    for node in &ast.declarations {
3382        let node = unwrap_export(node);
3383        match node {
3384            AstNode::Role { name, domain } => {
3385                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
3386                let key = (namespace.clone(), name.clone());
3387                if role_map.contains_key(&key) {
3388                    return Err(ParseError::duplicate_declaration_no_loc(format!(
3389                        "Role '{}' already declared in namespace '{}'",
3390                        name, namespace
3391                    )));
3392                }
3393
3394                let role = Role::new_with_namespace(name.clone(), namespace);
3395                let role_id = role.id().clone();
3396                graph
3397                    .add_role(role)
3398                    .map_err(|e| ParseError::GrammarError(format!("Failed to add role: {}", e)))?;
3399                role_map.insert(key, role_id);
3400            }
3401            AstNode::Entity {
3402                name,
3403                domain,
3404                version,
3405                annotations,
3406                body: _,
3407            } => {
3408                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
3409                let key = (namespace.clone(), name.clone());
3410                if entity_map.contains_key(&key) {
3411                    return Err(ParseError::duplicate_declaration_no_loc(format!(
3412                        "Entity '{}' already declared in namespace '{}'",
3413                        name, namespace
3414                    )));
3415                }
3416
3417                let mut entity = Entity::new_with_namespace(name.clone(), namespace);
3418
3419                if let Some(v_str) = version {
3420                    let sem_ver = SemanticVersion::parse(v_str).map_err(|e| {
3421                        ParseError::GrammarError(format!(
3422                            "Invalid entity version '{}': {}",
3423                            v_str, e
3424                        ))
3425                    })?;
3426                    entity = entity.with_version(sem_ver);
3427                }
3428
3429                if let Some(replaces_val) = annotations.get("replaces") {
3430                    if let Some(replaces_str) = replaces_val.as_str() {
3431                        entity = entity.with_replaces(replaces_str.to_string());
3432                    }
3433                }
3434
3435                if let Some(changes_val) = annotations.get("changes") {
3436                    if let Some(changes_arr) = changes_val.as_array() {
3437                        let changes: Vec<String> = changes_arr
3438                            .iter()
3439                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
3440                            .collect();
3441                        entity = entity.with_changes(changes);
3442                    }
3443                }
3444
3445                let entity_id = entity.id().clone();
3446                graph.add_entity(entity).map_err(|e| {
3447                    ParseError::GrammarError(format!("Failed to add entity: {}", e))
3448                })?;
3449                entity_map.insert(key, entity_id);
3450            }
3451            AstNode::Resource {
3452                name,
3453                unit_name,
3454                domain,
3455                ..
3456            } => {
3457                let namespace = domain.as_ref().unwrap_or(&default_namespace).clone();
3458                let key = (namespace.clone(), name.clone());
3459                if resource_map.contains_key(&key) {
3460                    return Err(ParseError::duplicate_declaration_no_loc(format!(
3461                        "Resource '{}' already declared in namespace '{}'",
3462                        name, namespace
3463                    )));
3464                }
3465
3466                let unit = unit_from_string(unit_name.as_deref().unwrap_or("units"));
3467                let resource = Resource::new_with_namespace(name.clone(), unit, namespace);
3468                let resource_id = resource.id().clone();
3469                graph.add_resource(resource).map_err(|e| {
3470                    ParseError::GrammarError(format!("Failed to add resource: {}", e))
3471                })?;
3472                resource_map.insert(key, resource_id);
3473            }
3474            _ => {}
3475        }
3476    }
3477
3478    // Third pass: Add flows
3479    for node in &ast.declarations {
3480        let node = unwrap_export(node);
3481        if let AstNode::Flow {
3482            resource_name,
3483            annotations,
3484            from_entity,
3485            to_entity,
3486            quantity,
3487        } = node
3488        {
3489            let from_id = resolve_by_name(&entity_map, from_entity, &default_namespace)?
3490                .ok_or_else(|| ParseError::undefined_entity_no_loc(from_entity))?;
3491
3492            let to_id = resolve_by_name(&entity_map, to_entity, &default_namespace)?
3493                .ok_or_else(|| ParseError::undefined_entity_no_loc(to_entity))?;
3494
3495            let resource_id = resolve_by_name(&resource_map, resource_name, &default_namespace)?
3496                .ok_or_else(|| ParseError::undefined_resource_no_loc(resource_name))?;
3497
3498            let qty = quantity.unwrap_or(Decimal::ZERO);
3499            let mut flow = Flow::new_with_namespace(
3500                resource_id.clone(),
3501                from_id.clone(),
3502                to_id.clone(),
3503                qty,
3504                default_namespace.clone(),
3505            );
3506
3507            // Preserve flow annotations (e.g. `@cqrs { "kind": "command" }`)
3508            // onto the flow's attribute map so downstream projection targets
3509            // can read them via `ResolvedFlow::annotations`.
3510            for (key, value) in annotations {
3511                flow.set_attribute(key.clone(), value.clone());
3512            }
3513
3514            graph
3515                .add_flow(flow)
3516                .map_err(|e| ParseError::GrammarError(format!("Failed to add flow: {}", e)))?;
3517        }
3518    }
3519
3520    // Fourth pass: Add relations
3521    for node in &ast.declarations {
3522        let node = unwrap_export(node);
3523        if let AstNode::Relation {
3524            name,
3525            subject_role,
3526            predicate,
3527            object_role,
3528            via_flow,
3529        } = node
3530        {
3531            if relation_map.contains_key(name) {
3532                return Err(ParseError::duplicate_declaration_no_loc(format!(
3533                    "Relation '{}' already declared",
3534                    name
3535                )));
3536            }
3537
3538            let subject_id = resolve_by_name(&role_map, subject_role, &default_namespace)?
3539                .ok_or_else(|| {
3540                    ParseError::GrammarError(format!("Undefined subject role '{}'", subject_role))
3541                })?;
3542
3543            let object_id = resolve_by_name(&role_map, object_role, &default_namespace)?
3544                .ok_or_else(|| {
3545                    ParseError::GrammarError(format!("Undefined object role '{}'", object_role))
3546                })?;
3547
3548            let via_flow_id = if let Some(flow_name) = via_flow {
3549                Some(
3550                    resolve_by_name(&resource_map, flow_name, &default_namespace)?
3551                        .ok_or_else(|| ParseError::undefined_resource_no_loc(flow_name))?,
3552                )
3553            } else {
3554                None
3555            };
3556
3557            let relation = RelationType::new(
3558                name.clone(),
3559                default_namespace.clone(),
3560                subject_id.clone(),
3561                predicate.clone(),
3562                object_id.clone(),
3563                via_flow_id,
3564            );
3565
3566            let relation_id = relation.id().clone();
3567            graph.add_relation_type(relation).map_err(|e| {
3568                ParseError::GrammarError(format!("Failed to add relation '{}': {}", name, e))
3569            })?;
3570            relation_map.insert(name.clone(), relation_id);
3571        }
3572    }
3573
3574    // Role binding pass: bind previously-declared roles to previously-
3575    // declared entities (Graph::assign_role_to_entity already rejects a
3576    // dangling reference on either side).
3577    for node in &ast.declarations {
3578        let node = unwrap_export(node);
3579        if let AstNode::RoleBinding { role, entity } = node {
3580            let role_id =
3581                resolve_by_name(&role_map, role, &default_namespace)?.ok_or_else(|| {
3582                    ParseError::GrammarError(format!(
3583                        "role_binding references undefined role '{}'",
3584                        role
3585                    ))
3586                })?;
3587            let entity_id =
3588                resolve_by_name(&entity_map, entity, &default_namespace)?.ok_or_else(|| {
3589                    ParseError::GrammarError(format!(
3590                        "role_binding references undefined entity '{}'",
3591                        entity
3592                    ))
3593                })?;
3594            graph
3595                .assign_role_to_entity(entity_id, role_id)
3596                .map_err(|e| {
3597                    ParseError::GrammarError(format!(
3598                        "Failed to bind role '{}' to entity '{}': {}",
3599                        role, entity, e
3600                    ))
3601                })?;
3602        }
3603    }
3604
3605    // Instance pass: Add instances (after entities are created)
3606    for node in &ast.declarations {
3607        let node = unwrap_export(node);
3608        if let AstNode::Instance {
3609            name,
3610            entity_type,
3611            fields,
3612        } = node
3613        {
3614            let namespace = default_namespace.clone();
3615            let mut instance = crate::primitives::Instance::new_with_namespace(
3616                name.clone(),
3617                entity_type.clone(),
3618                namespace,
3619            );
3620
3621            // Evaluate and set fields
3622            for (field_name, field_expr) in fields {
3623                let value = expression_to_json(field_expr)?;
3624                instance.set_field(field_name.clone(), value);
3625            }
3626
3627            graph.add_entity_instance(instance).map_err(|e| {
3628                ParseError::GrammarError(format!("Failed to add entity instance '{}': {}", name, e))
3629            })?;
3630        }
3631    }
3632
3633    // Fifth pass: Add policies
3634    for node in &ast.declarations {
3635        let node = unwrap_export(node);
3636        if let AstNode::Policy {
3637            name,
3638            version,
3639            metadata,
3640            expression,
3641        } = node
3642        {
3643            let namespace = ast
3644                .metadata
3645                .namespace
3646                .as_ref()
3647                .cloned()
3648                .or_else(|| options.default_namespace.clone())
3649                .unwrap_or_else(|| "default".to_string());
3650
3651            let kind = metadata.kind.as_ref().map(|kind| match kind {
3652                PolicyKind::Constraint => CorePolicyKind::Constraint,
3653                PolicyKind::Derivation => CorePolicyKind::Derivation,
3654                PolicyKind::Obligation => CorePolicyKind::Obligation,
3655            });
3656
3657            let modality = metadata.modality.as_ref().map(|modality| match modality {
3658                PolicyModality::Obligation => CorePolicyModality::Obligation,
3659                PolicyModality::Prohibition => CorePolicyModality::Prohibition,
3660                PolicyModality::Permission => CorePolicyModality::Permission,
3661            });
3662
3663            let mut policy =
3664                Policy::new_with_namespace(name.clone(), namespace, expression.clone())
3665                    .with_metadata(
3666                        kind,
3667                        modality,
3668                        metadata.priority,
3669                        metadata.rationale.clone(),
3670                        metadata.tags.clone(),
3671                    );
3672
3673            let version_to_apply = version
3674                .as_ref()
3675                .cloned()
3676                .or_else(|| ast.metadata.version.clone());
3677
3678            if let Some(version_str) = version_to_apply {
3679                let semantic_version = SemanticVersion::parse(&version_str).map_err(|err| {
3680                    ParseError::GrammarError(format!(
3681                        "Invalid policy version '{}': {}",
3682                        version_str, err
3683                    ))
3684                })?;
3685                policy = policy.with_version(semantic_version);
3686            }
3687
3688            graph.add_policy(policy).map_err(|e| {
3689                ParseError::GrammarError(format!("Failed to add policy '{}': {}", name, e))
3690            })?;
3691        }
3692    }
3693
3694    // Sixth pass: Add metrics
3695    for node in &ast.declarations {
3696        let node = unwrap_export(node);
3697        if let AstNode::Metric {
3698            name,
3699            expression,
3700            metadata,
3701        } = node
3702        {
3703            let namespace = ast
3704                .metadata
3705                .namespace
3706                .as_ref()
3707                .cloned()
3708                .or_else(|| options.default_namespace.clone())
3709                .unwrap_or_else(|| "default".to_string());
3710
3711            let mut metric =
3712                crate::primitives::Metric::new(name.clone(), namespace, expression.clone());
3713
3714            if let Some(duration) = metadata.refresh_interval {
3715                metric = metric.with_refresh_interval(duration);
3716            }
3717
3718            if let Some(unit) = &metadata.unit {
3719                metric = metric.with_unit(unit.clone());
3720            }
3721
3722            if let Some(threshold) = metadata.threshold {
3723                metric = metric.with_threshold(threshold);
3724            }
3725
3726            if let Some(severity) = metadata.severity.clone() {
3727                metric = metric.with_severity(severity);
3728            }
3729
3730            if let Some(target) = metadata.target {
3731                metric = metric.with_target(target);
3732            }
3733
3734            if let Some(duration) = metadata.window {
3735                metric = metric.with_window(duration);
3736            }
3737
3738            graph.add_metric(metric).map_err(|e| {
3739                ParseError::GrammarError(format!("Failed to add metric '{}': {}", name, e))
3740            })?;
3741        }
3742    }
3743
3744    // Seventh pass: Add mappings
3745    for node in &ast.declarations {
3746        let node = unwrap_export(node);
3747        if let AstNode::MappingDecl {
3748            name,
3749            target,
3750            rules,
3751        } = node
3752        {
3753            let namespace = ast
3754                .metadata
3755                .namespace
3756                .clone()
3757                .or_else(|| options.default_namespace.clone())
3758                .unwrap_or_else(|| "default".to_string());
3759            let mapping = crate::primitives::MappingContract::new(
3760                crate::ConceptId::from_concept(&namespace, name),
3761                name.clone(),
3762                namespace,
3763                target.clone(),
3764                rules.clone(),
3765            );
3766            graph
3767                .add_mapping(mapping)
3768                .map_err(|e| ParseError::GrammarError(format!("Failed to add mapping: {}", e)))?;
3769        }
3770    }
3771
3772    // Eighth pass: Add projections
3773    for node in &ast.declarations {
3774        let node = unwrap_export(node);
3775        if let AstNode::ProjectionDecl {
3776            name,
3777            target,
3778            overrides,
3779        } = node
3780        {
3781            let namespace = ast
3782                .metadata
3783                .namespace
3784                .clone()
3785                .or_else(|| options.default_namespace.clone())
3786                .unwrap_or_else(|| "default".to_string());
3787            let projection = crate::primitives::ProjectionContract::new(
3788                crate::ConceptId::from_concept(&namespace, name),
3789                name.clone(),
3790                namespace,
3791                target.clone(),
3792                overrides.clone(),
3793            );
3794            graph.add_projection(projection).map_err(|e| {
3795                ParseError::GrammarError(format!("Failed to add projection: {}", e))
3796            })?;
3797        }
3798    }
3799
3800    Ok(graph)
3801}
3802
3803/// Parse metric declaration
3804fn parse_metric(pair: Pair<Rule>) -> ParseResult<AstNode> {
3805    let mut inner = pair.into_inner();
3806
3807    let name = parse_name(
3808        inner
3809            .next()
3810            .ok_or_else(|| ParseError::GrammarError("Expected metric name".to_string()))?,
3811    )?;
3812
3813    let mut metadata = MetricMetadata {
3814        refresh_interval: None,
3815        unit: None,
3816        threshold: None,
3817        severity: None,
3818        target: None,
3819        window: None,
3820    };
3821
3822    let mut expression_pair = None;
3823
3824    for part in inner {
3825        match part.as_rule() {
3826            Rule::metric_annotation => {
3827                let mut annotation_inner = part.into_inner();
3828                let key_pair = annotation_inner.next().ok_or_else(|| {
3829                    ParseError::GrammarError("Expected annotation key".to_string())
3830                })?;
3831
3832                match key_pair.as_rule() {
3833                    Rule::ma_refresh_interval => {
3834                        let value_pair = annotation_inner.next().ok_or_else(|| {
3835                            ParseError::GrammarError("Expected refresh interval value".to_string())
3836                        })?;
3837                        let value = parse_number_i64(value_pair)?;
3838                        let unit_pair = annotation_inner.next().ok_or_else(|| {
3839                            ParseError::GrammarError("Expected refresh interval unit".to_string())
3840                        })?;
3841                        let unit = parse_string_literal(unit_pair.clone())?;
3842                        let duration = parse_duration_with_unit(value, &unit, unit_pair.as_span())?;
3843                        metadata.refresh_interval = Some(duration);
3844                    }
3845                    Rule::ma_unit => {
3846                        let unit_pair = annotation_inner
3847                            .next()
3848                            .ok_or_else(|| ParseError::GrammarError("Expected unit".to_string()))?;
3849                        metadata.unit = Some(parse_string_literal(unit_pair)?);
3850                    }
3851                    Rule::ma_threshold => {
3852                        let value_pair = annotation_inner.next().ok_or_else(|| {
3853                            ParseError::GrammarError("Expected threshold value".to_string())
3854                        })?;
3855                        metadata.threshold = Some(parse_decimal(value_pair)?);
3856                    }
3857                    Rule::ma_severity => {
3858                        let severity_pair = annotation_inner.next().ok_or_else(|| {
3859                            ParseError::GrammarError("Expected severity".to_string())
3860                        })?;
3861                        let severity_str = parse_string_literal(severity_pair.clone())?;
3862                        let severity =
3863                            parse_severity_value(&severity_str, severity_pair.as_span())?;
3864                        metadata.severity = Some(severity);
3865                    }
3866                    Rule::ma_target => {
3867                        let value_pair = annotation_inner.next().ok_or_else(|| {
3868                            ParseError::GrammarError("Expected target value".to_string())
3869                        })?;
3870                        metadata.target = Some(parse_decimal(value_pair)?);
3871                    }
3872                    Rule::ma_window => {
3873                        let value_pair = annotation_inner.next().ok_or_else(|| {
3874                            ParseError::GrammarError("Expected window value".to_string())
3875                        })?;
3876                        let value = parse_number_i64(value_pair)?;
3877                        let unit_pair = annotation_inner.next().ok_or_else(|| {
3878                            ParseError::GrammarError("Expected window unit".to_string())
3879                        })?;
3880                        let unit = parse_string_literal(unit_pair.clone())?;
3881                        let duration = parse_duration_with_unit(value, &unit, unit_pair.as_span())?;
3882                        metadata.window = Some(duration);
3883                    }
3884                    _ => {
3885                        let (line, column) = key_pair.as_span().start_pos().line_col();
3886                        return Err(ParseError::GrammarError(format!(
3887                            "Unknown metric annotation '{}' at {}:{}",
3888                            key_pair.as_str(),
3889                            line,
3890                            column
3891                        )));
3892                    }
3893                }
3894            }
3895            Rule::expression => {
3896                expression_pair = Some(part);
3897            }
3898            _ => {}
3899        }
3900    }
3901
3902    let expression = parse_expression(
3903        expression_pair
3904            .ok_or_else(|| ParseError::GrammarError("Expected metric expression".to_string()))?,
3905    )?;
3906
3907    Ok(AstNode::Metric {
3908        name,
3909        expression,
3910        metadata,
3911    })
3912}
3913
3914fn parse_duration_with_unit(value: i64, unit: &str, span: Span<'_>) -> ParseResult<Duration> {
3915    let normalized_unit = unit.to_ascii_lowercase();
3916    let multiplier = match normalized_unit.as_str() {
3917        "second" => Some(1),
3918        "seconds" | "s" => Some(1),
3919        "minute" => Some(60),
3920        "minutes" | "m" => Some(60),
3921        "hour" => Some(60 * 60),
3922        "hours" | "h" => Some(60 * 60),
3923        "day" => Some(60 * 60 * 24),
3924        "days" | "d" => Some(60 * 60 * 24),
3925        _ => None,
3926    }
3927    .ok_or_else(|| {
3928        let (line, column) = span.start_pos().line_col();
3929        ParseError::GrammarError(format!(
3930            "Invalid duration unit '{}' at {}:{} (allowed: second(s)/s, minute(s)/m, hour(s)/h, day(s)/d)",
3931            unit, line, column
3932        ))
3933    })?;
3934
3935    let total_seconds = value.checked_mul(multiplier).ok_or_else(|| {
3936        let (line, column) = span.start_pos().line_col();
3937        ParseError::GrammarError(format!(
3938            "Duration overflow for value {} {} at {}:{}",
3939            value, unit, line, column
3940        ))
3941    })?;
3942
3943    Ok(Duration::seconds(total_seconds))
3944}
3945
3946fn parse_severity_value(value: &str, span: Span<'_>) -> ParseResult<Severity> {
3947    let normalized = value.to_ascii_lowercase();
3948    match normalized.as_str() {
3949        "info" => Ok(Severity::Info),
3950        "warning" => Ok(Severity::Warning),
3951        "error" => Ok(Severity::Error),
3952        "critical" => Ok(Severity::Critical),
3953        _ => {
3954            let (line, column) = span.start_pos().line_col();
3955            Err(ParseError::GrammarError(format!(
3956                "Unknown severity '{}' at {}:{} (expected one of: info, warning, error, critical)",
3957                value, line, column
3958            )))
3959        }
3960    }
3961}
3962
3963fn parse_number_i64(pair: Pair<Rule>) -> ParseResult<i64> {
3964    let s = pair.as_str();
3965    s.parse::<i64>()
3966        .map_err(|_| ParseError::GrammarError(format!("Invalid integer: {}", s)))
3967}