compiletest/
header.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;

use semver::Version;
use tracing::*;

use crate::common::{Config, Debugger, FailMode, Mode, PassMode};
use crate::debuggers::{extract_cdb_version, extract_gdb_version};
use crate::header::auxiliary::{AuxProps, parse_and_update_aux};
use crate::header::cfg::{MatchOutcome, parse_cfg_name_directive};
use crate::header::needs::CachedNeedsConditions;
use crate::util::static_regex;

pub(crate) mod auxiliary;
mod cfg;
mod needs;
#[cfg(test)]
mod tests;

pub struct HeadersCache {
    needs: CachedNeedsConditions,
}

impl HeadersCache {
    pub fn load(config: &Config) -> Self {
        Self { needs: CachedNeedsConditions::load(config) }
    }
}

/// Properties which must be known very early, before actually running
/// the test.
#[derive(Default)]
pub struct EarlyProps {
    /// Auxiliary crates that should be built and made available to this test.
    /// Included in [`EarlyProps`] so that the indicated files can participate
    /// in up-to-date checking. Building happens via [`TestProps::aux`] instead.
    pub(crate) aux: AuxProps,
    pub revisions: Vec<String>,
}

impl EarlyProps {
    pub fn from_file(config: &Config, testfile: &Path) -> Self {
        let file = File::open(testfile).expect("open test file to parse earlyprops");
        Self::from_reader(config, testfile, file)
    }

    pub fn from_reader<R: Read>(config: &Config, testfile: &Path, rdr: R) -> Self {
        let mut props = EarlyProps::default();
        let mut poisoned = false;
        iter_header(
            config.mode,
            &config.suite,
            &mut poisoned,
            testfile,
            rdr,
            &mut |DirectiveLine { raw_directive: ln, .. }| {
                parse_and_update_aux(config, ln, &mut props.aux);
                config.parse_and_update_revisions(testfile, ln, &mut props.revisions);
            },
        );

        if poisoned {
            eprintln!("errors encountered during EarlyProps parsing: {}", testfile.display());
            panic!("errors encountered during EarlyProps parsing");
        }

        props
    }
}

#[derive(Clone, Debug)]
pub struct TestProps {
    // Lines that should be expected, in order, on standard out
    pub error_patterns: Vec<String>,
    // Regexes that should be expected, in order, on standard out
    pub regex_error_patterns: Vec<String>,
    // Extra flags to pass to the compiler
    pub compile_flags: Vec<String>,
    // Extra flags to pass when the compiled code is run (such as --bench)
    pub run_flags: Vec<String>,
    /// Extra flags to pass to rustdoc but not the compiler.
    pub doc_flags: Vec<String>,
    // If present, the name of a file that this test should match when
    // pretty-printed
    pub pp_exact: Option<PathBuf>,
    /// Auxiliary crates that should be built and made available to this test.
    pub(crate) aux: AuxProps,
    // Environment settings to use for compiling
    pub rustc_env: Vec<(String, String)>,
    // Environment variables to unset prior to compiling.
    // Variables are unset before applying 'rustc_env'.
    pub unset_rustc_env: Vec<String>,
    // Environment settings to use during execution
    pub exec_env: Vec<(String, String)>,
    // Environment variables to unset prior to execution.
    // Variables are unset before applying 'exec_env'
    pub unset_exec_env: Vec<String>,
    // Build documentation for all specified aux-builds as well
    pub build_aux_docs: bool,
    /// Build the documentation for each crate in a unique output directory.
    /// Uses `<root output directory>/docs/<test name>/doc`.
    pub unique_doc_out_dir: bool,
    // Flag to force a crate to be built with the host architecture
    pub force_host: bool,
    // Check stdout for error-pattern output as well as stderr
    pub check_stdout: bool,
    // Check stdout & stderr for output of run-pass test
    pub check_run_results: bool,
    // For UI tests, allows compiler to generate arbitrary output to stdout
    pub dont_check_compiler_stdout: bool,
    // For UI tests, allows compiler to generate arbitrary output to stderr
    pub dont_check_compiler_stderr: bool,
    // When checking the output of stdout or stderr check
    // that the lines of expected output are a subset of the actual output.
    pub compare_output_lines_by_subset: bool,
    // Don't force a --crate-type=dylib flag on the command line
    //
    // Set this for example if you have an auxiliary test file that contains
    // a proc-macro and needs `#![crate_type = "proc-macro"]`. This ensures
    // that the aux file is compiled as a `proc-macro` and not as a `dylib`.
    pub no_prefer_dynamic: bool,
    // Run -Zunpretty expanded when running pretty printing tests
    pub pretty_expanded: bool,
    // Which pretty mode are we testing with, default to 'normal'
    pub pretty_mode: String,
    // Only compare pretty output and don't try compiling
    pub pretty_compare_only: bool,
    // Patterns which must not appear in the output of a cfail test.
    pub forbid_output: Vec<String>,
    // Revisions to test for incremental compilation.
    pub revisions: Vec<String>,
    // Directory (if any) to use for incremental compilation.  This is
    // not set by end-users; rather it is set by the incremental
    // testing harness and used when generating compilation
    // arguments. (In particular, it propagates to the aux-builds.)
    pub incremental_dir: Option<PathBuf>,
    // If `true`, this test will use incremental compilation.
    //
    // This can be set manually with the `incremental` header, or implicitly
    // by being a part of an incremental mode test. Using the `incremental`
    // header should be avoided if possible; using an incremental mode test is
    // preferred. Incremental mode tests support multiple passes, which can
    // verify that the incremental cache can be loaded properly after being
    // created. Just setting the header will only verify the behavior with
    // creating an incremental cache, but doesn't check that it is created
    // correctly.
    //
    // Compiletest will create the incremental directory, and ensure it is
    // empty before the test starts. Incremental mode tests will reuse the
    // incremental directory between passes in the same test.
    pub incremental: bool,
    // If `true`, this test is a known bug.
    //
    // When set, some requirements are relaxed. Currently, this only means no
    // error annotations are needed, but this may be updated in the future to
    // include other relaxations.
    pub known_bug: bool,
    // How far should the test proceed while still passing.
    pass_mode: Option<PassMode>,
    // Ignore `--pass` overrides from the command line for this test.
    ignore_pass: bool,
    // How far this test should proceed to start failing.
    pub fail_mode: Option<FailMode>,
    // rustdoc will test the output of the `--test` option
    pub check_test_line_numbers_match: bool,
    // customized normalization rules
    pub normalize_stdout: Vec<(String, String)>,
    pub normalize_stderr: Vec<(String, String)>,
    pub failure_status: Option<i32>,
    // For UI tests, allows compiler to exit with arbitrary failure status
    pub dont_check_failure_status: bool,
    // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the
    // resulting Rust code.
    pub run_rustfix: bool,
    // If true, `rustfix` will only apply `MachineApplicable` suggestions.
    pub rustfix_only_machine_applicable: bool,
    pub assembly_output: Option<String>,
    // If true, the test is expected to ICE
    pub should_ice: bool,
    // If true, the stderr is expected to be different across bit-widths.
    pub stderr_per_bitwidth: bool,
    // The MIR opt to unit test, if any
    pub mir_unit_test: Option<String>,
    // Whether to tell `rustc` to remap the "src base" directory to a fake
    // directory.
    pub remap_src_base: bool,
    /// Extra flags to pass to `llvm-cov` when producing coverage reports.
    /// Only used by the "coverage-run" test mode.
    pub llvm_cov_flags: Vec<String>,
    /// Extra flags to pass to LLVM's `filecheck` tool, in tests that use it.
    pub filecheck_flags: Vec<String>,
    /// Don't automatically insert any `--check-cfg` args
    pub no_auto_check_cfg: bool,
    /// Run tests which require enzyme being build
    pub has_enzyme: bool,
    /// Build and use `minicore` as `core` stub for `no_core` tests in cross-compilation scenarios
    /// that don't otherwise want/need `-Z build-std`.
    pub add_core_stubs: bool,
}

mod directives {
    pub const ERROR_PATTERN: &'static str = "error-pattern";
    pub const REGEX_ERROR_PATTERN: &'static str = "regex-error-pattern";
    pub const COMPILE_FLAGS: &'static str = "compile-flags";
    pub const RUN_FLAGS: &'static str = "run-flags";
    pub const DOC_FLAGS: &'static str = "doc-flags";
    pub const SHOULD_ICE: &'static str = "should-ice";
    pub const BUILD_AUX_DOCS: &'static str = "build-aux-docs";
    pub const UNIQUE_DOC_OUT_DIR: &'static str = "unique-doc-out-dir";
    pub const FORCE_HOST: &'static str = "force-host";
    pub const CHECK_STDOUT: &'static str = "check-stdout";
    pub const CHECK_RUN_RESULTS: &'static str = "check-run-results";
    pub const DONT_CHECK_COMPILER_STDOUT: &'static str = "dont-check-compiler-stdout";
    pub const DONT_CHECK_COMPILER_STDERR: &'static str = "dont-check-compiler-stderr";
    pub const NO_PREFER_DYNAMIC: &'static str = "no-prefer-dynamic";
    pub const PRETTY_EXPANDED: &'static str = "pretty-expanded";
    pub const PRETTY_MODE: &'static str = "pretty-mode";
    pub const PRETTY_COMPARE_ONLY: &'static str = "pretty-compare-only";
    pub const AUX_BIN: &'static str = "aux-bin";
    pub const AUX_BUILD: &'static str = "aux-build";
    pub const AUX_CRATE: &'static str = "aux-crate";
    pub const AUX_CODEGEN_BACKEND: &'static str = "aux-codegen-backend";
    pub const EXEC_ENV: &'static str = "exec-env";
    pub const RUSTC_ENV: &'static str = "rustc-env";
    pub const UNSET_EXEC_ENV: &'static str = "unset-exec-env";
    pub const UNSET_RUSTC_ENV: &'static str = "unset-rustc-env";
    pub const FORBID_OUTPUT: &'static str = "forbid-output";
    pub const CHECK_TEST_LINE_NUMBERS_MATCH: &'static str = "check-test-line-numbers-match";
    pub const IGNORE_PASS: &'static str = "ignore-pass";
    pub const FAILURE_STATUS: &'static str = "failure-status";
    pub const DONT_CHECK_FAILURE_STATUS: &'static str = "dont-check-failure-status";
    pub const RUN_RUSTFIX: &'static str = "run-rustfix";
    pub const RUSTFIX_ONLY_MACHINE_APPLICABLE: &'static str = "rustfix-only-machine-applicable";
    pub const ASSEMBLY_OUTPUT: &'static str = "assembly-output";
    pub const STDERR_PER_BITWIDTH: &'static str = "stderr-per-bitwidth";
    pub const INCREMENTAL: &'static str = "incremental";
    pub const KNOWN_BUG: &'static str = "known-bug";
    pub const TEST_MIR_PASS: &'static str = "test-mir-pass";
    pub const REMAP_SRC_BASE: &'static str = "remap-src-base";
    pub const COMPARE_OUTPUT_LINES_BY_SUBSET: &'static str = "compare-output-lines-by-subset";
    pub const LLVM_COV_FLAGS: &'static str = "llvm-cov-flags";
    pub const FILECHECK_FLAGS: &'static str = "filecheck-flags";
    pub const NO_AUTO_CHECK_CFG: &'static str = "no-auto-check-cfg";
    pub const ADD_CORE_STUBS: &'static str = "add-core-stubs";
    // This isn't a real directive, just one that is probably mistyped often
    pub const INCORRECT_COMPILER_FLAGS: &'static str = "compiler-flags";
}

impl TestProps {
    pub fn new() -> Self {
        TestProps {
            error_patterns: vec![],
            regex_error_patterns: vec![],
            compile_flags: vec![],
            run_flags: vec![],
            doc_flags: vec![],
            pp_exact: None,
            aux: Default::default(),
            revisions: vec![],
            rustc_env: vec![
                ("RUSTC_ICE".to_string(), "0".to_string()),
                ("RUST_BACKTRACE".to_string(), "short".to_string()),
            ],
            unset_rustc_env: vec![("RUSTC_LOG_COLOR".to_string())],
            exec_env: vec![],
            unset_exec_env: vec![],
            build_aux_docs: false,
            unique_doc_out_dir: false,
            force_host: false,
            check_stdout: false,
            check_run_results: false,
            dont_check_compiler_stdout: false,
            dont_check_compiler_stderr: false,
            compare_output_lines_by_subset: false,
            no_prefer_dynamic: false,
            pretty_expanded: false,
            pretty_mode: "normal".to_string(),
            pretty_compare_only: false,
            forbid_output: vec![],
            incremental_dir: None,
            incremental: false,
            known_bug: false,
            pass_mode: None,
            fail_mode: None,
            ignore_pass: false,
            check_test_line_numbers_match: false,
            normalize_stdout: vec![],
            normalize_stderr: vec![],
            failure_status: None,
            dont_check_failure_status: false,
            run_rustfix: false,
            rustfix_only_machine_applicable: false,
            assembly_output: None,
            should_ice: false,
            stderr_per_bitwidth: false,
            mir_unit_test: None,
            remap_src_base: false,
            llvm_cov_flags: vec![],
            filecheck_flags: vec![],
            no_auto_check_cfg: false,
            has_enzyme: false,
            add_core_stubs: false,
        }
    }

    pub fn from_aux_file(&self, testfile: &Path, revision: Option<&str>, config: &Config) -> Self {
        let mut props = TestProps::new();

        // copy over select properties to the aux build:
        props.incremental_dir = self.incremental_dir.clone();
        props.ignore_pass = true;
        props.load_from(testfile, revision, config);

        props
    }

    pub fn from_file(testfile: &Path, revision: Option<&str>, config: &Config) -> Self {
        let mut props = TestProps::new();
        props.load_from(testfile, revision, config);
        props.exec_env.push(("RUSTC".to_string(), config.rustc_path.display().to_string()));

        match (props.pass_mode, props.fail_mode) {
            (None, None) if config.mode == Mode::Ui => props.fail_mode = Some(FailMode::Check),
            (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
            _ => {}
        }

        props
    }

    /// Loads properties from `testfile` into `props`. If a property is
    /// tied to a particular revision `foo` (indicated by writing
    /// `//@[foo]`), then the property is ignored unless `test_revision` is
    /// `Some("foo")`.
    fn load_from(&mut self, testfile: &Path, test_revision: Option<&str>, config: &Config) {
        let mut has_edition = false;
        if !testfile.is_dir() {
            let file = File::open(testfile).unwrap();

            let mut poisoned = false;

            iter_header(
                config.mode,
                &config.suite,
                &mut poisoned,
                testfile,
                file,
                &mut |directive @ DirectiveLine { raw_directive: ln, .. }| {
                    if !directive.applies_to_test_revision(test_revision) {
                        return;
                    }

                    use directives::*;

                    config.push_name_value_directive(
                        ln,
                        ERROR_PATTERN,
                        &mut self.error_patterns,
                        |r| r,
                    );
                    config.push_name_value_directive(
                        ln,
                        REGEX_ERROR_PATTERN,
                        &mut self.regex_error_patterns,
                        |r| r,
                    );

                    config.push_name_value_directive(ln, DOC_FLAGS, &mut self.doc_flags, |r| r);

                    fn split_flags(flags: &str) -> Vec<String> {
                        // Individual flags can be single-quoted to preserve spaces; see
                        // <https://github.com/rust-lang/rust/pull/115948/commits/957c5db6>.
                        flags
                            .split('\'')
                            .enumerate()
                            .flat_map(|(i, f)| {
                                if i % 2 == 1 { vec![f] } else { f.split_whitespace().collect() }
                            })
                            .map(move |s| s.to_owned())
                            .collect::<Vec<_>>()
                    }

                    if let Some(flags) = config.parse_name_value_directive(ln, COMPILE_FLAGS) {
                        self.compile_flags.extend(split_flags(&flags));
                    }
                    if config.parse_name_value_directive(ln, INCORRECT_COMPILER_FLAGS).is_some() {
                        panic!("`compiler-flags` directive should be spelled `compile-flags`");
                    }

                    if let Some(edition) = config.parse_edition(ln) {
                        self.compile_flags.push(format!("--edition={}", edition.trim()));
                        has_edition = true;
                    }

                    config.parse_and_update_revisions(testfile, ln, &mut self.revisions);

                    if let Some(flags) = config.parse_name_value_directive(ln, RUN_FLAGS) {
                        self.run_flags.extend(split_flags(&flags));
                    }

                    if self.pp_exact.is_none() {
                        self.pp_exact = config.parse_pp_exact(ln, testfile);
                    }

                    config.set_name_directive(ln, SHOULD_ICE, &mut self.should_ice);
                    config.set_name_directive(ln, BUILD_AUX_DOCS, &mut self.build_aux_docs);
                    config.set_name_directive(ln, UNIQUE_DOC_OUT_DIR, &mut self.unique_doc_out_dir);

                    config.set_name_directive(ln, FORCE_HOST, &mut self.force_host);
                    config.set_name_directive(ln, CHECK_STDOUT, &mut self.check_stdout);
                    config.set_name_directive(ln, CHECK_RUN_RESULTS, &mut self.check_run_results);
                    config.set_name_directive(
                        ln,
                        DONT_CHECK_COMPILER_STDOUT,
                        &mut self.dont_check_compiler_stdout,
                    );
                    config.set_name_directive(
                        ln,
                        DONT_CHECK_COMPILER_STDERR,
                        &mut self.dont_check_compiler_stderr,
                    );
                    config.set_name_directive(ln, NO_PREFER_DYNAMIC, &mut self.no_prefer_dynamic);
                    config.set_name_directive(ln, PRETTY_EXPANDED, &mut self.pretty_expanded);

                    if let Some(m) = config.parse_name_value_directive(ln, PRETTY_MODE) {
                        self.pretty_mode = m;
                    }

                    config.set_name_directive(
                        ln,
                        PRETTY_COMPARE_ONLY,
                        &mut self.pretty_compare_only,
                    );

                    // Call a helper method to deal with aux-related directives.
                    parse_and_update_aux(config, ln, &mut self.aux);

                    config.push_name_value_directive(
                        ln,
                        EXEC_ENV,
                        &mut self.exec_env,
                        Config::parse_env,
                    );
                    config.push_name_value_directive(
                        ln,
                        UNSET_EXEC_ENV,
                        &mut self.unset_exec_env,
                        |r| r,
                    );
                    config.push_name_value_directive(
                        ln,
                        RUSTC_ENV,
                        &mut self.rustc_env,
                        Config::parse_env,
                    );
                    config.push_name_value_directive(
                        ln,
                        UNSET_RUSTC_ENV,
                        &mut self.unset_rustc_env,
                        |r| r,
                    );
                    config.push_name_value_directive(
                        ln,
                        FORBID_OUTPUT,
                        &mut self.forbid_output,
                        |r| r,
                    );
                    config.set_name_directive(
                        ln,
                        CHECK_TEST_LINE_NUMBERS_MATCH,
                        &mut self.check_test_line_numbers_match,
                    );

                    self.update_pass_mode(ln, test_revision, config);
                    self.update_fail_mode(ln, config);

                    config.set_name_directive(ln, IGNORE_PASS, &mut self.ignore_pass);

                    if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stdout") {
                        self.normalize_stdout.push(rule);
                    }
                    if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stderr") {
                        self.normalize_stderr.push(rule);
                    }

                    if let Some(code) = config
                        .parse_name_value_directive(ln, FAILURE_STATUS)
                        .and_then(|code| code.trim().parse::<i32>().ok())
                    {
                        self.failure_status = Some(code);
                    }

                    config.set_name_directive(
                        ln,
                        DONT_CHECK_FAILURE_STATUS,
                        &mut self.dont_check_failure_status,
                    );

                    config.set_name_directive(ln, RUN_RUSTFIX, &mut self.run_rustfix);
                    config.set_name_directive(
                        ln,
                        RUSTFIX_ONLY_MACHINE_APPLICABLE,
                        &mut self.rustfix_only_machine_applicable,
                    );
                    config.set_name_value_directive(
                        ln,
                        ASSEMBLY_OUTPUT,
                        &mut self.assembly_output,
                        |r| r.trim().to_string(),
                    );
                    config.set_name_directive(
                        ln,
                        STDERR_PER_BITWIDTH,
                        &mut self.stderr_per_bitwidth,
                    );
                    config.set_name_directive(ln, INCREMENTAL, &mut self.incremental);

                    // Unlike the other `name_value_directive`s this needs to be handled manually,
                    // because it sets a `bool` flag.
                    if let Some(known_bug) = config.parse_name_value_directive(ln, KNOWN_BUG) {
                        let known_bug = known_bug.trim();
                        if known_bug == "unknown"
                            || known_bug.split(',').all(|issue_ref| {
                                issue_ref
                                    .trim()
                                    .split_once('#')
                                    .filter(|(_, number)| {
                                        number.chars().all(|digit| digit.is_numeric())
                                    })
                                    .is_some()
                            })
                        {
                            self.known_bug = true;
                        } else {
                            panic!(
                                "Invalid known-bug value: {known_bug}\nIt requires comma-separated issue references (`#000` or `chalk#000`) or `known-bug: unknown`."
                            );
                        }
                    } else if config.parse_name_directive(ln, KNOWN_BUG) {
                        panic!(
                            "Invalid known-bug attribute, requires comma-separated issue references (`#000` or `chalk#000`) or `known-bug: unknown`."
                        );
                    }

                    config.set_name_value_directive(
                        ln,
                        TEST_MIR_PASS,
                        &mut self.mir_unit_test,
                        |s| s.trim().to_string(),
                    );
                    config.set_name_directive(ln, REMAP_SRC_BASE, &mut self.remap_src_base);
                    config.set_name_directive(
                        ln,
                        COMPARE_OUTPUT_LINES_BY_SUBSET,
                        &mut self.compare_output_lines_by_subset,
                    );

                    if let Some(flags) = config.parse_name_value_directive(ln, LLVM_COV_FLAGS) {
                        self.llvm_cov_flags.extend(split_flags(&flags));
                    }

                    if let Some(flags) = config.parse_name_value_directive(ln, FILECHECK_FLAGS) {
                        self.filecheck_flags.extend(split_flags(&flags));
                    }

                    config.set_name_directive(ln, NO_AUTO_CHECK_CFG, &mut self.no_auto_check_cfg);

                    self.update_add_core_stubs(ln, config);
                },
            );

            if poisoned {
                eprintln!("errors encountered during TestProps parsing: {}", testfile.display());
                panic!("errors encountered during TestProps parsing");
            }
        }

        if self.should_ice {
            self.failure_status = Some(101);
        }

        if config.mode == Mode::Incremental {
            self.incremental = true;
        }

        if config.mode == Mode::Crashes {
            // we don't want to pollute anything with backtrace-files
            // also turn off backtraces in order to save some execution
            // time on the tests; we only need to know IF it crashes
            self.rustc_env = vec![
                ("RUST_BACKTRACE".to_string(), "0".to_string()),
                ("RUSTC_ICE".to_string(), "0".to_string()),
            ];
        }

        for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
            if let Ok(val) = env::var(key) {
                if !self.exec_env.iter().any(|&(ref x, _)| x == key) {
                    self.exec_env.push(((*key).to_owned(), val))
                }
            }
        }

        if let (Some(edition), false) = (&config.edition, has_edition) {
            self.compile_flags.push(format!("--edition={}", edition));
        }
    }

    fn update_fail_mode(&mut self, ln: &str, config: &Config) {
        let check_ui = |mode: &str| {
            // Mode::Crashes may need build-fail in order to trigger llvm errors or stack overflows
            if config.mode != Mode::Ui && config.mode != Mode::Crashes {
                panic!("`{}-fail` header is only supported in UI tests", mode);
            }
        };
        if config.mode == Mode::Ui && config.parse_name_directive(ln, "compile-fail") {
            panic!("`compile-fail` header is useless in UI tests");
        }
        let fail_mode = if config.parse_name_directive(ln, "check-fail") {
            check_ui("check");
            Some(FailMode::Check)
        } else if config.parse_name_directive(ln, "build-fail") {
            check_ui("build");
            Some(FailMode::Build)
        } else if config.parse_name_directive(ln, "run-fail") {
            check_ui("run");
            Some(FailMode::Run)
        } else {
            None
        };
        match (self.fail_mode, fail_mode) {
            (None, Some(_)) => self.fail_mode = fail_mode,
            (Some(_), Some(_)) => panic!("multiple `*-fail` headers in a single test"),
            (_, None) => {}
        }
    }

    fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) {
        let check_no_run = |s| match (config.mode, s) {
            (Mode::Ui, _) => (),
            (Mode::Crashes, _) => (),
            (Mode::Codegen, "build-pass") => (),
            (Mode::Incremental, _) => {
                if revision.is_some() && !self.revisions.iter().all(|r| r.starts_with("cfail")) {
                    panic!("`{s}` header is only supported in `cfail` incremental tests")
                }
            }
            (mode, _) => panic!("`{s}` header is not supported in `{mode}` tests"),
        };
        let pass_mode = if config.parse_name_directive(ln, "check-pass") {
            check_no_run("check-pass");
            Some(PassMode::Check)
        } else if config.parse_name_directive(ln, "build-pass") {
            check_no_run("build-pass");
            Some(PassMode::Build)
        } else if config.parse_name_directive(ln, "run-pass") {
            check_no_run("run-pass");
            Some(PassMode::Run)
        } else {
            None
        };
        match (self.pass_mode, pass_mode) {
            (None, Some(_)) => self.pass_mode = pass_mode,
            (Some(_), Some(_)) => panic!("multiple `*-pass` headers in a single test"),
            (_, None) => {}
        }
    }

    pub fn pass_mode(&self, config: &Config) -> Option<PassMode> {
        if !self.ignore_pass && self.fail_mode.is_none() {
            if let mode @ Some(_) = config.force_pass_mode {
                return mode;
            }
        }
        self.pass_mode
    }

    // does not consider CLI override for pass mode
    pub fn local_pass_mode(&self) -> Option<PassMode> {
        self.pass_mode
    }

    pub fn update_add_core_stubs(&mut self, ln: &str, config: &Config) {
        let add_core_stubs = config.parse_name_directive(ln, directives::ADD_CORE_STUBS);
        if add_core_stubs {
            if !matches!(config.mode, Mode::Ui | Mode::Codegen | Mode::Assembly) {
                panic!(
                    "`add-core-stubs` is currently only supported for ui, codegen and assembly test modes"
                );
            }

            // FIXME(jieyouxu): this check is currently order-dependent, but we should probably
            // collect all directives in one go then perform a validation pass after that.
            if self.local_pass_mode().is_some_and(|pm| pm == PassMode::Run) {
                // `minicore` can only be used with non-run modes, because it's `core` prelude stubs
                // and can't run.
                panic!("`add-core-stubs` cannot be used to run the test binary");
            }

            self.add_core_stubs = add_core_stubs;
        }
    }
}

/// If the given line begins with the appropriate comment prefix for a directive,
/// returns a struct containing various parts of the directive.
fn line_directive<'line>(
    line_number: usize,
    comment: &str,
    original_line: &'line str,
) -> Option<DirectiveLine<'line>> {
    // Ignore lines that don't start with the comment prefix.
    let after_comment = original_line.trim_start().strip_prefix(comment)?.trim_start();

    let revision;
    let raw_directive;

    if let Some(after_open_bracket) = after_comment.strip_prefix('[') {
        // A comment like `//@[foo]` only applies to revision `foo`.
        let Some((line_revision, after_close_bracket)) = after_open_bracket.split_once(']') else {
            panic!(
                "malformed condition directive: expected `{comment}[foo]`, found `{original_line}`"
            )
        };

        revision = Some(line_revision);
        raw_directive = after_close_bracket.trim_start();
    } else {
        revision = None;
        raw_directive = after_comment;
    };

    Some(DirectiveLine { line_number, revision, raw_directive })
}

// To prevent duplicating the list of directives between `compiletest`,`htmldocck` and `jsondocck`,
// we put it into a common file which is included in rust code and parsed here.
// FIXME: This setup is temporary until we figure out how to improve this situation.
//        See <https://github.com/rust-lang/rust/issues/125813#issuecomment-2141953780>.
include!("directive-list.rs");

const KNOWN_HTMLDOCCK_DIRECTIVE_NAMES: &[&str] = &[
    "count",
    "!count",
    "files",
    "!files",
    "has",
    "!has",
    "has-dir",
    "!has-dir",
    "hasraw",
    "!hasraw",
    "matches",
    "!matches",
    "matchesraw",
    "!matchesraw",
    "snapshot",
    "!snapshot",
];

const KNOWN_JSONDOCCK_DIRECTIVE_NAMES: &[&str] =
    &["count", "!count", "has", "!has", "is", "!is", "ismany", "!ismany", "set", "!set"];

/// The (partly) broken-down contents of a line containing a test directive,
/// which [`iter_header`] passes to its callback function.
///
/// For example:
///
/// ```text
/// //@ compile-flags: -O
///     ^^^^^^^^^^^^^^^^^ raw_directive
///
/// //@ [foo] compile-flags: -O
///      ^^^                    revision
///           ^^^^^^^^^^^^^^^^^ raw_directive
/// ```
struct DirectiveLine<'ln> {
    line_number: usize,
    /// Some test directives start with a revision name in square brackets
    /// (e.g. `[foo]`), and only apply to that revision of the test.
    /// If present, this field contains the revision name (e.g. `foo`).
    revision: Option<&'ln str>,
    /// The main part of the directive, after removing the comment prefix
    /// and the optional revision specifier.
    ///
    /// This is "raw" because the directive's name and colon-separated value
    /// (if present) have not yet been extracted or checked.
    raw_directive: &'ln str,
}

impl<'ln> DirectiveLine<'ln> {
    fn applies_to_test_revision(&self, test_revision: Option<&str>) -> bool {
        self.revision.is_none() || self.revision == test_revision
    }
}

pub(crate) struct CheckDirectiveResult<'ln> {
    is_known_directive: bool,
    trailing_directive: Option<&'ln str>,
}

pub(crate) fn check_directive<'a>(
    directive_ln: &'a str,
    mode: Mode,
    original_line: &str,
) -> CheckDirectiveResult<'a> {
    let (directive_name, post) = directive_ln.split_once([':', ' ']).unwrap_or((directive_ln, ""));

    let trailing = post.trim().split_once(' ').map(|(pre, _)| pre).unwrap_or(post);
    let is_known = |s: &str| {
        KNOWN_DIRECTIVE_NAMES.contains(&s)
            || match mode {
                Mode::Rustdoc | Mode::RustdocJson => {
                    original_line.starts_with("//@")
                        && match mode {
                            Mode::Rustdoc => KNOWN_HTMLDOCCK_DIRECTIVE_NAMES,
                            Mode::RustdocJson => KNOWN_JSONDOCCK_DIRECTIVE_NAMES,
                            _ => unreachable!(),
                        }
                        .contains(&s)
                }
                _ => false,
            }
    };
    let trailing_directive = {
        // 1. is the directive name followed by a space? (to exclude `:`)
        matches!(directive_ln.get(directive_name.len()..), Some(s) if s.starts_with(' '))
            // 2. is what is after that directive also a directive (ex: "only-x86 only-arm")
            && is_known(trailing)
    }
    .then_some(trailing);

    CheckDirectiveResult { is_known_directive: is_known(&directive_name), trailing_directive }
}

fn iter_header(
    mode: Mode,
    _suite: &str,
    poisoned: &mut bool,
    testfile: &Path,
    rdr: impl Read,
    it: &mut dyn FnMut(DirectiveLine<'_>),
) {
    if testfile.is_dir() {
        return;
    }

    // Coverage tests in coverage-run mode always have these extra directives, without needing to
    // specify them manually in every test file. (Some of the comments below have been copied over
    // from the old `tests/run-make/coverage-reports/Makefile`, which no longer exists.)
    //
    // FIXME(jieyouxu): I feel like there's a better way to do this, leaving for later.
    if mode == Mode::CoverageRun {
        let extra_directives: &[&str] = &[
            "needs-profiler-runtime",
            // FIXME(pietroalbini): this test currently does not work on cross-compiled targets
            // because remote-test is not capable of sending back the *.profraw files generated by
            // the LLVM instrumentation.
            "ignore-cross-compile",
        ];
        // Process the extra implied directives, with a dummy line number of 0.
        for raw_directive in extra_directives {
            it(DirectiveLine { line_number: 0, revision: None, raw_directive });
        }
    }

    // NOTE(jieyouxu): once we get rid of `Makefile`s we can unconditionally check for `//@`.
    let comment = if testfile.extension().is_some_and(|e| e == "rs") { "//@" } else { "#" };

    let mut rdr = BufReader::with_capacity(1024, rdr);
    let mut ln = String::new();
    let mut line_number = 0;

    loop {
        line_number += 1;
        ln.clear();
        if rdr.read_line(&mut ln).unwrap() == 0 {
            break;
        }
        let ln = ln.trim();

        // Assume that any directives will be found before the first module or function. This
        // doesn't seem to be an optimization with a warm page cache. Maybe with a cold one.
        // FIXME(jieyouxu): this will cause `//@` directives in the rest of the test file to
        // not be checked.
        if ln.starts_with("fn") || ln.starts_with("mod") {
            return;
        }

        let Some(directive_line) = line_directive(line_number, comment, ln) else {
            continue;
        };

        // Perform unknown directive check on Rust files.
        if testfile.extension().map(|e| e == "rs").unwrap_or(false) {
            let CheckDirectiveResult { is_known_directive, trailing_directive } =
                check_directive(directive_line.raw_directive, mode, ln);

            if !is_known_directive {
                *poisoned = true;

                eprintln!(
                    "error: detected unknown compiletest test directive `{}` in {}:{}",
                    directive_line.raw_directive,
                    testfile.display(),
                    line_number,
                );

                return;
            }

            if let Some(trailing_directive) = &trailing_directive {
                *poisoned = true;

                eprintln!(
                    "error: detected trailing compiletest test directive `{}` in {}:{}\n \
                      help: put the trailing directive in it's own line: `//@ {}`",
                    trailing_directive,
                    testfile.display(),
                    line_number,
                    trailing_directive,
                );

                return;
            }
        }

        it(directive_line);
    }
}

impl Config {
    fn parse_and_update_revisions(&self, testfile: &Path, line: &str, existing: &mut Vec<String>) {
        if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
            if self.mode == Mode::RunMake {
                panic!("`run-make` tests do not support revisions: {}", testfile.display());
            }

            let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
            for revision in raw.split_whitespace().map(|r| r.to_string()) {
                if !duplicates.insert(revision.clone()) {
                    panic!(
                        "duplicate revision: `{}` in line `{}`: {}",
                        revision,
                        raw,
                        testfile.display()
                    );
                }
                existing.push(revision);
            }
        }
    }

    fn parse_env(nv: String) -> (String, String) {
        // nv is either FOO or FOO=BAR
        let mut strs: Vec<String> = nv.splitn(2, '=').map(str::to_owned).collect();

        match strs.len() {
            1 => (strs.pop().unwrap(), String::new()),
            2 => {
                let end = strs.pop().unwrap();
                (strs.pop().unwrap(), end)
            }
            n => panic!("Expected 1 or 2 strings, not {}", n),
        }
    }

    fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
        if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
            Some(PathBuf::from(&s))
        } else if self.parse_name_directive(line, "pp-exact") {
            testfile.file_name().map(PathBuf::from)
        } else {
            None
        }
    }

    fn parse_custom_normalization(&self, line: &str, prefix: &str) -> Option<(String, String)> {
        let parsed = parse_cfg_name_directive(self, line, prefix);
        if parsed.outcome != MatchOutcome::Match {
            return None;
        }
        let name = parsed.name.expect("successful match always has a name");

        let Some((regex, replacement)) = parse_normalize_rule(line) else {
            panic!(
                "couldn't parse custom normalization rule: `{line}`\n\
                help: expected syntax is: `{prefix}-{name}: \"REGEX\" -> \"REPLACEMENT\"`"
            );
        };
        Some((regex, replacement))
    }

    fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
        // Ensure the directive is a whole word. Do not match "ignore-x86" when
        // the line says "ignore-x86_64".
        line.starts_with(directive)
            && matches!(line.as_bytes().get(directive.len()), None | Some(&b' ') | Some(&b':'))
    }

    fn parse_negative_name_directive(&self, line: &str, directive: &str) -> bool {
        line.starts_with("no-") && self.parse_name_directive(&line[3..], directive)
    }

    pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
        let colon = directive.len();
        if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
            let value = line[(colon + 1)..].to_owned();
            debug!("{}: {}", directive, value);
            Some(expand_variables(value, self))
        } else {
            None
        }
    }

    pub fn find_rust_src_root(&self) -> Option<PathBuf> {
        let mut path = self.src_base.clone();
        let path_postfix = Path::new("src/etc/lldb_batchmode.py");

        while path.pop() {
            if path.join(&path_postfix).is_file() {
                return Some(path);
            }
        }

        None
    }

    fn parse_edition(&self, line: &str) -> Option<String> {
        self.parse_name_value_directive(line, "edition")
    }

    fn set_name_directive(&self, line: &str, directive: &str, value: &mut bool) {
        match value {
            true => {
                if self.parse_negative_name_directive(line, directive) {
                    *value = false;
                }
            }
            false => {
                if self.parse_name_directive(line, directive) {
                    *value = true;
                }
            }
        }
    }

    fn set_name_value_directive<T>(
        &self,
        line: &str,
        directive: &str,
        value: &mut Option<T>,
        parse: impl FnOnce(String) -> T,
    ) {
        if value.is_none() {
            *value = self.parse_name_value_directive(line, directive).map(parse);
        }
    }

    fn push_name_value_directive<T>(
        &self,
        line: &str,
        directive: &str,
        values: &mut Vec<T>,
        parse: impl FnOnce(String) -> T,
    ) {
        if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
            values.push(value);
        }
    }
}

fn expand_variables(mut value: String, config: &Config) -> String {
    const CWD: &str = "{{cwd}}";
    const SRC_BASE: &str = "{{src-base}}";
    const BUILD_BASE: &str = "{{build-base}}";
    const RUST_SRC_BASE: &str = "{{rust-src-base}}";
    const SYSROOT_BASE: &str = "{{sysroot-base}}";
    const TARGET_LINKER: &str = "{{target-linker}}";
    const TARGET: &str = "{{target}}";

    if value.contains(CWD) {
        let cwd = env::current_dir().unwrap();
        value = value.replace(CWD, &cwd.to_string_lossy());
    }

    if value.contains(SRC_BASE) {
        value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
    }

    if value.contains(BUILD_BASE) {
        value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
    }

    if value.contains(SYSROOT_BASE) {
        value = value.replace(SYSROOT_BASE, &config.sysroot_base.to_string_lossy());
    }

    if value.contains(TARGET_LINKER) {
        value = value.replace(TARGET_LINKER, config.target_linker.as_deref().unwrap_or(""));
    }

    if value.contains(TARGET) {
        value = value.replace(TARGET, &config.target);
    }

    if value.contains(RUST_SRC_BASE) {
        let src_base = config.sysroot_base.join("lib/rustlib/src/rust");
        src_base.try_exists().expect(&*format!("{} should exists", src_base.display()));
        let src_base = src_base.read_link().unwrap_or(src_base);
        value = value.replace(RUST_SRC_BASE, &src_base.to_string_lossy());
    }

    value
}

/// Parses the regex and replacement values of a `//@ normalize-*` header,
/// in the format:
/// ```text
/// normalize-*: "REGEX" -> "REPLACEMENT"
/// ```
fn parse_normalize_rule(header: &str) -> Option<(String, String)> {
    // FIXME: Support escaped double-quotes in strings.
    let captures = static_regex!(
        r#"(?x) # (verbose mode regex)
        ^
        [^:\s]+:\s*             # (header name followed by colon)
        "(?<regex>[^"]*)"       # "REGEX"
        \s+->\s+                # ->
        "(?<replacement>[^"]*)" # "REPLACEMENT"
        $
        "#
    )
    .captures(header)?;
    let regex = captures["regex"].to_owned();
    let replacement = captures["replacement"].to_owned();
    Some((regex, replacement))
}

/// Given an llvm version string that looks like `1.2.3-rc1`, extract as semver. Note that this
/// accepts more than just strict `semver` syntax (as in `major.minor.patch`); this permits omitting
/// minor and patch version components so users can write e.g. `//@ min-llvm-version: 19` instead of
/// having to write `//@ min-llvm-version: 19.0.0`.
///
/// Currently panics if the input string is malformed, though we really should not use panic as an
/// error handling strategy.
///
/// FIXME(jieyouxu): improve error handling
pub fn extract_llvm_version(version: &str) -> Version {
    // The version substring we're interested in usually looks like the `1.2.3`, without any of the
    // fancy suffix like `-rc1` or `meow`.
    let version = version.trim();
    let uninterested = |c: char| !c.is_ascii_digit() && c != '.';
    let version_without_suffix = match version.split_once(uninterested) {
        Some((prefix, _suffix)) => prefix,
        None => version,
    };

    let components: Vec<u64> = version_without_suffix
        .split('.')
        .map(|s| s.parse().expect("llvm version component should consist of only digits"))
        .collect();

    match &components[..] {
        [major] => Version::new(*major, 0, 0),
        [major, minor] => Version::new(*major, *minor, 0),
        [major, minor, patch] => Version::new(*major, *minor, *patch),
        _ => panic!("malformed llvm version string, expected only 1-3 components: {version}"),
    }
}

pub fn extract_llvm_version_from_binary(binary_path: &str) -> Option<Version> {
    let output = Command::new(binary_path).arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    let version = String::from_utf8(output.stdout).ok()?;
    for line in version.lines() {
        if let Some(version) = line.split("LLVM version ").nth(1) {
            return Some(extract_llvm_version(version));
        }
    }
    None
}

/// For tests using the `needs-llvm-zstd` directive:
/// - for local LLVM builds, try to find the static zstd library in the llvm-config system libs.
/// - for `download-ci-llvm`, see if `lld` was built with zstd support.
pub fn llvm_has_libzstd(config: &Config) -> bool {
    // Strategy 1: works for local builds but not with `download-ci-llvm`.
    //
    // We check whether `llvm-config` returns the zstd library. Bootstrap's `llvm.libzstd` will only
    // ask to statically link it when building LLVM, so we only check if the list of system libs
    // contains a path to that static lib, and that it exists.
    //
    // See compiler/rustc_llvm/build.rs for more details and similar expectations.
    fn is_zstd_in_config(llvm_bin_dir: &Path) -> Option<()> {
        let llvm_config_path = llvm_bin_dir.join("llvm-config");
        let output = Command::new(llvm_config_path).arg("--system-libs").output().ok()?;
        assert!(output.status.success(), "running llvm-config --system-libs failed");

        let libs = String::from_utf8(output.stdout).ok()?;
        for lib in libs.split_whitespace() {
            if lib.ends_with("libzstd.a") && Path::new(lib).exists() {
                return Some(());
            }
        }

        None
    }

    // Strategy 2: `download-ci-llvm`'s `llvm-config --system-libs` will not return any libs to
    // use.
    //
    // The CI artifacts also don't contain the bootstrap config used to build them: otherwise we
    // could have looked at the `llvm.libzstd` config.
    //
    // We infer whether `LLVM_ENABLE_ZSTD` was used to build LLVM as a byproduct of testing whether
    // `lld` supports it. If not, an error will be emitted: "LLVM was not built with
    // LLVM_ENABLE_ZSTD or did not find zstd at build time".
    #[cfg(unix)]
    fn is_lld_built_with_zstd(llvm_bin_dir: &Path) -> Option<()> {
        let lld_path = llvm_bin_dir.join("lld");
        if lld_path.exists() {
            // We can't call `lld` as-is, it expects to be invoked by a compiler driver using a
            // different name. Prepare a temporary symlink to do that.
            let lld_symlink_path = llvm_bin_dir.join("ld.lld");
            if !lld_symlink_path.exists() {
                std::os::unix::fs::symlink(lld_path, &lld_symlink_path).ok()?;
            }

            // Run `lld` with a zstd flag. We expect this command to always error here, we don't
            // want to link actual files and don't pass any.
            let output = Command::new(&lld_symlink_path)
                .arg("--compress-debug-sections=zstd")
                .output()
                .ok()?;
            assert!(!output.status.success());

            // Look for a specific error caused by LLVM not being built with zstd support. We could
            // also look for the "no input files" message, indicating the zstd flag was accepted.
            let stderr = String::from_utf8(output.stderr).ok()?;
            let zstd_available = !stderr.contains("LLVM was not built with LLVM_ENABLE_ZSTD");

            // We don't particularly need to clean the link up (so the previous commands could fail
            // in theory but won't in practice), but we can try.
            std::fs::remove_file(lld_symlink_path).ok()?;

            if zstd_available {
                return Some(());
            }
        }

        None
    }

    #[cfg(not(unix))]
    fn is_lld_built_with_zstd(_llvm_bin_dir: &Path) -> Option<()> {
        None
    }

    if let Some(llvm_bin_dir) = &config.llvm_bin_dir {
        // Strategy 1: for local LLVM builds.
        if is_zstd_in_config(llvm_bin_dir).is_some() {
            return true;
        }

        // Strategy 2: for LLVM artifacts built on CI via `download-ci-llvm`.
        //
        // It doesn't work for cases where the artifacts don't contain the linker, but it's
        // best-effort: CI has `llvm.libzstd` and `lld` enabled on the x64 linux artifacts, so it
        // will at least work there.
        //
        // If this can be improved and expanded to less common cases in the future, it should.
        if config.target == "x86_64-unknown-linux-gnu"
            && config.host == config.target
            && is_lld_built_with_zstd(llvm_bin_dir).is_some()
        {
            return true;
        }
    }

    // Otherwise, all hope is lost.
    false
}

/// Takes a directive of the form `"<version1> [- <version2>]"`, returns the numeric representation
/// of `<version1>` and `<version2>` as tuple: `(<version1>, <version2>)`.
///
/// If the `<version2>` part is omitted, the second component of the tuple is the same as
/// `<version1>`.
fn extract_version_range<'a, F, VersionTy: Clone>(
    line: &'a str,
    parse: F,
) -> Option<(VersionTy, VersionTy)>
where
    F: Fn(&'a str) -> Option<VersionTy>,
{
    let mut splits = line.splitn(2, "- ").map(str::trim);
    let min = splits.next().unwrap();
    if min.ends_with('-') {
        return None;
    }

    let max = splits.next();

    if min.is_empty() {
        return None;
    }

    let min = parse(min)?;
    let max = match max {
        Some("") => return None,
        Some(max) => parse(max)?,
        _ => min.clone(),
    };

    Some((min, max))
}

pub fn make_test_description<R: Read>(
    config: &Config,
    cache: &HeadersCache,
    name: test::TestName,
    path: &Path,
    src: R,
    test_revision: Option<&str>,
    poisoned: &mut bool,
) -> test::TestDesc {
    let mut ignore = false;
    let mut ignore_message = None;
    let mut should_fail = false;

    let mut local_poisoned = false;

    // Scan through the test file to handle `ignore-*`, `only-*`, and `needs-*` directives.
    iter_header(
        config.mode,
        &config.suite,
        &mut local_poisoned,
        path,
        src,
        &mut |directive @ DirectiveLine { line_number, raw_directive: ln, .. }| {
            if !directive.applies_to_test_revision(test_revision) {
                return;
            }

            macro_rules! decision {
                ($e:expr) => {
                    match $e {
                        IgnoreDecision::Ignore { reason } => {
                            ignore = true;
                            // The ignore reason must be a &'static str, so we have to leak memory to
                            // create it. This is fine, as the header is parsed only at the start of
                            // compiletest so it won't grow indefinitely.
                            ignore_message = Some(&*Box::leak(Box::<str>::from(reason)));
                        }
                        IgnoreDecision::Error { message } => {
                            eprintln!("error: {}:{line_number}: {message}", path.display());
                            *poisoned = true;
                            return;
                        }
                        IgnoreDecision::Continue => {}
                    }
                };
            }

            decision!(cfg::handle_ignore(config, ln));
            decision!(cfg::handle_only(config, ln));
            decision!(needs::handle_needs(&cache.needs, config, ln));
            decision!(ignore_llvm(config, ln));
            decision!(ignore_cdb(config, ln));
            decision!(ignore_gdb(config, ln));
            decision!(ignore_lldb(config, ln));

            if config.target == "wasm32-unknown-unknown"
                && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS)
            {
                decision!(IgnoreDecision::Ignore {
                    reason: "ignored on WASM as the run results cannot be checked there".into(),
                });
            }

            should_fail |= config.parse_name_directive(ln, "should-fail");
        },
    );

    if local_poisoned {
        eprintln!("errors encountered when trying to make test description: {}", path.display());
        panic!("errors encountered when trying to make test description");
    }

    // The `should-fail` annotation doesn't apply to pretty tests,
    // since we run the pretty printer across all tests by default.
    // If desired, we could add a `should-fail-pretty` annotation.
    let should_panic = match config.mode {
        crate::common::Pretty => test::ShouldPanic::No,
        _ if should_fail => test::ShouldPanic::Yes,
        _ => test::ShouldPanic::No,
    };

    test::TestDesc {
        name,
        ignore,
        ignore_message,
        source_file: "",
        start_line: 0,
        start_col: 0,
        end_line: 0,
        end_col: 0,
        should_panic,
        compile_fail: false,
        no_run: false,
        test_type: test::TestType::Unknown,
    }
}

fn ignore_cdb(config: &Config, line: &str) -> IgnoreDecision {
    if config.debugger != Some(Debugger::Cdb) {
        return IgnoreDecision::Continue;
    }

    if let Some(actual_version) = config.cdb_version {
        if let Some(rest) = line.strip_prefix("min-cdb-version:").map(str::trim) {
            let min_version = extract_cdb_version(rest).unwrap_or_else(|| {
                panic!("couldn't parse version range: {:?}", rest);
            });

            // Ignore if actual version is smaller than the minimum
            // required version
            if actual_version < min_version {
                return IgnoreDecision::Ignore {
                    reason: format!("ignored when the CDB version is lower than {rest}"),
                };
            }
        }
    }
    IgnoreDecision::Continue
}

fn ignore_gdb(config: &Config, line: &str) -> IgnoreDecision {
    if config.debugger != Some(Debugger::Gdb) {
        return IgnoreDecision::Continue;
    }

    if let Some(actual_version) = config.gdb_version {
        if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) {
            let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
                .unwrap_or_else(|| {
                    panic!("couldn't parse version range: {:?}", rest);
                });

            if start_ver != end_ver {
                panic!("Expected single GDB version")
            }
            // Ignore if actual version is smaller than the minimum
            // required version
            if actual_version < start_ver {
                return IgnoreDecision::Ignore {
                    reason: format!("ignored when the GDB version is lower than {rest}"),
                };
            }
        } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) {
            let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
                .unwrap_or_else(|| {
                    panic!("couldn't parse version range: {:?}", rest);
                });

            if max_version < min_version {
                panic!("Malformed GDB version range: max < min")
            }

            if actual_version >= min_version && actual_version <= max_version {
                if min_version == max_version {
                    return IgnoreDecision::Ignore {
                        reason: format!("ignored when the GDB version is {rest}"),
                    };
                } else {
                    return IgnoreDecision::Ignore {
                        reason: format!("ignored when the GDB version is between {rest}"),
                    };
                }
            }
        }
    }
    IgnoreDecision::Continue
}

fn ignore_lldb(config: &Config, line: &str) -> IgnoreDecision {
    if config.debugger != Some(Debugger::Lldb) {
        return IgnoreDecision::Continue;
    }

    if let Some(actual_version) = config.lldb_version {
        if let Some(rest) = line.strip_prefix("min-lldb-version:").map(str::trim) {
            let min_version = rest.parse().unwrap_or_else(|e| {
                panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e);
            });
            // Ignore if actual version is smaller the minimum required
            // version
            if actual_version < min_version {
                return IgnoreDecision::Ignore {
                    reason: format!("ignored when the LLDB version is {rest}"),
                };
            }
        }
    }
    IgnoreDecision::Continue
}

fn ignore_llvm(config: &Config, line: &str) -> IgnoreDecision {
    if let Some(needed_components) =
        config.parse_name_value_directive(line, "needs-llvm-components")
    {
        let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
        if let Some(missing_component) = needed_components
            .split_whitespace()
            .find(|needed_component| !components.contains(needed_component))
        {
            if env::var_os("COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS").is_some() {
                panic!(
                    "missing LLVM component {}, and COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS is set",
                    missing_component
                );
            }
            return IgnoreDecision::Ignore {
                reason: format!("ignored when the {missing_component} LLVM component is missing"),
            };
        }
    }
    if let Some(actual_version) = &config.llvm_version {
        // Note that these `min` versions will check for not just major versions.

        if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") {
            let min_version = extract_llvm_version(&version_string);
            // Ignore if actual version is smaller than the minimum required version.
            if *actual_version < min_version {
                return IgnoreDecision::Ignore {
                    reason: format!(
                        "ignored when the LLVM version {actual_version} is older than {min_version}"
                    ),
                };
            }
        } else if let Some(version_string) =
            config.parse_name_value_directive(line, "min-system-llvm-version")
        {
            let min_version = extract_llvm_version(&version_string);
            // Ignore if using system LLVM and actual version
            // is smaller the minimum required version
            if config.system_llvm && *actual_version < min_version {
                return IgnoreDecision::Ignore {
                    reason: format!(
                        "ignored when the system LLVM version {actual_version} is older than {min_version}"
                    ),
                };
            }
        } else if let Some(version_range) =
            config.parse_name_value_directive(line, "ignore-llvm-version")
        {
            // Syntax is: "ignore-llvm-version: <version1> [- <version2>]"
            let (v_min, v_max) =
                extract_version_range(&version_range, |s| Some(extract_llvm_version(s)))
                    .unwrap_or_else(|| {
                        panic!("couldn't parse version range: \"{version_range}\"");
                    });
            if v_max < v_min {
                panic!("malformed LLVM version range where {v_max} < {v_min}")
            }
            // Ignore if version lies inside of range.
            if *actual_version >= v_min && *actual_version <= v_max {
                if v_min == v_max {
                    return IgnoreDecision::Ignore {
                        reason: format!("ignored when the LLVM version is {actual_version}"),
                    };
                } else {
                    return IgnoreDecision::Ignore {
                        reason: format!(
                            "ignored when the LLVM version is between {v_min} and {v_max}"
                        ),
                    };
                }
            }
        }
    }
    IgnoreDecision::Continue
}

enum IgnoreDecision {
    Ignore { reason: String },
    Continue,
    Error { message: String },
}