mimium-lang 4.0.0-alpha

mimium(minimal-musical-medium) an infrastructural programming language for sound and music.
Documentation
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! AST transformation pass for resolving qualified names.
//!
//! This pass converts `Expr::QualifiedVar` to `Expr::Var` with mangled names,
//! and resolves `use` aliases and wildcard imports. It runs before type checking,
//! allowing subsequent compiler phases to work with simple variable references.
//!
//! The resolution uses a 2-pass approach:
//! 1. First pass: Collect all defined names from the AST (Let/LetRec bindings)
//! 2. Second pass: Transform the AST, resolving qualified names, aliases, and wildcards
//!
//! Error handling:
//! - Private member access: Reports an error but allows type checking to proceed
//! - Unresolved names: Kept as-is for the type checker to report

use std::collections::HashSet;
use std::path::PathBuf;

use thiserror::Error;

use crate::ast::Expr;
use crate::ast::program::{ModuleInfo, resolve_qualified_path};
use crate::compiler::intrinsics;
use crate::interner::{ExprNodeId, Symbol, ToSymbol};
use crate::pattern::Pattern;
use crate::utils::error::ReportableError;
use crate::utils::metadata::Location;

/// Error types specific to qualified name resolution.
#[derive(Debug, Clone, Error)]
#[error("Private member access")]
pub enum Error {
    /// Attempted to access a private module member
    PrivateMemberAccess {
        module_path: Vec<Symbol>,
        member: Symbol,
        location: Location,
    },
}

impl ReportableError for Error {
    fn get_message(&self) -> String {
        match self {
            Error::PrivateMemberAccess {
                module_path,
                member,
                ..
            } => {
                let path_str = module_path
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>()
                    .join("::");
                format!("Member \"{member}\" in module \"{path_str}\" is private")
            }
        }
    }

    fn get_labels(&self) -> Vec<(Location, String)> {
        match self {
            Error::PrivateMemberAccess { location, .. } => {
                vec![(location.clone(), "private member accessed here".to_string())]
            }
        }
    }
}

// ============================================================================
// Pass 1: Collect all defined names from the AST
// ============================================================================

/// Collect all names defined in the AST (from Let and LetRec bindings).
fn collect_defined_names(expr: ExprNodeId, names: &mut HashSet<Symbol>) {
    match expr.to_expr() {
        Expr::Let(typed_pat, body, then) => {
            // Collect names from the pattern
            collect_names_from_pattern(&typed_pat.pat, names);
            collect_defined_names(body, names);
            if let Some(t) = then {
                collect_defined_names(t, names);
            }
        }
        Expr::LetRec(typed_id, body, then) => {
            names.insert(typed_id.id);
            collect_defined_names(body, names);
            if let Some(t) = then {
                collect_defined_names(t, names);
            }
        }
        Expr::Lambda(params, _, body) => {
            for param in params {
                names.insert(param.id);
            }
            collect_defined_names(body, names);
        }
        Expr::Tuple(v) => {
            for e in v {
                collect_defined_names(e, names);
            }
        }
        Expr::Proj(e, _) => collect_defined_names(e, names),
        Expr::Apply(fun, args) => {
            collect_defined_names(fun, names);
            for arg in args {
                collect_defined_names(arg, names);
            }
        }
        Expr::BinOp(lhs, _, rhs) => {
            collect_defined_names(lhs, names);
            collect_defined_names(rhs, names);
        }
        Expr::UniOp(_, e) => collect_defined_names(e, names),
        Expr::MacroExpand(fun, args) => {
            collect_defined_names(fun, names);
            for arg in args {
                collect_defined_names(arg, names);
            }
        }
        Expr::If(cond, then, opt_else) => {
            collect_defined_names(cond, names);
            collect_defined_names(then, names);
            if let Some(e) = opt_else {
                collect_defined_names(e, names);
            }
        }
        Expr::Block(body) => {
            if let Some(b) = body {
                collect_defined_names(b, names);
            }
        }
        Expr::Escape(e) | Expr::Bracket(e) | Expr::Paren(e) | Expr::Feed(_, e) => {
            collect_defined_names(e, names);
        }
        Expr::FieldAccess(record, _) => collect_defined_names(record, names),
        Expr::ArrayAccess(array, index) => {
            collect_defined_names(array, names);
            collect_defined_names(index, names);
        }
        Expr::ArrayLiteral(elems) => {
            for e in elems {
                collect_defined_names(e, names);
            }
        }
        Expr::RecordLiteral(fields) | Expr::ImcompleteRecord(fields) => {
            for f in fields {
                collect_defined_names(f.expr, names);
            }
        }
        Expr::RecordUpdate(record, fields) => {
            collect_defined_names(record, names);
            for f in fields {
                collect_defined_names(f.expr, names);
            }
        }
        Expr::Assign(target, value) => {
            collect_defined_names(target, names);
            collect_defined_names(value, names);
        }
        Expr::Then(e, then) => {
            collect_defined_names(e, names);
            if let Some(t) = then {
                collect_defined_names(t, names);
            }
        }
        Expr::Match(scrutinee, arms) => {
            collect_defined_names(scrutinee, names);
            for arm in arms {
                collect_defined_names(arm.body, names);
            }
        }
        // Leaf nodes - no names to collect
        Expr::Var(_) | Expr::QualifiedVar(_) | Expr::Literal(_) | Expr::Error => {}
    }
}

/// Extract all names bound by a pattern.
fn collect_names_from_pattern(pat: &Pattern, names: &mut HashSet<Symbol>) {
    match pat {
        Pattern::Single(name) => {
            names.insert(*name);
        }
        Pattern::Tuple(pats) => {
            for p in pats {
                collect_names_from_pattern(p, names);
            }
        }
        Pattern::Record(fields) => {
            for (_, p) in fields {
                collect_names_from_pattern(p, names);
            }
        }
        Pattern::Placeholder | Pattern::Error => {}
    }
}

// ============================================================================
// Pass 2: Transform the AST
// ============================================================================

/// Context for qualified name resolution.
struct ResolveContext<'a> {
    /// Module information (visibility, aliases, wildcards)
    module_info: &'a ModuleInfo,
    /// Set of all known names (from AST definitions + builtins)
    known_names: &'a HashSet<Symbol>,
    /// Current module context for relative path resolution
    current_module_context: Vec<Symbol>,
    /// File path for error reporting
    file_path: PathBuf,
    /// Accumulated errors
    errors: Vec<Error>,
}

impl<'a> ResolveContext<'a> {
    fn new(
        module_info: &'a ModuleInfo,
        known_names: &'a HashSet<Symbol>,
        file_path: PathBuf,
    ) -> Self {
        Self {
            module_info,
            known_names,
            current_module_context: Vec::new(),
            file_path,
            errors: Vec::new(),
        }
    }

    /// Check if a name exists in the known names set.
    fn name_exists(&self, name: &Symbol) -> bool {
        self.known_names.contains(name)
    }

    /// Try to resolve a simple variable name through wildcard imports.
    /// Returns the first matching mangled name if found.
    fn resolve_through_wildcards(&self, name: Symbol) -> Option<Symbol> {
        for base in &self.module_info.wildcard_imports {
            let mangled = if base.as_str().is_empty() {
                name
            } else {
                format!("{}${}", base.as_str(), name.as_str()).to_symbol()
            };

            if self.name_exists(&mangled) {
                // Check visibility - only allow public members through wildcards
                if let Some(&is_public) = self.module_info.visibility_map.get(&mangled) {
                    if is_public {
                        return Some(mangled);
                    }
                } else {
                    // If not in visibility map, treat as accessible
                    return Some(mangled);
                }
            }
        }
        None
    }

    /// Check if the resolved path is within the same module hierarchy as current context.
    fn is_within_module_hierarchy(&self, resolved_path: &[Symbol]) -> bool {
        if self.current_module_context.is_empty() || resolved_path.len() < 2 {
            return false;
        }
        let target_module = &resolved_path[..resolved_path.len() - 1];
        self.current_module_context.starts_with(target_module)
    }

    fn make_location(&self, e_id: ExprNodeId) -> Location {
        Location {
            span: e_id.to_span().clone(),
            path: self.file_path.clone(),
        }
    }
}

/// Convert qualified names in an AST, returning the transformed AST and any errors.
///
/// This function performs the following transformations:
/// 1. Converts `QualifiedVar` to `Var` with mangled names (e.g., `foo::bar` → `foo$bar`)
/// 2. Resolves explicit `use` aliases for simple `Var` references
/// 3. Resolves wildcard imports (`use foo::*`) by checking the collected environment
/// 4. Resolves relative paths within modules
/// 5. Reports errors for private member access (but allows type checking to proceed)
///
/// The `builtin_names` parameter should contain names from builtin functions and external functions.
pub fn convert_qualified_names(
    expr: ExprNodeId,
    module_info: &ModuleInfo,
    builtin_names: &[Symbol],
    file_path: PathBuf,
) -> (ExprNodeId, Vec<Error>) {
    // Pass 1: Collect all defined names from the AST
    let mut known_names: HashSet<Symbol> = builtin_names.iter().copied().collect();
    collect_defined_names(expr, &mut known_names);

    // Pass 2: Transform the AST
    let mut ctx = ResolveContext::new(module_info, &known_names, file_path);
    let result = convert_expr(&mut ctx, expr);
    (result, ctx.errors)
}

fn convert_expr(ctx: &mut ResolveContext, e_id: ExprNodeId) -> ExprNodeId {
    let loc = ctx.make_location(e_id);

    match e_id.to_expr().clone() {
        Expr::Var(name) => convert_var(ctx, name, loc),
        Expr::QualifiedVar(path) => convert_qualified_var(ctx, &path.segments, loc),

        // Update module context when entering a LetRec (function definition)
        Expr::LetRec(id, body, then) => {
            let name = id.id;
            // Save current context
            let prev_context = std::mem::take(&mut ctx.current_module_context);

            // Update context if this function has a module context
            if let Some(new_context) = ctx.module_info.module_context_map.get(&name) {
                ctx.current_module_context = new_context.clone();
            }

            let new_body = convert_expr(ctx, body);

            // Restore context
            ctx.current_module_context = prev_context;

            let new_then = then.map(|t| convert_expr(ctx, t));
            Expr::LetRec(id, new_body, new_then).into_id(loc)
        }

        // Recursively process other expression types
        Expr::Tuple(v) => {
            let new_v: Vec<_> = v.into_iter().map(|e| convert_expr(ctx, e)).collect();
            Expr::Tuple(new_v).into_id(loc)
        }
        Expr::Proj(e, idx) => {
            let new_e = convert_expr(ctx, e);
            Expr::Proj(new_e, idx).into_id(loc)
        }
        Expr::Let(pat, body, then) => {
            let prev_context = std::mem::take(&mut ctx.current_module_context);
            if let Some(module_context) = find_pattern_module_context(ctx, &pat.pat) {
                ctx.current_module_context = module_context;
            } else {
                ctx.current_module_context = prev_context.clone();
            }

            let new_body = convert_expr(ctx, body);
            let new_then = then.map(|t| convert_expr(ctx, t));

            ctx.current_module_context = prev_context;
            Expr::Let(pat, new_body, new_then).into_id(loc)
        }
        Expr::Lambda(params, r_type, body) => {
            let new_body = convert_expr(ctx, body);
            Expr::Lambda(params, r_type, new_body).into_id(loc)
        }
        Expr::Apply(fun, args) => {
            let new_fun = convert_expr(ctx, fun);
            let new_args: Vec<_> = args.into_iter().map(|e| convert_expr(ctx, e)).collect();
            Expr::Apply(new_fun, new_args).into_id(loc)
        }
        Expr::BinOp(lhs, op, rhs) => {
            let new_lhs = convert_expr(ctx, lhs);
            let new_rhs = convert_expr(ctx, rhs);
            Expr::BinOp(new_lhs, op, new_rhs).into_id(loc)
        }
        Expr::UniOp(op, expr) => {
            let new_expr = convert_expr(ctx, expr);
            Expr::UniOp(op, new_expr).into_id(loc)
        }
        Expr::MacroExpand(fun, args) => {
            let new_fun = convert_expr(ctx, fun);
            let new_args: Vec<_> = args.into_iter().map(|e| convert_expr(ctx, e)).collect();
            Expr::MacroExpand(new_fun, new_args).into_id(loc)
        }
        Expr::If(cond, then, opt_else) => {
            let new_cond = convert_expr(ctx, cond);
            let new_then = convert_expr(ctx, then);
            let new_else = opt_else.map(|e| convert_expr(ctx, e));
            Expr::If(new_cond, new_then, new_else).into_id(loc)
        }
        Expr::Block(body) => {
            let new_body = body.map(|e| convert_expr(ctx, e));
            Expr::Block(new_body).into_id(loc)
        }
        Expr::Escape(e) => {
            let new_e = convert_expr(ctx, e);
            Expr::Escape(new_e).into_id(loc)
        }
        Expr::Bracket(e) => {
            let new_e = convert_expr(ctx, e);
            Expr::Bracket(new_e).into_id(loc)
        }
        Expr::FieldAccess(record, field) => {
            let new_record = convert_expr(ctx, record);
            Expr::FieldAccess(new_record, field).into_id(loc)
        }
        Expr::ArrayAccess(array, index) => {
            let new_array = convert_expr(ctx, array);
            let new_index = convert_expr(ctx, index);
            Expr::ArrayAccess(new_array, new_index).into_id(loc)
        }
        Expr::ArrayLiteral(elems) => {
            let new_elems: Vec<_> = elems.into_iter().map(|e| convert_expr(ctx, e)).collect();
            Expr::ArrayLiteral(new_elems).into_id(loc)
        }
        Expr::RecordLiteral(fields) => {
            let new_fields = fields
                .into_iter()
                .map(|f| crate::ast::RecordField {
                    name: f.name,
                    expr: convert_expr(ctx, f.expr),
                })
                .collect();
            Expr::RecordLiteral(new_fields).into_id(loc)
        }
        Expr::ImcompleteRecord(fields) => {
            let new_fields = fields
                .into_iter()
                .map(|f| crate::ast::RecordField {
                    name: f.name,
                    expr: convert_expr(ctx, f.expr),
                })
                .collect();
            Expr::ImcompleteRecord(new_fields).into_id(loc)
        }
        Expr::RecordUpdate(record, fields) => {
            let new_record = convert_expr(ctx, record);
            let new_fields = fields
                .into_iter()
                .map(|f| crate::ast::RecordField {
                    name: f.name,
                    expr: convert_expr(ctx, f.expr),
                })
                .collect();
            Expr::RecordUpdate(new_record, new_fields).into_id(loc)
        }
        Expr::Assign(target, value) => {
            let new_target = convert_expr(ctx, target);
            let new_value = convert_expr(ctx, value);
            Expr::Assign(new_target, new_value).into_id(loc)
        }
        Expr::Then(e, then) => {
            let new_e = convert_expr(ctx, e);
            let new_then = then.map(|t| convert_expr(ctx, t));
            Expr::Then(new_e, new_then).into_id(loc)
        }
        Expr::Feed(sym, e) => {
            let new_e = convert_expr(ctx, e);
            Expr::Feed(sym, new_e).into_id(loc)
        }
        Expr::Paren(e) => {
            // Unwrap parenthesized expressions
            convert_expr(ctx, e)
        }
        Expr::Match(scrutinee, arms) => {
            let new_scrutinee = convert_expr(ctx, scrutinee);
            let new_arms = arms
                .into_iter()
                .map(|arm| crate::ast::MatchArm {
                    pattern: arm.pattern,
                    body: convert_expr(ctx, arm.body),
                })
                .collect();
            Expr::Match(new_scrutinee, new_arms).into_id(loc)
        }

        // Leaf nodes that don't need transformation
        Expr::Literal(_) | Expr::Error => e_id,
    }
}

fn find_pattern_module_context(
    ctx: &ResolveContext,
    pat: &crate::pattern::Pattern,
) -> Option<Vec<Symbol>> {
    match pat {
        Pattern::Single(name) => ctx.module_info.module_context_map.get(name).cloned(),
        Pattern::Tuple(items) => items
            .iter()
            .find_map(|item| find_pattern_module_context(ctx, item)),
        Pattern::Record(fields) => fields
            .iter()
            .find_map(|(_, item)| find_pattern_module_context(ctx, item)),
        Pattern::Placeholder | Pattern::Error => None,
    }
}

fn resolve_alias_chain(module_info: &ModuleInfo, symbol: Symbol) -> Symbol {
    let mut current = symbol;
    let mut visited = HashSet::new();
    while visited.insert(current) {
        match module_info.use_alias_map.get(&current).copied() {
            Some(next) if next != current => current = next,
            _ => break,
        }
    }
    current
}

fn is_core_intrinsic_name(name: Symbol) -> bool {
    matches!(
        name.as_str(),
        intrinsics::NEG
            | intrinsics::ADD
            | intrinsics::SUB
            | intrinsics::MULT
            | intrinsics::DIV
            | intrinsics::EQ
            | intrinsics::NE
            | intrinsics::LE
            | intrinsics::LT
            | intrinsics::GE
            | intrinsics::GT
            | intrinsics::MODULO
            | intrinsics::POW
            | intrinsics::AND
            | intrinsics::OR
            | intrinsics::TOFLOAT
    )
}

/// Convert a simple variable reference, resolving explicit `use` aliases and wildcards.
fn convert_var(ctx: &mut ResolveContext, name: Symbol, loc: Location) -> ExprNodeId {
    // Check if this is a use alias (explicit `use foo::bar` or `use foo::bar as alias`)
    if ctx.module_info.use_alias_map.contains_key(&name) {
        let mangled_name = resolve_alias_chain(ctx.module_info, name);
        // Check visibility
        if let Some(&is_public) = ctx.module_info.visibility_map.get(&mangled_name)
            && !is_public
            && !ctx.is_within_module_hierarchy(&extract_path_from_mangled(mangled_name))
        {
            let parts: Vec<&str> = mangled_name.as_str().split('$').collect();
            let module_path: Vec<Symbol> = parts[..parts.len() - 1]
                .iter()
                .map(|s| s.to_symbol())
                .collect();
            let member = parts.last().unwrap().to_symbol();
            ctx.errors.push(Error::PrivateMemberAccess {
                module_path,
                member,
                location: loc.clone(),
            });
            // Continue with the resolved name despite the error
        }
        return Expr::Var(mangled_name).into_id(loc);
    }

    // Try wildcard resolution
    if let Some(mangled) = ctx.resolve_through_wildcards(name) {
        return Expr::Var(mangled).into_id(loc);
    }

    if ctx.name_exists(&name) && is_core_intrinsic_name(name) {
        return Expr::Var(name).into_id(loc);
    }

    // Try relative resolution from current module context (for intra-module references)
    // and its parent modules.
    if !ctx.current_module_context.is_empty() {
        for prefix_len in (1..=ctx.current_module_context.len()).rev() {
            let mut relative_path = ctx.current_module_context[..prefix_len].to_vec();
            relative_path.push(name);
            let relative_mangled = relative_path
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join("$")
                .to_symbol();
            if ctx.name_exists(&relative_mangled) {
                return Expr::Var(relative_mangled).into_id(loc);
            }
        }
    }

    // If the unqualified name already exists (e.g. local binding or builtin),
    // keep it as-is.
    if ctx.name_exists(&name) {
        return Expr::Var(name).into_id(loc);
    }

    // Keep as-is - will be resolved by type checker (local variable or error)
    Expr::Var(name).into_id(loc)
}

/// Convert a qualified variable reference (e.g., `module::func`).
fn convert_qualified_var(
    ctx: &mut ResolveContext,
    segments: &[Symbol],
    loc: Location,
) -> ExprNodeId {
    // Build mangled name for absolute path
    let mangled_name = if segments.len() == 1 {
        segments[0]
    } else {
        segments
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join("$")
            .to_symbol()
    };

    // Try to resolve the path with relative fallback
    let (resolved_name, resolved_path) = resolve_qualified_path(
        segments,
        mangled_name,
        &ctx.current_module_context,
        |name| ctx.name_exists(name),
    );

    // Check if it's a re-exported alias
    let lookup_name = resolve_alias_chain(ctx.module_info, resolved_name);

    // Check visibility for module members
    if resolved_path.len() > 1
        && let Some(&is_public) = ctx.module_info.visibility_map.get(&resolved_name)
    {
        let is_same_module = ctx.is_within_module_hierarchy(&resolved_path);
        if !is_public && !is_same_module {
            ctx.errors.push(Error::PrivateMemberAccess {
                module_path: resolved_path[..resolved_path.len() - 1].to_vec(),
                member: *resolved_path.last().unwrap(),
                location: loc.clone(),
            });
            // Continue with the resolved name despite the error
        }
    }

    Expr::Var(lookup_name).into_id(loc)
}

/// Extract path segments from a mangled name (e.g., "foo$bar$baz" -> ["foo", "bar", "baz"])
fn extract_path_from_mangled(mangled: Symbol) -> Vec<Symbol> {
    mangled.as_str().split('$').map(|s| s.to_symbol()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::program::QualifiedPath;
    use crate::pattern::TypedPattern;
    use crate::types::Type;

    fn make_loc() -> Location {
        Location {
            span: 0..1,
            path: PathBuf::from("/test"),
        }
    }

    #[test]
    fn test_qualified_var_to_mangled() {
        let loc = make_loc();
        let mut module_info = ModuleInfo::default();
        module_info
            .visibility_map
            .insert("foo$bar".to_symbol(), true);

        let expr = Expr::QualifiedVar(QualifiedPath {
            segments: vec!["foo".to_symbol(), "bar".to_symbol()],
        })
        .into_id(loc.clone());

        // Add foo$bar to builtin_names so it's recognized
        let builtin_names = vec!["foo$bar".to_symbol()];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "foo$bar"));
    }

    #[test]
    fn test_private_member_access_reports_error_but_continues() {
        let loc = make_loc();
        let mut module_info = ModuleInfo::default();
        module_info
            .visibility_map
            .insert("foo$secret".to_symbol(), false);

        let expr = Expr::QualifiedVar(QualifiedPath {
            segments: vec!["foo".to_symbol(), "secret".to_symbol()],
        })
        .into_id(loc.clone());

        let builtin_names = vec!["foo$secret".to_symbol()];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        // Error should be reported
        assert_eq!(errors.len(), 1);
        assert!(matches!(&errors[0], Error::PrivateMemberAccess { .. }));
        // But the expression should still be converted
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "foo$secret"));
    }

    #[test]
    fn test_use_alias_resolution() {
        let loc = make_loc();
        let mut module_info = ModuleInfo::default();
        module_info
            .use_alias_map
            .insert("func".to_symbol(), "module$func".to_symbol());
        module_info
            .visibility_map
            .insert("module$func".to_symbol(), true);

        let expr = Expr::Var("func".to_symbol()).into_id(loc.clone());

        let builtin_names = vec!["module$func".to_symbol()];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "module$func"));
    }

    #[test]
    fn test_wildcard_resolution() {
        let loc = make_loc();
        let mut module_info = ModuleInfo::default();
        module_info.wildcard_imports.push("mymod".to_symbol());
        module_info
            .visibility_map
            .insert("mymod$helper".to_symbol(), true);

        let expr = Expr::Var("helper".to_symbol()).into_id(loc.clone());

        // mymod$helper is in the "environment" (builtin_names here for test)
        let builtin_names = vec!["mymod$helper".to_symbol()];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        // Now the variable SHOULD be resolved through wildcard
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "mymod$helper"));
    }

    #[test]
    fn test_wildcard_not_resolved_when_name_not_exists() {
        let loc = make_loc();
        let mut module_info = ModuleInfo::default();
        module_info.wildcard_imports.push("mymod".to_symbol());
        // mymod$helper is NOT in visibility_map and NOT in known_names

        let expr = Expr::Var("helper".to_symbol()).into_id(loc.clone());

        let builtin_names = vec![]; // Empty - no names known
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        // The variable should NOT be resolved - remains as "helper"
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "helper"));
    }

    #[test]
    fn test_simple_var_unchanged() {
        let loc = make_loc();
        let module_info = ModuleInfo::default();

        let expr = Expr::Var("local_var".to_symbol()).into_id(loc.clone());

        let builtin_names = vec![];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        assert!(matches!(result.to_expr(), Expr::Var(name) if name.as_str() == "local_var"));
    }

    #[test]
    fn test_names_collected_from_let() {
        // Test that names defined in Let are collected and can be used
        let loc = make_loc();
        let module_info = ModuleInfo::default();

        let unknownty = Type::Unknown.into_id_with_location(loc.clone());
        // let x = 1; x
        let expr = Expr::Let(
            TypedPattern {
                pat: Pattern::Single("x".to_symbol()),
                ty: unknownty,
                default_value: None,
            },
            Expr::Literal(crate::ast::Literal::Float("1.0".to_symbol())).into_id(loc.clone()),
            Some(Expr::Var("x".to_symbol()).into_id(loc.clone())),
        )
        .into_id(loc.clone());

        let builtin_names = vec![];
        let (result, errors) =
            convert_qualified_names(expr, &module_info, &builtin_names, PathBuf::from("/test"));

        assert!(errors.is_empty());
        // The structure should be preserved
        assert!(matches!(result.to_expr(), Expr::Let(..)));
    }
}