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