Debian Codegraph @

src/codegen/sys/tests.rs

raw
1 use std::{
2 io::{self, prelude::*},
3 path::Path,
4 str::FromStr,
5 };
6
7 use log::info;
8
9 use crate::{
10 analysis::types::IsIncomplete,
11 codegen::general,
12 config::gobjects::GStatus,
13 env::Env,
14 file_saver::save_to_file,
15 library::{self, Bitfield, Enumeration, MAIN_NAMESPACE, Namespace, Type},
16 };
17
18 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
19 struct CType {
20 /// Name of type, as used in C.
21 name: String,
22 /// Expression describing when type is available (when defined only
23 /// conditionally).
24 cfg_condition: Option<String>,
25 }
26
27 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
28 struct CConstant {
29 /// Identifier in C.
30 name: String,
31 /// Stringified value.
32 value: String,
33 status: GStatus,
34 }
35
36 pub fn generate(env: &Env, crate_name: &str) {
37 let ctypes = prepare_ctypes(env);
38 let cconsts = prepare_cconsts(env);
39
40 if ctypes.is_empty() && cconsts.is_empty() {
41 return;
42 }
43
44 let tests = env.config.target_path.join("tests");
45
46 let manual_h = tests.join("manual.h");
47 if !manual_h.exists() {
48 save_to_file(&manual_h, env.config.make_backup, |w| {
49 generate_manual_h(env, &manual_h, w)
50 });
51 }
52
53 let layout_c = tests.join("layout.c");
54 save_to_file(&layout_c, env.config.make_backup, |w| {
55 generate_layout_c(env, &layout_c, w, &ctypes)
56 });
57
58 let constant_c = tests.join("constant.c");
59 save_to_file(&constant_c, env.config.make_backup, |w| {
60 generate_constant_c(env, &constant_c, w, &cconsts)
61 });
62
63 let abi_rs = tests.join("abi.rs");
64 save_to_file(&abi_rs, env.config.make_backup, |w| {
65 generate_abi_rs(env, &abi_rs, w, crate_name, &ctypes, &cconsts)
66 });
67 }
68
69 fn prepare_ctypes(env: &Env) -> Vec<CType> {
70 let ns = env.library.namespace(MAIN_NAMESPACE);
71 let mut types: Vec<CType> = ns
72 .types
73 .iter()
74 .filter_map(Option::as_ref)
75 .filter(|t| !t.is_incomplete(&env.library))
76 .filter_map(|t| match t {
77 Type::Record(library::Record {
78 disguised: false, ..
79 }) => prepare_ctype(env, ns, t),
80 Type::Alias(_)
81 | Type::Class(_)
82 | Type::Union(_)
83 | Type::Enumeration(_)
84 | Type::Bitfield(_)
85 | Type::Interface(_) => prepare_ctype(env, ns, t),
86 _ => None,
87 })
88 .collect();
89
90 types.sort();
91 types
92 }
93
94 fn prepare_ctype(env: &Env, ns: &Namespace, t: &Type) -> Option<CType> {
95 let full_name = format!("{}.{}", ns.name, t.get_name());
96 if env.type_status_sys(&full_name).ignored() {
97 return None;
98 }
99 let name = t.get_glib_name()?;
100
101 if is_name_made_up(name) {
102 return None;
103 }
104 let object = env.config.objects.get(&full_name);
105 Some(CType {
106 name: name.to_owned(),
107 cfg_condition: object.and_then(|obj| obj.cfg_condition.clone()),
108 })
109 }
110
111 fn prepare_cconsts(env: &Env) -> Vec<CConstant> {
112 let ns = env.library.namespace(MAIN_NAMESPACE);
113 let mut constants: Vec<CConstant> = ns
114 .constants
115 .iter()
116 .filter_map(|constant| {
117 let full_name = format!("{}.{}", ns.name, constant.name);
118 if env.type_status_sys(&full_name).ignored() {
119 return None;
120 }
121 let value = match constant {
122 c if c.c_type == "gboolean" && c.value == "true" => "1".to_owned(),
123 c if c.c_type == "gboolean" && c.value == "false" => "0".to_owned(),
124 c if c.c_type == "gdouble" => {
125 let n = f64::from_str(&c.value).expect("Could not parse gdouble value as f64");
126 format!("{n:.6}")
127 }
128 c if c.c_type == "gfloat" => {
129 let n = f32::from_str(&c.value).expect("Could not parse gfloat value as f32");
130 format!("{n:.6}")
131 }
132 c => c.value.clone(),
133 };
134 Some(CConstant {
135 name: constant.c_identifier.clone(),
136 value,
137 status: GStatus::Generate, // Assume generate because we skip ignored ones above
138 })
139 })
140 .collect();
141
142 for typ in &ns.types {
143 let typ = if let Some(typ) = typ {
144 typ
145 } else {
146 continue;
147 };
148 let full_name = format!("{}.{}", ns.name, typ.get_name());
149 if env.type_status_sys(&full_name).ignored() {
150 continue;
151 }
152 match typ {
153 Type::Bitfield(Bitfield { members, .. }) => {
154 for member in members {
155 // GLib assumes that bitflags are unsigned integers,
156 // see the GValue machinery around them for example
157 constants.push(CConstant {
158 name: format!("(guint) {}", member.c_identifier),
159 value: member
160 .value
161 .parse::<i32>()
162 .map(|i| (i as u32).to_string())
163 .unwrap_or_else(|_| member.value.clone()),
164 status: member.status,
165 });
166 }
167 }
168 Type::Enumeration(Enumeration { members, .. }) => {
169 for member in members {
170 // GLib assumes that enums are signed integers,
171 // see the GValue machinery around them for example
172 constants.push(CConstant {
173 name: format!("(gint) {}", member.c_identifier),
174 value: member.value.clone(),
175 status: member.status,
176 });
177 }
178 }
179 _ => {}
180 }
181 }
182
183 constants.sort_by(|a, b| {
184 fn strip_cast(x: &CConstant) -> &str {
185 if x.name.starts_with("(gint) ") {
186 &x.name[7..]
187 } else if x.name.starts_with("(guint) ") {
188 &x.name[8..]
189 } else {
190 x.name.as_str()
191 }
192 }
193
194 strip_cast(a).cmp(strip_cast(b))
195 });
196 constants
197 }
198
199 /// Checks if type name is unlikely to correspond to a real C type name.
200 fn is_name_made_up(name: &str) -> bool {
201 // Unnamed types are assigned name during parsing, those names contain an
202 // underscore.
203 name.contains('_') && !name.ends_with("_t")
204 }
205
206 fn generate_manual_h(env: &Env, path: &Path, w: &mut dyn Write) -> io::Result<()> {
207 info!("Generating file {path:?}");
208 writeln!(
209 w,
210 "// Feel free to edit this file, it won't be regenerated by gir generator unless removed."
211 )?;
212 writeln!(w)?;
213
214 let ns = env.library.namespace(MAIN_NAMESPACE);
215 for include in &ns.c_includes {
216 writeln!(w, "#include <{include}>")?;
217 }
218
219 Ok(())
220 }
221
222 #[allow(clippy::write_literal)]
223 fn generate_layout_c(
224 env: &Env,
225 path: &Path,
226 w: &mut dyn Write,
227 ctypes: &[CType],
228 ) -> io::Result<()> {
229 info!("Generating file {path:?}");
230 general::start_comments(w, &env.config)?;
231 writeln!(w)?;
232 writeln!(w, "#include \"manual.h\"")?;
233 writeln!(w, "#include <stdalign.h>")?;
234 writeln!(w, "#include <stdio.h>")?;
235 writeln!(w)?;
236 writeln!(w, "{}", r"int main() {")?;
237
238 for ctype in ctypes {
239 writeln!(
240 w,
241 " printf(\"%s;%zu;%zu\\n\", \"{ctype}\", sizeof({ctype}), alignof({ctype}));",
242 ctype = ctype.name
243 )?;
244 }
245
246 writeln!(w, " return 0;")?;
247 writeln!(w, "{}", r"}")
248 }
249
250 #[allow(clippy::write_literal)]
251 fn generate_constant_c(
252 env: &Env,
253 path: &Path,
254 w: &mut dyn Write,
255 cconsts: &[CConstant],
256 ) -> io::Result<()> {
257 info!("Generating file {path:?}");
258 general::start_comments(w, &env.config)?;
259 writeln!(w)?;
260 writeln!(w, "#include \"manual.h\"")?;
261 writeln!(w, "#include <stdio.h>")?;
262 writeln!(
263 w,
264 "{}",
265 r#"
266 #define PRINT_CONSTANT(CONSTANT_NAME) \
267 printf("%s;", #CONSTANT_NAME); \
268 printf(_Generic((CONSTANT_NAME), \
269 char *: "%s", \
270 const char *: "%s", \
271 char: "%c", \
272 signed char: "%hhd", \
273 unsigned char: "%hhu", \
274 short int: "%hd", \
275 unsigned short int: "%hu", \
276 int: "%d", \
277 unsigned int: "%u", \
278 long: "%ld", \
279 unsigned long: "%lu", \
280 long long: "%lld", \
281 unsigned long long: "%llu", \
282 float: "%.6f", \
283 double: "%.6f", \
284 long double: "%ld"), \
285 CONSTANT_NAME); \
286 printf("\n");
287 "#
288 )?;
289
290 writeln!(w, "{}", r"int main() {")?;
291
292 for cconst in cconsts {
293 if cconst.status.ignored() {
294 continue;
295 }
296 writeln!(w, " PRINT_CONSTANT({name});", name = cconst.name,)?;
297 }
298
299 writeln!(w, " return 0;")?;
300 writeln!(w, "{}", r"}")
301 }
302
303 #[allow(clippy::write_literal)]
304 fn generate_abi_rs(
305 env: &Env,
306 path: &Path,
307 w: &mut dyn Write,
308 crate_name: &str,
309 ctypes: &[CType],
310 cconsts: &[CConstant],
311 ) -> io::Result<()> {
312 let ns = env.library.namespace(MAIN_NAMESPACE);
313 let mut package_names = ns.package_names.join("\", \"");
314 if !package_names.is_empty() {
315 package_names = format!("\"{package_names}\"");
316 }
317
318 info!("Generating file {path:?}");
319 general::start_comments(w, &env.config)?;
320 writeln!(w)?;
321 writeln!(w, "#![cfg(unix)]")?;
322 writeln!(w)?;
323
324 if !ctypes.is_empty() {
325 writeln!(w, "use {crate_name}::*;")?;
326 writeln!(w, "use std::mem::{{align_of, size_of}};")?;
327 }
328
329 writeln!(w, "use std::env;")?;
330 writeln!(w, "use std::error::Error;")?;
331 writeln!(w, "use std::ffi::OsString;")?;
332 writeln!(w, "use std::path::Path;")?;
333 writeln!(w, "use std::process::{{Command, Stdio}};")?;
334 writeln!(w, "use std::str;")?;
335 writeln!(w, "use tempfile::Builder;")?;
336 writeln!(w)?;
337 writeln!(w, "static PACKAGES: &[&str] = &[{package_names}];")?;
338 writeln!(
339 w,
340 "{}",
341 r#"
342 #[derive(Clone, Debug)]
343 struct Compiler {
344 pub args: Vec<String>,
345 }
346
347 impl Compiler {
348 pub fn new() -> Result<Self, Box<dyn Error>> {
349 let mut args = get_var("CC", "cc")?;
350 args.push("-Wno-deprecated-declarations".to_owned());
351 // For _Generic
352 args.push("-std=c11".to_owned());
353 // For %z support in printf when using MinGW.
354 args.push("-D__USE_MINGW_ANSI_STDIO".to_owned());
355 args.extend(get_var("CFLAGS", "")?);
356 args.extend(get_var("CPPFLAGS", "")?);
357 args.extend(pkg_config_cflags(PACKAGES)?);
358 Ok(Self { args })
359 }
360
361 pub fn compile(&self, src: &Path, out: &Path) -> Result<(), Box<dyn Error>> {
362 let mut cmd = self.to_command();
363 cmd.arg(src);
364 cmd.arg("-o");
365 cmd.arg(out);
366 let status = cmd.spawn()?.wait()?;
367 if !status.success() {
368 return Err(format!("compilation command {cmd:?} failed, {status}").into());
369 }
370 Ok(())
371 }
372
373 fn to_command(&self) -> Command {
374 let mut cmd = Command::new(&self.args[0]);
375 cmd.args(&self.args[1..]);
376 cmd
377 }
378 }
379
380 fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {
381 match env::var(name) {
382 Ok(value) => Ok(shell_words::split(&value)?),
383 Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),
384 Err(err) => Err(format!("{name} {err}").into()),
385 }
386 }
387
388 fn pkg_config_cflags(packages: &[&str]) -> Result<Vec<String>, Box<dyn Error>> {
389 if packages.is_empty() {
390 return Ok(Vec::new());
391 }
392 let pkg_config = env::var_os("PKG_CONFIG")
393 .unwrap_or_else(|| OsString::from("pkg-config"));
394 let mut cmd = Command::new(pkg_config);
395 cmd.arg("--cflags");
396 cmd.args(packages);
397 cmd.stderr(Stdio::inherit());
398 let out = cmd.output()?;
399 if !out.status.success() {
400 let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
401 return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
402 }
403 let stdout = str::from_utf8(&out.stdout)?;
404 Ok(shell_words::split(stdout.trim())?)
405 }
406
407
408 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
409 struct Layout {
410 size: usize,
411 alignment: usize,
412 }
413
414 #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
415 struct Results {
416 /// Number of successfully completed tests.
417 passed: usize,
418 /// Total number of failed tests (including those that failed to compile).
419 failed: usize,
420 }
421
422 impl Results {
423 fn record_passed(&mut self) {
424 self.passed += 1;
425 }
426 fn record_failed(&mut self) {
427 self.failed += 1;
428 }
429 fn summary(&self) -> String {
430 format!("{} passed; {} failed", self.passed, self.failed)
431 }
432 fn expect_total_success(&self) {
433 if self.failed == 0 {
434 println!("OK: {}", self.summary());
435 } else {
436 panic!("FAILED: {}", self.summary());
437 };
438 }
439 }
440
441 #[test]
442 fn cross_validate_constants_with_c() {
443 let mut c_constants: Vec<(String, String)> = Vec::new();
444
445 for l in get_c_output("constant").unwrap().lines() {
446 let (name, value) = l.split_once(';').expect("Missing ';' separator");
447 c_constants.push((name.to_owned(), value.to_owned()));
448 }
449
450 let mut results = Results::default();
451
452 for ((rust_name, rust_value), (c_name, c_value)) in
453 RUST_CONSTANTS.iter().zip(c_constants.iter())
454 {
455 if rust_name != c_name {
456 results.record_failed();
457 eprintln!("Name mismatch:\nRust: {rust_name:?}\nC: {c_name:?}");
458 continue;
459 }
460
461 if rust_value != c_value {
462 results.record_failed();
463 eprintln!(
464 "Constant value mismatch for {rust_name}\nRust: {rust_value:?}\nC: {c_value:?}",
465 );
466 continue;
467 }
468
469 results.record_passed();
470 }
471
472 results.expect_total_success();
473 }
474
475 #[test]
476 fn cross_validate_layout_with_c() {
477 let mut c_layouts = Vec::new();
478
479 for l in get_c_output("layout").unwrap().lines() {
480 let (name, value) = l.split_once(';').expect("Missing first ';' separator");
481 let (size, alignment) = value.split_once(';').expect("Missing second ';' separator");
482 let size = size.parse().expect("Failed to parse size");
483 let alignment = alignment.parse().expect("Failed to parse alignment");
484 c_layouts.push((name.to_owned(), Layout { size, alignment }));
485 }
486
487 let mut results = Results::default();
488
489 for ((rust_name, rust_layout), (c_name, c_layout)) in
490 RUST_LAYOUTS.iter().zip(c_layouts.iter())
491 {
492 if rust_name != c_name {
493 results.record_failed();
494 eprintln!("Name mismatch:\nRust: {rust_name:?}\nC: {c_name:?}");
495 continue;
496 }
497
498 if rust_layout != c_layout {
499 results.record_failed();
500 eprintln!(
501 "Layout mismatch for {rust_name}\nRust: {rust_layout:?}\nC: {c_layout:?}",
502 );
503 continue;
504 }
505
506 results.record_passed();
507 }
508
509 results.expect_total_success();
510 }
511
512 fn get_c_output(name: &str) -> Result<String, Box<dyn Error>> {
513 let tmpdir = Builder::new().prefix("abi").tempdir()?;
514 let exe = tmpdir.path().join(name);
515 let c_file = Path::new("tests").join(name).with_extension("c");
516
517 let cc = Compiler::new().expect("configured compiler");
518 cc.compile(&c_file, &exe)?;
519
520 let mut cmd = Command::new(exe);
521 cmd.stderr(Stdio::inherit());
522 let out = cmd.output()?;
523 if !out.status.success() {
524 let (status, stdout) = (out.status, String::from_utf8_lossy(&out.stdout));
525 return Err(format!("command {cmd:?} failed, {status:?}\nstdout: {stdout}").into());
526 }
527
528 Ok(String::from_utf8(out.stdout)?)
529 }
530
531 const RUST_LAYOUTS: &[(&str, Layout)] = &["#
532 )?;
533 for ctype in ctypes {
534 general::cfg_condition(w, ctype.cfg_condition.as_ref(), false, 1)?;
535 writeln!(
536 w,
537 " (\"{ctype}\", Layout {{size: size_of::<{ctype}>(), alignment: align_of::<{ctype}>()}}),",
538 ctype = ctype.name
539 )?;
540 }
541 writeln!(
542 w,
543 "{}",
544 r#"];
545
546 const RUST_CONSTANTS: &[(&str, &str)] = &["#
547 )?;
548 for cconst in cconsts {
549 if cconst.status.ignored() {
550 continue;
551 }
552 writeln!(
553 w,
554 " (\"{name}\", \"{value}\"),",
555 name = cconst.name,
556 value = general::escape_string(&cconst.value)
557 )?;
558 }
559 writeln!(
560 w,
561 "{}",
562 r#"];
563
564 "#
565 )
566 }