rsconf 0.3.0

The missing cargo API. A sane autoconf w/ build.rs helpers for testing for system headers, libraries, and symbols
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
//! The `rsconf` crate contains `build.rs` helper utilities and funcitionality to assist with
//! managing complicated build scripts, interacting with the native/system headers and libraries,
//! exposing rust constants based off of system headers, and conditionally compiling rust code based
//! off the presence or absence of certain functionality in the system headers and libraries.
//!
//! This crate can be used standalone or in conjunction with the [`cc`
//! crate](https://docs.rs/cc/latest/cc/) when introspecting the build system's environment.
//!
//! In addition to facilitating easier ffi and other native system interop, `rsconf` also exposes a
//! strongly typed API for interacting with `cargo` at build-time and influencing its behavior,
//! including more user-friendly alternatives to the low-level `println!("cargo:xxx")` "api" used to
//! enable features, enable `#[cfg(...)]` conditional compilation blocks or define `cfg` values, and
//! more.

mod tempdir;
#[cfg(test)]
mod tests;

use sealed::CompilerAtomic;

use cc::Build;
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::io::prelude::*;
use std::path::PathBuf;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicI32, Ordering};
use tempdir::TempDir;

static FILE_COUNTER: AtomicI32 = AtomicI32::new(0);
type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// Exposes an interface for testing whether the target system supports a particular feature or
/// provides certain functionality. This is the bulk of the `rsconf` api.
pub struct Target {
    /// Whether or not we are compiling with `cl.exe` (and not `clang.exe`) under `xxx-pc-windows-msvc`.
    is_cl: bool,
    temp: TempDir,
    toolchain: Build,
    verbose: bool,
}

macro_rules! snippet {
    ($name:expr) => {
        include_str!(concat!("../snippets/", $name))
    };
}

/// An error encountered during the compliation stage.
///
/// This is currently not public because we only return it as [`BoxedError`].
#[derive(Debug)]
struct CompilationError {
    output: Output,
}

impl std::fmt::Display for CompilationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "Compilation error: {}",
            String::from_utf8_lossy(&self.output.stderr)
        ))
    }
}

impl std::error::Error for CompilationError {}

fn output_or_err(output: Output) -> Result<(String, String), BoxedError> {
    if output.status.success() {
        Ok((
            String::from_utf8(output.stdout)?,
            String::from_utf8(output.stderr)?,
        ))
    } else {
        Err(Box::new(CompilationError { output }))
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum BuildMode {
    Executable,
    ObjectFile,
}

/// Specifies how a dependency library is linked.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum LinkType {
    /// Cargo is instructed to link the library without specifying/overriding how linking is
    /// performed. If an environment variable `LIBNAME_STATIC` is present, the dependency will be
    /// statically linked. (This way, downstream consumers of the crate may influence how the
    /// dependency is linked without modifying the build script and/or features.)
    ///
    /// Cargo is instructed to automatically rerun the build script if an environment variable by
    /// this name exists; you do not have to call [`rebuild_if_env_changed()`] yourself.
    #[default]
    Default,
    /// Cargo will be instructed to explicitly dynamically link against the target library,
    /// overriding the default configuration specified by the configuration or the toolchain.
    Dynamic,
    /// Cargo will be instructed to explicitly statically link against the target library,
    /// overriding the default configuration specified by the configuration or the toolchain.
    Static,
}

impl LinkType {
    fn emit_link_line(&self, lib: &str) {
        match self {
            LinkType::Static => println!("cargo:rustc-link-lib=static={lib}"),
            LinkType::Dynamic => println!("cargo:rustc-link-lib=dylib={lib}"),
            LinkType::Default => {
                // We do not specify the build type unless the LIBNAME_STATIC environment variable
                // is defined (and not set to 0), in which was we emit a static linkage instruction.
                let name = format!("{}_STATIC", lib.to_ascii_uppercase());
                println!("cargo:rerun-if-env-changed={name}");
                match std::env::var(name).as_deref() {
                    Err(_) | Ok("0") => println!("cargo:rustc-link-lib={lib}"),
                    _ => LinkType::Static.emit_link_line(lib),
                }
            }
        }
    }
}

/// Instruct Cargo to link the target object against `library`.
pub fn link_library(library: &str, how: LinkType) {
    how.emit_link_line(library)
}

/// Instruct Cargo to link the target object against `libraries` in the order provided.
pub fn link_libraries(libraries: &[&str], how: LinkType) {
    for lib in libraries {
        how.emit_link_line(lib)
    }
}

/// Instruct Cargo to rerun the build script if the provided path changes.
///
/// Change detection is based off the modification time (mtime). If the path is to a directory, the
/// build script is re-run if any files under that directory are modified.
///
/// By default, Cargo reruns the build script if any file in the source tree is modified. To make it
/// ignore changes, specify a file. To make it ignore all changes, call this with `"build.rs"` as
/// the target.
pub fn rebuild_if_path_changed(path: &str) {
    println!("cargo:rerun-if-changed={path}");
}

/// Instruct Cargo to rerun the build script if any of the provided paths change.
///
/// See [`rebuild_if_path_changed()`] for more information.
pub fn rebuild_if_paths_changed(paths: &[&str]) {
    for path in paths {
        rebuild_if_path_changed(path)
    }
}

/// Instruct Cargo to rerun the build script if the named environment variable changes.
pub fn rebuild_if_env_changed(var: &str) {
    println!("cargo:rerun-if-env-changed={var}");
}

/// Instruct Cargo to rerun the build script if any of the named environment variables change.
pub fn rebuild_if_envs_changed(vars: &[&str]) {
    for var in vars {
        rebuild_if_env_changed(var);
    }
}

/// Emit a compile-time warning.
///
/// This is typically only shown for the current crate when building with `cargo build`, but
/// warnings for non-path dependencies can be shown by using `cargo build -vv`.
#[macro_export]
macro_rules! warn {
    ($msg:tt $(, $($arg:tt)*)?) => {{
        println!(concat!("cargo:warning=", $msg) $(, $($arg)*)?)
    }};
}

/// Enables a feature flag that compiles code annotated with `#[cfg(feature = "name")]`.
///
/// The feature does not have to be named in `Cargo.toml` to be used here or in your code, but any
/// features dynamically enabled via this script will not participate in dependency resolution.
///
/// As of rust 1.80, features enabled in `build.rs` but not declared in `Cargo.toml` might trigger
/// build-time warnings; use [`declare_feature()`] instead to avoid this warning.
pub fn enable_feature(name: &str) {
    declare_feature(name, true)
}

/// Informs the compiler of a `feature` with the name `name`, possibly enabled.
///
/// The feature does not have to be named in `Cargo.toml` to be used here or in your code, but any
/// features dynamically enabled via this script will not participate in dependency resolution.
pub fn declare_feature(name: &str, enabled: bool) {
    if name.chars().any(|c| c == '"') {
        panic!("Invalid feature name: {name}");
    }
    declare_cfg_values("feature", &[name]);
    if enabled {
        println!("cargo:rustc-cfg=feature=\"{name}\"");
    }
}

/// Informs the compiler of a `cfg` with the name `name`, possibly enabled.
///
/// Enables conditional compilation of code behind `#[cfg(name)]` or with `if cfg!(name)`
/// (without quotes around `name`).
///
/// As of rust 1.80, using `#[cfg(foo)]` when said feature is not enabled results in a
/// compile-time warning as rust tries to protect against inadvertent use of invalid/unknown
/// features. Unlike [`enable_cfg()`], this function informs `rustc` about the presence of a feature
/// called `name` even when it's not enabled, so that `#[cfg(foo)]` or `#[cfg(not(foo))] do not
/// cause warnings when the `foo` cfg is not enabled.
///
/// See also: [`declare_cfg_values()`].
pub fn declare_cfg(name: &str, enabled: bool) {
    if name.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') {
        panic!("Invalid cfg name {name}");
    }
    // Use #[cfg(version = "1.80.0")] when RFC 2523 finally lands
    if rustc_version()
        .map(|v| v.cmp(&(1, 80, 0)).is_ge())
        .unwrap_or(true)
    {
        println!("cargo:rustc-check-cfg=cfg({name})");
    }
    if enabled {
        println!("cargo:rustc-cfg={name}");
    }
}

/// Enables Cargo/rustc feature with the name `name`.
///
/// Allows conditional compilation of code behind `#[cfg(name)]` or with `if cfg!(name)` (without
/// quotes around `name`).
///
/// See [`set_cfg_value()`] to set a `(name, value)` tuple to enable conditional compilation of the
/// form `#[cfg(name = "value")]` for cases where `name` is not a boolean cfg but rather takes any
/// of several discrete values.
///
/// Note the different from `#[cfg(feature = "name")]`! The configuration is invisible to end users
/// of your code (i.e. `name` does not appear anywhere in `Cargo.toml`) and does not participate in
/// dependency resolution.
pub fn enable_cfg(name: &str) {
    declare_cfg(name, true);
}

// TODO: Add a builder method to encompass the functionality of declare_cfg()/set_cfg()/
// declare_cfg_values()/set_cfg_value(). Something like
//     add_cfg("name").with_values(["a", "b", "c"])
// followed by .enable() or .set_value("a")

/// Inform the compiler of a cfg with name `name` and all its known valid values.
///
/// Call this before calling [`set_cfg_value()`] to avoid compiler warnings about unrecognized cfg
/// values under rust 1.80+.
pub fn declare_cfg_values(name: &str, values: &[&str]) {
    if name.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') {
        panic!("Invalid cfg name {name}");
    }
    // Use #[cfg(version = "1.80.0")] when RFC 2523 finally lands
    if rustc_version()
        .map(|v| v.cmp(&(1, 80, 0)).is_ge())
        .unwrap_or(true)
    {
        let payload = values
            .iter()
            .inspect(|value| {
                if value.chars().any(|c| c == '"') {
                    panic!("Invalid value {value} for cfg {name}");
                }
            })
            .map(|v| format!("\"{v}\""))
            .collect::<Vec<_>>()
            .join(",");
        println!("cargo:rustc-check-cfg=cfg({name}, values({payload}))");
    }
}

/// Activates conditional compilation for code behind `#[cfg(name = "value")]` or with `if cfg!(name
/// = "value")`.
///
/// As with [`enable_cfg()`], this is entirely internal to your code: `name` should not appear in
/// `Cargo.toml` and this configuration does not participate in dependency resolution (which takes
/// place before your build script is called).
///
/// Call [`declare_cfg_values()`] beforehand to inform the compiler of all possible values for this
/// cfg or else rustc 1.80+ will issue a compile-time warning about unrecognized cfg values.
pub fn set_cfg_value(name: &str, value: &str) {
    if value.chars().any(|c| c == '"') {
        panic!("Invalid value {value} for cfg {name}");
    }
    println!("cargo:rustc-cfg={name}={value}\"");
}

/// Makes an environment variable available to your code at build time, letting you use the value as
/// a compile-time constant with `env!(NAME)`.
pub fn set_env_value(name: &str, value: &str) {
    if value.chars().any(|c| c == '"') {
        panic!("Invalid value {value} for env var {name}");
    }
    println!("cargo:rustc-env={name}={value}");
}

/// Add a path to the list of directories rust will search when attempting to find a library to link
/// against.
///
/// The path does not have to exist as it could be created by the build script at a later date or
/// could be targeting a different platform altogether.
pub fn add_library_search_path(dir: &str) {
    println!("cargo:rustc-link-search={dir}");
}

/// The output directory in which all output and intermediate artifacts should be placed.
///
/// This folder is inside the build directory for the package being built, and it is unique for the
/// package in question. Corresponds to the `OUT_DIR` environment variable set by Cargo when when
/// compiling `build.rs`.
pub fn out_dir() -> std::path::PathBuf {
    let path = std::env::var_os("OUT_DIR").expect("OUT_DIR is missing!");
    std::path::PathBuf::from(path)
}

/// The rustc/llvm triple of the target hardware/os/toolchain.
///
/// Differs from [`host_triple()`] when cross-compiling and corresponds to the `TARGET` environment
/// variable set by Cargo when when compiling `build.rs`.
pub fn target_triple() -> String {
    std::env::var("TARGET").expect("Missing or invalid TARGET env variable!")
}

/// The rustc/llvm triple of the host hardware/os/toolchain.
///
/// Differs from [`target_triple()`] when cross-compiling and corresponds to the `HOST` environment
/// variable set by Cargo when when compiling `build.rs`.
pub fn host_triple() -> String {
    std::env::var("HOST").expect("Missing or invalid HOST env variable!")
}

/// The optimization level specified for the build profile specified/being compiled.
///
/// Corresponds to the `OPT_LEVEL` environment variable set by Cargo when when compiling `build.rs`.
pub fn opt_level() -> String {
    std::env::var("OPT_LEVEL").expect("Missing or invalid OPT_LEVEL env variable!")
}

/// Whether or not debug assertions are enabled.
///
/// Corresponds to the `DEBUG` environment variable set by Cargo when when compiling `build.rs`.
pub fn debug() -> bool {
    match std::env::var("DEBUG").as_ref().map(|s| s.as_str()) {
        Ok("true") => true,
        _ => false,
    }
}

/// The selected build profile, e.g. `release`, `debug`, or a custom profile as defined in
/// `Cargo.toml`.
///
/// Corresponds to the `DEBUG` environment variable set by Cargo when when compiling `build.rs`.
pub fn profile() -> String {
    std::env::var("PROFILE").expect("Missing or invalid PROFILE env variable!")
}

/// The path to the `rustc` compiler being used.
///
/// Corresponds to the `RUSTC` environment variable set by Cargo when compiling `build.rs`.
pub fn rustc() -> PathBuf {
    let rustc = std::env::var_os("RUSTC").expect("Missing RUSTC environment variable!");
    PathBuf::from(rustc)
}

/// The path to the `rustdoc` compiler being used.
///
/// Corresponds to the `RUSTDOC` environment variable set by Cargo when compiling `build.rs`.
pub fn rustdoc() -> PathBuf {
    let rustdoc = std::env::var_os("RUSTDOC").expect("Missing RUSTDOC environment variable!");
    PathBuf::from(rustdoc)
}

/// The `rustc` wrapper configured with the `RUSTC_WRAPPER` environment variable, if any.
///
/// Note that this may be a fully qualified path or an executable in `PATH`.
pub fn rustc_wrapper() -> Option<PathBuf> {
    std::env::var_os("RUSTC_WRAPPER").map(PathBuf::from)
}

/// The `rustc` wrapper used for the workspace, if any.
///
/// Note that this may be a fully qualified path or an executable in `PATH`.
pub fn rustc_workspace_wrapper() -> Option<PathBuf> {
    std::env::var_os("RUSTC_WORKSPACE_WRAPPER").map(PathBuf::from)
}

/// The path to the linker `cargo` has been configured to use for the current target, if any.
///
/// Corresponds to the `RUSTC_LINKER` environment variable set by Cargo when compiling `build.rs`.
pub fn rustc_linker() -> Option<PathBuf> {
    std::env::var_os("RUSTC_LINKER").map(PathBuf::from)
}

/// All the extra flags `rustc` will ultimately be invoked with.
///
/// Corresponds to the `CARGO_ENCODED_RUSTFLAGS` environment variable set by Cargo when compiling
/// `build.rs` on newer toolchain versions, and `RUSTFLAGS` for older ones, making a best-effort
/// attempt at parsing any un-encoded quotes in `RUSTFLAGS` to account for the difference.
pub fn rustflags() -> Vec<String> {
    if let Ok(flags) = std::env::var("CARGO_ENCODED_RUSTFLAGS") {
        // Flags can be specified in a myriad of different ways, CARGO_ENCODED_RUSTFLAGS has them
        // normalized into KEY=VALUE notation separated by the ASCII record separator (0x1F).
        flags.split('\x1f').map(From::from).collect()
    } else if let Ok(flags) = std::env::var("RUSTFLAGS") {
        shell_split(&flags)
    } else {
        Vec::new()
    }
}

/// Splits a string on spaces, respecting single and double quotes.
/// Not perfect, but good enough.
fn shell_split(s: &str) -> Vec<String> {
    let mut args = Vec::new();
    let mut current = String::new();
    let mut in_single = false;
    let mut in_double = false;
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        match c {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            ' ' if !in_single && !in_double => {
                if !current.is_empty() {
                    args.push(current.clone());
                    current.clear();
                }
            }
            // Basic escape character support
            '\\' if !in_single => {
                if let Some(&next) = chars.peek() {
                    current.push(next);
                    chars.next();
                }
            }
            _ => current.push(c),
        }
    }
    if !current.is_empty() {
        args.push(current);
    }
    args
}

/// The specified degree of build parallelism, defaulting to the host's thread count.
///
/// Obtain the value corresponding to the `NUM_JOBS` environment variable set by Cargo when
/// compiling `build.rs`.
pub fn num_jobs() -> Option<usize> {
    std::env::var("NUM_JOBS")
        .ok()
        .map(|n| n.parse::<usize>().expect(&format!("Invalid NUM_JOBS: {n}")))
}

impl Target {
    const NONE: &'static [&'static str] = &[];
    #[inline(always)]
    #[allow(non_snake_case)]
    fn NULL_CB(_: &str, _: &str) {}

    /// Create a new rsconf instance using the default [`cc::Build`] toolchain for the current
    /// compilation target.
    ///
    /// Use [`Target::new_from()`] to use a configured [`cc::Build`] instance instead.
    pub fn new() -> std::io::Result<Target> {
        let toolchain = cc::Build::new();
        Target::new_from(toolchain)
    }

    /// Create a new rsconf instance from the configured [`cc::Build`] instance `toolchain`.
    ///
    /// All tests inherit their base configuration from `toolchain`, so make sure it is configured
    /// with the appropriate header and library search paths as needed.
    pub fn new_from(mut toolchain: cc::Build) -> std::io::Result<Target> {
        let temp = if let Some(out_dir) = std::env::var_os("OUT_DIR") {
            TempDir::new_in(out_dir)?
        } else {
            // Configure Build's OUT_DIR if not set (e.g. for testing)
            let temp = TempDir::new()?;
            toolchain.out_dir(&temp);
            temp
        };

        let is_cl = cfg!(windows) && toolchain.get_compiler().is_like_msvc();

        Ok(Self {
            is_cl,
            temp,
            toolchain,
            verbose: false,
        })
    }

    /// Enables or disables verbose mode.
    ///
    /// In verbose mode, output of rsconf calls to the compiler are displayed to stdout and stderr.
    /// It is not enabled by default.
    ///
    /// Note that `cargo` suppresses all `build.rs` output in case of successful execution by
    /// default; intentionally fail the build (e.g. add a `panic!()` call) or compile with `cargo
    /// build -vv` to see verbose output.
    pub fn set_verbose(&mut self, verbose: bool) {
        self.verbose = verbose;
    }

    fn new_temp<S: AsRef<str>>(&self, stub: S, ext: &str) -> PathBuf {
        let file_num = FILE_COUNTER.fetch_add(1, Ordering::Release);
        let stub = stub.as_ref();
        let mut path = self.temp.to_owned();
        path.push(format!("{stub}-test-{file_num}{ext}"));
        path
    }

    fn build<S: AsRef<str>, C>(
        &self,
        stub: &str,
        mode: BuildMode,
        code: &str,
        libraries: &[S],
        callback: C,
    ) -> Result<PathBuf, BoxedError>
    where
        C: FnOnce(&str, &str),
    {
        let stub = fs_sanitize(stub);

        let in_path = self.new_temp(&stub, ".c");
        std::fs::File::create(&in_path)?.write_all(code.as_bytes())?;
        let exe_ext = if cfg!(unix) { ".out" } else { ".exe" };
        let obj_ext = if cfg!(unix) { ".o" } else { ".obj" };
        let out_path = match mode {
            BuildMode::Executable => self.new_temp(&stub, exe_ext),
            BuildMode::ObjectFile => self.new_temp(&stub, obj_ext),
        };
        let mut cmd = self.toolchain.try_get_compiler()?.to_command();
        cmd.current_dir(&self.temp);

        let exe = mode == BuildMode::Executable;
        let link = exe || !libraries.is_empty();
        let mut cmd = if cfg!(unix) || !self.is_cl {
            cmd.args([in_path.as_os_str(), OsStr::new("-o"), out_path.as_os_str()]);
            if !link {
                cmd.arg("-c");
            } else if !libraries.is_empty() {
                for library in libraries {
                    cmd.arg(format!("-l{}", library.as_ref()));
                }
            }
            cmd
        } else {
            cmd.arg(in_path);
            let mut output = OsString::from(if exe { "/Fe:" } else { "/Fo:" });
            output.push(&out_path);
            cmd.arg(output);
            if !link {
                cmd.arg("/c");
            } else if !libraries.is_empty() {
                cmd.arg("/link");
                for library in libraries {
                    let mut library = Cow::from(library.as_ref());
                    if !library.contains('.') {
                        let owned = library + ".lib";
                        library = owned;
                    }
                    cmd.arg(library.as_ref());
                }
            }
            cmd
        };

        if self.verbose {
            eprintln!("{:?}", cmd);
            eprintln!("{}", code);
        }
        let output = cmd.output()?;

        // We want to output text in verbose mode but writing directly to stdout doesn't get
        // intercepted by the cargo test harness. In test mode, we use the slower `println!()`/
        // `eprintln!()` macros together w/ from_utf8_lossy() to suppress unnecessary output when
        // we're not investigating the details with `cargo test -- --nocapture`, but we use the
        // faster approach when we're being used in an actual build script.
        #[cfg(test)]
        if self.verbose {
            println!("{}", String::from_utf8_lossy(&output.stdout));
            eprintln!("{}", String::from_utf8_lossy(&output.stderr));
        }
        #[cfg(not(test))]
        if self.verbose {
            std::io::stdout().lock().write_all(&output.stdout).ok();
            std::io::stderr().lock().write_all(&output.stderr).ok();
        }
        // Handle custom `CompilationError` output if we failed to compile.
        let output = output_or_err(output)?;
        callback(&output.0, &output.1);

        // Return the path to the resulting exe
        assert!(out_path.exists());
        Ok(out_path)
    }

    /// Checks whether a definition for type `name` exists without pulling in any headers.
    ///
    /// This operation does not link the output; only the header file is inspected.
    pub fn has_type(&self, name: &str) -> bool {
        let snippet = format!(snippet!("has_type.c"), "", name);
        self.build(
            name,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Checks whether a definition for type `name` exists in the supplied header or headers.
    ///
    /// The `headers` are included in the order they are provided for testing. See
    /// [`has_type()`](Self::has_type) for more info.
    pub fn has_type_in(&self, name: &str, headers: &[&str]) -> bool {
        let stub = format!("{}_multi", headers.first().unwrap_or(&"has_type_in"));
        let snippet = format!(snippet!("has_type.c"), to_includes(headers), name);
        self.build(
            &stub,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Checks whether or not the the requested `symbol` is exported by libc/by default (without
    /// linking against any additional libraries).
    ///
    /// See [`has_symbol_in()`](Self::has_symbol_in) to link against one or more libraries and test.
    ///
    /// This only checks for symbols exported by the C abi (so mangled names are required) and does
    /// not check for compile-time definitions provided by header files.
    ///
    /// See [`has_type()`](Self::has_type) to check for compile-time definitions. This
    /// function will return false if `library` could not be found or could not be linked; see
    /// [`has_library()`](Self::has_library) to test if `library` can be linked separately.
    pub fn has_symbol(&self, symbol: &str) -> bool {
        let snippet = format!(snippet!("has_symbol.c"), symbol);
        let libs: &'static [&'static str] = &[];
        self.build(symbol, BuildMode::Executable, &snippet, libs, Self::NULL_CB)
            .is_ok()
    }

    /// Like [`has_symbol()`] but links against a library or any number of `libraries`.
    ///
    /// You might need to supply multiple libraries if `symbol` is in a library that has its own
    /// transitive dependencies that must also be linked for compilation to succeed. Note that
    /// libraries are linked in the order they are provided.
    ///
    /// [`has_symbol()`]: Self::has_symbol()
    pub fn has_symbol_in(&self, symbol: &str, libraries: &[&str]) -> bool {
        let snippet = format!(snippet!("has_symbol.c"), symbol);
        self.build(
            symbol,
            BuildMode::Executable,
            &snippet,
            libraries,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Checks for the presence of all the named symbols in the libraries provided.
    ///
    /// Libraries are linked in the order provided. See [`has_symbol()`] and [`has_symbol_in()`] for
    /// more information.
    ///
    /// [`has_symbol()`]: Self::has_symbol()
    /// [`has_symbol_in()`]: Self::has_symbol_in()
    pub fn has_symbols_in(&self, symbols: &[&str], libraries: &[&str]) -> bool {
        symbols
            .iter()
            .copied()
            .all(|symbol| self.has_symbol_in(symbol, libraries))
    }

    /// Tests whether or not it was possible to link against `library`.
    ///
    /// If it is not possible to link against `library` without also linking against its transitive
    /// dependencies, use [`has_libraries()`](Self::has_libraries) to link against multiple
    /// libraries (in the order provided).
    ///
    /// You should normally pass the name of the library without any prefixes or suffixes. If a
    /// suffix is provided, it will not be removed.
    ///
    /// You may pass a full path to the library (again minus the extension) instead of just the
    /// library name in order to try linking against a library not in the library search path.
    /// Alternatively, configure the [`cc::Build`] instance with the search paths as needed before
    /// passing it to [`Target::new()`].
    ///
    /// Under Windows, if `library` does not have an extension it will be suffixed with `.lib` prior
    /// to testing linking. (This way it works under under both `cl.exe` and `clang.exe`.)
    pub fn has_library(&self, library: &str) -> bool {
        let snippet = snippet!("empty.c");
        self.build(
            library,
            BuildMode::ObjectFile,
            snippet,
            &[library],
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Tests whether or not it was possible to link against all of `libraries`.
    ///
    /// See [`has_library()`](Self::has_library()) for more information.
    ///
    /// The libraries will be linked in the order they are provided in when testing, which may
    /// influence the outcome.
    pub fn has_libraries(&self, libraries: &[&str]) -> bool {
        let stub = libraries.first().copied().unwrap_or("has_libraries");
        let snippet = snippet!("empty.c");
        self.build(
            stub,
            BuildMode::ObjectFile,
            snippet,
            libraries,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Returns the first library from those provided that can be successfully linked.
    ///
    /// Returns a reference to the first library name that was passed in that was ultimately found
    /// and linked successfully on the target system or `None` otherwise. See
    /// [`has_library()`](Self::has_library()) for more information.
    pub fn find_first_library<'a>(&self, libraries: &'a [&str]) -> Option<&'a str> {
        for lib in libraries {
            if self.has_library(lib) {
                return Some(*lib);
            }
        }
        None
    }

    /// Returns the first library from those provided that can be successfully linked and contains
    /// all named `symbols`.
    ///
    /// Returns a reference to the first library name that was passed in that was ultimately found
    /// on the target system and contains all the symbol names provided, or `None` if no such
    /// library was found. See [`has_library()`](Self::has_library()) and [`has_symbol()`] for more
    /// information.
    ///
    /// [`has_symbol()`]: Self::has_symbol()
    pub fn find_first_library_with<'a>(
        &self,
        libraries: &'a [&str],
        symbols: &[&str],
    ) -> Option<&'a str> {
        for lib in libraries {
            if !self.has_library(lib) {
                continue;
            }
            if self.has_symbols_in(symbols, &[lib]) {
                return Some(lib);
            }
        }
        None
    }

    /// Checks whether the [`cc::Build`] passed to [`Target::new()`] as configured can pull in the
    /// named `header` file.
    ///
    /// If including `header` requires pulling in additional headers before it to compile, use
    /// [`has_headers()`](Self::has_headers) instead to include multiple headers in the order
    /// they're specified.
    pub fn has_header(&self, header: &str) -> bool {
        let snippet = format!(snippet!("has_header.c"), to_include(header));
        self.build(
            header,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Checks whether the [`cc::Build`] passed to [`Target::new()`] as configured can pull in the
    /// named `headers` in the order they're provided.
    pub fn has_headers(&self, headers: &[&str]) -> bool {
        let stub = headers.first().copied().unwrap_or("has_headers");
        let snippet = format!(snippet!("has_header.c"), to_includes(headers));
        self.build(
            stub,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// A convenience function that links against `library` if it is found and linkable.
    ///
    /// This is internally a call to [`has_library()`](Self::has_library()) followed by a
    /// conditional call to [`link_library()`].
    pub fn try_link_library(&self, library: &str, how: LinkType) -> bool {
        if self.has_library(library) {
            link_library(library, how);
            return true;
        }
        false
    }

    /// A convenience function that links against `libraries` only if they are all found and
    /// linkable.
    ///
    /// This is internally a call to [`has_libraries()`](Self::has_libraries()) followed by a
    /// conditional call to [`link_libraries()`].
    pub fn try_link_libraries(&self, libraries: &[&str], how: LinkType) -> bool {
        if self.has_libraries(libraries) {
            link_libraries(libraries, how);
            return true;
        }
        false
    }

    /// Evaluates whether or not `define` is an extant preprocessor definition.
    ///
    /// This is the C equivalent of `#ifdef xxxx` and does not check if there is a value associated
    /// with the definition. (You can use [`r#if()`](Self::if()) to test if a define has a particular
    /// value.)
    pub fn ifdef(&self, define: &str, headers: &[&str]) -> bool {
        let snippet = format!(snippet!("ifdef.c"), to_includes(headers), define);
        self.build(
            define,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Evaluates whether or not `condition` evaluates to true at the C preprocessor time.
    ///
    /// This can be used with `condition` set to `defined(FOO)` to perform the equivalent of
    /// [`ifdef()`](Self::ifdef) or it can be used to check for specific values e.g. with
    /// `condition` set to something like `FOO != 0`.
    pub fn r#if(&self, condition: &str, headers: &[&str]) -> bool {
        let snippet = format!(snippet!("if.c"), to_includes(headers), condition);
        self.build(
            condition,
            BuildMode::ObjectFile,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )
        .is_ok()
    }

    /// Attempts to retrieve the definition of `ident` as an `i32` value.
    ///
    /// Returns `Ok` in case `ident` was defined, has a concrete value, is a compile-time constant
    /// (i.e. does not need to be linked to retrieve the value), and is a valid `i32` value.
    ///
    /// # Cross-compliation note:
    ///
    /// The `get_xxx_value()` methods do not currently support cross-compilation scenarios as they
    /// require being able to run a binary compiled for the target platform.
    pub fn get_i32_value(&self, ident: &str, headers: &[&str]) -> Result<i32, BoxedError> {
        let snippet = format!(snippet!("get_i32_value.c"), to_includes(headers), ident);
        let exe = self.build(
            ident,
            BuildMode::Executable,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )?;

        let output = Command::new(exe).output().map_err(|err| {
            format!(
                "Failed to run the test executable: {err}!\n{}",
                "Note that get_i32_value() does not support cross-compilation!"
            )
        })?;
        Ok(std::str::from_utf8(&output.stdout)?.parse()?)
    }

    /// Attempts to retrieve the definition of `ident` as a `u32` value.
    ///
    /// Returns `Ok` in case `ident` was defined, has a concrete value, is a compile-time constant
    /// (i.e. does not need to be linked to retrieve the value), and is a valid `u32` value.
    ///
    /// # Cross-compliation note:
    ///
    /// The `get_xxx_value()` methods do not currently support cross-compilation scenarios as they
    /// require being able to run a binary compiled for the target platform.
    pub fn get_u32_value(&self, ident: &str, headers: &[&str]) -> Result<u32, BoxedError> {
        let snippet = format!(snippet!("get_u32_value.c"), to_includes(headers), ident);
        let exe = self.build(
            ident,
            BuildMode::Executable,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )?;

        let output = Command::new(exe).output().map_err(|err| {
            format!(
                "Failed to run the test executable: {err}!\n{}",
                "Note that get_u32_value() does not support cross-compilation!"
            )
        })?;
        Ok(std::str::from_utf8(&output.stdout)?.parse()?)
    }

    /// Attempts to retrieve the definition of `ident` as an `i64` value.
    ///
    /// Returns `Ok` in case `ident` was defined, has a concrete value, is a compile-time constant
    /// (i.e. does not need to be linked to retrieve the value), and is a valid `i64` value.
    ///
    /// # Cross-compliation note:
    ///
    /// The `get_xxx_value()` methods do not currently support cross-compilation scenarios as they
    /// require being able to run a binary compiled for the target platform.
    pub fn get_i64_value(&self, ident: &str, headers: &[&str]) -> Result<i64, BoxedError> {
        let snippet = format!(snippet!("get_i64_value.c"), to_includes(headers), ident);
        let exe = self.build(
            ident,
            BuildMode::Executable,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )?;

        let output = Command::new(exe).output().map_err(|err| {
            format!(
                "Failed to run the test executable: {err}!\n{}",
                "Note that get_i64_value() does not support cross-compilation!"
            )
        })?;
        Ok(std::str::from_utf8(&output.stdout)?.parse()?)
    }

    /// Attempts to retrieve the definition of `ident` as a `u64` value.
    ///
    /// Returns `Ok` in case `ident` was defined, has a concrete value, is a compile-time constant
    /// (i.e. does not need to be linked to retrieve the value), and is a valid `u64` value.
    ///
    /// # Cross-compliation note:
    ///
    /// The `get_xxx_value()` methods do not currently support cross-compilation scenarios as they
    /// require being able to run a binary compiled for the target platform.
    pub fn get_u64_value(&self, ident: &str, headers: &[&str]) -> Result<u64, BoxedError> {
        let snippet = format!(snippet!("get_u64_value.c"), to_includes(headers), ident);
        let exe = self.build(
            ident,
            BuildMode::Executable,
            &snippet,
            Self::NONE,
            Self::NULL_CB,
        )?;

        let output = Command::new(exe).output().map_err(|err| {
            format!(
                "Failed to run the test executable: {err}!\n{}",
                "Note that get_u64_value() does not support cross-compilation!"
            )
        })?;
        Ok(std::str::from_utf8(&output.stdout)?.parse()?)
    }

    /// Retrieve the definition of a C preprocessor macro or define.
    ///
    /// For "function macros" like `max(x, y)`, make sure to supply parentheses and pass in
    /// placeholders for the parameters (like the `x` and `y` in the example); they will be returned
    /// as-is in the expanded output.
    pub fn get_macro_value(
        &self,
        ident: &str,
        headers: &[&str],
    ) -> Result<Option<String>, BoxedError> {
        // We use `ident` twice: to check if it's defined then to get its value
        // For "function macros", the first should be without parentheses!
        let bare_name = if let Some(idx) = ident.find('(') {
            std::str::from_utf8(&ident.as_bytes()[..idx]).unwrap()
        } else {
            ident
        };
        let snippet = format!(
            snippet!("get_macro_value.c"),
            to_includes(headers),
            bare_name,
            ident
        );
        let mut result = None;
        let callback = |stdout: &str, stderr: &str| {
            let buffer = if self.is_cl { stdout } else { stderr };
            if let Some(start) = buffer.find("EXFIL:::").map(|i| i + "EXFIL:::".len()) {
                let start = std::str::from_utf8(&buffer.as_bytes()[start..]).unwrap();
                let end = start
                    .find(":::EXFIL")
                    .expect("Did not find terminating :::EXFIL sequence!");
                result = Some(
                    std::str::from_utf8(&start.as_bytes()[..end])
                        .unwrap()
                        .to_string(),
                );
            }
        };
        self.build(ident, BuildMode::ObjectFile, &snippet, Self::NONE, callback)
            .map_err(|err| {
                format!(
                    "Test compilation failure. Is ident `{}` valid?\n{}",
                    bare_name, err
                )
            })?;
        Ok(result)
    }

    /// Retrieve the definition of a C preprocessor macro or define, recursively in case it is
    /// defined in terms of another `#define`.
    ///
    /// For "function macros" like `max(x, y)`, make sure to pass in placeholders for the parameters
    /// (they will be returned as-is in the expanded output).
    pub fn get_macro_value_recursive(
        &self,
        ident: &str,
        headers: &[&str],
    ) -> Result<Option<String>, BoxedError> {
        let mut result = self.get_macro_value(ident, headers)?;
        while result.is_some() {
            // We shouldn't bubble up recursive errors because a macro can expand to a value that
            // isn't a valid macro name (such as an expression wrapped in parentheses).
            match self.get_macro_value(result.as_ref().unwrap(), headers) {
                Ok(Some(r)) => result = Some(r),
                _ => break,
            };
        }
        Ok(result)
    }
}

// Implementations of CARGO_CFG_TARGET_XXX that provide parsed values
impl Target {
    /// Whether or not `CARGO_CFG_TARGET_UNIX` environment variable is defined by Cargo when
    /// compiling `build.rs`.
    pub fn is_unix() -> bool {
        std::env::var_os("CARGO_CFG_UNIX").is_some()
    }

    /// Whether or not `CARGO_CFG_TARGET_WINDOWS` environment variable is defined by Cargo when
    /// compiling `build.rs`.
    pub fn is_windows() -> bool {
        std::env::var_os("CARGO_CFG_WINDOWS").is_some()
    }

    /// Compiler features supported by the target's CPU.
    ///
    /// The values in the `CARGO_CFG_TARGET_FEATURE` environment variable defined by Cargo when
    /// compiling `build.rs`.
    pub fn cpu_features() -> Vec<String> {
        let features = std::env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new());
        features.split(',').map(From::from).collect()
    }

    /// The values in the `CARGO_CFG_TARGET_FAMILY` environment variable defined by Cargo when
    /// compiling `build.rs`.
    pub fn family() -> Vec<String> {
        let families =
            std::env::var("CARGO_CFG_TARGET_FAMILY").expect("CARGO_CFG_TARGET_FAMILY not found!");

        if families.contains(',') {
            families.split(',').map(From::from).collect()
        } else {
            vec![families]
        }
    }

    /// The value of the `CARGO_CFG_TARGET_OS` environment variable set by Cargo when compiling
    /// `build.rs`.
    pub fn os() -> String {
        std::env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS not found!")
    }

    /// The value of the `CARGO_CFG_TARGET_ARCH` environment variable set by Cargo when compiling
    /// `build.rs`.
    pub fn arch() -> String {
        std::env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH not found!")
    }

    /// The value of the `CARGO_CFG_TARGET_VENDOR` environment variable set by Cargo when compiling
    /// `build.rs`.
    pub fn vendor() -> String {
        std::env::var("CARGO_CFG_TARGET_VENDOR").expect("CARGO_CFG_TARGET_VENDOR not found!")
    }

    /// The value of the `CARGO_CFG_TARGET_ENV` environment variable set by Cargo when compiling
    /// `build.rs`.
    pub fn env() -> String {
        std::env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV not found!")
    }

    /// The value of the `CARGO_CFG_TARGET_ABI` environment variable set by Cargo when compiling
    /// `build.rs`.
    pub fn abi() -> String {
        std::env::var("CARGO_CFG_TARGET_ABI").expect("CARGO_CFG_TARGET_ABI not found!")
    }

    /// The rustc/llvm triple of the target hardware/os/toolchain.
    ///
    /// An alias for [`rsconf::target_triple()`](crate::target_triple). Differs from
    /// [`host_triple()`] when cross-compiling and corresponds to the `TARGET` environment variable
    /// set by Cargo when when compiling `build.rs`.
    #[inline(always)]
    pub fn triple() -> String {
        crate::target_triple()
    }

    /// The width of a pointer in bits, e.g. `32` on x86 systems and `64` on x86_64 or aarch64
    /// systems when targeting the native architecture.
    ///
    /// The value of the `CARGO_CFG_TARGET_POINTER_WIDTH` environment variable set by Cargo when
    /// compiling `build.rs`.
    pub fn pointer_width() -> usize {
        std::env::var("CARGO_CFG_TARGET_POINTER_WIDTH")
            .expect("CARGO_CFG_TARGET_POINTER_WIDTH not found!")
            .parse()
            .expect("Invalid CARGO_CFG_TARGET_POINTER_WIDTH!")
    }

    /// Whether the target is a [little Endian](Endian::Little) or [big Endian](Endian::Big)
    /// architecture.
    ///
    /// The value of the `CARGO_CFG_TARGET_POINTER_ENDIAN` environment variable set by Cargo when
    /// compiling `build.rs`.
    pub fn endian() -> Endian {
        match std::env::var("CARGO_CFG_TARGET_ENDIAN")
            .expect("CARGO_CFG_TARGET_ENDIAN not found!")
            .as_str()
        {
            "little" => Endian::Little,
            "big" => Endian::Big,
            other => panic!("Unexpected CARGO_CFG_TARGET_ENDIAN value {other}"),
        }
    }
}

/// Interprets whether or not a primitive type [ui][8,16,32,64,128,size] is covered by the atomic
/// environment variable in question.
fn parse_atomic<T>(var: &'static str) -> bool {
    let value = std::env::var(var).unwrap_or_default();
    let mut atomics = value.split(',');

    // Cheaper than converting the size into a string at runtime
    let tname = std::any::type_name::<T>();
    if tname.ends_with("size") {
        atomics.find(|&x| x == "ptr").is_some()
    } else {
        let num = tname.strip_prefix(['u', 'i']).unwrap();
        atomics.find(|&x| x == num).is_some()
    }
}

impl Target {
    /// Determines whether or not the target has atomic support for reads and writes of this type.
    ///
    /// Implemented for the primitive signed/unsigned integer types, e.g. `Target::has_atomic::<u64>()`.
    pub fn has_atomic<T: CompilerAtomic>() -> bool {
        T::has_atomic()
    }

    /// Indicates whether an `AtomicX` has the same alignment as the equivalent `X` integer type.
    ///
    /// Implemented for the primitive signed/unsigned integer types, e.g. `Target::has_atomic_equal_alignment::<usize>()`.
    ///
    /// Not available on the stable toolchain. See tracking [issue #93822](https://github.com/rust-lang/rust/issues/93822).
    #[cfg(feature = "nightly")]
    pub fn has_atomic_equal_alignment<T: CompilerAtomic>() -> bool {
        T::has_atomic_equal_alignment()
    }

    /// Indicates whether a target has atomic load/store support for the provided signed/unsigned integer type.
    ///
    /// Implemented for the primitive signed/unsigned integer types, e.g. `Target::has_atomic_load_store::<i32>()`.
    ///
    /// Not available on the stable toolchain. See tracking [issue #94039](https://github.com/rust-lang/rust/issues/94039).
    #[cfg(feature = "nightly")]
    pub fn has_atomic_load_store<T: CompilerAtomic>() -> bool {
        T::has_atomic_load_store()
    }
}

mod sealed {
    use super::parse_atomic;

    pub trait CompilerAtomic: Sized {
        fn has_atomic() -> bool {
            parse_atomic::<Self>("CARGO_CFG_TARGET_HAS_ATOMIC")
        }

        #[cfg(feature = "nightly")]
        fn has_atomic_equal_alignment() -> bool {
            parse_atomic::<Self>("CARGO_CFG_TARGET_HAS_ATOMIC_EQUAL_ALIGNMENT")
        }

        #[cfg(feature = "nightly")]
        fn has_atomic_load_store() -> bool {
            parse_atomic::<Self>("CARGO_CFG_TARGET_HAS_ATOMIC_LOAD_STORE")
        }
    }
}

impl CompilerAtomic for u8 {}
impl CompilerAtomic for u16 {}
impl CompilerAtomic for u32 {}
impl CompilerAtomic for u64 {}
impl CompilerAtomic for u128 {}
impl CompilerAtomic for usize {}

impl CompilerAtomic for i8 {}
impl CompilerAtomic for i16 {}
impl CompilerAtomic for i32 {}
impl CompilerAtomic for i64 {}
impl CompilerAtomic for i128 {}
impl CompilerAtomic for isize {}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Endian {
    Little,
    Big,
}

impl Endian {
    /// Whether or not the value is [`Endian::Little`]
    pub fn is_little(&self) -> bool {
        matches!(self, Self::Little)
    }

    /// Whether or not the value is [`Endian::Big`]
    pub fn is_big(&self) -> bool {
        matches!(self, Self::Big)
    }
}

impl From<cc::Build> for Target {
    fn from(build: cc::Build) -> Self {
        Self::new_from(build).unwrap()
    }
}

/// Sanitizes a string for use in a file name
fn fs_sanitize(s: &str) -> Cow<'_, str> {
    if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
        return Cow::Borrowed(s);
    }

    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if !c.is_ascii_alphanumeric() {
            out.push('_');
        } else {
            out.push(c);
        }
    }
    Cow::Owned(out)
}

/// Convert header filename `header` to a `#include <..>` statement.
fn to_include(header: &str) -> String {
    format!("#include <{}>", header)
}

/// Convert one or more header filenames `headers` to `#include <..>` statements.
fn to_includes(headers: &[&str]) -> String {
    let mut vec = Vec::with_capacity(headers.len());
    vec.extend(headers.iter().copied().map(to_include));
    vec.join("\n")
}

/// Returns the `(Major, Minor, Patch)` version of the in-use `rustc` compiler.
///
/// Returns `None` in case of unexpected output format or in the event of runtime invariants
/// being violated (i.e. non-executable RUSTC_WRAPPER, non-UTF-8 output, etc).
fn rustc_version() -> Option<(u8, u8, u8)> {
    use std::env;
    use std::sync::OnceLock;

    static RUSTC_VERSION: OnceLock<Option<(u8, u8, u8)>> = OnceLock::new();

    *RUSTC_VERSION.get_or_init(|| -> Option<(u8, u8, u8)> {
        let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
        let mut cmd = match env::var_os("RUSTC_WRAPPER").filter(|w| !w.is_empty()) {
            Some(wrapper) => {
                let mut cmd = Command::new(wrapper);
                cmd.arg(rustc);
                cmd
            }
            None => Command::new(rustc),
        };
        let cmd = cmd.arg("--version");

        let Ok(output) = cmd.output() else {
            warn!("Failed to execute rustc!");
            return None;
        };
        let Ok(parts) = std::str::from_utf8(&output.stdout) else {
            warn!("Failed to parse `rustc --version` output as UTF-8!");
            return None;
        };
        let mut parts = parts
            .strip_prefix("rustc ")
            // 1.80.0 or 1.80.0-nightly
            .and_then(|output| output.split([' ', '-']).next())?
            .split('.')
            .map_while(|v| v.parse::<u8>().ok());

        Some((parts.next()?, parts.next()?, parts.next()?))
    })
}

#[test]
fn rustc_version_test() {
    assert!(matches!(rustc_version(), Some((_major, _minor, _patch))));
}