Debian Codegraph @

debian/rust-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(__ZEROCOPY_INTERNAL_USE_ONLY_DEV_MODE)");
95 println!("cargo:rustc-check-cfg=cfg(coverage_nightly)");
96 println!("cargo:rustc-check-cfg=cfg(zerocopy_inline_always)");
97 println!("cargo:rustc-check-cfg=cfg(zerocopy_unstable_ptr)");
98 println!("cargo:rustc-check-cfg=cfg(zerocopy_unstable_linux)");
99 println!("cargo:rustc-check-cfg=cfg(no_fp_fmt_parse)");
100 }
101
102 for version_cfg in version_cfgs {
103 if rustc_version < version_cfg.version {
104 println!("cargo:rustc-cfg={}", version_cfg.cfg_name);
105 }
106 }
107 }
108
109 #[derive(Debug, Ord, PartialEq, PartialOrd, Eq)]
110 struct Version {
111 major: usize,
112 minor: usize,
113 patch: usize,
114 }
115
116 #[derive(Debug)]
117 struct VersionCfg {
118 version: Version,
119 cfg_name: String,
120 }
121
122 const ITER_FIRST_NEXT_EXPECT_MSG: &str = "unreachable: a string split cannot produce 0 items";
123
124 fn parse_version_cfgs_from_cargo_toml() -> Vec<VersionCfg> {
125 let cargo_toml = fs::read_to_string("Cargo.toml").expect("failed to read Cargo.toml");
126
127 // Expect a Cargo.toml with the following format:
128 //
129 // ...
130 //
131 // [package.metadata.build-rs]
132 // # Comments...
133 // zerocopy-panic-in-const-fn = "1.57.0"
134 //
135 // ...
136 //
137 // [...]
138 //
139 // In other words, the following sections, in order:
140 // - Arbitrary content
141 // - The literal header `[package.metadata.build-rs]`
142 // - Any number of:
143 // - Comments
144 // - Key/value pairs
145 // - A TOML table, indicating the end of the section we care about
146
147 const TABLE_HEADER: &str = "[package.metadata.build-rs]";
148
149 if !cargo_toml.contains(TABLE_HEADER) {
150 panic!("{}", format!("Cargo.toml does not contain `{}`", TABLE_HEADER));
151 }
152
153 // Now that we know there's at least one instance of `TABLE_HEADER`, we
154 // consume the iterator until we find the text following that first
155 // instance. This isn't terribly bullet-proof, but we also authored
156 // `Cargo.toml`, and we'd have to mess up pretty badly to accidentally put
157 // two copies of the same table header in that file.
158 let mut iter = cargo_toml.split(TABLE_HEADER);
159 let _prefix = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
160 let rest = iter.next().expect("unreachable: we already confirmed that there's a table header");
161
162 // Scan until we find the next table section, which should start with a `[`
163 // character at the beginning of a line.
164 let mut iter = rest.split("\n[");
165 let section = iter.next().expect("unreachable: a string split cannot produce 0 items");
166
167 section
168 .lines()
169 .filter_map(|line| {
170 // Parse lines of one of the following forms:
171 //
172 // # Comment
173 //
174 // name-of-key = "1.2.3" # Comment
175 //
176 // Comments on their own line are ignored, and comments after a
177 // key/value pair will be stripped before further processing.
178
179 // We don't need to handle the case where the `#` character isn't a
180 // comment (which can happen if it's inside a string) since we authored
181 // `Cargo.toml` and, in this section, we only put Rust version numbers
182 // in strings.
183 let before_comment = line.split('#').next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
184 let before_comment_without_whitespace = before_comment.trim_start();
185 if before_comment_without_whitespace.is_empty() {
186 return None;
187 }
188
189 // At this point, assuming Cargo.toml is correctly formatted according
190 // to the format expected by this function, we know that
191 // `before_comment_without_whitespace` is of the form:
192 //
193 // name-of-key = "1.2.3" # Comment
194 //
195 // ...with no leading whitespace, and where the trailing comment is
196 // optional.
197
198 let mut iter = before_comment_without_whitespace.split_whitespace();
199 let name = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
200 const EXPECT_MSG: &str =
201 "expected lines of the format `name-of-key = \"1.2.3\" # Comment`";
202 let equals_sign = iter.next().expect(EXPECT_MSG);
203 let value = iter.next().expect(EXPECT_MSG);
204
205 assert_eq!(equals_sign, "=", "{}", EXPECT_MSG);
206
207 // Replace dashes with underscores.
208 let name = name.replace('-', "_");
209
210 // Strip the quotation marks.
211 let value = value.trim_start_matches('"').trim_end_matches('"');
212
213 let mut iter = value.split('.');
214 let major = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
215 let minor = iter.next().expect(EXPECT_MSG);
216 let patch = iter.next().expect(EXPECT_MSG);
217
218 assert_eq!(iter.next(), None, "{}", EXPECT_MSG);
219
220 let major: usize = major.parse().expect(EXPECT_MSG);
221 let minor: usize = minor.parse().expect(EXPECT_MSG);
222 let patch: usize = patch.parse().expect(EXPECT_MSG);
223
224 Some(VersionCfg { version: Version { major, minor, patch }, cfg_name: name })
225 })
226 .collect()
227 }
228
229 fn rustc_version() -> Version {
230 let rustc_cmd_name = env::var_os("RUSTC").expect("could not get rustc command name");
231 let version =
232 Command::new(rustc_cmd_name).arg("--version").output().expect("could not invoke rustc");
233 if !version.status.success() {
234 panic!(
235 "rustc failed with status: {}\nrustc output: {}",
236 version.status,
237 String::from_utf8_lossy(version.stderr.as_slice())
238 );
239 }
240
241 const RUSTC_EXPECT_MSG: &str = "could not parse rustc version output";
242 let version = str::from_utf8(version.stdout.as_slice()).expect(RUSTC_EXPECT_MSG);
243 let version = version.trim_start_matches("rustc ");
244 // The version string is sometimes followed by other information such as the
245 // string `-nightly` or other build information. We don't care about any of
246 // that.
247 let version = version
248 .split(|c: char| c != '.' && !c.is_ascii_digit())
249 .next()
250 .expect(ITER_FIRST_NEXT_EXPECT_MSG);
251 let mut iter = version.split('.');
252 let major = iter.next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
253 let minor = iter.next().expect(RUSTC_EXPECT_MSG);
254 let patch = iter.next().expect(RUSTC_EXPECT_MSG);
255
256 let major: usize = major.parse().expect(RUSTC_EXPECT_MSG);
257 let minor: usize = minor.parse().expect(RUSTC_EXPECT_MSG);
258 let patch: usize = patch.parse().expect(RUSTC_EXPECT_MSG);
259
260 Version { major, minor, patch }
261 }