phenotyper 0.3.0

Core compiler library for the Phenotyper structural artifact definition language
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// SPDX-License-Identifier: Apache-2.0
//! AST-to-IR lowering pass (REQ-COMP-007).
//!
//! Walks the AST + symbol table and produces the normalized IR:
//! - Directive canonicalization: `@(field)` → `Emit(field_id)`
//! - Eol lowering: `@eol` → `Eol { field: None }`, `@eol(f)` → `Eol { field: Some(id) }`
//! - Union flattening: nested unions recursively flattened
//! - Primitive recognition: `string` etc. → `PrimitiveType`
//! - Singular/plural normalization: plural ref → `UserPlural { collection_of }`
//! - Cardinality normalization: `+` → `OneOrMore`, `*` → `ZeroOrMore`
//! - Block directive lowering: `@ifset`/`@ifnotempty` → `IfSet`/`IfNotEmpty`

use crate::diagnostic::Diagnostic;
use crate::parser::phenotyper_actions as ast;
use crate::symbol::{
    Cardinality, FieldId, PrimitiveType, Requiredness, ResolvedSymbol, Symbol, SymbolTable, TypeId,
};

use super::{
    EnumType, FieldDef, PhenotypeModule, PhenotypeType, RenderNode, SeparatorExpr, TypeAlias,
    ValueType,
};

/// Lower the entire module.
pub fn lower_module(
    file_ast: &ast::File,
    table: &SymbolTable,
    file: &str,
) -> (PhenotypeModule, Vec<Diagnostic>) {
    let mut diags = Vec::new();

    let namespace = table.namespace.join("/");

    let mut types = Vec::new();
    let mut enums = Vec::new();
    let mut aliases = Vec::new();

    if let Some(ref decls) = file_ast.ns.decls {
        for decl in decls {
            match decl {
                ast::TopLevelDecl::TypeDecl(td) => {
                    lower_type_decl(td, table, file, &mut diags, &mut enums, &mut aliases);
                }
                ast::TopLevelDecl::TypeDef(td) => {
                    if let Some(pt) = lower_type_def(td, table, file, &mut diags, &mut types, None)
                    {
                        types.push(pt);
                    }
                }
            }
        }
    }

    let module = PhenotypeModule {
        namespace,
        types,
        enums,
        aliases,
    };

    (module, diags)
}

/// Lower a type declaration (alias or enum).
fn lower_type_decl(
    decl: &ast::TypeDecl,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
    enums: &mut Vec<EnumType>,
    aliases: &mut Vec<TypeAlias>,
) {
    match &decl.body {
        ast::TypeDeclBody::Alias(alias) => {
            let id = match table.resolve(&decl.name) {
                Some(Symbol::Alias(aid)) => *aid,
                _ => return,
            };
            let target = lower_type_expr(&alias.alias, table, file, diags);
            aliases.push(TypeAlias {
                id,
                name: decl.name.clone(),
                target,
            });
        }
        ast::TypeDeclBody::Enum(enum_decl) => {
            let id = match table.resolve(&decl.name) {
                Some(Symbol::Enum(eid)) => *eid,
                _ => return,
            };
            let members = flatten_enum_members(&enum_decl.members);
            enums.push(EnumType {
                id,
                name: decl.name.clone(),
                members,
            });
        }
    }
}

/// Lower a phenotype type definition.
///
/// Nested phenotype definitions (BodyItem::NestedType) are recursively lowered
/// and flattened into the `extra_types` output vec — the IR is always flat.
///
/// `parent_name` is `Some("ParentType")` when lowering a nested phenotype inside
/// `ParentType`, enabling `@(Parent/field)` → `ParentFieldRef` resolution.
fn lower_type_def(
    def: &ast::TypeDef,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
    extra_types: &mut Vec<PhenotypeType>,
    parent_name: Option<&str>,
) -> Option<PhenotypeType> {
    let type_id = match table.resolve(&def.name) {
        Some(Symbol::Phenotype(id)) => *id,
        _ => return None,
    };

    let type_info = table.type_info(type_id)?;

    let plural_name = type_info.plural_name.clone();

    // Lower fields
    let mut fields = Vec::new();
    for item in &def.items {
        if let ast::BodyItem::Field(f) = item {
            if let Some(field_def) = lower_field_decl(&f.field, type_id, table, file, diags) {
                fields.push(field_def);
            }
        }
    }

    // Recursively lower nested phenotype definitions (pass current name as parent)
    for item in &def.items {
        if let ast::BodyItem::NestedType(nt) | ast::BodyItem::NestedTypePlural(nt) = item {
            if let Some(nested_pt) =
                lower_type_def(&nt.nested, table, file, diags, extra_types, Some(&def.name))
            {
                extra_types.push(nested_pt);
            }
        }
    }

    // Lower render expressions (pass fields for ? desugaring, parent for scoped refs)
    let mut render = Vec::new();
    let mut has_parent_refs = false;
    for item in &def.items {
        if let ast::BodyItem::Render(r) = item {
            if let Some(node) =
                lower_render_expr(&r.render, type_id, &fields, table, file, diags, parent_name)
            {
                if matches!(node, RenderNode::ParentFieldRef { .. }) {
                    has_parent_refs = true;
                }
                render.push(node);
            }
        }
    }

    // Set parent_context if this nested type actually uses parent field refs
    let parent_context = if has_parent_refs {
        parent_name.map(|s| s.to_string())
    } else {
        None
    };

    Some(PhenotypeType {
        id: type_id,
        singular_name: def.name.clone(),
        plural_name,
        fields,
        render,
        parent_context,
    })
}

/// Lower a field declaration.
fn lower_field_decl(
    field: &ast::FieldDecl,
    type_id: TypeId,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<FieldDef> {
    let field_info = table.resolve_field(type_id, &field.name)?;

    let requiredness = match field.req {
        ast::Requiredness::Req => Requiredness::Required,
        ast::Requiredness::Opt => Requiredness::Optional,
    };

    let (ty, cardinality) = lower_type_expr_with_cardinality(&field.type_expr, table, file, diags);

    Some(FieldDef {
        id: field_info.id,
        name: field.name.clone(),
        requiredness,
        cardinality,
        ty,
    })
}

/// Lower a type expression, extracting cardinality.
fn lower_type_expr_with_cardinality(
    expr: &ast::TypeExpr,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> (ValueType, Cardinality) {
    match expr {
        ast::TypeExpr::Simple(simple) => {
            let vt = lower_type_name(&simple.name, table, file, diags);
            (vt, Cardinality::One)
        }
        ast::TypeExpr::Cardinalized(card) => {
            let vt = lower_type_name(&card.base, table, file, diags);
            let cardinality = match card.card {
                ast::CardinalityOp::Plus => Cardinality::OneOrMore,
                ast::CardinalityOp::Star => Cardinality::ZeroOrMore,
            };
            (vt, cardinality)
        }
        ast::TypeExpr::Union(union) => {
            let vt = lower_union_type(&union.members, table, file, diags);
            (vt, Cardinality::One)
        }
    }
}

/// Lower a type expression (without cardinality extraction).
fn lower_type_expr(
    expr: &ast::TypeExpr,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> ValueType {
    let (vt, _) = lower_type_expr_with_cardinality(expr, table, file, diags);
    vt
}

/// Lower a single type name to a `ValueType`.
fn lower_type_name(
    name: &ast::TypeName,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> ValueType {
    match name {
        // Primitives
        ast::TypeName::String => ValueType::Primitive(PrimitiveType::String),
        ast::TypeName::Int64 => ValueType::Primitive(PrimitiveType::Int64),
        ast::TypeName::Real64 => ValueType::Primitive(PrimitiveType::Real64),
        ast::TypeName::Bool => ValueType::Primitive(PrimitiveType::Bool),
        ast::TypeName::Date => ValueType::Primitive(PrimitiveType::Date),
        ast::TypeName::Time => ValueType::Primitive(PrimitiveType::Time),
        ast::TypeName::DateTime => ValueType::Primitive(PrimitiveType::DateTime),

        // User-defined: resolve via symbol table (locals shadow imports)
        ast::TypeName::UserDefined(ud) => match table.resolve_any(&ud.name) {
            Some(ResolvedSymbol::Local(Symbol::Phenotype(id))) => ValueType::UserSingular(*id),
            Some(ResolvedSymbol::Local(Symbol::PluralCompanion { type_id })) => {
                ValueType::UserPlural {
                    collection_of: *type_id,
                }
            }
            Some(ResolvedSymbol::Local(Symbol::Enum(id))) => ValueType::Enum(*id),
            Some(ResolvedSymbol::Local(Symbol::Alias(id))) => ValueType::TypeAlias(*id),
            Some(ResolvedSymbol::Imported(is)) => ValueType::Imported(super::ImportedRef {
                namespace: is.namespace.clone(),
                name: is.name.clone(),
                kind: is.kind,
            }),
            Some(ResolvedSymbol::Ambiguous(_)) | None => {
                // Already reported by symbol resolution pass, but be defensive
                diags.push(super::error(
                    file,
                    format!("unresolved type `{}` during IR lowering", ud.name),
                ));
                ValueType::Primitive(PrimitiveType::String) // placeholder
            }
        },
    }
}

/// Lower a union type expression, flattening nested unions.
fn lower_union_type(
    members: &[ast::TypeName],
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> ValueType {
    let mut flat = Vec::new();
    for member in members {
        let vt = lower_type_name(member, table, file, diags);
        // Flatten nested unions
        if let ValueType::Union(inner) = vt {
            flat.extend(inner);
        } else {
            flat.push(vt);
        }
    }
    ValueType::Union(flat)
}

/// Extract the field name from a `FieldPath`.
///
/// For single-segment paths like `@(name)`, returns `"name"`.
/// For multi-segment scoped paths like `@(Parent/field)`, returns `"field"` —
/// the scope qualifier is resolved separately during symbol resolution.
fn resolve_field_path_name(
    path: &ast::FieldPath,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<String> {
    if path.segments.is_empty() {
        diags.push(super::error(file, "empty field path".to_string()));
        return None;
    }
    // Return the last segment as the field name
    Some(path.segments.last().unwrap().clone())
}

/// Lower a render expression to an IR `RenderNode`.
fn lower_render_expr(
    expr: &ast::RenderExpr,
    type_id: TypeId,
    fields: &[FieldDef],
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
    _parent_name: Option<&str>,
) -> Option<RenderNode> {
    match expr {
        // @(field) → Emit(field_id)
        // @(Parent/field) → ParentFieldRef { parent_type, field_name }
        ast::RenderExpr::FieldRef(fr) => {
            if fr.ref_path.segments.len() == 2 {
                // Scoped parent reference: @(Parent/field)
                let scope = &fr.ref_path.segments[0];
                let field_name = &fr.ref_path.segments[1];
                return Some(RenderNode::ParentFieldRef {
                    parent_type: scope.clone(),
                    field_name: field_name.clone(),
                });
            }
            let field_name = resolve_field_path_name(&fr.ref_path, file, diags)?;
            let field_id = resolve_field_id(&field_name, type_id, table, file, diags)?;
            Some(RenderNode::Emit(field_id))
        }

        // "literal" → Text(string)
        ast::RenderExpr::StringLit(sl) => {
            // Strip surrounding quotes from the string literal
            let value = strip_string_quotes(&sl.value);
            Some(RenderNode::Text(value))
        }

        // @eol (bare) → Eol { field: None }
        ast::RenderExpr::BareDirective(bd) => {
            if bd.name == "eol" {
                Some(RenderNode::Eol { field: None })
            } else {
                diags.push(super::error(
                    file,
                    format!("unknown bare directive `@{}`", bd.name),
                ));
                None
            }
        }

        // @name(...) with or without block body
        ast::RenderExpr::Directive(d) => lower_named_directive(d, type_id, table, file, diags),

        // @(field)? or @(field)? { body } — desugar to IfSet/IfNotEmpty
        ast::RenderExpr::ConditionalRef(cr) => {
            lower_conditional_ref(cr, type_id, fields, table, file, diags)
        }

        // @name(...)? or @name(...)? { body } — desugar directive with ?
        ast::RenderExpr::ConditionalDirective(cd) => {
            lower_conditional_directive(cd, type_id, fields, table, file, diags)
        }
    }
}

/// Lower a named directive (`@name(args) { body? }`).
fn lower_named_directive(
    d: &ast::Directive,
    type_id: TypeId,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<RenderNode> {
    let name = d.name.as_str();
    match &d.suffix {
        ast::DirectiveSuffix::WithArgs(wa) => {
            match name {
                "eol" => {
                    // @eol(field) → Eol { field: Some(id) }
                    let arg = single_ident_arg(&wa.args, "@eol", file, diags)?;
                    let field_id = resolve_field_id(&arg, type_id, table, file, diags)?;
                    Some(RenderNode::Eol {
                        field: Some(field_id),
                    })
                }
                "join" => {
                    // @join(field, separator) → Join { field, separator }
                    if wa.args.len() != 2 {
                        diags.push(super::error(
                            file,
                            format!("@join requires exactly 2 arguments, got {}", wa.args.len()),
                        ));
                        return None;
                    }
                    let field_name = ident_arg(&wa.args[0], "@join", file, diags)?;
                    let field_id = resolve_field_id(&field_name, type_id, table, file, diags)?;
                    let separator = lower_separator_arg(&wa.args[1], type_id, table, file, diags)?;
                    Some(RenderNode::Join {
                        field: field_id,
                        separator,
                    })
                }
                "ifset" => {
                    // @ifset(field) { body } → IfSet { field, body }
                    let arg = single_ident_arg(&wa.args, "@ifset", file, diags)?;
                    let field_id = resolve_field_id(&arg, type_id, table, file, diags)?;
                    let body = lower_block_body(&wa.block, type_id, table, file, diags);
                    Some(RenderNode::IfSet {
                        field: field_id,
                        body,
                    })
                }
                "ifnotempty" => {
                    // @ifnotempty(field) { body } → IfNotEmpty { field, body }
                    let arg = single_ident_arg(&wa.args, "@ifnotempty", file, diags)?;
                    let field_id = resolve_field_id(&arg, type_id, table, file, diags)?;
                    let body = lower_block_body(&wa.block, type_id, table, file, diags);
                    Some(RenderNode::IfNotEmpty {
                        field: field_id,
                        body,
                    })
                }
                _ => {
                    diags.push(super::error(file, format!("unknown directive `@{name}`")));
                    None
                }
            }
        }
        ast::DirectiveSuffix::EmptyParen(ep) => {
            match name {
                "eol" => {
                    // @eol() → Eol { field: None }
                    Some(RenderNode::Eol { field: None })
                }
                _ => {
                    if ep.block.is_some() {
                        diags.push(super::error(
                            file,
                            format!("`@{name}()` with block body is not supported"),
                        ));
                    } else {
                        diags.push(super::error(file, format!("unknown directive `@{name}()`")));
                    }
                    None
                }
            }
        }
    }
}

/// Lower a `@(field)?` or `@(field)? { body }` conditional reference.
///
/// Desugars based on field type:
/// - `optional` field → `IfSet { field, body }`
/// - Collection field (`*`/`+`) → `IfNotEmpty { field, body }`
/// - `required` scalar → treated as `IfSet` (semantic pass warns)
fn lower_conditional_ref(
    cr: &ast::ConditionalRef,
    type_id: TypeId,
    fields: &[FieldDef],
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<RenderNode> {
    let field_name = resolve_field_path_name(&cr.ref_path, file, diags)?;
    let field_id = resolve_field_id(&field_name, type_id, table, file, diags)?;

    // Determine body: if block is present, lower it; else default to [Emit(field)]
    let body = if let Some(ref block) = cr.block {
        let mut nodes = Vec::new();
        for item in &block.items {
            if let Some(node) = lower_render_expr(item, type_id, fields, table, file, diags, None) {
                nodes.push(node);
            }
        }
        nodes
    } else {
        vec![RenderNode::Emit(field_id)]
    };

    // Decide IfSet vs IfNotEmpty based on cardinality
    let field_def = fields.iter().find(|f| f.id == field_id);
    let is_collection = field_def
        .map(|f| {
            matches!(
                f.cardinality,
                Cardinality::OneOrMore | Cardinality::ZeroOrMore
            )
        })
        .unwrap_or(false);

    if is_collection {
        Some(RenderNode::IfNotEmpty {
            field: field_id,
            body,
        })
    } else {
        Some(RenderNode::IfSet {
            field: field_id,
            body,
        })
    }
}

/// Lower a `@name(args)?` or `@name(args)? { body }` conditional directive.
///
/// Currently only `@join(field, sep)?` is defined:
/// - Bare: `@join(f, s)?` → `IfNotEmpty { f, [Join(f, s)] }`
/// - Block: `@join(f, s)? { body }` → `IfNotEmpty { f, body }`
fn lower_conditional_directive(
    cd: &ast::ConditionalDirective,
    type_id: TypeId,
    fields: &[FieldDef],
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<RenderNode> {
    let name = cd.name.as_str();

    match &cd.suffix {
        ast::DirectiveSuffix::WithArgs(wa) => match name {
            "join" => {
                if wa.args.len() != 2 {
                    diags.push(super::error(
                        file,
                        format!("@join requires exactly 2 arguments, got {}", wa.args.len()),
                    ));
                    return None;
                }
                let field_name = ident_arg(&wa.args[0], "@join", file, diags)?;
                let field_id = resolve_field_id(&field_name, type_id, table, file, diags)?;
                let separator = lower_separator_arg(&wa.args[1], type_id, table, file, diags)?;

                // Determine body: block or default join
                let body = if let Some(ref block) = cd.block {
                    let mut nodes = Vec::new();
                    for item in &block.items {
                        if let Some(node) =
                            lower_render_expr(item, type_id, fields, table, file, diags, None)
                        {
                            nodes.push(node);
                        }
                    }
                    nodes
                } else {
                    vec![RenderNode::Join {
                        field: field_id,
                        separator,
                    }]
                };

                Some(RenderNode::IfNotEmpty {
                    field: field_id,
                    body,
                })
            }
            _ => {
                diags.push(super::error(
                    file,
                    format!("`?` suffix is not supported on `@{name}`"),
                ));
                None
            }
        },
        ast::DirectiveSuffix::EmptyParen(_) => {
            diags.push(super::error(
                file,
                format!("`@{name}()?` is not a valid conditional directive"),
            ));
            None
        }
    }
}

/// Lower the body of a block directive.
fn lower_block_body(
    block: &Option<ast::BlockBody>,
    type_id: TypeId,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Vec<RenderNode> {
    let mut nodes = Vec::new();
    if let Some(body) = block {
        for item in &body.items {
            // Block bodies inside @ifset/@ifnotempty don't need fields for ? desugaring
            // (nested ? is allowed but rare — pass empty slice)
            if let Some(node) = lower_render_expr(item, type_id, &[], table, file, diags, None) {
                nodes.push(node);
            }
        }
    }
    nodes
}

/// Lower a separator argument (can be a string literal or field ident).
fn lower_separator_arg(
    arg: &ast::Argument,
    type_id: TypeId,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<SeparatorExpr> {
    match arg {
        ast::Argument::LiteralArg(lit) => {
            Some(SeparatorExpr::Literal(strip_string_quotes(&lit.val)))
        }
        ast::Argument::IdentArg(id) => {
            let field_id = resolve_field_id(&id.val, type_id, table, file, diags)?;
            Some(SeparatorExpr::Field(field_id))
        }
    }
}

// ─── Helpers ────────────────────────────────────────────────────────────────

/// Extract a single identifier argument from an argument list.
fn single_ident_arg(
    args: &[ast::Argument],
    directive: &str,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<String> {
    if args.len() != 1 {
        diags.push(super::error(
            file,
            format!(
                "{directive} requires exactly 1 argument, got {}",
                args.len()
            ),
        ));
        return None;
    }
    ident_arg(&args[0], directive, file, diags)
}

/// Extract an identifier from an argument.
fn ident_arg(
    arg: &ast::Argument,
    directive: &str,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<String> {
    match arg {
        ast::Argument::IdentArg(id) => Some(id.val.clone()),
        ast::Argument::LiteralArg(_) => {
            diags.push(super::error(
                file,
                format!("{directive} expects an identifier argument, not a string literal"),
            ));
            None
        }
    }
}

/// Resolve a field name to its `FieldId` within a type.
fn resolve_field_id(
    field_name: &str,
    type_id: TypeId,
    table: &SymbolTable,
    file: &str,
    diags: &mut Vec<Diagnostic>,
) -> Option<FieldId> {
    match table.resolve_field(type_id, field_name) {
        Some(fi) => Some(fi.id),
        None => {
            diags.push(super::error(
                file,
                format!("unknown field `{field_name}` during IR lowering"),
            ));
            None
        }
    }
}

/// Strip surrounding double quotes from a string literal token value.
fn strip_string_quotes(s: &str) -> String {
    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
        // Also process escape sequences
        let inner = &s[1..s.len() - 1];
        unescape(inner)
    } else {
        s.to_string()
    }
}

/// Basic escape sequence processing for string literals.
fn unescape(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('n') => result.push('\n'),
                Some('t') => result.push('\t'),
                Some('r') => result.push('\r'),
                Some('\\') => result.push('\\'),
                Some('"') => result.push('"'),
                Some(other) => {
                    result.push('\\');
                    result.push(other);
                }
                None => result.push('\\'),
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Flatten the recursive `EnumMembers` AST to a flat `Vec<String>`.
fn flatten_enum_members(members: &ast::EnumMembers) -> Vec<String> {
    let mut result = Vec::new();
    flatten_inner(members, &mut result);
    result
}

fn flatten_inner(members: &ast::EnumMembers, out: &mut Vec<String>) {
    match members {
        ast::EnumMembers::Cons(cons) => {
            out.push(cons.first.clone());
            flatten_inner(&cons.rest, out);
        }
        ast::EnumMembers::Single(single) => {
            out.push(single.last.clone());
        }
    }
}