Debian Codegraph @

.cargo/vendor/zerocopy/build.rs

raw
1 // Copyright 2024 The Fuchsia Authors
2 //
3 // Licensed under the 2-Clause BSD License <LICENSE-BSD or
4 // https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
5 // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
6 // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
7 // This file may not be copied, modified, or distributed except according to
8 // those terms.
9
10 // Sometimes we want to use lints which were added after our MSRV.
11 // `unknown_lints` is `warn` by default and we deny warnings in CI, so without
12 // this attribute, any unknown lint would cause a CI failure when testing with
13 // our MSRV.
14 #![allow(unknown_lints)]
15 #![deny(renamed_and_removed_lints)]
16 #![deny(
17 anonymous_parameters,
18 deprecated_in_future,
19 late_bound_lifetime_arguments,
20 missing_copy_implementations,
21 missing_debug_implementations,
22 path_statements,
23 patterns_in_fns_without_body,
24 rust_2018_idioms,
25 trivial_numeric_casts,
26 unreachable_pub,
27 unsafe_op_in_unsafe_fn,
28 unused_extern_crates,
29 variant_size_differences
30 )]
31 #![deny(
32 clippy::all,
33 clippy::alloc_instead_of_core,
34 clippy::arithmetic_side_effects,
35 clippy::as_underscore,
36 clippy::assertions_on_result_states,
37 clippy::as_conversions,
38 clippy::correctness,
39 clippy::dbg_macro,
40 clippy::decimal_literal_representation,
41 clippy::get_unwrap,
42 clippy::indexing_slicing,
43 clippy::missing_inline_in_public_items,
44 clippy::missing_safety_doc,
45 clippy::obfuscated_if_else,
46 clippy::perf,
47 clippy::print_stdout,
48 clippy::style,
49 clippy::suspicious,
50 clippy::todo,
51 clippy::undocumented_unsafe_blocks,
52 clippy::unimplemented,
53 clippy::unnested_or_patterns,
54 clippy::unwrap_used,
55 clippy::use_debug
56 )]
57
58 use std::{env, fs, process::Command, str};
59
60 fn main() {
61 // Avoid unnecessary re-building.
62 println!("cargo:rerun-if-changed=build.rs");
63 // This is necessary because changes to the list of detected Rust toolchain
64 // versions will affect what `--cfg`s this script emits. Without this,
65 // changes to that list have no effect on the build without running `cargo
66 // clean` or similar.
67 println!("cargo:rerun-if-changed=Cargo.toml");
68
69 let version_cfgs = parse_version_cfgs_from_cargo_toml();
70 let rustc_version = rustc_version();
71
72 if rustc_version >= (Version { major: 1, minor: 77, patch: 0 }) {
73 for version_cfg in &version_cfgs {
74 // This tells the `unexpected_cfgs` lint to expect to see all of
75 // these `cfg`s. The `cargo::` syntax was only added in 1.77, so we
76 // don't emit these on earlier toolchain versions.
77 println!("cargo:rustc-check-cfg=cfg({})", version_cfg.cfg_name);
78
79 // This tells the `unexpected_cfgs` lint to expect to see `cfg`s of
80 // the form `rust = "1.2.3"`. These aren't real `cfg`s, but we use
81 // them in `cfg_attr(doc_cfg, doc(cfg(rust = "1.2.3")))` on items
82 // that are version-gated so that the rendered Rustdoc shows which
83 // Rust toolchain versions those items are available on.
84 let Version { major, minor, patch } = version_cfg.version;
85 println!("cargo:rustc-check-cfg=cfg(rust, values(\"{}.{}.{}\"))", major, minor, patch);
86 }
87 // FIXME(https://github.com/rust-lang/rust/issues/124816): Remove these
88 // once they're no longer needed.
89 println!("cargo:rustc-check-cfg=cfg(doc_cfg)");
90 println!("cargo:rustc-check-cfg=cfg(kani)");
91 println!(
92 "cargo:rustc-check-cfg=cfg(__ZEROCOPY_INTERNAL_USE_ONLY_NIGHTLY_FEATURES_IN_TESTS)"
93 );
94 println!("cargo:rustc-check-cfg=cfg(coverage_nightly)");
95 }
96
97 for version_cfg in version_cfgs {
98 if rustc_version >= version_cfg.version {
99 println!("cargo:rustc-cfg={}", version_cfg.cfg_name);
100 }
101 }
102 }
103
104 #[derive(Debug, Ord, PartialEq, PartialOrd, Eq)]
105 struct Version {
106 major: usize,
107 minor: usize,
108 patch: usize,
109 }
110
111 #[derive(Debug)]
112 struct VersionCfg {
113 version: Version,
114 cfg_name: String,
115 }
116
117 const ITER_FIRST_NEXT_EXPECT_MSG: &str = "unreachable: a string split cannot produce 0 items";
118
119 fn parse_version_cfgs_from_cargo_toml() -> Vec<VersionCfg> {
120 let cargo_toml = fs::read_to_string("Cargo.toml").expect("failed to read Cargo.toml");
121
122 // Expect a Cargo.toml with the following format:
123 //
124 // ...
125 //
126 // [package.metadata.build-rs]
127 // # Comments...
128 // zerocopy-panic-in-const-fn = "1.57.0"
129 //
130 // ...
131 //
132 // [...]
133 //
134 // In other words, the following sections, in order:
135 // - Arbitrary content
136 // - The literal header `[package.metadata.build-rs]`
137 // - Any number of:
138 // - Comments
139 // - Key/value pairs
140 // - A TOML table, indicating the end of the section we care about
141
142 const TABLE_HEADER: &str = "[package.metadata.build-rs]";
143
144 if !cargo_toml.contains(TABLE_HEADER) {
145 panic!("{}", format!("Cargo.toml does not contain `{}`", TABLE_HEADER));
146 }
147
148 // Now that we know there's at least one instance of `TABLE_HEADER`, we
149 // consume the iterator until we find the text following that first
150 // instance. This isn't terribly bullet-proof, but we also authored
151 // `Cargo.toml`, and we'd have to mess up pretty badly to accidentally put
152 // two copies of the same table header in that file.
153 let mut iter = cargo_toml.split(TABLE_HEADER);
154 let _prefix = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
155 let rest = iter.next().expect("unreachable: we already confirmed that there's a table header");
156
157 // Scan until we find the next table section, which should start with a `[`
158 // character at the beginning of a line.
159 let mut iter = rest.split("\n[");
160 let section = iter.next().expect("unreachable: a string split cannot produce 0 items");
161
162 section
163 .lines()
164 .filter_map(|line| {
165 // Parse lines of one of the following forms:
166 //
167 // # Comment
168 //
169 // name-of-key = "1.2.3" # Comment
170 //
171 // Comments on their own line are ignored, and comments after a
172 // key/value pair will be stripped before further processing.
173
174 // We don't need to handle the case where the `#` character isn't a
175 // comment (which can happen if it's inside a string) since we authored
176 // `Cargo.toml` and, in this section, we only put Rust version numbers
177 // in strings.
178 let before_comment = line.split('#').next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
179 let before_comment_without_whitespace = before_comment.trim_start();
180 if before_comment_without_whitespace.is_empty() {
181 return None;
182 }
183
184 // At this point, assuming Cargo.toml is correctly formatted according
185 // to the format expected by this function, we know that
186 // `before_comment_without_whitespace` is of the form:
187 //
188 // name-of-key = "1.2.3" # Comment
189 //
190 // ...with no leading whitespace, and where the trailing comment is
191 // optional.
192
193 let mut iter = before_comment_without_whitespace.split_whitespace();
194 let name = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
195 const EXPECT_MSG: &str =
196 "expected lines of the format `name-of-key = \"1.2.3\" # Comment`";
197 let equals_sign = iter.next().expect(EXPECT_MSG);
198 let value = iter.next().expect(EXPECT_MSG);
199
200 assert_eq!(equals_sign, "=", "{}", EXPECT_MSG);
201
202 // Replace dashes with underscores.
203 let name = name.replace('-', "_");
204
205 // Strip the quotation marks.
206 let value = value.trim_start_matches('"').trim_end_matches('"');
207
208 let mut iter = value.split('.');
209 let major = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
210 let minor = iter.next().expect(EXPECT_MSG);
211 let patch = iter.next().expect(EXPECT_MSG);
212
213 assert_eq!(iter.next(), None, "{}", EXPECT_MSG);
214
215 let major: usize = major.parse().expect(EXPECT_MSG);
216 let minor: usize = minor.parse().expect(EXPECT_MSG);
217 let patch: usize = patch.parse().expect(EXPECT_MSG);
218
219 Some(VersionCfg { version: Version { major, minor, patch }, cfg_name: name })
220 })
221 .collect()
222 }
223
224 fn rustc_version() -> Version {
225 let rustc_cmd_name = env::var_os("RUSTC").expect("could not get rustc command name");
226 let version =
227 Command::new(rustc_cmd_name).arg("--version").output().expect("could not invoke rustc");
228 if !version.status.success() {
229 panic!(
230 "rustc failed with status: {}\nrustc output: {}",
231 version.status,
232 String::from_utf8_lossy(version.stderr.as_slice())
233 );
234 }
235
236 const RUSTC_EXPECT_MSG: &str = "could not parse rustc version output";
237 let version = str::from_utf8(version.stdout.as_slice()).expect(RUSTC_EXPECT_MSG);
238 let version = version.trim_start_matches("rustc ");
239 // The version string is sometimes followed by other information such as the
240 // string `-nightly` or other build information. We don't care about any of
241 // that.
242 let version = version
243 .split(|c: char| c != '.' && !c.is_ascii_digit())
244 .next()
245 .expect(ITER_FIRST_NEXT_EXPECT_MSG);
246 let mut iter = version.split('.');
247 let major = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
248 let minor = iter.next().expect(RUSTC_EXPECT_MSG);
249 let patch = iter.next().expect(RUSTC_EXPECT_MSG);
250
251 let major: usize = major.parse().expect(RUSTC_EXPECT_MSG);
252 let minor: usize = minor.parse().expect(RUSTC_EXPECT_MSG);
253 let patch: usize = patch.parse().expect(RUSTC_EXPECT_MSG);
254
255 Version { major, minor, patch }
256 }