rust-samp 3.6.0-rc.3

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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
//! Comparing a hand-written Pawn include against the natives a plugin registers.
//!
//! `#[native]` derives a declaration for every native, and
//! [`crate::plugin::pawn_include`] writes them out as an `.inc`. That works when
//! the include is generated. Plugins that maintain theirs by hand do so for
//! reasons the Rust signature cannot express — default values, `sizeof(dest)`,
//! varargs, documentation — and pay for it with drift: a native renamed in Rust
//! and forgotten in the include fails only when a script calls it.
//!
//! This module finds that drift. It parses declarations out of an include and
//! compares them with what the plugin registered, reporting what disagrees and
//! staying quiet about what a hand-written include is entitled to add.
//!
//! ```rust,no_run
//! for finding in samp::pawn_include::compare_file("email_samp.inc").unwrap() {
//!     log::warn!("{finding}");
//! }
//! ```
//!
//! Setting `SAMP_PAWN_INCLUDE_CHECK` to a path makes the SDK run the comparison
//! at load and log whatever it finds, which is the shape a CI job wants.
//!
//! ## What is compared, and what is not
//!
//! The name, the return tag, the number of arguments, and each argument's tag,
//! by-reference marker and array marker. A hand-written include may add default
//! values (`account = 0`), size expressions (`sizeof(dest)`), varargs
//! (`{Float,_}:...`) and any amount of documentation: those are additions the
//! Rust side has no way to state, so they are not divergences.
//!
//! An argument list ending in varargs also stops arity checking there — the
//! declaration is deliberately open-ended.

use std::fmt;
use std::path::Path;

/// One argument of a declaration, reduced to what both sides can state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Argument {
    /// `Float:` and friends, lowercased without the colon; empty when untagged.
    pub tag: String,
    /// Declared as `&arg`.
    pub by_reference: bool,
    /// Declared as `arg[]`.
    pub array: bool,
}

/// A `native` declaration, from either side of the comparison.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Declaration {
    pub name: String,
    /// Return tag, lowercased without the colon; empty when untagged.
    pub tag: String,
    pub arguments: Vec<Argument>,
    /// The list ends in `...`, so the argument count is open.
    pub variadic: bool,
    /// The native this one is an alias of: `native Email_Close(...) = email_close;`
    /// declares the name a script calls, implemented by the registered native
    /// after the `=`. Comparison follows the `=`, so an include that renames the
    /// whole surface is not reported as drift.
    pub implemented_by: Option<String>,
    /// Whether the argument list is known at all. A `raw` native registers its
    /// name but parses its own arguments, so nothing but the name can be
    /// compared; the include is the only place its shape is written down.
    pub shape_known: bool,
}

/// Something the include and the plugin disagree about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Divergence {
    /// Registered by the plugin, absent from the include — a script calling it
    /// will not compile.
    MissingFromInclude { native: String },
    /// Declared in the include, not registered — a script calling it compiles
    /// and fails at runtime.
    NotRegistered { native: String },
    /// Both sides have it, with a different number of arguments.
    Arity {
        native: String,
        include: usize,
        plugin: usize,
    },
    /// Both sides have it, with a different return tag.
    ReturnTag {
        native: String,
        include: String,
        plugin: String,
    },
    /// A callback the plugin calls that the include does not `forward`: a script
    /// implementing it as `public` would not be called.
    CallbackNotForwarded { callback: String },
    /// The include is a template that does not render — checked here because a
    /// template that cannot be rendered cannot be compared either.
    Template { problem: String },
    /// One argument is declared differently: a tag, a `&`, or a `[]`.
    ArgumentShape {
        native: String,
        position: usize,
        include: Argument,
        plugin: Argument,
    },
}

impl fmt::Display for Divergence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn describe(argument: &Argument) -> String {
            let mut text = String::new();
            if argument.by_reference {
                text.push('&');
            }
            if !argument.tag.is_empty() {
                text.push_str(&argument.tag);
                text.push(':');
            }
            text.push_str("arg");
            if argument.array {
                text.push_str("[]");
            }
            text
        }

        match self {
            Self::MissingFromInclude { native } => write!(
                f,
                "{native} is registered but missing from the include; a script calling it will not compile"
            ),
            Self::NotRegistered { native } => write!(
                f,
                "{native} is declared in the include but not registered; a script calling it fails at runtime"
            ),
            Self::Arity {
                native,
                include,
                plugin,
            } => write!(
                f,
                "{native} takes {plugin} argument(s), the include declares {include}"
            ),
            Self::ReturnTag {
                native,
                include,
                plugin,
            } => {
                let shown = |tag: &str| {
                    if tag.is_empty() {
                        "untagged".into()
                    } else {
                        format!("{tag}:")
                    }
                };
                write!(
                    f,
                    "{native} returns {}, the include declares {}",
                    shown(plugin),
                    shown(include)
                )
            }
            Self::CallbackNotForwarded { callback } => write!(
                f,
                "{callback} is called by the plugin but the include does not forward it; \
                 a script implementing it as `public` would never be called"
            ),
            Self::Template { problem } => write!(f, "{problem}"),
            Self::ArgumentShape {
                native,
                position,
                include,
                plugin,
            } => write!(
                f,
                "{native} argument {position} is {}, the include declares {}",
                describe(plugin),
                describe(include)
            ),
        }
    }
}

/// Strips `//` and `/* */` comments, so a commented-out declaration is not read
/// as one.
fn without_comments(source: &str) -> String {
    let mut out = String::with_capacity(source.len());
    let mut chars = source.chars().peekable();
    let mut in_block = false;

    while let Some(c) = chars.next() {
        if in_block {
            if c == '*' && chars.peek() == Some(&'/') {
                chars.next();
                in_block = false;
            }
            continue;
        }
        match (c, chars.peek()) {
            ('/', Some('/')) => {
                for c in chars.by_ref() {
                    if c == '\n' {
                        out.push('\n');
                        break;
                    }
                }
            }
            ('/', Some('*')) => {
                chars.next();
                in_block = true;
            }
            _ => out.push(c),
        }
    }
    out
}

/// Splits an argument list at top-level commas, ignoring those inside braces or
/// parentheses — `{Float,_}:...` and `sizeof(a,b)` are single arguments.
fn split_arguments(list: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut depth = 0i32;
    let mut current = String::new();

    for c in list.chars() {
        match c {
            '{' | '(' | '[' => {
                depth += 1;
                current.push(c);
            }
            '}' | ')' | ']' => {
                depth -= 1;
                current.push(c);
            }
            ',' if depth == 0 => parts.push(std::mem::take(&mut current)),
            _ => current.push(c),
        }
    }
    if !current.trim().is_empty() {
        parts.push(current);
    }
    parts
}

/// Reads one argument, dropping what only a hand-written include can say.
fn parse_argument(text: &str) -> Option<Argument> {
    // A default value is the include's business, not the plugin's.
    let text = text.split('=').next().unwrap_or(text).trim();
    let text = text.trim_start_matches("const").trim();
    // `...`, alone or tagged as `{Float,_}:...`, marks varargs, not an argument.
    if text.is_empty() || text.contains("...") {
        return None;
    }

    let by_reference = text.starts_with('&');
    let text = text.trim_start_matches('&').trim();

    let (tag, rest) = match text.split_once(':') {
        // `{Float,_}:...` is the varargs form, which carries no single tag.
        Some((tag, rest)) if !tag.starts_with('{') => (tag.trim().to_lowercase(), rest),
        _ => (String::new(), text),
    };

    Some(Argument {
        tag,
        by_reference,
        array: rest.contains('['),
    })
}

/// Every `native` declaration in `source`.
///
/// Understands what a hand-written include contains: comments, default values,
/// size expressions, varargs, and declarations spread over several lines.
#[must_use]
pub fn parse(source: &str) -> Vec<Declaration> {
    parse_declarations(source, "native ")
}

/// Reads every declaration introduced by `keyword` (`native ` or `forward `).
fn parse_declarations(source: &str, keyword: &str) -> Vec<Declaration> {
    let cleaned = without_comments(source);
    let mut declarations = Vec::new();
    let mut rest = cleaned.as_str();

    while let Some(start) = rest.find(keyword) {
        rest = &rest[start + keyword.len()..];
        let Some(open) = rest.find('(') else { break };
        let Some(close) = rest.find(')') else { break };
        if close < open {
            continue;
        }

        let head = rest[..open].trim();
        let (tag, name) = match head.rsplit_once(':') {
            Some((tag, name)) => (tag.trim().to_lowercase(), name.trim()),
            None => (String::new(), head),
        };
        if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            rest = &rest[close..];
            continue;
        }

        // `native Alias(...) = real_name;` — everything up to the `;` after the
        // argument list, which is where an alias is written.
        let tail = &rest[close + 1..];
        let tail = &tail[..tail.find(';').unwrap_or(0)];
        let tail_len = tail.len();
        let implemented_by = tail
            .split_once('=')
            .map(|(_, target)| target.trim().to_string())
            .filter(|target| {
                !target.is_empty() && target.chars().all(|c| c.is_alphanumeric() || c == '_')
            });

        let list = &rest[open + 1..close];
        let variadic = list.contains("...");
        let arguments = split_arguments(list)
            .iter()
            .filter_map(|argument| parse_argument(argument))
            .collect();

        declarations.push(Declaration {
            name: name.to_string(),
            tag,
            arguments,
            variadic,
            implemented_by,
            shape_known: true,
        });
        rest = &rest[close + 1 + tail_len..];
    }
    declarations
}

/// Every `forward` declaration in `source`.
///
/// A script implements a plugin's callbacks as `public`, and the include is
/// where they are `forward`ed. Parsed the same way natives are, so the same
/// tolerance applies: comments, defaults and several lines.
#[must_use]
pub fn parse_forwards(source: &str) -> Vec<Declaration> {
    parse_declarations(source, "forward ")
}

/// Compares an include's text with the natives this plugin registered.
///
/// Findings come back in a stable order: what is missing, what is extra, then
/// the mismatches, each sorted by native name, so a CI job's output does not
/// churn between runs.
#[must_use]
pub fn compare(include_source: &str) -> Vec<Divergence> {
    compare_with(include_source, &crate::plugin::native_decls())
}

/// Renders an include from a name and declarations, no server involved.
///
/// The counterpart of [`compare_with`] for generating rather than checking: a
/// plugin can write its `.inc` from a test, instead of starting a server with
/// `SAMP_PAWN_INCLUDE` set.
#[must_use]
pub fn render(plugin_name: &str, decls: &[&str]) -> String {
    crate::plugin::render_include(plugin_name, decls)
}

/// Reads the declarations `#[native]` derived, as produced by the
/// `pawn_native_decls()` the plugin macro generates.
///
/// A `raw` native comes rendered commented out, its arity not being in the Rust
/// signature. The name is still registered, so it is read back here and marked
/// [`Declaration::shape_known`] `false` — its presence is compared, its shape is
/// not.
#[must_use]
pub fn registered(decls: &[&str]) -> Vec<Declaration> {
    decls
        .iter()
        .filter_map(|decl| {
            let (source, shape_known) = match decl.trim_start().strip_prefix("//") {
                Some(rest) => (rest.trim_start(), false),
                None => (*decl, true),
            };
            let mut parsed = parse(source).into_iter().next()?;
            parsed.shape_known = shape_known;
            Some(parsed)
        })
        .collect()
}

/// Compares an include with declarations in hand, no server involved.
///
/// This is the form a CI job wants: pass the `pawn_native_decls()` the plugin
/// macro generates and the check runs in `cargo test`.
#[must_use]
pub fn compare_with(include_source: &str, decls: &[&str]) -> Vec<Divergence> {
    // A template is checked as what it renders to: its declarations come from
    // the same place, so the comparison is about the hand-written ones around
    // them — and a template that will not render is worth hearing about here too.
    let rendered = if include_source.contains("{{") {
        match Template::new(include_source, decls).render() {
            Ok(rendered) => rendered,
            Err(errors) => {
                return errors
                    .into_iter()
                    .map(|e| Divergence::Template {
                        problem: e.to_string(),
                    })
                    .collect();
            }
        }
    } else {
        include_source.to_string()
    };

    let mut findings = compare_declarations(&parse(&rendered), &registered(decls));
    findings.extend(missing_forwards(
        &rendered,
        &crate::runtime::Runtime::try_get()
            .map(|rt| rt.callback_decls().to_vec())
            .unwrap_or_default(),
    ));
    findings
}

/// Callbacks the plugin calls that the include does not `forward`.
///
/// The names are compared, not the arguments: a callback's signature lives in
/// the declaration the plugin wrote, and a script may legitimately forward it
/// with its own argument names.
#[must_use]
pub fn missing_forwards(include_source: &str, callbacks: &[&str]) -> Vec<Divergence> {
    let forwarded = parse_forwards(include_source);
    let mut missing: Vec<String> = callbacks
        .iter()
        .filter_map(|declared| {
            let name = declared
                .trim()
                .split('(')
                .next()
                .unwrap_or("")
                .trim()
                .to_string();
            (!name.is_empty() && !forwarded.iter().any(|f| f.name == name)).then_some(name)
        })
        .collect();
    missing.sort();

    missing
        .into_iter()
        .map(|callback| Divergence::CallbackNotForwarded { callback })
        .collect()
}

/// Reads `path` and compares it with declarations in hand.
///
/// # Errors
/// Propagates the [`std::io::Error`] when the file cannot be read.
pub fn compare_file_with(
    path: impl AsRef<Path>,
    decls: &[&str],
) -> std::io::Result<Vec<Divergence>> {
    Ok(compare_with(&std::fs::read_to_string(path)?, decls))
}

/// Reads `path` and compares it with the registered natives.
///
/// # Errors
/// Propagates the [`std::io::Error`] when the file cannot be read.
pub fn compare_file(path: impl AsRef<Path>) -> std::io::Result<Vec<Divergence>> {
    Ok(compare(&std::fs::read_to_string(path)?))
}

/// The comparison itself, over two parsed lists — the part worth testing
/// without a plugin behind it.
#[must_use]
pub fn compare_declarations(
    declared: &[Declaration],
    registered: &[Declaration],
) -> Vec<Divergence> {
    // What the plugin registered is the name after an `=`, when there is one,
    // and the declared name otherwise.
    fn implementing(declaration: &Declaration) -> &str {
        declaration
            .implemented_by
            .as_deref()
            .unwrap_or(&declaration.name)
    }

    let mut findings = Vec::new();

    let mut missing: Vec<&Declaration> = registered
        .iter()
        .filter(|r| !declared.iter().any(|d| implementing(d) == r.name))
        .collect();
    missing.sort_by(|a, b| a.name.cmp(&b.name));
    findings.extend(missing.into_iter().map(|r| Divergence::MissingFromInclude {
        native: r.name.clone(),
    }));

    let mut extra: Vec<&Declaration> = declared
        .iter()
        .filter(|d| !registered.iter().any(|r| r.name == implementing(d)))
        .collect();
    extra.sort_by(|a, b| a.name.cmp(&b.name));
    findings.extend(extra.into_iter().map(|d| Divergence::NotRegistered {
        native: d.name.clone(),
    }));

    let mut shared: Vec<(&Declaration, &Declaration)> = declared
        .iter()
        .filter_map(|d| {
            registered
                .iter()
                .find(|r| r.name == implementing(d))
                .map(|r| (d, r))
        })
        .collect();
    shared.sort_by(|a, b| a.0.name.cmp(&b.0.name));

    for (include, plugin) in shared {
        // A raw native wrote down neither its arguments nor, reliably, more
        // than its name: only the include states its shape.
        if !plugin.shape_known {
            continue;
        }
        if include.tag != plugin.tag {
            findings.push(Divergence::ReturnTag {
                native: include.name.clone(),
                include: include.tag.clone(),
                plugin: plugin.tag.clone(),
            });
        }

        // A variadic declaration is open-ended on purpose, so only the
        // arguments it does name are compared.
        if !include.variadic && include.arguments.len() != plugin.arguments.len() {
            findings.push(Divergence::Arity {
                native: include.name.clone(),
                include: include.arguments.len(),
                plugin: plugin.arguments.len(),
            });
        }

        for (position, (declared_arg, registered_arg)) in include
            .arguments
            .iter()
            .zip(plugin.arguments.iter())
            .enumerate()
        {
            if declared_arg != registered_arg {
                findings.push(Divergence::ArgumentShape {
                    native: include.name.clone(),
                    position: position + 1,
                    include: declared_arg.clone(),
                    plugin: registered_arg.clone(),
                });
            }
        }
    }
    findings
}

/// Reads a path from `var`, honouring a per-plugin selector.
///
/// The environment belongs to the whole process, and a server can have several
/// Rust plugins loaded, each with its own include — pointed at one path, they
/// would overwrite each other's file. So a value may name the plugin it is for:
///
/// ```text
/// SAMP_PAWN_INCLUDE=counter.inc                     # whichever plugin reads it
/// SAMP_PAWN_INCLUDE=counter=counter.inc,email_samp=email.inc
/// ```
///
/// A bare path applies to every plugin, which is what a single-plugin setup
/// wants. With selectors, a plugin not named takes nothing.
pub(crate) fn path_for_plugin(var: &str) -> Option<std::ffi::OsString> {
    let value = std::env::var_os(var)?;
    let text = value.to_string_lossy();

    // A Windows path (`C:\...`) has no `=`; a selector always does.
    if !text.contains('=') {
        return Some(value);
    }

    let plugin = crate::runtime::Runtime::try_get().map_or("plugin", |rt| rt.plugin_name());
    for entry in text.split(',') {
        if let Some((name, path)) = entry.split_once('=')
            && name.trim() == plugin
        {
            return Some(std::ffi::OsString::from(path.trim()));
        }
    }
    None
}

/// Renders `template` into `out`, for the `SAMP_PAWN_INCLUDE_TEMPLATE` path.
///
/// Values for placeholders beyond the built-in ones come from the environment:
/// `SAMP_PAWN_VAR_RELEASED=2026-09-26` supplies `{{RELEASED}}`. That keeps the
/// generation usable with no code at all — start the server once with the two
/// variables set — while a plugin that wants more control uses [`Template`]
/// from a test.
///
/// Every failure is logged and otherwise ignored: producing a development
/// artifact must never take the server down.
pub(crate) fn write_from_template(template: &std::ffi::OsStr, out: &std::ffi::OsStr) {
    let shown = template.to_string_lossy().into_owned();

    let source = match std::fs::read_to_string(template) {
        Ok(source) => source,
        Err(e) => {
            crate::macros::sdk_warn!("could not read {shown}: {e}");
            return;
        }
    };

    let decls = crate::plugin::native_decls();
    let mut rendering = Template::new(&source, &decls);
    for (key, value) in std::env::vars() {
        if let Some(name) = key.strip_prefix("SAMP_PAWN_VAR_") {
            rendering = rendering.var(name, value);
        }
    }

    match rendering.write(out) {
        Ok(()) => crate::macros::sdk_info!(
            "Pawn include written to {} from {shown}",
            out.to_string_lossy()
        ),
        Err(e) => crate::macros::sdk_warn!("{shown}: {e}"),
    }
}

/// Runs the comparison when `SAMP_PAWN_INCLUDE_CHECK` names an include.
///
/// Called by the SDK right after `on_load`, not from the entry point: the check
/// has nothing but log output to show, and under native open.mp a component's
/// entry point runs before any logger exists, so anything logged there is lost.
///
/// Anything found is logged as a warning; a missing or unreadable file is
/// reported and otherwise ignored, since a development check must never take a
/// server down.
pub(crate) fn check_if_requested() {
    let Some(path) = path_for_plugin("SAMP_PAWN_INCLUDE_CHECK") else {
        return;
    };
    let shown = path.to_string_lossy().into_owned();

    match compare_file(&path) {
        Ok(findings) if findings.is_empty() => {
            crate::macros::sdk_info!("{shown} matches the registered natives");
        }
        Ok(findings) => {
            crate::macros::sdk_warn!("{shown} disagrees with the registered natives:");
            for finding in findings {
                crate::macros::sdk_warn!("  {finding}");
            }
        }
        Err(e) => crate::macros::sdk_warn!("could not read {shown}: {e}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn argument(tag: &str, by_reference: bool, array: bool) -> Argument {
        Argument {
            tag: tag.to_string(),
            by_reference,
            array,
        }
    }

    #[test]
    fn reads_a_plain_declaration() {
        let declarations = parse("native bool:Counter_Get(&out);");
        assert_eq!(declarations.len(), 1);
        assert_eq!(declarations[0].name, "Counter_Get");
        assert_eq!(declarations[0].tag, "bool");
        assert_eq!(declarations[0].arguments, vec![argument("", true, false)]);
    }

    #[test]
    fn ignores_what_only_an_include_can_say() {
        // Defaults, `sizeof`, `const` and documentation are the include's to
        // add; none of them is a divergence.
        let declarations = parse(
            "/* docs */ native bool:email_status(account = 0, dest[], dest_len = sizeof(dest));",
        );
        assert_eq!(declarations.len(), 1);
        assert_eq!(
            declarations[0].arguments,
            vec![
                argument("", false, false),
                argument("", false, true),
                argument("", false, false),
            ]
        );
    }

    #[test]
    fn a_commented_out_declaration_is_not_one() {
        let source = "// native Old_Removed(a);\n/* native Also_Gone(); */\nnative Live(a);";
        let names: Vec<_> = parse(source).into_iter().map(|d| d.name).collect();
        assert_eq!(names, vec!["Live"]);
    }

    #[test]
    fn varargs_leave_the_argument_count_open() {
        let declarations =
            parse("native bool:email_test(account = 0, const format[], {Float,_}:...);");
        assert!(declarations[0].variadic);
        // The varargs marker itself is not an argument.
        assert_eq!(declarations[0].arguments.len(), 2);

        let registered = parse("native bool:email_test(account, const format[], extra1, extra2);");
        // More arguments than the include names is fine: it said "and more".
        assert!(compare_declarations(&declarations, &registered).is_empty());
    }

    #[test]
    fn reports_a_native_the_include_forgot() {
        let findings = compare_declarations(&parse(""), &parse("native Foo(a);"));
        assert_eq!(
            findings,
            vec![Divergence::MissingFromInclude {
                native: "Foo".into()
            }]
        );
        assert!(findings[0].to_string().contains("will not compile"));
    }

    #[test]
    fn reports_a_declaration_with_no_native_behind_it() {
        let findings = compare_declarations(&parse("native Ghost(a);"), &parse(""));
        assert_eq!(
            findings,
            vec![Divergence::NotRegistered {
                native: "Ghost".into()
            }]
        );
        assert!(findings[0].to_string().contains("fails at runtime"));
    }

    #[test]
    fn reports_arity_and_tag_and_shape() {
        let declared = parse("native Foo(a, b);\nnative bool:Bar(x);\nnative Baz(n);");
        let registered = parse("native Foo(a);\nnative Bar(x);\nnative Baz(&Float:n);");
        let findings = compare_declarations(&declared, &registered);

        assert!(findings.contains(&Divergence::Arity {
            native: "Foo".into(),
            include: 2,
            plugin: 1
        }));
        assert!(findings.contains(&Divergence::ReturnTag {
            native: "Bar".into(),
            include: "bool".into(),
            plugin: String::new()
        }));
        assert!(findings.iter().any(|f| matches!(
            f,
            Divergence::ArgumentShape { native, position: 1, .. } if native == "Baz"
        )));
    }

    #[test]
    fn a_raw_native_is_compared_by_name_only() {
        // `raw` natives parse their own arguments, so the include is the only
        // place their shape is written down: presence is checked, shape is not.
        let mut registered = parse("native bool:email_send_to(...);");
        registered[0].shape_known = false;
        let declared = parse(
            "native bool:email_send_to(const to[], const subject[], const body[], {Float,_}:...);",
        );
        assert!(compare_declarations(&declared, &registered).is_empty());

        // Its absence from the include is still reported.
        assert_eq!(
            compare_declarations(&parse(""), &registered),
            vec![Divergence::MissingFromInclude {
                native: "email_send_to".into()
            }]
        );
    }

    #[test]
    fn an_alias_is_matched_by_what_implements_it() {
        // An include may present the whole surface under other names, each
        // aliasing the registered native; that is not drift.
        let declared = parse("native bool:Email_Close(account = 0) = email_close;");
        assert_eq!(declared[0].implemented_by.as_deref(), Some("email_close"));
        assert!(
            compare_declarations(&declared, &parse("native bool:email_close(account);")).is_empty()
        );

        // The shape is still compared, and reported under the declared name.
        let findings = compare_declarations(
            &declared,
            &parse("native bool:email_close(account, force);"),
        );
        assert_eq!(
            findings,
            vec![Divergence::Arity {
                native: "Email_Close".into(),
                include: 1,
                plugin: 2
            }]
        );
    }

    #[test]
    fn an_include_that_matches_reports_nothing() {
        let source = "native bool:Counter_Get(&out);\nnative Counter_Reset();";
        assert!(compare_declarations(&parse(source), &parse(source)).is_empty());
    }

    // -----------------------------------------------------------------------
    // Templates
    // -----------------------------------------------------------------------

    const DECLS: &[&str] = &[
        "native Counter_Increment();",
        "native bool:Counter_Get(&out);",
        "// native Counter_Send(...); // raw native — fill in the arguments",
    ];

    #[test]
    fn the_prose_stays_and_the_declarations_are_filled_in() {
        let template = "\
// My plugin v{{VERSION}}
#if defined {{GUARD}}
    #endinput
#endif
#define {{GUARD}}

// Adds one.
{{NATIVE:Counter_Increment}}

{{NATIVES}}
";
        let out = Template::new(template, DECLS)
            .plugin_name("counter")
            .var("VERSION", "1.2.3")
            .render()
            .expect("the template places every native");

        assert!(out.contains("// My plugin v1.2.3"));
        assert!(out.contains("#define _counter_included"));
        // Placed by name, under its own comment, and not repeated by {{NATIVES}}.
        assert_eq!(out.matches("native Counter_Increment();").count(), 1);
        assert!(out.contains("native bool:Counter_Get(&out);"));
    }

    #[test]
    fn a_native_can_be_placed_under_another_name() {
        let out = Template::new("{{NATIVE:Counter_Get as Counter_Read}}\n{{NATIVES}}", DECLS)
            .render()
            .unwrap();

        assert!(out.contains("native bool:Counter_Read(&out) = Counter_Get;"));
        assert!(
            !out.contains("native bool:Counter_Get(&out);"),
            "the alias replaces the original, it does not add to it"
        );
    }

    #[test]
    fn a_raw_native_can_be_placed_by_name() {
        // Its rendered form is commented out, so a template that only wants the
        // hand-written line places it and writes the arguments itself.
        let out = Template::new("{{NATIVES}}", DECLS).render().unwrap();
        assert!(out.contains("// native Counter_Send(...);"));
    }

    #[test]
    fn a_native_the_template_forgets_is_an_error() {
        let errors = Template::new("{{NATIVE:Counter_Increment}}", DECLS)
            .render()
            .expect_err("two natives are left out");

        assert!(errors.contains(&TemplateError::NativeNotPlaced {
            native: "Counter_Get".into()
        }));
        assert!(errors[0].to_string().contains("{{NATIVES}}"));
    }

    #[test]
    fn a_placeholder_with_nothing_behind_it_is_an_error() {
        let errors = Template::new("{{RELEASED}}{{NATIVES}}", DECLS)
            .render()
            .expect_err("RELEASED was never supplied");

        assert_eq!(
            errors,
            vec![TemplateError::UnknownPlaceholder {
                name: "RELEASED".into()
            }]
        );
    }

    #[test]
    fn naming_a_native_that_does_not_exist_is_an_error() {
        let errors = Template::new("{{NATIVE:Counter_Gone}}{{NATIVES}}", DECLS)
            .render()
            .expect_err("no such native");

        assert!(errors.contains(&TemplateError::UnknownNative {
            native: "Counter_Gone".into()
        }));
    }

    #[test]
    fn an_unclosed_placeholder_is_an_error() {
        let errors = Template::new("{{NATIVES}} and then {{OOPS", DECLS)
            .render()
            .expect_err("the second placeholder never closes");

        assert!(
            errors
                .iter()
                .any(|e| matches!(e, TemplateError::UnclosedPlaceholder { .. }))
        );
    }

    #[test]
    fn version_comes_from_the_plugin_unless_the_caller_says_otherwise() {
        // The version is in every include header, so the SDK fills it in from
        // the plugin crate; passing one takes precedence.
        let out = Template::new("v{{VERSION}}\n{{NATIVES}}", DECLS)
            .var("VERSION", "9.9.9")
            .render()
            .unwrap();

        assert!(out.starts_with("v9.9.9"));
    }

    #[test]
    fn the_last_value_for_a_name_wins() {
        let out = Template::new("{{V}}{{NATIVES}}", DECLS)
            .var("V", "first")
            .var("V", "second")
            .render()
            .unwrap();

        assert!(out.starts_with("second"));
    }

    #[test]
    fn checking_a_template_compares_what_it_renders_to() {
        // The template's own declarations cannot drift; a line written by hand
        // beside them still can.
        let shaped: &[&str] = &[
            "native Counter_Increment();",
            "native bool:Counter_Get(&out);",
        ];
        assert!(compare_with("{{NATIVES}}", shaped).is_empty());

        let with_a_stale_line = "{{NATIVES}}\nnative Counter_Removed(a);";
        assert_eq!(
            compare_with(with_a_stale_line, shaped),
            vec![Divergence::NotRegistered {
                native: "Counter_Removed".into()
            }]
        );
    }

    #[test]
    fn a_raw_native_left_commented_out_is_still_reported_as_missing() {
        // `{{NATIVES}}` emits it as `#[native]` rendered it — commented out —
        // so the include does not declare it. Give the native an `args = "…"`
        // in its attribute, or write the line in the template.
        assert_eq!(
            compare_with("{{NATIVES}}", DECLS),
            vec![Divergence::MissingFromInclude {
                native: "Counter_Send".into()
            }]
        );
    }

    #[test]
    fn a_template_that_will_not_render_is_reported_by_the_check() {
        let findings = compare_with("{{NOPE}}{{NATIVES}}", DECLS);
        assert!(matches!(findings.as_slice(), [Divergence::Template { .. }]));
        assert!(findings[0].to_string().contains("NOPE"));
    }

    // -----------------------------------------------------------------------
    // Pawn documentation comments
    // -----------------------------------------------------------------------

    #[test]
    fn a_rust_doc_becomes_the_format_the_openmp_includes_use() {
        let out = pawndoc(
            "Set a player's position.\n\
             @param playerid The ID of the player\n\
             @param x The x coordinate\n\
             @returns 1 on success, 0 otherwise.\n\
             @remarks Removes the player from any vehicle.\n\
             @seealso GetPlayerPos",
        );

        assert_eq!(
            out,
            "/**\n\
             \x20* <summary>Set a player\'s position.</summary>\n\
             \x20* <param name=\"playerid\">The ID of the player</param>\n\
             \x20* <param name=\"x\">The x coordinate</param>\n\
             \x20* <returns>1 on success, 0 otherwise.</returns>\n\
             \x20* <remarks>Removes the player from any vehicle.</remarks>\n\
             \x20* <seealso name=\"GetPlayerPos\" />\n\
             \x20*/"
        );
    }

    #[test]
    fn pawndoc_written_by_hand_passes_through() {
        // An author who wants the full format — <library>, nested markup —
        // writes it, and it is not touched.
        let out = pawndoc("<library>counter</library>\n<summary>Adds <em>one</em>.</summary>");
        assert!(out.contains("<library>counter</library>"));
        assert!(out.contains("<summary>Adds <em>one</em>.</summary>"));
    }

    #[test]
    fn text_that_would_break_a_tag_is_escaped() {
        let out = pawndoc("True when a < b && c > d.");
        assert!(out.contains("a &lt; b &amp;&amp; c &gt; d"));
    }

    #[test]
    fn an_undocumented_native_produces_no_comment() {
        assert_eq!(pawndoc("   \n  "), "");
    }

    #[test]
    fn a_long_summary_is_wrapped_as_written() {
        let out = pawndoc("First line.\nSecond line.");
        assert!(out.contains(" * <summary>\n *   First line.\n *   Second line.\n * </summary>"));
    }

    #[test]
    fn docs_can_be_placed_on_their_own_or_above_each_declaration() {
        let docs = ["Adds one.\n@returns The new value.", "", ""];

        // On its own, for a template that lays out each native by hand.
        let out = Template::new("{{DOC:Counter_Increment}}\n{{NATIVES}}", DECLS)
            .docs(&docs)
            .render()
            .unwrap();
        assert!(out.contains("<summary>Adds one.</summary>"));
        assert!(out.contains("<returns>The new value.</returns>"));

        // Or above every declaration at once.
        let out = Template::new("{{NATIVES}}", DECLS)
            .docs(&docs)
            .with_docs()
            .render()
            .unwrap();
        let at = out
            .find("<summary>Adds one.</summary>")
            .expect("documented");
        let decl = out.find("native Counter_Increment();").expect("declared");
        assert!(at < decl, "the documentation comes above the declaration");

        // An undocumented native is just its declaration.
        assert!(out.contains("native bool:Counter_Get(&out);"));
    }

    #[test]
    fn callbacks_become_forwards() {
        let out = Template::new("{{CALLBACKS}}\n{{NATIVES}}", DECLS)
            .callbacks(&["OnCounterWorkDone(delay)", "OnCounterMax(value);"])
            .render()
            .unwrap();

        assert!(out.contains("forward OnCounterWorkDone(delay);"));
        // A trailing `;` in the declaration is not doubled.
        assert!(out.contains("forward OnCounterMax(value);"));
        assert!(!out.contains(";;"));
    }

    #[test]
    fn a_callback_the_include_never_forwards_is_reported() {
        // A script would implement it as `public` and never be called.
        let include = "native Counter_Increment();\nforward OnCounterWorkDone(delay);";
        let callbacks = ["OnCounterWorkDone(delay)", "OnCounterMax(value)"];

        assert_eq!(
            missing_forwards(include, &callbacks),
            vec![Divergence::CallbackNotForwarded {
                callback: "OnCounterMax".into()
            }]
        );
        assert!(
            missing_forwards(include, &callbacks)[0]
                .to_string()
                .contains("never be called")
        );
    }

    #[test]
    fn a_forward_is_read_like_a_native_declaration() {
        let forwards = parse_forwards(
            "// forward OnOld(a);\nforward OnCounterWorkDone(delay);\nnative Nope();",
        );
        let names: Vec<_> = forwards.into_iter().map(|f| f.name).collect();
        assert_eq!(names, vec!["OnCounterWorkDone"]);
    }

    #[test]
    fn stock_functions_and_macros_in_a_template_are_left_alone() {
        // An include carries hand-written Pawn too — a `stock` helper, a macro
        // shorthand. Neither is a declaration, and neither is drift.
        let include = "\
#define Counter::%0(%1) forward %0(%1); public %0(%1)
stock Counter_Double(v) { return v * 2; }
native Counter_Increment();
";
        let names: Vec<_> = parse(include).into_iter().map(|d| d.name).collect();
        assert_eq!(names, vec!["Counter_Increment"]);
        assert!(compare_with(include, &["native Counter_Increment();"]).is_empty());
    }

    #[test]
    fn placing_the_same_native_twice_is_an_error() {
        let errors = Template::new(
            "{{NATIVE:Counter_Increment}}{{NATIVE:Counter_Increment}}{{NATIVES}}",
            DECLS,
        )
        .render()
        .expect_err("Pawn would reject the second declaration");

        assert!(errors.contains(&TemplateError::PlacedTwice {
            native: "Counter_Increment".into()
        }));
    }

    #[test]
    fn an_alias_beside_the_original_is_not_a_duplicate() {
        Template::new(
            "{{NATIVE:Counter_Get}}{{NATIVE:Counter_Get as Counter_Read}}{{NATIVES}}",
            DECLS,
        )
        .render()
        .expect("two names, two declarations, no clash");
    }

    #[test]
    fn an_env_path_can_name_the_plugin_it_is_for() {
        // Several Rust plugins on one server read the same variable, so a value
        // may say which plugin each path is for. A bare path is for everyone.
        const VAR: &str = "SAMP_PAWN_INCLUDE_TEST_PATH";
        let _fixture = crate::test_support::exclusive();

        // SAFETY: the fixture's lock keeps this the only test touching the
        // environment, and the variable is this test's own.
        unsafe { std::env::set_var(VAR, "plain.inc") };
        assert_eq!(path_for_plugin(VAR).unwrap(), "plain.inc");

        unsafe { std::env::set_var(VAR, "counter=counter.inc, other=other.inc") };
        let plugin = crate::runtime::Runtime::try_get().map_or("plugin", |rt| rt.plugin_name());
        assert_eq!(
            path_for_plugin(VAR),
            None,
            "the test plugin ({plugin}) is not named, so it takes nothing"
        );

        unsafe { std::env::set_var(VAR, format!("{plugin}=mine.inc,other=other.inc")) };
        assert_eq!(path_for_plugin(VAR).unwrap(), "mine.inc");

        unsafe { std::env::remove_var(VAR) };
        assert_eq!(path_for_plugin(VAR), None);
    }

    #[test]
    fn findings_come_back_in_a_stable_order() {
        let registered = parse("native Zeta();\nnative Alpha();");
        let findings = compare_declarations(&parse(""), &registered);
        let names: Vec<_> = findings
            .iter()
            .map(|f| match f {
                Divergence::MissingFromInclude { native } => native.clone(),
                _ => unreachable!(),
            })
            .collect();
        assert_eq!(names, vec!["Alpha", "Zeta"]);
    }
}

// ---------------------------------------------------------------------------
// Generating from a template
// ---------------------------------------------------------------------------

/// Why a template could not be rendered.
///
/// Each variant is a mistake that would otherwise ship as a broken include, so
/// rendering reports it instead of guessing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TemplateError {
    /// `{{SOMETHING}}` with no value behind it.
    UnknownPlaceholder { name: String },
    /// `{{NATIVE:Name}}` naming a native the plugin does not register.
    UnknownNative { native: String },
    /// A registered native that no placeholder emits, with no `{{NATIVES}}` to
    /// collect it: it would be missing from the include.
    NativeNotPlaced { native: String },
    /// A `{{` with no `}}` after it.
    UnclosedPlaceholder { at: usize },
    /// The same declaration emitted twice: Pawn rejects the second as a symbol
    /// that is already defined.
    PlacedTwice { native: String },
}

impl fmt::Display for TemplateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownPlaceholder { name } => {
                write!(
                    f,
                    "{{{{{name}}}}} has no value; pass it with .var(\"{name}\", …)"
                )
            }
            Self::UnknownNative { native } => {
                write!(
                    f,
                    "{{{{NATIVE:{native}}}}} names a native this plugin does not register"
                )
            }
            Self::NativeNotPlaced { native } => write!(
                f,
                "{native} is registered but the template never places it; \
                 name it with {{{{NATIVE:{native}}}}} or add {{{{NATIVES}}}}"
            ),
            Self::PlacedTwice { native } => write!(
                f,
                "{native} is placed twice; Pawn rejects the second declaration as \
                 an already defined symbol"
            ),
            Self::UnclosedPlaceholder { at } => {
                write!(
                    f,
                    "a placeholder opened at byte {at} is never closed with }}}}"
                )
            }
        }
    }
}

/// A Pawn include written by hand, with the declarations filled in.
///
/// The prose, the sections, the constants and the callback documentation stay in
/// the template, where they belong; every `native` line comes from the Rust
/// signature, so it cannot drift. This is the middle ground between generating
/// the whole file — which throws the documentation away — and maintaining it by
/// hand, which drifts.
///
/// Placeholders, all written `{{NAME}}`:
///
/// | Placeholder | Becomes |
/// | ----------- | ------- |
/// | `{{NATIVES}}` | every declaration not placed individually, in registration order |
/// | `{{NATIVE:Name}}` | that one declaration |
/// | `{{NATIVE:Name as Alias}}` | `native Alias(…) = Name;`, the aliased form |
/// | `{{PLUGIN}}` | the plugin's crate name |
/// | `{{GUARD}}` | `_<plugin>_included`, the usual include guard symbol |
/// | anything else | what [`Template::var`] supplied, or an error |
///
/// ```rust,no_run
/// # fn pawn_native_decls() -> Vec<&'static str> { vec![] }
/// # fn example() -> std::io::Result<()> {
/// let template = std::fs::read_to_string("include/my_plugin.inc.in")?;
///
/// samp::pawn_include::Template::new(&template, &pawn_native_decls())
///     .var("VERSION", env!("CARGO_PKG_VERSION"))
///     .write("include/my_plugin.inc")
///     .expect("the template and the natives agree");
/// # Ok(())
/// # }
/// ```
///
/// A native the template never places is an error, not a silent omission: that
/// is the drift this exists to prevent.
pub struct Template<'a> {
    source: &'a str,
    /// Callbacks the plugin says it calls, for `{{CALLBACKS}}`.
    callbacks: Vec<String>,
    /// Doc comment of each native, aligned with `natives`.
    docs: Vec<String>,
    /// Whether a placed declaration is preceded by its documentation.
    with_docs: bool,
    /// Each declaration as `#[native]` rendered it, paired with the native's
    /// name. Kept side by side so a placeholder naming one and `{{NATIVES}}`
    /// collecting the rest agree on which is which.
    natives: Vec<(String, String)>,
    vars: Vec<(String, String)>,
    plugin_name: String,
}

impl<'a> Template<'a> {
    /// Takes the template's text and the declarations to place into it, as
    /// `pawn_native_decls()` produces them.
    #[must_use]
    pub fn new(source: &'a str, decls: &[&str]) -> Self {
        let natives = decls
            .iter()
            .map(|decl| {
                // A `raw` native comes rendered commented out; its name is still
                // in there, and placing it by name is how a template gives it
                // the argument list the signature does not have.
                let body = decl.trim_start().trim_start_matches("//").trim_start();
                let name = parse(body)
                    .first()
                    .map(|d| d.name.clone())
                    .unwrap_or_default();
                ((*decl).to_string(), name)
            })
            .collect();

        Self {
            source,
            docs: crate::runtime::Runtime::try_get()
                .map(|rt| rt.native_docs().iter().map(|d| (*d).to_string()).collect())
                .unwrap_or_default(),
            with_docs: false,
            natives,
            callbacks: crate::runtime::Runtime::try_get()
                .map(|rt| {
                    rt.callback_decls()
                        .iter()
                        .map(|c| (*c).to_string())
                        .collect()
                })
                .unwrap_or_default(),
            vars: Vec::new(),
            plugin_name: String::new(),
        }
    }

    /// Supplies one `{{NAME}}`. The last value for a name wins.
    #[must_use]
    pub fn var(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.vars.push((name.into(), value.into()));
        self
    }

    /// The doc comment of each native, in the order the declarations came.
    ///
    /// Defaults to what `#[native]` captured from the Rust doc comments, so this
    /// is for generating an include without a plugin loaded — from a test.
    #[must_use]
    pub fn docs(mut self, docs: &[&str]) -> Self {
        self.docs = docs.iter().map(|d| (*d).to_string()).collect();
        self
    }

    /// Puts each native's documentation above its declaration, as a Pawn
    /// documentation comment.
    ///
    /// Off by default: a template that documents each native in its own prose
    /// should not get a second copy. With it on, the documentation lives once,
    /// next to the Rust code. `{{DOC:Name}}` places one on its own either way.
    #[must_use]
    pub fn with_docs(mut self) -> Self {
        self.with_docs = true;
        self
    }

    /// The callbacks `{{CALLBACKS}}` should forward.
    ///
    /// Defaults to what `initialize_plugin!` declared in `callbacks: [...]`, so
    /// this is for generating an include without a plugin loaded — from a test.
    #[must_use]
    pub fn callbacks(mut self, callbacks: &[&str]) -> Self {
        self.callbacks = callbacks.iter().map(|c| (*c).to_string()).collect();
        self
    }

    /// Names the plugin, for `{{PLUGIN}}` and `{{GUARD}}`.
    ///
    /// Defaults to the name the plugin registered, which is its crate name.
    #[must_use]
    pub fn plugin_name(mut self, name: impl Into<String>) -> Self {
        self.plugin_name = name.into();
        self
    }

    /// Renders the include.
    ///
    /// # Errors
    /// Returns every [`TemplateError`] found, in the order they were met, so one
    /// pass names all of them rather than one per run.
    pub fn render(&self) -> Result<String, Vec<TemplateError>> {
        let mut out = String::with_capacity(self.source.len() + 256);
        let mut errors = Vec::new();
        let mut placed: Vec<usize> = Vec::new();
        let mut emitted: Vec<String> = Vec::new();
        let mut rest = self.source;
        let mut consumed = 0usize;

        while let Some(open) = rest.find("{{") {
            out.push_str(&rest[..open]);
            let after = &rest[open + 2..];

            let Some(close) = after.find("}}") else {
                errors.push(TemplateError::UnclosedPlaceholder {
                    at: consumed + open,
                });
                break;
            };

            let name = after[..close].trim();
            match self.expand(name, &mut placed) {
                Ok(text) => {
                    // The same native under the same name twice is a Pawn error,
                    // and the template is where it can still be caught.
                    for declared in parse(&text) {
                        if emitted.contains(&declared.name) {
                            errors.push(TemplateError::PlacedTwice {
                                native: declared.name.clone(),
                            });
                        } else {
                            emitted.push(declared.name);
                        }
                    }
                    out.push_str(&text);
                }
                Err(e) => errors.push(e),
            }

            consumed += open + 2 + close + 2;
            rest = &after[close + 2..];
        }

        if errors.is_empty() {
            out.push_str(rest);
        }

        // Everything not placed by name goes where `{{NATIVES}}` asked for it,
        // and if nothing did, its absence is the error worth reporting.
        for (i, (_, name)) in self.natives.iter().enumerate() {
            if !placed.contains(&i) {
                errors.push(TemplateError::NativeNotPlaced {
                    native: name.clone(),
                });
            }
        }

        if errors.is_empty() {
            Ok(out)
        } else {
            Err(errors)
        }
    }

    /// Renders and writes the include to `path`.
    ///
    /// # Errors
    /// The template's own errors, or the [`std::io::Error`] from writing.
    pub fn write(&self, path: impl AsRef<Path>) -> Result<(), WriteError> {
        let rendered = self.render().map_err(WriteError::Template)?;
        std::fs::write(path, rendered).map_err(WriteError::Io)
    }

    /// Expands one placeholder, recording which declarations it consumed.
    fn expand(&self, name: &str, placed: &mut Vec<usize>) -> Result<String, TemplateError> {
        if name == "NATIVES" {
            let mut lines = Vec::new();
            for i in 0..self.natives.len() {
                if !placed.contains(&i) {
                    placed.push(i);
                    lines.push(self.declaration(i, None));
                }
            }
            // Documented declarations are blocks, so they read better separated.
            let separator = if self.with_docs { "\n\n" } else { "\n" };
            return Ok(lines.join(separator));
        }

        if let Some(spec) = name.strip_prefix("NATIVE:") {
            let (native, alias) = match spec.split_once(" as ") {
                Some((native, alias)) => (native.trim(), Some(alias.trim())),
                None => (spec.trim(), None),
            };
            let Some(i) = self.natives.iter().position(|(_, name)| name == native) else {
                return Err(TemplateError::UnknownNative {
                    native: native.to_string(),
                });
            };
            if !placed.contains(&i) {
                placed.push(i);
            }
            return Ok(self.declaration(i, alias));
        }

        if let Some(native) = name.strip_prefix("DOC:") {
            let native = native.trim();
            let Some(i) = self.natives.iter().position(|(_, name)| name == native) else {
                return Err(TemplateError::UnknownNative {
                    native: native.to_string(),
                });
            };
            return Ok(pawndoc(self.docs.get(i).map_or("", String::as_str)));
        }

        if name == "CALLBACKS" {
            return Ok(self
                .callbacks
                .iter()
                .map(|c| format!("forward {};", c.trim().trim_end_matches(';')))
                .collect::<Vec<_>>()
                .join("\n"));
        }
        if name == "PLUGIN" {
            return Ok(self.name());
        }
        // `{{VERSION}}` is the plugin crate's version unless the caller
        // supplied one: it is in every include header, and the SDK knows it.
        if name == "VERSION"
            && !self.vars.iter().any(|(key, _)| key == "VERSION")
            && let Some(rt) = crate::runtime::Runtime::try_get()
        {
            return Ok(rt.plugin_version().to_string());
        }
        if name == "GUARD" {
            return Ok(guard_symbol(&self.name()));
        }

        self.vars
            .iter()
            .rev()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value.clone())
            .ok_or_else(|| TemplateError::UnknownPlaceholder {
                name: name.to_string(),
            })
    }

    /// Declaration `i`, under `alias` if given, with its documentation above it
    /// when the template asked for documentation.
    fn declaration(&self, i: usize, alias: Option<&str>) -> String {
        let (decl, native) = &self.natives[i];
        let line = match alias {
            Some(alias) => alias_line(decl, native, alias),
            None => decl.clone(),
        };

        if !self.with_docs {
            return line;
        }
        match pawndoc(self.docs.get(i).map_or("", String::as_str)) {
            doc if doc.is_empty() => line,
            doc => format!("{doc}\n{line}"),
        }
    }

    fn name(&self) -> String {
        if self.plugin_name.is_empty() {
            crate::runtime::Runtime::try_get()
                .map_or_else(|| String::from("plugin"), |rt| rt.plugin_name().to_string())
        } else {
            self.plugin_name.clone()
        }
    }
}

/// A template that could not be rendered, or could not be written.
#[derive(Debug)]
pub enum WriteError {
    Template(Vec<TemplateError>),
    Io(std::io::Error),
}

impl fmt::Display for WriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Template(errors) => {
                writeln!(f, "the template could not be rendered:")?;
                for e in errors {
                    writeln!(f, "  {e}")?;
                }
                Ok(())
            }
            Self::Io(e) => write!(f, "{e}"),
        }
    }
}

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

/// Renders a Rust doc comment as a Pawn documentation comment.
///
/// Pawn's own documentation format — what the open.mp includes use and what
/// `pawncc -r` reads — is a `/** */` block of XML tags:
///
/// ```text
/// /**
///  * <summary>Set a player's position.</summary>
///  * <param name="playerid">The ID of the player</param>
///  * <returns>1 on success, 0 otherwise.</returns>
///  */
/// ```
///
/// The mapping from the Rust side stays close to how one writes Rust docs:
///
/// - the text becomes `<summary>`;
/// - `@param name text` becomes `<param name="name">text</param>`;
/// - `@returns`, `@remarks` and `@seealso` become those tags;
/// - a line already starting with `<` passes through untouched, so an author who
///   wants full pawndoc — `<library>`, `<em>`, nested markup — just writes it.
///
/// Text that is not passed through has `&`, `<` and `>` escaped, so a doc
/// mentioning `a < b` cannot produce a broken tag.
#[must_use]
pub fn pawndoc(doc: &str) -> String {
    if doc.trim().is_empty() {
        return String::new();
    }

    fn escape(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
    }

    let mut summary: Vec<String> = Vec::new();
    let mut tagged: Vec<String> = Vec::new();

    for line in doc.lines() {
        let line = line.trim_end();
        let trimmed = line.trim_start();

        if trimmed.starts_with('<') {
            tagged.push(trimmed.to_string());
        } else if let Some(rest) = trimmed.strip_prefix("@param ") {
            let (name, text) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
            tagged.push(format!(
                "<param name=\"{}\">{}</param>",
                escape(name),
                escape(text.trim())
            ));
        } else if let Some(rest) = trimmed.strip_prefix("@returns ") {
            tagged.push(format!("<returns>{}</returns>", escape(rest.trim())));
        } else if let Some(rest) = trimmed.strip_prefix("@remarks ") {
            tagged.push(format!("<remarks>{}</remarks>", escape(rest.trim())));
        } else if let Some(rest) = trimmed.strip_prefix("@seealso ") {
            tagged.push(format!("<seealso name=\"{}\" />", escape(rest.trim())));
        } else if !trimmed.is_empty() || !summary.is_empty() {
            summary.push(escape(trimmed));
        }
    }

    while summary.last().is_some_and(|l| l.is_empty()) {
        summary.pop();
    }

    let mut body: Vec<String> = Vec::new();
    if !summary.is_empty() {
        // A one-line summary stays on one line, which is how the open.mp
        // includes read; a longer one is wrapped as written.
        if summary.len() == 1 {
            body.push(format!("<summary>{}</summary>", summary[0]));
        } else {
            body.push("<summary>".to_string());
            body.extend(summary.iter().map(|l| format!("  {l}")));
            body.push("</summary>".to_string());
        }
    }
    body.extend(tagged);

    let mut out = String::from("/**\n");
    for line in body {
        if line.is_empty() {
            out.push_str(" *\n");
        } else {
            out.push_str(&format!(" * {line}\n"));
        }
    }
    out.push_str(" */");
    out
}

/// Turns a declaration into its aliased form: `native Alias(…) = original;`.
fn alias_line(decl: &str, native: &str, alias: &str) -> String {
    let renamed = decl.replacen(native, alias, 1);
    match renamed.rfind(';') {
        Some(at) => format!("{} = {native};", &renamed[..at]),
        None => renamed,
    }
}

/// The include guard a plugin name produces, with what Pawn rejects replaced.
fn guard_symbol(plugin_name: &str) -> String {
    let body: String = plugin_name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();
    format!("_{body}_included")
}