rust-samp 3.6.0

Write SA-MP and open.mp plugins in safe Rust instead of C++. A single binary runs natively on both servers, with proc macros (`#[native]`, `initialize_plugin!`) that hide the FFI boilerplate and ABI-correct marshalling for Linux (Itanium) and Windows (MSVC).
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
//! API the Rust plugin uses: trait [`SampPlugin`] (lifecycle) + global
//! functions to enable features (`enable_tick`, `logger`, `omp_query`).

use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

use samp_sdk::amx::Amx;
use samp_sdk::cell::AmxCell;

use crate::macros::sdk_warn;
use crate::runtime::Runtime;

#[doc(hidden)]
pub fn initialize<F, T>(constructor: F)
where
    F: FnOnce() -> T + 'static,
    T: SampPlugin + 'static,
{
    let rt = Runtime::initialize();
    let plugin = constructor();

    rt.set_plugin(plugin);
    rt.post_initialize();
}

/// Tells the SDK how often [`SampPlugin::on_tick`] should fire on each
/// server.
///
/// The two servers schedule periodic callbacks differently:
///
/// - **SA-MP** exports `ProcessTick`. The server's main loop invokes it on
///   every iteration — the cadence is whatever the server is configured for.
///   The SDK has no say over the interval; the [`sa_mp`] flag only decides
///   whether the export is advertised at all.
/// - **native Open Multiplayer** has no built-in `ProcessTick` equivalent.
///   The SDK installs a repeating timer on the server's `ITimersComponent`
///   in `on_ready` and dispatches the timeout into [`on_tick`]. The
///   interval is the [`omp_interval`] field.
///
/// [`sa_mp`]: TickConfig::sa_mp
/// [`omp_interval`]: TickConfig::omp_interval
/// [`on_tick`]: SampPlugin::on_tick
#[derive(Debug, Clone, Copy)]
pub struct TickConfig {
    /// Enable the tick on SA-MP. When `false`, the plugin does not advertise
    /// `Supports::PROCESS_TICK` and the export becomes inert.
    pub sa_mp: bool,
    /// Enable the tick on native Open Multiplayer. When `false`, the SDK
    /// does not create the `ITimersComponent` timer in `on_ready`.
    pub omp: bool,
    /// Interval the SDK uses when creating the Open Multiplayer timer.
    /// Ignored when [`omp`] is `false`. Ignored entirely on SA-MP (the
    /// server controls the cadence).
    ///
    /// [`omp`]: TickConfig::omp
    pub omp_interval: Duration,
}

impl Default for TickConfig {
    /// Default: enabled on both servers, 5 ms timer on Open Multiplayer.
    fn default() -> Self {
        Self {
            sa_mp: true,
            omp: true,
            omp_interval: Duration::from_millis(5),
        }
    }
}

impl TickConfig {
    /// Equivalent to `TickConfig::default()`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Builder: sets [`sa_mp`].
    ///
    /// [`sa_mp`]: TickConfig::sa_mp
    #[must_use]
    pub fn sa_mp(mut self, enabled: bool) -> Self {
        self.sa_mp = enabled;
        self
    }

    /// Builder: sets [`omp`].
    ///
    /// [`omp`]: TickConfig::omp
    #[must_use]
    pub fn omp(mut self, enabled: bool) -> Self {
        self.omp = enabled;
        self
    }

    /// Builder: sets [`omp_interval`].
    ///
    /// [`omp_interval`]: TickConfig::omp_interval
    #[must_use]
    pub fn omp_interval(mut self, interval: Duration) -> Self {
        self.omp_interval = interval;
        self
    }

    /// Shortcut: tick only on SA-MP. Equivalent to
    /// `TickConfig::new().omp(false)`.
    ///
    /// Use when the plugin has no meaningful work to do on the Open
    /// Multiplayer tick — for example, a pure SA-MP plugin running in
    /// legacy mode under Open Multiplayer.
    #[must_use]
    pub fn sa_mp_only() -> Self {
        Self::default().omp(false)
    }

    /// Shortcut: tick only on native Open Multiplayer, at the supplied
    /// interval. Equivalent to
    /// `TickConfig::new().sa_mp(false).omp_interval(interval)`.
    ///
    /// Use when the plugin needs a controlled cadence specifically on
    /// Open Multiplayer and should stay silent on SA-MP — for example,
    /// a component that drives a long-poll loop only meaningful when
    /// the component API is reachable.
    #[must_use]
    pub fn omp_only(interval: Duration) -> Self {
        Self::default().sa_mp(false).omp_interval(interval)
    }
}

/// Origin of the current [`SampPlugin::on_tick`] invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TickSource {
    /// Fired by SA-MP's `ProcessTick` export, on every iteration of the
    /// server's main loop.
    SaMp,
    /// Fired by the SDK-owned repeating timer on native Open Multiplayer
    /// (created via `ITimersComponent` in `on_ready`). Matches the
    /// `omp` / `Omp*` identifier convention used elsewhere in the SDK
    /// (`OmpComponent`, `OmpComponentHandle`, …).
    OmpTimer,
}

/// Per-call context delivered to [`SampPlugin::on_tick`].
#[derive(Debug, Clone, Copy)]
pub struct TickContext {
    /// Wall-clock time elapsed since the previous `on_tick` dispatch in
    /// this plugin instance. `Duration::ZERO` on the very first call.
    pub elapsed: Duration,
    /// Which server scheduled this dispatch.
    pub source: TickSource,
}

/// Enables [`SampPlugin::on_tick`] with default settings: tick on both
/// servers, 5 ms interval on Open Multiplayer.
///
/// Call inside `initialize_plugin!`. Without this opt-in the tick stays
/// inert — useful for purely reactive plugins that do not need the cycle.
pub fn enable_tick() {
    enable_tick_with(TickConfig::default());
}

/// Enables [`SampPlugin::on_tick`] with an explicit [`TickConfig`].
///
/// Use this form to disable the tick on one server, or to choose a
/// different Open Multiplayer timer interval.
///
/// # Example
/// ```rust,no_run
/// # use std::time::Duration;
/// # use samp::plugin::{enable_tick_with, TickConfig};
/// // Tick every 50 ms on Open Multiplayer; rely on SA-MP's default cadence.
/// enable_tick_with(TickConfig::new().omp_interval(Duration::from_millis(50)));
/// ```
pub fn enable_tick_with(config: TickConfig) {
    Runtime::get().set_tick_config(config);
}

/// Installs the SDK's debug hook on `amx`, routing every executed line into
/// [`SampPlugin::on_debug_break`]. Call from [`SampPlugin::on_amx_load`] for
/// each AMX you want to debug (typically the gamemode).
///
/// The `.amx` must have been compiled with `-d2`/`-d3` for the VM to invoke the
/// hook. To stop receiving callbacks, call [`disable_debug_hook`].
///
/// This is the turnkey alternative to [`Amx::install_debug_hook`]: instead of
/// managing a raw `extern "C"` callback and global state yourself, the SDK owns
/// a panic-guarded trampoline and dispatches into your plugin instance.
///
/// # Example
/// ```rust,ignore
/// impl SampPlugin for MyDebugger {
///     fn on_amx_load(&mut self, amx: &Amx) {
///         samp::plugin::enable_debug_hook(amx);
///     }
///     fn on_debug_break(&mut self, amx: &Amx) {
///         let line = amx.cip();
///         // inspect / pause / forward to a DAP client...
///     }
/// }
/// ```
pub fn enable_debug_hook(amx: &Amx) {
    amx.install_debug_hook(debug_hook_trampoline);
}

/// Removes the SDK debug hook previously installed by [`enable_debug_hook`] on
/// `amx`, so [`SampPlugin::on_debug_break`] stops firing for it.
pub fn disable_debug_hook(amx: &Amx) {
    amx.remove_debug_hook();
}

/// SDK-owned debug hook callback. The VM calls this on every source line of an
/// AMX that opted in via [`enable_debug_hook`]. It wraps the raw `*mut AMX` and
/// dispatches into the plugin's [`SampPlugin::on_debug_break`].
///
/// Crosses the FFI boundary, so it must never unwind: the dispatch is wrapped in
/// `catch_unwind` and always returns `AMX_ERR_NONE` (0).
extern "C" fn debug_hook_trampoline(amx: *mut samp_sdk::raw::types::AMX) -> i32 {
    let _ = crate::panic_guard::catch(|| {
        let Some(rt) = Runtime::try_get() else { return };
        let wrapped = Amx::new(amx, rt.amx_exports());
        Runtime::plugin().on_debug_break(&wrapped);
    });
    0 // AMX_ERR_NONE
}

/// Returns a [`fern::Dispatch`] already chained into the server's log system,
/// disabling the SDK's default routing.
///
/// Lets the plugin customize format, level, sink (file, console) without
/// giving up delivery to the server (SA-MP `logprintf` or
/// `ICore::logLnU8`). The `log` crate level is mapped automatically to
/// [`samp_sdk::omp::LogLevel`] in Open Multiplayer mode.
///
/// # Example
/// ```rust,ignore
/// initialize_plugin!({
///     let _ = fern::Dispatch::new()
///         .format(|cb, msg, rec| cb.finish(format_args!("[MyPlugin][{}]: {}", rec.level(), msg)))
///         .level(log::LevelFilter::Info)
///         .chain(samp::plugin::logger())
///         .apply();
///     MyPlugin
/// });
/// ```
pub fn logger() -> fern::Dispatch {
    let rt = Runtime::get();
    rt.disable_default_logger();

    // Through the logger's queue: a line logged on another thread reaches the
    // server on the main thread, since neither server's log is thread-safe.
    fern::Dispatch::new().chain(fern::Output::call(|record| {
        crate::logger::to_server(record.level(), record.args().to_string());
    }))
}

#[doc(hidden)]
#[must_use]
pub fn get<T: SampPlugin + 'static>() -> NonNull<T> {
    Runtime::plugin_cast()
}

/// What `#[native]` uses to reach the plugin: `None` instead of a panic when
/// there is no plugin yet, since a native can be called by another plugin
/// outside the order the server keeps.
#[doc(hidden)]
#[must_use]
pub fn try_get<T: SampPlugin + 'static>() -> Option<NonNull<T>> {
    Runtime::try_plugin_cast()
}

// ---------------------------------------------------------------------------
// Reaching the plugin from outside a native
// ---------------------------------------------------------------------------

/// Set while a [`with_instance`] closure runs.
static PLUGIN_BORROWED: AtomicBool = AtomicBool::new(false);

/// Depth of native calls in progress. A native already holds `&mut self`, so
/// handing out another borrow underneath one would alias it.
///
/// Natives run on the main thread only, so this is the only thread that writes
/// it: a load and a store do, without the locked read-modify-write a
/// `fetch_add` costs on every native call.
static NATIVE_DEPTH: AtomicUsize = AtomicUsize::new(0);

/// Marks a native call for the duration of its frame.
///
/// Generated by `#[native]`; not part of the stable surface.
#[doc(hidden)]
pub struct NativeFrame;

impl NativeFrame {
    /// Enters a native frame, warning once if a `with_instance` borrow is alive.
    ///
    /// That combination means a main-thread job called into Pawn and the script
    /// called back into this plugin, so the native's `&mut self` aliases the
    /// job's `&mut T`. The SDK cannot refuse — the native must still answer the
    /// script — so it names the problem instead of leaving it silent.
    #[must_use]
    pub fn enter() -> Self {
        if PLUGIN_BORROWED.load(Ordering::Acquire) {
            static WARNED: AtomicBool = AtomicBool::new(false);
            if !WARNED.swap(true, Ordering::Relaxed) {
                sdk_warn!(
                    "a native ran while a main-thread job held the plugin: the two \
                     `&mut` borrows alias. Call into Pawn after the job's closure \
                     returns — collect what to send, end the closure, then send it."
                );
            }
        }
        let depth = NATIVE_DEPTH.load(Ordering::Acquire);
        NATIVE_DEPTH.store(depth + 1, Ordering::Release);
        Self
    }
}

impl Drop for NativeFrame {
    fn drop(&mut self) {
        let depth = NATIVE_DEPTH.load(Ordering::Acquire);
        NATIVE_DEPTH.store(depth.saturating_sub(1), Ordering::Release);
    }
}

/// Runs `f` with the plugin instance, on the main thread.
///
/// This is the general way to reach plugin state from code the plugin does not
/// own the call site of — a main-thread job, a callback helper, a timer — where
/// there is no `&mut self` in scope.
///
/// ```rust,no_run
/// # use samp::prelude::*;
/// # struct MyPlugin { sent: u32 }
/// # impl SampPlugin for MyPlugin {}
/// let sent = samp::plugin::with_instance::<MyPlugin, _>(|plugin| {
///     plugin.sent += 1;
///     plugin.sent
/// });
/// ```
///
/// Returns `None`, having logged why, when the plugin cannot be lent out:
///
/// - `T` is not the type the plugin was created as;
/// - the plugin does not exist yet, or no longer does;
/// - a borrow is already alive — a nested `with_instance`, or a call from
///   inside a native, which already holds `&mut self`. Use that `self`.
///
/// Must be called from the main thread. There is nothing to synchronize with
/// off it: the plugin is not `Sync`, and the server touches it from one thread.
/// Work arriving on another thread belongs in [`crate::mainthread::post_with`],
/// which calls through here at the right moment.
pub fn with_instance<T, R>(f: impl FnOnce(&mut T) -> R) -> Option<R>
where
    T: SampPlugin + 'static,
{
    if NATIVE_DEPTH.load(Ordering::Acquire) > 0 {
        sdk_warn!(
            "with_instance() called from inside a native, which already holds \
             `&mut self` — use that instead; nothing was run"
        );
        return None;
    }
    if PLUGIN_BORROWED.swap(true, Ordering::AcqRel) {
        sdk_warn!("with_instance() called while the plugin was already borrowed; nothing was run");
        return None;
    }

    // Released on every path, including a panic in `f`, so one bad job does not
    // lock the plugin away for the rest of the process.
    struct Release;
    impl Drop for Release {
        fn drop(&mut self) {
            PLUGIN_BORROWED.store(false, Ordering::Release);
        }
    }
    let _release = Release;

    let Some(plugin) = Runtime::plugin_as::<T>() else {
        if Runtime::plugin_is_set() {
            sdk_warn!(
                "with_instance::<{}>() does not name the plugin's type; nothing was run",
                std::any::type_name::<T>()
            );
        } else {
            sdk_warn!("with_instance() called before the plugin was created; nothing was run");
        }
        return None;
    };

    Some(f(plugin))
}

/// Whether a [`with_instance`] borrow is alive right now.
///
/// Exposed for a plugin deciding whether to reach for state or defer.
#[must_use]
pub fn is_borrowed() -> bool {
    PLUGIN_BORROWED.load(Ordering::Acquire)
}

/// Returns the Open Multiplayer server's `ICore*` pointer received in `on_load`.
///
/// Available only in native Open Multiplayer mode (without the `samp-only` feature).
/// Returns `None` if the plugin was loaded via SA-MP or if `on_load` has not
/// been called yet.
#[cfg(not(feature = "samp-only"))]
#[must_use]
pub fn omp_core() -> Option<*mut samp_sdk::omp::component::ICore> {
    crate::runtime::Runtime::get().omp_core()
}

/// Looks up an Open Multiplayer component by UID in the list received in `on_init`.
///
/// Returns `None` if the server has not yet called `on_init` or if the component
/// is not registered.
///
/// # Example
/// ```rust,no_run
/// use samp::plugin::omp_query_component;
/// use samp_sdk::omp::server::PAWN_COMPONENT_UID;
///
/// if let Some(_pawn) = omp_query_component(PAWN_COMPONENT_UID) {
///     // IPawnComponent available
/// }
/// ```
#[cfg(not(feature = "samp-only"))]
#[must_use]
pub fn omp_query_component(
    uid: samp_sdk::omp::types::UID,
) -> Option<*mut samp_sdk::omp::server::ServerComponent> {
    crate::runtime::Runtime::get().omp_query_component(uid)
}

/// Looks up an Open Multiplayer component via its typed wrapper.
///
/// Typed version of `omp_query_component`: uses the `UID` declared in the type's
/// `OmpComponentHandle` trait, returns a wrapper that exposes specific methods.
///
/// # Example
/// ```rust,no_run
/// use samp_sdk::omp::PawnComponent;
///
/// if let Some(pawn) = samp::plugin::omp_query::<PawnComponent>() {
///     if let Some(version) = pawn.version() {
///         println!("Pawn component: {}.{}.{}", version.major, version.minor, version.patch);
///     }
/// }
/// ```
#[cfg(not(feature = "samp-only"))]
#[must_use]
pub fn omp_query<T>() -> Option<T>
where
    T: samp_sdk::omp::OmpComponentHandle,
{
    let raw = omp_query_component(T::UID)?;
    let nonnull_ptr = std::ptr::NonNull::new(raw)?;
    Some(unsafe { T::from_raw(nonnull_ptr) })
}

/// Plugin lifecycle. All methods are optional — the trait provides empty
/// implementations so the plugin only overrides the relevant ones.
///
/// Instead of implementing manually, use `#[derive(SampPlugin)]` if no
/// method needs custom logic.
pub trait SampPlugin {
    /// Server has finished loading the plugin (`Load()` on SA-MP /
    /// `onLoad(ICore*)` on Open Multiplayer). Good moment to initialize state.
    fn on_load(&mut self) {}

    /// Server is unloading the plugin. Release external resources here.
    fn on_unload(&mut self) {}

    /// A Pawn script (`.amx`) was loaded. On SA-MP it is called by the
    /// `AmxLoad` export; on Open Multiplayer by `IEventDispatcher<PawnEventHandler>`.
    fn on_amx_load(&mut self, amx: &Amx) {
        let _ = amx;
    }

    /// A Pawn script is being unloaded. Clean per-AMX state here.
    fn on_amx_unload(&mut self, amx: &Amx) {
        let _ = amx;
    }

    /// The VM's debug hook fired on a source line. Only called for AMXs the
    /// plugin opted in via [`enable_debug_hook`], and only when the `.amx` was
    /// compiled with `-d2`/`-d3`.
    ///
    /// This runs on the VM thread, synchronously, on every executed line — keep
    /// it cheap, and block here (e.g. waiting for a debugger client) only if you
    /// intend to freeze the server. Use the VM accessors on [`Amx`]
    /// (`cip`, `frame`, `read_cell`/`write_cell`) to read the paused state, and
    /// pair them with `samp::debug` (feature `debug`) to map addresses to source
    /// lines and symbols.
    fn on_debug_break(&mut self, amx: &Amx) {
        let _ = amx;
    }

    /// Periodic callback. Fires only when the plugin opted in via
    /// [`enable_tick`] (or [`enable_tick_with`]).
    ///
    /// The two servers schedule this differently:
    /// - **SA-MP**: the server invokes the `ProcessTick` export on every
    ///   iteration of its main loop. The cadence is whatever the server is
    ///   configured for — the SDK has no control over it.
    /// - **native Open Multiplayer**: there is no native equivalent of
    ///   `ProcessTick` for components. The SDK installs a repeating timer
    ///   on the server's `ITimersComponent` in `on_ready` and dispatches
    ///   its timeout here. The interval is whatever [`TickConfig::omp_interval`]
    ///   was set to (default: 5 ms).
    ///
    /// `ctx.source` tells which server scheduled the call; `ctx.elapsed`
    /// is the wall-clock time since the previous dispatch (zero on the
    /// first call).
    fn on_tick(&mut self, ctx: TickContext) {
        let _ = ctx;
    }

    /// Called when all Open Multiplayer components have finished initializing.
    ///
    /// This is the safe moment to interact with other server components,
    /// since all of them have already gone through their `on_init`.
    ///
    /// Available only in native Open Multiplayer mode (without the `samp-only` feature).
    #[cfg(not(feature = "samp-only"))]
    fn on_omp_ready(&mut self) {}

    /// Called when any Open Multiplayer component is being unloaded.
    ///
    /// Use together with `samp::plugin::omp_query_component()` to check
    /// which components are still available after the notification.
    ///
    /// Available only in native Open Multiplayer mode (without the `samp-only` feature).
    #[cfg(not(feature = "samp-only"))]
    fn on_component_free(&mut self) {}
}

#[doc(hidden)]
pub fn convert_return_value<T: AmxCell<'static>>(value: T) -> i32 {
    value.as_cell()
}

// ---------------------------------------------------------------------------
// Pawn include generation
// ---------------------------------------------------------------------------

/// Pawn `.inc` source for every native this plugin registers.
///
/// The declarations are derived by `#[native]` from the Rust signatures, so the
/// include cannot drift from the code: rename an argument or change a type and
/// the next build produces the new line.
///
/// Types map as follows — `f32` to `Float:`, `bool` to `bool:`, `AmxString` to
/// `const name[]`, `Ref<T>` to `&name` keeping `T`'s tag, and buffers to
/// `name[]`. A type the macro does not recognize becomes a plain cell, which is
/// what the AMX passes anyway; only the Pawn tag is lost. Natives declared
/// `raw` come back commented out, since their arity is not in the signature.
///
/// Returns an empty include (header only) before the plugin is loaded.
#[must_use]
pub fn pawn_include() -> String {
    let rt = Runtime::get();
    render_include(rt.plugin_name(), rt.native_decls())
}

/// The Pawn declaration of every registered native, as `#[native]` derived it.
///
/// A `raw` native appears commented out, its arity not being in the signature.
pub(crate) fn native_decls() -> Vec<&'static str> {
    Runtime::get().native_decls().to_vec()
}

/// Renders the include from a name and a list of declarations.
///
/// Public through [`crate::pawn_include::render`], which is where it is
/// documented; kept here next to the rest of the include plumbing.
pub(crate) fn render_include(name: &str, decls: &[&str]) -> String {
    // A crate name may carry characters Pawn does not accept in an identifier
    // (`email-samp`), so the include guard uses a sanitized form.
    let guard: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();
    let mut out = format!(
        "// Generated by rust-samp from the #[native] signatures of {name}.\n\
         // Edits are lost on the next build — change the Rust side instead.\n\n\
         #if defined _{guard}_included\n    #endinput\n#endif\n#define _{guard}_included\n\n"
    );
    for decl in decls {
        out.push_str(decl);
        out.push('\n');
    }
    out
}

/// Writes [`pawn_include`] to `path`, creating or truncating the file.
///
/// # Errors
/// Returns the underlying [`std::io::Error`] when the path cannot be written.
pub fn write_pawn_include(path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
    std::fs::write(path, pawn_include())
}

/// Writes the include when `SAMP_PAWN_INCLUDE` holds a path.
///
/// Called by the SDK once the natives are known, so a plugin author gets the
/// `.inc` by starting the server once with the variable set, on either server
/// and either mode. A failure is logged and otherwise ignored: producing a
/// development artifact must never take the server down.
pub(crate) fn write_pawn_include_if_requested() {
    let Some(path) = crate::pawn_include::path_for_plugin("SAMP_PAWN_INCLUDE") else {
        return;
    };

    // With a template, the include is that template with the declarations
    // filled in; without one, it is the plain generated file.
    if let Some(template) = crate::pawn_include::path_for_plugin("SAMP_PAWN_INCLUDE_TEMPLATE") {
        crate::pawn_include::write_from_template(&template, &path);
        return;
    }

    match write_pawn_include(&path) {
        Ok(()) => crate::macros::sdk_info!("Pawn include written to {}", path.to_string_lossy()),
        Err(e) => crate::macros::sdk_warn!(
            "could not write the Pawn include to {}: {e}",
            path.to_string_lossy()
        ),
    }
}

#[cfg(test)]
mod pawn_include_tests {
    use super::render_include;

    #[test]
    fn header_names_the_plugin_and_declarations_follow() {
        let out = render_include("counter", &["native Counter_Get(&out);"]);
        assert!(out.contains("signatures of counter"));
        assert!(out.ends_with("native Counter_Get(&out);\n"));
    }

    #[test]
    fn include_guard_drops_characters_pawn_rejects() {
        // `email-samp` would produce `_email-samp_included`, which the Pawn
        // preprocessor reads as a subtraction.
        let out = render_include("email-samp", &[]);
        assert!(out.contains("#define _email_samp_included"));
        assert!(!out.contains("email-samp_included"));
    }

    #[test]
    fn a_plugin_without_natives_still_produces_a_valid_include() {
        let out = render_include("hello", &[]);
        assert!(out.contains("#if defined _hello_included"));
    }
}

#[cfg(test)]
mod instance_tests {
    use super::*;
    use crate::test_support::{TestPlugin, exclusive, value};

    /// A second plugin type, never installed: naming it must reach nothing.
    struct Other;
    impl SampPlugin for Other {}

    #[test]
    fn the_closure_reaches_the_plugin_and_returns_its_value() {
        let _g = exclusive();

        let before = value();
        let after = with_instance::<TestPlugin, _>(|p| {
            p.value += 7;
            p.value
        })
        .unwrap();

        assert_eq!(after, before + 7);
        assert_eq!(value(), after);
    }

    #[test]
    fn naming_the_wrong_type_runs_nothing() {
        let _g = exclusive();

        let mut ran = false;
        let out = with_instance::<Other, _>(|_| {
            ran = true;
        });

        assert!(out.is_none());
        assert!(
            !ran,
            "the plugin's bytes must not be reinterpreted as another type"
        );
    }

    #[test]
    fn a_nested_borrow_is_refused_rather_than_aliased() {
        let _g = exclusive();

        let inner = with_instance::<TestPlugin, _>(|_outer| {
            assert!(is_borrowed());
            with_instance::<TestPlugin, _>(|_| "ran anyway")
        })
        .unwrap();

        assert_eq!(inner, None);
        assert!(!is_borrowed(), "the borrow is released on the way out");
    }

    #[test]
    fn a_native_frame_holds_the_borrow_off() {
        let _g = exclusive();

        let frame = NativeFrame::enter();
        assert!(
            with_instance::<TestPlugin, _>(|p| p.value).is_none(),
            "a native already holds `&mut self`"
        );
        drop(frame);

        assert!(with_instance::<TestPlugin, _>(|p| p.value).is_some());
    }

    #[test]
    fn a_panic_inside_the_closure_does_not_lock_the_plugin_away() {
        let _g = exclusive();

        let panicked = std::panic::catch_unwind(|| {
            with_instance::<TestPlugin, _>(|_| panic!("closure blew up"));
        });

        assert!(panicked.is_err());
        assert!(!is_borrowed());
        assert!(with_instance::<TestPlugin, _>(|p| p.value).is_some());
    }
}