cpp_code_analysis 0.1.4

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
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
//! The project's own configuration file, `.cppls.toml`.
//!
//! Everything else in this crate is *derived*: the compile database says how a project is built, the toolchain says
//! where its headers are, and the scan says which files are sources. This file is the one place a **person** says
//! something the analysis cannot work out on its own — "the build tree is not source", "this one is built with
//! `-DFEATURE=1`", "look for the database in `build/`" — and the one place a *guess* can be overridden.
//!
//! ```toml
//! [workspace]
//! exclude = ["**/build/**", "third_party/**"]     # what the analysis should not read
//! source_extensions = ["cuh", "cppm"]             # extensions beyond the engine's own list
//!
//! [compile.cuda]                                  # a CUDA project: see `CudaSection`
//! enable = true                                   # read it as CUDA even without an `nvcc` in the database
//! toolkit = "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.4"
//! host_compiler = "cl"                            # the host dialect: cl (MSVC) or g++/clang++ (GNU)
//!
//! [compile]
//! database = "build/compile_commands.json"        # where the compile database is, if discovery guesses wrong
//! compiler = "clang++"                            # or a path; absent means "the toolchain discovery decides"
//! args = ["-std=c++20", "-Iinclude"]              # used **instead of** the database's flags when present
//! extra_args = ["-DFEATURE=1"]                    # added on top of whichever flags won
//! remove_args = ["-Werror"]                       # dropped from whichever flags won
//!
//! [index]
//! cache_dir = ".cppls"
//! max_files = 20000
//!
//! [diagnostics]                                   # read by the language server, not by the analysis
//! on_change_ms = 500
//!
//! [hover]
//! enable = true
//!
//! [format]                                        # where this project's format strings are
//! enable = true                                   # colouring, popup and completion, all three
//! std = true                                      # `{…}` — std::format / fmt::format
//! printf = true                                   # `%…` — printf, fprintf, fmt::printf
//! scanf = true                                    # `%…` with scansets — scanf, sscanf
//!
//! [format.functions]                              # our own, by the resolved qualified name
//! "mylib::logf" = "printf"
//! "mylib::log" = "std"
//! "mylib::trace" = { syntax = "printf", argument = 1 }
//! ```
//!
//! # Measured, on a project with no compile database at all
//!
//! `E:\EmmyLuaCodeStyle` — 198 C++ sources in nine CMake targets, plus a `3rd/` tree, **no
//! `compile_commands.json`** because nobody had configured it with `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`. Its
//! includes are written against each target's include directory (`#include "Session/StandardIOSession.h"` from
//! `CodeFormatServer/src/`), which is what `target_include_directories` means and what a compile database would
//! have said.
//!
//! ```text
//!                                    without .cppls.toml   with [compile] args
//!   include paths the resolver had   8                     21
//!   summaries refused by the cache   1046 of 1729          235 of 1729
//!   index time                       16.0 s                20.0 s
//! ```
//!
//! The 13 `-I` flags are the project's own layout, written out once. **The time went up because the analysis is
//! doing more**: an unresolved include refuses the whole summary (`has_unresolved_includes`), so before, the work
//! was *skipped* rather than saved — 1046 files were read, found to be unmemorable, and would be read again next
//! time.
//!
//! The 235 that remain are files reaching headers this machine genuinely does not have (MSVC's own
//! `xmmintrin.h` asks for `xmm_func.h`). That is the honest floor without a database, and it is why a
//! `compile_commands.json` is still the better answer when a project has one.
//!
//! # Where a guess sits, and where it must not
//!
//! **A person's file wins; discovery is a fallback; and no guess is load-bearing.** The order is:
//!
//! ```text
//!   [compile] args          a person said exactly what the compiler is given — and it is used *instead of* the
//!                           database's flags, so this is the override and not a hint
//!   the compile database    the compiler's own answer, per file
//!   toolchain discovery     the system's headers, from the compiler that was found
//!   inferred layout         `include_roots_above` in `crate::include` — a *narrow* rule (an ancestor directory
//!                           holding `include/`) so that the common single-target layout resolves before anyone has
//!                           written a configuration file
//! ```
//!
//! The last of those is the only guess, it is deliberately narrow, and **it does not cover the layout this project
//! has**: its include roots are *siblings* (`CodeFormatCore/include`, `LuaParser/include`) and grandchildren
//! (`3rd/asio-1.24.0/include`) of the file, not ancestors — so the rule finds nothing there and the configuration
//! file is what resolves them. A rule broad enough to find those would be searching a checkout for any directory
//! named `include`, which is the kind of guess that silently picks the wrong file. It is not written, and the
//! table above is what it costs to write thirteen paths down instead.
//!
//! # Why the parse is section-by-section
//!
//! A file a person edits will eventually have a typo in it, and the useful answer to a typo is "the key `exlude` in
//! `[workspace]` is not one I know, and here is what I did with the rest" — not "the configuration could not be
//! read, so everything is default". So the text is read into a `toml::Value` once, and then **each section is
//! decoded on its own**: a section that fails to decode is reported and left at its defaults, and every other
//! section is applied. An unknown *section* is a problem too, listed by name, because a mistyped section header is
//! the typo that would otherwise be the most silent of all.
//!
//! # Why the file is not written back
//!
//! This crate never writes the file. A configuration file belongs to the project, it is committed, it has the
//! user's comments in it — so the analysis reads it and reports what it thinks, and any future "fix my config"
//! feature has to propose a patch rather than rewrite what it did not author.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::file::paths::FileProvider;

/// The name a project's configuration is conventionally found under, in the workspace root.
pub const PROJECT_CONFIG_FILE: &str = ".cppls.toml";

/// Everything `.cppls.toml` can say, after parsing.
///
/// The sections that only a language server reads ([`DiagnosticsSection`], [`HoverSection`],
/// [`FormatSection`]) are here as **data**: this crate parses and validates one file, so that two crates cannot
/// disagree about what it says — the meaning of `diagnostics.on_change_ms` lives in the server, and what lives here is
/// the key and its type.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProjectConfig {
    pub workspace: WorkspaceSection,
    pub compile: CompileSection,
    pub index: IndexSection,
    pub diagnostics: DiagnosticsSection,
    pub hover: HoverSection,
    pub format: FormatSection,
    /// **`[unreal]`** — Unreal Engine's conventions, switched on by the project rather than guessed.
    ///
    /// UE code is C++ that is not readable as ordinary C++: `UCLASS()`, `GENERATED_BODY()` and `UPROPERTY(…)` come
    /// from its headers, and its naming rules — a `UCLASS` starts with `U`, a `USTRUCT` with `F`, a `boolean` member
    /// with `b` — are conventions no ordinary C++ project follows. Turning this on is what makes the two rules that
    /// know them run, and nothing else changes: the macros are the project's headers, not this configuration.
    pub unreal: Option<UnrealSection>,
    /// **The language this project's messages are written in** — `locale = "zh-CN"`.
    ///
    /// The one key that stands alone rather than in a section, because it is a preference about the *editor*: what
    /// the diagnostics, the parse errors and the hover popups say. Read by the server at start-up and whenever the
    /// file changes; a project that names it wins over the locale the client sent at `initialize`.
    pub locale: Option<String>,
}

/// **`[unreal]`** — whether this project is Unreal Engine code.
///
/// ```toml
/// [unreal]
/// enable = true
/// ```
///
/// The one key, and it is deliberately a project's decision rather than a detection: a file that writes `UCLASS()`
/// outside UE is a file with an unknown macro, not a game, and running Epic's naming rules on an engine-agnostic
/// project would report every `class Widget` as a missing `A`/`U`/`F`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnrealSection {
    /// Run the Unreal conventions — see `ue-naming` and `ue-generate-body`.
    #[serde(default)]
    pub enable: bool,
}

/// `[workspace]` — what the project is made of.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceSection {
    /// Glob patterns the analysis should not read: a build tree, a vendored copy, generated sources.
    #[serde(default)]
    pub exclude: Vec<String>,
    /// Extensions **added** to the engine's own source list.
    ///
    /// Added rather than replacing, because the engine's list is what a C++ project is made of and a project that
    /// writes `source_extensions` is saying "and also these" — a CUDA `.cuh` or a module `.cppm`. Replacing the
    /// list is what `exclude` is for, one file at a time.
    #[serde(default)]
    pub source_extensions: Vec<String>,
}

/// `[compile.cuda]` — a CUDA project's extra configuration.
///
/// ```toml
/// [compile.cuda]
/// enable = true                                       # read this project as CUDA even if nothing says so
/// toolkit = "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.4"
/// host_compiler = "cl"                                # the host dialect: cl (MSVC) or g++/clang++ (GNU)
/// include = ["third_party/cutlass/include"]           # extra include directories for CUDA units
/// args = ["-arch=sm_80"]                              # extra flags, appended to whatever won
/// ```
///
/// # What each key is for, and what is deliberately absent
///
/// `enable` is the escape hatch of the detection: the analysis reads a project as CUDA when its toolchain is `nvcc`
/// (`__CUDACC__` in the macro table, or the compiler's name), and a project that has `.cu` files but no compile
/// database has neither. Saying so here is one line, and it is the same switch — the grammar's CUDA rules, on.
///
/// `toolkit` is the key that makes `<cuda_runtime.h>` resolve: the toolkit installs its headers under
/// `<toolkit>/include` (and, from CUDA 12.8, a CCCL include beside it), and **nothing on the system path knows
/// that**. The directory is added as a system include path, so `#include <cuda_runtime.h>` and the vector types it
/// defines (`float4`, `dim3`) become visible without a single line in the project's own headers.
///
/// `host_compiler` decides the **dialect**, which is a different question from the CUDA flag: on Windows `nvcc`
/// drives `cl.exe`, on Linux `g++`, so `__int64` and `__cdecl` are MSVC's names in one project and GNU's in the
/// other. Only the name is read here — `cl` (and `cl.exe`) means MSVC, anything with `g++`, `gcc` or `clang` in it
/// means GNU — because the compiler itself is discovered and asked elsewhere.
///
/// **`__CUDA_ARCH__` is deliberately not a key.** It is defined **only in the device compilation pass**, so a
/// language server that defined it for the whole file would evaluate `#if __CUDA_ARCH__ >= 800` in host code that a
/// compiler never sees. An `arch` key would be a lie of exactly that shape; a project that needs it can put it in
/// `args` and accept the same lie knowingly.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CudaSection {
    /// Read this project as CUDA even when the toolchain does not say so — see the section's own note.
    #[serde(default)]
    pub enable: bool,
    /// The CUDA toolkit's installation directory — `…/CUDA/v12.4`. Its `include` (and `include/cccl`, when present)
    /// are added as system include paths.
    #[serde(default)]
    pub toolkit: Option<PathBuf>,
    /// The host compiler's name, for the **dialect**: `cl` is MSVC, `g++`/`gcc`/`clang++` is GNU.
    #[serde(default)]
    pub host_compiler: Option<String>,
    /// Extra include directories, relative to the workspace root (or absolute), added after the toolkit's own.
    #[serde(default)]
    pub include: Vec<PathBuf>,
    /// Flags appended to whichever set won — the same arrangement [`CompileSection::extra_args`] has.
    #[serde(default)]
    pub args: Vec<String>,
}

impl CudaSection {
    /// **The configuration this section describes**, applied to what discovery worked out.
    ///
    /// One function rather than a handful of edits in the session, because the keys are one statement: a project that
    /// names a toolkit means "and read the files as CUDA", and splitting that across three call sites is how the
    /// include path would one day be added without the switch.
    pub fn applied_to(
        &self,
        mut config: crate::include::config::CompilerConfig,
        root: &std::path::Path,
    ) -> crate::include::config::CompilerConfig {
        if self.enable {
            config = config.with_cuda(true);
        }
        if let Some(host) = &self.host_compiler {
            let name = host
                .rsplit(['/', '\\'])
                .next()
                .unwrap_or(host)
                .trim_end_matches(".exe");
            let dialect = if name == "cl" {
                cpp_parser::Dialect::Msvc
            } else if name.contains("g++")
                || name.contains("gcc")
                || name.contains("clang")
                || name == "cc"
                || name == "c++"
            {
                cpp_parser::Dialect::Gnu
            } else {
                config.dialect()
            };
            config = config.with_dialect(dialect);
        }
        if let Some(toolkit) = &self.toolkit {
            // **A relative toolkit is relative to the workspace root**, like every other path in this file: the
            // process's own directory is wherever the editor was started from, which has nothing to do with the
            // project. Measured: `toolkit = "cuda"` added `cuda/include`, a relative spelling the include resolver
            // could not open, and the header it was supposed to bring in was reported missing.
            let toolkit = if toolkit.is_absolute() {
                toolkit.clone()
            } else {
                root.join(toolkit)
            };
            let toolkit = &toolkit;
            // **The toolkit's own include directories**, which no compiler on the machine answers for: `nvcc` ships
            // them, and they are not on `PATH` or in any system directory. `cccl` is the CUDA 12.8+ layout, where the
            // C++ standard library parallel algorithms moved out of `include` — added only when it exists, so an older
            // toolkit does not gain a directory that is not there.
            for relative in ["include", "include/cccl"] {
                let directory = toolkit.join(relative);
                if relative == "include" || directory.is_dir() {
                    config
                        .include_paths
                        .push(crate::include::config::IncludePath::system(directory));
                }
            }
        }
        for directory in &self.include {
            let directory = if directory.is_absolute() {
                directory.clone()
            } else {
                root.join(directory)
            };
            config
                .include_paths
                .push(crate::include::config::IncludePath::system(directory));
        }
        config.extra_args.extend(self.args.iter().cloned());
        config
    }
}
/// `[compile]` — how this project is built, when the discovered answer is not the right one.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CompileSection {
    /// The compile database to read, relative to the workspace root (or absolute).
    ///
    /// The escape hatch for discovery: a project whose `compile_commands.json` lives somewhere no convention
    /// predicts — a hand-written CMake build directory, a tool that emits it into `.cache/`.
    #[serde(default)]
    pub database: Option<PathBuf>,
    /// The compiler to use, as a name on `PATH` or a path. `"auto"` (or absent) leaves it to the discovery order.
    #[serde(default)]
    pub compiler: Option<String>,
    /// The language standard the whole project is built with, as `-std=` spells it (`"c++20"`).
    ///
    /// The project-wide default a `[[compile.target]]` inherits when it states none, and — like `args` — the
    /// person's word: it is applied ahead of what the compile database's command line says, because a build's
    /// `-std=gnu++20` is what the *build* ran rather than what the project means.
    ///
    /// This exists as its own key rather than as an `args` entry because it is the one flag nearly every project
    /// states and nearly every target restates, and writing `-std=c++20` into a list of flags hides it among the
    /// `-W`/`-O` noise. See [`TargetSection::standard`] for the per-target form.
    #[serde(default)]
    pub standard: Option<String>,
    /// The flags to compile with, **instead of** the compile database's.
    ///
    /// # What this costs, and why it is still the right default
    ///
    /// When this key is present the database's flags are ignored entirely: a project that writes `args` has said
    /// what its compilation is, and merging two sets of flags would make the result depend on their order (two
    /// `-std=` options, a `-I` before and after) in a way nobody can predict by reading the file. The cost is real
    /// — change a `target_compile_definitions` in `CMakeLists.txt` and this file has to be updated by hand — and
    /// the way out is `extra_args`, which adds to whichever flags won. It records the
    /// decision and the alternatives.
    #[serde(default)]
    pub args: Option<Vec<String>>,
    /// Flags added on top of whichever set won, in this order.
    #[serde(default)]
    pub extra_args: Vec<String>,
    /// Flags dropped from whichever set won, matched by their **whole** spelling (`-Werror`, `-std=c++17`).
    #[serde(default)]
    pub remove_args: Vec<String>,
    /// **`[compile.cuda]`** — what this project says about CUDA, when the discovery cannot work it out.
    ///
    /// See [`CudaSection`]: the toolkit's location is the one thing no compiler on the machine can answer, because
    /// `nvcc` is not installed by default and the headers it ships are not on any system path.
    #[serde(default)]
    pub cuda: Option<CudaSection>,
    /// Extra include directories, by the directory they apply to; `"*"` applies to the whole project.
    ///
    /// Paths are relative to the workspace root. This exists for the project that compiles one subtree with an
    /// extra `-I` — a legacy module, a generated header directory — which is exactly the case a single project-wide
    /// configuration cannot express and a per-file database can.
    #[serde(default)]
    pub include: BTreeMap<String, Vec<String>>,
    /// **Find an `#include` by the tail of its path when no include directory could have.**
    ///
    /// `None` means "as the analysis decides", which is off — a guess must never shadow what a project stated. Set
    /// it `true` for a project whose build system cannot state its include directories at all: a Visual Studio
    /// solution, whose database CMake cannot export, or a checkout nobody has configured.
    ///
    /// See [`crate::include::fuzzy`] for the rule. It runs only after every exact candidate has failed, and it
    /// refuses a target with no directory in it (`#include <vector>`), which is what keeps it from answering a
    /// question the search path was supposed to answer.
    #[serde(default)]
    pub fuzzy_includes: Option<bool>,
    /// **The project's compilation *targets*** — see [`TargetSection`].
    ///
    /// The key that makes this file usable on a real C++ project, because a real C++ project is not one
    /// compilation: it is several, each with its own include directories and its own defines, and a single `args`
    /// list cannot describe them. Writing every target's `-I` into one list is not a simplification but a wrong
    /// answer — a header reachable only from another target's directory then resolves, and an include of
    /// `"Config.h"` picks whichever `Config.h` the search order reaches first.
    ///
    /// Spelled `[[compile.target]]`, one table per target. A file is described by the target whose `sources` match
    /// it most specifically; a file no target matches is described by `[compile]` itself.
    /// Spelled [[compile.target]] — one table per target, which is CMake's word for the thing.
    #[serde(default, rename = "target")]
    pub targets: Vec<TargetSection>,
}

/// **One compilation target** — what a build system has and one `[compile]` cannot say.
///
/// ```toml
/// [compile]
/// standard = "c++20"
/// fuzzy_includes = true
///
/// [[compile.target]]
/// name     = "CodeFormatServer"
/// sources  = ["CodeFormatServer/**"]
/// includes = ["CodeFormatServer/include", "CodeFormatServer/src", "Util/include"]
/// defines  = ["URI_STATIC_BUILD", "WIN32_LEAN_AND_MEAN"]
/// ```
///
/// # The syntax, and how much of CMake it is
///
/// Deliberately a few ideas and no more — CMake's own words where they fit, so that a person who knows
/// `target_include_directories` and `target_compile_definitions` has nothing to learn:
///
/// ```text
/// name        what to call it in a message        (CMake: the target's name)
/// sources     which files it describes           (CMake: add_executable's list, as a pattern)
/// includes    its include directories            (CMake: target_include_directories)
/// defines     its preprocessor definitions       (CMake: target_compile_definitions)
/// standard    its language standard              (CMake: CXX_STANDARD)
/// ```
///
/// **What it is not** is a build system: there are no dependencies, no sources to compile, no commands to run,
/// and nothing here can make anything happen. It describes compilations, which is all an analysis needs and all a
/// person should have to write down. Anything that must be *generated* belongs in a compile database — which is
/// what `[compile].database` is for.
///
/// # How a file finds its target
///
/// `sources` is a **pattern**, matched against the file's path relative to the root, component by component:
///
/// ```text
/// "CodeFormatServer/**"     the subtree, at any depth
/// "*/src/**"                any target's src tree
/// "Util/*.cpp"              direct children only
/// ```
///
/// `**` stands for any number of components (including none), `*` for any run of characters **within** one, and
/// everything else is literal. A pattern is matched against the whole path unless its last component is `**`.
///
/// When several targets match, the **most specific** wins — the one fixing the most literal components — and ties
/// go to the one written first. A target for `Util/**` therefore beats one for `**`, and which target describes a
/// file is decided by the file rather than by the order of the tables.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetSection {
    /// What to call this target in a problem message. Absent is allowed; [`TargetSection::label`] then says
    /// something a person can still act on.
    #[serde(default)]
    pub name: Option<String>,
    /// Which files this target describes, as patterns relative to the project root.
    #[serde(default)]
    pub sources: Vec<String>,
    /// Its include directories, relative to the project root (or absolute).
    #[serde(default)]
    pub includes: Vec<String>,
    /// Its preprocessor definitions — `"NAME"` or `"NAME=value"`, without the `-D`.
    #[serde(default)]
    pub defines: Vec<String>,
    /// Its language standard, as `-std=` spells it (`"c++20"`). The project's is used when this is absent.
    #[serde(default)]
    pub standard: Option<String>,
    /// The target's **whole** command line, when a person wants to write it out — used *instead of* the
    /// discovered flags for the files it describes, exactly as [`CompileSection::args`] is for the project.
    #[serde(default)]
    pub args: Option<Vec<String>>,
    /// Flags added on top of whichever set won for this target.
    #[serde(default)]
    pub extra_args: Vec<String>,
    /// Flags dropped from whichever set won for this target.
    #[serde(default)]
    pub remove_args: Vec<String>,
}

/// **The target that describes `file`**, for a caller that holds the list and not the section.
///
/// The same rule [`CompileSection::target_for`] applies, as a function, because the include resolver is built per
/// file from a [`CompilerConfig`](crate::CompilerConfig) and never sees the configuration file itself.
/// **Every target a configuration describes**, including the one `[compile.include]` implies.
///
/// `[compile].include` is the older, smaller spelling of the same idea — a directory and the include paths it
/// needs — and it is turned into a target here rather than read anywhere else, so that there is **one** mechanism
/// deciding which include directories a file gets. Before this it was parsed, validated, documented and never
/// applied: a project that wrote it got nothing, which is one reason a whole project's `-I` flags end up in a
/// single `args` list.
///
/// A key of `"*"` becomes the target for every file; any other key becomes that subtree's.
pub fn targets_for(section: &CompileSection) -> Vec<TargetSection> {
    let mut targets: Vec<TargetSection> = section
        .include
        .iter()
        .map(|(directory, includes)| TargetSection {
            name: Some(format!("[compile.include] {directory}")),
            sources: vec![if directory == "*" {
                "**".to_string()
            } else {
                format!("{directory}/**")
            }],
            includes: includes.clone(),
            ..TargetSection::default()
        })
        .collect();

    targets.extend(section.targets.iter().cloned());
    targets
}
pub fn target_for<'a>(
    targets: &'a [TargetSection],
    root: &Path,
    file: &Path,
) -> Option<&'a TargetSection> {
    targets
        .iter()
        .enumerate()
        .filter_map(|(order, target)| {
            target
                .describes(root, file)
                .map(|specific| (specific, std::cmp::Reverse(order), target))
        })
        .max_by_key(|(specific, order, _)| (*specific, *order))
        .map(|(_, _, target)| target)
}
impl TargetSection {
    /// What to call it when a message has to name it.
    pub fn label(&self) -> &str {
        self.name.as_deref().unwrap_or("an unnamed target")
    }

    /// **How specifically this target describes `file`**, or `None` when it does not.
    ///
    /// The number is the count of **literal** components the pattern fixed, which is what "most specific" means to
    /// a reader: `Util/src/**` fixes two, `**` fixes none. No `sources` at all matches nothing — a target that
    /// names no files is not a target for every file.
    pub fn describes(&self, root: &Path, file: &Path) -> Option<usize> {
        let relative = file.strip_prefix(root).ok()?;
        let components: Vec<String> = relative
            .components()
            .map(|component| component.as_os_str().to_string_lossy().to_lowercase())
            .collect();

        self.sources
            .iter()
            .filter_map(|pattern| pattern_specificity(pattern, &components))
            .max()
    }
}

/// **Does `pattern` describe the path whose components are `path`**, and how specifically?
///
/// `Some(literal components fixed)` when it does, `None` when it does not. Matching is case-insensitive because a
/// path that differs only in case is the same file on the platforms this runs on, and a configuration file should
/// not be what decides otherwise.
fn pattern_specificity(pattern: &str, path: &[String]) -> Option<usize> {
    let parts: Vec<String> = pattern
        .split('/')
        .filter(|part| !part.is_empty() && *part != ".")
        .map(|part| part.to_lowercase())
        .collect();

    if parts.is_empty() {
        return None;
    }

    /// `**` matches any number of components, including none, so the walk carries how many literal components
    /// have been fixed and takes the best of every way through.
    fn walk(parts: &[String], path: &[String], fixed: usize) -> Option<usize> {
        let Some((head, rest)) = parts.split_first() else {
            // The pattern is spent: it describes this file only if the path is spent too.
            return path.is_empty().then_some(fixed);
        };

        if head == "**" {
            return (0..=path.len())
                .filter_map(|skipped| walk(rest, &path[skipped..], fixed))
                .max();
        }

        let (component, remaining) = path.split_first()?;
        if !component_matches(head, component) {
            return None;
        }

        let fixed = if head.contains('*') { fixed } else { fixed + 1 };
        walk(rest, remaining, fixed)
    }

    walk(&parts, path, 0)
}

/// One component of a pattern against one component of a path: `*` is any run of characters.
fn component_matches(pattern: &str, component: &str) -> bool {
    let Some(star) = pattern.find('*') else {
        return pattern == component;
    };

    let (before, after) = (&pattern[..star], &pattern[star + 1..]);
    component.starts_with(before)
        && component.len() >= before.len() + after.len()
        && component.ends_with(after)
}

impl CompileSection {
    /// Is the compiler left to discovery?
    pub fn compiler_is_auto(&self) -> bool {
        match &self.compiler {
            None => true,
            Some(named) => named.eq_ignore_ascii_case("auto"),
        }
    }

    /// The compiler this file names, when it names one.
    pub fn named_compiler(&self) -> Option<&str> {
        match self.compiler.as_deref() {
            Some(named) if !self.compiler_is_auto() => Some(named),
            _ => None,
        }
    }

    /// **The target that describes `file`**, when one does.
    ///
    /// The most specific match wins and ties go to the one written first — see [`TargetSection::describes`] for
    /// what "specific" counts. A file no target matches is described by `[compile]` itself, which is what makes
    /// targets an addition rather than a replacement.
    pub fn target_for(&self, root: &Path, file: &Path) -> Option<&TargetSection> {
        self.targets
            .iter()
            .enumerate()
            .filter_map(|(order, target)| {
                target
                    .describes(root, file)
                    .map(|specific| (specific, std::cmp::Reverse(order), target))
            })
            .max_by_key(|(specific, order, _)| (*specific, *order))
            .map(|(_, _, target)| target)
    }
    /// The extra include directories that apply to a file.
    ///
    /// Longest matching prefix wins, and `"*"` applies everywhere: a project that says `"src/legacy"` means that
    /// subtree and not the project, and one that says `"*"` means all of it. Both can be true at once, and the
    /// nearer rule is the one that should be added first — the resolver searches include paths in order.
    pub fn includes_for(&self, root: &Path, file: &Path) -> Vec<PathBuf> {
        let mut chosen: Vec<(&str, &Vec<String>)> = self
            .include
            .iter()
            .filter(|(directory, _)| {
                directory.as_str() == "*" || file.starts_with(root.join(directory))
            })
            .map(|(directory, paths)| (directory.as_str(), paths))
            .collect();

        // The specific directories first, then `*`; longest prefix first among the specific ones.
        chosen
            .sort_by_key(|(directory, _)| (directory == &"*", std::cmp::Reverse(directory.len())));

        chosen
            .into_iter()
            .flat_map(|(_, paths)| paths.iter())
            .map(|directory| root.join(directory))
            .collect()
    }
}

/// `[index]` — the cache and the scan.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IndexSection {
    /// The cache directory's name, relative to the workspace root.
    #[serde(default)]
    pub cache_dir: Option<String>,
    /// How many files the project scan may list.
    #[serde(default)]
    pub max_files: Option<usize>,
}

/// `[diagnostics]` — read by the language server.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DiagnosticsSection {
    /// How long a file's diagnostics wait for the typing to stop, in milliseconds.
    #[serde(default)]
    pub on_change_ms: Option<u64>,
    /// **Only these rules** — the codes of `DiagnosticCode`, by their kebab-case names.
    ///
    /// Empty means "whatever the defaults say", which is every rule: a project that wants three rules and nothing
    /// else lists all three here.
    #[serde(default)]
    pub enable: Vec<String>,
    /// **Not these rules**, whether or not `enable` also names them.
    ///
    /// `disable` wins, so the two can be read together as "everything except …" and "these few" without a project
    /// having to think about which section wins. A name this build does not have is reported to the user rather than
    /// ignored — a rule believed to be on and that never runs is the failure this pair exists to prevent.
    #[serde(default)]
    pub disable: Vec<String>,
}

/// `[hover]` — read by the language server.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HoverSection {
    #[serde(default)]
    pub enable: Option<bool>,
}

/// `[format]` — **where this project's format strings are**, read by the language server.
///
/// ```toml
/// [format]
/// enable = true          # the whole feature: the colouring inside a literal, the popup on a part of one, the
///                        # completions inside one. `false` is all three at once.
/// std = true             # `{…}` — std::format / std::print / fmt::format …
/// printf = true          # `%…` — printf, fprintf, snprintf, fmt::printf …
/// scanf = true           # `%…` with scansets — scanf, sscanf …
///
/// [format.functions]     # the project's own, by the name the analysis **resolves** them to
/// "mylib::logf" = "printf"                        # printf's syntax, the format string first
/// "mylib::log" = "std"
/// "mylib::trace" = { syntax = "printf", argument = 1 }   # `trace(level, fmt, …)`
/// ```
///
/// # Why it is shaped this way
///
/// **One section named for the feature, not for one of its three faces.** It began as `[highlight]` with
/// `format_strings` / `extra_format` in it, which was wrong twice over: the same question decides a popup and a
/// completion as well as a colour, and two list keys spelled that differently could only be understood by reading
/// which one took `{}` and which took `%`. So the section is `[format]`, each grammar switch is named after the
/// grammar it switches, and **a project's own functions are one table keyed by name** — the syntax is the value, so
/// nothing has to be remembered.
///
/// **A table rather than a list because a wrapper has a position.** `mylib::trace(level, fmt, …)` puts the format
/// string second, and a list of names cannot say so; `{ syntax = "printf", argument = 1 }` can. A bare string is the
/// common case and means "the first argument".
///
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FormatSection {
    /// The whole feature. `Some(false)` turns the colouring, the popup and the completions off together.
    #[serde(default)]
    pub enable: Option<bool>,
    /// `std::format` / `print` / `println` / `format_to` … and the `fmt` library's names.
    #[serde(default)]
    pub std: Option<bool>,
    /// The C library's `printf` family, and `fmt::printf`'s.
    #[serde(default)]
    pub printf: Option<bool>,
    /// The C library's `scanf` family.
    #[serde(default)]
    pub scanf: Option<bool>,
    /// **The project's own format functions**, keyed by the qualified name the analysis resolves them to.
    ///
    /// A string value is the syntax, with the format string first: `"mylib::logf" = "printf"`. A table value says
    /// where the format string is: `"mylib::trace" = { syntax = "printf", argument = 1 }`.
    #[serde(default)]
    pub functions: BTreeMap<String, FunctionEntry>,
}

/// **One of a project's own format functions** — the syntax it takes, and which argument is the format string.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum FunctionEntry {
    /// `"mylib::logf" = "printf"` — the first argument is the format string.
    Syntax(String),
    /// `"mylib::trace" = { syntax = "printf", argument = 1 }`.
    Detailed {
        syntax: String,
        #[serde(default)]
        argument: Option<usize>,
    },
}

impl FunctionEntry {
    /// The syntax as the analysis names it, or `None` for a name this build does not have — which is reported to the
    /// user by [`validate`] rather than silently ignored.
    pub fn syntax(&self) -> Option<FormatSyntax> {
        let written = match self {
            FunctionEntry::Syntax(syntax) => syntax,
            FunctionEntry::Detailed { syntax, .. } => syntax,
        };
        match written.trim() {
            "std" => Some(FormatSyntax::Std),
            "printf" => Some(FormatSyntax::Printf),
            "scanf" => Some(FormatSyntax::Scanf),
            _ => None,
        }
    }

    /// Which argument holds the format string — `0` when the entry does not say.
    pub fn argument(&self) -> usize {
        match self {
            FunctionEntry::Syntax(_) => 0,
            FunctionEntry::Detailed { argument, .. } => argument.unwrap_or(0),
        }
    }
}

/// **The three grammars a format string can be written in**, as the configuration spells them.
///
/// Here rather than in [`crate::format`] so that the analysis's own vocabulary and the file's do not become one
/// thing: the file's job is to say what a person wrote, and `crate::format::FormatKind` is what the scanner reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatSyntax {
    Std,
    Printf,
    Scanf,
}

/// How bad a configuration problem is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// The file could not be read as TOML, or a section could not be decoded: what that section said is **not**
    /// in effect.
    Error,
    /// The file said something that is understood but unusable — a cache directory that is not a directory name, a
    /// pattern that is not a pattern. The rest of the configuration is in effect.
    Warning,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigProblem {
    pub severity: Severity,
    /// One sentence, in the shape a person can act on: what was wrong, and what was done instead.
    pub message: String,
}

impl ConfigProblem {
    fn error(message: impl Into<String>) -> Self {
        ConfigProblem {
            severity: Severity::Error,
            message: message.into(),
        }
    }

    fn warning(message: impl Into<String>) -> Self {
        ConfigProblem {
            severity: Severity::Warning,
            message: message.into(),
        }
    }
}

/// A configuration file, read: what it said, where it was, and everything wrong with it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConfigReport {
    pub config: ProjectConfig,
    /// The file this came from, when there was one.
    pub path: Option<PathBuf>,
    /// Every problem, in the order they were found. Empty is the ordinary case.
    pub problems: Vec<ConfigProblem>,
}

impl ConfigReport {
    /// The configuration a project with no file has: everything default, nothing wrong.
    pub fn none() -> Self {
        ConfigReport::default()
    }

    /// Was the file read at all?
    pub fn found(&self) -> bool {
        self.path.is_some()
    }

    /// The problems worth showing a user without being asked.
    pub fn errors(&self) -> impl Iterator<Item = &ConfigProblem> {
        self.problems
            .iter()
            .filter(|problem| problem.severity == Severity::Error)
    }
}

/// Read a project's configuration from a provider.
///
/// `explicit` is a path a caller named (a command-line `--config`); when it is `None` the conventional name in the
/// workspace root is tried. A file that is not there is **not** a problem: every project without a configuration
/// file is the ordinary case, and a report with no path says so.
pub fn load_config(
    files: &impl FileProvider,
    root: &Path,
    explicit: Option<&Path>,
) -> ConfigReport {
    let path = match explicit {
        Some(path) => path.to_path_buf(),
        None => root.join(PROJECT_CONFIG_FILE),
    };

    let Some(text) = files.read(&path) else {
        if explicit.is_some() {
            return ConfigReport {
                config: ProjectConfig::default(),
                path: None,
                problems: vec![ConfigProblem::error(format!(
                    "the configuration file {} could not be read",
                    path.display()
                ))],
            };
        }

        return ConfigReport::none();
    };

    parse_config(&text, &path)
}

/// Read a configuration file's text.
///
/// Split from [`load_config`] so that the parse can be tested without a filesystem — and because the text is the
/// only input that decides what the configuration is: a test that goes through a `MemoryFiles` asserts the same
/// thing with more moving parts.
pub fn parse_config(text: &str, path: &Path) -> ConfigReport {
    let value: toml::Value = match toml::from_str(text) {
        Ok(value) => value,
        Err(error) => {
            return ConfigReport {
                config: ProjectConfig::default(),
                path: Some(path.to_path_buf()),
                problems: vec![ConfigProblem::error(format!(
                    "{} is not valid TOML, so none of it is in effect: {error}",
                    path.display()
                ))],
            };
        }
    };

    let mut report = ConfigReport {
        config: ProjectConfig::default(),
        path: Some(path.to_path_buf()),
        problems: Vec::new(),
    };

    let Some(table) = value.as_table() else {
        report.problems.push(ConfigProblem::error(format!(
            "{} does not hold a table of sections",
            path.display()
        )));
        return report;
    };

    // Each section on its own, so that one typo cannot take the others with it.
    for (name, section) in table {
        let section = section.clone();

        match name.as_str() {
            "workspace" => match decode::<WorkspaceSection>(section, name) {
                Ok(decoded) => report.config.workspace = decoded,
                Err(problem) => report.problems.push(problem),
            },
            "compile" => match decode::<CompileSection>(section, name) {
                Ok(decoded) => report.config.compile = decoded,
                Err(problem) => report.problems.push(problem),
            },
            "index" => match decode::<IndexSection>(section, name) {
                Ok(decoded) => report.config.index = decoded,
                Err(problem) => report.problems.push(problem),
            },
            "diagnostics" => match decode::<DiagnosticsSection>(section, name) {
                Ok(decoded) => report.config.diagnostics = decoded,
                Err(problem) => report.problems.push(problem),
            },
            "hover" => match decode::<HoverSection>(section, name) {
                Ok(decoded) => report.config.hover = decoded,
                Err(problem) => report.problems.push(problem),
            },
            "format" => match decode::<FormatSection>(section, name) {
                Ok(decoded) => report.config.format = decoded,
                Err(problem) => report.problems.push(problem),
            },
            // **[unreal]** — the engine's conventions, which a project switches on rather than a file's spelling
            // implying. See [`UnrealSection`].
            "unreal" => match decode::<UnrealSection>(section, name) {
                Ok(decoded) => report.config.unreal = Some(decoded),
                Err(problem) => report.problems.push(problem),
            },
            // **[locale]** — the language this project's messages are written in.
            //
            // A bare key rather than a section, because it is about the *editor*: `locale = "zh-CN"` is the same
            // kind of statement as `hover.enable = false`. A project that names it wins over the locale the client
            // sent at `initialize`, which is what a reader expects — the file in the repository is more specific
            // than the editor's global setting.
            "locale" => match section.as_str() {
                Some(locale) if !locale.trim().is_empty() => {
                    report.config.locale = Some(locale.trim().to_string());
                }
                Some(_) => report.problems.push(ConfigProblem::warning(
                    "`locale` is empty, so the language is the one the client asked for".to_string(),
                )),
                None => report.problems.push(ConfigProblem::error(
                    "`locale` holds a language tag written as a string — `locale = \"zh-CN\"` — so the value here \
                     is not in effect"
                        .to_string(),
                )),
            },
            unknown => report.problems.push(ConfigProblem::error(format!(
                "[{unknown}] is not a section this server reads (workspace, compile, index, diagnostics, hover, \
                 format), and `locale` is the one key that stands alone, so nothing under it is in effect"
            ))),
        }
    }

    validate(&mut report);
    report
}

/// Decode one section, reporting a failure instead of failing the file.
fn decode<T>(value: toml::Value, name: &str) -> Result<T, ConfigProblem>
where
    T: for<'de> Deserialize<'de>,
{
    value.try_into::<T>().map_err(|error| {
        ConfigProblem::error(format!(
            "[{name}] could not be read, so that section keeps its defaults: {error}"
        ))
    })
}

/// The checks serde cannot make: values that are the right *type* and still unusable.
fn validate(report: &mut ConfigReport) {
    if let Some(cache_dir) = &report.config.index.cache_dir {
        let path = Path::new(cache_dir);
        let one_component = path.components().count() == 1;
        let named = matches!(
            path.components().next(),
            Some(std::path::Component::Normal(_))
        );

        if !one_component || !named {
            report.problems.push(ConfigProblem::warning(format!(
                "index.cache_dir = {cache_dir:?} is not a directory name inside the project, so the default \
                 `{}` is used instead",
                crate::CACHE_DIRECTORY
            )));
            report.config.index.cache_dir = None;
        }
    }

    if report.config.index.max_files == Some(0) {
        report.problems.push(ConfigProblem::warning(
            "index.max_files = 0 would mean \"index nothing\", so the default is used instead"
                .to_string(),
        ));
        report.config.index.max_files = None;
    }

    // The patterns are compiled by the caller that builds the filter, but a bad one is a *configuration* problem
    // and belongs in the report the user reads — so it is checked here, once, where the file is read.
    let bad_patterns: Vec<&String> = report
        .config
        .workspace
        .exclude
        .iter()
        .filter(|pattern| crate::PathPattern::new(pattern).is_err())
        .collect();

    for pattern in bad_patterns {
        report.problems.push(ConfigProblem::warning(format!(
            "workspace.exclude has {pattern:?}, which is not a path pattern, so it is ignored"
        )));
    }
    report
        .config
        .workspace
        .exclude
        .retain(|pattern| crate::PathPattern::new(pattern).is_ok());

    for relative in report.config.compile.include.values().flatten() {
        if Path::new(relative).is_absolute() {
            report.problems.push(ConfigProblem::warning(format!(
                "compile.include names the absolute path {relative:?}; absolute paths in a committed file do not \
                 survive a move, and this one is used as written"
            )));
        }
    }

    // **`[format.functions]`: a syntax this build does not have, and a name that is not a name.**
    //
    // The section decodes without them (a `BTreeMap<String, FunctionEntry>` takes any string as a value), so this is
    // the only place that can say so — and it must, because a function listed with a syntax nobody reads is a
    // project that believes it configured something. The entries are *dropped* rather than kept: the analysis would
    // otherwise have to carry a "this one is broken" state in a type that has no room for it.
    let broken: Vec<String> = report
        .config
        .format
        .functions
        .iter()
        .filter(|(_, entry)| entry.syntax().is_none())
        .map(|(name, _)| name.clone())
        .collect();
    for name in broken {
        let written = match report.config.format.functions.get(&name) {
            Some(FunctionEntry::Syntax(syntax)) | Some(FunctionEntry::Detailed { syntax, .. }) => {
                syntax.clone()
            }
            None => String::new(),
        };
        report.problems.push(ConfigProblem::warning(format!(
            "format.functions names {name:?} with the syntax {written:?}, which is not one this server reads \
             (std, printf, scanf), so that function is not read"
        )));
        report.config.format.functions.remove(&name);
    }

    for (name, entry) in &report.config.format.functions {
        if !name.contains("::") {
            report.problems.push(ConfigProblem::warning(format!(
                "format.functions has {name:?}, which is not a qualified name; an unqualified entry would claim \
                 every function of that spelling in the project, including the standard library's"
            )));
        }
        if entry.argument() > 3 {
            report.problems.push(ConfigProblem::warning(format!(
                "format.functions gives {name:?} the argument {}, which is past the point any format function puts \
                 its format string",
                entry.argument()
            )));
        }
    }

    if report
        .config
        .compile
        .database
        .as_ref()
        .is_some_and(|database| {
            Path::new(database)
                .components()
                .any(|component| matches!(component, std::path::Component::ParentDir))
        })
    {
        report.problems.push(ConfigProblem::warning(
            "compile.database walks out of the project with `..`; it is used as written"
                .to_string(),
        ));
    }
}

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

    fn parse(text: &str) -> ConfigReport {
        parse_config(text, Path::new("/p/.cppls.toml"))
    }

    /// **`[format]` is read**, and a key it does not have is reported rather than silently ignored — a project that
    /// switched a grammar off, and whose key was misspelled, would otherwise never know the colouring never stopped.
    ///
    /// The table of the project's own functions is the half the old `[highlight]` could not express at all: **which
    /// argument holds the format string**. Both spellings are asserted — a bare syntax string and the table form —
    /// because both are what a person writes.
    #[test]
    fn the_format_section_is_read() {
        let report = parse(
            "[format]\nenable = true\nstd = false\nprintf = false\n\n[format.functions]\n\
             \"mylib::logf\" = \"printf\"\n\
             \"mylib::log\" = \"std\"\n\
             \"mylib::trace\" = { syntax = \"printf\", argument = 1 }\n",
        );

        assert_eq!(report.config.format.enable, Some(true));
        assert_eq!(report.config.format.std, Some(false));
        assert_eq!(report.config.format.printf, Some(false));
        // **A key the section does not name keeps its default**, which is "on" — the server reads `None` that way.
        assert_eq!(report.config.format.scanf, None);
        assert_eq!(
            report
                .config
                .format
                .functions
                .get("mylib::logf")
                .and_then(FunctionEntry::syntax),
            Some(FormatSyntax::Printf)
        );
        assert_eq!(
            report
                .config
                .format
                .functions
                .get("mylib::trace")
                .map(|entry| (entry.syntax(), entry.argument())),
            Some((Some(FormatSyntax::Printf), 1)),
            "the table form says which argument is the format string"
        );
        assert_eq!(
            report
                .config
                .format
                .functions
                .get("mylib::log")
                .map(FunctionEntry::argument),
            Some(0),
            "a bare string means the first argument"
        );
        assert!(report.problems.is_empty(), "{:?}", problems(&report));

        // A project with no `[format]` at all is the ordinary case: everything default, nothing wrong.
        let report = parse("[workspace]\nexclude = [\"build/**\"]\n");
        assert_eq!(report.config.format, FormatSection::default());
        assert!(report.problems.is_empty());

        // …and a misspelled key is *this* section's problem, not the file's.
        let report = parse("[format]\nprintff = false\n");
        assert_eq!(report.config.format, FormatSection::default());
        assert_eq!(report.problems.len(), 1);
        assert!(
            report.problems[0].message.contains("[format]"),
            "{:?}",
            problems(&report)
        );

        // **A syntax this build does not have is reported and the rest of the section is kept.** A function that is
        // silently never read is a project believing it configured something.
        let report = parse("[format.functions]\n\"mylib::logf\" = \"printff\"\n");
        assert_eq!(report.problems.len(), 1);
        assert!(
            report.problems[0].message.contains("printff"),
            "the message names the value: {:?}",
            problems(&report)
        );
        assert!(report.problems[0].message.contains("std, printf, scanf"));
    }

    #[test]
    fn the_cuda_section_is_read_and_applied() {
        // **A CUDA project with no `nvcc` on the machine** — the state this section exists for. Every key is one the
        // discovery cannot answer: where the toolkit is, which compiler the host dialect belongs to, which extra
        // directories the project's own kernels include.
        let report = parse(
            "[compile.cuda]\n\
             enable = true\n\
             toolkit = '/opt/cuda-12.4'\n\
             host_compiler = 'cl.exe'\n\
             include = ['third_party/cutlass/include']\n\
             args = ['-arch=sm_80']\n\
             [compile]\n\
             standard = 'c++20'\n",
        );
        assert_eq!(problems(&report), Vec::<String>::new());
        let cuda = report
            .config
            .compile
            .cuda
            .as_ref()
            .expect("the section is here");
        assert!(cuda.enable);
        assert_eq!(cuda.toolkit.as_deref(), Some(Path::new("/opt/cuda-12.4")));
        assert_eq!(cuda.host_compiler.as_deref(), Some("cl.exe"));
        assert_eq!(cuda.args, vec!["-arch=sm_80"]);

        // **What it does to the configuration**: the switch on, the dialect from the host compiler — `cl.exe` is
        // MSVC, whose `__int64` and `__cdecl` are the host compiler's half of a CUDA unit.
        let config = cuda.applied_to(
            crate::include::config::CompilerConfig::new(),
            Path::new("/p"),
        );
        assert!(config.cuda(), "`enable` is the parser's CUDA switch");
        assert_eq!(config.dialect(), cpp_parser::Dialect::Msvc);
        assert!(
            config
                .include_paths
                .iter()
                .any(|path| path.directory == Path::new("/opt/cuda-12.4/include")),
            "the toolkit's include directory is what makes `<cuda_runtime.h>` resolve: {:?}",
            config.include_paths
        );
        assert!(
            config
                .include_paths
                .iter()
                .any(|path| path.directory == Path::new("/p/third_party/cutlass/include")),
            "and the project's own are relative to the root: {:?}",
            config.include_paths
        );
        assert!(config.extra_args.iter().any(|arg| arg == "-arch=sm_80"));
    }

    #[test]
    fn a_cuda_section_without_enable_does_not_turn_the_reading_on() {
        // `toolkit` alone says *where the headers are*, not *how to read the files*: a project may want the include
        // path for an editor that is not parsing its kernels as CUDA (a `.cu` opened as C++), and turning the grammar
        // on behind that would be a different claim. Only `enable` (or a real `nvcc`) does.
        let report = parse("[compile.cuda]\ntoolkit = '/opt/cuda'\n");
        assert_eq!(problems(&report), Vec::<String>::new());
        let cuda = report.config.compile.cuda.as_ref().expect("the section");
        let config = cuda.applied_to(
            crate::include::config::CompilerConfig::new(),
            Path::new("/p"),
        );
        assert!(!config.cuda(), "no `enable`, no CUDA reading");
        assert!(
            config
                .include_paths
                .iter()
                .any(|path| path.directory == Path::new("/opt/cuda/include")),
            "…but the headers are still where the project said"
        );
    }
    fn problems(report: &ConfigReport) -> Vec<String> {
        report
            .problems
            .iter()
            .map(|problem| problem.message.clone())
            .collect()
    }

    #[test]
    fn an_empty_file_is_the_default_configuration() {
        let report = parse("");

        assert_eq!(report.config, ProjectConfig::default());
        assert!(report.problems.is_empty());
        assert!(report.found());
    }

    #[test]
    fn every_key_is_read() {
        let report = parse(
            r#"
            [workspace]
            exclude = ["**/build/**", "third_party/**"]
            source_extensions = ["cuh"]

            [compile]
            database = "build/compile_commands.json"
            compiler = "clang++"
            args = ["-std=c++20", "-Iinclude"]
            extra_args = ["-DFEATURE=1"]
            remove_args = ["-Werror"]
            [compile.include]
            "src/legacy" = ["include/legacy"]

            [index]
            cache_dir = ".cache"
            max_files = 20000

            [diagnostics]
            on_change_ms = 250

            [hover]
            enable = false
            "#,
        );

        assert!(report.problems.is_empty(), "{:?}", problems(&report));
        let config = &report.config;
        assert_eq!(config.workspace.exclude, ["**/build/**", "third_party/**"]);
        assert_eq!(config.workspace.source_extensions, ["cuh"]);
        assert_eq!(
            config.compile.database.as_deref(),
            Some(Path::new("build/compile_commands.json"))
        );
        assert_eq!(config.compile.named_compiler(), Some("clang++"));
        assert_eq!(
            config.compile.args.as_deref(),
            Some(["-std=c++20".to_string(), "-Iinclude".to_string()].as_slice())
        );
        assert_eq!(config.compile.extra_args, ["-DFEATURE=1"]);
        assert_eq!(config.compile.remove_args, ["-Werror"]);
        assert_eq!(
            config.compile.include.get("src/legacy").map(Vec::len),
            Some(1)
        );
        assert_eq!(config.index.cache_dir.as_deref(), Some(".cache"));
        assert_eq!(config.index.max_files, Some(20000));
        assert_eq!(config.diagnostics.on_change_ms, Some(250));
        assert_eq!(config.hover.enable, Some(false));
    }

    #[test]
    fn auto_is_not_a_compiler() {
        let report = parse("[compile]\ncompiler = \"auto\"\n");

        assert!(report.config.compile.compiler_is_auto());
        assert_eq!(report.config.compile.named_compiler(), None);
    }

    #[test]
    fn an_unknown_section_does_not_take_the_others_with_it() {
        // The typo that would otherwise be the most silent of all: a misspelled section header.
        let report =
            parse("[workspace]\nexclude = [\"build/**\"]\n\n[compilee]\ncompiler = \"clang++\"\n");

        assert_eq!(report.config.workspace.exclude, ["build/**"]);
        assert_eq!(report.config.compile.named_compiler(), None);
        assert_eq!(report.problems.len(), 1);
        assert!(
            report.problems[0].message.contains("[compilee]"),
            "{:?}",
            problems(&report)
        );
        assert_eq!(report.problems[0].severity, Severity::Error);
    }

    #[test]
    fn an_unknown_key_in_a_section_keeps_that_section_at_its_defaults_and_says_which() {
        let report = parse("[workspace]\nexlude = [\"build/**\"]\n");

        assert!(report.config.workspace.exclude.is_empty());
        assert_eq!(report.problems.len(), 1);
        assert_eq!(report.problems[0].severity, Severity::Error);
        assert!(
            report.problems[0].message.contains("exlude"),
            "the problem names the key: {:?}",
            problems(&report)
        );
    }

    #[test]
    fn a_section_of_the_wrong_shape_is_reported() {
        let report = parse("[index]\ncache_dir = 5\n");

        assert_eq!(report.config.index.cache_dir, None);
        assert_eq!(report.problems.len(), 1);
        assert!(report.problems[0].message.contains("[index]"));
    }

    #[test]
    fn a_syntax_error_reports_the_file_and_keeps_nothing() {
        let report = parse("[workspace\nexclude = [\n");

        assert_eq!(report.config, ProjectConfig::default());
        assert_eq!(report.problems.len(), 1);
        assert!(report.problems[0].message.contains("not valid TOML"));
    }

    #[test]
    fn a_cache_directory_that_is_not_a_name_is_replaced_by_the_default() {
        for written in ["../outside", "/tmp/cppls", "a/b"] {
            let report = parse(&format!("[index]\ncache_dir = {written:?}\n"));

            assert_eq!(report.config.index.cache_dir, None, "{written}");
            assert_eq!(report.problems.len(), 1, "{written}");
            assert_eq!(report.problems[0].severity, Severity::Warning);
        }
    }

    #[test]
    fn a_pattern_that_is_not_a_pattern_is_dropped_from_the_list() {
        let report = parse("[workspace]\nexclude = [\"**/build/**\", \"**/[unclosed\"]\n");

        assert_eq!(report.config.workspace.exclude, ["**/build/**"]);
        assert_eq!(report.problems.len(), 1);
        assert_eq!(report.problems[0].severity, Severity::Warning);
        assert!(report.problems[0].message.contains("unclosed"));
    }

    #[test]
    fn an_include_a_project_names_is_relative_to_the_root_and_the_nearest_rule_wins() {
        let report = parse(
            r#"
            [compile.include]
            "*" = ["include"]
            "src/legacy" = ["include/legacy", "generated"]
            "#,
        );
        let root = Path::new("/p");

        let legacy = report
            .config
            .compile
            .includes_for(root, Path::new("/p/src/legacy/old.cpp"));
        assert_eq!(
            legacy,
            [
                PathBuf::from("/p/include/legacy"),
                PathBuf::from("/p/generated"),
                PathBuf::from("/p/include"),
            ],
            "the specific directory first, then the project-wide one"
        );

        let elsewhere = report
            .config
            .compile
            .includes_for(root, Path::new("/p/src/new/modern.cpp"));
        assert_eq!(elsewhere, [PathBuf::from("/p/include")]);
    }

    #[test]
    fn a_file_that_is_not_there_is_not_a_problem() {
        let files = crate::MemoryFiles::new();
        let report = load_config(&files, Path::new("/p"), None);

        assert!(!report.found());
        assert!(report.problems.is_empty());
    }

    #[test]
    fn a_file_the_caller_named_must_exist() {
        // `--config x` is an instruction, not a convention: a missing one is worth saying out loud.
        let files = crate::MemoryFiles::new();
        let report = load_config(&files, Path::new("/p"), Some(Path::new("/p/other.toml")));

        assert!(!report.found());
        assert_eq!(report.problems.len(), 1);
        assert!(report.problems[0].message.contains("other.toml"));
    }

    #[test]
    fn a_configuration_is_read_from_a_provider() {
        let files = crate::MemoryFiles::new()
            .with_file("/p/.cppls.toml", "[workspace]\nexclude = [\"build/**\"]\n");
        let report = load_config(&files, Path::new("/p"), None);

        assert_eq!(report.path.as_deref(), Some(Path::new("/p/.cppls.toml")));
        assert_eq!(report.config.workspace.exclude, ["build/**"]);
    }
}