cpp_code_analysis 0.1.1

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
//! Where the files are, and what the compiler was told about them.
//!
//! # Why this is configuration and not a guess
//!
//! Every resolution decision downstream depends on these values, and every one of them is invisible in
//! the source text:
//!
//! * `#include <vector>` finds a different file under `-I /opt/gcc/include` than under the default, and
//!   a wrong answer means every declaration in the file has the wrong types;
//! * `#ifdef _WIN32` is decided by the *target*, not by the machine the editor runs on, so analysing a
//!   Windows codebase on Linux with the host's macros reports half of it as not compiled;
//! * `-DNDEBUG` changes which `#ifdef` branches are live, and it is set by the build type, not by
//!   anything in the file.
//!
//! So the configuration is supplied, and [`CompilerConfig::default`] is deliberately *empty* rather than
//! a plausible guess: an empty configuration makes `#if` conditions `Unknown`, which is honest, while a
//! guessed one makes them wrong, which is not.
//!
//! A caller with a build system reads it from the project's [`compile_commands.json`] rather than writing it
//! down twice — see [`parse_compile_commands`], which turns a translation unit's command line into exactly these
//! fields.
//!
//! [`compile_commands.json`]: https://clang.llvm.org/docs/JSONCompilationDatabase.html

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

use cpp_parser::Dialect;

/// An include search directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludePath {
    pub directory: PathBuf,
    /// Was this a *system* directory (`-isystem`, or the toolchain's own)?
    ///
    /// It decides which spelling of `#include` finds it first, and — with `-Wsystem-headers` semantics —
    /// whether diagnostics inside it are worth reporting at all.
    pub is_system: bool,
}

impl IncludePath {
    pub fn user(directory: impl Into<PathBuf>) -> Self {
        IncludePath {
            directory: directory.into(),
            is_system: false,
        }
    }

    pub fn system(directory: impl Into<PathBuf>) -> Self {
        IncludePath {
            directory: directory.into(),
            is_system: true,
        }
    }
}

/// A macro the compiler was given on the command line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandLineMacro {
    pub name: Box<str>,
    /// `-DFOO` defines `FOO` as `1`, not as nothing: the standard says so, and code that writes
    /// `#if FOO` depends on it.
    pub value: Option<Box<str>>,
}

impl CommandLineMacro {
    /// `-DFOO` — defined as `1`.
    pub fn defined(name: impl Into<Box<str>>) -> Self {
        CommandLineMacro {
            name: name.into(),
            value: None,
        }
    }

    /// `-DFOO=bar` — defined with a value.
    pub fn with_value(name: impl Into<Box<str>>, value: impl Into<Box<str>>) -> Self {
        CommandLineMacro {
            name: name.into(),
            value: Some(value.into()),
        }
    }
}

/// What the compiler was told.
///
/// Cloneable and cheap to compare, because a file's analysis is only valid for the configuration it was
/// computed under: when the configuration changes, everything computed from it is stale. Comparing whole
/// configurations is how that invalidation is decided, so a configuration that cannot be compared cannot
/// be cached.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompilerConfig {
    /// **The project's compilation database**, when one was found — what each file's own command says.
    ///
    /// Carried here because the compilation is *per file* and the answer cannot be: a database with one entry per
    /// translation unit says something different for each of them, and a project-wide list built from its first
    /// entry is another target's compilation. That is not a simplification but a wrong answer — a header reachable
    /// only from another target's directory resolves, and an include of `"Config.h"` takes whichever `Config.h` the
    /// search order reaches first. [`CompilerConfig::for_file`] is where it is consulted.
    pub database: Option<std::sync::Arc<CompileCommands>>,
    /// Flags `[compile].remove_args` drops, and `[compile].extra_args` adds — kept here because they apply to
    /// **whichever set won**, and with a compilation database there is no single winning set: each file's own
    /// command is filtered by these in [`CompilerConfig::for_file`], in the documented order (removing first,
    /// then appending), so that "drop the database's `-std=c++17`, add `-std=c++20`" means what it says for every
    /// file rather than only for a project-wide answer that no longer exists.
    pub remove_args: Vec<String>,
    /// See [`CompilerConfig::remove_args`].
    pub extra_args: Vec<String>,
    /// **The project's compilation targets**, when its own file describes them — see
    /// [`TargetSection`](crate::project::TargetSection), and [`CompilerConfig::for_file`] for what they decide.
    ///
    /// Carried on the configuration rather than looked up where it is needed, because the places that need it hold
    /// a configuration and a **file** and nothing else.
    pub targets: Vec<crate::project::TargetSection>,

    /// `-I` and `-isystem`, in the order they were given.
    ///
    /// Order is load-bearing: the first directory that holds the file wins, which is how a project
    /// overrides a system header with its own copy of the same name.
    pub include_paths: Vec<IncludePath>,

    /// `-D`, in the order they were given. Later definitions of a name shadow earlier ones.
    pub defines: Vec<CommandLineMacro>,

    /// `-U`, which removes a definition. Applied after the defines that precede it.
    pub undefines: Vec<Box<str>>,

    /// The standard, as spelled on the command line (`c++20`, `gnu++17`).
    ///
    /// `None` means "not told", which is not the same as "the default": a file that uses C++20 features is
    /// only wrong to reject if the configuration says a standard that lacks them.
    pub standard: Option<Box<str>>,

    /// `--target`, or `-m32`/`-m64`.
    ///
    /// Kept separate from the standard because the two answer different questions, and because the target
    /// is what decides the platform macros — which are not predefined here, since the toolchain that
    /// defines them is not the one analysing.
    pub target: Option<Box<str>>,

    /// **Which compiler** the flags above are for, as far as the *parser* has to care.
    ///
    /// The language is the same everywhere; a handful of reserved spellings are not. `__int128` is a type to g++
    /// and a plain name to cl.exe, `__int64` is the other way round, and `_Float16` is GCC's. Reading one of them
    /// the wrong way is not a diagnostic but a **silent wrong tree** — with `__int128` read as a name,
    /// `unsigned __int128 x;` comes out as a declaration of a variable called `__int128` with a macro suffix `x`
    /// — so the parser has to be told which compiler is reading the file.
    ///
    /// Set from the toolchain's own predefined macros (`__GNUC__` / `_MSC_VER`, see
    /// [`Dialect::from_predefined_macros`]) rather than guessed from the flags, and it is part of the summary's
    /// **context hash**: the same text read for two targets is two different summaries, and a cache that confused
    /// them would serve one target's facts to the other.
    pub dialect: Dialect,

    /// **Read this project as CUDA** — see [`cpp_parser::ParserConfig::cuda`], which is the switch the grammar's
    /// CUDA rules are behind.
    ///
    /// Set by the toolchain (`__CUDACC__` in the predefined macros, or an `nvcc` compiler) and by a project that says
    /// so in `.cppls.toml`. Not the same question as [`CompilerConfig::dialect`]: `nvcc` compiles host code with a host
    /// compiler, so a CUDA program is C++ *and* MSVC-or-GNU *and* CUDA — three independent layers, which is why this is
    /// a flag rather than another [`Dialect`] variant.
    pub cuda: bool,

    /// The directory the compilation was run in.
    ///
    /// A relative `-I` and a relative `#include` are both relative to *this*, not to the file or to the
    /// editor's working directory. Without it, a project's own include paths resolve against nothing in
    /// particular.
    pub working_directory: Option<PathBuf>,

    /// **The project root, for the one search that is about where files *are* rather than where a compiler looked.**
    ///
    /// `None` in every caller that has no root to name — the parser's own tests, a snippet with no project — and the
    /// only thing that reads it is [`Self::fuzzy_includes`]'s fallback.
    pub root: Option<PathBuf>,

    /// **May an `#include` be found by matching the tail of its path against the files under [`Self::root`]?**
    ///
    /// Off by default, and the default is the point: this is a **guess**, and a project that has stated how it is
    /// built must never have a guess shadow what it said. See [`crate::include::fuzzy`] for the rule and what it
    /// refuses to match.
    ///
    /// **On is the interesting setting**, because the alternative is a compile database: a Visual Studio solution
    /// cannot export one, and a checkout nobody has configured does not have one, and in both cases the choice is
    /// between a fuzzy match and a closure of fourteen files. Measured on a real CMake project with no database, the
    /// fallback is what turns `#include "Session/StandardIOSession.h"` from an unresolved name into the header.
    pub fuzzy_includes: bool,
}

impl CompilerConfig {
    /// **This configuration as it applies to one file** — its target's include directories and defines.
    ///
    /// The reason the type carries [`CompilerConfig::targets`] at all. On a real C++ project the compilation is
    /// *per target*, and one project-wide list is not a simplification but a wrong answer: a header reachable only
    /// from another target's directory resolves, and an include of `"Config.h"` takes whichever `Config.h` the
    /// search order happens to reach first.
    ///
    /// Three rules, in the order a reader would expect:
    ///
    /// ```text
    /// 1. the target's directories go **in front**   its own headers win over anything project-wide
    /// 2. `[compile.include]` follows                the older per-directory key, which this makes work
    /// 3. the rest is unchanged                      flags, undefines, target, compiler
    /// ```
    ///
    /// A file no target describes is returned unchanged, and so is a configuration whose root is unknown — the
    /// paths in a configuration file are relative to the root, so without one there is nothing to resolve.
    /// **The language a file is compiled as**, from its own command's `-std=` — the last thing that decides which syntax
    /// the parser may accept, and until now the one thing nobody asked about.
    ///
    /// Order, and why: the file's own command first, because a compilation database is per translation unit and one
    /// target may be C++17 while another is C++20; then the project's `extra_args`, which is a person saying what the
    /// build is; then [`LanguageConfig::permissive`], because a parse that has not been told what it is reading must not
    /// refuse the headers it is reading.
    ///
    /// No stored field: a cached copy would go stale the moment the database or `extra_args` changed, and the database is
    /// already the one place the answer comes from.
    pub fn language_for(&self, file: &Path) -> cpp_parser::features::LanguageConfig {
        let from_the_command = self
            .database
            .as_ref()
            .and_then(|database| database.command_for(file))
            .and_then(|command| {
                cpp_parser::features::LanguageConfig::from_command_line(command.arguments.iter())
            });
        from_the_command
            // **The project's own `-std=`**, which is where `[compile] standard` and a `-std=` inside
            // `[compile] args` end up (see `project_config_from_flags`). It was missing here, so a project that
            // states its language in its own file was read as *not told*: `args = ["-std=gnu11"]` on neovim's
            // `arglist.c` left the family unknown, and every C++-only rule fired on a C file — measured, **14
            // `cstyle-cast` findings** telling a C program to write `static_cast`.
            .or_else(|| {
                self.standard
                    .as_deref()
                    .and_then(cpp_parser::features::LanguageConfig::from_standard_spelling)
            })
            .or_else(|| {
                cpp_parser::features::LanguageConfig::from_command_line(self.extra_args.iter())
            })
            // **A `.c` file is C.** When nothing above has said what the file is — no database entry, no
            // `[compile] standard`, no `-std=` — the extension is what every compiler decides by, and it is what the
            // *editor* decided too when it opened the file. Without this the family was unknown, `is_c()` answered
            // false, and every C++-only rule fired on C: measured on vim's `charset.c`, `(unsigned)c` in a binary
            // search was underlined as a C-style cast — a diagnostic telling a C program to write `static_cast`,
            // which the language does not have.
            //
            // `.h` is deliberately not here: a header is included by whichever language includes it, and guessing
            // would put the same false positive on the other family.
            .or_else(|| {
                matches!(
                    file.extension().and_then(|extension| extension.to_str()),
                    Some("c") | Some("i")
                )
                .then(cpp_parser::features::LanguageConfig::c)
            })
            .unwrap_or_else(cpp_parser::features::LanguageConfig::permissive)
    }

    pub fn for_file(&self, file: &Path) -> CompilerConfig {
        self.for_file_with(file, &mut |path| std::fs::read_to_string(path).ok())
    }

    /// **[`CompilerConfig::for_file`] with the file reads the caller's**, which is what a test needs and what a
    /// caller holding an unsaved buffer would need.
    ///
    /// The reads are here because a compile command may name a **response file** and keep its
    /// include paths inside it: CMake writes `@CMakeFiles/<target>.dir/includes_CXX.rsp` for the
    /// Makefile and Ninja generators alike, and on a real project *every* entry of its database was
    /// that shape. Expanding it only for the language standard (which is what happened before) left
    /// the per-file include paths of such a project **empty** — measured: `CommandService.cpp`
    /// cannot see `LanguageServer.h` from one directory up, so the include edge is never built,
    /// `LanguageServer`'s 32 member facts are invisible from that file, and every member query that
    /// starts there refuses.
    pub fn for_file_with(
        &self,
        file: &Path,
        read: &mut dyn FnMut(&Path) -> Option<String>,
    ) -> CompilerConfig {
        let Some(root) = self.root.clone() else {
            return self.clone();
        };

        let mut config = self.clone();
        let mut ahead: Vec<IncludePath> = Vec::new();

        // **This file's own command, when the project has one.** It *replaces* whatever project-wide answer was in
        // force rather than joining it: with one database entry per translation unit, the entry for another file is
        // not a weaker answer but a different compilation, and its include directories are where the wrong header
        // lives. `[compile].args` is the one thing that can override this, because a person who wrote the
        // compilation down has said what it is — that is applied where the configuration is built, before this.
        if let Some(command) = self
            .database
            .as_ref()
            .and_then(|database| database.command_for(file))
        {
            // **The project's own edits apply to this file's command**, in the order the configuration documents:
            // `remove_args` drops, `extra_args` appends. Doing it here rather than once for the project is what
            // keeps the two keys meaning what they say now that the flags are per file.
            let arguments: Vec<String> = command
                .arguments
                .iter()
                .filter(|argument| !self.remove_args.iter().any(|drop| drop == *argument))
                .cloned()
                .chain(self.extra_args.iter().cloned())
                .collect();

            // **The `@response` file is expanded before anything is read out of the command**, because that is
            // where a CMake build keeps the include paths — see [`CompilerConfig::for_file_with`] for the measured
            // cost of not doing it.
            let arguments = expand_response_files(&arguments, command.directory.as_deref(), read);

            // **The include paths, and only those.** They are what decides which header a name resolves to, so they
            // are the ones that must be this file's; the defines stay project-wide because the **cook** seeds every
            // file's macro environment from the project-wide configuration, and a resolver that disagreed with the
            // cooker about `-DFEATURE_ONLY` would answer about a program nobody compiled. Making the defines per
            // file means making the seed per file, which is the next step rather than half of this one.
            //
            // **But the file's command replaces the *project's* directories, never the compiler's.** A compile
            // command does not spell out its own search path: `g++ -std=c++23 -c x.cpp` names no `-I` for `<string>`,
            // because those directories are built into the compiler and printed only when it is asked (`-E -v`).
            // Taking `own.include_paths` alone therefore deleted the standard library for **every** project that has
            // a database — measured on a four-entry C++23 demo whose commands have no `-I` at all: `<string>`,
            // `<print>`, `<expected>` and `<windows.h>` were all reported missing, and `std::expected<double,
            // std::string>` had no type. The system entries are the one part of the search path the entry knows
            // nothing about, so they survive it — after its own directories, which is the order a compiler searches.
            let own = config_from_arguments(&arguments, command.directory.clone());
            let system: Vec<IncludePath> = config
                .include_paths
                .iter()
                .filter(|path| path.is_system)
                .cloned()
                .collect();
            config.include_paths = own.include_paths;
            for path in system {
                let known = config
                    .include_paths
                    .iter()
                    .any(|held| held.directory == path.directory);
                if !known {
                    config.include_paths.push(path);
                }
            }
        }

        // **Every target that describes the file, nearest first.** `[compile].include` has always documented itself
        // as additive — "*both can be true at once, and the nearer rule is the one that should be added first*" —
        // and a target is the same idea with more to say, so the two are one mechanism here rather than two rules
        // that would disagree. Patterns of different targets usually exclude each other (`Server/**` and `Core/**`),
        // and where they do not, the nearer one's directories come first, which is what "nearest first" means for a
        // search path.
        let mut describing: Vec<(
            usize,
            std::cmp::Reverse<usize>,
            &crate::project::TargetSection,
        )> = self
            .targets
            .iter()
            .enumerate()
            .filter_map(|(order, target)| {
                target
                    .describes(&root, file)
                    .map(|specific| (specific, std::cmp::Reverse(order), target))
            })
            .collect();
        describing.sort_by_key(|(specific, order, _)| (std::cmp::Reverse(*specific), *order));

        for (_, _, target) in describing {
            for directory in &target.includes {
                let joined = root.join(directory);
                if !config
                    .include_paths
                    .iter()
                    .any(|held| held.directory == joined)
                    && !ahead.iter().any(|held| held.directory == joined)
                {
                    ahead.push(IncludePath::user(&joined));
                }
            }
            for definition in &target.defines {
                if !config.defines.iter().any(|held| {
                    held.name.as_ref() == definition.split('=').next().unwrap_or("").trim()
                }) {
                    config.defines.push(define_from_a_config_file(definition));
                }
            }
            // The nearest target that states a standard is the one that decides it.
            if config.standard.is_none()
                && let Some(standard) = &target.standard
            {
                config.standard = Some(standard.as_str().into());
            }
        }

        ahead.extend(config.include_paths);
        config.include_paths = ahead;
        config
    }
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_include_path(mut self, directory: impl Into<PathBuf>) -> Self {
        self.include_paths.push(IncludePath::user(directory));
        self
    }

    pub fn with_system_include_path(mut self, directory: impl Into<PathBuf>) -> Self {
        self.include_paths.push(IncludePath::system(directory));
        self
    }

    pub fn with_define(mut self, definition: CommandLineMacro) -> Self {
        self.defines.push(definition);
        self
    }

    pub fn with_standard(mut self, standard: impl Into<Box<str>>) -> Self {
        self.standard = Some(standard.into());
        self
    }

    /// Compile for a **target**: the triple (`x86_64-w64-mingw32`) or the flag (`-m32`) the command line named.
    ///
    /// It decides the platform macros a condition may ask about — see [`predefined_macros_of`], which is where the
    /// names a triple fixes are turned into definitions.
    pub fn with_target(mut self, target: impl Into<Box<str>>) -> Self {
        self.target = Some(target.into());
        self
    }

    /// Parse for a **target compiler**: what its reserved spellings mean. See [`CompilerConfig::dialect`].
    pub fn with_dialect(mut self, dialect: Dialect) -> Self {
        self.dialect = dialect;
        self
    }

    /// The dialect in force. [`Dialect::default`] until a toolchain says otherwise.
    pub fn dialect(&self) -> Dialect {
        self.dialect
    }

    /// **Read this project as CUDA** — see [`CompilerConfig::cuda`].
    pub fn with_cuda(mut self, cuda: bool) -> Self {
        self.cuda = cuda;
        self
    }

    /// Is this project CUDA? — see [`CompilerConfig::cuda`].
    pub fn cuda(&self) -> bool {
        self.cuda
    }

    pub fn with_working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
        self.working_directory = Some(directory.into());
        self
    }

    /// Is the configuration empty — nothing supplied at all?
    ///
    /// Worth asking, because an empty configuration is the state in which conditions are `Unknown` and
    /// includes resolve only relative to the including file. A consumer that wants to warn "this project
    /// has no compile database" asks this rather than inspecting five fields.
    pub fn is_empty(&self) -> bool {
        self.include_paths.is_empty()
            && self.defines.is_empty()
            && self.undefines.is_empty()
            && self.standard.is_none()
            && self.target.is_none()
            && self.working_directory.is_none()
    }

    /// The user (`-I`) directories, in order.
    pub fn user_include_paths(&self) -> impl Iterator<Item = &Path> {
        self.include_paths
            .iter()
            .filter(|path| !path.is_system)
            .map(|path| path.directory.as_path())
    }

    /// The system (`-isystem`) directories, in order.
    pub fn system_include_paths(&self) -> impl Iterator<Item = &Path> {
        self.include_paths
            .iter()
            .filter(|path| path.is_system)
            .map(|path| path.directory.as_path())
    }

    /// Resolve a path that came from the command line against the working directory.
    ///
    /// A relative `-I` is relative to where the compiler ran. A caller that has not said where that was
    /// gets the path unchanged, which is the least surprising answer: it is what the command line said.
    pub fn resolve_against_working_directory(&self, path: &Path) -> PathBuf {
        if path.is_absolute() {
            return path.to_path_buf();
        }

        match &self.working_directory {
            Some(directory) => directory.join(path),
            None => path.to_path_buf(),
        }
    }

    /// Every include directory, in the order a `#include "..."` searches them.
    ///
    /// The including file's own directory is *not* here: it is not a property of the configuration but of
    /// the file doing the including, so it is prepended by the resolver.
    pub fn search_order(&self) -> impl Iterator<Item = (&Path, bool)> {
        self.include_paths
            .iter()
            .map(|path| (path.directory.as_path(), path.is_system))
    }
}

/// One entry of a `compile_commands.json`.
///
/// The format every C++ build system can emit, and the only reliable way to learn how a project is meant
/// to be compiled. Guessing include paths from a directory listing is what produces an analysis that
/// works on the author's machine and fails everywhere else.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCommand {
    /// The file this command compiles.
    pub file: PathBuf,
    /// The directory the command runs in.
    pub directory: Option<PathBuf>,
    /// The command, split into arguments.
    pub arguments: Vec<String>,
}

impl CompileCommand {
    /// Read the compiler configuration out of this command's arguments.
    ///
    /// Only the flags that change *what the code means* are read: include paths, defines, the standard,
    /// the target, and the `-o`/`-c`/input/output plumbing that is skipped. A flag this does not know is
    /// ignored rather than guessed at, because a wrong `-D` is worse than a missing one.
    pub fn to_config(&self) -> CompilerConfig {
        config_from_arguments(&self.arguments, self.directory.clone())
    }

    /// The same, with the command's **response files read** — which is what a build system's own command line means,
    /// and what CMake's database needs.
    ///
    /// CMake does not write its include paths into the arguments: it writes
    /// `@CMakeFiles/<target>.dir/includes_CXX.rsp` and puts the `-I` flags in that file, for the Makefile and Ninja
    /// generators alike. Measured on a real CMake project: **every** entry of its `compile_commands.json` was of that
    /// shape, so a reader that does not follow the indirection sees a project with no include paths at all — its own
    /// headers stop resolving, and the file list stops being the build's.
    ///
    /// `read` is the caller's, because this crate reads through a provider rather than the filesystem: the server has
    /// to answer for a buffer nobody has saved, and a test has to be able to say what a file holds.
    pub fn to_config_with(&self, read: &mut dyn FnMut(&Path) -> Option<String>) -> CompilerConfig {
        let arguments = expand_response_files(&self.arguments, self.directory.as_deref(), read);

        config_from_arguments(&arguments, self.directory.clone())
    }
}

/// **The arguments a command really has, once the response files it names have been read.**
///
/// An argument beginning `@` names a file whose contents are arguments — the form CMake uses for the include paths of
/// every target it generates a Makefile or Ninja build for. A relative name is relative to the command's **working
/// directory**, which is what the compiler resolves it against, and the expansion is recursive because a response
/// file may name another. A file that cannot be read is **left as it stands** rather than dropped: the argument is
/// what the build wrote, and an argument this layer cannot interpret is not one it may silently delete.
pub fn expand_response_files(
    arguments: &[String],
    working_directory: Option<&Path>,
    read: &mut dyn FnMut(&Path) -> Option<String>,
) -> Vec<String> {
    /// How deep a chain of response files may go before the rest is left alone. A build system writes one level; the
    /// bound is here so that a file naming itself terminates rather than hanging the analysis.
    const DEEPEST: usize = 8;

    let mut expanded = Vec::with_capacity(arguments.len());
    let mut pending: Vec<(String, usize)> = arguments
        .iter()
        .rev()
        .map(|argument| (argument.clone(), 0usize))
        .collect();

    while let Some((argument, depth)) = pending.pop() {
        let Some(name) = argument.strip_prefix('@').filter(|name| !name.is_empty()) else {
            expanded.push(argument);
            continue;
        };

        let named = Path::new(name);
        let resolved = match (named.is_absolute(), working_directory) {
            (true, _) | (false, None) => named.to_path_buf(),
            (false, Some(directory)) => directory.join(named),
        };

        let Some(text) = read(&resolved).filter(|_| depth < DEEPEST) else {
            expanded.push(argument);
            continue;
        };

        // Reversed, because the stack pops from the end: the file's own arguments keep their order.
        for inner in split_command_line(&text).into_iter().rev() {
            pending.push((inner, depth + 1));
        }
    }

    expanded
}

/// Read a compiler configuration out of a list of arguments.
///
/// The one implementation of "what does this flag mean", used by both sources of flags a project has: the
/// `compile_commands.json` entries the build system wrote, and the `[compile].args` a person wrote in
/// `.cppls.toml`. Two readers of the same flag vocabulary would be free to disagree about `-DFOO=` or `-m64`, and
/// the disagreement would show up as a project that analyses differently depending on which source won.
pub fn config_from_arguments(
    arguments: &[String],
    working_directory: Option<PathBuf>,
) -> CompilerConfig {
    let mut config = CompilerConfig {
        working_directory,
        ..CompilerConfig::default()
    };

    let mut index = 0;
    while index < arguments.len() {
        let argument = arguments[index].as_str();
        index += 1;

        // The two spellings of every option: joined (`-Ifoo`) and separate (`-I foo`).
        let take_value = |index: &mut usize| -> Option<&str> {
            let value = arguments.get(*index).map(String::as_str);
            if value.is_some() {
                *index += 1;
            }
            value
        };

        if let Some(rest) = argument.strip_prefix("-isystem") {
            let directory = if rest.is_empty() {
                take_value(&mut index)
            } else {
                Some(rest)
            };
            if let Some(directory) = directory {
                config.include_paths.push(IncludePath::system(directory));
            }
        } else if let Some(rest) = argument.strip_prefix("-I") {
            let directory = if rest.is_empty() {
                take_value(&mut index)
            } else {
                Some(rest)
            };
            if let Some(directory) = directory {
                config.include_paths.push(IncludePath::user(directory));
            }
        } else if let Some(rest) = argument.strip_prefix("-D") {
            let definition = if rest.is_empty() {
                take_value(&mut index)
            } else {
                Some(rest)
            };
            if let Some(definition) = definition {
                config.defines.push(parse_define_argument(definition));
            }
        } else if let Some(rest) = argument.strip_prefix("-U") {
            let name = if rest.is_empty() {
                take_value(&mut index)
            } else {
                Some(rest)
            };
            if let Some(name) = name {
                config.undefines.push(name.into());
            }
        } else if let Some(rest) = argument.strip_prefix("-std=") {
            config.standard = Some(rest.into());
        } else if let Some(rest) = argument.strip_prefix("--target=") {
            config.target = Some(rest.into());
        } else if argument == "--target" {
            if let Some(target) = take_value(&mut index) {
                config.target = Some(target.into());
            }
        } else if argument == "-m32" || argument == "-m64" {
            config.target = Some(argument.into());
        }
    }

    config
}

/// Apply a project's `[compile]` section to a list of flags and read the result.
///
/// The order is the whole meaning of the three keys, and it is one pass:
///
/// ```text
/// 1. remove_args drops flags from the list that won       (`-Werror`, a stale `-std=c++17`)
/// 2. extra_args appends the project's own                 (`-DFEATURE=1`)
/// 3. the result is read once, left to right               so a later `-std=` wins over an earlier one
/// ```
///
/// Removing **before** appending is what makes "drop the database's `-std=c++17`, add `-std=c++20`" work: the
/// other order would leave the added flag first and have the removed one overwrite it. Matching is by the whole
/// spelling — `-std=c++17` — because that is what a person reads in the database and copies into the file; it is
/// not a pattern language.
pub fn project_config_from_flags(
    flags: &[String],
    working_directory: Option<PathBuf>,
    section: &crate::project::CompileSection,
) -> CompilerConfig {
    let mut arguments: Vec<String> = flags
        .iter()
        .filter(|argument| !section.remove_args.iter().any(|drop| drop == *argument))
        .cloned()
        .collect();

    arguments.extend(section.extra_args.iter().cloned());

    config_from_arguments(&arguments, working_directory)
}

/// Read `-DFOO` or `-DFOO=bar`.
///
/// `-DFOO` defines `FOO` as `1` — the standard says so, and `#if FOO` depends on it. An empty value
/// (`-DFOO=`) is *not* the same thing: it is a definition with an empty body, which `#if FOO` rejects.
fn parse_define_argument(argument: &str) -> CommandLineMacro {
    match argument.split_once('=') {
        Some((name, value)) => CommandLineMacro::with_value(name, value),
        None => CommandLineMacro::defined(argument),
    }
}

/// Read a `compile_commands.json`.
///
/// A hand-written reader rather than a `serde` dependency, for two reasons: the shape is one array of
/// objects with three string fields, and — the deciding one — a compile database that does not parse must
/// **not** be a hard failure. Projects emit them with comments, with trailing commas, and with entries for
/// languages this analysis has nothing to say about; the useful behaviour is to take the entries that do
/// parse and say how many did not.
pub fn parse_compile_commands(json: &str) -> CompileCommands {
    let mut commands = Vec::new();
    let mut malformed = 0usize;

    for object in top_level_objects(json) {
        match parse_command_object(&object) {
            Some(command) => commands.push(command),
            None => malformed += 1,
        }
    }

    CompileCommands {
        commands,
        malformed,
    }
}

/// A parsed compile database, and what was skipped.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompileCommands {
    pub commands: Vec<CompileCommand>,
    /// How many entries were present but not understood.
    ///
    /// Reported rather than ignored: a database where most entries failed to parse is one whose include
    /// paths are mostly missing, and an analysis built on it would be quietly wrong rather than loudly
    /// incomplete.
    pub malformed: usize,
}

impl CompileCommands {
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// The command for a file, if the database has one.
    ///
    /// Compared by the *tail* of the path, and falling back to the tail is the point: a database writes
    /// absolute paths from the machine that produced it, and a project opened somewhere else has the same
    /// files with a different prefix — a different checkout directory, a container path, a drive letter.
    /// Requiring an exact match would make a checked-in `compile_commands.json` useless, which is the case
    /// it is most often generated for.
    ///
    /// The two are matched by their **longest common tail**: the request's tails are collected into a set
    /// and the stored path's tails are looked up in it. Comparing only one side's tails would match in one
    /// direction — a request with a prefix the database lacks, but not a database entry with a prefix the
    /// request lacks — and the two directions are the same question asked twice.
    pub fn command_for(&self, file: &Path) -> Option<&CompileCommand> {
        let requested = normalize_for_comparison(file);
        let request_tails: std::collections::HashSet<&str> =
            path_suffixes(&requested).into_iter().collect();

        // The most specific match wins, so a database with both `/a/x.h` and `/b/a/x.h` answers a request
        // for the latter with the entry that names more of it.
        let mut best: Option<(usize, &CompileCommand)> = None;

        for command in &self.commands {
            let stored = normalize_for_comparison(&command.file);

            for tail in path_suffixes(&stored) {
                if request_tails.contains(tail) {
                    let specificity = tail.len();
                    if best.is_none_or(|(best_len, _)| specificity > best_len) {
                        best = Some((specificity, command));
                    }
                    break;
                }
            }
        }

        best.map(|(_, command)| command)
    }
}

/// Every tail of a path that starts at a component boundary, longest first.
///
/// `a/b/c.cpp` yields `a/b/c.cpp`, `b/c.cpp`, `c.cpp`. The boundary is what keeps the match meaningful:
/// a bare `ends_with` would let a request for `in.cpp` find `main.cpp`, which is not a path relationship
/// but a string one.
///
/// A root is part of the boundary rather than a component, so `/a/b.cpp` also yields `a/b.cpp` — a request
/// spelled with an absolute prefix still matches a database entry spelled without one, and the reverse.
fn path_suffixes(path: &str) -> Vec<&str> {
    let mut suffixes = vec![path];

    for (index, character) in path.char_indices() {
        if character == '/' {
            let rest = &path[index + 1..];
            // A root on its own, or a drive root (`C:/`), leaves nothing to match at this boundary.
            if !rest.is_empty() {
                suffixes.push(rest);
            }
        }
    }

    // A drive prefix is a boundary too: `c:/a/b.h` yields `a/b.h`.
    if let Some(index) = path.find(":/")
        && index + 2 < path.len()
    {
        suffixes.push(&path[index + 2..]);
    }

    suffixes
}

/// A path reduced to the form two spellings of one file agree on.
///
/// Separators are unified **before** lexical normalization, and that order matters: on Unix a backslash is
/// an ordinary character in a file name, so `normalize_path` leaves `C:\proj\a.cpp` as one component named
/// `C:\proj\a.cpp`. A database written on Windows and read on Linux — which is what a checked-in
/// `compile_commands.json` usually is — has to be read as a path, not as a file name containing
/// backslashes.
///
/// Case is folded for the same reason: the same file spelled two ways across platforms.
fn normalize_for_comparison(path: &Path) -> String {
    let unified: String = path
        .to_string_lossy()
        .chars()
        .map(|character| if character == '\\' { '/' } else { character })
        .collect();

    crate::paths::normalize_path(Path::new(&unified), true)
}

/// The `{...}` objects directly inside the outermost array.
///
/// Deliberately shallow: it tracks brace and string nesting so that a `{` inside a string does not count,
/// and it does not attempt to be a general JSON reader.
fn top_level_objects(json: &str) -> Vec<String> {
    let mut objects = Vec::new();
    let mut depth = 0usize;
    let mut start: Option<usize> = None;
    let mut in_string = false;
    let mut escaped = false;

    for (index, character) in json.char_indices() {
        if in_string {
            if escaped {
                escaped = false;
            } else if character == '\\' {
                escaped = true;
            } else if character == '"' {
                in_string = false;
            }
            continue;
        }

        match character {
            '"' => in_string = true,
            '{' => {
                if depth == 0 {
                    start = Some(index);
                }
                depth += 1;
            }
            '}' => {
                depth = depth.saturating_sub(1);
                if depth == 0
                    && let Some(start) = start.take()
                {
                    objects.push(json[start..=index].to_string());
                }
            }
            _ => {}
        }
    }

    objects
}

/// Read the three fields of one entry.
fn parse_command_object(object: &str) -> Option<CompileCommand> {
    let directory = string_field(object, "directory").map(PathBuf::from);
    let file = string_field(object, "file")?;

    // Either shape: `arguments` is a list, `command` is a shell string. Both are in the wild, and a
    // project may use either, so neither can be treated as the real one.
    let arguments = match array_field(object, "arguments") {
        Some(arguments) => arguments,
        None => split_command_line(&string_field(object, "command")?),
    };

    Some(CompileCommand {
        file: PathBuf::from(file),
        directory,
        arguments,
    })
}

/// The value of a top-level string field.
fn string_field(object: &str, name: &str) -> Option<String> {
    let key = format!("\"{name}\"");
    let after_key = object.find(&key)? + key.len();

    let rest = object[after_key..].trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let rest = rest.strip_prefix('"')?;

    let mut value = String::new();
    let mut escaped = false;
    for character in rest.chars() {
        if escaped {
            // The sequences that appear in paths: a Windows separator and a quote.
            value.push(match character {
                'n' => '\n',
                't' => '\t',
                other => other,
            });
            escaped = false;
            continue;
        }

        match character {
            '\\' => escaped = true,
            '"' => return Some(value),
            other => value.push(other),
        }
    }

    None
}

/// The values of a top-level string-array field.
fn array_field(object: &str, name: &str) -> Option<Vec<String>> {
    let key = format!("\"{name}\"");
    let after_key = object.find(&key)? + key.len();

    let rest = object[after_key..].trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let rest = rest.strip_prefix('[')?;

    let mut values = Vec::new();
    let mut current: Option<String> = None;
    let mut escaped = false;

    for character in rest.chars() {
        if escaped {
            if let Some(value) = current.as_mut() {
                value.push(character);
            }
            escaped = false;
            continue;
        }

        match character {
            '\\' => escaped = true,
            '"' => match current.take() {
                Some(value) => values.push(value),
                None => current = Some(String::new()),
            },
            ']' if current.is_none() => return Some(values),
            other => {
                if let Some(value) = current.as_mut() {
                    value.push(other);
                }
            }
        }
    }

    None
}

/// Split a shell command line into arguments.
///
/// Handles the quoting a build system uses: single and double quotes, and backslash escapes. Not a shell
/// — no expansion, no pipes — because a compile command is a program with arguments, and anything more
/// would be reading a language this is not trying to implement.
///
/// # A backslash is a separator before it is an escape
///
/// The rule is **"a backslash escapes only whitespace and a quote"**, and it is one rule rather
/// than two because the same function reads the database on every platform: `\` is the path
/// separator on Windows and the escape character in a POSIX shell, and a reader that treats it as
/// POSIX does everywhere deletes the character after every separator. Every `#include <print>` in
/// it then resolved to the wrong library or to nothing, which is what "the editor does not
/// understand this project" looks like from the outside.
///
/// So a backslash before a letter, a digit or another backslash is **kept**: `C:\Users\zc` is a path, `-I a\ b` is
/// an escaped space, `"a \"quoted\" b"` is a quoted run with two quotation marks in it. `\\server\share` keeps both
/// of its leading separators, which the POSIX rule would have collapsed — the one place this is deliberately wider
/// than a shell, because a UNC path is a real spelling and `\\` after an escape is not.
pub fn split_command_line(command: &str) -> Vec<String> {
    let mut arguments = Vec::new();
    let mut current = String::new();
    let mut has_current = false;
    let mut quote: Option<char> = None;
    let mut characters = command.chars().peekable();

    while let Some(character) = characters.next() {
        match character {
            // Before a quote or a space a backslash is an escape; anywhere else it is a path separator.
            '\\' if quote != Some('\'') => {
                let escapes = characters
                    .peek()
                    .is_some_and(|next| next.is_whitespace() || *next == '"' || *next == '\'');
                if escapes {
                    current.push(characters.next().expect("peeked"));
                } else {
                    current.push('\\');
                }
                has_current = true;
            }
            '"' | '\'' if quote.is_none() => {
                quote = Some(character);
                // A quote opens an argument even if it is empty: `"" ` is one empty argument.
                has_current = true;
            }
            character if Some(character) == quote => quote = None,
            character if character.is_whitespace() && quote.is_none() => {
                if has_current {
                    arguments.push(std::mem::take(&mut current));
                    has_current = false;
                }
            }
            other => {
                current.push(other);
                has_current = true;
            }
        }
    }

    if has_current {
        arguments.push(current);
    }

    arguments
}

/// The macros a **configuration decides by itself** — before a single file is read, and whether or not a compiler
/// was found.
///
/// A discovered toolchain's `-dM` output is the fuller answer and stays the base (see `Toolchain::macros`); this is
/// the other half. A compile database that says `-std=c++20` and nothing else has already **decided**
/// `__cplusplus`, and every `#if __cplusplus >= 201703L` in every header is a question about it — a question the
/// condition layer can only answer `Unknown` (and therefore keeps every branch's `#define` out of the evidence)
/// when nobody puts the number there. The same goes for the platform a `--target` triple names.
///
/// # What is deliberately *not* here
///
/// Nothing whose value the configuration does not fix. `__GNUC__`'s **version** is not in `-std=c++20`, and a
/// guessed `__GNUC__ 1` answers `#if __GNUC__ >= 5` with a confident **false** — the one kind of answer this
/// layer must never give, because `Unknown` costs a reading while a wrong `false` loses a branch. The compiler's
/// family and version are the toolchain's to report.
///
/// # Order
///
/// Callers apply these **over** the toolchain's predefined macros and **under** the configuration's own `-D`s: a
/// project that says `-std=c++11` means it, even when the compiler's default invocation would have said
/// `202002L` — which is exactly the point `Toolchain::search_paths` makes about passing the standard on.
pub fn predefined_macros_of(config: &CompilerConfig) -> Vec<CommandLineMacro> {
    let mut macros = Vec::new();

    if let Some(standard) = config.standard.as_deref() {
        if let Some(value) = cplusplus_value(standard) {
            macros.push(CommandLineMacro::with_value("__cplusplus", value));

            // MSVC's own headers ask `_MSVC_LANG` for the same number, and its value is the language version
            // rather than the compiler's — so it is decided by the standard here too.
            if config.dialect() == Dialect::Msvc {
                macros.push(CommandLineMacro::with_value("_MSVC_LANG", value));
            }
        } else if let Some(value) = c_version(standard) {
            macros.push(CommandLineMacro::with_value("__STDC__", "1"));
            macros.push(CommandLineMacro::with_value("__STDC_VERSION__", value));
        }
    }

    if let Some(target) = config.target.as_deref() {
        macros.extend(target_macros(target));
    }

    macros
}

/// The standard with the dialect prefix (`gnu`) taken off: `gnu++20` → `++20`, `c++17` → `c++17`, `gnu11` → `11`.
fn without_the_gnu_prefix(standard: &str) -> &str {
    standard.strip_prefix("gnu").unwrap_or(standard)
}

/// `c++17` → `201703L`, `gnu++20` → `202002L`, and the older `c++2a`/`c++2b` spellings.
///
/// `None` for anything this table does not know — an unset standard, a typo, or a draft whose number is not settled
/// (`c++26`): a wrong `__cplusplus` is worse than an absent one, because absent is `Unknown`.
fn cplusplus_value(standard: &str) -> Option<&'static str> {
    // `-std=c++17` and `-std=gnu++17` differ only in whose extensions are on, and only the first writes the `c`.
    let rest = without_the_gnu_prefix(standard);
    let year = rest
        .strip_prefix("c++")
        .or_else(|| rest.strip_prefix("++"))?;

    Some(match year {
        "98" | "03" => "199711L",
        "11" => "201103L",
        "14" => "201402L",
        "17" => "201703L",
        "20" | "2a" => "202002L",
        "23" | "2b" => "202302L",
        _ => return None,
    })
}

/// `c11` → `201112L`, `gnu99` → `199901L`. `None` for a C++ standard or an unknown spelling.
fn c_version(standard: &str) -> Option<&'static str> {
    // `-std=c11` and `-std=gnu11` are the same standard, and only the first has a `c` to take off.
    let rest = without_the_gnu_prefix(standard);
    let year = rest.strip_prefix('c').unwrap_or(rest);

    Some(match year {
        "89" | "90" => "199409L",
        "99" => "199901L",
        "11" => "201112L",
        "17" | "18" => "201710L",
        "23" | "2x" => "202311L",
        _ => return None,
    })
}

/// The platform names a target triple — or `-m32`/`-m64` — decides.
///
/// Only the names the target **fixes**: the operating system and the pointer width. Sizes, versions and the
/// compiler's family are not in a triple's spelling, and guessing them is what [`predefined_macros_of`] refuses.
fn target_macros(target: &str) -> Vec<CommandLineMacro> {
    let lowered = target.to_ascii_lowercase();
    let mut macros = Vec::new();

    // 64- and 32-bit are marked by the **architecture** name, which is why the answer is a pair: `_WIN64` is about
    // the target being a 64-bit one, and `x86_64-w64-mingw32`'s `w64` is the *vendor's* spelling — a `i686-w64-…`
    // target is 32-bit with the same vendor string, which is how a `contains("64")` test gets it wrong.
    let architecture =
        if lowered.contains("x86_64") || lowered.contains("amd64") || lowered == "-m64" {
            Some(("__x86_64__", true))
        } else if lowered.contains("i686")
            || lowered.contains("i386")
            || lowered.contains("x86")
            || lowered == "-m32"
        {
            Some(("__i386__", false))
        } else if lowered.contains("aarch64") || lowered.contains("arm64") {
            Some(("__aarch64__", true))
        } else if lowered.contains("arm") {
            Some(("__arm__", false))
        } else {
            None
        };

    let is_windows =
        lowered.contains("windows") || lowered.contains("mingw") || lowered.contains("msvc");

    if let Some((name, _)) = architecture {
        macros.push(CommandLineMacro::with_value(name, "1"));
    }

    if is_windows {
        macros.push(CommandLineMacro::with_value("_WIN32", "1"));
        if architecture.is_some_and(|(_, wide)| wide) {
            macros.push(CommandLineMacro::with_value("_WIN64", "1"));
        }
    }

    if lowered.contains("apple") || lowered.contains("darwin") {
        macros.push(CommandLineMacro::with_value("__APPLE__", "1"));
    }

    if lowered.contains("linux") {
        macros.push(CommandLineMacro::with_value("__linux__", "1"));
    }

    macros
}

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

    /// The standard is a **decision**, and the one every header asks about.
    #[test]
    fn the_standard_decides_cplusplus() {
        for (standard, expected) in [
            ("c++98", "199711L"),
            ("gnu++03", "199711L"),
            ("c++11", "201103L"),
            ("gnu++14", "201402L"),
            ("c++17", "201703L"),
            ("gnu++20", "202002L"),
            ("c++2a", "202002L"),
            ("c++23", "202302L"),
        ] {
            let config = CompilerConfig::default().with_standard(standard);
            let macros = predefined_macros_of(&config);
            let cplusplus = macros.iter().find(|entry| &*entry.name == "__cplusplus");

            assert_eq!(
                cplusplus.and_then(|entry| entry.value.as_deref()),
                Some(expected),
                "{standard} means {expected}"
            );
        }

        // A standard this table does not know, and no standard at all: **nothing** is said, which is `Unknown`
        // rather than a wrong number. `c++26`'s value is not settled, so it is not guessed either.
        for standard in ["c++26", "c++29", "c90", "nonsense"] {
            let config = CompilerConfig::default().with_standard(standard);
            assert!(
                !predefined_macros_of(&config)
                    .iter()
                    .any(|entry| &*entry.name == "__cplusplus"),
                "{standard} says nothing about `__cplusplus`"
            );
        }
    }

    /// MSVC's headers ask the same question under a different name.
    #[test]
    fn the_msvc_dialect_gets_the_language_version_too() {
        let config = CompilerConfig::default()
            .with_standard("c++17")
            .with_dialect(Dialect::Msvc);
        let macros = predefined_macros_of(&config);

        assert_eq!(
            macros
                .iter()
                .find(|entry| &*entry.name == "_MSVC_LANG")
                .and_then(|entry| entry.value.as_deref()),
            Some("201703L")
        );
        // And GCC's dialect does not: a name that compiler never defines is a name its headers never ask about.
        let config = CompilerConfig::default().with_standard("c++17");
        assert!(
            !predefined_macros_of(&config)
                .iter()
                .any(|entry| &*entry.name == "_MSVC_LANG")
        );
    }

    /// C is a different language with a different macro — and its own spellings.
    #[test]
    fn a_c_standard_decides_the_c_version() {
        let config = CompilerConfig::default().with_standard("gnu11");
        let macros = predefined_macros_of(&config);

        let value = |name: &str| {
            macros
                .iter()
                .find(|entry| &*entry.name == name)
                .and_then(|entry| entry.value.as_deref())
        };

        assert_eq!(value("__STDC_VERSION__"), Some("201112L"));
        assert_eq!(value("__STDC__"), Some("1"));
        assert_eq!(value("__cplusplus"), None, "C has no `__cplusplus`");
    }

    /// The target decides the platform, and **only** what it says.
    #[test]
    fn the_target_decides_the_platform_names() {
        let names = |target: &str| {
            predefined_macros_of(&CompilerConfig::default().with_target(target))
                .into_iter()
                .map(|entry| entry.name.to_string())
                .collect::<Vec<_>>()
        };

        assert!(names("x86_64-w64-mingw32").contains(&"_WIN32".to_string()));
        assert!(names("x86_64-w64-mingw32").contains(&"_WIN64".to_string()));
        assert!(names("x86_64-w64-mingw32").contains(&"__x86_64__".to_string()));
        assert!(names("x86_64-unknown-linux-gnu").contains(&"__linux__".to_string()));
        assert!(!names("x86_64-unknown-linux-gnu").contains(&"_WIN32".to_string()));
        assert!(names("i686-w64-mingw32").contains(&"__i386__".to_string()));
        assert!(!names("i686-w64-mingw32").contains(&"_WIN64".to_string()));
        assert!(names("-m32").contains(&"__i386__".to_string()));
        assert!(names("-m64").contains(&"__x86_64__".to_string()));

        // A target nobody described says nothing: the platform macros are a claim about the *target*, and a
        // spelling this table does not know is not one.
        assert!(names("wasm32-unknown-unknown").is_empty());
    }
}
/// **One definition as a configuration file writes it** — `"NAME"` or `"NAME=value"`, without the `-D`.
///
/// The same reading `-D` gets on a command line, because the two say the same thing in two places: `#if NAME`
/// depends on which of the two spellings was used.
fn define_from_a_config_file(written: &str) -> CommandLineMacro {
    match written.split_once('=') {
        Some((name, value)) => CommandLineMacro::with_value(name.trim(), value),
        None => CommandLineMacro::defined(written.trim()),
    }
}
#[cfg(test)]
mod database_search_path_tests {
    use super::*;

    /// **A compile database entry replaces the project's directories, never the compiler's.**
    ///
    /// Reported from a project with `compile_commands.json`: "几乎不认识 C++ 标准库了". The database's commands were
    /// `c++ -std=c++23 ... -c src/main.cpp` — **no `-I` at all**, because a compiler's own search path is built in and
    /// never written on the command line. Taking that entry's (empty) directory list as the file's whole search path
    /// therefore deleted `<string>`, `<print>`, `<expected>` and `<windows.h>` from every file of the project: four
    /// `IncludeNotFound` diagnostics and no type for `std::expected<double, std::string>`.
    ///
    /// A project that is *not* behind a database was unaffected — which is why this survived: without one, the
    /// toolchain's paths are the only ones there are.
    #[test]
    fn the_compilers_own_directories_survive_an_empty_database_entry() {
        let root = PathBuf::from("/p");
        let file = root.join("src/main.cpp");
        let database = CompileCommands {
            commands: vec![CompileCommand {
                file: file.clone(),
                directory: Some(root.clone()),
                // The shape CMake's Ninja generator writes: the standard, warnings, and the input file.
                arguments: vec![
                    "c++".to_string(),
                    "-std=c++23".to_string(),
                    "-c".to_string(),
                    file.to_string_lossy().into_owned(),
                ],
            }],
            malformed: 0,
        };

        let config = CompilerConfig {
            root: Some(root.clone()),
            database: Some(std::sync::Arc::new(database)),
            include_paths: vec![
                IncludePath::user("/project/include"),
                IncludePath::system("/gcc/include/c++/15.1.0"),
                IncludePath::system("/gcc/include-fixed"),
            ],
            ..CompilerConfig::default()
        };

        let per_file = config.for_file(&file);
        let directories: Vec<&Path> = per_file
            .include_paths
            .iter()
            .map(|path| path.directory.as_path())
            .collect();

        // The project's own directory is the *entry's* to replace — it is gone, because that entry lists none.
        assert!(
            !directories.contains(&Path::new("/project/include")),
            "the database entry replaces the project's directories: {directories:?}"
        );
        // The compiler's are not, and they come after whatever the entry did say.
        assert_eq!(
            directories,
            vec![
                Path::new("/gcc/include/c++/15.1.0"),
                Path::new("/gcc/include-fixed")
            ],
            "the toolchain's directories are the one part of the search path the entry knows nothing about"
        );
        assert!(
            per_file.include_paths.iter().all(|path| path.is_system),
            "and they keep their kind, so `#include <…>` still finds them"
        );
    }

    /// **A database entry's own `-I` comes first**, and the compiler's directories after it — the order a compiler
    /// searches, and the reason the fix appends rather than prepends.
    #[test]
    fn the_entries_own_directories_come_before_the_compilers() {
        let root = PathBuf::from("/p");
        let file = root.join("src/main.cpp");
        let database = CompileCommands {
            commands: vec![CompileCommand {
                file: file.clone(),
                directory: Some(root.clone()),
                arguments: vec![
                    "c++".to_string(),
                    "-I/project/generated".to_string(),
                    "-c".to_string(),
                    file.to_string_lossy().into_owned(),
                ],
            }],
            malformed: 0,
        };

        let config = CompilerConfig {
            root: Some(root),
            database: Some(std::sync::Arc::new(database)),
            include_paths: vec![IncludePath::system("/gcc/include")],
            ..CompilerConfig::default()
        };

        let directories: Vec<PathBuf> = config
            .for_file(&file)
            .include_paths
            .iter()
            .map(|path| path.directory.clone())
            .collect();
        assert_eq!(
            directories,
            vec![
                PathBuf::from("/project/generated"),
                PathBuf::from("/gcc/include")
            ]
        );
    }
}