rsconstruct 0.9.7

Rust based fast build system
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
mod analyzer_configs;
mod processor_configs;
mod provenance;
mod variables;
#[cfg(test)]
mod tests;

pub(crate) use analyzer_configs::*;
pub(crate) use processor_configs::*;
pub(crate) use provenance::{FieldProvenance, ProvenanceMap, Section, SpanMap};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::errors;
use variables::substitute_variables;

const CONFIG_FILE: &str = "rsconstruct.toml";

/// Scan field names in StandardConfig.
/// These are automatically appended to every processor's known fields during validation.
pub(crate) const SCAN_CONFIG_FIELDS: &[&str] = &[
    "src_dirs", "src_extensions", "src_exclude_dirs", "src_exclude_files", "src_exclude_paths", "src_files",
];

pub(crate) trait KnownFields {
    /// Return the known fields for this config struct, excluding scan fields.
    fn known_fields() -> &'static [&'static str];

    /// Return only the fields that affect build output.
    /// Changes to these fields should trigger config change detection.
    /// Fields not listed here (e.g., src_dirs, src_exclude_dirs, batch, max_jobs)
    /// are discovery or execution parameters that don't affect what the tool produces.
    fn checksum_fields() -> &'static [&'static str];

    /// Return fields that must be explicitly set (non-empty) for the processor to work.
    /// If any of these fields are absent or empty in the user's config, an error is reported.
    /// Default is no required fields.
    fn must_fields() -> &'static [&'static str] {
        &[]
    }

    /// Return (field_name, description) pairs for processor-specific fields only.
    /// Shared scan/dep/exec field descriptions are added by the display layer.
    fn field_descriptions() -> &'static [(&'static str, &'static str)] {
        &[]
    }
}

/// Default scan configuration for a processor, as plain data.
/// Used to resolve None scan fields in StandardConfig after TOML deserialization.
pub(crate) struct ScanDefaultsData {
    pub src_dirs: &'static [&'static str],
    pub src_extensions: &'static [&'static str],
    pub src_exclude_dirs: &'static [&'static str],
}

/// Per-processor default values applied after TOML deserialization.
pub(crate) struct ProcessorDefaults {
    /// Default command binary name. Empty if not applicable.
    pub command: &'static str,
    /// Default dep_auto entries.
    pub dep_auto: &'static [&'static str],
    /// Default output directory (generators only). Empty if not applicable.
    pub output_dir: &'static str,
    /// Default output formats (generators only). Empty if not applicable.
    pub formats: &'static [&'static str],
    /// Default args. Empty if not applicable.
    pub args: &'static [&'static str],
    /// Override for batch. None means leave the StandardConfig default (true).
    pub batch: Option<bool>,
}

impl Default for ProcessorDefaults {
    fn default() -> Self {
        Self {
            command: "",
            dep_auto: &[],
            output_dir: "",
            formats: &[],
            args: &[],
            batch: None,
        }
    }
}

/// Parameters for a simple checker processor — pure data, no macros.
#[derive(Copy, Clone)]
pub(crate) struct SimpleCheckerParams {
    /// Human-readable description
    pub description: &'static str,
    /// Optional subcommand (e.g., "check" for ruff)
    pub subcommand: Option<&'static str>,
    /// Args prepended before config args (e.g., ["--check"] for black)
    pub prepend_args: &'static [&'static str],
    /// Additional tools required beyond the command (e.g., ["python3", "node"])
    pub extra_tools: &'static [&'static str],
    /// Fix mode: subcommand to use (e.g., Some("format") for ruff).
    /// None means same command/subcommand as check but with different args.
    /// If both `fix_subcommand` and `fix_prepend_args` are unset, the
    /// processor has no fix capability.
    pub fix_subcommand: Option<&'static str>,
    /// Args prepended in fix mode (e.g., &["--write"] for prettier, &["--fix"] for eslint).
    /// Empty means no fix capability (unless fix_subcommand is set).
    pub fix_prepend_args: &'static [&'static str],
    /// Whether fix mode supports batch execution. Defaults follow check batch.
    pub fix_batch: Option<bool>,
}

/// Validate dep_inputs paths exist and return them as PathBufs.
/// Paths are relative to project root (which is cwd).
pub(crate) fn resolve_extra_inputs(dep_inputs: &[String]) -> Result<Vec<PathBuf>> {
    let mut resolved = Vec::new();
    for p in dep_inputs {
        if p.contains('*') || p.contains('?') || p.contains('[') {
            // Glob pattern: expand to matching files
            for entry in glob::glob(p)
                .with_context(|| format!("Invalid glob pattern in dep_inputs: {}", p))?
            {
                let path = crate::errors::ctx(entry, &format!("Failed to read glob entry for: {}", p))?;
                if path.is_file() {
                    resolved.push(path);
                }
            }
        } else {
            let path = PathBuf::from(p);
            if !path.exists() {
                anyhow::bail!("dep_inputs file not found: {}", p);
            }
            resolved.push(path);
        }
    }
    Ok(resolved)
}

/// Descriptions for scan fields shared by every processor.
pub(crate) const SCAN_FIELD_DESCRIPTIONS: &[(&str, &str)] = &[
    ("src_dirs",            "Directories to scan for source files"),
    ("src_extensions",      "File extensions to match during scanning"),
    ("src_exclude_dirs",    "Directory path segments to skip during scanning"),
    ("src_exclude_files",   "File names to exclude from scanning"),
    ("src_exclude_paths",   "Relative paths to exclude from scanning"),
    ("src_files",           "Additional files to include alongside normal scanning"),
];

/// Descriptions for execution/dependency fields shared by most processors.
pub(crate) const SHARED_FIELD_DESCRIPTIONS: &[(&str, &str)] = &[
    ("dep_inputs",  "Extra files that trigger a rebuild when their content changes"),
    ("dep_auto",    "Config files silently added as dep_inputs when they exist on disk"),
    ("batch",       "Pass all matched files to the tool in a single invocation"),
    ("max_jobs",    "Maximum parallel jobs for this processor (overrides global --jobs)"),
];

/// Compute a config hash including only the fields named in `checksum_fields`.
/// This is allowlist-based: any key not in `checksum_fields` is removed before
/// hashing. Each processor declares its own checksum_fields() list, which is the
/// single source of truth for which config fields trigger cache invalidation.
pub(crate) fn output_config_hash(value: &impl Serialize, checksum_fields: &[&str]) -> String {
    let json_value: serde_json::Value = serde_json::to_value(value).expect(errors::CONFIG_SERIALIZE);
    let filtered = if let serde_json::Value::Object(map) = json_value {
        let kept: serde_json::Map<String, serde_json::Value> = map.into_iter()
            .filter(|(k, _)| checksum_fields.contains(&k.as_str()))
            .collect();
        serde_json::Value::Object(kept)
    } else {
        json_value
    };
    let json = serde_json::to_string(&filtered).expect(errors::CONFIG_SERIALIZE);
    let hash = Sha256::digest(json.as_bytes());
    hex::encode(hash)
}



const DEFAULT_PLUGINS_DIR: &str = "plugins";

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct PluginsConfig {
    #[serde(default = "default_plugins_dir")]
    pub dir: String,
}

fn default_plugins_dir() -> String {
    DEFAULT_PLUGINS_DIR.into()
}

impl Default for PluginsConfig {
    fn default() -> Self {
        Self { dir: DEFAULT_PLUGINS_DIR.into() }
    }
}

/// Declared project dependencies by package manager.
/// Used by `rsconstruct doctor` to verify and `rsconstruct tools install-deps` to install.
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct DependenciesConfig {
    /// Python packages (installed via pip)
    #[serde(default)]
    pub pip: Vec<String>,
    /// Node.js packages (installed via npm)
    #[serde(default)]
    pub npm: Vec<String>,
    /// Ruby gems (installed via gem)
    #[serde(default)]
    pub gem: Vec<String>,
    /// System packages (checked via `which`, not auto-installed)
    #[serde(default)]
    pub system: Vec<String>,
}

impl DependenciesConfig {
    pub fn is_empty(&self) -> bool {
        self.pip.is_empty() && self.npm.is_empty() && self.gem.is_empty() && self.system.is_empty()
    }
}

#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct Config {
    #[serde(default)]
    pub build: BuildConfig,
    #[serde(default)]
    pub cache: CacheConfig,
    #[serde(default)]
    pub processor: ProcessorConfig,
    #[serde(default)]
    pub analyzer: AnalyzerConfig,
    #[serde(default)]
    pub completions: CompletionsConfig,
    #[serde(default)]
    pub graph: GraphConfig,
    #[serde(default)]
    pub plugins: PluginsConfig,
    #[serde(default)]
    pub dependencies: DependenciesConfig,
    #[serde(default)]
    pub command: CommandsConfig,
    /// Field-level provenance for every top-level `[section]` (build, cache,
    /// graph, plugins, dependencies, command, completions). Each key is the
    /// section name; the inner map's keys are field names within that section.
    /// Populated by `Config::load` from a toml_edit walk — never present in
    /// user TOML, so skipped during (de)serialization.
    #[serde(skip)]
    pub global_provenance: HashMap<String, ProvenanceMap>,
}

/// Configuration for the `symlink-install` command.
/// `sources[i]` is symlinked to `targets[i]`. Both arrays must be the same length.
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct SymlinkInstallConfig {
    /// Source folders containing files to symlink
    #[serde(default)]
    pub sources: Vec<String>,
    /// Target folders where symlinks are created (same length as sources)
    #[serde(default)]
    pub targets: Vec<String>,
}

/// Configuration for custom commands.
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct CommandsConfig {
    #[serde(default)]
    pub symlink_install: SymlinkInstallConfig,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct BuildConfig {
    /// Number of parallel jobs (1 = sequential, 0 = auto-detect CPU cores)
    #[serde(default = "default_parallel")]
    pub parallel: usize,
    /// Maximum files per batch for batch-capable processors.
    /// 0 = no limit (all files in one batch), None = disable batching entirely.
    #[serde(default)]
    pub batch_size: Option<usize>,
    /// Global output directory prefix (default: "out").
    /// Processor output_dir fields that start with "out/" will use this as the base instead.
    #[serde(default = "default_output_dir")]
    pub output_dir: String,
}

fn default_parallel() -> usize {
    0
}

fn default_output_dir() -> String {
    "out".into()
}

impl Default for BuildConfig {
    fn default() -> Self {
        Self {
            parallel: 0,
            batch_size: Some(0), // Default: batching enabled, no size limit
            output_dir: "out".into(),
        }
    }
}

/// Method used to restore files from cache
#[derive(Debug, Deserialize, Serialize, Clone, Copy, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum RestoreMethod {
    /// Auto-detect: use copy in CI environments (CI=true), hardlink otherwise.
    #[default]
    Auto,
    Hardlink,
    Copy,
}

impl RestoreMethod {
    /// Resolve `Auto` to a concrete method based on environment.
    pub fn resolve(self) -> Self {
        match self {
            RestoreMethod::Auto => {
                if std::env::var("CI").is_ok_and(|v| v == "true") {
                    RestoreMethod::Copy
                } else {
                    RestoreMethod::Hardlink
                }
            }
            other => other,
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct CacheConfig {
    #[serde(default)]
    pub restore_method: RestoreMethod,
    /// Whether to compress cached objects with zstd (default: false).
    /// Incompatible with hardlink restore method.
    #[serde(default)]
    pub compression: bool,
    /// Remote cache URL (e.g., "s3://bucket/prefix", "http://host:port/path", or local "file:///path")
    #[serde(default)]
    pub remote: Option<String>,
    /// Whether to push local builds to remote cache (default: true)
    #[serde(default = "default_true")]
    pub remote_push: bool,
    /// Whether to pull from remote cache on miss (default: true)
    #[serde(default = "default_true")]
    pub remote_pull: bool,
    /// Whether to use mtime pre-check to skip unchanged file checksums (default: true)
    #[serde(default = "default_true")]
    pub mtime_check: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            restore_method: RestoreMethod::default(),
            compression: false,
            remote: None,
            remote_push: true,
            remote_pull: true,
            mtime_check: true,
        }
    }
}

pub(crate) fn default_true() -> bool {
    true
}

/// A single processor instance parsed from the TOML config.
/// `[processor.pylint]` produces one instance with type_name="pylint", instance_name="pylint".
/// `[processor.pylint.core]` produces one with type_name="pylint", instance_name="pylint.core".
#[derive(Debug, Clone)]
pub(crate) struct ProcessorInstance {
    /// Instance name: "pylint" for single, "pylint.core" for named
    pub instance_name: String,
    /// Processor type name: always "pylint"
    pub type_name: String,
    /// The raw TOML config for this instance (deserialized lazily per processor type)
    pub config_toml: toml::Value,
    /// Source of every field in `config_toml` (user TOML, processor default, scan default, …).
    pub provenance: ProvenanceMap,
}

use crate::registries::{self as registry, ProcessorPlugin};

pub(crate) fn find_registry_entry(type_name: &str) -> Option<&'static ProcessorPlugin> {
    registry::all_plugins().find(|e| e.name == type_name)
}

/// Return all registered processor plugins.
pub(crate) fn registry_entries() -> impl Iterator<Item = &'static ProcessorPlugin> {
    registry::all_plugins()
}

/// Return all known builtin processor type names.
pub(crate) fn all_type_names() -> Vec<&'static str> {
    registry::all_plugins().map(|e| e.name).collect()
}

/// Check if a name is a known builtin processor type.
pub(crate) fn is_builtin_type(name: &str) -> bool {
    find_registry_entry(name).is_some()
}

/// Seed a provenance map with every top-level key currently present in `value`,
/// marking each as originating from the user's TOML. Defaults applied afterwards
/// will see these entries and not overwrite them.
///
/// Line numbers are filled in later by the toml_edit span pass; until then we
/// use line 0 as a sentinel meaning "from user TOML, line unknown".
pub(crate) fn seed_user_provenance(value: &toml::Value) -> ProvenanceMap {
    let mut map = ProvenanceMap::new();
    if let Some(table) = value.as_table() {
        for key in table.keys() {
            map.insert(key.clone(), FieldProvenance::UserToml { line: 0 });
        }
    }
    map
}

/// Resolve scan and processor defaults for an instance config in-place.
pub(crate) fn resolve_instance_defaults(
    type_name: &str,
    value: &mut toml::Value,
    provenance: &mut ProvenanceMap,
) -> anyhow::Result<()> {
    if find_registry_entry(type_name).is_some() {
        registry::apply_all_defaults(type_name, value, provenance);
    }
    Ok(())
}

impl ProcessorConfig {
    /// Collect unique scan directories from all declared instances.
    pub(crate) fn src_dirs(&self) -> Vec<String> {
        let mut dirs: Vec<String> = self.instances.iter()
            .flat_map(|inst| {
                inst.config_toml.get("src_dirs")
                    .and_then(|v| v.as_array())
                    .into_iter()
                    .flat_map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())))
                    .filter(|d| !d.is_empty())
            })
            .collect();
        dirs.sort();
        dirs.dedup();
        dirs
    }

    /// Return known fields for a builtin processor type, or None for Lua plugins.
    pub(crate) fn known_fields_for(type_name: &str) -> Option<&'static [&'static str]> {
        find_registry_entry(type_name).map(|e| (e.known_fields)())
    }

    /// Return checksum-affecting fields for a builtin processor type, or None for Lua plugins.
    pub(crate) fn checksum_fields_for(type_name: &str) -> Option<&'static [&'static str]> {
        find_registry_entry(type_name).map(|e| (e.checksum_fields)())
    }

    /// Return must fields (required non-empty fields) for a builtin processor type, or None for Lua plugins.
    pub(crate) fn must_fields_for(type_name: &str) -> Option<&'static [&'static str]> {
        find_registry_entry(type_name).map(|e| (e.must_fields)())
    }

    /// Return (field, description) pairs for a builtin processor type, or None for Lua plugins.
    pub(crate) fn field_descriptions_for(type_name: &str) -> Option<&'static [(&'static str, &'static str)]> {
        find_registry_entry(type_name).map(|e| (e.field_descriptions)())
    }

    /// Return the default src_dirs for a builtin processor type, or None for Lua plugins.
    pub(crate) fn default_src_dirs_for(type_name: &str) -> Option<&'static [&'static str]> {
        scan_defaults_for(type_name).map(|d| d.src_dirs)
    }

    /// Return the default config for a processor type as pretty JSON, or None if unknown.
    pub(crate) fn defconfig_json(type_name: &str) -> Option<String> {
        let entry = find_registry_entry(type_name)?;
        (entry.defconfig_json)(entry.name)
    }
}

/// Return scan defaults for a builtin processor type.
pub(crate) fn scan_defaults_for(type_name: &str) -> Option<ScanDefaultsData> {
    Some(match type_name {
        "tera" => ScanDefaultsData { src_dirs: &["tera.templates"], src_extensions: &[".tera"], src_exclude_dirs: &[] },
        "ruff" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "pylint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "mypy" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "pyrefly" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "black" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "doctest" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "pytest" => ScanDefaultsData { src_dirs: &["tests"], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "cc_single_file" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".c", ".cc"], src_exclude_dirs: &[] },
        "cc" => ScanDefaultsData { src_dirs: &[], src_extensions: &["cc.yaml"], src_exclude_dirs: &[] },
        "cppcheck" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".c", ".cc"], src_exclude_dirs: &[] },
        "clang_tidy" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".c", ".cc"], src_exclude_dirs: &[] },
        "zspell" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "shellcheck" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".sh", ".bash"], src_exclude_dirs: &[] },
        "luacheck" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".lua"], src_exclude_dirs: &[] },
        "make" => ScanDefaultsData { src_dirs: &[], src_extensions: &["Makefile"], src_exclude_dirs: &[] },
        "cargo" => ScanDefaultsData { src_dirs: &[], src_extensions: &["Cargo.toml"], src_exclude_dirs: &[] },
        "clippy" => ScanDefaultsData { src_dirs: &[], src_extensions: &["Cargo.toml"], src_exclude_dirs: &[] },
        "rumdl" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "yamllint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".yml", ".yaml"], src_exclude_dirs: &[] },
        "jq" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".json"], src_exclude_dirs: &[] },
        "jsonlint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".json"], src_exclude_dirs: &[] },
        "taplo" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".toml"], src_exclude_dirs: &[] },
        "json_schema" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".json"], src_exclude_dirs: &[] },
        "tags" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "pip" => ScanDefaultsData { src_dirs: &[], src_extensions: &["requirements.txt"], src_exclude_dirs: &[] },
        "requirements" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py"], src_exclude_dirs: &[] },
        "sphinx" => ScanDefaultsData { src_dirs: &[], src_extensions: &["conf.py"], src_exclude_dirs: &[] },
        "mdbook" => ScanDefaultsData { src_dirs: &[], src_extensions: &["book.toml"], src_exclude_dirs: &[] },
        "npm" => ScanDefaultsData { src_dirs: &[], src_extensions: &["package.json"], src_exclude_dirs: &[] },
        "gem" => ScanDefaultsData { src_dirs: &[], src_extensions: &["Gemfile"], src_exclude_dirs: &[] },
        "mdl" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "markdownlint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "aspell" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "marp" => ScanDefaultsData { src_dirs: &["marp"], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "pandoc" => ScanDefaultsData { src_dirs: &["pandoc"], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "markdown2html" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "pdflatex" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".tex"], src_exclude_dirs: &[] },
        "a2x" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".txt"], src_exclude_dirs: &[] },
        "ascii" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "terms" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "chromium" => ScanDefaultsData { src_dirs: &["out/marp"], src_extensions: &[".html"], src_exclude_dirs: &[] },
        "mako" => ScanDefaultsData { src_dirs: &["templates.mako"], src_extensions: &[".mako"], src_exclude_dirs: &[] },
        "jinja2" => ScanDefaultsData { src_dirs: &["templates.jinja2"], src_extensions: &[".j2"], src_exclude_dirs: &[] },
        "mermaid" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".mmd"], src_exclude_dirs: &[] },
        "drawio" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".drawio"], src_exclude_dirs: &[] },
        "libreoffice" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".odp"], src_exclude_dirs: &[] },
        "protobuf" => ScanDefaultsData { src_dirs: &["proto"], src_extensions: &[".proto"], src_exclude_dirs: &[] },
        "pdfunite" => ScanDefaultsData { src_dirs: &[], src_extensions: &["course.yaml"], src_exclude_dirs: &[] },
        "ipdfunite" => ScanDefaultsData { src_dirs: &[], src_extensions: &["course.yaml"], src_exclude_dirs: &[] },
        "script" => ScanDefaultsData { src_dirs: &[], src_extensions: &[], src_exclude_dirs: &[] },
        "creator" => ScanDefaultsData { src_dirs: &[], src_extensions: &[], src_exclude_dirs: &[] },
        "generator" => ScanDefaultsData { src_dirs: &[], src_extensions: &[], src_exclude_dirs: &[] },
        "explicit" => ScanDefaultsData { src_dirs: &[], src_extensions: &[], src_exclude_dirs: &[] },
        "linux_module" => ScanDefaultsData { src_dirs: &[], src_extensions: &["linux-module.yaml"], src_exclude_dirs: &[] },
        "cpplint" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".c", ".cc", ".h", ".hh"], src_exclude_dirs: &[] },
        "checkpatch" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".c", ".h"], src_exclude_dirs: &[] },
        "objdump" => ScanDefaultsData { src_dirs: &["out/cc_single_file"], src_extensions: &[".elf"], src_exclude_dirs: &[] },
        "prettier" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".css", ".scss", ".less", ".html", ".json", ".md", ".yaml", ".yml"], src_exclude_dirs: &[] },
        "eslint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"], src_exclude_dirs: &[] },
        "jshint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".js", ".jsx", ".mjs", ".cjs"], src_exclude_dirs: &[] },
        "htmlhint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".html", ".htm"], src_exclude_dirs: &[] },
        "tidy" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".html", ".htm"], src_exclude_dirs: &[] },
        "stylelint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".css", ".scss", ".sass", ".less"], src_exclude_dirs: &[] },
        "jslint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".js"], src_exclude_dirs: &[] },
        "standard" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".js"], src_exclude_dirs: &[] },
        "htmllint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".html", ".htm"], src_exclude_dirs: &[] },
        "php_lint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".php"], src_exclude_dirs: &[] },
        "perlcritic" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".pl", ".pm"], src_exclude_dirs: &[] },
        "xmllint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".xml", ".svg"], src_exclude_dirs: &[] },
        "svglint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".svg"], src_exclude_dirs: &[] },
        "svgo" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".svg"], src_exclude_dirs: &[] },
        "checkstyle" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".java"], src_exclude_dirs: &[] },
        "yq" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".yml", ".yaml"], src_exclude_dirs: &[] },
        "cmake" => ScanDefaultsData { src_dirs: &[], src_extensions: &["CMakeLists.txt"], src_exclude_dirs: &[] },
        "hadolint" => ScanDefaultsData { src_dirs: &[], src_extensions: &["Dockerfile"], src_exclude_dirs: &[] },
        "jekyll" => ScanDefaultsData { src_dirs: &[], src_extensions: &["_config.yml"], src_exclude_dirs: &[] },
        "sass" => ScanDefaultsData { src_dirs: &["sass"], src_extensions: &[".scss", ".sass"], src_exclude_dirs: &[] },
        "ijq" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".json"], src_exclude_dirs: &[] },
        "ijsonlint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".json"], src_exclude_dirs: &[] },
        "iyamllint" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".yml", ".yaml"], src_exclude_dirs: &[] },
        "iyamlschema" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".yml", ".yaml"], src_exclude_dirs: &[] },
        "itaplo" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".toml"], src_exclude_dirs: &[] },
        "imarkdown2html" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "isass" => ScanDefaultsData { src_dirs: &["sass"], src_extensions: &[".scss", ".sass"], src_exclude_dirs: &[] },
        "yaml2json" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".yml", ".yaml"], src_exclude_dirs: &[] },
        "rust_single_file" => ScanDefaultsData { src_dirs: &["src"], src_extensions: &[".rs"], src_exclude_dirs: &[] },
        "slidev" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "encoding" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py", ".rs", ".js", ".ts", ".c", ".cc", ".h", ".hh", ".java", ".rb", ".go", ".sh", ".bash", ".lua", ".pl", ".pm", ".php", ".md", ".yaml", ".yml", ".json", ".toml", ".xml", ".html", ".htm", ".css", ".scss", ".sass", ".tex", ".txt"], src_exclude_dirs: &[] },
        "duplicate_files" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py", ".rs", ".js", ".ts", ".c", ".cc", ".h", ".hh", ".java", ".rb", ".go", ".sh", ".md", ".yaml", ".yml", ".json", ".toml", ".xml", ".html", ".css"], src_exclude_dirs: &[] },
        "marp_images" => ScanDefaultsData { src_dirs: &["marp"], src_extensions: &[".md"], src_exclude_dirs: &[] },
        "license_header" => ScanDefaultsData { src_dirs: &[], src_extensions: &[".py", ".rs", ".js", ".ts", ".c", ".cc", ".h", ".hh", ".java", ".rb", ".go", ".sh", ".bash"], src_exclude_dirs: &[] },
        _ => return None,
    })
}

/// Return per-processor default values (command, dep_auto, batch override).
/// Only needed for processors whose defaults differ from the struct's Default impl.
pub(crate) fn processor_defaults_for(type_name: &str) -> Option<ProcessorDefaults> {
    let d = ProcessorDefaults::default();
    Some(match type_name {
        "ruff" => ProcessorDefaults { command: "ruff", dep_auto: &["ruff.toml", ".ruff.toml", "pyproject.toml"], ..d },
        "pylint" => ProcessorDefaults { command: "pylint", dep_auto: &[".pylintrc"], ..d },
        "pytest" => ProcessorDefaults { command: "pytest", dep_auto: &["conftest.py", "pytest.ini", "pyproject.toml"], ..d },
        "black" => ProcessorDefaults { command: "black", dep_auto: &["pyproject.toml"], ..d },
        "mypy" => ProcessorDefaults { command: "mypy", dep_auto: &["mypy.ini"], ..d },
        "pyrefly" => ProcessorDefaults { command: "pyrefly", dep_auto: &["pyproject.toml"], ..d },
        "rumdl" => ProcessorDefaults { command: "rumdl", dep_auto: &[".rumdl.toml"], ..d },
        "yamllint" => ProcessorDefaults { command: "yamllint", dep_auto: &[".yamllint", ".yamllint.yml", ".yamllint.yaml"], ..d },
        "jq" => ProcessorDefaults { command: "jq", ..d },
        "jsonlint" => ProcessorDefaults { command: "jsonlint", ..d },
        "taplo" => ProcessorDefaults { command: "taplo", dep_auto: &["taplo.toml", ".taplo.toml"], ..d },
        "cppcheck" => ProcessorDefaults { command: "cppcheck", args: &["--error-exitcode=1", "--enable=warning,style,performance,portability"], dep_auto: &[".cppcheck"], batch: Some(false), ..d },
        "cpplint" => ProcessorDefaults { command: "cpplint", ..d },
        "checkpatch" => ProcessorDefaults { command: "checkpatch.pl", ..d },
        "shellcheck" => ProcessorDefaults { command: "shellcheck", dep_auto: &[".shellcheckrc"], ..d },
        "luacheck" => ProcessorDefaults { command: "luacheck", dep_auto: &[".luacheckrc"], ..d },
        "prettier" => ProcessorDefaults { command: "prettier", dep_auto: &[".prettierrc", ".prettierrc.json", ".prettierrc.js", ".prettierrc.yml", ".prettierrc.yaml", ".prettierrc.toml", ".prettierrc.cjs", ".prettierrc.mjs", "prettier.config.js", "prettier.config.cjs", "prettier.config.mjs"], ..d },
        "eslint" => ProcessorDefaults { command: "eslint", dep_auto: &[".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.yml", ".eslintrc.yaml", ".eslintrc.cjs", "eslint.config.js", "eslint.config.mjs", "eslint.config.cjs"], ..d },
        "jshint" => ProcessorDefaults { command: "jshint", dep_auto: &[".jshintrc"], ..d },
        "htmlhint" => ProcessorDefaults { command: "htmlhint", dep_auto: &[".htmlhintrc"], ..d },
        "stylelint" => ProcessorDefaults { command: "stylelint", dep_auto: &[".stylelintrc", ".stylelintrc.json", ".stylelintrc.yml", ".stylelintrc.yaml", ".stylelintrc.js", ".stylelintrc.cjs", "stylelint.config.js", "stylelint.config.cjs"], ..d },
        "perlcritic" => ProcessorDefaults { command: "perlcritic", dep_auto: &[".perlcriticrc"], ..d },
        "svglint" => ProcessorDefaults { command: "svglint", dep_auto: &[".svglintrc.js"], ..d },
        "svgo" => ProcessorDefaults { command: "svgo", dep_auto: &["svgo.config.js", "svgo.config.mjs", "svgo.config.cjs"], ..d },
        "checkstyle" => ProcessorDefaults { command: "checkstyle", dep_auto: &["checkstyle.xml"], ..d },
        "cmake" => ProcessorDefaults { command: "cmake", ..d },
        "doctest" => ProcessorDefaults { command: "python3", ..d },
        "hadolint" => ProcessorDefaults { command: "hadolint", ..d },
        "htmllint" => ProcessorDefaults { command: "htmllint", ..d },
        "jslint" => ProcessorDefaults { command: "jslint", ..d },
        "php_lint" => ProcessorDefaults { command: "php", ..d },
        "slidev" => ProcessorDefaults { command: "slidev", ..d },
        "standard" => ProcessorDefaults { command: "standard", ..d },
        "tidy" => ProcessorDefaults { command: "tidy", ..d },
        "xmllint" => ProcessorDefaults { command: "xmllint", ..d },
        "yq" => ProcessorDefaults { command: "yq", ..d },
        // Generators
        "marp" => ProcessorDefaults { output_dir: "out/marp", formats: &["pdf"], args: &["--html", "--allow-local-files"], command: "marp", ..d },
        "markdown2html" => ProcessorDefaults { output_dir: "out/markdown2html", command: "markdown", ..d },
        "chromium" => ProcessorDefaults { output_dir: "out/chromium", command: "google-chrome", ..d },
        "mermaid" => ProcessorDefaults { output_dir: "out/mermaid", formats: &["png"], command: "mmdc", ..d },
        "drawio" => ProcessorDefaults { output_dir: "out/drawio", formats: &["png"], command: "drawio", ..d },
        "libreoffice" => ProcessorDefaults { output_dir: "out/libreoffice", formats: &["pdf"], command: "libreoffice", ..d },
        "protobuf" => ProcessorDefaults { output_dir: "out/protobuf", command: "protoc", ..d },
        "cc_single_file" => ProcessorDefaults { output_dir: "out/cc_single_file", ..d },
        "cargo" => ProcessorDefaults { command: "build", ..d },
        "clippy" => ProcessorDefaults { command: "clippy", ..d },
        "generator" => ProcessorDefaults { output_dir: "out/generator", ..d },
        "explicit" => ProcessorDefaults { ..d },
        "sphinx" => ProcessorDefaults { command: "sphinx-build", output_dir: "docs", ..d },
        "mdbook" => ProcessorDefaults { command: "mdbook", output_dir: "book", ..d },
        "npm" => ProcessorDefaults { command: "npm", ..d },
        "sass" => ProcessorDefaults { output_dir: "out/sass", command: "sass", ..d },
        "pandoc" => ProcessorDefaults { output_dir: "out/pandoc", formats: &["pdf", "html", "docx"], command: "pandoc", ..d },
        "a2x" => ProcessorDefaults { output_dir: "out/a2x", command: "a2x", ..d },
        "objdump" => ProcessorDefaults { output_dir: "out/objdump", command: "objdump", ..d },
        "imarkdown2html" => ProcessorDefaults { output_dir: "out/imarkdown2html", ..d },
        "isass" => ProcessorDefaults { output_dir: "out/isass", ..d },
        "yaml2json" => ProcessorDefaults { output_dir: "out/yaml2json", ..d },
        // Checkers with custom dep_auto
        "mdl" => ProcessorDefaults { command: "mdl", dep_auto: &[".mdlrc"], ..d },
        "markdownlint" => ProcessorDefaults { command: "markdownlint", dep_auto: &[".markdownlint.json", ".markdownlint.jsonc", ".markdownlint.yaml"], ..d },
        "aspell" => ProcessorDefaults { command: "aspell", dep_auto: &[".aspell.conf", ".aspell.en.pws", ".aspell.en.prepl"], ..d },
        // Generators with custom output_dir
        "pdflatex" => ProcessorDefaults { command: "pdflatex", output_dir: "out/pdflatex", ..d },
        "rust_single_file" => ProcessorDefaults { command: "rustc", output_dir: "out/rust_single_file", ..d },
        "pdfunite" => ProcessorDefaults { command: "pdfunite", output_dir: "out/pdfunite", ..d },
        "ipdfunite" => ProcessorDefaults { output_dir: "out/ipdfunite", ..d },
        // Creators with custom command
        "gem" => ProcessorDefaults { command: "bundle", ..d },
        "pip" => ProcessorDefaults { command: "pip", ..d },
        "make" => ProcessorDefaults { command: "make", ..d },
        _ => return None,
    })
}

/// Apply processor-specific defaults to a config TOML value.
/// Sets command and dep_auto if they weren't explicitly provided by the user.
/// Every field that's actually injected is recorded in `provenance` as a processor default.
/// Fields already present in `provenance` (i.e. user-set) are skipped.
pub(crate) fn apply_processor_defaults(
    type_name: &str,
    value: &mut toml::Value,
    provenance: &mut ProvenanceMap,
) {
    let defaults = match processor_defaults_for(type_name) {
        Some(d) => d,
        None => return,
    };
    let table = match value.as_table_mut() {
        Some(t) => t,
        None => return,
    };
    set_string_default(table, "command", defaults.command, provenance, FieldProvenance::ProcessorDefault);
    set_string_default(table, "output_dir", defaults.output_dir, provenance, FieldProvenance::ProcessorDefault);
    set_string_array_default(table, "dep_auto", defaults.dep_auto, provenance, FieldProvenance::ProcessorDefault);
    set_string_array_default(table, "formats", defaults.formats, provenance, FieldProvenance::ProcessorDefault);
    set_string_array_default(table, "args", defaults.args, provenance, FieldProvenance::ProcessorDefault);
    if let Some(batch) = defaults.batch
        && !table.contains_key("batch")
    {
        table.insert("batch".into(), toml::Value::Boolean(batch));
        provenance::record_if_absent(provenance, "batch", FieldProvenance::ProcessorDefault);
    }
}

fn set_string_default(
    table: &mut toml::map::Map<String, toml::Value>,
    key: &str,
    val: &str,
    provenance: &mut ProvenanceMap,
    source: FieldProvenance,
) {
    if !val.is_empty() && !table.contains_key(key) {
        table.insert(key.into(), toml::Value::String(val.into()));
        provenance::record_if_absent(provenance, key, source);
    }
}

fn set_string_array_default(
    table: &mut toml::map::Map<String, toml::Value>,
    key: &str,
    vals: &[&str],
    provenance: &mut ProvenanceMap,
    source: FieldProvenance,
) {
    if !vals.is_empty() && !table.contains_key(key) {
        let arr: Vec<toml::Value> = vals.iter().map(|s| toml::Value::String(s.to_string())).collect();
        table.insert(key.into(), toml::Value::Array(arr));
        provenance::record_if_absent(provenance, key, source);
    }
}

fn set_empty_array_default(
    table: &mut toml::map::Map<String, toml::Value>,
    key: &str,
    provenance: &mut ProvenanceMap,
    source: FieldProvenance,
) {
    if !table.contains_key(key) {
        table.insert(key.into(), toml::Value::Array(Vec::new()));
        provenance::record_if_absent(provenance, key, source);
    }
}

fn set_maybe_empty_array_default(
    table: &mut toml::map::Map<String, toml::Value>,
    key: &str,
    vals: &[&str],
    provenance: &mut ProvenanceMap,
    source: FieldProvenance,
) {
    if !table.contains_key(key) {
        let arr: Vec<toml::Value> = vals.iter().map(|s| toml::Value::String(s.to_string())).collect();
        table.insert(key.into(), toml::Value::Array(arr));
        provenance::record_if_absent(provenance, key, source);
    }
}

/// Apply scan defaults to a config TOML value.
/// Sets src_dirs, src_extensions, and src_exclude_dirs if not explicitly provided.
/// Every field that's actually injected is recorded in `provenance` as a scan default.
pub(crate) fn apply_scan_defaults(
    type_name: &str,
    value: &mut toml::Value,
    provenance: &mut ProvenanceMap,
) {
    let defaults = match scan_defaults_for(type_name) {
        Some(d) => d,
        None => return,
    };
    let table = match value.as_table_mut() {
        Some(t) => t,
        None => return,
    };
    set_maybe_empty_array_default(table, "src_dirs", defaults.src_dirs, provenance, FieldProvenance::ScanDefault);
    set_maybe_empty_array_default(table, "src_extensions", defaults.src_extensions, provenance, FieldProvenance::ScanDefault);
    set_maybe_empty_array_default(table, "src_exclude_dirs", defaults.src_exclude_dirs, provenance, FieldProvenance::ScanDefault);
    set_empty_array_default(table, "src_exclude_files", provenance, FieldProvenance::ScanDefault);
    set_empty_array_default(table, "src_exclude_paths", provenance, FieldProvenance::ScanDefault);
    set_empty_array_default(table, "src_files", provenance, FieldProvenance::ScanDefault);
}

/// Processor configuration: a collection of declared processor instances.
/// Each `[processor.TYPE]` or `[processor.TYPE.NAME]` section in rsconstruct.toml
/// creates a ProcessorInstance. No instances exist by default — only what's declared.
#[derive(Debug, Default)]
pub(crate) struct ProcessorConfig {
    /// All declared processor instances
    pub instances: Vec<ProcessorInstance>,
    /// Lua plugin configs (processor types not in the builtin registry)
    pub extra: HashMap<String, toml::Value>,
}

impl Serialize for ProcessorConfig {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(None)?;
        for inst in &self.instances {
            // For named instances (type.name), we need to nest
            if inst.instance_name.contains('.') {
                // Handled as part of the parent type table
            } else {
                map.serialize_entry(&inst.instance_name, &inst.config_toml)?;
            }
        }
        // Group named instances by type
        let mut types: HashMap<&str, Vec<&ProcessorInstance>> = HashMap::new();
        for inst in &self.instances {
            if let Some(dot) = inst.instance_name.find('.') {
                let type_name = &inst.instance_name[..dot];
                types.entry(type_name).or_default().push(inst);
            }
        }
        for (type_name, insts) in &types {
            let mut table = toml::map::Map::new();
            for inst in insts {
                let name = &inst.instance_name[type_name.len() + 1..];
                table.insert(name.to_string(), inst.config_toml.clone());
            }
            map.serialize_entry(type_name, &toml::Value::Table(table))?;
        }
        for (name, value) in &self.extra {
            map.serialize_entry(name, value)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for ProcessorConfig {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let table = toml::Value::deserialize(deserializer)?;
        ProcessorConfig::from_toml(&table).map_err(serde::de::Error::custom)
    }
}

impl ProcessorConfig {
    /// Parse the `[processor]` table from TOML into instances.
    pub(crate) fn from_toml(value: &toml::Value) -> Result<Self> {
        let table = match value.as_table() {
            Some(t) => t,
            None => return Ok(Self::default()),
        };

        let mut instances = Vec::new();
        let mut extra = HashMap::new();

        for (key, val) in table {
            let sub_table = match val.as_table() {
                Some(t) => t,
                None => continue, // skip non-table entries
            };

            if is_builtin_type(key) {
                // Check if this is single-instance or multi-instance
                if Self::is_multi_instance(key, sub_table) {
                    // Multi-instance: [processor.pylint.core], [processor.pylint.tests]
                    for (name, inst_val) in sub_table {
                        let instance_name = format!("{}.{}", key, name);
                        let mut config = inst_val.clone();
                        let mut provenance = seed_user_provenance(&config);
                        resolve_instance_defaults(key, &mut config, &mut provenance)?;
                        instances.push(ProcessorInstance {
                            instance_name,
                            type_name: key.clone(),
                            config_toml: config,
                            provenance,
                        });
                    }
                } else {
                    // Single instance: [processor.pylint]
                    let mut config = val.clone();
                    let mut provenance = seed_user_provenance(&config);
                    resolve_instance_defaults(key, &mut config, &mut provenance)?;
                    instances.push(ProcessorInstance {
                        instance_name: key.clone(),
                        type_name: key.clone(),
                        config_toml: config,
                        provenance,
                    });
                }
            } else {
                // Unknown type — Lua plugin
                extra.insert(key.clone(), val.clone());
            }
        }

        Ok(Self { instances, extra })
    }

    /// Determine if a processor section contains named sub-instances (multi-instance)
    /// or direct config fields (single-instance).
    ///
    /// Heuristic: if ALL values are tables AND none of the keys match known config
    /// field names for this processor type, it's multi-instance.
    fn is_multi_instance(type_name: &str, table: &toml::map::Map<String, toml::Value>) -> bool {
        if table.is_empty() {
            return false;
        }

        let known = Self::known_fields_for(type_name);
        let known_fields: Vec<&str> = match known {
            Some(fields) => fields.iter()
                .chain(SCAN_CONFIG_FIELDS.iter())
                .copied()
                .collect(),
            None => return false,
        };

        // If ANY key is a known config field, it's single-instance
        for key in table.keys() {
            if known_fields.contains(&key.as_str()) {
                return false;
            }
        }

        // If ALL values are tables, it's multi-instance
        table.values().all(|v| v.is_table())
    }

    /// Resolve scan defaults for all instances.
    pub(crate) fn resolve_scan_defaults(&mut self) {
        for inst in &mut self.instances {
            resolve_instance_defaults(&inst.type_name, &mut inst.config_toml, &mut inst.provenance).ok();
        }
    }

    /// Rewrite output paths in processor configs:
    /// 1. For named instances (e.g., `pylint.core`), remap default `out/{type_name}`
    ///    to `out/{instance_name}` so each instance gets its own output directory.
    /// 2. If the global `output_dir` is not "out", replace the `out/` prefix with the
    ///    global value (e.g., `build/` → `build/marp`).
    ///
    /// When a field was originally a ProcessorDefault and gets rewritten here, its
    /// provenance is upgraded to OutputDirDefault so `config show` can explain why
    /// the value differs from the processor's own default.
    pub(crate) fn apply_output_dir_defaults(&mut self, global_output_dir: &str) {
        for inst in &mut self.instances {
            let type_default_prefix = format!("out/{}", inst.type_name);
            let instance_prefix = format!("{}/{}", global_output_dir, inst.instance_name);

            for field in &["output_dir", "output"] {
                let val = match inst.config_toml.get(field).and_then(|v| v.as_str()).map(|s| s.to_string()) {
                    Some(v) => v,
                    None => continue,
                };
                let new_val = if inst.instance_name != inst.type_name && val.starts_with(&type_default_prefix) {
                    // Named instance: remap out/{type} → {global}/{instance}
                    format!("{}{}", instance_prefix, &val[type_default_prefix.len()..])
                } else if global_output_dir != "out" && val.starts_with("out/") {
                    // Global output dir override: remap out/ → {global}/
                    format!("{}/{}", global_output_dir, &val[4..])
                } else {
                    continue;
                };
                if let Some(table) = inst.config_toml.as_table_mut() {
                    table.insert(field.to_string(), toml::Value::String(new_val));
                }
                // Only upgrade provenance if the field wasn't user-set — we must not
                // overwrite a UserToml entry, since the user explicitly chose the
                // pre-rewrite value.
                if matches!(
                    inst.provenance.get(*field),
                    Some(FieldProvenance::ProcessorDefault) | None,
                ) {
                    inst.provenance.insert((*field).to_string(), FieldProvenance::OutputDirDefault);
                }
            }
        }
    }

    /// Get the first instance of a given type (for single-instance access).
    /// Returns None if no instance of that type is declared.
    pub(crate) fn first_instance_of_type(&self, type_name: &str) -> Option<&ProcessorInstance> {
        self.instances.iter().find(|i| i.type_name == type_name)
    }

    /// Get a typed config value from an instance's TOML config.
    /// Returns the default if the instance is not declared or the field is missing.
    pub(crate) fn instance_field_str(&self, type_name: &str, field: &str) -> Option<String> {
        self.first_instance_of_type(type_name)
            .and_then(|inst| inst.config_toml.get(field))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }
}


pub(crate) fn default_cc_compiler() -> String {
    "gcc".into()
}

pub(crate) fn default_cxx_compiler() -> String {
    "g++".into()
}

pub(crate) fn default_output_suffix() -> String {
    ".elf".into()
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct CompletionsConfig {
    #[serde(default = "default_shells")]
    pub shells: Vec<String>,
}

fn default_shells() -> Vec<String> {
    vec!["bash".into()]
}

impl Default for CompletionsConfig {
    fn default() -> Self {
        Self { shells: vec!["bash".into()] }
    }
}

/// A single analyzer instance parsed from the TOML config.
/// `[analyzer.cpp]` produces one instance with type_name="cpp", instance_name="cpp".
/// `[analyzer.cpp.kernel]` produces one with type_name="cpp", instance_name="cpp.kernel".
#[derive(Debug, Clone)]
pub(crate) struct AnalyzerInstance {
    /// Instance name: "cpp" for single, "cpp.kernel" for named
    pub instance_name: String,
    /// Analyzer type name (must match a registered AnalyzerPlugin name)
    pub type_name: String,
    /// The raw TOML config for this instance
    pub config_toml: toml::Value,
    /// Source of every field in `config_toml` (user TOML, serde default, …).
    pub provenance: ProvenanceMap,
}

/// Configuration for dependency analyzers.
/// Each `[analyzer.NAME]` section in rsconstruct.toml creates an AnalyzerInstance.
/// No analyzers run unless explicitly declared in the config.
#[derive(Debug, Default)]
pub(crate) struct AnalyzerConfig {
    /// All declared analyzer instances
    pub instances: Vec<AnalyzerInstance>,
}

impl Serialize for AnalyzerConfig {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(None)?;
        // Emit single instances directly; group named sub-instances under the type.
        for inst in &self.instances {
            if inst.instance_name == inst.type_name {
                map.serialize_entry(&inst.instance_name, &inst.config_toml)?;
            }
        }
        let mut types: HashMap<&str, Vec<&AnalyzerInstance>> = HashMap::new();
        for inst in &self.instances {
            if inst.instance_name != inst.type_name {
                types.entry(inst.type_name.as_str()).or_default().push(inst);
            }
        }
        for (type_name, insts) in &types {
            let mut table = toml::map::Map::new();
            for inst in insts {
                let name = &inst.instance_name[type_name.len() + 1..];
                table.insert(name.to_string(), inst.config_toml.clone());
            }
            map.serialize_entry(type_name, &toml::Value::Table(table))?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for AnalyzerConfig {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let table = toml::Value::deserialize(deserializer)?;
        AnalyzerConfig::from_toml(&table).map_err(serde::de::Error::custom)
    }
}

impl AnalyzerConfig {
    /// Parse the `[analyzer]` table from TOML into instances.
    ///
    /// Supports both single-instance and multi-instance syntax:
    /// - `[analyzer.cpp]` with config fields → one instance, instance_name="cpp"
    /// - `[analyzer.cpp.kernel]` + `[analyzer.cpp.userspace]` → two instances,
    ///   instance_name="cpp.kernel" and "cpp.userspace"
    pub(crate) fn from_toml(value: &toml::Value) -> Result<Self> {
        let table = match value.as_table() {
            Some(t) => t,
            None => return Ok(Self::default()),
        };

        let mut instances = Vec::new();
        for (type_name, val) in table {
            if registry::find_analyzer_plugin(type_name).is_none() {
                anyhow::bail!("Unknown analyzer '{}'. Run 'rsconstruct analyzers list' to see available analyzers.", type_name);
            }
            let sub_table = match val.as_table() {
                Some(t) => t,
                None => anyhow::bail!("Expected [analyzer.{}] to be a table", type_name),
            };
            if Self::is_multi_instance(sub_table) {
                for (name, inst_val) in sub_table {
                    let provenance = seed_user_provenance(inst_val);
                    instances.push(AnalyzerInstance {
                        instance_name: format!("{}.{}", type_name, name),
                        type_name: type_name.clone(),
                        config_toml: inst_val.clone(),
                        provenance,
                    });
                }
            } else {
                let provenance = seed_user_provenance(val);
                instances.push(AnalyzerInstance {
                    instance_name: type_name.clone(),
                    type_name: type_name.clone(),
                    config_toml: val.clone(),
                    provenance,
                });
            }
        }
        Ok(Self { instances })
    }

    /// Multi-instance iff the table is non-empty and every value is itself a
    /// table. Single-instance if any value is a scalar/array (i.e. a config field).
    fn is_multi_instance(table: &toml::map::Map<String, toml::Value>) -> bool {
        !table.is_empty() && table.values().all(|v| v.is_table())
    }

}

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
#[serde(deny_unknown_fields)]
pub(crate) struct GraphConfig {
    #[serde(default)]
    pub viewer: Option<String>,
    /// Reject products with no input files. Default: true.
    #[serde(default = "default_true")]
    pub validate_empty_inputs: bool,
    /// Validate that dependency references point to existing products. Default: true.
    #[serde(default = "default_true")]
    pub validate_dep_references: bool,
    /// Warn when the same input file appears in multiple products of the same processor. Default: false.
    #[serde(default)]
    pub validate_duplicate_inputs: bool,
    /// Check for cycles immediately after resolving dependencies (rather than at topological sort time). Default: false.
    #[serde(default)]
    pub validate_early_cycles: bool,
}

/// Expected TOML type for a config field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FieldType {
    String,
    Bool,
    Integer,
    StringArray,
    /// Array of tables (e.g., [[processor.cc_single_file.compilers]])
    TableArray,
}

impl FieldType {
    fn label(self) -> &'static str {
        match self {
            FieldType::String => "a string",
            FieldType::Bool => "a boolean",
            FieldType::Integer => "an integer",
            FieldType::StringArray => "an array of strings",
            FieldType::TableArray => "an array of tables",
        }
    }

    /// Check whether a TOML value matches this expected type.
    fn matches(self, value: &toml::Value) -> bool {
        match self {
            FieldType::String => value.is_str(),
            FieldType::Bool => value.as_bool().is_some(),
            FieldType::Integer => value.is_integer(),
            FieldType::StringArray => value.as_array()
                .is_some_and(|arr| arr.iter().all(|v| v.is_str())),
            FieldType::TableArray => value.as_array()
                .is_some_and(|arr| arr.iter().all(|v| v.is_table())),
        }
    }

    fn describe_value(value: &toml::Value) -> &'static str {
        match value {
            toml::Value::String(_) => "a string",
            toml::Value::Integer(_) => "an integer",
            toml::Value::Float(_) => "a float",
            toml::Value::Boolean(_) => "a boolean",
            toml::Value::Datetime(_) => "a datetime",
            toml::Value::Array(_) => "an array",
            toml::Value::Table(_) => "a table",
        }
    }
}

/// Return the expected TOML type for a processor config field.
/// Fields common to all processors (scan fields, enabled, args, dep_inputs)
/// are handled generically. Processor-specific fields are looked up by processor name.
fn expected_field_type(processor: &str, field: &str) -> Option<FieldType> {
    // Scan fields — shared by all processors
    match field {
        "src_dirs" => return Some(FieldType::StringArray),
        "src_extensions" => return Some(FieldType::StringArray),
        "src_exclude_dirs" => return Some(FieldType::StringArray),
        "src_exclude_files" => return Some(FieldType::StringArray),
        "src_exclude_paths" => return Some(FieldType::StringArray),
        // Common processor fields
        "args" => return Some(FieldType::StringArray),
        "dep_inputs" => return Some(FieldType::StringArray),
        "dep_auto" => return Some(FieldType::StringArray),
        _ => {}
    }

    // Processor-specific fields
    match (processor, field) {
        // tera
        // tera has no processor-specific fields
        // ruff
        ("ruff", "command") => Some(FieldType::String),
        // cc_single_file
        ("cc_single_file", "cc" | "cxx" | "output_suffix") => Some(FieldType::String),
        ("cc_single_file", "cflags" | "cxxflags" | "ldflags" | "include_paths") => Some(FieldType::StringArray),
        ("cc_single_file", "include_scanner") => Some(FieldType::String),
        ("cc_single_file", "compilers") => Some(FieldType::TableArray),
        // cc (full project builds)
        ("cc", "cc" | "cxx") => Some(FieldType::String),
        ("cc", "cflags" | "cxxflags" | "ldflags" | "include_dirs") => Some(FieldType::StringArray),
        ("cc", "single_invocation" | "cache_output_dir") => Some(FieldType::Bool),
        // cppcheck — only common fields
        // clang_tidy
        ("clang_tidy", "compiler_args") => Some(FieldType::StringArray),
        // zspell
        ("zspell", "language" | "words_file") => Some(FieldType::String),
        ("zspell", "auto_add_words") => Some(FieldType::Bool),
        // make
        ("make", "command" | "target") => Some(FieldType::String),
        // cargo / clippy
        ("cargo", "profiles") => Some(FieldType::StringArray),
        ("cargo" | "clippy", "cargo" | "command") => Some(FieldType::String),
        // mypy, pyrefly, shellcheck, rumdl, yamllint, jq, jsonlint, taplo
        ("mypy" | "pyrefly" | "shellcheck" | "luacheck" | "script", "checker") => Some(FieldType::String),
        ("rumdl" | "yamllint" | "jsonlint" | "taplo", "linter") => Some(FieldType::String),
        ("jq", "checker") => Some(FieldType::String),
        // tags
        ("tags", "output" | "tags_dir") => Some(FieldType::String),
        // pip
        ("pip", "command") => Some(FieldType::String),
        // sphinx
        ("sphinx", "command" | "output_dir" | "working_dir") => Some(FieldType::String),
        // mdbook
        ("mdbook", "command" | "output_dir") => Some(FieldType::String),
        // npm
        ("npm", "command") => Some(FieldType::String),
        // gem
        ("gem", "command" | "gem_home") => Some(FieldType::String),
        // mdl
        ("mdl", "gem_home" | "command" | "gem_stamp") => Some(FieldType::String),
        ("mdl", "local_repo") => Some(FieldType::Bool),
        // markdownlint
        ("markdownlint", "command" | "npm_stamp") => Some(FieldType::String),
        ("markdownlint", "local_repo") => Some(FieldType::Bool),
        // aspell
        ("aspell", "command" | "conf" | "words_file") => Some(FieldType::String),
        ("aspell", "auto_add_words") => Some(FieldType::Bool),
        // marp
        ("marp", "marp_bin" | "output_dir") => Some(FieldType::String),
        ("marp", "formats") => Some(FieldType::StringArray),
        // pandoc
        ("pandoc", "pandoc" | "output_dir") => Some(FieldType::String),
        ("pandoc", "formats") => Some(FieldType::StringArray),
        // markdown
        ("markdown2html", "markdown_bin" | "output_dir") => Some(FieldType::String),
        // pdflatex
        ("pdflatex", "command" | "output_dir") => Some(FieldType::String),
        ("pdflatex", "runs") => Some(FieldType::Integer),
        ("pdflatex", "qpdf") => Some(FieldType::Bool),
        // a2x
        ("a2x", "a2x" | "output_dir") => Some(FieldType::String),
        ("chromium", "chromium_bin" | "output_dir") => Some(FieldType::String),
        // mermaid
        ("mermaid", "mmdc_bin" | "output_dir") => Some(FieldType::String),
        ("mermaid", "formats") => Some(FieldType::StringArray),
        // drawio
        ("drawio", "drawio_bin" | "output_dir") => Some(FieldType::String),
        ("drawio", "formats") => Some(FieldType::StringArray),
        // libreoffice
        ("libreoffice", "libreoffice_bin" | "output_dir") => Some(FieldType::String),
        ("libreoffice", "formats") => Some(FieldType::StringArray),
        // pdfunite
        ("pdfunite", "command" | "source_dir" | "source_ext" | "source_output_dir" | "output_dir") => Some(FieldType::String),
        // objdump
        ("objdump", "output_dir") => Some(FieldType::String),
        // cache_output_dir — shared by creators
        ("cargo" | "sphinx" | "mdbook" | "npm" | "gem", "cache_output_dir") => Some(FieldType::Bool),
        _ => None,
    }
}

/// Validate fields in a single processor config table.
fn validate_single_processor(
    type_name: &str,
    section_label: &str,
    table: &toml::map::Map<String, toml::Value>,
    errors: &mut Vec<String>,
) {
    let own_fields: &[&str] = match ProcessorConfig::known_fields_for(type_name) {
        Some(fields) => fields,
        None => return, // unknown = Lua plugin, skip
    };

    for (key, field_value) in table {
        if !own_fields.contains(&key.as_str()) && !SCAN_CONFIG_FIELDS.contains(&key.as_str()) {
            let all_fields: Vec<&str> = own_fields.iter()
                .chain(SCAN_CONFIG_FIELDS.iter())
                .copied()
                .collect();
            errors.push(format!(
                "[{}]: unknown field '{}' (valid fields: {})",
                section_label, key, all_fields.join(", ")
            ));
            continue;
        }

        if let Some(expected) = expected_field_type(type_name, key)
            && !expected.matches(field_value)
        {
            errors.push(format!(
                "[{}]: field '{}' must be {}, got {} ({})",
                section_label, key, expected.label(),
                FieldType::describe_value(field_value),
                field_value,
            ));
        }
    }

    // Check that all must_fields are present and non-empty
    if let Some(must) = ProcessorConfig::must_fields_for(type_name) {
        for field in must {
            match table.get(*field) {
                None => {
                    errors.push(format!(
                        "[{}]: required field '{}' must be specified",
                        section_label, field,
                    ));
                }
                Some(toml::Value::Array(arr)) if arr.is_empty() => {
                    errors.push(format!(
                        "[{}]: required field '{}' must not be empty",
                        section_label, field,
                    ));
                }
                Some(toml::Value::String(s)) if s.is_empty() => {
                    errors.push(format!(
                        "[{}]: required field '{}' must not be empty",
                        section_label, field,
                    ));
                }
                _ => {} // present and non-empty: OK
            }
        }
    }

    // Require src_dirs for processors whose default would scan the project root.
    // This prevents accidentally scanning everything when the user forgets to set src_dirs.
    // Exempt processors that don't use src_dirs for file discovery,
    // and processors that specify src_files (files are explicitly listed).
    const SCAN_DIRS_EXEMPT: &[&str] = &["explicit", "pdfunite", "ipdfunite"];
    let has_match_paths = table.get("src_files")
        .and_then(|v| v.as_array())
        .is_some_and(|arr| !arr.is_empty());
    if ProcessorConfig::default_src_dirs_for(type_name).is_some_and(|dirs| dirs.is_empty())
    && !SCAN_DIRS_EXEMPT.contains(&type_name)
    && !has_match_paths {
        match table.get("src_dirs") {
            None => {
                errors.push(format!(
                    "[{}]: 'src_dirs' must be specified (this processor defaults to scanning the project root)",
                    section_label,
                ));
            }
            Some(toml::Value::Array(arr))
                if arr.len() == 1
                    && arr[0].as_str().is_some_and(|s| s.is_empty()) =>
            {
                errors.push(format!(
                    "[{}]: 'src_dirs' must not contain empty strings; specify actual directories to scan",
                    section_label,
                ));
            }
            _ => {} // present and non-empty: OK
        }
    }
}

/// Validate that all fields in `[processor.X]` sections are known fields for that processor
/// and have the correct TOML types. Supports both single-instance and multi-instance formats.
/// Returns a list of error strings (empty if valid). `Config::load` combines this with the
/// analyzer validator output under a single "Invalid config:" header.
fn validate_processor_fields_raw(raw: &toml::Value) -> Vec<String> {
    let processor_table = match raw.get("processor").and_then(|v| v.as_table()) {
        Some(t) => t,
        None => return Vec::new(),
    };

    let mut errors = Vec::new();

    for (name, value) in processor_table {
        let table = match value.as_table() {
            Some(t) => t,
            None => continue, // skip non-table entries
        };

        if !is_builtin_type(name) {
            // Check if there's a matching Lua plugin file
            let plugins_dir = raw.get("plugins")
                .and_then(|p| p.get("dir"))
                .and_then(|d| d.as_str())
                .unwrap_or(DEFAULT_PLUGINS_DIR);
            let plugin_path = std::path::Path::new(plugins_dir)
                .join(format!("{}.lua", name));
            if !plugin_path.exists() {
                errors.push(format!(
                    "[processor.{}]: unknown processor type '{}' (not a builtin processor or Lua plugin at {})",
                    name, name, plugin_path.display(),
                ));
            }
            continue;
        }

        // Check if multi-instance
        if ProcessorConfig::is_multi_instance(name, table) {
            for (inst_name, inst_value) in table {
                if let Some(inst_table) = inst_value.as_table() {
                    let section = format!("processor.{}.{}", name, inst_name);
                    validate_single_processor(name, &section, inst_table, &mut errors);
                }
            }
        } else {
            let section = format!("processor.{}", name);
            validate_single_processor(name, &section, table, &mut errors);
        }
    }

    errors
}

/// Validate `[analyzer.X]` sections: reject unknown analyzer types and unknown
/// fields within each section. Runs at config-load time, before any analyzer
/// is instantiated, so users see schema errors up front instead of at build
/// time. Returns a list of error strings (empty if valid). `Config::load`
/// combines this with the processor validator output under a single
/// "Invalid config:" header.
fn validate_analyzer_fields_raw(raw: &toml::Value) -> Vec<String> {
    let analyzer_table = match raw.get("analyzer").and_then(|v| v.as_table()) {
        Some(t) => t,
        None => return Vec::new(),
    };

    let mut errors = Vec::new();

    for (type_name, value) in analyzer_table {
        let table = match value.as_table() {
            Some(t) => t,
            None => {
                errors.push(format!(
                    "[analyzer.{}]: expected a table", type_name,
                ));
                continue;
            }
        };

        let plugin = match registry::find_analyzer_plugin(type_name) {
            Some(p) => p,
            None => {
                errors.push(format!(
                    "[analyzer.{}]: unknown analyzer type '{}' (run 'rsconstruct analyzers list' to see available)",
                    type_name, type_name,
                ));
                continue;
            }
        };

        // Multi-instance: `[analyzer.cpp.kernel]` / `[analyzer.cpp.userspace]`.
        // Detected iff every value is itself a table.
        let is_multi_instance = !table.is_empty() && table.values().all(|v| v.is_table());

        if is_multi_instance {
            for (inst_name, inst_value) in table {
                if let Some(inst_table) = inst_value.as_table() {
                    let section = format!("analyzer.{}.{}", type_name, inst_name);
                    validate_analyzer_section(plugin, &section, inst_table, &mut errors);
                }
            }
        } else {
            let section = format!("analyzer.{}", type_name);
            validate_analyzer_section(plugin, &section, table, &mut errors);
        }
    }

    errors
}

/// Check a single analyzer section's fields against the plugin's known_fields list.
fn validate_analyzer_section(
    plugin: &registry::AnalyzerPlugin,
    section_label: &str,
    table: &toml::map::Map<String, toml::Value>,
    errors: &mut Vec<String>,
) {
    let known = (plugin.known_fields)();
    for key in table.keys() {
        if !known.contains(&key.as_str()) {
            errors.push(format!(
                "[{}]: unknown field '{}' (valid fields: {})",
                section_label, key, known.join(", ")
            ));
        }
    }
}

impl Config {
    pub(crate) fn require_config() -> Result<()> {
        let config_path = Path::new(CONFIG_FILE);
        if !config_path.exists() {
            return Err(crate::exit_code::RsconstructError::new(
                crate::exit_code::RsconstructExitCode::ConfigError,
                "No rsconstruct.toml found. Run 'rsconstruct init' to create one.",
            ).into());
        }
        Ok(())
    }

    pub(crate) fn load() -> Result<Self> {
        let config_path = Path::new(CONFIG_FILE);

        let (mut config, span_map, global_span_map) = if config_path.exists() {
            let content = fs::read_to_string(config_path)
                .with_context(|| format!("Failed to read config file: {}", config_path.display()))?;
            let substituted = substitute_variables(&content)
                .with_context(|| format!("Failed to substitute variables in: {}", config_path.display()))?;
            let raw: toml::Value = toml::from_str(&substituted)
                .with_context(|| format!("Failed to parse config file: {}", config_path.display()))?;
            // Run both schema validators before serde sees the config, so users
            // get pretty per-section errors instead of serde's raw messages.
            // Errors from both validators are surfaced together under a single
            // "Invalid config:" header.
            let mut all_errors = validate_processor_fields_raw(&raw);
            all_errors.extend(validate_analyzer_fields_raw(&raw));
            if !all_errors.is_empty() {
                anyhow::bail!("Invalid config:\n{}", all_errors.join("\n"));
            }
            let config: Config = toml::from_str(&substituted)
                .with_context(|| format!("Failed to parse config file: {}", config_path.display()))?;
            // Capture byte-level spans from the substituted source so we can
            // report user-set fields as `rsconstruct.toml:<line>` instead of
            // the sentinel `line: 0` we seeded during deserialization.
            let spans = provenance::build_span_map(&substituted);
            let global_spans = provenance::build_global_span_map(&substituted);
            (config, spans, global_spans)
        } else {
            (Config::default(), SpanMap::new(), provenance::GlobalSpanMap::new())
        };
        config.processor.resolve_scan_defaults();
        config.processor.apply_output_dir_defaults(&config.build.output_dir);
        config.apply_span_map(&span_map);
        config.populate_global_provenance(&global_span_map)?;
        Ok(config)
    }

    /// Seed `global_provenance` for every top-level section. Every field
    /// listed in the span map is `UserToml { line }`; every other field of
    /// the section — discovered by serializing the section struct and reading
    /// its keys — is `SerdeDefault`.
    fn populate_global_provenance(
        &mut self,
        global_spans: &provenance::GlobalSpanMap,
    ) -> Result<()> {
        // Serialize the whole config once so we can walk each section's
        // effective keys without reaching into every section struct.
        let serialized = toml::Value::try_from(&*self)
            .context("Failed to serialize config for global provenance walk")?;
        let root = match serialized.as_table() {
            Some(t) => t,
            None => return Ok(()),
        };
        for (section_name, section_value) in root {
            // Skip processor/analyzer — those are tracked per-instance in the
            // instances' own provenance maps.
            if section_name == "processor" || section_name == "analyzer" {
                continue;
            }
            let section_table = match section_value.as_table() {
                Some(t) => t,
                None => continue,
            };
            let user_fields = global_spans.get(section_name);
            let mut map = ProvenanceMap::new();
            for field in section_table.keys() {
                let source = match user_fields.and_then(|f| f.get(field)) {
                    Some(&line) => FieldProvenance::UserToml { line },
                    None => FieldProvenance::SerdeDefault,
                };
                map.insert(field.clone(), source);
            }
            self.global_provenance.insert(section_name.clone(), map);
        }
        Ok(())
    }

    /// Replace sentinel `UserToml { line: 0 }` entries with real line numbers
    /// from the toml_edit pass. Any user-set field that didn't get a span
    /// stays at line 0 (fine — the `config show` formatter falls back to
    /// "from rsconstruct.toml" without a line number).
    fn apply_span_map(&mut self, spans: &SpanMap) {
        for inst in &mut self.processor.instances {
            apply_spans_to_instance(&mut inst.provenance, spans, Section::Processor, &inst.instance_name);
        }
        for inst in &mut self.analyzer.instances {
            apply_spans_to_instance(&mut inst.provenance, spans, Section::Analyzer, &inst.instance_name);
        }
    }
}

fn apply_spans_to_instance(
    provenance: &mut ProvenanceMap,
    spans: &SpanMap,
    section: Section,
    instance_name: &str,
) {
    let keys: Vec<String> = provenance.keys().cloned().collect();
    for key in keys {
        if let Some(FieldProvenance::UserToml { line }) = provenance.get(&key) {
            if *line != 0 {
                continue; // already enriched
            }
            if let Some(&real_line) = spans.get(&(section, instance_name.to_string(), key.clone())) {
                provenance.insert(key, FieldProvenance::UserToml { line: real_line });
            }
        }
    }
}

/// Extract a `StandardConfig` with scan fields from a dynamic TOML table (used by Lua plugins).
/// Falls back to the given defaults for any missing scan fields.
pub(crate) fn standard_config_from_toml(
    value: &toml::Value,
    default_src_dirs: &[&str],
    default_src_extensions: &[&str],
    default_exclude_dirs: &[&str],
) -> StandardConfig {
    let table = value.as_table();

    let toml_array = |key: &str| -> Option<Vec<String>> {
        table
            .and_then(|t| t.get(key))
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
    };

    let mut cfg = StandardConfig {
        src_dirs: toml_array("src_dirs"),
        src_extensions: toml_array("src_extensions"),
        src_exclude_dirs: toml_array("src_exclude_dirs"),
        src_exclude_files: toml_array("src_exclude_files"),
        src_exclude_paths: toml_array("src_exclude_paths"),
        src_files: toml_array("src_files"),
        ..StandardConfig::default()
    };
    // Fill defaults for None fields
    if cfg.src_dirs.is_none() {
        cfg.src_dirs = Some(default_src_dirs.iter().map(|s| s.to_string()).collect());
    }
    if cfg.src_extensions.is_none() {
        cfg.src_extensions = Some(default_src_extensions.iter().map(|s| s.to_string()).collect());
    }
    if cfg.src_exclude_dirs.is_none() {
        cfg.src_exclude_dirs = Some(default_exclude_dirs.iter().map(|s| s.to_string()).collect());
    }
    if cfg.src_exclude_files.is_none() {
        cfg.src_exclude_files = Some(Vec::new());
    }
    if cfg.src_exclude_paths.is_none() {
        cfg.src_exclude_paths = Some(Vec::new());
    }
    if cfg.src_files.is_none() {
        cfg.src_files = Some(Vec::new());
    }
    cfg
}