beamr 0.16.0

A Rust runtime with the BEAM's execution model, targeting Gleam
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
//! Module registry — dual-version.
//!
//! Stores loaded modules by atom name. Supports lookup by name,
//! function lookup by MFA (module:function/arity), and handles
//! duplicate module loads (the new version becomes current while the
//! previous current remains available as the old version until purged).
//! Returns an explicit undef error for missing exports.

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;

use dashmap::DashMap;
use dashmap::mapref::entry::Entry;

use crate::atom::Atom;
use crate::constant_pool::ConstantPool;
use crate::error::ExecError;
use crate::loader::{Instruction, LambdaEntry, LineInfo, Literal};
use crate::native::NativeEntry;

/// Callable target produced by import resolution.
#[derive(Copy, Clone, Debug)]
pub enum ResolvedImportTarget {
    /// A function exported by another loaded BEAM module.
    Code {
        /// Target module atom.
        module: Atom,
        /// Label exported by the target module.
        label: u32,
    },
    /// A Rust native function registered as a BIF.
    Native(NativeEntry),
    /// A native import denied by the capability policy at load time.
    ///
    /// Carried as an explicit variant (not a sentinel function pointer, which
    /// is unreliable to compare across codegen units in release builds) so
    /// dispatch can raise a rich `undef` with the denied MFA.
    Denied {
        /// Capability the policy refused to grant.
        capability: crate::native::Capability,
    },
    /// A BEAM function whose module was not loaded when this module was loaded.
    Deferred {
        /// Target module atom.
        module: Atom,
        /// Target function atom.
        function: Atom,
        /// Target arity.
        arity: u8,
    },
    /// An import whose module was loaded but did not export the requested MFA.
    ///
    /// Keeping a placeholder preserves BEAM import-table indexing so later
    /// imports remain reachable even when an earlier import is unresolved.
    Unresolved {
        /// Target module atom.
        module: Atom,
        /// Target function atom.
        function: Atom,
        /// Target arity.
        arity: u8,
    },
}

/// One import table entry and the callable target it resolved to.
#[derive(Copy, Clone, Debug)]
pub struct ResolvedImport {
    /// Imported module atom.
    pub module: Atom,
    /// Imported function atom.
    pub function: Atom,
    /// Imported arity.
    pub arity: u8,
    /// Resolved callable target.
    pub target: ResolvedImportTarget,
}

/// Origin metadata for a loaded module.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ModuleOrigin {
    /// Module loaded from a filesystem path.
    Filesystem(PathBuf),
    /// Module loaded from the compile-time embedded archive.
    Embedded,
    /// Module loaded directly from caller-provided bytes or test/preload setup.
    Preloaded,
    /// Module fetched at runtime by the wasm artifact loader (WPORT-6).
    Fetched,
}

impl ModuleOrigin {
    /// Return the atom name used by `module_info(Module, source)`.
    #[must_use]
    pub const fn source_atom_name(&self) -> &'static str {
        match self {
            Self::Filesystem(_) => "filesystem",
            Self::Embedded => "embedded",
            Self::Preloaded => "preloaded",
            Self::Fetched => "fetched",
        }
    }
}

/// Immutable loaded module data shared by the registry and processes.
#[derive(Clone, Debug)]
pub struct Module {
    /// Module atom name.
    pub name: Atom,
    /// Monotonically increasing generation assigned by the registry.
    pub generation: u64,
    /// Where this module was loaded from.
    pub origin: ModuleOrigin,
    /// Exported functions keyed by function atom and arity, mapping to code labels.
    pub exports: HashMap<(Atom, u8), u32>,
    /// O(1) index from code label numbers to instruction indices.
    pub label_index: HashMap<u32, usize>,
    /// Decoded BEAM instructions.
    pub code: Vec<Instruction>,
    /// Sorted func_info table: instruction pointer, function atom, arity.
    pub function_table: Vec<(usize, Atom, u8)>,
    /// Sorted line table: instruction pointer, line-info index.
    pub line_table: Vec<(usize, usize)>,
    /// Decoded literal table.
    pub literals: Vec<Literal>,
    /// Pre-materialised literal terms backed by module-owned storage.
    pub constant_pool: ConstantPool,
    /// Import table entries that resolved to callable targets.
    pub resolved_imports: Vec<ResolvedImport>,
    /// Decoded lambda table entries.
    pub lambdas: Vec<LambdaEntry>,
    /// Decoded string table bytes.
    pub string_table: Vec<u8>,
    /// Decoded line information.
    pub line_info: Vec<LineInfo>,
}

impl Module {
    /// Returns the registry-assigned module generation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Finds a lambda by its stable hot-code identifier.
    #[must_use]
    pub fn find_lambda_by_id(&self, unique_id: u64) -> Option<&LambdaEntry> {
        self.lambdas
            .iter()
            .find(|lambda| lambda.unique_id == unique_id)
    }

    /// Resolves a code label to its instruction index.
    pub fn label_ip(&self, label: u32) -> Result<usize, ExecError> {
        self.label_index
            .get(&label)
            .copied()
            .ok_or(ExecError::InvalidLabel { label })
    }

    /// Resolves an exported function to its instruction index.
    pub fn export_ip(&self, function: Atom, arity: u8) -> Result<usize, ExecError> {
        let label = self
            .exports
            .get(&(function, arity))
            .copied()
            .ok_or(ExecError::Undef {
                module: self.name,
                function,
                arity,
            })?;

        self.label_ip(label)
    }

    /// Resolves the function containing `ip` from the last preceding `func_info`.
    #[must_use]
    pub fn function_at_ip(&self, ip: usize) -> Option<(Atom, u8)> {
        let index = self
            .function_table
            .binary_search_by_key(&ip, |(entry_ip, _, _)| *entry_ip)
            .map_or_else(|insertion| insertion.checked_sub(1), Some)?;
        let (_, function, arity) = self.function_table.get(index).copied()?;
        Some((function, arity))
    }

    /// Returns whether `ip` is a canonical function entry: the `FuncInfo`
    /// instruction itself, or the instruction immediately following it (the
    /// entry label position that `export_ip`/call-label resolution produce).
    ///
    /// JIT dispatch and [`Self::function_instructions`] refuse non-canonical
    /// ips: a mid-function label shares its containing function's MFA, so
    /// profiling, compiling, or caching a suffix under that identity would let
    /// entry calls execute the suffix in place of the whole function.
    #[must_use]
    pub fn is_function_entry(&self, ip: usize) -> bool {
        if ip >= self.code.len() {
            return false;
        }
        self.function_table
            .binary_search_by_key(&ip, |(entry_ip, _, _)| *entry_ip)
            .map_or_else(
                |insertion| {
                    insertion.checked_sub(1).is_some_and(|index| {
                        self.function_table
                            .get(index)
                            .is_some_and(|(entry_ip, _, _)| ip == entry_ip + 1)
                    })
                },
                |_| true,
            )
    }

    /// Returns the instruction slice of the function entered at `entry_ip` —
    /// the slice shape `JitCompiler::compile` consumes, identical to
    /// `aot::exported_instructions` for the same function.
    ///
    /// `entry_ip` is a canonical call target (a `label_ip`/`export_ip`
    /// result): the single entry `Label`/`FuncInfo` prelude instruction is
    /// skipped, and the slice ends before the next `FuncInfo` or at code end.
    /// `None` when `entry_ip` is outside the code, precedes the first
    /// function entry, or is not a canonical function entry
    /// ([`Self::is_function_entry`]) — a mid-function ip yields no slice.
    #[must_use]
    pub fn function_instructions(&self, entry_ip: usize) -> Option<&[Instruction]> {
        if !self.is_function_entry(entry_ip) {
            return None;
        }
        // LEG 1c A1+A2: retain the func_info prelude. `is_function_entry` accepts
        // either the `FuncInfo` ip or the export label right after it; locate this
        // function's `FuncInfo`, then start the slice at its preceding prelude
        // label (the dispatch fail-edge target) so a multi-clause `select_val`
        // fail and a self `call_last {f,entry}` both resolve. The `FuncInfo` is
        // the function_clause landing pad (lowered as a DEOPT terminal); normal
        // calls enter at the export label, which sits inside the slice. Kept
        // element-identical to `aot::exported_instructions` (the R8 pin is wall).
        let funcinfo_ip = match self.code.get(entry_ip)? {
            Instruction::FuncInfo { .. } => entry_ip,
            _ => entry_ip
                .checked_sub(1)
                .filter(|&ip| matches!(self.code.get(ip), Some(Instruction::FuncInfo { .. })))?,
        };
        // The prelude is `Label(prelude), [Line...], FuncInfo`; back up over any
        // line markers to the prelude label (the dispatch fail-edge target).
        let mut start = funcinfo_ip;
        while start > 0 && matches!(self.code.get(start - 1), Some(Instruction::Line { .. })) {
            start -= 1;
        }
        if start > 0 && matches!(self.code.get(start - 1), Some(Instruction::Label { .. })) {
            start -= 1;
        }
        // The slice ends at the NEXT function's `FuncInfo`, searched from AFTER
        // this function's own retained `FuncInfo` so it does not self-terminate.
        let end = self
            .code
            .iter()
            .enumerate()
            .skip(funcinfo_ip + 1)
            .find_map(|(index, instruction)| match instruction {
                Instruction::FuncInfo { .. } => Some(index),
                _ => None,
            })
            .unwrap_or(self.code.len());
        self.code.get(start..end)
    }

    /// Resolves the source line containing `ip` from the last preceding line marker.
    #[must_use]
    pub fn line_at_ip(&self, ip: usize) -> Option<u32> {
        let index = self
            .line_table
            .binary_search_by_key(&ip, |(entry_ip, _)| *entry_ip)
            .map_or_else(|insertion| insertion.checked_sub(1), Some)?;
        let (_, line_info_index) = self.line_table.get(index).copied()?;
        self.line_info.get(line_info_index).map(|info| info.line)
    }
}

/// Code pointer returned by function lookup.
#[derive(Clone, Debug)]
pub struct CodePointer {
    /// Loaded module containing the target code.
    pub module: Arc<Module>,
    /// Code label for the exported function.
    pub label: u32,
    /// Generation of the loaded module containing the target code.
    pub generation: u64,
}

impl PartialEq for CodePointer {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.module, &other.module)
            && self.label == other.label
            && self.generation == other.generation
    }
}

impl Eq for CodePointer {}

/// Current and retained old versions for one loaded module name.
#[derive(Clone, Debug)]
pub struct ModuleVersions {
    /// Current module version used by compatibility lookups.
    pub current: Arc<Module>,
    /// Previous current module version, retained until safe purge.
    pub old: Option<Arc<Module>>,
}

/// Error returned when purging retained old module versions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PurgeError {
    /// The old version is still referenced outside the registry.
    StillReferenced { module: Atom, ref_count: usize },
    /// The module has no retained old version.
    NoOldVersion { module: Atom },
}

impl fmt::Display for PurgeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::StillReferenced { module, ref_count } => write!(
                formatter,
                "old module version {:?} is still referenced ({ref_count} references)",
                module
            ),
            Self::NoOldVersion { module } => {
                write!(formatter, "module {:?} has no old version to purge", module)
            }
        }
    }
}

impl std::error::Error for PurgeError {}

/// One registry slot: the live versions plus the name's next generation.
///
/// The slot SURVIVES `delete_module` (versions become `None`) so generations
/// are monotonic across delete — a deleted name's reload continues the
/// numbering instead of restarting at 1, which would let stale JIT state from
/// a prior incarnation collide with the replacement. Growth is bounded by the
/// count of distinct names ever deleted and not reloaded: one small slot each.
#[derive(Debug)]
struct ModuleSlot {
    versions: Option<ModuleVersions>,
    /// The generation the next insert of this name receives when no current
    /// version exists; maintained as `last assigned + 1` on every insert.
    next_generation: u64,
}

/// Thread-safe dual-version module registry.
///
/// Generation numbers are per-name and MONOTONIC ACROSS DELETE: within one
/// registry, a later insert of a name never receives a generation less than
/// or equal to any earlier version's — "older generation" always means older
/// code.
#[derive(Debug, Default)]
pub struct ModuleRegistry {
    modules: DashMap<Atom, ModuleSlot>,
}

impl ModuleRegistry {
    /// Creates an empty module registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a module, promoting any current version to old.
    pub fn insert(&self, module: Module) -> Arc<Module> {
        self.insert_version(module)
    }

    /// Inserts an already shared module, promoting any current version to old.
    ///
    /// The registry assigns generations at insertion time, so this method clones
    /// the module data into a newly shared current version instead of storing the
    /// caller-provided `Arc` by pointer identity.
    pub fn insert_arc(&self, module: Arc<Module>) -> Arc<Module> {
        self.insert_version((*module).clone())
    }

    fn insert_version(&self, mut module: Module) -> Arc<Module> {
        let name = module.name;

        match self.modules.entry(name) {
            Entry::Occupied(mut entry) => {
                let slot = entry.get_mut();
                let (generation, previous_current) = match &slot.versions {
                    Some(versions) => (
                        versions.current.generation().saturating_add(1),
                        Some(Arc::clone(&versions.current)),
                    ),
                    // A deleted name continues its numbering: the slot's
                    // retained next_generation is the monotonicity carrier.
                    None => (slot.next_generation.max(1), None),
                };
                module.generation = generation;
                let module = Arc::new(module);
                slot.versions = Some(ModuleVersions {
                    current: Arc::clone(&module),
                    old: previous_current,
                });
                slot.next_generation = generation.saturating_add(1);
                module
            }
            Entry::Vacant(entry) => {
                module.generation = 1;
                let module = Arc::new(module);
                entry.insert(ModuleSlot {
                    versions: Some(ModuleVersions {
                        current: Arc::clone(&module),
                        old: None,
                    }),
                    next_generation: 2,
                });
                module
            }
        }
    }

    /// Looks up the current module version by name.
    #[must_use]
    pub fn lookup(&self, name: Atom) -> Option<Arc<Module>> {
        self.modules.get(&name).and_then(|entry| {
            entry
                .value()
                .versions
                .as_ref()
                .map(|versions| Arc::clone(&versions.current))
        })
    }

    /// Looks up the origin metadata for the current module version by name.
    #[must_use]
    pub fn origin(&self, name: Atom) -> Option<ModuleOrigin> {
        self.lookup(name).map(|module| module.origin.clone())
    }

    /// Lists current loaded modules and their origin metadata.
    #[must_use]
    pub fn all_loaded(&self) -> Vec<(Atom, ModuleOrigin)> {
        let mut modules: Vec<_> = self
            .modules
            .iter()
            .filter_map(|entry| {
                let versions = entry.value().versions.as_ref()?;
                Some((*entry.key(), versions.current.origin.clone()))
            })
            .collect();
        modules.sort_by_key(|(name, _)| name.index());
        modules
    }

    /// Looks up the retained old module version by name.
    #[must_use]
    pub fn lookup_old(&self, name: Atom) -> Option<Arc<Module>> {
        self.modules.get(&name).and_then(|entry| {
            entry
                .value()
                .versions
                .as_ref()
                .and_then(|versions| versions.old.as_ref().map(Arc::clone))
        })
    }

    /// Returns the number of retained versions for a module name.
    #[must_use]
    pub fn module_version_count(&self, name: Atom) -> usize {
        self.modules.get(&name).map_or(0, |entry| {
            entry
                .value()
                .versions
                .as_ref()
                .map_or(0, |versions| 1 + usize::from(versions.old.is_some()))
        })
    }

    /// Purges an old module version when only the registry still references it.
    ///
    /// Callers must serialize purge requests through the single code-server
    /// thread. This method keeps the strong-count check and removal under one
    /// DashMap entry lock.
    pub fn purge_old(&self, name: Atom) -> Result<(), PurgeError> {
        let mut entry = self
            .modules
            .get_mut(&name)
            .ok_or(PurgeError::NoOldVersion { module: name })?;
        let versions = entry
            .versions
            .as_mut()
            .ok_or(PurgeError::NoOldVersion { module: name })?;
        let old = versions
            .old
            .as_ref()
            .ok_or(PurgeError::NoOldVersion { module: name })?;
        let ref_count = Arc::strong_count(old);
        if ref_count != 1 {
            return Err(PurgeError::StillReferenced {
                module: name,
                ref_count,
            });
        }

        versions.old = None;
        Ok(())
    }

    /// Looks up an exported function by module/function/arity.
    pub fn lookup_mfa(
        &self,
        module: Atom,
        function: Atom,
        arity: u8,
    ) -> Result<CodePointer, ExecError> {
        let loaded = self.lookup(module).ok_or(ExecError::Undef {
            module,
            function,
            arity,
        })?;
        let label = loaded
            .exports
            .get(&(function, arity))
            .copied()
            .ok_or(ExecError::Undef {
                module,
                function,
                arity,
            })?;

        Ok(CodePointer {
            generation: loaded.generation(),
            module: loaded,
            label,
        })
    }

    /// Returns true when an old version is retained for `name`.
    #[must_use]
    pub fn has_old_code(&self, name: Atom) -> bool {
        self.lookup_old(name).is_some()
    }

    /// Removes every retained version for `name` from the registry.
    ///
    /// Callers are responsible for checking process references before deleting.
    /// The name's generation numbering SURVIVES the delete: a later reload
    /// continues at the next generation rather than restarting at 1, so stale
    /// JIT state from the deleted incarnation can never share a generation
    /// number with the replacement.
    pub fn delete_module(&self, name: Atom) -> bool {
        self.modules
            .get_mut(&name)
            .is_some_and(|mut entry| entry.versions.take().is_some())
    }

    /// Removes the retained old version without checking external references.
    ///
    /// This is only for force purge after the scheduler has terminated every
    /// process that was running or pinned to old code.
    ///
    /// Only the `threads`-gated scheduler `module_management` path calls this.
    #[cfg(feature = "threads")]
    pub(crate) fn force_remove_old(&self, name: Atom) -> Result<(), PurgeError> {
        let mut entry = self
            .modules
            .get_mut(&name)
            .ok_or(PurgeError::NoOldVersion { module: name })?;
        entry
            .versions
            .as_mut()
            .ok_or(PurgeError::NoOldVersion { module: name })?
            .old
            .take()
            .ok_or(PurgeError::NoOldVersion { module: name })?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::{Module, ModuleOrigin, ModuleRegistry, PurgeError};
    use crate::atom::AtomTable;
    use crate::error::ExecError;
    use crate::loader::{LambdaEntry, LineInfo};

    fn label_index(code: &[crate::loader::Instruction]) -> HashMap<u32, usize> {
        code.iter()
            .enumerate()
            .filter_map(|(ip, instruction)| match instruction {
                crate::loader::Instruction::Label { label } => Some((*label, ip)),
                _ => None,
            })
            .collect()
    }

    fn empty_module(name: crate::atom::Atom) -> Module {
        Module {
            name,
            generation: 0,
            origin: ModuleOrigin::Preloaded,
            exports: HashMap::new(),
            label_index: HashMap::new(),
            code: Vec::new(),
            literals: Vec::new(),
            constant_pool: crate::constant_pool::ConstantPool::default(),
            resolved_imports: Vec::new(),
            lambdas: Vec::new(),
            string_table: Vec::new(),
            function_table: Vec::new(),
            line_table: Vec::new(),
            line_info: Vec::new(),
        }
    }

    #[test]
    fn fetched_origin_reports_fetched_source_atom() {
        // WPORT-6 (OQ-C RULED IN): the additive runtime-fetch provenance
        // variant pins its `module_info(Module, source)` atom name.
        assert_eq!(ModuleOrigin::Fetched.source_atom_name(), "fetched");
    }

    #[test]
    fn function_at_ip_resolves_last_preceding_func_info() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.function_table = vec![
            (1, crate::atom::Atom::OK, 0),
            (5, crate::atom::Atom::BADARG, 1),
            (9, crate::atom::Atom::FLUSH, 2),
        ];

        assert_eq!(module.function_at_ip(0), None);
        assert_eq!(module.function_at_ip(1), Some((crate::atom::Atom::OK, 0)));
        assert_eq!(module.function_at_ip(4), Some((crate::atom::Atom::OK, 0)));
        assert_eq!(
            module.function_at_ip(5),
            Some((crate::atom::Atom::BADARG, 1))
        );
        assert_eq!(
            module.function_at_ip(12),
            Some((crate::atom::Atom::FLUSH, 2))
        );
    }

    #[test]
    fn function_instructions_slices_one_function_between_func_info_boundaries() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.code = vec![
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::OK)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Label { label: 2 },
            crate::loader::Instruction::Return,
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::BADARG)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Label { label: 3 },
            crate::loader::Instruction::Swap {
                left: crate::loader::decode::Operand::X(0),
                right: crate::loader::decode::Operand::X(1),
            },
            crate::loader::Instruction::Return,
        ];
        module.function_table = vec![
            (0, crate::atom::Atom::OK, 0),
            (3, crate::atom::Atom::BADARG, 0),
        ];

        // LEG 1c A1+A2: the slice RETAINS the func_info prelude (starts at the
        // FuncInfo, or its preceding prelude label when present) and stops before
        // the next FuncInfo.
        assert_eq!(
            module.function_instructions(1),
            Some(&module.code[0..3]),
            "first function's slice retains the func_info prelude and ends before the next FuncInfo"
        );
        // Entry label of the last function: the slice runs to code end.
        assert_eq!(module.function_instructions(4), Some(&module.code[3..7]));
        // A mid-function ip is NOT a canonical entry: compiling a suffix under
        // the containing function's MFA would let entry calls execute the
        // suffix in place of the whole function.
        assert!(!module.is_function_entry(5));
        assert_eq!(
            module.function_instructions(5),
            None,
            "a mid-function ip must yield no slice"
        );
        // Canonical entries: the FuncInfo itself and the instruction after it.
        assert!(module.is_function_entry(0));
        assert!(module.is_function_entry(1));
        assert!(module.is_function_entry(3));
        assert!(module.is_function_entry(4));
        assert!(!module.is_function_entry(2));
        assert!(!module.is_function_entry(6));
        assert!(!module.is_function_entry(7));
    }

    #[test]
    fn function_instructions_includes_a_non_prelude_entry_instruction() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.code = vec![
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::OK)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Swap {
                left: crate::loader::decode::Operand::X(0),
                right: crate::loader::decode::Operand::X(1),
            },
            crate::loader::Instruction::Return,
        ];
        module.function_table = vec![(0, crate::atom::Atom::OK, 0)];

        // The entry position holds a body instruction (no entry label): it is
        // canonical. The slice retains the func_info prelude (LEG 1c A2), so it
        // spans the FuncInfo through the body.
        assert!(module.is_function_entry(1));
        assert_eq!(module.function_instructions(1), Some(&module.code[0..3]));
    }

    #[test]
    fn function_instructions_yields_an_empty_slice_for_an_empty_non_final_function() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.code = vec![
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::OK)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Label { label: 2 },
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::BADARG)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Label { label: 3 },
            crate::loader::Instruction::Return,
        ];
        module.function_table = vec![
            (0, crate::atom::Atom::OK, 0),
            (2, crate::atom::Atom::BADARG, 0),
        ];

        // LEG 1c A2: with prelude retention an empty (bodyless) function yields
        // its FuncInfo prelude + entry label, ending before the next FuncInfo.
        assert_eq!(
            module.function_instructions(1),
            Some(&module.code[0..2]),
            "an empty non-final function retains its func_info prelude + entry label"
        );
        // The following function slices from its own prelude label (the label
        // immediately before its FuncInfo) through its body.
        assert_eq!(module.function_instructions(3), Some(&module.code[1..5]));
    }

    #[test]
    fn function_instructions_refuses_out_of_code_and_pre_function_ips() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.code = vec![
            crate::loader::Instruction::Label { label: 1 },
            crate::loader::Instruction::Return,
            crate::loader::Instruction::FuncInfo {
                module: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::MODULE)),
                function: crate::loader::decode::Operand::Atom(Some(crate::atom::Atom::OK)),
                arity: crate::loader::decode::Operand::Unsigned(0),
            },
            crate::loader::Instruction::Label { label: 2 },
            crate::loader::Instruction::Return,
        ];
        module.function_table = vec![(2, crate::atom::Atom::OK, 0)];

        assert_eq!(
            module.function_instructions(0),
            None,
            "an ip before the first function entry has no owning function"
        );
        assert_eq!(
            module.function_instructions(module.code.len()),
            None,
            "an ip outside the code bounds yields no slice"
        );
        // LEG 1c A2: the slice retains the func_info prelude (code[2] here).
        assert_eq!(module.function_instructions(3), Some(&module.code[2..5]));
    }

    #[test]
    fn line_at_ip_resolves_last_preceding_line_marker() {
        let mut module = empty_module(crate::atom::Atom::MODULE);
        module.line_info = vec![
            LineInfo { file: 0, line: 10 },
            LineInfo { file: 0, line: 20 },
        ];
        module.line_table = vec![(2, 0), (6, 1), (10, 99)];

        assert_eq!(module.line_at_ip(1), None);
        assert_eq!(module.line_at_ip(2), Some(10));
        assert_eq!(module.line_at_ip(5), Some(10));
        assert_eq!(module.line_at_ip(6), Some(20));
        assert_eq!(module.line_at_ip(10), None);
    }

    #[test]
    fn registry_stores_and_replaces_modules_by_name() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let registry = ModuleRegistry::new();

        let first = registry.insert(empty_module(module_name));
        let mut replacement = empty_module(module_name);
        replacement.code.push(crate::loader::Instruction::Return);
        let second = registry.insert(replacement);

        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup(module_name).expect("module loaded"),
            &second
        ));
        assert!(!std::sync::Arc::ptr_eq(&first, &second));
    }

    #[test]
    fn registry_retains_only_current_and_previous_old_versions() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let registry = ModuleRegistry::new();

        let v1 = registry.insert(empty_module(module_name));
        assert_eq!(registry.module_version_count(module_name), 1);
        assert!(registry.lookup_old(module_name).is_none());
        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup(module_name).expect("v1 current"),
            &v1
        ));

        let mut second = empty_module(module_name);
        second.code.push(crate::loader::Instruction::Return);
        let v2 = registry.insert(second);
        assert_eq!(registry.module_version_count(module_name), 2);
        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup(module_name).expect("v2 current"),
            &v2
        ));
        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup_old(module_name).expect("v1 old"),
            &v1
        ));

        let mut third = empty_module(module_name);
        third.code.push(crate::loader::Instruction::Return);
        third.code.push(crate::loader::Instruction::Return);
        let v3 = registry.insert(third);
        assert_eq!(registry.module_version_count(module_name), 2);
        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup(module_name).expect("v3 current"),
            &v3
        ));
        assert!(std::sync::Arc::ptr_eq(
            &registry.lookup_old(module_name).expect("v2 old"),
            &v2
        ));
        assert_eq!(v1.generation(), 1);
        assert_eq!(v2.generation(), 2);
        assert_eq!(v3.generation(), 3);
    }

    #[test]
    fn deleted_names_do_not_reuse_generations() {
        let registry = ModuleRegistry::new();
        let v1 = registry.insert(empty_module(crate::atom::Atom::MODULE));
        let v2 = registry.insert(empty_module(crate::atom::Atom::MODULE));
        assert_eq!(v1.generation(), 1);
        assert_eq!(v2.generation(), 2);

        assert!(registry.delete_module(crate::atom::Atom::MODULE));
        assert!(registry.lookup(crate::atom::Atom::MODULE).is_none());
        assert_eq!(registry.module_version_count(crate::atom::Atom::MODULE), 0);

        // The reload CONTINUES the numbering: "older generation" always means
        // older code, even across a delete.
        let v3 = registry.insert(empty_module(crate::atom::Atom::MODULE));
        assert_eq!(
            v3.generation(),
            3,
            "a deleted name's reload must not reuse generation numbers"
        );

        // Delete again, reload again: still monotonic.
        assert!(registry.delete_module(crate::atom::Atom::MODULE));
        let v4 = registry.insert(empty_module(crate::atom::Atom::MODULE));
        assert_eq!(v4.generation(), 4);

        // A second delete of an already-deleted name reports nothing removed.
        assert!(registry.delete_module(crate::atom::Atom::MODULE));
        assert!(!registry.delete_module(crate::atom::Atom::MODULE));
    }

    #[test]
    fn generations_are_tracked_per_module_name() {
        let atoms = AtomTable::new();
        let first_name = atoms.intern("first");
        let second_name = atoms.intern("second");
        let registry = ModuleRegistry::new();

        let first_v1 = registry.insert(empty_module(first_name));
        let second_v1 = registry.insert(empty_module(second_name));
        let first_v2 = registry.insert(empty_module(first_name));

        assert_eq!(first_v1.generation(), 1);
        assert_eq!(second_v1.generation(), 1);
        assert_eq!(first_v2.generation(), 2);
    }

    #[test]
    fn purge_old_requires_no_external_references() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let registry = ModuleRegistry::new();
        registry.insert(empty_module(module_name));
        registry.insert(empty_module(module_name));

        let old_ref = registry.lookup_old(module_name).expect("old version");
        assert!(matches!(
            registry.purge_old(module_name),
            Err(PurgeError::StillReferenced { module, ref_count })
                if module == module_name && ref_count >= 2
        ));
        drop(old_ref);

        assert_eq!(registry.purge_old(module_name), Ok(()));
        assert!(registry.lookup_old(module_name).is_none());
        assert_eq!(registry.module_version_count(module_name), 1);
        assert_eq!(
            registry.purge_old(module_name),
            Err(PurgeError::NoOldVersion {
                module: module_name
            })
        );
    }

    #[test]
    fn registry_lookup_unloaded_module_returns_none() {
        let atoms = AtomTable::new();
        let registry = ModuleRegistry::new();

        assert!(registry.lookup(atoms.intern("missing")).is_none());
    }

    #[test]
    fn lookup_mfa_returns_code_pointer_for_export() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let function = atoms.intern("main");
        let registry = ModuleRegistry::new();
        let mut module = empty_module(module_name);
        module.exports.insert((function, 0), 7);
        registry.insert(module);

        let pointer = registry
            .lookup_mfa(module_name, function, 0)
            .expect("exported function");

        assert_eq!(pointer.label, 7);
        assert_eq!(pointer.module.name, module_name);
        assert_eq!(pointer.generation, 1);
    }

    #[test]
    fn module_resolves_labels_from_index() {
        let atoms = AtomTable::new();
        let mut module = empty_module(atoms.intern("sample"));
        module.code = vec![
            crate::loader::Instruction::Return,
            crate::loader::Instruction::Label { label: 10 },
            crate::loader::Instruction::Return,
            crate::loader::Instruction::Label { label: 20 },
        ];
        module.label_index = label_index(&module.code);

        assert_eq!(module.label_ip(10), Ok(1));
        assert_eq!(module.label_ip(20), Ok(3));
        assert_eq!(
            module.label_ip(30),
            Err(ExecError::InvalidLabel { label: 30 })
        );
    }

    #[test]
    fn module_resolves_exports_to_instruction_indices() {
        let atoms = AtomTable::new();
        let function = atoms.intern("main");
        let mut module = empty_module(atoms.intern("sample"));
        module.code = vec![
            crate::loader::Instruction::Return,
            crate::loader::Instruction::Label { label: 10 },
            crate::loader::Instruction::Return,
            crate::loader::Instruction::Label { label: 20 },
        ];
        module.label_index = label_index(&module.code);
        module.exports.insert((function, 0), 20);

        assert_eq!(module.export_ip(function, 0), Ok(3));
    }

    #[test]
    fn module_reports_undef_for_missing_export() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let function = atoms.intern("missing");
        let module = empty_module(module_name);

        assert!(matches!(
            module.export_ip(function, 0),
            Err(ExecError::Undef {
                module,
                function: undef_function,
                arity: 0,
            }) if module == module_name && undef_function == function
        ));
    }

    #[test]
    fn module_reports_invalid_label_for_export_missing_from_index() {
        let atoms = AtomTable::new();
        let function = atoms.intern("main");
        let mut module = empty_module(atoms.intern("sample"));
        module.exports.insert((function, 0), 99);

        assert_eq!(
            module.export_ip(function, 0),
            Err(ExecError::InvalidLabel { label: 99 })
        );
    }

    #[test]
    fn find_lambda_by_id_resolves_reordered_lambda_tables() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let first_fun = atoms.intern("first@anon");
        let second_fun = atoms.intern("second@anon");
        let first_id = crate::loader::lambda_unique_id(&atoms, module_name, first_fun, 1, 2)
            .expect("first id");
        let second_id = crate::loader::lambda_unique_id(&atoms, module_name, second_fun, 0, 0)
            .expect("second id");

        let mut v1 = empty_module(module_name);
        v1.lambdas = vec![
            LambdaEntry {
                function: first_fun,
                arity: 1,
                label: 10,
                num_free: 2,
                unique_id: first_id,
            },
            LambdaEntry {
                function: second_fun,
                arity: 0,
                label: 20,
                num_free: 0,
                unique_id: second_id,
            },
        ];
        let mut v2 = empty_module(module_name);
        v2.lambdas = vec![
            LambdaEntry {
                function: second_fun,
                arity: 0,
                label: 200,
                num_free: 0,
                unique_id: second_id,
            },
            LambdaEntry {
                function: first_fun,
                arity: 1,
                label: 100,
                num_free: 2,
                unique_id: first_id,
            },
        ];

        assert_eq!(
            v1.find_lambda_by_id(first_id).map(|lambda| lambda.label),
            Some(10)
        );
        assert_eq!(
            v2.find_lambda_by_id(first_id).map(|lambda| lambda.label),
            Some(100)
        );
        assert_eq!(
            v1.find_lambda_by_id(second_id).map(|lambda| lambda.label),
            Some(20)
        );
        assert_eq!(
            v2.find_lambda_by_id(second_id).map(|lambda| lambda.label),
            Some(200)
        );
    }

    #[test]
    fn lookup_mfa_reports_undef_for_missing_targets() {
        let atoms = AtomTable::new();
        let module_name = atoms.intern("sample");
        let function = atoms.intern("main");
        let other = atoms.intern("other");
        let registry = ModuleRegistry::new();
        registry.insert(empty_module(module_name));

        assert!(matches!(
            registry.lookup_mfa(other, function, 0),
            Err(ExecError::Undef {
                module,
                function: undef_function,
                arity: 0,
            }) if module == other && undef_function == function
        ));
        assert!(matches!(
            registry.lookup_mfa(module_name, function, 0),
            Err(ExecError::Undef {
                module,
                function: undef_function,
                arity: 0,
            }) if module == module_name && undef_function == function
        ));
        assert!(matches!(
            registry.lookup_mfa(module_name, function, 1),
            Err(ExecError::Undef {
                module,
                function: undef_function,
                arity: 1,
            }) if module == module_name && undef_function == function
        ));
    }
}