    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

    use proc_macro::*;
    use std::process::Command;
    use std::sync::Once;

    #[proc_macro_attribute]
    pub fn cargo_test(attr: TokenStream, item: TokenStream) -> TokenStream {
        // Ideally these options would be embedded in the test itself. However, I
        // find it very helpful to have the test clearly state whether or not it
        // is ignored. It would be nice to have some kind of runtime ignore
        // support (such as
        // https://internals.rust-lang.org/t/pre-rfc-skippable-tests/14611).
        //
        // Unfortunately a big drawback here is that if the environment changes
        // (such as the existence of the `git` CLI), this will not trigger a
        // rebuild and the test will still be ignored. In theory, something like
        // `tracked_env` or `tracked_path`
        // (https://github.com/rust-lang/rust/issues/99515) could help with this,
        // but they don't really handle the absence of files well.
        let mut ignore = false;
        let mut requires_reason = false;
        let mut explicit_reason = None;
        let mut implicit_reasons = Vec::new();
        macro_rules! set_ignore {
            ($predicate:expr, $($arg:tt)*) => {
                let p = $predicate;
                ignore |= p;
                if p {
                    implicit_reasons.push(std::fmt::format(format_args!($($arg)*)));
                }
            };
        }
        let is_not_nightly = !version().1;
        for rule in split_rules(attr) {
            match rule.as_str() {
                "build_std_real" => {
                    // Only run the "real" build-std tests on nightly and with an
                    // explicit opt-in (these generally only work on linux, and
                    // have some extra requirements, and are slow, and can pollute
                    // the environment since it downloads dependencies).
                    set_ignore!(is_not_nightly, "requires nightly");
                    set_ignore!(
                        option_env!("CARGO_RUN_BUILD_STD_TESTS").is_none(),
                        "CARGO_RUN_BUILD_STD_TESTS must be set"
                    );
                }
                "build_std_mock" => {
                    // Only run the "mock" build-std tests on nightly and disable
                    // for windows-gnu which is missing object files (see
                    // https://github.com/rust-lang/wg-cargo-std-aware/issues/46).
                    set_ignore!(is_not_nightly, "requires nightly");
                    set_ignore!(
                        cfg!(all(target_os = "windows", target_env = "gnu")),
                        "does not work on windows-gnu"
                    );
                }
                "container_test" => {
                    // These tests must be opt-in because they require docker.
                    set_ignore!(
                        option_env!("CARGO_CONTAINER_TESTS").is_none(),
                        "CARGO_CONTAINER_TESTS must be set"
                    );
                }
                "public_network_test" => {
                    // These tests must be opt-in because they touch the public
                    // network. The use of these should be **EXTREMELY RARE**, and
                    // should only touch things which would nearly certainly work
                    // in CI (like github.com).
                    set_ignore!(
                        option_env!("CARGO_PUBLIC_NETWORK_TESTS").is_none(),
                        "CARGO_PUBLIC_NETWORK_TESTS must be set"
                    );
                }
                "nightly" => {
                    requires_reason = true;
                    set_ignore!(is_not_nightly, "requires nightly");
                }
                s if s.starts_with("requires_") => {
                    let command = &s[9..];
                    set_ignore!(!has_command(command), "{command} not installed");
                }
                s if s.starts_with(">=1.") => {
                    requires_reason = true;
                    let min_minor = s[4..].parse().unwrap();
                    let minor = version().0;
                    set_ignore!(minor < min_minor, "requires rustc 1.{minor} or newer");
                }
                s if s.starts_with("reason=") => {
                    explicit_reason = Some(s[7..].parse().unwrap());
                }
                s if s.starts_with("ignore_windows=") => {
                    set_ignore!(cfg!(windows), "{}", &s[16..s.len() - 1]);
                }
                _ => panic!("unknown rule {:?}", rule),
            }
        }
        if requires_reason && explicit_reason.is_none() {
            panic!(
                "#[cargo_test] with a rule also requires a reason, \
                such as #[cargo_test(nightly, reason = \"needs -Z unstable-thing\")]"
            );
        }

        // Construct the appropriate attributes.
        let span = Span::call_site();
        let mut ret = TokenStream::new();
        let add_attr = |ret: &mut TokenStream, attr_name, attr_input| {
            ret.extend(Some(TokenTree::from(Punct::new('#', Spacing::Alone))));
            let attr = TokenTree::from(Ident::new(attr_name, span));
            let mut attr_stream: TokenStream = attr.into();
            if let Some(input) = attr_input {
                attr_stream.extend(input);
            }
            ret.extend(Some(TokenTree::from(Group::new(
                Delimiter::Bracket,
                attr_stream,
            ))));
        };
        add_attr(&mut ret, "test", None);
        if ignore {
            let reason = explicit_reason
                .or_else(|| {
                    (!implicit_reasons.is_empty())
                        .then(|| TokenTree::from(Literal::string(&implicit_reasons.join(", "))).into())
                })
                .map(|reason: TokenStream| {
                    let mut stream = TokenStream::new();
                    stream.extend(Some(TokenTree::from(Punct::new('=', Spacing::Alone))));
                    stream.extend(Some(reason));
                    stream
                });
            add_attr(&mut ret, "ignore", reason);
        }

        // Find where the function body starts, and add the boilerplate at the start.
        for token in item {
            let group = match token {
                TokenTree::Group(g) => {
                    if g.delimiter() == Delimiter::Brace {
                        g
                    } else {
                        ret.extend(Some(TokenTree::Group(g)));
                        continue;
                    }
                }
                other => {
                    ret.extend(Some(other));
                    continue;
                }
            };

            let mut new_body = to_token_stream(
                r#"let _test_guard = {
                    let tmp_dir = option_env!("CARGO_TARGET_TMPDIR");
                    cargo_test_support::paths::init_root(tmp_dir)
                };"#,
            );

            new_body.extend(group.stream());
            ret.extend(Some(TokenTree::from(Group::new(
                group.delimiter(),
                new_body,
            ))));
        }

        ret
    }

    fn split_rules(t: TokenStream) -> Vec<String> {
        let tts: Vec<_> = t.into_iter().collect();
        tts.split(|tt| match tt {
            TokenTree::Punct(p) => p.as_char() == ',',
            _ => false,
        })
        .filter(|parts| !parts.is_empty())
        .map(|parts| {
            parts
                .into_iter()
                .map(|part| part.to_string())
                .collect::<String>()
        })
        .collect()
    }

    fn to_token_stream(code: &str) -> TokenStream {
        code.parse().unwrap()
    }

    static mut VERSION: (u32, bool) = (0, false);

    fn version() -> &'static (u32, bool) {
        static INIT: Once = Once::new();
        INIT.call_once(|| {
            let output = Command::new("rustc")
                .arg("-V")
                .output()
                .expect("rustc should run");
            let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
            let vers = stdout.split_whitespace().skip(1).next().unwrap();
            let is_nightly = option_env!("CARGO_TEST_DISABLE_NIGHTLY").is_none()
                && (vers.contains("-nightly") || vers.contains("-dev"));
            let minor = vers.split('.').skip(1).next().unwrap().parse().unwrap();
            unsafe { VERSION = (minor, is_nightly) }
        });
        unsafe { &VERSION }
    }

    fn has_command(command: &str) -> bool {
        let output = match Command::new(command).arg("--version").output() {
            Ok(output) => output,
            Err(e) => {
                // * hg is not installed on GitHub macOS or certain constrained
                //   environments like Docker. Consider installing it if Cargo
                //   gains more hg support, but otherwise it isn't critical.
                // * lldb is not pre-installed on Ubuntu and Windows, so skip.
                if is_ci() && !["hg", "lldb"].contains(&command) {
                    panic!(
                        "expected command `{}` to be somewhere in PATH: {}",
                        command, e
                    );
                }
                return false;
            }
        };
        if !output.status.success() {
            // Debian specific patch, upstream wontfix:
            // qemu has a faulty vfork where it fails to fail if a command is not
            // found, with a unix_wait_status of 32512, or 0x7f00, 7f meaning
            // exit code 127. See https://github.com/rust-lang/rust/issues/90825
            use std::os::unix::process::ExitStatusExt;
            if output.status.into_raw() == 0x7f00 {
                return false;
            }
            panic!(
                "expected command `{}` to be runnable, got error {}:\n\
                stderr:{}\n\
                stdout:{}\n",
                command,
                output.status,
                String::from_utf8_lossy(&output.stderr),
                String::from_utf8_lossy(&output.stdout)
            );
        }
        true
    }

    /// Whether or not this running in a Continuous Integration environment.
    fn is_ci() -> bool {
        // Consider using `tracked_env` instead of option_env! when it is stabilized.
        // `tracked_env` will handle changes, but not require rebuilding the macro
        // itself like option_env does.
        option_env!("CI").is_some() || option_env!("TF_BUILD").is_some()
    }