razeri-plugin-api 0.20.0

Extension traits and registries for Razeri plugins
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
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Loading plugins built as shared libraries.
//!
//! A plugin compiled as a shared library (`.so`, `.dylib`, `.dll`) is loaded
//! from a directory at start-up by [`load_plugins_from_dir`]. The library and
//! the razeri that loads it then share Rust types: the dialect traits, the
//! registry builder, and every value passed between them. Rust lays those
//! types out the same way on both sides only when both sides are the same
//! build — the same compiler, and the same source of `razeri-plugin-api` and
//! `razeri-plugin-contract`. Anything else reads memory the wrong way, and the
//! process crashes rather than failing.
//!
//! So a plugin says how it was built, in a [`BuildDeclaration`], and says it
//! through a door every compiler reads alike: a C function returning a
//! `#[repr(C)]` record of C strings and one number. The loader reads that
//! first. A library whose declaration differs from this razeri's own in any
//! part, or that declares nothing, is refused with a [`PluginRefusal`] that
//! names what it was built with and what it needs, and none of its Rust code
//! is run.
//!
//! A plugin exports its declaration and its registration with one line,
//! [`export_plugin!`](crate::export_plugin). The same line lets the crate be
//! linked into a razeri you build yourself instead, which needs no match at
//! all because there is only one build.
//!
//! ## What else the loader does
//!
//! - **Panics stay in the plugin**: registration runs inside `catch_unwind`.
//! - **Libraries stay loaded**: a library whose registration ran is never
//!   unloaded, because what it registered lives as long as the process. A
//!   refused library is unloaded at once; nothing of it was kept.
//! - **An open directory is named**: on Unix, a plugin directory anyone can
//!   write to is reported in the log.

use crate::builder::PluginRegistryBuilder;
use std::fmt;

/// Where a plugin author reads how to link a dialect into a razeri they build
/// — the other way to run a plugin, and the one every refusal offers. It names
/// the page inside the book each release carries, because the book has no
/// public address.
pub const LINKING_GUIDE: &str = "plugins/linking-a-dialect.html in the razeri book";

/// Symbol name for the plugin registration function.
///
/// The function signature is [`RegisterPluginFn`]. It is called only after
/// the library's [`BuildDeclaration`] matches this razeri's.
pub const PLUGIN_REGISTER_SYMBOL: &str = "razeri_plugin_register_v1";

/// Symbol name for the function that says how a plugin was built.
///
/// The function signature is [`BuildDeclarationFn`]. A library without it is
/// refused.
pub const PLUGIN_BUILD_SYMBOL: &str = "razeri_plugin_build";

/// Type signature for the plugin registration entry point.
///
/// # Safety
///
/// The `builder` pointer must be valid and outlive the call, and the library
/// must have been built exactly as the caller was.
pub type RegisterPluginFn = unsafe fn(&mut PluginRegistryBuilder);

/// Type signature for the function that says how a plugin was built.
///
/// It uses the C calling convention and returns a pointer to a `#[repr(C)]`
/// record, so a library built by any compiler answers it the same way.
pub type BuildDeclarationFn = extern "C" fn() -> *const export::ExportedBuildDeclaration;

/// How a plugin was built: the compiler, and the two plugin crates it was
/// compiled against.
///
/// A plugin loaded from a directory is accepted only when its declaration is
/// equal to [`BuildDeclaration::this_build`] in every part.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildDeclaration {
    /// The compiler, as `rustc -V` names it, such as
    /// `rustc 1.93.1 (01f6ddf75 2026-02-11)`.
    pub compiler: String,
    /// The version of `razeri-plugin-api`.
    pub plugin_api: String,
    /// The version of `razeri-plugin-contract`.
    pub contract: String,
    /// A fingerprint of the source of both crates. Two builds carrying the
    /// same version numbers over different source have different
    /// fingerprints.
    pub source: u64,
}

/// One part of a [`BuildDeclaration`], named so a refusal can say which parts
/// differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuildPart {
    /// The compiler.
    Compiler,
    /// The version of `razeri-plugin-api`.
    PluginApi,
    /// The version of `razeri-plugin-contract`.
    Contract,
    /// The source of the two crates, when their versions agree.
    Source,
}

impl BuildDeclaration {
    /// How this build of `razeri-plugin-api` was made — the declaration a host
    /// compares plugins against, and the one [`export_plugin!`](crate::export_plugin)
    /// exports from a plugin.
    #[must_use]
    pub fn this_build() -> Self {
        Self {
            compiler: export::COMPILER.to_string_lossy().into_owned(),
            plugin_api: export::PLUGIN_API.to_string_lossy().into_owned(),
            contract: export::CONTRACT.to_string_lossy().into_owned(),
            source: export::SOURCE,
        }
    }

    /// The parts in which `self` differs from `needs`, in the order a reader
    /// meets them. Empty when the two are the same build.
    #[must_use]
    pub fn differences(&self, needs: &Self) -> Vec<BuildPart> {
        let mut parts = Vec::new();
        if self.compiler != needs.compiler {
            parts.push(BuildPart::Compiler);
        }
        if self.plugin_api != needs.plugin_api {
            parts.push(BuildPart::PluginApi);
        }
        if self.contract != needs.contract {
            parts.push(BuildPart::Contract);
        }
        // Another version is another source; the fingerprint is news only
        // when both versions agree.
        let versions_agree = self.plugin_api == needs.plugin_api && self.contract == needs.contract;
        if versions_agree && self.source != needs.source {
            parts.push(BuildPart::Source);
        }
        parts
    }
}

impl fmt::Display for BuildDeclaration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} against razeri-plugin-api {} and razeri-plugin-contract {} (source {:016x})",
            self.compiler, self.plugin_api, self.contract, self.source
        )
    }
}

/// Why the loader would not load a plugin library.
///
/// A refusal is always this razeri's. Its message says what to rebuild the
/// plugin with, from [`BuildDeclaration::this_build`], unless the plugin was
/// built against newer plugin crates than this razeri: then it says to run the
/// razeri the plugin was built for, and names both builds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginRefusal {
    /// The library does not say how it was built: it has no
    /// [`PLUGIN_BUILD_SYMBOL`]. Every plugin exported without
    /// [`export_plugin!`](crate::export_plugin) is one of these.
    Undeclared,
    /// The library says how it was built in a form this razeri cannot read.
    Unreadable {
        /// The form number the library declared.
        form: u32,
    },
    /// The library was built differently from this razeri.
    BuiltDifferently {
        /// How the library was built.
        built_with: BuildDeclaration,
    },
}

impl PluginRefusal {
    /// The refusal a plugin declaring `built_with` receives from this razeri,
    /// or `None` when it was built exactly as this razeri was.
    #[must_use]
    pub fn for_declaration(built_with: BuildDeclaration) -> Option<Self> {
        if built_with.differences(&BuildDeclaration::this_build()).is_empty() {
            None
        } else {
            Some(Self::BuiltDifferently { built_with })
        }
    }
}

/// Which side of a refusal is the older build: the plugin, or the razeri
/// loading it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OlderSide {
    /// The plugin was built against older plugin crates than this razeri.
    Plugin,
    /// This razeri was built against older plugin crates than the plugin.
    Razeri,
}

/// **Which side is older**, read from the two crate versions: the plugin
/// where neither of its versions is newer than this razeri's and one is
/// older, this razeri where the reverse holds. `None` where the versions
/// agree, where one is newer and the other older, or where either is not a
/// version this can read: no side is plainly the older one then.
fn older_side(built_with: &BuildDeclaration, needs: &BuildDeclaration) -> Option<OlderSide> {
    let pairs =
        [(&built_with.plugin_api, &needs.plugin_api), (&built_with.contract, &needs.contract)];
    let mut orders = Vec::new();
    for (plugin, razeri) in pairs {
        orders.push(release_numbers(plugin)?.cmp(&release_numbers(razeri)?));
    }
    let any = |order| orders.contains(&order);
    match (any(std::cmp::Ordering::Less), any(std::cmp::Ordering::Greater)) {
        (true, false) => Some(OlderSide::Plugin),
        (false, true) => Some(OlderSide::Razeri),
        _ => None,
    }
}

/// `0.18.1` as `[0, 18, 1]`; a pre-release or build suffix (`-pre.1`,
/// `+local`) is left off. `None` for anything that is not dotted numbers.
fn release_numbers(version: &str) -> Option<Vec<u64>> {
    let release = version.split(['-', '+']).next()?;
    release.split('.').map(|part| part.parse().ok()).collect()
}

impl fmt::Display for PluginRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let needs = BuildDeclaration::this_build();
        let older = match self {
            Self::BuiltDifferently { built_with } => older_side(built_with, &needs),
            Self::Undeclared | Self::Unreadable { .. } => None,
        };

        // **A plugin newer than this razeri is not told to rebuild**
        // (`fr-1029-72`): rebuilding would move a current plugin back to an
        // older contract. The cure is the razeri it was built for.
        if let (Some(OlderSide::Razeri), Self::BuiltDifferently { built_with }) = (older, self) {
            return write!(
                f,
                "Run the razeri this plugin was built for, or link it into a razeri you build \
                 yourself ({LINKING_GUIDE}). This razeri is older than the plugin: it was built \
                 against razeri-plugin-api {} and razeri-plugin-contract {}, and the plugin \
                 against razeri-plugin-api {} and razeri-plugin-contract {}. A plugin loaded from \
                 a directory must be built exactly as the razeri that loads it.",
                needs.plugin_api, needs.contract, built_with.plugin_api, built_with.contract
            );
        }

        // What to do, first.
        let only_the_source_differs = matches!(
            self,
            Self::BuiltDifferently { built_with }
                if built_with.differences(&needs) == [BuildPart::Source]
        );
        if only_the_source_differs {
            write!(
                f,
                "Rebuild it with {} against the same source of razeri-plugin-api {} and \
                 razeri-plugin-contract {} this razeri was built from (source {:016x})",
                needs.compiler, needs.plugin_api, needs.contract, needs.source
            )?;
        } else {
            write!(
                f,
                "Rebuild it with {} against razeri-plugin-api {} and razeri-plugin-contract {}",
                needs.compiler, needs.plugin_api, needs.contract
            )?;
        }
        if matches!(self, Self::Undeclared) {
            f.write_str(", exporting it with razeri_plugin_api::export_plugin!")?;
        }
        write!(f, ", or link it into a razeri you build yourself ({LINKING_GUIDE}). ")?;

        // Then why.
        match self {
            Self::Undeclared => f.write_str("It does not say how it was built")?,
            Self::Unreadable { form, .. } => write!(
                f,
                "It says how it was built in a form this razeri does not read (form {form})"
            )?,
            Self::BuiltDifferently { built_with } => {
                if older == Some(OlderSide::Plugin) {
                    f.write_str("The plugin is older than this razeri: ")?;
                    write!(f, "it was built {}", built_differently(built_with, &needs))?;
                } else {
                    write!(f, "It was built {}", built_differently(built_with, &needs))?;
                }
            }
        }
        f.write_str(
            ", and a plugin loaded from a directory must be built exactly as the razeri that \
             loads it.",
        )
    }
}

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

/// The parts of `built_with` that differ from `needs`, as the end of the
/// sentence "It was built …".
fn built_differently(built_with: &BuildDeclaration, needs: &BuildDeclaration) -> String {
    let parts = built_with.differences(needs);
    let mut clauses = Vec::new();
    if parts.contains(&BuildPart::Compiler) {
        clauses.push(format!("with {}", built_with.compiler));
    }
    let mut against = Vec::new();
    if parts.contains(&BuildPart::PluginApi) {
        against.push(format!("razeri-plugin-api {}", built_with.plugin_api));
    }
    if parts.contains(&BuildPart::Contract) {
        against.push(format!("razeri-plugin-contract {}", built_with.contract));
    }
    if !against.is_empty() {
        clauses.push(format!("against {}", against.join(" and ")));
    }
    if parts.contains(&BuildPart::Source) {
        clauses.push(format!(
            "against another source of those two versions (source {:016x})",
            built_with.source
        ));
    }
    clauses.join(" ")
}

/// Outcome of loading a single plugin library.
#[derive(Debug)]
pub enum PluginLoadResult {
    /// Plugin loaded and registered successfully.
    Loaded {
        /// Display name (file stem).
        name: String,
        /// Path to the shared library.
        path: std::path::PathBuf,
    },
    /// The library was found and not loaded, because it was not built as
    /// this razeri was. None of its Rust code ran.
    Refused {
        /// Path to the shared library.
        path: std::path::PathBuf,
        /// Why it was refused.
        refusal: PluginRefusal,
    },
    /// Library could not be loaded or registration failed.
    Failed {
        /// Path to the shared library.
        path: std::path::PathBuf,
        /// Error description.
        error: String,
    },
}

/// Read a declaration a library exported.
///
/// # Errors
///
/// A [`PluginRefusal::Unreadable`] when the record is in a form this razeri
/// does not read, or a string in it is missing.
///
/// # Safety
///
/// `record` must be null or point to a live [`export::ExportedBuildDeclaration`]
/// whose string pointers are null or point to NUL-terminated strings.
pub unsafe fn read_declaration(
    record: *const export::ExportedBuildDeclaration,
) -> Result<BuildDeclaration, PluginRefusal> {
    let unreadable = |form| PluginRefusal::Unreadable { form };
    if record.is_null() {
        return Err(unreadable(0));
    }
    // The form comes first and is read on its own: a record in another form
    // may be laid out differently after it.
    // SAFETY: the caller promises a live record, which begins with its form.
    let form = unsafe { record.cast::<u32>().read() };
    if form != export::FORM {
        return Err(unreadable(form));
    }
    // SAFETY: a live record in the form this crate writes.
    let record = unsafe { &*record };
    // SAFETY: the caller promises each string pointer is null or NUL-terminated.
    let text = |part: *const std::ffi::c_char| {
        (!part.is_null())
            .then(|| unsafe { std::ffi::CStr::from_ptr(part) }.to_string_lossy().into_owned())
    };
    match (text(record.compiler), text(record.plugin_api), text(record.contract)) {
        (Some(compiler), Some(plugin_api), Some(contract)) => {
            Ok(BuildDeclaration { compiler, plugin_api, contract, source: record.source })
        }
        _ => Err(unreadable(form)),
    }
}

/// What [`export_plugin!`](crate::export_plugin) expands to reaches through
/// here. Not for use by hand.
#[doc(hidden)]
pub mod export {
    use std::ffi::{CStr, c_char};

    pub use inventory;

    /// The form of [`ExportedBuildDeclaration`] this crate writes and reads.
    /// A record declaring any other form is refused as unreadable.
    pub const FORM: u32 = 1;

    /// A [`BuildDeclaration`](super::BuildDeclaration) as it crosses the
    /// library boundary: C strings and one number, laid out as C lays them
    /// out, with the form first so a reader knows how to read the rest.
    /// A later form may add fields after these; it never moves one.
    #[repr(C)]
    pub struct ExportedBuildDeclaration {
        /// Which form of this record follows.
        pub form: u32,
        /// The compiler, NUL-terminated.
        pub compiler: *const c_char,
        /// The version of `razeri-plugin-api`, NUL-terminated.
        pub plugin_api: *const c_char,
        /// The version of `razeri-plugin-contract`, NUL-terminated.
        pub contract: *const c_char,
        /// The fingerprint of both crates' source.
        pub source: u64,
    }

    // SAFETY: every pointer in the record points to a string that lives for
    // the life of the program and is never written.
    unsafe impl Sync for ExportedBuildDeclaration {}

    /// The compiler this crate was built with, as `rustc -V` names it. The
    /// build script asks the compiler cargo is building with.
    pub const COMPILER: &CStr = c_str(concat!(env!("RAZERI_PLUGIN_API_COMPILER"), "\0"));

    /// This crate's version.
    pub const PLUGIN_API: &CStr = c_str(concat!(env!("CARGO_PKG_VERSION"), "\0"));

    /// The version of `razeri-plugin-contract` this crate was built against.
    pub const CONTRACT: &CStr = c_str_from_bytes(&CONTRACT_WITH_NUL);

    /// The fingerprint of both crates' source: the contract's, then this
    /// crate's, folded into one number.
    pub const SOURCE: u64 = fold(razeri_plugin_contract::SOURCE_FINGERPRINT, API_SOURCE);

    /// This crate's own source fingerprint, from its build script.
    const API_SOURCE: u64 = match u64::from_str_radix(env!("RAZERI_PLUGIN_API_SOURCE"), 16) {
        Ok(fingerprint) => fingerprint,
        Err(_) => panic!("the build script writes the fingerprint in hexadecimal"),
    };

    /// The contract's version with the NUL a C string ends in.
    const CONTRACT_WITH_NUL: [u8; razeri_plugin_contract::VERSION.len() + 1] =
        with_nul(razeri_plugin_contract::VERSION);

    const fn with_nul<const N: usize>(text: &str) -> [u8; N] {
        let bytes = text.as_bytes();
        let mut out = [0; N];
        let mut i = 0;
        while i < bytes.len() {
            out[i] = bytes[i];
            i += 1;
        }
        out
    }

    const fn c_str(text: &'static str) -> &'static CStr {
        c_str_from_bytes(text.as_bytes())
    }

    const fn c_str_from_bytes(bytes: &'static [u8]) -> &'static CStr {
        match CStr::from_bytes_with_nul(bytes) {
            Ok(text) => text,
            Err(_) => panic!("a part of the build declaration holds a NUL"),
        }
    }

    /// FNV-1a over the two fingerprints' bytes, the contract's first.
    const fn fold(contract: u64, api: u64) -> u64 {
        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
        let bytes = [contract.to_le_bytes(), api.to_le_bytes()];
        let mut half = 0;
        while half < 2 {
            let mut i = 0;
            while i < 8 {
                hash ^= bytes[half][i] as u64;
                hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
                i += 1;
            }
            half += 1;
        }
        hash
    }

    /// This build's declaration, the record a plugin exports.
    pub static THIS_BUILD: ExportedBuildDeclaration = ExportedBuildDeclaration {
        form: FORM,
        compiler: COMPILER.as_ptr(),
        plugin_api: PLUGIN_API.as_ptr(),
        contract: CONTRACT.as_ptr(),
        source: SOURCE,
    };
}

// ── Feature-gated loading implementation ────────────────────────────

// Dynamic library loading (`libloading`/dlopen) is native-only: there is no
// shared-library loading on wasm32-unknown-unknown, and `libloading` is not a
// dependency of the wasm build. The `dynamic` feature is a no-op on wasm.
#[cfg(all(feature = "dynamic", not(target_arch = "wasm32")))]
mod loader {
    use super::{
        BuildDeclarationFn, PLUGIN_BUILD_SYMBOL, PLUGIN_REGISTER_SYMBOL, PluginLoadResult,
        PluginRefusal, PluginRegistryBuilder, RegisterPluginFn, read_declaration,
    };
    use std::path::Path;

    /// Load all plugin shared libraries from `dir` and register them
    /// with `builder`.
    ///
    /// Scans `dir` for files with the platform-appropriate extension
    /// (`.so`, `.dylib`, `.dll`). Each library is loaded, its build
    /// declaration is compared with this razeri's, and its registration
    /// function is called only when the two match.
    ///
    /// Returns one [`PluginLoadResult`] per library file found.
    pub fn load_plugins_from_dir(
        dir: &Path,
        builder: &mut PluginRegistryBuilder,
    ) -> Vec<PluginLoadResult> {
        warn_if_world_writable(dir);

        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(e) => {
                tracing::debug!("Cannot read plugin directory {}: {e}", dir.display());
                return Vec::new();
            }
        };

        let mut results = Vec::new();

        for entry in entries.flatten() {
            let path = entry.path();
            if !is_shared_library(&path) {
                continue;
            }
            results.push(load_single_plugin(&path, builder));
        }

        results
    }

    /// Load a single shared library plugin.
    fn load_single_plugin(path: &Path, builder: &mut PluginRegistryBuilder) -> PluginLoadResult {
        let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown").to_string();

        // SAFETY: opening a library runs its initialisers, which is the one
        // thing done before its declaration is read. A file in a plugin
        // directory is trusted that far and no further.
        let lib = match unsafe { libloading::Library::new(path) } {
            Ok(l) => l,
            Err(e) => {
                return PluginLoadResult::Failed {
                    path: path.to_path_buf(),
                    error: format!("Failed to load library: {e}"),
                };
            }
        };

        // How the library was built, read through its C door. Nothing else
        // in it is called until this matches this razeri's own build.
        // SAFETY: the symbol, when present, has the C signature every
        // compiler agrees on, and returns a record `read_declaration` reads
        // through its C layout.
        let declared = unsafe {
            match lib.get::<BuildDeclarationFn>(PLUGIN_BUILD_SYMBOL.as_bytes()) {
                Ok(declare) => read_declaration(declare()),
                Err(_) => Err(PluginRefusal::Undeclared),
            }
        };
        let refusal = match declared {
            Ok(built_with) => PluginRefusal::for_declaration(built_with),
            Err(refusal) => Some(refusal),
        };
        if let Some(refusal) = refusal {
            // Nothing the library holds was handed to razeri, so it can go.
            drop(lib);
            return PluginLoadResult::Refused { path: path.to_path_buf(), refusal };
        }

        // SAFETY: the library was built exactly as this razeri was, so the
        // registration's Rust signature means the same thing on both sides.
        let register_fn = unsafe {
            match lib.get::<RegisterPluginFn>(PLUGIN_REGISTER_SYMBOL.as_bytes()) {
                Ok(f) => *f,
                Err(e) => {
                    return PluginLoadResult::Failed {
                        path: path.to_path_buf(),
                        error: format!("Missing symbol '{PLUGIN_REGISTER_SYMBOL}': {e}"),
                    };
                }
            }
        };

        // Call registration wrapped in catch_unwind for safety.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // SAFETY: the builder outlives the call, and the build matched.
            unsafe { register_fn(builder) };
        }));

        // Once the registration has run, the library stays loaded for the
        // life of the process, whatever it did: anything it registered before
        // a panic points into it, and unloading it would leave those behind.
        std::mem::forget(lib);
        match result {
            Ok(()) => {
                tracing::info!("Loaded plugin '{name}' from {}", path.display());
                PluginLoadResult::Loaded { name, path: path.to_path_buf() }
            }
            Err(_) => PluginLoadResult::Failed {
                path: path.to_path_buf(),
                error: "Plugin registration panicked".to_string(),
            },
        }
    }

    /// Check if a path has a shared-library extension.
    fn is_shared_library(path: &Path) -> bool {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        matches!(ext, "so" | "dylib" | "dll")
    }

    /// Emit a warning if the directory is world-writable (Unix only).
    #[cfg(unix)]
    fn warn_if_world_writable(dir: &Path) {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(dir) {
            let mode = meta.permissions().mode();
            if mode & 0o002 != 0 {
                tracing::warn!(
                    "Plugin directory {} is world-writable — this is a security risk",
                    dir.display()
                );
            }
        }
    }

    #[cfg(not(unix))]
    fn warn_if_world_writable(_dir: &Path) {
        // No-op on non-Unix platforms.
    }
}

#[cfg(all(feature = "dynamic", not(target_arch = "wasm32")))]
pub use loader::load_plugins_from_dir;

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::export::{ExportedBuildDeclaration, FORM, THIS_BUILD};
    use super::*;

    /// A declaration that differs from this build only where the test says.
    fn this_build_but(change: impl FnOnce(&mut BuildDeclaration)) -> BuildDeclaration {
        let mut declared = BuildDeclaration::this_build();
        change(&mut declared);
        declared
    }

    /// The message a plugin declaring `declared` is refused with.
    fn refusal_text(declared: BuildDeclaration) -> String {
        PluginRefusal::for_declaration(declared)
            .expect("a declaration that differs is refused")
            .to_string()
    }

    #[test]
    fn symbol_names_are_stable() {
        assert_eq!(PLUGIN_REGISTER_SYMBOL, "razeri_plugin_register_v1");
        assert_eq!(PLUGIN_BUILD_SYMBOL, "razeri_plugin_build");
    }

    /// **This build names its compiler, both crates and their source.** A
    /// declaration with an empty part would match any other with the same
    /// empty part, which is the silence the declaration exists to end.
    #[test]
    fn this_build_names_its_compiler_both_crate_versions_and_its_source() {
        let this = BuildDeclaration::this_build();
        assert!(this.compiler.starts_with("rustc "), "{this:?}");
        assert_eq!(this.plugin_api, env!("CARGO_PKG_VERSION"));
        assert_eq!(this.contract, razeri_plugin_contract::VERSION);
        assert_ne!(this.source, 0, "{this:?}");
    }

    /// **What a plugin exports reads back, through its C layout, as the build
    /// that made it.**
    #[test]
    fn the_exported_declaration_reads_back_as_this_build() {
        // SAFETY: THIS_BUILD is a live record of static C strings.
        let read = unsafe { read_declaration(&raw const THIS_BUILD) };
        assert_eq!(read, Ok(BuildDeclaration::this_build()));
    }

    #[test]
    fn a_declaration_identical_to_this_build_is_accepted() {
        assert_eq!(PluginRefusal::for_declaration(BuildDeclaration::this_build()), None);
        let this = BuildDeclaration::this_build();
        assert!(this.differences(&this).is_empty());
    }

    /// **Another compiler is refused, and the refusal names both.** A newer
    /// compiler over the same source is enough to crash a process that calls
    /// into the library, so the compiler is compared on its own.
    #[test]
    fn a_different_compiler_is_refused_naming_the_compiler() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| d.compiler = "rustc 1.0.0 (elsewhere)".to_string());
        assert_eq!(declared.differences(&needs), vec![BuildPart::Compiler]);

        let text = refusal_text(declared);
        assert!(text.contains("rustc 1.0.0 (elsewhere)"), "{text}");
        assert!(text.contains(&needs.compiler), "{text}");
    }

    #[test]
    fn a_different_plugin_api_version_is_refused_naming_it() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| d.plugin_api = "0.0.1".to_string());
        assert_eq!(declared.differences(&needs), vec![BuildPart::PluginApi]);

        let text = refusal_text(declared);
        assert!(text.contains("razeri-plugin-api 0.0.1"), "{text}");
        assert!(text.contains(&format!("razeri-plugin-api {}", needs.plugin_api)), "{text}");
    }

    #[test]
    fn a_different_contract_version_is_refused_naming_the_contract() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| d.contract = "0.0.2".to_string());
        assert_eq!(declared.differences(&needs), vec![BuildPart::Contract]);

        let text = refusal_text(declared);
        assert!(text.contains("razeri-plugin-contract 0.0.2"), "{text}");
        assert!(text.contains(&format!("razeri-plugin-contract {}", needs.contract)), "{text}");
    }

    /// **The same version numbers over different source are refused.** A
    /// crate's version moves when it is published, not when its source does,
    /// so a plugin built against the published crates and a razeri built from
    /// newer source can carry the same numbers and different types.
    #[test]
    fn the_same_versions_over_different_source_are_refused() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| d.source = needs.source ^ 1);
        assert_eq!(declared.differences(&needs), vec![BuildPart::Source]);

        let text = refusal_text(declared);
        assert!(text.contains(&format!("{:016x}", needs.source)), "{text}");
        assert!(text.contains(&format!("{:016x}", needs.source ^ 1)), "{text}");
    }

    /// Every part that differs is named, in the order a reader meets them.
    #[test]
    fn every_part_that_differs_is_named() {
        let needs = BuildDeclaration::this_build();
        let declared = BuildDeclaration {
            compiler: "rustc 1.0.0 (elsewhere)".to_string(),
            plugin_api: "0.0.1".to_string(),
            contract: "0.0.2".to_string(),
            source: needs.source ^ 1,
        };
        assert_eq!(
            declared.differences(&needs),
            vec![BuildPart::Compiler, BuildPart::PluginApi, BuildPart::Contract]
        );
    }

    /// **The fix comes first.** Every refusal opens with what to do, names
    /// both ways to do it, and never names a type or a symbol the reader did
    /// not write.
    #[test]
    fn every_refusal_says_what_to_do_first_and_names_both_ways() {
        let needs = BuildDeclaration::this_build();
        let refusals = [
            PluginRefusal::Undeclared,
            PluginRefusal::Unreadable { form: FORM + 1 },
            PluginRefusal::for_declaration(this_build_but(|d| d.compiler = "rustc 1.0.0".into()))
                .expect("refused"),
        ];
        for refusal in refusals {
            let text = refusal.to_string();
            assert!(text.starts_with("Rebuild it "), "the fix is not first: {text}");
            assert!(text.contains(&needs.compiler), "{text}");
            assert!(text.contains(&format!("razeri-plugin-api {}", needs.plugin_api)), "{text}");
            assert!(text.contains(&format!("razeri-plugin-contract {}", needs.contract)), "{text}");
            assert!(text.contains("link it into a razeri you build"), "{text}");
            assert!(text.contains(LINKING_GUIDE), "{text}");
            for internal in ["BuildDeclaration", "PluginRefusal", "razeri_plugin_build"] {
                assert!(!text.contains(internal), "names {internal}: {text}");
            }
        }
    }

    /// `0.18.2` moved `steps` minor versions: `1` is `0.19.0`, `-1` is
    /// `0.17.0`.
    fn minor_moved(version: &str, steps: i64) -> String {
        let mut parts = version.split('.').map(|part| part.parse::<i64>().expect("a number"));
        let (major, minor) = (parts.next().expect("major"), parts.next().expect("minor"));
        format!("{major}.{}.0", minor + steps)
    }

    /// **A plugin newer than this razeri is told to run the razeri it was
    /// built for**, not to rebuild against an older contract (`fr-1029-72`).
    /// Measured on `pre.11`: a template built against contract 0.17.1, loaded
    /// by a `pre.10` razeri, was told to rebuild against 0.16.0 — a downgrade
    /// of a current plugin to an old contract.
    #[test]
    fn a_plugin_newer_than_this_razeri_is_told_to_run_the_razeri_it_was_built_for() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| {
            d.plugin_api = minor_moved(&needs.plugin_api, 1);
            d.contract = minor_moved(&needs.contract, 1);
        });
        let text = refusal_text(declared.clone());
        assert!(text.starts_with("Run the razeri this plugin was built for"), "{text}");
        assert!(text.contains("This razeri is older than the plugin"), "{text}");
        assert!(!text.contains("Rebuild it"), "no downgrade is offered: {text}");
        for version in
            [&needs.plugin_api, &needs.contract, &declared.plugin_api, &declared.contract]
        {
            assert!(text.contains(version.as_str()), "names {version}: {text}");
        }
        assert!(text.contains(LINKING_GUIDE), "{text}");

        // Newer on one part and the same on the other is still newer.
        let text = refusal_text(this_build_but(|d| d.contract = minor_moved(&needs.contract, 1)));
        assert!(text.starts_with("Run the razeri this plugin was built for"), "{text}");
    }

    /// **A plugin older than this razeri is told to rebuild**, and told it is
    /// the older side.
    #[test]
    fn a_plugin_older_than_this_razeri_is_told_to_rebuild_and_that_it_is_older() {
        let needs = BuildDeclaration::this_build();
        let declared = this_build_but(|d| {
            d.plugin_api = minor_moved(&needs.plugin_api, -1);
            d.contract = minor_moved(&needs.contract, -1);
        });
        let text = refusal_text(declared);
        assert!(text.starts_with("Rebuild it with"), "{text}");
        assert!(text.contains("The plugin is older than this razeri"), "{text}");

        // One part newer and one older says neither is older, and keeps the
        // rebuild: there is no razeri the plugin was built for to point at.
        let mixed = refusal_text(this_build_but(|d| {
            d.plugin_api = minor_moved(&needs.plugin_api, 1);
            d.contract = minor_moved(&needs.contract, -1);
        }));
        assert!(mixed.starts_with("Rebuild it with"), "{mixed}");
        assert!(!mixed.contains("older than"), "{mixed}");
    }

    #[test]
    fn a_plugin_that_declares_nothing_is_told_so_and_how_to_export_one() {
        let text = PluginRefusal::Undeclared.to_string();
        assert!(text.contains("does not say how it was built"), "{text}");
        assert!(text.contains("export_plugin!"), "{text}");
    }

    /// **A form this razeri does not read is refused, not guessed at.**
    #[test]
    fn a_declaration_in_a_form_this_razeri_does_not_read_is_refused() {
        let later = ExportedBuildDeclaration {
            form: FORM + 1,
            compiler: std::ptr::null(),
            plugin_api: std::ptr::null(),
            contract: std::ptr::null(),
            source: 0,
        };
        // SAFETY: a live record; its null strings are never read for an
        // unknown form.
        let read = unsafe { read_declaration(&raw const later) };
        assert_eq!(read, Err(PluginRefusal::Unreadable { form: FORM + 1 }));
        let text = read.unwrap_err().to_string();
        assert!(text.contains(&format!("form {}", FORM + 1)), "{text}");
    }

    #[test]
    fn a_record_with_a_missing_part_is_refused_as_unreadable() {
        let broken = ExportedBuildDeclaration {
            form: FORM,
            compiler: std::ptr::null(),
            plugin_api: c"0.0.1".as_ptr(),
            contract: c"0.0.2".as_ptr(),
            source: 1,
        };
        // SAFETY: a live record whose strings are null or static.
        let read = unsafe { read_declaration(&raw const broken) };
        assert!(matches!(read, Err(PluginRefusal::Unreadable { form: FORM, .. })), "{read:?}");
    }

    #[test]
    fn no_record_at_all_is_refused_as_unreadable() {
        // SAFETY: null is allowed and never dereferenced.
        let read = unsafe { read_declaration(std::ptr::null()) };
        assert!(matches!(read, Err(PluginRefusal::Unreadable { .. })), "{read:?}");
    }

    #[cfg(all(feature = "dynamic", not(target_arch = "wasm32")))]
    mod dynamic_tests {
        use super::*;
        use std::path::Path;

        #[test]
        fn load_from_nonexistent_dir_returns_empty() {
            let mut builder = PluginRegistryBuilder::new();
            let results = load_plugins_from_dir(
                Path::new("/tmp/razeri-nonexistent-plugin-dir-12345"),
                &mut builder,
            );
            assert!(results.is_empty());
        }

        #[test]
        fn load_from_empty_dir_returns_empty() {
            let dir = tempfile::tempdir().unwrap();
            let mut builder = PluginRegistryBuilder::new();
            let results = load_plugins_from_dir(dir.path(), &mut builder);
            assert!(results.is_empty());
        }

        #[test]
        fn load_skips_non_library_files() {
            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("notes.txt"), "hello").unwrap();
            std::fs::write(dir.path().join("data.json"), "{}").unwrap();

            let mut builder = PluginRegistryBuilder::new();
            let results = load_plugins_from_dir(dir.path(), &mut builder);
            assert!(results.is_empty());
        }

        #[test]
        fn load_invalid_so_returns_failed() {
            let dir = tempfile::tempdir().unwrap();
            let lib_name = if cfg!(target_os = "macos") {
                "bad.dylib"
            } else if cfg!(target_os = "windows") {
                "bad.dll"
            } else {
                "bad.so"
            };
            std::fs::write(dir.path().join(lib_name), "not a real library").unwrap();

            let mut builder = PluginRegistryBuilder::new();
            let results = load_plugins_from_dir(dir.path(), &mut builder);
            assert_eq!(results.len(), 1);
            assert!(
                matches!(&results[0], PluginLoadResult::Failed { error, .. } if error.contains("Failed to load library"))
            );
        }
    }
}