Skip to content

Commit

Permalink
Generate doc comment when type alias is hidden
Browse files Browse the repository at this point in the history
If a type is not documented, but a type alias with
the same canonical path is, then generate the
documentation of the typealias onto the type,
since otherwise it would be lost.
  • Loading branch information
jschwe committed Feb 8, 2025
1 parent 03d49b6 commit 27ec386
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 1 deletion.

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

7 changes: 7 additions & 0 deletions bindgen-tests/tests/headers/3119_overlapping_alias_comment.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// bindgen-flags: --no-layout-tests

/**
* This is a forward declared struct alias with overlapping names
* and documentation.
*/
typedef struct Struct Struct;
48 changes: 47 additions & 1 deletion bindgen/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2410,7 +2410,11 @@ impl CodeGenerator for CompInfo {
let mut needs_debug_impl = false;
let mut needs_partialeq_impl = false;
let needs_flexarray_impl = flex_array_generic.is_some();
if let Some(comment) = item.comment(ctx) {
let type_id = item.id().expect_type_id(ctx);

if let Some(comment) = item.comment(ctx)
.or_else(|| Self::get_typedef_fallback_comment(ctx, &type_id))
{
attributes.push(attributes::doc(&comment));
}

Expand Down Expand Up @@ -2987,6 +2991,48 @@ impl CompInfo {
}
}
}

/// Use a fallback comment from a type alias to this type if necessary
///
/// The documentation for a type could get lost in the following circumstances:
///
/// - We have a type and a type alias with the same canonical path
/// - The Documentation is only associated with the type alias
///
/// In this case bindgen will not generate the type alias and the documentation would be lost.
/// To avoid this, we check here if there is any type alias to this type, which has
/// the same canonical path and return the comment as a fallback, if our type does
/// not have documentation.
fn get_typedef_fallback_comment(
ctx: &BindgenContext,
type_id: &crate::ir::context::TypeId,
) -> Option<String> {
if !ctx.options().generate_comments {
return None;
}
let type_alias_comment = ctx
.items()
.filter(|(_id, alias)| {
let Some(this_ty) = alias.as_type() else {
return false;
};
let TypeKind::Alias(alias_to) = this_ty.kind() else {
return false;
};
//
match ctx.resolve_type(*alias_to).kind() {
TypeKind::ResolvedTypeRef(resolved_typeid) => {
resolved_typeid == type_id &&
alias.canonical_path(ctx) ==
type_id.canonical_path(ctx)
}
_ => false,
}
})
.filter_map(|(_id, item)| item.comment(ctx));
let alias_comment: Vec<String> = type_alias_comment.collect();
alias_comment.get(0).cloned()
}
}

impl Method {
Expand Down

0 comments on commit 27ec386

Please sign in to comment.