Skip to content

ctest-next: miscellaneous filtering bug fixes #4613

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

Merged
merged 1 commit into from
Aug 11, 2025
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ jobs:
# Remove `-Dwarnings` at the MSRV since lints may be different
export RUSTFLAGS=""
# Remove `ctest-next` which uses the 2024 edition
perl -i -ne 'print unless /"ctest-(next|test)",/' Cargo.toml
perl -i -ne 'print unless /"ctest-(next|test)",/ || /"libc-test",/' Cargo.toml
fi
./ci/verify-build.sh
Expand Down Expand Up @@ -320,7 +320,7 @@ jobs:
- name: Install Rust
run: rustup update "$MSRV" --no-self-update && rustup default "$MSRV"
- name: Remove edition 2024 crates
run: perl -i -ne 'print unless /"ctest-(next|test)",/' Cargo.toml
run: perl -i -ne 'print unless /"ctest-(next|test)",/ || /"libc-test",/' Cargo.toml
- uses: Swatinem/rust-cache@v2
- run: cargo build -p ctest

Expand Down
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.

1 change: 0 additions & 1 deletion ctest-next/src/ast/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::{BoxStr, Field};
/// Represents a union defined in Rust.
#[derive(Debug, Clone)]
pub struct Union {
#[expect(unused)]
pub(crate) public: bool,
pub(crate) ident: BoxStr,
pub(crate) fields: Vec<Field>,
Expand Down
37 changes: 2 additions & 35 deletions ctest-next/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ pub struct TestGenerator {
cfg: Vec<(String, Option<String>)>,
mapped_names: Vec<MappedName>,
pub(crate) skips: Vec<Skip>,
verbose_skip: bool,
pub(crate) verbose_skip: bool,
pub(crate) volatile_items: Vec<VolatileItem>,
pub(crate) array_arg: Option<ArrayArg>,
skip_private: bool,
pub(crate) skip_private: bool,
pub(crate) skip_roundtrip: Option<SkipTest>,
pub(crate) skip_signededness: Option<SkipTest>,
pub(crate) skip_fn_ptrcheck: Option<SkipTest>,
Expand Down Expand Up @@ -898,8 +898,6 @@ impl TestGenerator {
let mut ffi_items = FfiItems::new();
ffi_items.visit_file(&ast);

self.filter_ffi_items(&mut ffi_items);

let output_directory = self
.out_dir
.clone()
Expand Down Expand Up @@ -938,37 +936,6 @@ impl TestGenerator {
Ok(output_file_path)
}

/// Skips entire items such as structs, constants, and aliases from being tested.
///
/// Does not skip specific tests or specific fields. If `skip_private` is true,
/// it will skip tests for all private items.
fn filter_ffi_items(&self, ffi_items: &mut FfiItems) {
let verbose = self.verbose_skip;

macro_rules! filter {
($field:ident, $variant:ident, $label:literal) => {{
let skipped: Vec<_> = ffi_items
.$field
.extract_if(.., |item| {
self.skips.iter().any(|f| f(&MapInput::$variant(item)))
|| (self.skip_private && !item.public)
})
.collect();
if verbose {
skipped
.iter()
.for_each(|item| eprintln!("Skipping {} \"{}\"", $label, item.ident()));
}
}};
}

filter!(aliases, Alias, "alias");
filter!(constants, Const, "const");
filter!(structs, Struct, "struct");
filter!(foreign_functions, Fn, "fn");
filter!(foreign_statics, Static, "static");
}

/// Maps Rust identifiers or types to C counterparts, or defaults to the original name.
pub(crate) fn rty_to_cty<'a>(&self, item: impl Into<MapInput<'a>>) -> String {
let item = item.into();
Expand Down
86 changes: 63 additions & 23 deletions ctest-next/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use proc_macro2::Span;
use quote::ToTokens;
use syn::spanned::Spanned;

use crate::cdecl::Constness;
use crate::ffi_items::FfiItems;
use crate::translator::{TranslationErrorKind, Translator};
use crate::{
Expand Down Expand Up @@ -86,7 +87,7 @@ impl TestTemplate {
&mut self,
helper: &TranslateHelper,
) -> Result<(), TranslationError> {
for constant in helper.ffi_items.constants() {
for constant in helper.filtered_ffi_items.constants() {
if let syn::Type::Ptr(ptr) = &constant.ty
&& let syn::Type::Path(path) = &*ptr.elem
&& path.path.segments.last().unwrap().ident == "c_char"
Expand Down Expand Up @@ -124,7 +125,7 @@ impl TestTemplate {
&mut self,
helper: &TranslateHelper,
) -> Result<(), TranslationError> {
for alias in helper.ffi_items.aliases() {
for alias in helper.filtered_ffi_items.aliases() {
let item = TestSizeAlign {
test_name: size_align_test_ident(alias.ident()),
id: alias.ident().into(),
Expand All @@ -134,7 +135,7 @@ impl TestTemplate {
self.size_align_tests.push(item.clone());
self.test_idents.push(item.test_name);
}
for struct_ in helper.ffi_items.structs() {
for struct_ in helper.filtered_ffi_items.structs() {
let item = TestSizeAlign {
test_name: size_align_test_ident(struct_.ident()),
id: struct_.ident().into(),
Expand All @@ -144,7 +145,7 @@ impl TestTemplate {
self.size_align_tests.push(item.clone());
self.test_idents.push(item.test_name);
}
for union_ in helper.ffi_items.unions() {
for union_ in helper.filtered_ffi_items.unions() {
let item = TestSizeAlign {
test_name: size_align_test_ident(union_.ident()),
id: union_.ident().into(),
Expand All @@ -165,7 +166,7 @@ impl TestTemplate {
&mut self,
helper: &TranslateHelper,
) -> Result<(), TranslationError> {
for alias in helper.ffi_items.aliases() {
for alias in helper.filtered_ffi_items.aliases() {
let should_skip_signededness_test = helper
.generator
.skip_signededness
Expand Down Expand Up @@ -197,7 +198,7 @@ impl TestTemplate {
let should_skip = |map_input| helper.generator.skips.iter().any(|f| f(&map_input));

let struct_fields = helper
.ffi_items
.filtered_ffi_items
.structs()
.iter()
.flat_map(|struct_| struct_.fields.iter().map(move |field| (struct_, field)))
Expand All @@ -213,7 +214,7 @@ impl TestTemplate {
)
});
let union_fields = helper
.ffi_items
.filtered_ffi_items
.unions()
.iter()
.flat_map(|union_| union_.fields.iter().map(move |field| (union_, field)))
Expand Down Expand Up @@ -251,15 +252,15 @@ impl TestTemplate {
&mut self,
helper: &TranslateHelper,
) -> Result<(), TranslationError> {
for alias in helper.ffi_items.aliases() {
for alias in helper.filtered_ffi_items.aliases() {
let c_ty = helper.c_type(alias)?;
self.add_roundtrip_test(helper, alias.ident(), &[], &c_ty, true);
}
for struct_ in helper.ffi_items.structs() {
for struct_ in helper.filtered_ffi_items.structs() {
let c_ty = helper.c_type(struct_)?;
self.add_roundtrip_test(helper, struct_.ident(), &struct_.fields, &c_ty, false);
}
for union_ in helper.ffi_items.unions() {
for union_ in helper.filtered_ffi_items.unions() {
let c_ty = helper.c_type(union_)?;
self.add_roundtrip_test(helper, union_.ident(), &union_.fields, &c_ty, false);
}
Expand Down Expand Up @@ -303,14 +304,14 @@ impl TestTemplate {
let should_skip = |map_input| helper.generator.skips.iter().any(|f| f(&map_input));

let struct_fields = helper
.ffi_items
.filtered_ffi_items
.structs()
.iter()
.flat_map(|s| s.fields.iter().map(move |f| (s, f)))
.filter(|(s, f)| {
!should_skip(MapInput::StructField(s, f))
&& !should_skip(MapInput::StructFieldType(s, f))
&& f.public
!(should_skip(MapInput::StructField(s, f))
|| should_skip(MapInput::StructFieldType(s, f))
|| !f.public)
})
.map(|(s, f)| {
(
Expand All @@ -332,14 +333,14 @@ impl TestTemplate {
)
});
let union_fields = helper
.ffi_items
.filtered_ffi_items
.unions()
.iter()
.flat_map(|u| u.fields.iter().map(move |f| (u, f)))
.filter(|(u, f)| {
!should_skip(MapInput::UnionField(u, f))
&& !should_skip(MapInput::UnionFieldType(u, f))
&& f.public
!(should_skip(MapInput::UnionField(u, f))
|| should_skip(MapInput::UnionFieldType(u, f))
|| !f.public)
})
.map(|(u, f)| {
(
Expand Down Expand Up @@ -532,6 +533,7 @@ fn foreign_fn_test_ident(ident: &str) -> BoxStr {

/// Wrap methods that depend on both ffi items and the generator.
pub(crate) struct TranslateHelper<'a> {
filtered_ffi_items: FfiItems,
ffi_items: &'a FfiItems,
Comment on lines +536 to 537
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to keep the unfiltered ffi_items at all anymore? It seems cleaner to only keep the filtered items here, if possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's to fix one of the bugs, if say a struct T1Bar is skipped for testing it won't be in filtered_ffi_items, but if some other test for a different struct returns a *const T1Bar, then it would fail to realize that T1Bar is a struct, since originally we were using the filtered_ffi_items in c_type.

generator: &'a TestGenerator,
translator: Translator<'a>,
Expand All @@ -540,11 +542,49 @@ pub(crate) struct TranslateHelper<'a> {
impl<'a> TranslateHelper<'a> {
/// Create a new translation helper.
pub(crate) fn new(ffi_items: &'a FfiItems, generator: &'a TestGenerator) -> Self {
Self {
let filtered_ffi_items = ffi_items.clone();
let mut helper = Self {
filtered_ffi_items,
ffi_items,
generator,
translator: Translator::new(ffi_items, generator),
};
helper.filter_ffi_items();

helper
}

/// Skips entire items such as structs, constants, and aliases from being tested.
///
/// Does not skip specific tests or specific fields. If `skip_private` is true,
/// it will skip tests for all private items.
fn filter_ffi_items(&mut self) {
let verbose = self.generator.verbose_skip;

macro_rules! filter {
($field:ident, $variant:ident, $label:literal) => {{
let skipped = self.filtered_ffi_items.$field.extract_if(.., |item| {
(self.generator.skip_private && !item.public)
|| self
.generator
.skips
.iter()
.any(|f| f(&MapInput::$variant(item)))
});
for item in skipped {
if verbose {
eprintln!("Skipping {} \"{}\"", $label, item.ident())
}
}
}};
}

filter!(aliases, Alias, "alias");
filter!(constants, Const, "const");
filter!(structs, Struct, "struct");
filter!(unions, Union, "union");
filter!(foreign_functions, Fn, "fn");
filter!(foreign_statics, Static, "static");
}

/// Returns the equivalent C/Cpp identifier of the Rust item.
Expand All @@ -565,9 +605,9 @@ impl<'a> TranslateHelper<'a> {
// inside of `Fn` when parsed.
MapInput::Fn(_) => unimplemented!(),
// For structs/unions/aliases, their type is the same as their identifier.
MapInput::Alias(a) => (a.ident(), cdecl::named(a.ident(), cdecl::Constness::Mut)),
MapInput::Struct(s) => (s.ident(), cdecl::named(s.ident(), cdecl::Constness::Mut)),
MapInput::Union(u) => (u.ident(), cdecl::named(u.ident(), cdecl::Constness::Mut)),
MapInput::Alias(a) => (a.ident(), cdecl::named(a.ident(), Constness::Mut)),
MapInput::Struct(s) => (s.ident(), cdecl::named(s.ident(), Constness::Mut)),
MapInput::Union(u) => (u.ident(), cdecl::named(u.ident(), Constness::Mut)),

MapInput::StructType(_) => panic!("MapInput::StructType is not allowed!"),
MapInput::UnionType(_) => panic!("MapInput::UnionType is not allowed!"),
Expand All @@ -584,7 +624,7 @@ impl<'a> TranslateHelper<'a> {
)
})?;

let item = if self.ffi_items.contains_struct(ident) {
let item = if self.ffi_items.contains_struct(&ty) {
MapInput::StructType(&ty)
} else if self.ffi_items.contains_union(ident) {
MapInput::UnionType(&ty)
Expand Down
8 changes: 8 additions & 0 deletions ctest-next/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,11 @@ fn test_translate_helper_array_1d_2d() {
assert_r2cdecl("[u8; 10]", "uint8_t foo[10]");
assert_r2cdecl("[[u8; 64]; 32]", "uint8_t foo[32][64]");
}

#[test]
fn test_translate_expr_literal_types() {
assert_eq!(
r2cdecl("[u8; 10usize]", "foo").unwrap(),
"uint8_t foo[(size_t)10]"
);
}
18 changes: 18 additions & 0 deletions ctest-next/src/translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,24 @@ pub(crate) fn ptr_with_inner(
/// This function will just pass the expression as is in most cases.
pub(crate) fn translate_expr(expr: &syn::Expr) -> String {
match expr {
syn::Expr::Index(i) => {
let base = translate_expr(&i.expr);
let index = translate_expr(&i.index);
format!("{base}[{index}]")
}
// This is done to deal with things like 3usize.
syn::Expr::Lit(l) => match &l.lit {
syn::Lit::Int(i) => {
let suffix = translate_primitive_type(i.suffix());
let val = i.base10_digits().to_string();
if suffix.is_empty() {
val
} else {
format!("({suffix}){val}")
}
}
_ => l.to_token_stream().to_string(),
},
syn::Expr::Path(p) => p.path.segments.last().unwrap().ident.to_string(),
syn::Expr::Cast(c) => translate_expr(c.expr.deref()),
expr => expr.to_token_stream().to_string(),
Expand Down
6 changes: 6 additions & 0 deletions libc-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ annotate-snippets = { version = "0.11.5", features = ["testing-colors"] }
[build-dependencies]
cc = "1.2.29"
ctest = { path = "../ctest" }
ctest-next = { path = "../ctest-next" }
regex = "1.11.1"

[features]
Expand All @@ -33,6 +34,11 @@ name = "ctest"
path = "test/ctest.rs"
harness = false

[[test]]
name = "ctest_next"
path = "test/ctest_next.rs"
harness = false

[[test]]
name = "linux-fcntl"
path = "test/linux_fcntl.rs"
Expand Down
13 changes: 13 additions & 0 deletions libc-test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ fn ctest_cfg() -> ctest::TestGenerator {
ctest::TestGenerator::new()
}

#[expect(unused)]
fn ctest_next_cfg() -> ctest_next::TestGenerator {
ctest_next::TestGenerator::new()
}

fn do_semver() {
let mut out = PathBuf::from(env::var("OUT_DIR").unwrap());
out.push("semver.rs");
Expand Down Expand Up @@ -164,6 +169,14 @@ fn main() {
let re = regex::bytes::Regex::new(r"(?-u:\b)crate::").unwrap();
copy_dir_hotfix(Path::new("../src"), &hotfix_dir, &re, b"::");

// FIXME(ctest): Only needed until ctest-next supports all tests.
// Provide a default for targets that don't yet use `ctest-next`.
std::fs::write(
format!("{}/main_next.rs", std::env::var("OUT_DIR").unwrap()),
"\nfn main() { println!(\"test result: ok\"); }\n",
)
.unwrap();

do_cc();
do_ctest();
do_semver();
Expand Down
5 changes: 5 additions & 0 deletions libc-test/test/ctest_next.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[allow(deprecated)]
#[allow(unused_imports)]
use libc::*;

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