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                        println!("debug insert annotation {} = {:?}", key, value);
1284                        annotations.insert(key, value);
1285                    }
1286                    _ => {
1287                        return Err(ParseError::GrammarError(format!(
1288                            "Unexpected flow annotation: {}",
1289                            key_pair.as_str()
1290                        )));
1291                    }
1292                }
1293            }
1294            Rule::in_keyword => {
1295                // Skip "in"
1296            }
1297            Rule::identifier => {
1298                // This must be the domain
1299                domain = Some(parse_identifier(part)?);
1300            }
1301            _ => {}
1302        }
1303    }
1304
1305    Ok(AstNode::Entity {
1306        name,
1307        version,
1308        annotations,
1309        domain,
1310        body,
1311    })
1312}
1313
1314/// Parse concept change declaration
1315fn parse_concept_change(pair: Pair<Rule>) -> ParseResult<AstNode> {
1316    let mut inner = pair.into_inner();
1317
1318    let name =
1319        parse_name(inner.next().ok_or_else(|| {
1320            ParseError::GrammarError("Expected concept change name".to_string())
1321        })?)?;
1322
1323    let mut from_version = String::new();
1324    let mut to_version = String::new();
1325    let mut migration_policy = String::new();
1326    let mut breaking_change = false;
1327
1328    for part in inner {
1329        if part.as_rule() == Rule::concept_change_annotation {
1330            let mut annotation_inner = part.into_inner();
1331
1332            let key_pair = annotation_inner
1333                .next()
1334                .ok_or_else(|| ParseError::GrammarError("Expected annotation key".to_string()))?;
1335            let value_pair = annotation_inner
1336                .next()
1337                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
1338
1339            match key_pair.as_rule() {
1340                Rule::cc_from_version => from_version = parse_version(value_pair)?,
1341                Rule::cc_to_version => to_version = parse_version(value_pair)?,
1342                Rule::cc_migration_policy => migration_policy = parse_identifier(value_pair)?,
1343                Rule::cc_breaking_change => {
1344                    breaking_change = value_pair.as_str() == "true";
1345                }
1346                _ => {}
1347            }
1348        }
1349    }
1350
1351    if from_version.is_empty() {
1352        return Err(ParseError::GrammarError(
1353            "Missing cc_from_version annotation".to_string(),
1354        ));
1355    }
1356
1357    if to_version.is_empty() {
1358        return Err(ParseError::GrammarError(
1359            "Missing cc_to_version annotation".to_string(),
1360        ));
1361    }
1362
1363    if migration_policy.is_empty() {
1364        return Err(ParseError::GrammarError(
1365            "Missing cc_migration_policy annotation".to_string(),
1366        ));
1367    }
1368
1369    Ok(AstNode::ConceptChange {
1370        name,
1371        from_version,
1372        to_version,
1373        migration_policy,
1374        breaking_change,
1375    })
1376}
1377
1378/// Parse resource declaration
1379fn parse_resource(pair: Pair<Rule>) -> ParseResult<AstNode> {
1380    let mut inner = pair.into_inner();
1381
1382    let name = parse_name(
1383        inner
1384            .next()
1385            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
1386    )?;
1387
1388    let mut annotations = HashMap::new();
1389    let mut unit_name = None;
1390    let mut domain = None;
1391    let mut saw_in_keyword = false;
1392
1393    for part in inner {
1394        match part.as_rule() {
1395            Rule::resource_annotation => {
1396                let mut annotation_inner = part.into_inner();
1397                let key_pair = annotation_inner
1398                    .next()
1399                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;
1400
1401                match key_pair.as_rule() {
1402                    Rule::ea_replaces => {
1403                        let target_name =
1404                            parse_name(annotation_inner.next().ok_or_else(|| {
1405                                ParseError::GrammarError("Expected name in replaces".to_string())
1406                            })?)?;
1407                        // Check for optional version
1408                        let mut target_version = None;
1409                        if let Some(next) = annotation_inner.next() {
1410                            if next.as_rule() == Rule::version {
1411                                target_version = Some(next.as_str().to_string());
1412                            }
1413                        }
1414
1415                        let value = if let Some(v) = target_version {
1416                            format!("{} v{}", target_name, v)
1417                        } else {
1418                            target_name
1419                        };
1420                        annotations.insert("replaces".to_string(), JsonValue::String(value));
1421                    }
1422                    Rule::ea_changes => {
1423                        let array_pair = annotation_inner.next().ok_or_else(|| {
1424                            ParseError::GrammarError("Expected string array in changes".to_string())
1425                        })?;
1426                        let mut changes = Vec::new();
1427                        for item in array_pair.into_inner() {
1428                            changes.push(parse_string_literal(item)?);
1429                        }
1430                        annotations.insert(
1431                            "changes".to_string(),
1432                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
1433                        );
1434                    }
1435                    Rule::identifier => {
1436                        let key = parse_identifier(key_pair)?.to_lowercase();
1437                        let value_pair = annotation_inner.next().ok_or_else(|| {
1438                            ParseError::GrammarError("Expected annotation value".to_string())
1439                        })?;
1440                        let value = parse_annotation_value(value_pair)?;
1441                        annotations.insert(key, value);
1442                    }
1443                    _ => {
1444                        return Err(ParseError::GrammarError(format!(
1445                            "Unexpected flow annotation: {}",
1446                            key_pair.as_str()
1447                        )));
1448                    }
1449                }
1450            }
1451            Rule::in_keyword => {
1452                // Mark that we've seen 'in', next identifier is domain
1453                saw_in_keyword = true;
1454            }
1455            Rule::identifier => {
1456                // If we've seen 'in' keyword, this is domain; otherwise it's unit
1457                if saw_in_keyword {
1458                    domain = Some(parse_identifier(part)?);
1459                    saw_in_keyword = false; // Reset for safety
1460                } else {
1461                    unit_name = Some(parse_identifier(part)?);
1462                }
1463            }
1464            _ => {}
1465        }
1466    }
1467
1468    Ok(AstNode::Resource {
1469        name,
1470        annotations,
1471        unit_name,
1472        domain,
1473    })
1474}
1475
1476/// Parse flow declaration
1477fn parse_flow(pair: Pair<Rule>) -> ParseResult<AstNode> {
1478    let mut inner = pair.into_inner();
1479
1480    let resource_name = parse_string_literal(
1481        inner
1482            .next()
1483            .ok_or_else(|| ParseError::GrammarError("Expected resource name".to_string()))?,
1484    )?;
1485
1486    let mut annotations = HashMap::new();
1487    let mut from_entity = None;
1488    let mut to_entity = None;
1489    let mut quantity = None;
1490    let mut pending_annotation_key: Option<String> = None;
1491
1492    for part in inner {
1493        match part.as_rule() {
1494            Rule::flow_annotation => {
1495                let mut annotation_inner = part.into_inner();
1496                let key_pair = annotation_inner
1497                    .next()
1498                    .ok_or_else(|| ParseError::GrammarError("Empty annotation".to_string()))?;
1499
1500                match key_pair.as_rule() {
1501                    Rule::ea_replaces => {
1502                        let target_name =
1503                            parse_name(annotation_inner.next().ok_or_else(|| {
1504                                ParseError::GrammarError("Expected name in replaces".to_string())
1505                            })?)?;
1506                        // Check for optional version
1507                        let mut target_version = None;
1508                        if let Some(next) = annotation_inner.next() {
1509                            if next.as_rule() == Rule::version {
1510                                target_version = Some(next.as_str().to_string());
1511                            }
1512                        }
1513
1514                        let value = if let Some(v) = target_version {
1515                            format!("{} v{}", target_name, v)
1516                        } else {
1517                            target_name
1518                        };
1519                        annotations.insert("replaces".to_string(), JsonValue::String(value));
1520                    }
1521                    Rule::ea_changes => {
1522                        let array_pair = annotation_inner.next().ok_or_else(|| {
1523                            ParseError::GrammarError("Expected string array in changes".to_string())
1524                        })?;
1525                        let mut changes = Vec::new();
1526                        for item in array_pair.into_inner() {
1527                            changes.push(parse_string_literal(item)?);
1528                        }
1529                        annotations.insert(
1530                            "changes".to_string(),
1531                            JsonValue::Array(changes.into_iter().map(JsonValue::String).collect()),
1532                        );
1533                    }
1534                    Rule::identifier => {
1535                        let key = parse_identifier(key_pair)?.to_lowercase();
1536                        let value_pair = annotation_inner.next().ok_or_else(|| {
1537                            ParseError::GrammarError("Expected annotation value".to_string())
1538                        })?;
1539                        let value = parse_annotation_value(value_pair)?;
1540                        annotations.insert(key, value);
1541                    }
1542                    _ => {
1543                        return Err(ParseError::GrammarError(format!(
1544                            "Unexpected flow annotation: {}",
1545                            key_pair.as_str()
1546                        )));
1547                    }
1548                }
1549            }
1550            Rule::identifier => {
1551                if pending_annotation_key.is_some() {
1552                    return Err(ParseError::GrammarError(
1553                        "Unexpected annotation key without value".to_string(),
1554                    ));
1555                }
1556                pending_annotation_key = Some(parse_identifier(part)?.to_lowercase());
1557            }
1558            Rule::annotation_value
1559            | Rule::object_literal
1560            | Rule::string_array
1561            | Rule::boolean
1562            | Rule::number
1563            | Rule::string_literal => {
1564                if let Some(key) = pending_annotation_key.take() {
1565                    let value = parse_annotation_value(part)?;
1566                    annotations.insert(key, value);
1567                    continue;
1568                }
1569
1570                if part.as_rule() == Rule::string_literal {
1571                    // These are from_entity and to_entity in order
1572                    let parsed = parse_string_literal(part)?;
1573                    if from_entity.is_none() {
1574                        from_entity = Some(parsed);
1575                    } else if to_entity.is_none() {
1576                        to_entity = Some(parsed);
1577                    }
1578                } else if part.as_rule() == Rule::number {
1579                    quantity = Some(parse_decimal(part)?);
1580                }
1581            }
1582            _ => {}
1583        }
1584    }
1585
1586    Ok(AstNode::Flow {
1587        resource_name,
1588        annotations,
1589        from_entity: from_entity
1590            .ok_or_else(|| ParseError::GrammarError("Expected from entity".to_string()))?,
1591        to_entity: to_entity
1592            .ok_or_else(|| ParseError::GrammarError("Expected to entity".to_string()))?,
1593        quantity,
1594    })
1595}
1596
1597/// Parse pattern declaration
1598fn parse_pattern(pair: Pair<Rule>) -> ParseResult<AstNode> {
1599    let mut inner = pair.into_inner();
1600
1601    let name = parse_name(
1602        inner
1603            .next()
1604            .ok_or_else(|| ParseError::GrammarError("Expected pattern name".to_string()))?,
1605    )?;
1606
1607    let regex_literal = inner
1608        .next()
1609        .ok_or_else(|| ParseError::GrammarError("Expected regex for pattern".to_string()))?;
1610    let regex = parse_string_literal(regex_literal)?;
1611
1612    Ok(AstNode::Pattern { name, regex })
1613}
1614
1615/// Parse role declaration
1616fn parse_role(pair: Pair<Rule>) -> ParseResult<AstNode> {
1617    let mut inner = pair.into_inner();
1618
1619    let name = parse_name(
1620        inner
1621            .next()
1622            .ok_or_else(|| ParseError::GrammarError("Expected role name".to_string()))?,
1623    )?;
1624
1625    let mut domain = None;
1626    for part in inner {
1627        match part.as_rule() {
1628            Rule::in_keyword => {
1629                // Skip "in"
1630            }
1631            Rule::identifier => {
1632                domain = Some(parse_identifier(part)?);
1633            }
1634            _ => {}
1635        }
1636    }
1637
1638    Ok(AstNode::Role { name, domain })
1639}
1640
1641/// Parse relation declaration
1642fn parse_relation(pair: Pair<Rule>) -> ParseResult<AstNode> {
1643    let mut inner = pair.into_inner();
1644
1645    let name = parse_name(
1646        inner
1647            .next()
1648            .ok_or_else(|| ParseError::GrammarError("Expected relation name".to_string()))?,
1649    )?;
1650
1651    let subject_literal = inner
1652        .next()
1653        .ok_or_else(|| ParseError::GrammarError("Expected subject role in relation".to_string()))?;
1654    let subject_role = parse_string_literal(subject_literal)?;
1655
1656    let predicate_literal = inner
1657        .next()
1658        .ok_or_else(|| ParseError::GrammarError("Expected predicate in relation".to_string()))?;
1659    let predicate = parse_string_literal(predicate_literal)?;
1660
1661    let object_literal = inner
1662        .next()
1663        .ok_or_else(|| ParseError::GrammarError("Expected object role in relation".to_string()))?;
1664    let object_role = parse_string_literal(object_literal)?;
1665
1666    let via_flow = if let Some(via_pair) = inner.next() {
1667        match via_pair.as_rule() {
1668            Rule::string_literal => Some(parse_string_literal(via_pair)?),
1669            _ => {
1670                let mut via_inner = via_pair.into_inner();
1671                let flow_literal = via_inner.next().ok_or_else(|| {
1672                    ParseError::GrammarError("Expected flow name after via".to_string())
1673                })?;
1674                Some(parse_string_literal(flow_literal)?)
1675            }
1676        }
1677    } else {
1678        None
1679    };
1680
1681    Ok(AstNode::Relation {
1682        name,
1683        subject_role,
1684        predicate,
1685        object_role,
1686        via_flow,
1687    })
1688}
1689
1690fn parse_role_binding(pair: Pair<Rule>) -> ParseResult<AstNode> {
1691    let mut inner = pair.into_inner();
1692    let role = parse_string_literal(inner.next().ok_or_else(|| {
1693        ParseError::GrammarError("Expected role name in role_binding".to_string())
1694    })?)?;
1695    let entity = parse_string_literal(inner.next().ok_or_else(|| {
1696        ParseError::GrammarError("Expected entity name in role_binding".to_string())
1697    })?)?;
1698    Ok(AstNode::RoleBinding { role, entity })
1699}
1700
1701/// Parse instance declaration
1702fn parse_instance(pair: Pair<Rule>) -> ParseResult<AstNode> {
1703    let mut inner = pair.into_inner();
1704
1705    let name = parse_identifier(
1706        inner
1707            .next()
1708            .ok_or_else(|| ParseError::GrammarError("Expected instance name".to_string()))?,
1709    )?;
1710
1711    let entity_type = parse_string_literal(
1712        inner
1713            .next()
1714            .ok_or_else(|| ParseError::GrammarError("Expected entity type".to_string()))?,
1715    )?;
1716
1717    let mut fields = HashMap::new();
1718
1719    // Parse optional instance body
1720    if let Some(body_pair) = inner.next() {
1721        if body_pair.as_rule() == Rule::instance_body {
1722            for field_pair in body_pair.into_inner() {
1723                if field_pair.as_rule() == Rule::instance_field {
1724                    let span = field_pair.as_span();
1725                    let mut field_inner = field_pair.into_inner();
1726
1727                    let field_name = parse_identifier(field_inner.next().ok_or_else(|| {
1728                        ParseError::GrammarError("Expected field name".to_string())
1729                    })?)?;
1730
1731                    if fields.contains_key(&field_name) {
1732                        let (line, column) = span.start_pos().line_col();
1733                        return Err(ParseError::GrammarError(format!(
1734                            "Duplicate field name '{}' at line {}, column {}",
1735                            field_name, line, column
1736                        )));
1737                    }
1738
1739                    let field_value = parse_expression(field_inner.next().ok_or_else(|| {
1740                        ParseError::GrammarError("Expected field value".to_string())
1741                    })?)?;
1742
1743                    fields.insert(field_name, field_value);
1744                }
1745            }
1746        }
1747    }
1748
1749    Ok(AstNode::Instance {
1750        name,
1751        entity_type,
1752        fields,
1753    })
1754}
1755
1756/// Parse policy declaration
1757fn parse_policy(pair: Pair<Rule>) -> ParseResult<AstNode> {
1758    let mut inner = pair.into_inner();
1759
1760    let name = parse_identifier(
1761        inner
1762            .next()
1763            .ok_or_else(|| ParseError::GrammarError("Expected policy name".to_string()))?,
1764    )?;
1765
1766    let mut metadata = PolicyMetadata {
1767        kind: None,
1768        modality: None,
1769        priority: None,
1770        rationale: None,
1771        tags: Vec::new(),
1772    };
1773    let mut version: Option<String> = None;
1774
1775    for next_pair in inner {
1776        match next_pair.as_rule() {
1777            Rule::policy_kind => {
1778                metadata.kind = Some(match next_pair.as_str().to_lowercase().as_str() {
1779                    "constraint" => PolicyKind::Constraint,
1780                    "derivation" => PolicyKind::Derivation,
1781                    "obligation" => PolicyKind::Obligation,
1782                    _ => {
1783                        return Err(ParseError::GrammarError(format!(
1784                            "Unknown policy kind: {}",
1785                            next_pair.as_str()
1786                        )))
1787                    }
1788                });
1789            }
1790            Rule::policy_modality => {
1791                metadata.modality = Some(match next_pair.as_str().to_lowercase().as_str() {
1792                    "obligation" => PolicyModality::Obligation,
1793                    "prohibition" => PolicyModality::Prohibition,
1794                    "permission" => PolicyModality::Permission,
1795                    _ => {
1796                        return Err(ParseError::GrammarError(format!(
1797                            "Unknown policy modality: {}",
1798                            next_pair.as_str()
1799                        )))
1800                    }
1801                });
1802            }
1803            Rule::number => {
1804                metadata.priority = Some(parse_number(next_pair)?);
1805            }
1806            Rule::policy_annotation => {
1807                parse_policy_annotation(next_pair, &mut metadata)?;
1808            }
1809            Rule::version => {
1810                version = Some(next_pair.as_str().to_string());
1811            }
1812            Rule::expression => {
1813                let expression = parse_expression(next_pair)?;
1814                return Ok(AstNode::Policy {
1815                    name,
1816                    version,
1817                    metadata,
1818                    expression,
1819                });
1820            }
1821            _ => {}
1822        }
1823    }
1824
1825    Err(ParseError::GrammarError(
1826        "Policy missing expression".to_string(),
1827    ))
1828}
1829
1830fn parse_policy_annotation(pair: Pair<Rule>, metadata: &mut PolicyMetadata) -> ParseResult<()> {
1831    let mut inner = pair.into_inner();
1832
1833    let name = inner
1834        .next()
1835        .ok_or_else(|| ParseError::GrammarError("Expected annotation name".to_string()))?;
1836    let value = inner
1837        .next()
1838        .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
1839
1840    let name_str = name.as_str().to_lowercase();
1841
1842    match name_str.as_str() {
1843        "rationale" => {
1844            metadata.rationale = Some(parse_string_literal(value)?);
1845        }
1846        "tags" => {
1847            if value.as_rule() == Rule::string_array {
1848                for tag_pair in value.into_inner() {
1849                    if tag_pair.as_rule() == Rule::string_literal {
1850                        metadata.tags.push(parse_string_literal(tag_pair)?);
1851                    }
1852                }
1853            } else {
1854                metadata.tags.push(parse_string_literal(value)?);
1855            }
1856        }
1857        _ => {
1858            return Err(ParseError::GrammarError(format!(
1859                "Unknown policy annotation: {}",
1860                name_str
1861            )))
1862        }
1863    }
1864
1865    Ok(())
1866}
1867
1868/// Parse expression
1869fn parse_expression(pair: Pair<Rule>) -> ParseResult<Expression> {
1870    match pair.as_rule() {
1871        Rule::expression => {
1872            let inner = pair
1873                .into_inner()
1874                .next()
1875                .ok_or_else(|| ParseError::GrammarError("Empty expression".to_string()))?;
1876            parse_expression(inner)
1877        }
1878        Rule::or_expr => parse_or_expr(pair),
1879        Rule::and_expr => parse_and_expr(pair),
1880        Rule::not_expr => parse_not_expr(pair),
1881        Rule::comparison_expr => parse_comparison_expr(pair),
1882        Rule::additive_expr => parse_additive_expr(pair),
1883        Rule::multiplicative_expr => parse_multiplicative_expr(pair),
1884        Rule::unary_expr => parse_unary_expr(pair),
1885        Rule::cast_expr => parse_cast_expr(pair),
1886        Rule::primary_expr => parse_primary_expr(pair),
1887        _ => Err(ParseError::InvalidExpression(format!(
1888            "Unexpected expression rule: {:?}",
1889            pair.as_rule()
1890        ))),
1891    }
1892}
1893
1894/// Parse a single expression string into an Expression AST node.
1895pub fn parse_expression_from_str(source: &str) -> ParseResult<Expression> {
1896    let pairs = SeaParser::parse(Rule::expression, source)
1897        .map_err(|e| ParseError::GrammarError(format!("Parse error: {}", e)))?;
1898    let parsed_pairs: Vec<_> = pairs.collect();
1899
1900    if parsed_pairs.is_empty() {
1901        return Err(ParseError::GrammarError("Empty expression".to_string()));
1902    }
1903    if parsed_pairs.len() > 1 {
1904        return Err(ParseError::GrammarError(
1905            "Trailing input detected after expression".to_string(),
1906        ));
1907    }
1908
1909    let pair = parsed_pairs.into_iter().next().unwrap();
1910
1911    // Check that the entire input was consumed (no trailing characters)
1912    let consumed = pair.as_span().end();
1913    let trimmed_source = source.trim_end();
1914    if consumed < trimmed_source.len() {
1915        return Err(ParseError::GrammarError(format!(
1916            "Trailing input after expression: '{}'",
1917            &source[consumed..]
1918        )));
1919    }
1920
1921    parse_expression(pair)
1922}
1923
1924/// Parse OR expression
1925fn parse_or_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1926    let mut inner = pair.into_inner();
1927    let mut left =
1928        parse_expression(inner.next().ok_or_else(|| {
1929            ParseError::GrammarError("Expected left expression in OR".to_string())
1930        })?)?;
1931
1932    for right_pair in inner {
1933        let right = parse_expression(right_pair)?;
1934        left = Expression::Binary {
1935            left: Box::new(left),
1936            op: BinaryOp::Or,
1937            right: Box::new(right),
1938        };
1939    }
1940
1941    Ok(left)
1942}
1943
1944/// Parse AND expression
1945fn parse_and_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1946    let mut inner = pair.into_inner();
1947    let mut left =
1948        parse_expression(inner.next().ok_or_else(|| {
1949            ParseError::GrammarError("Expected left expression in AND".to_string())
1950        })?)?;
1951
1952    for right_pair in inner {
1953        let right = parse_expression(right_pair)?;
1954        left = Expression::Binary {
1955            left: Box::new(left),
1956            op: BinaryOp::And,
1957            right: Box::new(right),
1958        };
1959    }
1960
1961    Ok(left)
1962}
1963
1964/// Parse NOT expression
1965fn parse_not_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1966    let mut inner = pair.into_inner();
1967    let first = inner
1968        .next()
1969        .ok_or_else(|| ParseError::GrammarError("Expected expression in NOT".to_string()))?;
1970
1971    // Check if this is actually a NOT expression or just a comparison_expr
1972    if first.as_rule() == Rule::not_expr {
1973        // This is a recursive NOT, parse it
1974        let expr = parse_expression(first)?;
1975        Ok(Expression::Unary {
1976            op: UnaryOp::Not,
1977            operand: Box::new(expr),
1978        })
1979    } else {
1980        // This is just a comparison_expr, parse it directly
1981        parse_expression(first)
1982    }
1983}
1984
1985/// Parse comparison expression
1986fn parse_comparison_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
1987    let mut inner = pair.into_inner();
1988    let mut left = parse_expression(inner.next().ok_or_else(|| {
1989        ParseError::GrammarError("Expected left expression in comparison".to_string())
1990    })?)?;
1991
1992    if let Some(op_pair) = inner.next() {
1993        let op = parse_comparison_op(op_pair)?;
1994        let right = parse_expression(inner.next().ok_or_else(|| {
1995            ParseError::GrammarError("Expected right expression in comparison".to_string())
1996        })?)?;
1997        left = Expression::Binary {
1998            left: Box::new(left),
1999            op,
2000            right: Box::new(right),
2001        };
2002    }
2003
2004    Ok(left)
2005}
2006
2007/// Parse comparison operator
2008fn parse_comparison_op(pair: Pair<Rule>) -> ParseResult<BinaryOp> {
2009    let op_str = pair.as_str();
2010    match op_str {
2011        "=" => Ok(BinaryOp::Equal),
2012        "!=" => Ok(BinaryOp::NotEqual),
2013        ">" => Ok(BinaryOp::GreaterThan),
2014        "<" => Ok(BinaryOp::LessThan),
2015        ">=" => Ok(BinaryOp::GreaterThanOrEqual),
2016        "<=" => Ok(BinaryOp::LessThanOrEqual),
2017        _ if op_str.eq_ignore_ascii_case("contains") => Ok(BinaryOp::Contains),
2018        _ if op_str.eq_ignore_ascii_case("startswith") => Ok(BinaryOp::StartsWith),
2019        _ if op_str.eq_ignore_ascii_case("endswith") => Ok(BinaryOp::EndsWith),
2020        _ if op_str.eq_ignore_ascii_case("matches") => Ok(BinaryOp::Matches),
2021        _ if op_str.eq_ignore_ascii_case("before") => Ok(BinaryOp::Before),
2022        _ if op_str.eq_ignore_ascii_case("after") => Ok(BinaryOp::After),
2023        _ if op_str.eq_ignore_ascii_case("during") => Ok(BinaryOp::During),
2024        _ if op_str.eq_ignore_ascii_case("has_role") => Ok(BinaryOp::HasRole),
2025        _ => Err(ParseError::InvalidExpression(format!(
2026            "Unknown comparison operator: {}",
2027            op_str
2028        ))),
2029    }
2030}
2031
2032/// Parse additive expression
2033fn parse_additive_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2034    let mut inner = pair.into_inner();
2035    let mut left = parse_expression(inner.next().ok_or_else(|| {
2036        ParseError::GrammarError("Expected left expression in additive".to_string())
2037    })?)?;
2038
2039    while let Some(op_pair) = inner.next() {
2040        let op = match op_pair.as_str() {
2041            "+" => BinaryOp::Plus,
2042            "-" => BinaryOp::Minus,
2043            _ => {
2044                return Err(ParseError::InvalidExpression(
2045                    "Invalid additive operator".to_string(),
2046                ))
2047            }
2048        };
2049        let right = parse_expression(inner.next().ok_or_else(|| {
2050            ParseError::GrammarError("Expected right expression in additive".to_string())
2051        })?)?;
2052        left = Expression::Binary {
2053            left: Box::new(left),
2054            op,
2055            right: Box::new(right),
2056        };
2057    }
2058
2059    Ok(left)
2060}
2061
2062/// Parse multiplicative expression
2063fn parse_multiplicative_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2064    let mut inner = pair.into_inner();
2065    let mut left = parse_expression(inner.next().ok_or_else(|| {
2066        ParseError::GrammarError("Expected left expression in multiplicative".to_string())
2067    })?)?;
2068
2069    while let Some(op_pair) = inner.next() {
2070        let op = match op_pair.as_str() {
2071            "*" => BinaryOp::Multiply,
2072            "/" => BinaryOp::Divide,
2073            _ => {
2074                return Err(ParseError::InvalidExpression(
2075                    "Invalid multiplicative operator".to_string(),
2076                ))
2077            }
2078        };
2079        let right = parse_expression(inner.next().ok_or_else(|| {
2080            ParseError::GrammarError("Expected right expression in multiplicative".to_string())
2081        })?)?;
2082        left = Expression::Binary {
2083            left: Box::new(left),
2084            op,
2085            right: Box::new(right),
2086        };
2087    }
2088
2089    Ok(left)
2090}
2091
2092/// Parse cast expression
2093fn parse_cast_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2094    let mut inner = pair.into_inner();
2095    let primary = parse_expression(inner.next().ok_or_else(|| {
2096        ParseError::GrammarError("Expected primary expression in cast".to_string())
2097    })?)?;
2098
2099    if let Some(as_pair) = inner.next() {
2100        let target_type = parse_string_literal(as_pair)?;
2101        Ok(Expression::cast(primary, target_type))
2102    } else {
2103        Ok(primary)
2104    }
2105}
2106
2107/// Parse unary expression
2108fn parse_unary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2109    let mut inner = pair.into_inner();
2110    let first = inner
2111        .next()
2112        .ok_or_else(|| ParseError::GrammarError("Expected expression in unary".to_string()))?;
2113
2114    if first.as_str() == "-" {
2115        // Unary minus
2116        let expr = parse_expression(inner.next().ok_or_else(|| {
2117            ParseError::GrammarError("Expected expression after unary minus".to_string())
2118        })?)?;
2119        Ok(Expression::Unary {
2120            op: UnaryOp::Negate,
2121            operand: Box::new(expr),
2122        })
2123    } else {
2124        parse_expression(first)
2125    }
2126}
2127
2128/// Parse primary expression
2129fn parse_primary_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2130    let inner = pair.into_inner().next().ok_or_else(|| {
2131        ParseError::GrammarError("Expected inner expression in primary".to_string())
2132    })?;
2133
2134    match inner.as_rule() {
2135        Rule::expression => parse_expression(inner),
2136        Rule::group_by_expr => parse_group_by_expr(inner),
2137        Rule::aggregation_expr => parse_aggregation_expr(inner),
2138        Rule::quantified_expr => parse_quantified_expr(inner),
2139        Rule::member_access => parse_member_access(inner),
2140        Rule::application_role_ref => parse_application_role_ref(inner),
2141        Rule::literal => parse_literal_expr(inner),
2142        Rule::identifier => {
2143            let name = parse_identifier(inner)?;
2144            Ok(Expression::Variable(name))
2145        }
2146        _ => Err(ParseError::InvalidExpression(format!(
2147            "Unexpected primary expression: {:?}",
2148            inner.as_rule()
2149        ))),
2150    }
2151}
2152
2153fn parse_application_role_ref(pair: Pair<Rule>) -> ParseResult<Expression> {
2154    let mut inner = pair.into_inner();
2155    let sym_pair = inner
2156        .next()
2157        .ok_or_else(|| ParseError::GrammarError("Expected symbol in role<...>".to_string()))?;
2158    let mut sym_inner = sym_pair.into_inner();
2159    let first = parse_identifier(sym_inner.next().ok_or_else(|| {
2160        ParseError::GrammarError("Expected identifier in role symbol_ref".to_string())
2161    })?)?;
2162    let role = match sym_inner.next() {
2163        Some(second) => format!("{}.{}", first, parse_identifier(second)?),
2164        None => first,
2165    };
2166    Ok(Expression::RoleReference { role })
2167}
2168
2169/// Parse aggregation expression
2170fn parse_aggregation_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2171    let mut inner = pair.into_inner();
2172
2173    let function_pair = inner.next().ok_or_else(|| {
2174        ParseError::GrammarError(
2175            "Expected aggregate function in aggregation expression".to_string(),
2176        )
2177    })?;
2178    let function = parse_aggregate_fn(function_pair)?;
2179
2180    let collection_pair = inner.next().ok_or_else(|| {
2181        ParseError::GrammarError("Expected collection in aggregation expression".to_string())
2182    })?;
2183
2184    // Aggregation can be a simple form (e.g., sum(flows), sum(flows.quantity))
2185    // or the comprehension form (e.g., sum(f in flows where f.resource = "Money": f.quantity as "USD")).
2186    if collection_pair.as_rule() == Rule::aggregation_comprehension {
2187        // Parse aggregation comprehension
2188        let mut comp_inner = collection_pair.into_inner();
2189        let variable_pair = comp_inner.next().ok_or_else(|| {
2190            ParseError::GrammarError("Expected variable in aggregation comprehension".to_string())
2191        })?;
2192        let variable = parse_identifier(variable_pair)?;
2193        // Next token should be collection
2194        let collection_token = comp_inner.next().ok_or_else(|| {
2195            ParseError::GrammarError("Expected collection in aggregation comprehension".to_string())
2196        })?;
2197        let collection_name = parse_collection(collection_token)?;
2198        let collection = Box::new(Expression::Variable(collection_name));
2199
2200        let mut next_pair = comp_inner.next().ok_or_else(|| {
2201            ParseError::GrammarError(
2202                "Expected predicate expression, projection, or window in aggregation comprehension"
2203                    .to_string(),
2204            )
2205        })?;
2206
2207        let mut window = None;
2208        if next_pair.as_rule() == Rule::window_clause {
2209            window = Some(parse_window_clause(next_pair)?);
2210            next_pair = comp_inner.next().ok_or_else(|| {
2211                ParseError::GrammarError(
2212                    "Expected predicate or projection expression in aggregation comprehension"
2213                        .to_string(),
2214                )
2215            })?;
2216        }
2217
2218        let remaining_pairs: Vec<Pair<Rule>> =
2219            std::iter::once(next_pair).chain(comp_inner).collect();
2220
2221        let mut expr_pairs: Vec<Pair<Rule>> = Vec::new();
2222        let mut target_unit: Option<String> = None;
2223        for pair in remaining_pairs {
2224            match pair.as_rule() {
2225                Rule::expression => expr_pairs.push(pair),
2226                Rule::string_literal => {
2227                    target_unit = Some(parse_string_literal(pair)?);
2228                }
2229                Rule::identifier if pair.as_str().eq_ignore_ascii_case("as") => {
2230                    // skip explicit AS token
2231                }
2232                other => {
2233                    return Err(ParseError::GrammarError(format!(
2234                        "Unexpected token {:?} in aggregation comprehension",
2235                        other
2236                    )))
2237                }
2238            }
2239        }
2240
2241        let (predicate, projection) = match expr_pairs.len() {
2242            2 => {
2243                let mut expr_iter = expr_pairs.into_iter();
2244                let predicate_expr = parse_expression(expr_iter.next().ok_or_else(|| {
2245                    ParseError::GrammarError(
2246                        "Expected predicate expression in aggregation comprehension".to_string(),
2247                    )
2248                })?)?;
2249                let projection_expr = parse_expression(expr_iter.next().ok_or_else(|| {
2250                    ParseError::GrammarError(
2251                        "Expected projection expression in aggregation comprehension".to_string(),
2252                    )
2253                })?)?;
2254                (predicate_expr, projection_expr)
2255            }
2256            1 => {
2257                let projection_expr =
2258                    parse_expression(expr_pairs.into_iter().next().ok_or_else(|| {
2259                        ParseError::GrammarError(
2260                            "Expected projection expression in aggregation comprehension"
2261                                .to_string(),
2262                        )
2263                    })?)?;
2264                (Expression::Literal(JsonValue::Bool(true)), projection_expr)
2265            }
2266            other => {
2267                return Err(ParseError::GrammarError(format!(
2268                    "Unexpected number of expressions in aggregation comprehension: {}",
2269                    other
2270                )))
2271            }
2272        };
2273
2274        return Ok(Expression::AggregationComprehension {
2275            function,
2276            variable,
2277            collection,
2278            window,
2279            predicate: Box::new(predicate),
2280            projection: Box::new(projection),
2281            target_unit,
2282        });
2283    }
2284
2285    // Parse aggregation_simple
2286    let mut simple_inner = collection_pair.into_inner();
2287
2288    // First item is either collection or identifier
2289    let first_pair = simple_inner.next().ok_or_else(|| {
2290        ParseError::GrammarError(
2291            "Expected collection or identifier in aggregation_simple".to_string(),
2292        )
2293    })?;
2294
2295    let collection = match first_pair.as_rule() {
2296        Rule::collection => parse_collection(first_pair)?,
2297        Rule::identifier => parse_identifier(first_pair)?,
2298        _ => {
2299            return Err(ParseError::GrammarError(format!(
2300                "Expected collection or identifier, got {:?}",
2301                first_pair.as_rule()
2302            )))
2303        }
2304    };
2305
2306    let mut field: Option<String> = None;
2307    let mut filter: Option<Expression> = None;
2308
2309    // Parse optional field and filter
2310    for item in simple_inner {
2311        match item.as_rule() {
2312            Rule::identifier => {
2313                field = Some(parse_identifier(item)?);
2314            }
2315            Rule::expression => {
2316                filter = Some(parse_expression(item)?);
2317            }
2318            _ => {}
2319        }
2320    }
2321
2322    Ok(Expression::aggregation(
2323        function,
2324        Expression::Variable(collection),
2325        field,
2326        filter,
2327    ))
2328}
2329
2330/// Parse aggregate function
2331fn parse_aggregate_fn(pair: Pair<Rule>) -> ParseResult<AggregateFunction> {
2332    let fn_str = pair.as_str();
2333    match fn_str.to_lowercase().as_str() {
2334        "count" => Ok(AggregateFunction::Count),
2335        "sum" => Ok(AggregateFunction::Sum),
2336        "min" => Ok(AggregateFunction::Min),
2337        "max" => Ok(AggregateFunction::Max),
2338        "avg" => Ok(AggregateFunction::Avg),
2339        _ => Err(ParseError::InvalidExpression(format!(
2340            "Unknown aggregate function: {}",
2341            fn_str
2342        ))),
2343    }
2344}
2345
2346/// Parse quantified expression
2347fn parse_quantified_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2348    let mut inner = pair.into_inner();
2349
2350    let quantifier = parse_quantifier(inner.next().ok_or_else(|| {
2351        ParseError::GrammarError("Expected quantifier in quantified expression".to_string())
2352    })?)?;
2353    let variable = parse_identifier(inner.next().ok_or_else(|| {
2354        ParseError::GrammarError(
2355            "Expected variable identifier in quantified expression".to_string(),
2356        )
2357    })?)?;
2358    let collection = parse_collection(inner.next().ok_or_else(|| {
2359        ParseError::GrammarError(
2360            "Expected collection identifier in quantified expression".to_string(),
2361        )
2362    })?)?;
2363    let condition = parse_expression(inner.next().ok_or_else(|| {
2364        ParseError::GrammarError("Expected quantified condition expression".to_string())
2365    })?)?;
2366
2367    Ok(Expression::Quantifier {
2368        quantifier,
2369        variable,
2370        collection: Box::new(Expression::Variable(collection)),
2371        condition: Box::new(condition),
2372    })
2373}
2374
2375/// Parse quantifier
2376fn parse_quantifier(pair: Pair<Rule>) -> ParseResult<PolicyQuantifier> {
2377    let q_str = pair.as_str();
2378    match q_str.to_lowercase().as_str() {
2379        "forall" => Ok(PolicyQuantifier::ForAll),
2380        "exists" => Ok(PolicyQuantifier::Exists),
2381        "exists_unique" => Ok(PolicyQuantifier::ExistsUnique),
2382        _ => Err(ParseError::InvalidExpression(format!(
2383            "Unknown quantifier: {}",
2384            q_str
2385        ))),
2386    }
2387}
2388
2389/// Parse collection type. `entity_instances of "EntityType"` carries an
2390/// inner `string_literal`; encode it as `entity_instances:EntityType` in
2391/// the returned name (matching how a bound-variable member access is
2392/// already encoded as `variable.field` — see `Expression::substitute`), so
2393/// every existing site that keys on a plain `Expression::Variable(String)`
2394/// collection name needs no new AST variant.
2395fn parse_collection(pair: Pair<Rule>) -> ParseResult<String> {
2396    // `.trim()`: the optional `of "EntityType"` suffix means pest's implicit
2397    // whitespace-skip between it and the base keyword can end up inside this
2398    // rule's span even when the suffix itself does not match (bare
2399    // `entity_instances`), so the untrimmed text can carry trailing
2400    // whitespace that would otherwise defeat the exact-match lookups below.
2401    let text = pair.as_str().trim().to_lowercase();
2402    for inner in pair.into_inner() {
2403        if inner.as_rule() == Rule::string_literal {
2404            let entity_type = parse_string_literal(inner)?;
2405            return Ok(format!("entity_instances:{entity_type}"));
2406        }
2407    }
2408    Ok(text)
2409}
2410
2411/// Parse member access
2412fn parse_member_access(pair: Pair<Rule>) -> ParseResult<Expression> {
2413    let mut inner = pair.into_inner();
2414    let object = parse_identifier(inner.next().ok_or_else(|| {
2415        ParseError::GrammarError("Expected object identifier in member access".to_string())
2416    })?)?;
2417    let member = parse_identifier(inner.next().ok_or_else(|| {
2418        ParseError::GrammarError("Expected member identifier in member access".to_string())
2419    })?)?;
2420
2421    Ok(Expression::MemberAccess { object, member })
2422}
2423
2424/// Parse literal expression
2425fn parse_literal_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2426    let inner = pair
2427        .into_inner()
2428        .next()
2429        .ok_or_else(|| ParseError::GrammarError("Expected literal content".to_string()))?;
2430
2431    match inner.as_rule() {
2432        Rule::string_literal => {
2433            let s = parse_string_literal(inner)?;
2434            Ok(Expression::Literal(JsonValue::String(s)))
2435        }
2436        Rule::multiline_string => {
2437            let s = parse_multiline_string(inner)?;
2438            Ok(Expression::Literal(JsonValue::String(s)))
2439        }
2440        Rule::quantity_literal => {
2441            let mut parts = inner.into_inner();
2442            let number_part = parts.next().ok_or_else(|| {
2443                ParseError::GrammarError("Expected number in quantity literal".to_string())
2444            })?;
2445            let unit_part = parts.next().ok_or_else(|| {
2446                ParseError::GrammarError("Expected unit string in quantity literal".to_string())
2447            })?;
2448            let value = parse_decimal(number_part)?;
2449            let unit = parse_string_literal(unit_part)?;
2450            Ok(Expression::QuantityLiteral { value, unit })
2451        }
2452        Rule::time_literal => {
2453            // Parse ISO 8601 timestamp (already includes quotes in grammar)
2454            let timestamp = inner.as_str();
2455            // Remove surrounding quotes
2456            let timestamp = timestamp.trim_start_matches('"').trim_end_matches('"');
2457            Ok(Expression::TimeLiteral(timestamp.to_string()))
2458        }
2459        Rule::interval_literal => {
2460            // Parse interval("start", "end")
2461            let mut parts = inner.into_inner();
2462            let start_part = parts.next().ok_or_else(|| {
2463                ParseError::GrammarError("Expected start time in interval literal".to_string())
2464            })?;
2465            let end_part = parts.next().ok_or_else(|| {
2466                ParseError::GrammarError("Expected end time in interval literal".to_string())
2467            })?;
2468            let start = parse_string_literal(start_part)?;
2469            let end = parse_string_literal(end_part)?;
2470            Ok(Expression::IntervalLiteral { start, end })
2471        }
2472        Rule::number => {
2473            let n = parse_decimal(inner)?;
2474            // Convert Decimal to f64 for JSON Number representation
2475            let f = n.to_f64().ok_or_else(|| {
2476                ParseError::InvalidQuantity(format!(
2477                    "Decimal value {} cannot be represented as f64",
2478                    n
2479                ))
2480            })?;
2481            // Ensure the value is finite
2482            if !f.is_finite() {
2483                return Err(ParseError::InvalidQuantity(format!(
2484                    "Decimal value {} converts to non-finite f64: {}",
2485                    n, f
2486                )));
2487            }
2488            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
2489                ParseError::InvalidQuantity(format!(
2490                    "Cannot create JSON Number from f64 value: {}",
2491                    f
2492                ))
2493            })?;
2494            Ok(Expression::Literal(JsonValue::Number(num)))
2495        }
2496        Rule::boolean => {
2497            let b = inner.as_str().eq_ignore_ascii_case("true");
2498            Ok(Expression::Literal(JsonValue::Bool(b)))
2499        }
2500        Rule::array_literal => {
2501            let mut values = Vec::new();
2502            for element in inner.into_inner() {
2503                if element.as_rule() != Rule::literal {
2504                    continue;
2505                }
2506                match parse_literal_expr(element)? {
2507                    Expression::Literal(v) => values.push(v),
2508                    other => {
2509                        return Err(ParseError::GrammarError(format!(
2510                            "Array literal elements must be plain literals, got {:?}",
2511                            other
2512                        )))
2513                    }
2514                }
2515            }
2516            Ok(Expression::Literal(JsonValue::Array(values)))
2517        }
2518        _ => Err(ParseError::InvalidExpression(format!(
2519            "Unknown literal type: {:?}",
2520            inner.as_rule()
2521        ))),
2522    }
2523}
2524
2525/// Parse name (handles both string_literal and multiline_string)
2526fn parse_name(pair: Pair<Rule>) -> ParseResult<String> {
2527    let inner = pair.into_inner().next().ok_or_else(|| {
2528        ParseError::GrammarError("Expected inner token for name but got empty pair".to_string())
2529    })?;
2530    match inner.as_rule() {
2531        Rule::string_literal => parse_string_literal(inner),
2532        Rule::multiline_string => parse_multiline_string(inner),
2533        _ => Err(ParseError::GrammarError(format!(
2534            "Expected string or multiline string for name, got {:?}",
2535            inner.as_rule()
2536        ))),
2537    }
2538}
2539
2540/// Parse string literal (handles escape sequences)
2541fn parse_string_literal(pair: Pair<Rule>) -> ParseResult<String> {
2542    let s = pair.as_str();
2543    if s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') {
2544        return Err(ParseError::GrammarError(format!(
2545            "Invalid string literal: {}",
2546            s
2547        )));
2548    }
2549
2550    // Use serde_json to properly parse and unescape the string
2551    // The string already has quotes, so pass it directly
2552    match serde_json::from_str(s) {
2553        Ok(unescaped) => Ok(unescaped),
2554        Err(e) => Err(ParseError::GrammarError(format!(
2555            "Invalid string literal escape sequences: {} - {}",
2556            s, e
2557        ))),
2558    }
2559}
2560
2561/// Parse multiline string (removes triple quotes and handles escape sequences)
2562fn parse_multiline_string(pair: Pair<Rule>) -> ParseResult<String> {
2563    let s = pair.as_str();
2564    if s.len() < 6 || !s.starts_with("\"\"\"") || !s.ends_with("\"\"\"") {
2565        return Err(ParseError::GrammarError(format!(
2566            "Invalid multiline string: {}",
2567            s
2568        )));
2569    }
2570
2571    let content = &s[3..s.len() - 3];
2572
2573    // Escape special characters for JSON compatibility
2574    let escaped = content
2575        .replace('\\', "\\\\") // Backslash must be first
2576        .replace('"', "\\\"") // Double quotes
2577        .replace('\n', "\\n") // Newlines
2578        .replace('\r', "\\r") // Carriage returns
2579        .replace('\t', "\\t"); // Tabs
2580
2581    // Create a JSON string and parse it to handle escape sequences
2582    let json_string = format!("\"{}\"", escaped);
2583    match serde_json::from_str(&json_string) {
2584        Ok(unescaped) => Ok(unescaped),
2585        Err(e) => Err(ParseError::GrammarError(format!(
2586            "Invalid multiline string escape sequences in '{}': {}",
2587            s, e
2588        ))),
2589    }
2590}
2591
2592/// Parse identifier
2593fn parse_identifier(pair: Pair<Rule>) -> ParseResult<String> {
2594    Ok(pair.as_str().to_string())
2595}
2596
2597/// Parse semantic version (validated by grammar)
2598fn parse_version(pair: Pair<Rule>) -> ParseResult<String> {
2599    Ok(pair.as_str().to_string())
2600}
2601
2602/// Parse number as i32
2603fn parse_number(pair: Pair<Rule>) -> ParseResult<i32> {
2604    pair.as_str()
2605        .parse()
2606        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid number: {}", pair.as_str())))
2607}
2608
2609/// Parse number as Decimal
2610fn parse_decimal(pair: Pair<Rule>) -> ParseResult<Decimal> {
2611    pair.as_str()
2612        .parse()
2613        .map_err(|_| ParseError::InvalidQuantity(format!("Invalid decimal: {}", pair.as_str())))
2614}
2615
2616/// Parse group_by expression
2617fn parse_group_by_expr(pair: Pair<Rule>) -> ParseResult<Expression> {
2618    let mut inner = pair.into_inner();
2619
2620    let variable_pair = inner
2621        .next()
2622        .ok_or_else(|| ParseError::GrammarError("Expected variable in group_by".to_string()))?;
2623    let variable = parse_identifier(variable_pair)?;
2624
2625    let collection_pair = inner
2626        .next()
2627        .ok_or_else(|| ParseError::GrammarError("Expected collection in group_by".to_string()))?;
2628    let collection_name = parse_collection(collection_pair)?;
2629    let collection = Box::new(Expression::Variable(collection_name));
2630
2631    let next_pair = inner.next().ok_or_else(|| {
2632        ParseError::GrammarError("Expected key or where clause in group_by".to_string())
2633    })?;
2634
2635    // Collect remaining pairs to determine structure without cloning
2636    let remaining: Vec<Pair<Rule>> = std::iter::once(next_pair).chain(inner).collect();
2637
2638    let (filter_expr, key_expr, condition_expr) = match remaining.len() {
2639        3 => {
2640            let mut iter = remaining.into_iter();
2641            let filter = parse_expression(iter.next().ok_or_else(|| {
2642                ParseError::GrammarError("Expected filter expression in group_by".to_string())
2643            })?)?;
2644            let key = parse_expression(iter.next().ok_or_else(|| {
2645                ParseError::GrammarError("Expected key expression in group_by".to_string())
2646            })?)?;
2647            let condition = parse_expression(iter.next().ok_or_else(|| {
2648                ParseError::GrammarError("Expected condition expression in group_by".to_string())
2649            })?)?;
2650            (Some(filter), key, condition)
2651        }
2652        2 => {
2653            let mut iter = remaining.into_iter();
2654            let key = parse_expression(iter.next().ok_or_else(|| {
2655                ParseError::GrammarError("Expected key expression in group_by".to_string())
2656            })?)?;
2657            let condition = parse_expression(iter.next().ok_or_else(|| {
2658                ParseError::GrammarError("Expected condition expression in group_by".to_string())
2659            })?)?;
2660            (None, key, condition)
2661        }
2662        other => {
2663            return Err(ParseError::GrammarError(format!(
2664                "Unexpected number of expressions in group_by: {}",
2665                other
2666            )))
2667        }
2668    };
2669
2670    Ok(Expression::GroupBy {
2671        variable,
2672        collection,
2673        filter: filter_expr.map(Box::new),
2674        key: Box::new(key_expr),
2675        condition: Box::new(condition_expr),
2676    })
2677}
2678
2679/// Parse window clause
2680fn parse_window_clause(pair: Pair<Rule>) -> ParseResult<WindowSpec> {
2681    let mut inner = pair.into_inner();
2682
2683    let duration_pair = inner.next().ok_or_else(|| {
2684        ParseError::GrammarError("Expected duration in window clause".to_string())
2685    })?;
2686    let duration_i32 = parse_number(duration_pair)?;
2687    if duration_i32 < 0 {
2688        return Err(ParseError::InvalidQuantity(
2689            "Window duration must be non-negative".to_string(),
2690        ));
2691    }
2692    let duration = duration_i32 as u64;
2693
2694    let unit_pair = inner
2695        .next()
2696        .ok_or_else(|| ParseError::GrammarError("Expected unit in window clause".to_string()))?;
2697    let unit = parse_string_literal(unit_pair)?;
2698
2699    Ok(WindowSpec { duration, unit })
2700}
2701
2702fn expression_kind(expr: &Expression) -> &'static str {
2703    match expr {
2704        Expression::Literal(_) => "literal",
2705        Expression::QuantityLiteral { .. } => "quantity_literal",
2706        Expression::TimeLiteral(_) => "time_literal",
2707        Expression::IntervalLiteral { .. } => "interval_literal",
2708        Expression::Variable(_) => "variable",
2709        Expression::GroupBy { .. } => "group_by",
2710        Expression::Binary { .. } => "binary",
2711        Expression::Unary { .. } => "unary",
2712        Expression::Cast { .. } => "cast",
2713        Expression::Quantifier { .. } => "quantifier",
2714        Expression::MemberAccess { .. } => "member_access",
2715        Expression::Aggregation { .. } => "aggregation",
2716        Expression::AggregationComprehension { .. } => "aggregation_comprehension",
2717        Expression::RoleReference { .. } => "role_reference",
2718    }
2719}
2720
2721/// Convert an Expression to a JSON Value for instance fields
2722fn expression_to_json(expr: &Expression) -> ParseResult<JsonValue> {
2723    match expr {
2724        Expression::Literal(v) => Ok(v.clone()),
2725        Expression::Variable(name) => Ok(JsonValue::String(name.clone())),
2726        Expression::QuantityLiteral { value, unit } => Ok(json!({
2727            "value": value.to_string(),
2728            "unit": unit
2729        })),
2730        Expression::TimeLiteral(timestamp) => Ok(JsonValue::String(timestamp.clone())),
2731        _ => Err(ParseError::UnsupportedExpression {
2732            kind: expression_kind(expr).to_string(),
2733            span: None,
2734        }),
2735    }
2736}
2737
2738/// Parse mapping declaration
2739fn parse_mapping(pair: Pair<Rule>) -> ParseResult<AstNode> {
2740    let mut inner = pair.into_inner();
2741
2742    let name = parse_string_literal(
2743        inner
2744            .next()
2745            .ok_or_else(|| ParseError::GrammarError("Expected mapping name".to_string()))?,
2746    )?;
2747
2748    let target_pair = inner
2749        .next()
2750        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
2751    let target = parse_target_format(target_pair)?;
2752
2753    let mut rules = Vec::new();
2754
2755    for rule_pair in inner {
2756        if rule_pair.as_rule() == Rule::mapping_rule {
2757            rules.push(parse_mapping_rule(rule_pair)?);
2758        }
2759    }
2760
2761    Ok(AstNode::MappingDecl {
2762        name,
2763        target,
2764        rules,
2765    })
2766}
2767
2768fn parse_target_format(pair: Pair<Rule>) -> ParseResult<TargetFormat> {
2769    match pair.as_str().to_lowercase().as_str() {
2770        "calm" => Ok(TargetFormat::Calm),
2771        "kg" => Ok(TargetFormat::Kg),
2772        "sbvr" => Ok(TargetFormat::Sbvr),
2773        "protobuf" | "proto" => Ok(TargetFormat::Protobuf),
2774        _ => Err(ParseError::GrammarError(format!(
2775            "Unknown target format: {}",
2776            pair.as_str()
2777        ))),
2778    }
2779}
2780
2781fn parse_mapping_rule(pair: Pair<Rule>) -> ParseResult<MappingRule> {
2782    let mut inner = pair.into_inner();
2783
2784    let primitive_type = inner
2785        .next()
2786        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
2787        .as_str()
2788        .to_string();
2789
2790    let primitive_name = parse_string_literal(
2791        inner
2792            .next()
2793            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
2794    )?;
2795
2796    let target_structure = inner
2797        .next()
2798        .ok_or_else(|| ParseError::GrammarError("Expected target structure".to_string()))?;
2799
2800    let mut target_inner = target_structure.into_inner();
2801    let target_type = parse_identifier(
2802        target_inner
2803            .next()
2804            .ok_or_else(|| ParseError::GrammarError("Expected target type".to_string()))?,
2805    )?;
2806
2807    let mut fields = HashMap::new();
2808    for field_pair in target_inner {
2809        if field_pair.as_rule() == Rule::mapping_field {
2810            let mut field_inner = field_pair.into_inner();
2811            let key = parse_identifier(
2812                field_inner
2813                    .next()
2814                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
2815            )?;
2816            let value_pair = field_inner
2817                .next()
2818                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;
2819
2820            let value = match value_pair.as_rule() {
2821                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
2822                Rule::boolean => JsonValue::Bool(value_pair.as_str().eq_ignore_ascii_case("true")),
2823                Rule::object_literal => parse_object_literal(value_pair)?,
2824                _ => {
2825                    return Err(ParseError::GrammarError(
2826                        "Unexpected mapping field value".to_string(),
2827                    ))
2828                }
2829            };
2830            fields.insert(key, value);
2831        }
2832    }
2833
2834    Ok(MappingRule {
2835        primitive_type,
2836        primitive_name,
2837        target_type,
2838        fields,
2839    })
2840}
2841
2842fn parse_object_literal(pair: Pair<Rule>) -> ParseResult<JsonValue> {
2843    let mut map = serde_json::Map::new();
2844    let mut inner = pair.into_inner();
2845    while let Some(key_pair) = inner.next() {
2846        let key = parse_string_literal(key_pair)?;
2847        let value_pair = inner.next().ok_or_else(|| {
2848            ParseError::GrammarError("Expected value in object literal".to_string())
2849        })?;
2850        let value = parse_annotation_value(value_pair)?;
2851        map.insert(key, value);
2852    }
2853    Ok(JsonValue::Object(map))
2854}
2855
2856fn parse_annotation_value(pair: Pair<Rule>) -> ParseResult<JsonValue> {
2857    match pair.as_rule() {
2858        Rule::annotation_value => {
2859            let mut inner = pair.into_inner();
2860            let value_pair = inner
2861                .next()
2862                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
2863            parse_annotation_value(value_pair)
2864        }
2865        Rule::string_literal => Ok(JsonValue::String(parse_string_literal(pair)?)),
2866        Rule::string_array => {
2867            let mut values = Vec::new();
2868            for item in pair.into_inner() {
2869                values.push(JsonValue::String(parse_string_literal(item)?));
2870            }
2871            Ok(JsonValue::Array(values))
2872        }
2873        Rule::boolean => Ok(JsonValue::Bool(pair.as_str().eq_ignore_ascii_case("true"))),
2874        Rule::number => {
2875            let d = parse_decimal(pair)?;
2876            let f = d.to_f64().ok_or_else(|| {
2877                ParseError::InvalidQuantity(format!(
2878                    "Decimal value {} cannot be represented as f64",
2879                    d
2880                ))
2881            })?;
2882            if !f.is_finite() {
2883                return Err(ParseError::InvalidQuantity(format!(
2884                    "Decimal value {} converts to non-finite f64",
2885                    d
2886                )));
2887            }
2888            let num = serde_json::Number::from_f64(f).ok_or_else(|| {
2889                ParseError::InvalidQuantity(format!("Cannot create JSON Number from decimal {}", d))
2890            })?;
2891            Ok(JsonValue::Number(num))
2892        }
2893        Rule::object_literal => parse_object_literal(pair),
2894        _ => Err(ParseError::GrammarError(format!(
2895            "Unexpected annotation value: {}",
2896            pair.as_str()
2897        ))),
2898    }
2899}
2900
2901/// Parse projection declaration
2902fn parse_projection(pair: Pair<Rule>) -> ParseResult<AstNode> {
2903    let mut inner = pair.into_inner();
2904
2905    let name = parse_string_literal(
2906        inner
2907            .next()
2908            .ok_or_else(|| ParseError::GrammarError("Expected projection name".to_string()))?,
2909    )?;
2910
2911    let target_pair = inner
2912        .next()
2913        .ok_or_else(|| ParseError::GrammarError("Expected target format".to_string()))?;
2914    let target = parse_target_format(target_pair)?;
2915
2916    let mut overrides = Vec::new();
2917
2918    for rule_pair in inner {
2919        if rule_pair.as_rule() == Rule::projection_rule {
2920            overrides.push(parse_projection_rule(rule_pair)?);
2921        }
2922    }
2923
2924    Ok(AstNode::ProjectionDecl {
2925        name,
2926        target,
2927        overrides,
2928    })
2929}
2930
2931fn parse_projection_rule(pair: Pair<Rule>) -> ParseResult<ProjectionOverride> {
2932    let mut inner = pair.into_inner();
2933
2934    let primitive_type = inner
2935        .next()
2936        .ok_or_else(|| ParseError::GrammarError("Expected primitive type".to_string()))?
2937        .as_str()
2938        .to_string();
2939
2940    let primitive_name = parse_string_literal(
2941        inner
2942            .next()
2943            .ok_or_else(|| ParseError::GrammarError("Expected primitive name".to_string()))?,
2944    )?;
2945
2946    let mut fields = HashMap::new();
2947    for field_pair in inner {
2948        if field_pair.as_rule() == Rule::projection_field {
2949            let mut field_inner = field_pair.into_inner();
2950            let key = parse_identifier(
2951                field_inner
2952                    .next()
2953                    .ok_or_else(|| ParseError::GrammarError("Expected field key".to_string()))?,
2954            )?;
2955            let value_pair = field_inner
2956                .next()
2957                .ok_or_else(|| ParseError::GrammarError("Expected field value".to_string()))?;
2958
2959            let value = match value_pair.as_rule() {
2960                Rule::string_literal => JsonValue::String(parse_string_literal(value_pair)?),
2961                Rule::property_mapping => parse_property_mapping(value_pair)?,
2962                _ => {
2963                    return Err(ParseError::GrammarError(
2964                        "Unexpected projection field value".to_string(),
2965                    ))
2966                }
2967            };
2968            fields.insert(key, value);
2969        }
2970    }
2971
2972    Ok(ProjectionOverride {
2973        primitive_type,
2974        primitive_name,
2975        fields,
2976    })
2977}
2978
2979/// Parse a `generic_annotation*` sequence (`"@" key value`) shared by all
2980/// cell-environment declarations into a flat annotation map. Duplicate keys
2981/// (after lowercasing) on the same declaration are an authoring error and are
2982/// rejected, including case-insensitive collisions (e.g. `@Host` after
2983/// `@host`).
2984fn parse_generic_annotations<'a>(
2985    pairs: impl Iterator<Item = Pair<'a, Rule>>,
2986) -> ParseResult<HashMap<String, JsonValue>> {
2987    let mut annotations = HashMap::new();
2988    for part in pairs {
2989        if part.as_rule() == Rule::generic_annotation {
2990            let mut inner = part.into_inner();
2991            let key =
2992                parse_identifier(inner.next().ok_or_else(|| {
2993                    ParseError::GrammarError("Expected annotation key".to_string())
2994                })?)?
2995                .to_lowercase();
2996            let value_pair = inner
2997                .next()
2998                .ok_or_else(|| ParseError::GrammarError("Expected annotation value".to_string()))?;
2999            if annotations.contains_key(&key) {
3000                return Err(ParseError::GrammarError(format!(
3001                    "Duplicate annotation '@{key}' on the same declaration"
3002                )));
3003            }
3004            annotations.insert(key, parse_annotation_value(value_pair)?);
3005        }
3006    }
3007    Ok(annotations)
3008}
3009
3010fn parse_cell(pair: Pair<Rule>) -> ParseResult<AstNode> {
3011    let mut inner = pair.into_inner();
3012    let name = parse_name(
3013        inner
3014            .next()
3015            .ok_or_else(|| ParseError::GrammarError("Expected cell name".to_string()))?,
3016    )?;
3017    let annotations = parse_generic_annotations(inner)?;
3018    Ok(AstNode::Cell { name, annotations })
3019}
3020
3021fn parse_system_dependency(pair: Pair<Rule>) -> ParseResult<AstNode> {
3022    let mut inner = pair.into_inner().peekable();
3023    let name =
3024        parse_name(inner.next().ok_or_else(|| {
3025            ParseError::GrammarError("Expected system dependency name".to_string())
3026        })?)?;
3027    let mut version = None;
3028    if let Some(peeked) = inner.peek() {
3029        if peeked.as_rule() == Rule::string_literal {
3030            version = Some(parse_string_literal(inner.next().unwrap())?);
3031        }
3032    }
3033    let annotations = parse_generic_annotations(inner)?;
3034    Ok(AstNode::SystemDependency {
3035        name,
3036        version,
3037        annotations,
3038    })
3039}
3040
3041fn parse_runtime(pair: Pair<Rule>) -> ParseResult<AstNode> {
3042    let mut inner = pair.into_inner();
3043    let name = parse_name(
3044        inner
3045            .next()
3046            .ok_or_else(|| ParseError::GrammarError("Expected runtime name".to_string()))?,
3047    )?;
3048    let version_pair = inner
3049        .next()
3050        .ok_or_else(|| ParseError::GrammarError("Expected runtime version".to_string()))?;
3051    let version = parse_string_literal(version_pair)?;
3052    let annotations = parse_generic_annotations(inner)?;
3053    Ok(AstNode::Runtime {
3054        name,
3055        version,
3056        annotations,
3057    })
3058}
3059
3060fn parse_tool(pair: Pair<Rule>) -> ParseResult<AstNode> {
3061    let mut inner = pair.into_inner();
3062    let name = parse_name(
3063        inner
3064            .next()
3065            .ok_or_else(|| ParseError::GrammarError("Expected tool name".to_string()))?,
3066    )?;
3067    let version_pair = inner
3068        .next()
3069        .ok_or_else(|| ParseError::GrammarError("Expected tool version".to_string()))?;
3070    let version = parse_string_literal(version_pair)?;
3071    let annotations = parse_generic_annotations(inner)?;
3072    Ok(AstNode::Tool {
3073        name,
3074        version,
3075        annotations,
3076    })
3077}
3078
3079fn parse_dependency_set(pair: Pair<Rule>) -> ParseResult<AstNode> {
3080    let mut inner = pair.into_inner();
3081    let name =
3082        parse_name(inner.next().ok_or_else(|| {
3083            ParseError::GrammarError("Expected dependency set name".to_string())
3084        })?)?;
3085    let annotations = parse_generic_annotations(inner)?;
3086    Ok(AstNode::DependencySet { name, annotations })
3087}
3088
3089fn parse_service(pair: Pair<Rule>) -> ParseResult<AstNode> {
3090    let mut inner = pair.into_inner().peekable();
3091    let name = parse_name(
3092        inner
3093            .next()
3094            .ok_or_else(|| ParseError::GrammarError("Expected service name".to_string()))?,
3095    )?;
3096    let mut version = None;
3097    if let Some(peeked) = inner.peek() {
3098        if peeked.as_rule() == Rule::string_literal {
3099            version = Some(parse_string_literal(inner.next().unwrap())?);
3100        }
3101    }
3102    let annotations = parse_generic_annotations(inner)?;
3103    Ok(AstNode::Service {
3104        name,
3105        version,
3106        annotations,
3107    })
3108}
3109
3110fn parse_mount(pair: Pair<Rule>) -> ParseResult<AstNode> {
3111    let mut inner = pair.into_inner();
3112    let name = parse_name(
3113        inner
3114            .next()
3115            .ok_or_else(|| ParseError::GrammarError("Expected mount name".to_string()))?,
3116    )?;
3117    let annotations = parse_generic_annotations(inner)?;
3118    Ok(AstNode::Mount { name, annotations })
3119}
3120
3121fn parse_endpoint(pair: Pair<Rule>) -> ParseResult<AstNode> {
3122    let mut inner = pair.into_inner();
3123    let name = parse_name(
3124        inner
3125            .next()
3126            .ok_or_else(|| ParseError::GrammarError("Expected endpoint name".to_string()))?,
3127    )?;
3128    let annotations = parse_generic_annotations(inner)?;
3129    Ok(AstNode::Endpoint { name, annotations })
3130}
3131
3132fn parse_network_flow(pair: Pair<Rule>) -> ParseResult<AstNode> {
3133    let mut inner = pair.into_inner();
3134    let name = parse_name(
3135        inner
3136            .next()
3137            .ok_or_else(|| ParseError::GrammarError("Expected network flow name".to_string()))?,
3138    )?;
3139    let from_ref = parse_string_literal(inner.next().ok_or_else(|| {
3140        ParseError::GrammarError("Expected network flow 'from' reference".to_string())
3141    })?)?;
3142    let to_ref = parse_string_literal(inner.next().ok_or_else(|| {
3143        ParseError::GrammarError("Expected network flow 'to' reference".to_string())
3144    })?)?;
3145    let annotations = parse_generic_annotations(inner)?;
3146    Ok(AstNode::NetworkFlow {
3147        name,
3148        from_ref,
3149        to_ref,
3150        annotations,
3151    })
3152}
3153
3154fn parse_credential(pair: Pair<Rule>) -> ParseResult<AstNode> {
3155    let mut inner = pair.into_inner();
3156    let name = parse_name(
3157        inner
3158            .next()
3159            .ok_or_else(|| ParseError::GrammarError("Expected credential name".to_string()))?,
3160    )?;
3161    let annotations = parse_generic_annotations(inner)?;
3162    Ok(AstNode::Credential { name, annotations })
3163}
3164
3165fn parse_property_mapping(pair: Pair<Rule>) -> ParseResult<JsonValue> {
3166    let mut map = serde_json::Map::new();
3167    let mut inner = pair.into_inner();
3168    while let Some(key_pair) = inner.next() {
3169        let key = parse_string_literal(key_pair)?;
3170        let value_pair = inner.next().ok_or_else(|| {
3171            ParseError::GrammarError("Expected value in property mapping".to_string())
3172        })?;
3173        let value = parse_string_literal(value_pair)?;
3174        map.insert(key, JsonValue::String(value));
3175    }
3176    Ok(JsonValue::Object(map))
3177}
3178
3179fn unwrap_export(spanned: &Spanned<AstNode>) -> &AstNode {
3180    match &spanned.node {
3181        AstNode::Export(inner) => &inner.node,
3182        other => other,
3183    }
3184}
3185
3186/// Resolve a name in a namespace-keyed map.
3187/// Tries (default_namespace, name) first, then scans all namespaces for an unqualified match.
3188/// Returns None if not found, or the concept ID if exactly one match exists.
3189fn resolve_by_name(
3190    map: &HashMap<(String, String), crate::ConceptId>,
3191    name: &str,
3192    default_namespace: &str,
3193) -> Result<Option<crate::ConceptId>, ParseError> {
3194    // Try exact match in default namespace first
3195    if let Some(id) = map.get(&(default_namespace.to_string(), name.to_string())) {
3196        return Ok(Some(id.clone()));
3197    }
3198    // Fall back to any namespace with this name
3199    let matches: Vec<(&str, &crate::ConceptId)> = map
3200        .iter()
3201        .filter(|((_, n), _)| n == name)
3202        .map(|((namespace, _), id)| (namespace.as_str(), id))
3203        .collect();
3204    if matches.len() == 1 {
3205        return Ok(Some(matches[0].1.clone()));
3206    }
3207    if matches.len() > 1 {
3208        let mut namespaces: Vec<&str> = matches
3209            .into_iter()
3210            .map(|(namespace, _)| namespace)
3211            .collect();
3212        namespaces.sort_unstable();
3213        namespaces.dedup();
3214        return Err(ParseError::Validation(format!(
3215            "Ambiguous reference '{}' found in namespaces: {}",
3216            name,
3217            namespaces.join(", ")
3218        )));
3219    }
3220    Ok(None)
3221}
3222
3223/// Convert AST to Graph
3224pub fn ast_to_graph(ast: Ast) -> ParseResult<Graph> {
3225    ast_to_graph_with_options(ast, &ParseOptions::default())
3226}
3227
3228pub fn ast_to_graph_with_options(mut ast: Ast, options: &ParseOptions) -> ParseResult<Graph> {
3229    use crate::parser::profiles::ProfileRegistry;
3230    let registry = ProfileRegistry::global();
3231    let active_profile = ast
3232        .metadata
3233        .profile
3234        .clone()
3235        .or_else(|| options.active_profile.clone())
3236        .unwrap_or_else(|| "default".to_string());
3237    ast.metadata.profile.get_or_insert(active_profile.clone());
3238
3239    if registry.get(&active_profile).is_none() {
3240        let available = registry.list_names().join(", ");
3241        let message = format!(
3242            "Unknown profile: '{}'. Available profiles: {}",
3243            active_profile, available
3244        );
3245        if options.tolerate_profile_warnings {
3246            log::warn!("{}", message);
3247        } else {
3248            return Err(ParseError::Validation(message));
3249        }
3250    }
3251
3252    let mut graph = Graph::new();
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}