Debian Codegraph @

build.rs

raw symbols SCIP
1 use std::{collections::HashMap, error::Error, fs::File, io::Write, path::Path};
2
3 fn main() -> Result<(), Box<dyn Error>> {
4 let rustc_version = include_str!("rustc-version.txt").trim();
5 let target_features = include_str!("target-features.txt");
6 let target_cpus = include_str!("target-cpus.txt");
7 let out_dir = std::env::var_os("OUT_DIR").unwrap();
8
9 // Parse the generated features file
10 let mut lines = target_features.lines().peekable();
11 let mut features = Vec::new();
12 while lines.peek().is_some() {
13 let feature = lines
14 .next()
15 .unwrap()
16 .strip_prefix("feature =")
17 .unwrap()
18 .trim();
19 let arch = lines.next().unwrap().strip_prefix("arch =").unwrap().trim();
20 let implies = lines
21 .next()
22 .unwrap()
23 .strip_prefix("implies =")
24 .unwrap()
25 .trim()
26 .split(' ')
27 .filter(|s| !s.is_empty())
28 .collect::<Vec<_>>();
29 let description = lines
30 .next()
31 .unwrap()
32 .strip_prefix("description =")
33 .unwrap()
34 .trim();
35 let _ = lines.next();
36 features.push((feature, arch, description, implies));
37 }
38
39 // Parse the generated CPUs file
40 let mut lines = target_cpus.lines().peekable();
41 let mut cpus = Vec::new();
42 while lines.peek().is_some() {
43 let cpu = lines.next().unwrap().strip_prefix("cpu =").unwrap().trim();
44 let arch = lines.next().unwrap().strip_prefix("arch =").unwrap().trim();
45 let features = lines
46 .next()
47 .unwrap()
48 .strip_prefix("features =")
49 .unwrap()
50 .trim()
51 .split(' ')
52 .filter(|s| !s.is_empty())
53 .collect::<Vec<_>>();
54 let _ = lines.next();
55 cpus.push((cpu, arch, features));
56 }
57
58 // Write the generated docs
59 let mut rustc_docs = File::create(Path::new(&out_dir).join("generated.md"))?;
60 writeln!(rustc_docs, "Generated with {rustc_version}.")?;
61
62 // Write a module
63 let mut module = File::create(Path::new(&out_dir).join("generated.rs"))?;
64
65 // Generate the features array
66 writeln!(
67 module,
68 "const FEATURES: &[(crate::Architecture, &str, &str, &[Feature])] = &["
69 )?;
70 for (feature, arch, description, implies) in &features {
71 let implies = implies
72 .iter()
73 .map(|implied_feature| {
74 format!(
75 "Feature({})",
76 features
77 .iter()
78 .position(|(f, a, _, _)| implied_feature == f && arch == a)
79 .unwrap()
80 )
81 })
82 .collect::<Vec<_>>()
83 .join(", ");
84 writeln!(
85 module,
86 " (crate::Architecture::{arch}, \"{feature}\", \"{description}\", &[{implies}]),"
87 )?;
88 }
89 writeln!(module, "];")?;
90
91 // Generate the CPUs array
92 writeln!(
93 module,
94 "const CPUS: &[(crate::Architecture, &str, &[Feature])] = &["
95 )?;
96 for (cpu, arch, cpu_features) in &cpus {
97 let cpu_features = cpu_features
98 .iter()
99 .map(|feature| {
100 format!(
101 "Feature({})",
102 features
103 .iter()
104 .position(|(f, a, _, _)| feature == f && arch == a)
105 .unwrap()
106 )
107 })
108 .collect::<Vec<_>>()
109 .join(", ");
110 writeln!(
111 module,
112 " (crate::Architecture::{arch}, \"{cpu}\", &[{cpu_features}]),"
113 )?;
114 }
115 writeln!(module, "];")?;
116
117 let build_features = std::env::var("CARGO_CFG_TARGET_FEATURE")
118 .map(|x| x.split(',').map(ToString::to_string).collect())
119 .unwrap_or_else(|_| Vec::new());
120 let build_arch = match std::env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
121 "arm" => "Arm",
122 "aarch64" => "AArch64",
123 "bpf" => "Bpf",
124 "hexagon" => "Hexagon",
125 "mips" | "mips64" => "Mips",
126 "powerpc" | "powerpc64" => "PowerPC",
127 "riscv32" | "riscv64" => "RiscV",
128 "wasm32" | "wasm64" => "Wasm",
129 "x86" | "x86_64" => "X86",
130 _ => "Unsupported",
131 };
132 writeln!(module, "/// The target of the current build.")?;
133 writeln!(module, "#[allow(clippy::let_and_return)]")?;
134 writeln!(module, "pub const CURRENT_TARGET: Target = {{")?;
135 writeln!(module, " let arch = Architecture::{build_arch};")?;
136 writeln!(module, " let target = Target::new(arch);")?;
137 for feature in build_features {
138 writeln!(module, " let target = if let Ok(feature) = Feature::new(arch, \"{feature}\") {{ target.with_feature(feature) }} else {{ target }};")?;
139 }
140 writeln!(module, " target")?;
141 writeln!(module, "}};")?;
142
143 // Generate the features docs
144 let mut docs = File::create(Path::new(&out_dir).join("docs.rs"))?;
145 let mut by_arch = HashMap::<_, (Vec<_>, Vec<_>)>::new();
146 for (feature, arch, description, implies) in features {
147 by_arch
148 .entry(arch)
149 .or_default()
150 .0
151 .push((feature, description, implies));
152 }
153 for (cpu, arch, features) in cpus {
154 by_arch.entry(arch).or_default().1.push((cpu, features));
155 }
156 let mut by_arch = by_arch.drain().collect::<Vec<_>>();
157 by_arch.sort();
158 for (arch, (features, cpus)) in by_arch.drain(..) {
159 writeln!(docs, "/// {} documentation", arch.to_lowercase())?;
160 writeln!(docs, "///")?;
161 writeln!(docs, "/// ## Features")?;
162 writeln!(
163 docs,
164 "/// | Feature | Description | Also Enables<sup>†</sup> |"
165 )?;
166 writeln!(
167 docs,
168 "/// | ------- | ----------- | ------------------------ |"
169 )?;
170 for (feature, description, implies) in features {
171 write!(docs, "/// | `{feature}` | {description} | ")?;
172 for (i, feature) in implies.into_iter().enumerate() {
173 if i != 0 {
174 write!(docs, ", ")?;
175 }
176 write!(docs, "`{feature}`")?;
177 }
178 writeln!(docs, " |")?;
179 }
180 writeln!(docs, "///")?;
181 writeln!(docs, "/// <sup>†</sup> This is often empirical, rather than specified in any standard, i.e. all available CPUs with a particular feature also have another feature.")?;
182 writeln!(docs, "///")?;
183 writeln!(docs, "/// ## CPUs")?;
184 writeln!(docs, "/// | CPU | Enabled Features |")?;
185 writeln!(docs, "/// | --- | -------- |")?;
186 for (cpu, features) in cpus {
187 writeln!(
188 docs,
189 "/// | `{cpu}` | {} |",
190 features
191 .iter()
192 .map(|f| format!("`{f}`"))
193 .collect::<Vec<_>>()
194 .join(", ")
195 )?;
196 }
197 writeln!(docs, "pub mod {} {{}}", arch.to_lowercase())?;
198 }
199
200 // Rerun build if the source features changed
201 println!("cargo:rerun-if-changed=rustc-version.txt");
202 println!("cargo:rerun-if-changed=target-features.txt");
203 println!("cargo:rerun-if-changed=target-cpus.txt");
204 println!("cargo:rerun-if-changed=build.rs");
205 Ok(())
206 }