Skip to content

ctest: test ctest-next in ctest-test #4558

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions ctest-next/src/ast/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub struct Fn {
#[expect(unused)]
pub(crate) abi: Abi,
pub(crate) ident: BoxStr,
pub(crate) link_name: Option<BoxStr>,
#[expect(unused)]
pub(crate) parameters: Vec<Parameter>,
#[expect(unused)]
Expand All @@ -20,4 +21,9 @@ impl Fn {
pub fn ident(&self) -> &str {
&self.ident
}

/// Return the name of the function to be linked C side with.
pub fn link_name(&self) -> Option<&str> {
self.link_name.as_deref()
}
}
6 changes: 6 additions & 0 deletions ctest-next/src/ast/static_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub struct Static {
#[expect(unused)]
pub(crate) abi: Abi,
pub(crate) ident: BoxStr,
pub(crate) link_name: Option<BoxStr>,
pub(crate) ty: syn::Type,
}

Expand All @@ -18,4 +19,9 @@ impl Static {
pub fn ident(&self) -> &str {
&self.ident
}

/// Return the name of the function to be linked C side with.
pub fn link_name(&self) -> Option<&str> {
self.link_name.as_deref()
}
}
30 changes: 29 additions & 1 deletion ctest-next/src/ffi_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::ops::Deref;
use syn::punctuated::Punctuated;
use syn::visit::Visit;

use crate::{Abi, Const, Field, Fn, Parameter, Static, Struct, Type, Union};
use crate::{Abi, BoxStr, Const, Field, Fn, Parameter, Static, Struct, Type, Union};

/// Represents a collected set of top-level Rust items relevant to FFI generation or analysis.
///
Expand Down Expand Up @@ -95,6 +95,30 @@ fn collect_fields(fields: &Punctuated<syn::Field, syn::Token![,]>) -> Vec<Field>
.collect()
}

fn extract_single_link_name(attrs: &[syn::Attribute]) -> Option<BoxStr> {
let mut link_name_iter = attrs
.iter()
.filter(|attr| attr.path().is_ident("link_name"));

let link_name = link_name_iter.next().and_then(|attr| match &attr.meta {
syn::Meta::NameValue(nv) => {
if let syn::Expr::Lit(expr_lit) = &nv.value {
if let syn::Lit::Str(lit_str) = &expr_lit.lit {
return Some(lit_str.value().into_boxed_str());
}
}
None
}
_ => None,
});

if let Some(attr) = link_name_iter.next() {
panic!("multiple `#[link_name = ...]` attributes found: {attr:?}");
}

link_name
}

fn visit_foreign_item_fn(table: &mut FfiItems, i: &syn::ForeignItemFn, abi: &Abi) {
let public = is_visible(&i.vis);
let abi = abi.clone();
Expand Down Expand Up @@ -122,11 +146,13 @@ fn visit_foreign_item_fn(table: &mut FfiItems, i: &syn::ForeignItemFn, abi: &Abi
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, ty) => Some(ty.deref().clone()),
};
let link_name = extract_single_link_name(&i.attrs);

table.foreign_functions.push(Fn {
public,
abi,
ident,
link_name,
parameters,
return_type,
});
Expand All @@ -137,11 +163,13 @@ fn visit_foreign_item_static(table: &mut FfiItems, i: &syn::ForeignItemStatic, a
let abi = abi.clone();
let ident = i.ident.to_string().into_boxed_str();
let ty = i.ty.deref().clone();
let link_name = extract_single_link_name(&i.attrs);

table.foreign_statics.push(Static {
public,
abi,
ident,
link_name,
ty,
});
}
Expand Down
7 changes: 4 additions & 3 deletions ctest-next/templates/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
mod generated_tests {
#![allow(non_snake_case)]
#![deny(improper_ctypes_definitions)]
use std::ffi::CStr;
use std::ffi::{CStr, c_char};
use std::fmt::{Debug, LowerHex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[expect(unused_imports)]
use std::{mem, ptr, slice};

use super::*;
Expand Down Expand Up @@ -62,7 +63,7 @@ mod generated_tests {

// SAFETY: FFI call returns a valid C string.
let c_val = unsafe {
let c_ptr: *const c_char = unsafe { ctest_const_cstr__{{ const_cstr.id }}() };
let c_ptr: *const c_char = ctest_const_cstr__{{ const_cstr.id }}();
CStr::from_ptr(c_ptr)
};

Expand All @@ -89,7 +90,7 @@ mod generated_tests {
};

let c_bytes = unsafe {
let c_ptr: *const T = unsafe { ctest_const__{{ constant.id }}() };
let c_ptr: *const T = ctest_const__{{ constant.id }}();
slice::from_raw_parts(c_ptr.cast::<u8>(), size_of::<T>())
};

Expand Down
5 changes: 3 additions & 2 deletions ctest-next/tests/input/hierarchy.out.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
mod generated_tests {
#![allow(non_snake_case)]
#![deny(improper_ctypes_definitions)]
use std::ffi::CStr;
use std::ffi::{CStr, c_char};
use std::fmt::{Debug, LowerHex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[expect(unused_imports)]
use std::{mem, ptr, slice};

use super::*;
Expand Down Expand Up @@ -58,7 +59,7 @@ mod generated_tests {
};

let c_bytes = unsafe {
let c_ptr: *const T = unsafe { ctest_const__ON() };
let c_ptr: *const T = ctest_const__ON();
slice::from_raw_parts(c_ptr.cast::<u8>(), size_of::<T>())
};

Expand Down
3 changes: 2 additions & 1 deletion ctest-next/tests/input/macro.out.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
mod generated_tests {
#![allow(non_snake_case)]
#![deny(improper_ctypes_definitions)]
use std::ffi::CStr;
use std::ffi::{CStr, c_char};
use std::fmt::{Debug, LowerHex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[expect(unused_imports)]
use std::{mem, ptr, slice};

use super::*;
Expand Down
7 changes: 4 additions & 3 deletions ctest-next/tests/input/simple.out.with-renames.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
mod generated_tests {
#![allow(non_snake_case)]
#![deny(improper_ctypes_definitions)]
use std::ffi::CStr;
use std::ffi::{CStr, c_char};
use std::fmt::{Debug, LowerHex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[expect(unused_imports)]
use std::{mem, ptr, slice};

use super::*;
Expand Down Expand Up @@ -57,7 +58,7 @@ mod generated_tests {

// SAFETY: FFI call returns a valid C string.
let c_val = unsafe {
let c_ptr: *const c_char = unsafe { ctest_const_cstr__A() };
let c_ptr: *const c_char = ctest_const_cstr__A();
CStr::from_ptr(c_ptr)
};

Expand All @@ -80,7 +81,7 @@ mod generated_tests {

// SAFETY: FFI call returns a valid C string.
let c_val = unsafe {
let c_ptr: *const c_char = unsafe { ctest_const_cstr__B() };
let c_ptr: *const c_char = ctest_const_cstr__B();
CStr::from_ptr(c_ptr)
};

Expand Down
5 changes: 3 additions & 2 deletions ctest-next/tests/input/simple.out.with-skips.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
mod generated_tests {
#![allow(non_snake_case)]
#![deny(improper_ctypes_definitions)]
use std::ffi::CStr;
use std::ffi::{CStr, c_char};
use std::fmt::{Debug, LowerHex};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[expect(unused_imports)]
use std::{mem, ptr, slice};

use super::*;
Expand Down Expand Up @@ -57,7 +58,7 @@ mod generated_tests {

// SAFETY: FFI call returns a valid C string.
let c_val = unsafe {
let c_ptr: *const c_char = unsafe { ctest_const_cstr__A() };
let c_ptr: *const c_char = ctest_const_cstr__A();
CStr::from_ptr(c_ptr)
};

Expand Down
12 changes: 11 additions & 1 deletion ctest-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ name = "ctest-test"
version = "0.1.0"
authors = ["Alex Crichton <[email protected]>"]
publish = false
edition = "2021"
edition = "2024"

[build-dependencies]
ctest = { path = "../ctest" }
ctest-next = { path = "../ctest-next" }
cc = "1.2"

[dev-dependencies]
ctest = { path = "../ctest" }
ctest-next = { path = "../ctest-next" }

[dependencies]
cfg-if = "1.0.1"
Expand All @@ -24,6 +26,14 @@ test = false
name = "t2"
test = false

[[bin]]
name = "t1_next"
test = false

[[bin]]
name = "t2_next"
test = false

[[bin]]
name = "t1_cxx"
test = false
Expand Down
77 changes: 64 additions & 13 deletions ctest-test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,14 @@ fn main() {
if profile == "release" || opt_level >= 2 {
println!("cargo:rustc-cfg=optimized");
}
cc::Build::new()
.include("src")
.warnings(false)
.file("src/t1.c")
.compile("libt1.a");
println!("cargo:rerun-if-changed=src/t1.c");
println!("cargo:rerun-if-changed=src/t1.h");
cc::Build::new()
.warnings(false)
.file("src/t2.c")
.compile("libt2.a");
println!("cargo:rerun-if-changed=src/t2.c");
println!("cargo:rerun-if-changed=src/t2.h");

do_cc();
test_ctest_c();
test_ctest_cpp();
test_ctest_next();
}

fn test_ctest_c() {
ctest::TestGenerator::new()
.header("t1.h")
.include("src")
Expand All @@ -37,10 +32,13 @@ fn main() {
.volatile_item(t1_volatile)
.array_arg(t1_arrays)
.skip_roundtrip(|n| n == "Arr")
.skip_const(|name| name == "T1S")
.generate("src/t1.rs", "t1gen.rs");

ctest::TestGenerator::new()
.header("t2.h")
.include("src")
.skip_const(|name| name == "T2S")
.type_name(move |ty, is_struct, is_union| match ty {
"T2Union" => ty.to_string(),
t if is_struct => format!("struct {t}"),
Expand All @@ -49,7 +47,9 @@ fn main() {
})
.skip_roundtrip(|_| true)
.generate("src/t2.rs", "t2gen.rs");
}

fn test_ctest_cpp() {
println!("cargo::rustc-check-cfg=cfg(has_cxx)");
if !cfg!(unix) || Command::new("c++").arg("v").output().is_ok() {
// A C compiler is always available, but these are only run if a C++ compiler is
Expand All @@ -68,14 +68,17 @@ fn main() {
t if is_union => format!("union {t}"),
t => t.to_string(),
})
.skip_const(|name| name == "T1S")
.volatile_item(t1_volatile)
.array_arg(t1_arrays)
.skip_roundtrip(|n| n == "Arr")
.generate("src/t1.rs", "t1gen_cxx.rs");

ctest::TestGenerator::new()
.header("t2.h")
.language(ctest::Lang::CXX)
.include("src")
.skip_const(|name| name == "T2S")
.type_name(move |ty, is_struct, is_union| match ty {
"T2Union" => ty.to_string(),
t if is_struct => format!("struct {t}"),
Expand All @@ -89,6 +92,54 @@ fn main() {
}
}

fn test_ctest_next() {
let mut t1gen = ctest_next::TestGenerator::new();
t1gen
.header("t1.h")
.include("src")
.skip_private(true)
.rename_fn(|f| f.link_name().unwrap_or(f.ident()).to_string().into())
.rename_union_ty(|ty| (ty == "T1Union").then_some(ty.to_string()))
.rename_struct_ty(|ty| (ty == "Transparent").then_some(ty.to_string()))
.volatile_struct_field(|s, f| s.ident() == "V" && f.ident() == "v")
.volatile_static(|s| s.ident() == "vol_ptr")
.volatile_static(|s| s.ident() == "T1_fn_ptr_vol")
.volatile_fn_arg(|f, p| f.ident() == "T1_vol0" && p.ident() == "arg0")
.volatile_fn_arg(|f, p| f.ident() == "T1_vol2" && p.ident() == "arg1")
.volatile_fn_return_type(|f| f.ident() == "T1_vol1")
.volatile_fn_return_type(|f| f.ident() == "T1_vol2")
// The parameter `a` of the functions `T1r`, `T1s`, `T1t`, `T1v` is an array.
.array_arg(|f, p| matches!(f.ident(), "T1r" | "T1s" | "T1t" | "T1v") && p.ident() == "a")
.skip_roundtrip(|n| n == "Arr");
ctest_next::generate_test(&mut t1gen, "src/t1.rs", "t1nextgen.rs").unwrap();

let mut t2gen = ctest_next::TestGenerator::new();
t2gen
.header("t2.h")
.include("src")
// public C typedefs have to manually be specified because they are identical to normal
// structs on the Rust side.
.rename_union_ty(|ty| (ty == "T2Union").then_some(ty.to_string()))
.skip_roundtrip(|_| true);
ctest_next::generate_test(&mut t2gen, "src/t2.rs", "t2nextgen.rs").unwrap();
}

fn do_cc() {
cc::Build::new()
.include("src")
.warnings(false)
.file("src/t1.c")
.compile("libt1.a");
println!("cargo:rerun-if-changed=src/t1.c");
println!("cargo:rerun-if-changed=src/t1.h");
cc::Build::new()
.warnings(false)
.file("src/t2.c")
.compile("libt2.a");
println!("cargo:rerun-if-changed=src/t2.c");
println!("cargo:rerun-if-changed=src/t2.h");
}

fn t1_volatile(i: ctest::VolatileItemKind) -> bool {
use ctest::VolatileItemKind::*;
match i {
Expand Down
2 changes: 1 addition & 1 deletion ctest-test/src/bin/t1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
#![deny(warnings)]

use ctest_test::t1::*;
use libc::*;
use std::ffi::c_uint;

include!(concat!(env!("OUT_DIR"), "/t1gen.rs"));
Loading
Loading