vdev 0.3.12

CLI utilities for Vector (vector.dev) development and CI workflows
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
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
//! Walks `src/**/*.rs` and `lib/**/*.rs`, extracts internal-event definitions
//! and `tracing` log calls via `syn`'s AST, and validates them against the
//! rules in `docs/specs/instrumentation.md`. Macro argument scraping (the
//! contents of `counter!(...)`, `trace!(...)`, etc.) uses small targeted
//! regexes on the macro's already-tokenised input — never on raw source.

#![allow(clippy::print_stdout, clippy::print_stderr)]

use std::{
    collections::{BTreeMap, HashMap},
    fs,
    path::PathBuf,
    process,
    sync::LazyLock,
};

use anyhow::Result;
use convert_case::{Case, Casing};
use glob::glob;
use proc_macro2::TokenStream;
use quote::ToTokens;
use regex::Regex;
use syn::{
    ItemImpl, ItemStruct, Type,
    spanned::Spanned,
    visit::{self, Visit},
};

const BYTE_SIZE_COUNT: &[&str] = &["byte_size", "count"];

const METRIC_NAME_EVENTS_DROPPED: &str = "component_discarded_events_total";
const METRIC_NAME_ERROR: &str = "component_errors_total";

struct EventClass {
    /// Required log message text for events with this suffix.
    message: &'static str,
    /// Counter suffixes (full name is `component_<suffix>_total`).
    counters: &'static [&'static str],
    /// Tags that must appear on logs and on counters (minus `BYTE_SIZE_COUNT`).
    additional_tags: &'static [&'static str],
}

const EVENT_CLASSES: &[(&str, EventClass)] = &[
    (
        "BytesReceived",
        EventClass {
            message: "Bytes received.",
            counters: &["received_bytes"],
            additional_tags: &["byte_size", "protocol"],
        },
    ),
    (
        "EventsReceived",
        EventClass {
            message: "Events received.",
            counters: &["received_events", "received_event_bytes"],
            additional_tags: &["count", "byte_size"],
        },
    ),
    (
        "EventsSent",
        EventClass {
            message: "Events sent.",
            counters: &["sent_events", "sent_event_bytes"],
            additional_tags: &["count", "byte_size"],
        },
    ),
    (
        "BytesSent",
        EventClass {
            message: "Bytes sent.",
            counters: &["sent_bytes"],
            additional_tags: &["byte_size", "protocol"],
        },
    ),
];

#[derive(Debug, Default, Clone)]
struct SkipFlags {
    dropped_events: bool,
    duplicate_check: bool,
    validity_check: bool,
}

#[derive(Debug, Default, Clone)]
struct Event {
    path: Option<String>,
    skip: SkipFlags,
    emits_component_events_dropped: bool,
    members: BTreeMap<String, String>,
    counters: BTreeMap<String, BTreeMap<String, String>>,
    metrics: BTreeMap<String, BTreeMap<String, String>>,
    logs: Vec<LogCall>,
    uses: u32,
    internal_impl: bool,
    register_impl: Option<String>,
    impl_event_handle: bool,
    reports: Vec<String>,
}

#[derive(Debug, Clone)]
struct LogCall {
    level: String,
    message: String,
    parameters: Vec<String>,
}

impl Event {
    fn add_metric(&mut self, ty: &str, name: &str, tags: BTreeMap<String, String>) {
        let key = format!("{ty}:{name}");
        self.metrics.insert(key, tags.clone());
        if ty == "counter" {
            self.counters.insert(name.to_string(), tags);
        }
    }

    fn add_log(&mut self, level: &str, message: &str, parameters: Vec<String>) {
        self.logs.push(LogCall {
            level: level.to_string(),
            message: message.to_string(),
            parameters,
        });
    }

    fn append(&mut self, report: impl Into<String>) {
        self.reports.push(report.into());
    }

    fn signature(&self) -> Option<String> {
        if self.metrics.is_empty() && self.logs.is_empty() {
            return None;
        }
        let members: Vec<String> = self
            .members
            .iter()
            .map(|(name, ty)| format!("{name}:{ty}"))
            .collect();
        let mut metrics: Vec<String> = self
            .metrics
            .iter()
            .map(|(name, tags)| {
                let mut keys: Vec<&str> = tags.keys().map(String::as_str).collect();
                keys.sort_unstable();
                format!("{name}({})", keys.join(","))
            })
            .collect();
        metrics.sort();
        let mut logs: Vec<String> = self
            .logs
            .iter()
            .map(|l| format!("[\"{}\", \"{}\", {:?}]", l.level, l.message, l.parameters))
            .collect();
        logs.sort();
        Some(format!(
            "{}[{}][{}]",
            members.join(":"),
            logs.join(";"),
            metrics.join(";")
        ))
    }
}

// ---- Validation ------------------------------------------------------------

fn log_level_one_of(reports: &mut Vec<String>, logs: &[LogCall], levels: &[&str]) {
    if !logs.iter().any(|l| levels.contains(&l.level.as_str())) {
        reports.push(format!(
            "This event MUST log with one of these levels: [{}].",
            levels
                .iter()
                .map(|l| format!("\"{l}\""))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
}

fn counters_must_include_exclude_tags(
    reports: &mut Vec<String>,
    counters: &BTreeMap<String, BTreeMap<String, String>>,
    name: &str,
    required_tags: &[&str],
    exclude_tags: &[&str],
) {
    let Some(tags) = counters.get(name) else {
        reports.push(format!("This event MUST increment counter \"{name}\"."));
        return;
    };
    for tag in required_tags {
        if !tags.contains_key(*tag) {
            reports.push(format!("Counter \"{name}\" MUST include tag \"{tag}\"."));
        }
    }
    for tag in exclude_tags {
        if tags.contains_key(*tag) {
            reports.push(format!(
                "Counter \"{name}\" MUST NOT include tag \"{tag}\"."
            ));
        }
    }
}

fn check_event_class(reports: &mut Vec<String>, name: &str, event: &Event, handle: &Event) {
    for (suffix, class) in EVENT_CLASSES {
        if !name.ends_with(suffix) {
            continue;
        }
        for log in &handle.logs {
            if log.level != "trace" {
                reports.push("Log type MUST be \"trace!\".".to_string());
            }
            if log.message != class.message {
                reports.push(format!(
                    "Log message MUST be \"{}\" (is \"{}\").",
                    class.message, log.message
                ));
            }
            for tag in class.additional_tags {
                if !log.parameters.iter().any(|p| p == tag) {
                    reports.push(format!("Log MUST contain tag \"{tag}\""));
                }
            }
        }
        for counter in class.counters {
            let counter_name = format!("component_{counter}_total");
            let required: Vec<&str> = class
                .additional_tags
                .iter()
                .copied()
                .filter(|t| !BYTE_SIZE_COUNT.contains(t))
                .collect();
            counters_must_include_exclude_tags(
                reports,
                &event.counters,
                &counter_name,
                &required,
                &[],
            );
        }
    }
}

fn check_error_event(reports: &mut Vec<String>, name: &str, event: &Event, handle: &Event) {
    if !name.ends_with("Error") {
        reports.push("Error events MUST be named \"___Error\".".to_string());
    }
    log_level_one_of(reports, &handle.logs, &["error"]);
    counters_must_include_exclude_tags(
        reports,
        &event.counters,
        METRIC_NAME_ERROR,
        &["error_type", "stage"],
        &[],
    );
    for log in &handle.logs {
        if log.level != "error" {
            continue;
        }
        for parameter in ["error_type", "stage"] {
            if !log.parameters.iter().any(|p| p == parameter) {
                reports.push(format!(
                    "Error log for Error event MUST include parameter \"{parameter}\"."
                ));
            }
        }
        for parameter in ["error_code", "error_type", "stage"] {
            if log.parameters.iter().any(|p| p == parameter)
                && !event
                    .counters
                    .get(METRIC_NAME_ERROR)
                    .is_some_and(|m| m.contains_key(parameter))
            {
                reports.push(format!(
                    "Counter \"{METRIC_NAME_ERROR}\" must include \"{parameter}\" to match error log."
                ));
            }
        }
    }
}

fn check_events_dropped(reports: &mut Vec<String>, name: &str, event: &Event, handle: &Event) {
    if event.emits_component_events_dropped {
        if event.counters.contains_key(METRIC_NAME_EVENTS_DROPPED) {
            reports.push(format!(
                "Event emitting ComponentEventsDropped should not also increment counter `{METRIC_NAME_EVENTS_DROPPED}`"
            ));
        }
        return;
    }
    if !name.ends_with("EventsDropped") {
        reports.push("EventsDropped events MUST be named \"___EventsDropped\".".to_string());
    }
    log_level_one_of(reports, &handle.logs, &["error", "debug"]);
    counters_must_include_exclude_tags(
        reports,
        &event.counters,
        METRIC_NAME_EVENTS_DROPPED,
        &["intentional"],
        &["reason", "count"],
    );
    for log in &handle.logs {
        if log.level != "error" {
            continue;
        }
        for parameter in ["count", "intentional", "reason"] {
            if !log.parameters.iter().any(|p| p == parameter) {
                reports.push(format!(
                    "Error log for EventsDropped event MUST include parameter \"{parameter}\"."
                ));
            }
        }
        if log.parameters.iter().any(|p| p == "intentional")
            && !event
                .counters
                .get(METRIC_NAME_EVENTS_DROPPED)
                .is_some_and(|m| m.contains_key("intentional"))
        {
            reports.push(format!(
                "Counter \"{METRIC_NAME_EVENTS_DROPPED}\" must include \"intentional\" to match error log."
            ));
        }
    }
}

fn check_error_counter_tag_constants(reports: &mut Vec<String>, event: &Event) {
    for (cname, tags) in &event.counters {
        if cname != METRIC_NAME_ERROR && cname != METRIC_NAME_EVENTS_DROPPED {
            continue;
        }
        for (tag, value) in tags {
            if tag == "stage" && !value.starts_with("error_stage::") {
                reports.push(format!(
                    "Counter \"{cname}\" tag \"{tag}\" value must be an \"error_stage\" constant."
                ));
            } else if tag == "error_type" && !value.starts_with("error_type::") {
                reports.push(format!(
                    "Counter \"{cname}\" tag \"{tag}\" value must be an \"error_type\" constant."
                ));
            }
        }
    }
}

fn validate_event(events: &HashMap<String, Event>, name: &str, handle_name: &str) -> Vec<String> {
    let event = events.get(name).expect("event present");
    let handle = events.get(handle_name).expect("handle present");
    let mut reports: Vec<String> = Vec::new();

    if event.uses == 0 {
        reports.push("Event has no uses.".to_string());
    }

    check_event_class(&mut reports, name, event, handle);

    let has_error_logs = handle.logs.iter().filter(|l| l.level == "error").count() == 1;
    let is_events_dropped_event =
        name.ends_with("EventsDropped") || event.counters.contains_key(METRIC_NAME_EVENTS_DROPPED);

    if (has_error_logs && !is_events_dropped_event) || name.ends_with("Error") {
        check_error_event(&mut reports, name, event, handle);
    }

    if is_events_dropped_event && !event.skip.dropped_events {
        check_events_dropped(&mut reports, name, event, handle);
    }

    check_error_counter_tag_constants(&mut reports, event);

    for r in &event.reports {
        reports.push(r.clone());
    }

    reports
}

// ---- Macro arg parsers (operate on small token strings) --------------------

/// `emit!(ComponentEventsDropped...)` detection regex, applied to the raw
/// source slice of an impl block (which preserves comments and original
/// formatting that `to_token_stream` strips).
static RE_EMIT_DROPPED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:emit|register)!\([ \t\r\n]*ComponentEventsDropped(?:[^A-Za-z0-9_]|$)").unwrap()
});

/// `emit!(EventName)` / `register!(Path::EventName)` use-counting regex,
/// applied to the raw file text so it sees calls nested inside other macros
/// (e.g. `tokio::select!`) that `syn` does not descend into.
static RE_USES: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?:^|[^A-Za-z0-9_])(?:emit!?|register!?)\((?:[a-z][a-z0-9_:]+)?([A-Z][A-Za-z0-9]+)",
    )
    .unwrap()
});

/// Locator for `tracing` log-macro calls (`trace!(`, `debug!(`, `info!(`,
/// `warn!(`, `error!(`) in raw source text. Used by the format-check pass
/// because the AST visitor cannot see log calls nested inside opaque outer
/// macros like `tokio::select!`.
static RE_LOG_CALL_OPEN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?:^|[^A-Za-z0-9_])(trace|debug|info|warn|error)!\(").unwrap());

/// `"key" => value` tag-pair regex. Used inside `counter!(...)` arg lists.
/// Note: syn's `TokenStream` rendering may produce `=>` as `= >`; the regex
/// accepts either form via `=[ \t]*>`.
static RE_TAG_PAIR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#""([^"]+)"[ \t\r\n]*=[ \t\r\n]*>[ \t\r\n]*(.+?)(?:,|$)"#).unwrap()
});

/// Strip whitespace introduced by `TokenStream::to_string` around `::` so
/// `error_stage :: PROCESSING` becomes `error_stage::PROCESSING` for the
/// constant-prefix validation (`starts_with("error_stage::")`).
fn normalize_value(s: &str) -> String {
    let trimmed = s.trim();
    let collapsed = Regex::new(r"[ \t\r\n]*::[ \t\r\n]*")
        .unwrap()
        .replace_all(trimmed, "::");
    collapsed.into_owned()
}

/// Split a token stream that represents a comma-separated argument list into
/// per-argument substrings, respecting bracket/paren/brace nesting and string
/// literals. Operates on the (already-bounded) macro-arg token text.
///
/// Angle brackets are tracked as a separate depth so that generic-type commas
/// like `Registered<ComponentEventsDropped<'static, INTENTIONAL>>` don't
/// fragment a `registered_event!` field. `>` only decrements when there is a
/// matching `<`, so the `>` in `key => value` tag pairs (used by `counter!`
/// args) doesn't underflow.
#[expect(
    clippy::string_slice,
    reason = "indices from byte-iterator over ASCII delimiters, always char boundaries"
)]
fn split_comma_args(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth: i32 = 0;
    let mut angle_depth: i32 = 0;
    let mut in_str = false;
    let mut esc = false;
    let mut start = 0;
    let bytes = s.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if in_str {
            if esc {
                esc = false;
            } else if b == b'\\' {
                esc = true;
            } else if b == b'"' {
                in_str = false;
            }
            continue;
        }
        match b {
            b'"' => in_str = true,
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b'<' => angle_depth += 1,
            b'>' if angle_depth > 0 => angle_depth -= 1,
            b',' if depth == 0 && angle_depth == 0 => {
                out.push(s[start..i].trim().to_string());
                start = i + 1;
            }
            _ => {}
        }
    }
    let last = s[start..].trim().to_string();
    if !last.is_empty() {
        out.push(last);
    }
    out
}

#[derive(Debug)]
struct ParsedMetric {
    ty: String,
    name: String,
    tags: BTreeMap<String, String>,
}

/// Parse a `counter!(...)` / `gauge!(...)` / `histogram!(...)` invocation's
/// already-tokenised args into a name (string literal or `CamelCase` variant
/// of `<X>Name::Variant`) and its `"key" => value` tag pairs.
fn parse_metric_args(ty: &str, tokens: &TokenStream) -> Option<ParsedMetric> {
    let raw = tokens.to_string();
    let args = split_comma_args(&raw);
    if args.is_empty() {
        return None;
    }
    let name = parse_metric_name(args[0].as_str())?;
    let mut tags = BTreeMap::new();
    let rest = args[1..].join(",");
    for caps in RE_TAG_PAIR.captures_iter(&rest) {
        tags.insert(caps[1].to_string(), normalize_value(&caps[2]));
    }
    if tags.is_empty() {
        for caps in RE_TAG_PAIR.captures_iter(&raw) {
            tags.insert(caps[1].to_string(), normalize_value(&caps[2]));
        }
    }
    Some(ParsedMetric {
        ty: ty.to_string(),
        name,
        tags,
    })
}

/// Extract the metric name from the first arg of a `counter!`/`gauge!`/`histogram!`.
/// Accepts `"literal"` or `<TypeName>::<Variant>`.
fn parse_metric_name(arg: &str) -> Option<String> {
    let arg = arg.trim();
    if let Some(stripped) = arg.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
        return Some(stripped.to_string());
    }
    // path::Variant — Ruby matched `\w+Name::(\w+)` and snake-cased the variant.
    let re = Regex::new(r"^[A-Za-z0-9_]+Name[ \t]*::[ \t]*([A-Za-z0-9_]+)").unwrap();
    re.captures(arg).map(|c| (&c[1]).to_case(Case::Snake))
}

#[derive(Debug)]
struct ParsedLog {
    /// The captured message text (string literal contents *or* variable name
    /// if the message was passed as an expression). Always set when the log
    /// has any message-shaped argument.
    message: String,
    /// Whether the message came from a string literal (`"..."`). Format
    /// checks (capitalised, trailing period) only run on literal messages.
    has_literal_message: bool,
    parameters: Vec<String>,
}

/// Parse a `trace!(...)` / `debug!(...)` / `info!(...)` / `warn!(...)` /
/// `error!(...)` invocation's already-stringified args into the message text
/// and the list of parameter names it carries.
///
/// `tracing` allows the message in any position: leading positional literal,
/// trailing positional literal, or `message = "..."` named field. We mirror
/// the Ruby script: take the first string-literal value across all args (be
/// it a positional `"..."` or a `message = "..."` named field) and treat it
/// as the message. Only when no literal is present do we fall back to the
/// first bare positional expression — otherwise patterns like
/// `warn!(%error, "Failed to flush.")` would never have their message format
/// checked because the bare `%error` would be claimed as the message first.
fn parse_log_args(raw: &str) -> ParsedLog {
    let args = split_comma_args(raw);

    let mut literal_message: Option<String> = None;
    let mut named_var_message: Option<String> = None;
    let mut bare_positional_message: Option<String> = None;
    let mut parameters: Vec<String> = Vec::new();

    for arg in &args {
        let trimmed = arg.trim();
        if trimmed.starts_with("target :") || trimmed.starts_with("parent :") {
            continue;
        }

        // `message = ...` (named field). The value may or may not be a literal.
        if let Some(rest) = trimmed.strip_prefix("message")
            && let Some(value) = rest.trim_start().strip_prefix('=').map(str::trim_start)
        {
            let value = value.trim();
            if let Some(stripped) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
                if literal_message.is_none() {
                    literal_message = Some(stripped.to_string());
                }
            } else if named_var_message.is_none() {
                named_var_message = Some(value.to_string());
            }
            continue;
        }

        // Leading/trailing positional string literal (`"..."` standalone arg).
        if let Some(stripped) = trimmed.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
            if literal_message.is_none() {
                literal_message = Some(stripped.to_string());
            }
            continue;
        }

        // Bare positional expression (no `=`). Track the first one as a
        // candidate message in case no literal is found later, and *also*
        // record it as a parameter — `tracing` lets the same expression
        // serve both roles.
        if !trimmed.contains('=') {
            if bare_positional_message.is_none() {
                bare_positional_message = Some(trimmed.to_string());
            }
            if let Some(name) = parameter_name(trimmed) {
                parameters.push(name);
            }
            continue;
        }

        // Any other `key = value` named field: just a parameter.
        if let Some(name) = parameter_name(trimmed) {
            parameters.push(name);
        }
    }

    let (message, has_literal_message) = if let Some(m) = literal_message {
        (m, true)
    } else if let Some(m) = named_var_message {
        (m, false)
    } else if let Some(m) = bare_positional_message {
        (m, false)
    } else {
        (String::new(), false)
    };

    ParsedLog {
        message,
        has_literal_message,
        parameters,
    }
}

/// Extract the parameter name from a log-macro arg. `tracing` accepts:
/// `name = expr`, `?name`, `%name`, and bare `name`. Token-stream
/// serialisation puts whitespace around punctuation (`% protocol`) so we
/// trim after stripping each prefix.
fn parameter_name(arg: &str) -> Option<String> {
    let s = arg.trim();
    if s.is_empty() {
        return None;
    }
    if let Some((lhs, _)) = s.split_once('=') {
        let lhs = lhs
            .trim()
            .trim_start_matches('?')
            .trim_start_matches('%')
            .trim();
        if is_identifier(lhs) {
            return Some(lhs.to_string());
        }
    }
    let stripped = s
        .trim_start_matches('?')
        .trim_start_matches('%')
        .trim_start();
    let head: String = stripped
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '.')
        .collect();
    if !head.is_empty() && head.chars().any(|c| c.is_ascii_alphabetic() || c == '_') {
        return Some(head);
    }
    None
}

fn is_identifier(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
        && s.chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
}

// ---- AST scanner -----------------------------------------------------------

#[derive(Clone)]
struct ImplCtx {
    event_name: String,
}

struct Scanner<'a> {
    events: &'a mut HashMap<String, Event>,
    path_str: String,
    in_internal_events_dir: bool,
    skip_dropped_for_file: bool,
    text: &'a str,
    impl_stack: Vec<ImplCtx>,
}

impl<'ast> Visit<'ast> for Scanner<'_> {
    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        if self.in_internal_events_dir {
            let name = node.ident.to_string();
            let event = self.events.entry(name).or_default();
            event.path = Some(self.path_str.clone());
            event.skip.dropped_events = self.skip_dropped_for_file;
            for field in &node.fields {
                if let Some(ident) = &field.ident {
                    let ty = field.ty.to_token_stream().to_string();
                    event.members.insert(ident.to_string(), ty);
                }
            }
        }
        visit::visit_item_struct(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        let trait_name = node
            .trait_
            .as_ref()
            .and_then(|(_, path, _)| path.segments.last())
            .map(|s| s.ident.to_string());
        let event_name = match &*node.self_ty {
            Type::Path(tp) => tp.path.segments.last().map(|s| s.ident.to_string()),
            _ => None,
        };

        if self.in_internal_events_dir
            && let (Some(trait_name), Some(event_name)) = (trait_name.as_deref(), event_name)
        {
            let mut handled = false;
            if matches!(
                trait_name,
                "InternalEvent" | "RegisterInternalEvent" | "InternalEventHandle"
            ) {
                // The token-stream form of the impl block has all comments
                // stripped by syn, so the `## skip ##` markers (which live in
                // line comments) are missing. Read them from the original
                // source text within the span instead.
                let raw_block = source_slice(self.text, node.span());
                let registers_inside = node.to_token_stream().to_string().contains("register (");

                let event = self.events.entry(event_name.clone()).or_default();
                event.path = Some(self.path_str.clone());
                event.skip.duplicate_check |=
                    raw_block.contains("## skip check-duplicate-events ##");
                event.skip.validity_check |= raw_block.contains("## skip check-validity-events ##");

                match trait_name {
                    "InternalEvent" if !registers_inside => {
                        event.internal_impl = true;
                    }
                    "RegisterInternalEvent" => {
                        event.register_impl = Some(event_name.clone());
                        event.append(
                            "Do not implement RegisterInternalEvent manually. Use the registered_event! macro instead.",
                        );
                    }
                    "InternalEventHandle" => event.impl_event_handle = true,
                    _ => {}
                }
                if RE_EMIT_DROPPED.is_match(&raw_block) {
                    event.emits_component_events_dropped = true;
                }
                self.impl_stack.push(ImplCtx { event_name });
                handled = true;
            }
            visit::visit_item_impl(self, node);
            if handled {
                self.impl_stack.pop();
            }
            return;
        }
        visit::visit_item_impl(self, node);
    }

    fn visit_macro(&mut self, node: &'ast syn::Macro) {
        let name = node
            .path
            .segments
            .last()
            .map(|s| s.ident.to_string())
            .unwrap_or_default();

        // Use-counting, ComponentEventsDropped detection, and the
        // log-message format check all run via a separate raw-source pass
        // because `syn` does not descend into the bodies of arbitrary
        // `tokio::select!` / `cfg_if!` / etc. macro invocations.

        // Inside an InternalEvent-family impl: capture logs / metrics /
        //    ComponentEventsDropped emissions for the active event.
        if let Some(ctx) = self.impl_stack.last().cloned() {
            match name.as_str() {
                "trace" | "debug" | "info" | "warn" | "error" => {
                    let parsed = parse_log_args(&node.tokens.to_string());
                    let event = self.events.entry(ctx.event_name.clone()).or_default();
                    event.add_log(&name, &parsed.message, parsed.parameters);
                }
                "counter" | "gauge" | "histogram" => {
                    if let Some(metric) = parse_metric_args(&name, &node.tokens) {
                        let event = self.events.entry(ctx.event_name.clone()).or_default();
                        event.add_metric(&metric.ty, &metric.name, metric.tags);
                    }
                }
                _ => {}
            }
        }
        if name == "registered_event" {
            self.handle_registered_event(node);
        }

        visit::visit_macro(self, node);
    }
}

impl Scanner<'_> {
    /// Parse a `registered_event!` invocation's tokens to extract the event
    /// name, members, handle metrics, and emit-block log calls.
    #[expect(
        clippy::string_slice,
        reason = "indices from find() on ASCII patterns or match_paren_end(), always char boundaries"
    )]
    fn handle_registered_event(&mut self, mac: &syn::Macro) {
        let raw = mac.tokens.to_string();
        // Event name: first ident.
        let Some(event_name) = first_ident(&raw) else {
            return;
        };
        let event = self.events.entry(event_name.clone()).or_default();
        event.path = Some(self.path_str.clone());

        // Pull out the optional `{ event_fields }` immediately after the name,
        // then `=> { handle_fields }`, and the `fn emit(...)  { body }`.
        let after_name = match raw.find(&event_name) {
            Some(idx) => &raw[idx + event_name.len()..],
            None => return,
        };
        let after_name = after_name.trim_start();

        // Extract `{ ... }` after name, if any (optional event fields).
        let (event_fields_text, after_fields): (Option<String>, &str) =
            if after_name.starts_with('{') {
                let (block, rest) = split_brace_block(after_name);
                (Some(block.to_string()), rest)
            } else {
                (None, after_name)
            };

        // Parse member fields from the event-fields block.
        if let Some(block) = event_fields_text {
            for arg in split_comma_args(&block) {
                if let Some((name, ty)) = arg.split_once(':') {
                    event
                        .members
                        .insert(name.trim().to_string(), ty.trim().to_string());
                }
            }
        }

        // Skip past `=> { handle_fields }`.
        let after_arrow = after_fields.trim_start();
        let after_arrow = after_arrow
            .strip_prefix("=>")
            .unwrap_or(after_arrow)
            .trim_start();
        let (handle_block, _after_handle) = if after_arrow.starts_with('{') {
            let (block, rest) = split_brace_block(after_arrow);
            (block.to_string(), rest)
        } else {
            return;
        };

        // Each handle field: `name : type = expr ,`. Pick out metric calls
        // inside the `expr` portion to register on the event.
        for arg in split_comma_args(&handle_block) {
            let arg = arg.trim();
            if arg.is_empty() {
                continue;
            }
            // Attempt to parse the assignment.
            let after_colon = match arg.find(':') {
                Some(i) => &arg[i + 1..],
                None => continue,
            };
            let Some((_ty, expr)) = after_colon.split_once('=') else {
                continue;
            };
            let expr = expr.trim();

            // Look for embedded `counter!` / `gauge!` / `histogram!` calls.
            for ty in ["counter", "gauge", "histogram"] {
                let needle = format!("{ty} ! (");
                if let Some(idx) = expr.find(&needle) {
                    // Find the matching `)` from the `(` after `!`.
                    let after = &expr[idx + needle.len()..];
                    if let Some(end) = match_paren_end(after) {
                        let inside = &after[..end];
                        let toks: TokenStream = inside.parse().unwrap_or_default();
                        if let Some(metric) = parse_metric_args(ty, &toks) {
                            event.add_metric(&metric.ty, &metric.name, metric.tags);
                        }
                    }
                }
            }

            // Component-events-dropped emission.
            if expr.contains("emit ! (ComponentEventsDropped")
                || expr.contains("register ! (ComponentEventsDropped")
            {
                event.emits_component_events_dropped = true;
            }
        }

        // The emit-fn body. Find `fn emit (...) { ... }` after the handle block.
        // We re-scan the original tokens for any log macros within the impl
        // body via the AST visitor — simpler than reparsing here. The handle
        // block above already covers metric extraction. Logs registered to the
        // outer event come from the visit_macro handling above when the visitor
        // descends into nested macros (note: macros aren't normal items, so
        // visit_macro won't recurse into a parent macro's tokens). To capture
        // log calls inside `registered_event!`, we parse them out by scanning
        // the macro's full token text for log macro signatures.
        for ty in ["trace", "debug", "info", "warn", "error"] {
            let needle = format!("{ty} ! (");
            let mut start = 0;
            while let Some(idx) = raw[start..].find(&needle) {
                let after = &raw[start + idx + needle.len()..];
                if let Some(end) = match_paren_end(after) {
                    let inside = &after[..end];
                    let parsed = parse_log_args(inside);
                    let event = self.events.entry(event_name.clone()).or_default();
                    event.add_log(ty, &parsed.message, parsed.parameters);
                    start = start + idx + needle.len() + end;
                } else {
                    break;
                }
            }
        }
    }
}

/// Format-check every `tracing` log macro invocation in `text` (a Rust
/// source file's contents). Returns a list of human-readable report lines.
///
/// Operates on the raw source rather than via the AST so that log calls
/// nested inside opaque outer macros (`tokio::select!`, `cfg_if!`, …) are
/// also covered — those bodies are not visited by `syn`.
#[expect(
    clippy::string_slice,
    reason = "indices from regex .end() and match_paren_end(), always char boundaries"
)]
fn format_check_log_messages(text: &str, path_str: &str) -> Vec<String> {
    let mut reports = Vec::new();
    for caps in RE_LOG_CALL_OPEN.captures_iter(text) {
        let level_match = caps.get(1).expect("group 1 is the level");
        let level = level_match.as_str();
        // The match ends with the literal `(`. Walk forward from there to
        // find the matching `)` accounting for nested parens / braces /
        // brackets and string literals; this is the inside of the macro.
        let after_paren = caps.get(0).expect("full match").end();
        if after_paren > text.len() {
            continue;
        }
        let body_start = after_paren; // position right after `(`
        let Some(close_offset) = match_paren_end(&text[body_start..]) else {
            continue;
        };
        let inside = &text[body_start..body_start + close_offset];
        let parsed = parse_log_args(inside);
        if !parsed.has_literal_message {
            continue;
        }
        let message = parsed.message;
        if message.is_empty() {
            continue;
        }
        let is_capitalized = message.starts_with('{')
            || !message
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic())
            || message
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_uppercase());
        let has_trailing_period = message.ends_with('}') || message.ends_with('.');
        if is_capitalized && has_trailing_period {
            continue;
        }
        let line_no = text[..level_match.start()].matches('\n').count() + 1;
        if !is_capitalized {
            reports.push(format!(
                "    Message must start with a capital. (`{level}` call on {path_str}:{line_no})"
            ));
        }
        if !has_trailing_period {
            reports.push(format!(
                "    Message must end with a period. (`{level}` call on {path_str}:{line_no})"
            ));
        }
    }
    reports
}

/// Extract the source slice covered by a `proc_macro2::Span`. Used to read
/// line-comment skip markers (e.g. `## skip check-validity-events ##`) which
/// `syn` discards from the AST.
fn source_slice(text: &str, span: proc_macro2::Span) -> String {
    let start = span.start();
    let end = span.end();
    let mut out = String::new();
    for (i, line) in text.lines().enumerate() {
        let line_no = i + 1;
        if line_no >= start.line && line_no <= end.line {
            out.push_str(line);
            out.push('\n');
        }
        if line_no > end.line {
            break;
        }
    }
    out
}

/// Given a string starting with `(`, find the index of the matching `)`.
fn match_paren_end(s: &str) -> Option<usize> {
    // `s` here is the text right after the opening `(`. Walk it tracking depth.
    let mut depth: i32 = 1;
    let mut in_str = false;
    let mut esc = false;
    for (i, b) in s.bytes().enumerate() {
        if in_str {
            if esc {
                esc = false;
            } else if b == b'\\' {
                esc = true;
            } else if b == b'"' {
                in_str = false;
            }
            continue;
        }
        match b {
            b'"' => in_str = true,
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Split a `{ ... }` block off the front of `s`, returning `(inside, rest)`.
#[expect(
    clippy::string_slice,
    reason = "indices from byte-iterator over ASCII '{' '}', always char boundaries"
)]
fn split_brace_block(s: &str) -> (&str, &str) {
    if !s.starts_with('{') {
        return ("", s);
    }
    let mut depth = 0i32;
    let mut in_str = false;
    let mut esc = false;
    for (i, b) in s.bytes().enumerate() {
        if in_str {
            if esc {
                esc = false;
            } else if b == b'\\' {
                esc = true;
            } else if b == b'"' {
                in_str = false;
            }
            continue;
        }
        match b {
            b'"' => in_str = true,
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return (&s[1..i], &s[i + 1..]);
                }
            }
            _ => {}
        }
    }
    ("", s)
}

/// Pull the first identifier-shaped substring out of a token text.
fn first_ident(s: &str) -> Option<String> {
    for tok in s.split(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
        if !tok.is_empty()
            && tok
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        {
            return Some(tok.to_string());
        }
    }
    None
}

// ---- CLI -------------------------------------------------------------------

/// Check that internal events satisfy the patterns set in
/// <https://github.com/vectordotdev/vector/blob/master/docs/specs/instrumentation.md>.
#[derive(clap::Args, Debug)]
#[command()]
pub(super) struct Cli {}

fn collect_source_paths() -> Result<Vec<PathBuf>> {
    let mut paths: Vec<PathBuf> = Vec::new();
    for pattern in ["src/**/*.rs", "lib/**/*.rs"] {
        for entry in glob(pattern)? {
            paths.push(entry?);
        }
    }
    paths.sort();
    Ok(paths)
}

fn scan_file(path: &PathBuf, events: &mut HashMap<String, Event>) -> Result<usize> {
    let path_str = path.to_string_lossy().replace('\\', "/");
    let text = fs::read_to_string(path)?;
    let lower = text.to_ascii_lowercase();

    let in_internal_events = path_str.starts_with("src/internal_events/")
        || path_str.starts_with("lib/vector-common/src/internal_event/");
    let in_src = path_str.starts_with("src/");
    let skip_dropped = lower.contains("## skip check-dropped-events ##");

    for caps in RE_USES.captures_iter(&text) {
        let name = caps[1].to_string();
        events.entry(name).or_default().uses += 1;
    }

    let mut errors = 0usize;
    if in_src {
        let format_reports = format_check_log_messages(&text, &path_str);
        if !format_reports.is_empty() {
            for r in &format_reports {
                println!("{r}");
            }
            errors += format_reports.len();
        }
    }

    let file = match syn::parse_file(&text) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("warning: failed to parse {path_str}: {e}");
            return Ok(errors);
        }
    };

    let mut scanner = Scanner {
        events,
        path_str: path_str.clone(),
        in_internal_events_dir: in_internal_events,
        skip_dropped_for_file: skip_dropped,
        text: &text,
        impl_stack: Vec::new(),
    };
    visit::visit_file(&mut scanner, &file);
    Ok(errors)
}

fn report_event_errors(events: &HashMap<String, Event>, name: &str, handle_name: &str) -> bool {
    let reports = validate_event(events, name, handle_name);
    if reports.is_empty() {
        return false;
    }
    let path = events
        .get(name)
        .and_then(|e| e.path.as_deref())
        .unwrap_or("?");
    println!("{path}: Errors in event {name}:");
    for r in &reports {
        println!("    {r}");
    }
    true
}

fn validate_all(events: &HashMap<String, Event>) -> usize {
    let mut names: Vec<String> = events.keys().cloned().collect();
    names.sort();
    let mut duplicates: HashMap<String, Vec<String>> = HashMap::new();
    let mut error_count = 0usize;

    for name in &names {
        let event = events.get(name).expect("present");
        if !event.skip.duplicate_check
            && (event.internal_impl || event.impl_event_handle)
            && let Some(sig) = event.signature()
        {
            duplicates.entry(sig).or_default().push(name.clone());
        }
        if event.skip.validity_check {
            continue;
        }
        if event.internal_impl {
            if report_event_errors(events, name, name) {
                error_count += 1;
            }
        } else if let Some(handle_name) = event.register_impl.as_deref() {
            if events.contains_key(handle_name) {
                if report_event_errors(events, name, handle_name) {
                    error_count += 1;
                }
            } else {
                println!("Registered event {name} references nonexistent handle {handle_name}");
                error_count += 1;
            }
        }
    }

    let mut dup_keys: Vec<&String> = duplicates.keys().collect();
    dup_keys.sort();
    for sig in dup_keys {
        let dupes = &duplicates[sig];
        if dupes.len() > 1 {
            println!("Duplicate events detected: {}", dupes.join(", "));
            error_count += 1;
        }
    }

    error_count
}

impl Cli {
    pub(super) fn exec(self) -> Result<()> {
        // Resolve all `src/**` / `lib/**` globs against the repo root rather
        // than the caller's CWD. Without this, running the binary from
        // anywhere outside the repo root silently scans nothing and reports
        // `0 error(s)` — which the previous Ruby script wrapper avoided
        // because it was always invoked with the repo as the working dir.
        let repo_root = crate::utils::paths::find_repo_root()?;
        std::env::set_current_dir(&repo_root)?;

        let mut events: HashMap<String, Event> = HashMap::new();
        let mut error_count = 0usize;

        for path in &collect_source_paths()? {
            error_count += scan_file(path, &mut events)?;
        }

        error_count += validate_all(&events);

        println!("{error_count} error(s)");
        if error_count > 0 {
            process::exit(1);
        }
        Ok(())
    }
}

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

    #[test]
    fn split_comma_args_respects_nesting() {
        assert_eq!(
            split_comma_args(r#""a", "b" => "c, d", e"#),
            vec![
                r#""a""#.to_string(),
                r#""b" => "c, d""#.to_string(),
                "e".to_string(),
            ]
        );
    }

    #[test]
    fn split_comma_args_respects_angle_brackets() {
        // A `registered_event!` handle field with a generic type containing a
        // comma must not be split at the comma inside `<...>`.
        let input = "events_dropped : Registered<ComponentEventsDropped<'static, INTENTIONAL>> = register!(X)";
        assert_eq!(split_comma_args(input), vec![input.to_string()]);
    }

    #[test]
    fn parse_metric_name_string_or_variant() {
        assert_eq!(
            parse_metric_name(r#""my_metric""#),
            Some("my_metric".to_string())
        );
        assert_eq!(
            parse_metric_name("CounterName::ComponentErrorsTotal"),
            Some("component_errors_total".to_string())
        );
        assert_eq!(parse_metric_name("not_a_metric"), None);
    }

    #[test]
    fn signature_none_when_empty() {
        assert!(Event::default().signature().is_none());
    }

    fn parse(src: &str) -> ParsedLog {
        let mac: syn::Macro = syn::parse_str(src).expect("parse macro");
        parse_log_args(&mac.tokens.to_string())
    }

    #[test]
    fn parse_log_args_literal_message_first() {
        let p = parse(r#"trace!("Hello there.", count = 1)"#);
        assert_eq!(p.message, "Hello there.");
        assert!(p.has_literal_message);
        assert_eq!(p.parameters, vec!["count".to_string()]);
    }

    #[test]
    fn parse_log_args_literal_message_named() {
        let p = parse(r#"error!(message = "Stuff broke.", error_type = err)"#);
        assert_eq!(p.message, "Stuff broke.");
        assert!(p.has_literal_message);
        assert_eq!(p.parameters, vec!["error_type".to_string()]);
    }

    #[test]
    fn parse_log_args_variable_message_named() {
        let p = parse("error!(message = exec_reason, error_type = err, stage = stg)");
        assert_eq!(p.message, "exec_reason");
        assert!(!p.has_literal_message);
        assert_eq!(
            p.parameters,
            vec!["error_type".to_string(), "stage".to_string()]
        );
    }

    #[test]
    fn parse_log_args_trailing_string_literal() {
        // Some sites pass key=values first and the literal message last —
        // tracing accepts this.
        let p = parse(r#"error!(path = req.uri().path(), "Bad request.")"#);
        assert_eq!(p.message, "Bad request.");
        assert!(p.has_literal_message);
        assert!(p.parameters.contains(&"path".to_string()));
    }

    #[test]
    fn format_check_finds_nested_log_calls() {
        // `syn` does not descend into the bodies of opaque outer macros like
        // `tokio::select!`, which is why this check runs over the raw source
        // rather than via the AST visitor. Fixture covers both a top-level
        // violation and one nested inside `tokio::select!`.
        let src = r#"
            fn _f() {
                error!("missing period");
                tokio::select! {
                    _ = something() => {
                        info!("lowercase first.");
                    }
                }
            }
        "#;
        let reports = format_check_log_messages(src, "fixture.rs");
        let joined = reports.join("\n");
        assert!(
            joined.contains("Message must end with a period.") && joined.contains("`error` call"),
            "expected period-violation report, got: {joined}"
        );
        assert!(
            joined.contains("Message must start with a capital.") && joined.contains("`info` call"),
            "expected capital-violation report on the nested info!, got: {joined}"
        );
    }

    #[test]
    fn format_check_skips_non_literal_messages() {
        // `error!(?err, "Plain text.")` — literal is fine, no report.
        let src = r#"fn _f() { error!(?err, "Plain text."); }"#;
        let reports = format_check_log_messages(src, "fixture.rs");
        assert!(reports.is_empty(), "expected no reports, got: {reports:?}");
    }

    #[test]
    fn parse_log_args_bare_field_then_trailing_literal() {
        // `warn!(%error, "Message.")` — the bare field comes first but the
        // string literal is the real message. The parser must scan all args
        // for a literal before falling back to the bare expression as the
        // message, otherwise the format checks never fire here.
        let p = parse(r#"warn!(%error, "Failed to flush.")"#);
        assert_eq!(p.message, "Failed to flush.");
        assert!(p.has_literal_message);
        assert!(p.parameters.contains(&"error".to_string()));
    }

    #[test]
    fn parse_log_args_percent_capture() {
        let p = parse(r#"trace!(message = "Bytes received.", byte_size = bs, %protocol)"#);
        assert!(p.has_literal_message);
        assert_eq!(p.message, "Bytes received.");
        assert!(p.parameters.contains(&"byte_size".to_string()));
        assert!(p.parameters.contains(&"protocol".to_string()));
    }

    fn check(message: &str) -> (bool, bool) {
        // Replicates the gating in `format_check_log_messages` for a literal message.
        let is_capitalized = message.starts_with('{')
            || !message
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic())
            || message
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_uppercase());
        let has_trailing_period = message.ends_with('}') || message.ends_with('.');
        (is_capitalized, has_trailing_period)
    }

    #[test]
    fn message_format_capital_period_pass() {
        assert_eq!(check("Hello there."), (true, true));
    }

    #[test]
    fn message_format_lowercase_first_fails() {
        let (cap, _) = check("hello there.");
        assert!(!cap);
    }

    #[test]
    fn message_format_no_period_fails() {
        let (_, period) = check("Hello there");
        assert!(!period);
    }

    #[test]
    fn message_format_interpolation_passes() {
        // `{...}` at start or end is fine — we can't see what it expands to.
        assert_eq!(check("{count} dropped."), (true, true));
        assert_eq!(check("Dropped {count}"), (true, true));
    }

    #[test]
    fn message_format_non_alpha_first_passes() {
        // E.g. starts with a number — no capitalisation requirement.
        assert_eq!(check("42 things happened."), (true, true));
    }

    // ---- validate_event branch coverage --------------------------------
    //
    // Each test builds a synthetic `Event` (or a `(event, handle)` pair for
    // registered events), inserts it into a HashMap, calls `validate_event`,
    // and asserts on the returned report list. This covers the rule branches
    // independently of the parsing/scanning layer.

    fn mk_event() -> Event {
        Event {
            uses: 1, // default to "has uses" so that branch isn't always firing
            internal_impl: true,
            ..Default::default()
        }
    }

    fn one_log(level: &str, message: &str, params: &[&str]) -> Vec<LogCall> {
        vec![LogCall {
            level: level.to_string(),
            message: message.to_string(),
            parameters: params.iter().map(|s| (*s).to_string()).collect(),
        }]
    }

    fn counter(tags: &[(&str, &str)]) -> BTreeMap<String, String> {
        tags.iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect()
    }

    fn run(name: &str, event: Event) -> Vec<String> {
        let mut events = HashMap::new();
        events.insert(name.to_string(), event);
        validate_event(&events, name, name)
    }

    #[test]
    fn validate_event_no_uses_reported() {
        let mut e = mk_event();
        e.uses = 0;
        let r = run("Foo", e);
        assert!(r.iter().any(|m| m == "Event has no uses."));
    }

    #[test]
    fn validate_bytes_received_log_type_must_be_trace() {
        let mut e = mk_event();
        e.logs = one_log("info", "Bytes received.", &["byte_size", "protocol"]);
        e.counters.insert(
            "component_received_bytes_total".to_string(),
            counter(&[("protocol", "tcp")]),
        );
        let r = run("FooBytesReceived", e);
        assert!(r.iter().any(|m| m == "Log type MUST be \"trace!\"."));
    }

    #[test]
    fn validate_bytes_received_log_message_exact() {
        let mut e = mk_event();
        e.logs = one_log(
            "trace",
            "Bytes were received here.",
            &["byte_size", "protocol"],
        );
        e.counters.insert(
            "component_received_bytes_total".to_string(),
            counter(&[("protocol", "tcp")]),
        );
        let r = run("FooBytesReceived", e);
        assert!(
            r.iter()
                .any(|m| m.contains("Log message MUST be \"Bytes received.\""))
        );
    }

    #[test]
    fn validate_bytes_received_log_required_tag() {
        let mut e = mk_event();
        e.logs = one_log("trace", "Bytes received.", &["byte_size"]); // missing protocol
        e.counters.insert(
            "component_received_bytes_total".to_string(),
            counter(&[("protocol", "tcp")]),
        );
        let r = run("FooBytesReceived", e);
        assert!(r.iter().any(|m| m == "Log MUST contain tag \"protocol\""));
    }

    #[test]
    fn validate_bytes_received_counter_required_tag() {
        let mut e = mk_event();
        e.logs = one_log("trace", "Bytes received.", &["byte_size", "protocol"]);
        e.counters
            .insert("component_received_bytes_total".to_string(), counter(&[])); // missing protocol
        let r = run("FooBytesReceived", e);
        assert!(r.iter().any(|m| {
            m == "Counter \"component_received_bytes_total\" MUST include tag \"protocol\"."
        }));
    }

    #[test]
    fn validate_events_received_class() {
        let mut e = mk_event();
        e.logs = one_log("trace", "Wrong message.", &["count", "byte_size"]);
        let r = run("FooEventsReceived", e);
        assert!(
            r.iter()
                .any(|m| m.contains("Log message MUST be \"Events received.\""))
        );
        assert!(
            r.iter()
                .any(|m| m
                    == "This event MUST increment counter \"component_received_events_total\".")
        );
    }

    #[test]
    fn validate_error_event_must_be_named_error() {
        let mut e = mk_event();
        e.logs = one_log("error", "Something failed.", &["error_type", "stage"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("BadlyNamed", e);
        assert!(
            r.iter()
                .any(|m| m == "Error events MUST be named \"___Error\".")
        );
    }

    #[test]
    fn validate_error_event_log_level_must_be_error() {
        let mut e = mk_event();
        // info-level log when name ends with Error
        e.logs = one_log("info", "Something failed.", &["error_type", "stage"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("FooError", e);
        assert!(
            r.iter()
                .any(|m| m.contains("MUST log with one of these levels: [\"error\"]"))
        );
    }

    #[test]
    fn validate_error_event_log_must_include_error_type_and_stage() {
        let mut e = mk_event();
        e.logs = one_log("error", "Something failed.", &[]); // no error_type, no stage
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("FooError", e);
        assert!(
            r.iter()
                .any(|m| m == "Error log for Error event MUST include parameter \"error_type\".")
        );
        assert!(
            r.iter()
                .any(|m| m == "Error log for Error event MUST include parameter \"stage\".")
        );
    }

    #[test]
    fn validate_error_counter_must_match_error_log_params() {
        let mut e = mk_event();
        // Log mentions error_code but counter doesn't
        e.logs = one_log("error", "Failed.", &["error_type", "stage", "error_code"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("FooError", e);
        assert!(r.iter().any(|m| {
            m == "Counter \"component_errors_total\" must include \"error_code\" to match error log."
        }));
    }

    #[test]
    fn validate_error_stage_must_be_constant() {
        let mut e = mk_event();
        e.logs = one_log("error", "Failed.", &["error_type", "stage"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "\"processing\""),
            ]),
        );
        let r = run("FooError", e);
        assert!(
            r.iter()
                .any(|m| m.contains("must be an \"error_stage\" constant"))
        );
    }

    #[test]
    fn validate_error_type_must_be_constant() {
        let mut e = mk_event();
        e.logs = one_log("error", "Failed.", &["error_type", "stage"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "\"connection_failed\""),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("FooError", e);
        assert!(
            r.iter()
                .any(|m| m.contains("must be an \"error_type\" constant"))
        );
    }

    #[test]
    fn validate_events_dropped_must_be_named_events_dropped() {
        let mut e = mk_event();
        e.logs = one_log(
            "error",
            "Events dropped.",
            &["count", "intentional", "reason"],
        );
        e.counters.insert(
            METRIC_NAME_EVENTS_DROPPED.to_string(),
            counter(&[("intentional", "false")]),
        );
        let r = run("BadlyNamed", e);
        assert!(
            r.iter()
                .any(|m| m == "EventsDropped events MUST be named \"___EventsDropped\".")
        );
    }

    #[test]
    fn validate_events_dropped_log_level_error_or_debug() {
        let mut e = mk_event();
        e.logs = one_log("info", "Dropped.", &["count", "intentional", "reason"]);
        e.counters.insert(
            METRIC_NAME_EVENTS_DROPPED.to_string(),
            counter(&[("intentional", "false")]),
        );
        let r = run("FooEventsDropped", e);
        assert!(
            r.iter().any(|m| {
                m.contains("MUST log with one of these levels: [\"error\", \"debug\"]")
            })
        );
    }

    #[test]
    fn validate_events_dropped_counter_required_and_excluded_tags() {
        let mut e = mk_event();
        e.logs = one_log("error", "Dropped.", &["count", "intentional", "reason"]);
        // Missing intentional, has reason and count (which it must NOT)
        e.counters.insert(
            METRIC_NAME_EVENTS_DROPPED.to_string(),
            counter(&[("reason", "\"r\""), ("count", "1")]),
        );
        let r = run("FooEventsDropped", e);
        assert!(r.iter().any(|m| {
            m == "Counter \"component_discarded_events_total\" MUST include tag \"intentional\"."
        }));
        assert!(r.iter().any(|m| {
            m == "Counter \"component_discarded_events_total\" MUST NOT include tag \"reason\"."
        }));
        assert!(r.iter().any(|m| {
            m == "Counter \"component_discarded_events_total\" MUST NOT include tag \"count\"."
        }));
    }

    #[test]
    fn validate_events_dropped_log_required_params() {
        let mut e = mk_event();
        // Error log present but missing required params (count, intentional, reason)
        e.logs = one_log("error", "Dropped.", &[]);
        e.counters.insert(
            METRIC_NAME_EVENTS_DROPPED.to_string(),
            counter(&[("intentional", "false")]),
        );
        let r = run("FooEventsDropped", e);
        for p in ["count", "intentional", "reason"] {
            assert!(
                r.iter().any(|m| m
                    == &format!(
                        "Error log for EventsDropped event MUST include parameter \"{p}\"."
                    )),
                "missing report for parameter {p} in: {r:?}"
            );
        }
    }

    #[test]
    fn validate_emits_dropped_must_not_also_increment_counter() {
        let mut e = mk_event();
        e.emits_component_events_dropped = true;
        e.counters.insert(
            METRIC_NAME_EVENTS_DROPPED.to_string(),
            counter(&[("intentional", "false")]),
        );
        let r = run("FooEventsDropped", e);
        assert!(r.iter().any(|m| {
            m.contains("should not also increment counter")
                && m.contains(METRIC_NAME_EVENTS_DROPPED)
        }));
    }

    #[test]
    fn validate_clean_event_no_reports() {
        // A correctly-shaped Error event should produce no reports.
        let mut e = mk_event();
        e.logs = one_log("error", "Connection failed.", &["error_type", "stage"]);
        e.counters.insert(
            METRIC_NAME_ERROR.to_string(),
            counter(&[
                ("error_type", "error_type::CONNECTION_FAILED"),
                ("stage", "error_stage::PROCESSING"),
            ]),
        );
        let r = run("ConnectionFailedError", e);
        assert!(r.is_empty(), "expected no reports, got: {r:?}");
    }
}