perl-lsp 0.3.0

A Perl LSP server built on tree-sitter-perl and tower-lsp
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
//! Rhai-scripted plugin support.
//!
//! A `RhaiPlugin` wraps a compiled Rhai script that exposes top-level
//! functions: `id()`, `triggers()`, `on_function_call(ctx)`, `on_method_call(ctx)`,
//! and/or `on_use(ctx)`. Each callback returns an array of emission object-maps
//! that convert back into strongly-typed `EmitAction` values.
//!
//! All context and emission data crosses the script boundary as Rhai `Dynamic`
//! — we never hand out mutable references to the builder. This keeps scripts
//! pure and lets us test them as functions from input to action list.

use std::sync::Arc;

use rhai::{
    serde::{from_dynamic, to_dynamic},
    Array, Dynamic, Engine, AST,
};

use crate::file_analysis::{HashKeyOwner, InferredType, Span};
use tree_sitter::Point;

use super::{
    CallContext, CompletionQueryContext, EmitAction, FrameworkPlugin, PluginCompletionAnswer,
    PluginSigHelpAnswer, SigHelpQueryContext, Trigger, TypeOverride, UseContext,
};

/// An engine built with our helpers and type registrations. Engines are
/// cheap to reuse; scripts share one instance across all callbacks.
pub fn make_engine() -> Engine {
    let mut engine = Engine::new();
    engine.set_max_expr_depths(64, 64);
    // Kill switch: a runaway Rhai script (infinite loop, stuck on a bad
    // input) would otherwise hang the LSP build thread indefinitely.
    // 1M operations is comfortably more than any sensible plugin hook
    // needs (emit hooks top out in the hundreds; query hooks lower) and
    // low enough to bail in well under a second on modern hardware.
    // Override via `PERL_LSP_RHAI_MAX_OPS` for debugging heavy plugins.
    let max_ops: u64 = std::env::var("PERL_LSP_RHAI_MAX_OPS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(1_000_000);
    engine.set_max_operations(max_ops);

    // Shorthand constructors for `HashKeyOwner` — Rhai scripts avoid writing
    // enum discriminants by using these helper functions.
    engine.register_fn("owner_sub", |package: String, name: String| {
        let pkg = if package.is_empty() { None } else { Some(package) };
        let owner = HashKeyOwner::Sub { package: pkg, name };
        to_dynamic(owner).unwrap_or(Dynamic::UNIT)
    });
    engine.register_fn("owner_sub_unscoped", |name: String| {
        let owner = HashKeyOwner::Sub { package: None, name };
        to_dynamic(owner).unwrap_or(Dynamic::UNIT)
    });
    engine.register_fn("owner_class", |class: String| {
        let owner = HashKeyOwner::Class(class);
        to_dynamic(owner).unwrap_or(Dynamic::UNIT)
    });

    // `InferredType` convenience constructors — scripts can say
    // `type_class("Foo")` instead of nesting enum variants manually.
    engine.register_fn("type_string", || to_dynamic(InferredType::String).unwrap());
    engine.register_fn("type_numeric", || to_dynamic(InferredType::Numeric).unwrap());
    engine.register_fn("type_hashref", || to_dynamic(InferredType::HashRef).unwrap());
    engine.register_fn("type_arrayref", || to_dynamic(InferredType::ArrayRef).unwrap());
    engine.register_fn("type_coderef", || {
        to_dynamic(InferredType::CodeRef { return_edge: None }).unwrap()
    });
    engine.register_fn("type_regexp", || to_dynamic(InferredType::Regexp).unwrap());
    engine.register_fn("type_class", |class: String| {
        to_dynamic(InferredType::ClassName(class)).unwrap_or(Dynamic::UNIT)
    });

    // Mark a param-list's first element as the implicit invocant.
    // Framework callbacks typically receive the receiver as their
    // first positional (`$c` for Mojolicious helpers, `$self_in`
    // for Mojo::EventEmitter handlers, etc.); the plugin knows
    // this, the core does not. Running the array through this
    // helper tells sig help / hover / outline to drop param 0 at
    // display time without the core matching on names.
    engine.register_fn("as_invocant_params", |list: Array| -> Array {
        let mut out = list;
        if let Some(first) = out.get_mut(0) {
            if let Ok(mut m) = first.as_map_mut() {
                m.insert("is_invocant".into(), Dynamic::from(true));
            }
        }
        out
    });

    // Subspan helper: plugins frequently want to narrow a parser-given
    // span (e.g. a whole string literal) down to a portion of its
    // content (the method-name half of `"Controller#action"`). This
    // returns a new span on the same row with columns offset from
    // `base`'s start. Plugins pass column *deltas* — 0 for "start of
    // base", `len(content)` for "end" — and we compute the absolute
    // columns.
    engine.register_fn(
        "subspan_cols",
        |base: Dynamic, col_start_delta: i64, col_end_delta: i64| -> Dynamic {
            let Ok(span) = from_dynamic::<Span>(&base) else { return Dynamic::UNIT; };
            let start = Point::new(
                span.start.row,
                (span.start.column as i64 + col_start_delta).max(0) as usize,
            );
            let end = Point::new(
                span.start.row,
                (span.start.column as i64 + col_end_delta).max(0) as usize,
            );
            to_dynamic(Span { start, end }).unwrap_or(Dynamic::UNIT)
        },
    );

    engine
}

pub struct RhaiPlugin {
    id: String,
    triggers: Vec<Trigger>,
    overrides: Vec<TypeOverride>,
    engine: Arc<Engine>,
    ast: Arc<AST>,
    has_on_function_call: bool,
    has_on_method_call: bool,
    has_on_use: bool,
    has_on_signature_help: bool,
    has_on_completion: bool,
}

impl RhaiPlugin {
    /// Compile a script from source text and interrogate its metadata
    /// (`id()`, `triggers()`) up-front so dispatch is cheap.
    pub fn from_source(
        source: &str,
        engine: Arc<Engine>,
    ) -> Result<Self, String> {
        let ast = engine
            .compile(source)
            .map_err(|e| format!("rhai compile: {}", e))?;

        let id: String = engine
            .call_fn(&mut rhai::Scope::new(), &ast, "id", ())
            .map_err(|e| format!("rhai `id()`: {}", e))?;

        let trig_dyn: Array = engine
            .call_fn(&mut rhai::Scope::new(), &ast, "triggers", ())
            .map_err(|e| format!("rhai `triggers()`: {}", e))?;

        let mut triggers = Vec::with_capacity(trig_dyn.len());
        for d in trig_dyn {
            let t: Trigger = from_dynamic(&d)
                .map_err(|e| format!("bad trigger from `{}`: {}", id, e))?;
            triggers.push(t);
        }

        let signatures: Vec<String> = ast
            .iter_functions()
            .map(|f| f.name.to_string())
            .collect();

        // `overrides()` is optional. Read once at compile time; missing
        // function == no overrides. A bad return shape logs and treats
        // as empty — same fail-safe as the emit hooks (a broken plugin
        // shouldn't break the build).
        let mut overrides: Vec<TypeOverride> = Vec::new();
        if signatures.iter().any(|n| n == "overrides") {
            match engine.call_fn::<Array>(&mut rhai::Scope::new(), &ast, "overrides", ()) {
                Ok(arr) => {
                    for d in arr {
                        match from_dynamic::<TypeOverride>(&d) {
                            Ok(o) => overrides.push(o),
                            Err(e) => log::error!(
                                "plugin `{}` overrides() bad entry: {}",
                                id,
                                e
                            ),
                        }
                    }
                }
                Err(e) => log::error!("plugin `{}` overrides() failed: {}", id, e),
            }
        }

        Ok(Self {
            has_on_function_call: signatures.iter().any(|n| n == "on_function_call"),
            has_on_method_call: signatures.iter().any(|n| n == "on_method_call"),
            has_on_use: signatures.iter().any(|n| n == "on_use"),
            has_on_signature_help: signatures.iter().any(|n| n == "on_signature_help"),
            has_on_completion: signatures.iter().any(|n| n == "on_completion"),
            id,
            triggers,
            overrides,
            engine,
            ast: Arc::new(ast),
        })
    }

    /// Call a Rhai query hook that returns a single map (sig help)
    /// or nil. Returns `None` if the script's fn returned unit or
    /// the call failed — plugins stay silent unless they have
    /// something to contribute.
    fn call_opt_map<T: serde::de::DeserializeOwned>(&self, fn_name: &str, arg: Dynamic) -> Option<T> {
        let out: Result<Dynamic, _> =
            self.engine.call_fn(&mut rhai::Scope::new(), &self.ast, fn_name, (arg,));
        let v = match out {
            Ok(v) => v,
            Err(e) => {
                // A Rhai call failure is a plugin bug (bad script, kill
                // switch triggered, panic inside the VM) — log at
                // ERROR, not warn. `warn!` gets filtered by default
                // log levels and the user sees missing features with
                // no hint.
                log::error!("plugin `{}`::{} failed: {}", self.id, fn_name, e);
                return None;
            }
        };
        if v.is_unit() { return None; }
        match from_dynamic::<T>(&v) {
            Ok(parsed) => Some(parsed),
            Err(e) => {
                log::error!("plugin `{}`::{} bad return: {}", self.id, fn_name, e);
                None
            }
        }
    }

    fn dispatch(&self, fn_name: &str, arg: Dynamic) -> Vec<EmitAction> {
        let out: Result<Array, _> =
            self.engine.call_fn(&mut rhai::Scope::new(), &self.ast, fn_name, (arg,));
        let arr = match out {
            Ok(a) => a,
            Err(e) => {
                log::error!("plugin `{}`::{} failed: {}", self.id, fn_name, e);
                return Vec::new();
            }
        };
        arr.into_iter()
            .filter_map(|d| {
                from_dynamic::<EmitAction>(&d)
                    .map_err(|e| {
                        log::error!(
                            "plugin `{}`::{} bad emission: {}",
                            self.id,
                            fn_name,
                            e
                        )
                    })
                    .ok()
            })
            .collect()
    }
}

impl FrameworkPlugin for RhaiPlugin {
    fn id(&self) -> &str {
        &self.id
    }

    fn triggers(&self) -> &[Trigger] {
        &self.triggers
    }

    fn overrides(&self) -> &[TypeOverride] {
        &self.overrides
    }

    fn on_function_call(&self, ctx: &CallContext) -> Vec<EmitAction> {
        if !self.has_on_function_call {
            return Vec::new();
        }
        match to_dynamic(ctx) {
            Ok(d) => self.dispatch("on_function_call", d),
            Err(e) => {
                log::warn!("plugin `{}`: ctx serialize: {}", self.id, e);
                Vec::new()
            }
        }
    }

    fn on_method_call(&self, ctx: &CallContext) -> Vec<EmitAction> {
        if !self.has_on_method_call {
            return Vec::new();
        }
        match to_dynamic(ctx) {
            Ok(d) => self.dispatch("on_method_call", d),
            Err(e) => {
                log::warn!("plugin `{}`: ctx serialize: {}", self.id, e);
                Vec::new()
            }
        }
    }

    fn on_signature_help(&self, ctx: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> {
        if !self.has_on_signature_help { return None; }
        let d = to_dynamic(ctx).ok()?;
        self.call_opt_map("on_signature_help", d)
    }

    fn on_completion(&self, ctx: &CompletionQueryContext) -> Option<PluginCompletionAnswer> {
        if !self.has_on_completion { return None; }
        let d = to_dynamic(ctx).ok()?;
        self.call_opt_map("on_completion", d)
    }

    fn on_use(&self, ctx: &UseContext) -> Vec<EmitAction> {
        if !self.has_on_use {
            return Vec::new();
        }
        match to_dynamic(ctx) {
            Ok(d) => self.dispatch("on_use", d),
            Err(e) => {
                log::warn!("plugin `{}`: use ctx serialize: {}", self.id, e);
                Vec::new()
            }
        }
    }
}

// ---- Bundled plugins ----

/// Bundled Rhai script sources shipped with the binary. Third-party plugins
/// can be loaded from disk via `load_plugin_dir`.
const BUNDLED: &[(&str, &str)] = &[
    ("mojo-events", include_str!("../../frameworks/mojo-events.rhai")),
    ("mojo-helpers", include_str!("../../frameworks/mojo-helpers.rhai")),
    ("mojo-routes", include_str!("../../frameworks/mojo-routes.rhai")),
    ("mojo-lite", include_str!("../../frameworks/mojo-lite.rhai")),
    ("minion", include_str!("../../frameworks/minion.rhai")),
    ("data-printer", include_str!("../../frameworks/data-printer.rhai")),
];

pub fn load_bundled(engine: Arc<Engine>) -> Vec<Box<dyn FrameworkPlugin>> {
    let mut out: Vec<Box<dyn FrameworkPlugin>> = Vec::new();
    for (id, src) in BUNDLED {
        match RhaiPlugin::from_source(src, engine.clone()) {
            Ok(p) => {
                log::info!("loaded bundled plugin `{}`", id);
                out.push(Box::new(p));
            }
            Err(e) => {
                log::warn!("bundled plugin `{}` failed to load: {}", id, e);
            }
        }
    }
    out
}

/// Stable hash of the plugin set the next `build()` will load. Used by the
/// SQLite module cache to invalidate stored FileAnalysis blobs when the
/// plugins that produced them have changed — without this, editing a
/// `.rhai` and restarting the LSP serves stale cross-file analyses.
///
/// Inputs:
///   * Every bundled plugin's `(id, source)` pair — catches binary
///     rebuilds whose only change was a `frameworks/*.rhai` edit.
///   * Every `.rhai` file in `$PERL_LSP_PLUGIN_DIR`, with its path —
///     catches user-plugin add / remove / rename / edit across LSP
///     restarts.
///
/// Read-only: no compile, no side effects, no log spam. Fails open
/// (returns the bundled-only hash) if the user dir can't be read,
/// matching the rest of the loader's silently-tolerant behavior.
pub fn plugin_fingerprint() -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();

    for (id, src) in BUNDLED {
        id.hash(&mut hasher);
        src.hash(&mut hasher);
    }

    if let Ok(dir) = std::env::var("PERL_LSP_PLUGIN_DIR") {
        let path = std::path::PathBuf::from(&dir);
        // Sort entries by path so the hash is independent of readdir order.
        let mut entries: Vec<std::path::PathBuf> = match std::fs::read_dir(&path) {
            Ok(read) => read
                .flatten()
                .map(|e| e.path())
                .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("rhai"))
                .collect(),
            Err(_) => Vec::new(),
        };
        entries.sort();
        for p in entries {
            // Path is part of the hash so a rename invalidates.
            p.to_string_lossy().hash(&mut hasher);
            if let Ok(src) = std::fs::read_to_string(&p) {
                src.hash(&mut hasher);
            }
        }
    }

    format!("{:016x}", hasher.finish())
}

/// Load all `*.rhai` files from a directory. Used for user-installed plugins.
pub fn load_plugin_dir(
    dir: &std::path::Path,
    engine: Arc<Engine>,
) -> Vec<Box<dyn FrameworkPlugin>> {
    let mut out: Vec<Box<dyn FrameworkPlugin>> = Vec::new();
    let read = match std::fs::read_dir(dir) {
        Ok(r) => r,
        Err(_) => return out,
    };
    for entry in read.flatten() {
        let path = entry.path();
        if path.extension().and_then(|s| s.to_str()) != Some("rhai") {
            continue;
        }
        let source = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(e) => {
                log::warn!("plugin {}: read: {}", path.display(), e);
                continue;
            }
        };
        match RhaiPlugin::from_source(&source, engine.clone()) {
            Ok(p) => {
                log::info!("loaded plugin {} from {}", p.id(), path.display());
                out.push(Box::new(p));
            }
            Err(e) => log::warn!("plugin {}: {}", path.display(), e),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file_analysis::Span;
    use tree_sitter::Point;

    fn sp(r1: usize, c1: usize, r2: usize, c2: usize) -> Span {
        Span { start: Point::new(r1, c1), end: Point::new(r2, c2) }
    }

    #[test]
    fn minimal_plugin_loads_and_dispatches() {
        let src = r#"
            fn id() { "demo" }
            fn triggers() { [ #{ UsesModule: "Demo" } ] }
            fn on_function_call(ctx) {
                if ctx.function_name == "greet" {
                    return [
                        #{
                            Method: #{
                                name: "hello",
                                span: ctx.call_span,
                                selection_span: ctx.selection_span,
                                params: [],
                                is_method: true,
                                return_type: (),
                                doc: (),
                            }
                        }
                    ];
                }
                []
            }
        "#;

        let engine = Arc::new(make_engine());
        let plugin = RhaiPlugin::from_source(src, engine).expect("compiles");
        assert_eq!(plugin.id(), "demo");
        assert_eq!(plugin.triggers().len(), 1);

        let ctx = CallContext {
            call_kind: super::super::CallKind::Function,
            function_name: Some("greet".into()),
            method_name: None,
            receiver_text: None,
            receiver_type: None,
            args: vec![],
            call_span: sp(0, 0, 0, 5),
            selection_span: sp(0, 0, 0, 5),
            current_package: Some("Demo::App".into()),
            current_package_parents: vec![],
            current_package_uses: vec!["Demo".into()],
        };

        let emissions = plugin.on_function_call(&ctx);
        assert_eq!(emissions.len(), 1);
        match &emissions[0] {
            EmitAction::Method { name, is_method, .. } => {
                assert_eq!(name, "hello");
                assert!(*is_method);
            }
            other => panic!("unexpected emission: {:?}", other),
        }
    }

    #[test]
    fn plugin_fingerprint_invariants() {
        // Two contracts in one test (env var is process-global, so
        // splitting these into parallel-safe tests would race):
        //
        //   1. Stability — identical inputs must produce identical
        //      hashes, otherwise we'd nuke the SQLite cache on every
        //      LSP startup.
        //   2. Sensitivity — editing a `.rhai` in the user plugin dir
        //      must change the fingerprint, so the cache invalidates
        //      on the next LSP restart and the author can QA their
        //      changes.
        let dir = std::env::temp_dir().join(format!(
            "perl-lsp-fp-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let plugin_path = dir.join("test.rhai");

        let saved = std::env::var("PERL_LSP_PLUGIN_DIR").ok();
        std::env::set_var("PERL_LSP_PLUGIN_DIR", &dir);

        std::fs::write(&plugin_path, r#"fn id() { "v1" } fn triggers() { [] }"#).unwrap();
        let v1a = plugin_fingerprint();
        let v1b = plugin_fingerprint();

        std::fs::write(&plugin_path, r#"fn id() { "v2" } fn triggers() { [] }"#).unwrap();
        let v2 = plugin_fingerprint();

        // Restore env BEFORE asserting so a panic doesn't leak the override.
        match saved {
            Some(v) => std::env::set_var("PERL_LSP_PLUGIN_DIR", v),
            None => std::env::remove_var("PERL_LSP_PLUGIN_DIR"),
        }
        let _ = std::fs::remove_file(&plugin_path);
        let _ = std::fs::remove_dir(&dir);

        assert!(!v1a.is_empty(), "fingerprint should never be empty");
        assert_eq!(v1a, v1b, "fingerprint must be deterministic");
        assert_ne!(v1a, v2, "fingerprint must change when a user plugin's source changes");
    }

    #[test]
    fn bundled_script_compiles() {
        // Diagnostic: if load_bundled drops ANY script due to a compile
        // error, surface the real error instead of the opaque
        // "not found" failure later. Each bundled script is exercised.
        let engine = Arc::new(make_engine());
        for (id, src) in [
            ("mojo-events", include_str!("../../frameworks/mojo-events.rhai")),
            ("mojo-helpers", include_str!("../../frameworks/mojo-helpers.rhai")),
            ("mojo-routes", include_str!("../../frameworks/mojo-routes.rhai")),
            ("mojo-lite", include_str!("../../frameworks/mojo-lite.rhai")),
            ("minion", include_str!("../../frameworks/minion.rhai")),
            ("data-printer", include_str!("../../frameworks/data-printer.rhai")),
        ] {
            RhaiPlugin::from_source(src, engine.clone())
                .unwrap_or_else(|e| panic!("{}.rhai failed to compile: {e}", id));
        }
    }

    #[test]
    fn bundled_mojo_events_loads_and_emits() {
        use crate::plugin::{ArgInfo, CallKind};

        let engine = Arc::new(make_engine());
        let bundled = load_bundled(engine);
        let plugin = bundled
            .into_iter()
            .find(|p| p.id() == "mojo-events")
            .expect("mojo-events is bundled");

        let evt_span = sp(3, 15, 3, 23);
        let cb_span = sp(3, 25, 3, 40);
        let ctx = CallContext {
            call_kind: CallKind::Method,
            function_name: None,
            method_name: Some("on".into()),
            receiver_text: Some("$self".into()),
            receiver_type: Some(InferredType::ClassName("My::Emitter".into())),
            args: vec![
                ArgInfo {
                    text: "'connect'".into(),
                    string_value: Some("connect".into()),
                    span: evt_span,
                    content_span: None,
                    inferred_type: Some(InferredType::String), sub_params: vec![], callable_return_edge: None,
                },
                ArgInfo {
                    text: "sub { ... }".into(),
                    string_value: None,
                    span: cb_span,
                    content_span: None,
                    inferred_type: Some(InferredType::CodeRef { return_edge: None }), sub_params: vec![], callable_return_edge: None,
                },
            ],
            call_span: sp(3, 4, 3, 45),
            selection_span: sp(3, 10, 3, 12),
            current_package: Some("My::Emitter".into()),
            current_package_parents: vec!["Mojo::EventEmitter".into()],
            current_package_uses: vec![],
        };

        let emissions = plugin.on_method_call(&ctx);
        // DispatchCall (ref) + Handler (def) + PluginNamespace (bridge).
        assert_eq!(emissions.len(), 3,
            "dispatch call + handler + namespace; got: {:?}", emissions);

        let has_dispatch = emissions.iter().any(|e| {
            matches!(e, EmitAction::DispatchCall { name, dispatcher, .. }
                if name == "connect" && dispatcher == "on")
        });
        assert!(has_dispatch, "missing DispatchCall for 'connect' via ->on");

        let has_handler = emissions.iter().any(|e| {
            matches!(e, EmitAction::Handler { name, .. } if name == "connect")
        });
        assert!(has_handler, "missing Handler symbol for 'connect'");

        let has_namespace = emissions.iter().any(|e| {
            matches!(e, EmitAction::PluginNamespace { id, kind, entity_names, .. }
                if id == "mojo-events:My::Emitter"
                    && kind == "events"
                    && entity_names.iter().any(|n| n == "connect"))
        });
        assert!(has_namespace,
            "missing PluginNamespace for My::Emitter events; got: {:?}", emissions);
    }

    #[test]
    fn mojo_events_skips_dynamic_event_name() {
        use crate::plugin::{ArgInfo, CallKind};

        let engine = Arc::new(make_engine());
        let bundled = load_bundled(engine);
        let plugin = bundled
            .into_iter()
            .find(|p| p.id() == "mojo-events")
            .unwrap();

        let ctx = CallContext {
            call_kind: CallKind::Method,
            function_name: None,
            method_name: Some("on".into()),
            receiver_text: Some("$self".into()),
            receiver_type: Some(InferredType::ClassName("Foo".into())),
            args: vec![
                // Dynamic name — string_value is None, so plugin must skip.
                ArgInfo {
                    text: "$name".into(),
                    string_value: None,
                    span: sp(0, 0, 0, 5),
                    content_span: None,
                    inferred_type: None, sub_params: vec![], callable_return_edge: None,
                },
                ArgInfo {
                    text: "sub {}".into(),
                    string_value: None,
                    span: sp(0, 6, 0, 12),
                    content_span: None,
                    inferred_type: Some(InferredType::CodeRef { return_edge: None }), sub_params: vec![], callable_return_edge: None,
                },
            ],
            call_span: sp(0, 0, 0, 15),
            selection_span: sp(0, 0, 0, 2),
            current_package: Some("Foo".into()),
            current_package_parents: vec!["Mojo::EventEmitter".into()],
            current_package_uses: vec![],
        };

        let emissions = plugin.on_method_call(&ctx);
        assert!(emissions.is_empty(), "dynamic name must not emit");
    }

    #[test]
    fn rhai_overrides_function_is_read_at_compile_time() {
        // A plugin that defines a top-level `overrides()` function:
        // the host reads it once at load and exposes the list via
        // FrameworkPlugin::overrides — no runtime call cost. This
        // pins the static-manifest contract; if a future refactor
        // moves overrides() to a per-build hook, this test breaks
        // and forces a rethink.
        let src = r#"
            fn id() { "demo-overrides" }
            fn triggers() { [] }
            fn overrides() {
                [
                    #{
                        target: #{ Method: #{ class: "Foo", name: "bar" } },
                        return_type: #{ ClassName: "Foo" },
                        reason: "test",
                    }
                ]
            }
        "#;
        let engine = Arc::new(make_engine());
        let plugin = RhaiPlugin::from_source(src, engine).expect("compiles");
        let ovs = plugin.overrides();
        assert_eq!(ovs.len(), 1);
        match &ovs[0].target {
            crate::plugin::OverrideTarget::Method { class, name } => {
                assert_eq!(class, "Foo");
                assert_eq!(name, "bar");
            }
            other => panic!("expected Method target, got {:?}", other),
        }
        assert_eq!(
            ovs[0].return_type,
            InferredType::ClassName("Foo".into())
        );
        assert_eq!(ovs[0].reason, "test");
    }

    #[test]
    fn rhai_overrides_missing_function_yields_empty() {
        // Plugins without an `overrides()` function must still load.
        // The default registry uses this default for every plugin
        // that doesn't ship overrides — silent absence, not error.
        let src = r#"
            fn id() { "no-overrides" }
            fn triggers() { [] }
        "#;
        let engine = Arc::new(make_engine());
        let plugin = RhaiPlugin::from_source(src, engine).expect("compiles");
        assert!(plugin.overrides().is_empty());
    }

    #[test]
    fn non_matching_function_returns_empty() {
        let src = r#"
            fn id() { "demo2" }
            fn triggers() { [ #{ Always: () } ] }
            fn on_function_call(ctx) {
                if ctx.function_name == "wanted" { return [#{ FrameworkImport: #{ keyword: "ok" } }]; }
                []
            }
        "#;
        let engine = Arc::new(make_engine());
        let plugin = RhaiPlugin::from_source(src, engine).unwrap();

        let ctx = CallContext {
            call_kind: super::super::CallKind::Function,
            function_name: Some("unrelated".into()),
            method_name: None,
            receiver_text: None,
            receiver_type: None,
            args: vec![],
            call_span: sp(0, 0, 0, 0),
            selection_span: sp(0, 0, 0, 0),
            current_package: None,
            current_package_parents: vec![],
            current_package_uses: vec![],
        };
        assert!(plugin.on_function_call(&ctx).is_empty());
    }
}