Skip to content

Add dummy definition for referenced but never-defined structs#143

Open
lucic71 wants to merge 4 commits into
Cpp2Rust:masterfrom
lucic71:opaque-ptrs
Open

Add dummy definition for referenced but never-defined structs#143
lucic71 wants to merge 4 commits into
Cpp2Rust:masterfrom
lucic71:opaque-ptrs

Conversation

@lucic71
Copy link
Copy Markdown
Contributor

@lucic71 lucic71 commented May 22, 2026

This handles opaque pointers to user defined forward declared structs. It's allowed to use such pointers, even though the struct is not defined in any translation unit.

To implement this, I modified record_decls_ to also keep an extra bool with the following meaning:

    // record name -> true if a definition has been emitted, false if only
    // referenced.
    std::unordered_map<std::string, bool> entries_;

At the end of visiting all TU's, for the record_decls_ that are only referenced (not defined), a dummy struct definition is generated:

#[repr(C)]
pub struct opaque {
    _opaque: [u8; 0],
}

@lucic71 lucic71 marked this pull request as draft May 22, 2026 14:48
@lucic71 lucic71 marked this pull request as ready for review May 22, 2026 15:45
@lucic71 lucic71 changed the title Add dummy definition for referenced never-defined structs Add dummy definition for referenced but never-defined structs May 22, 2026
@lucic71
Copy link
Copy Markdown
Contributor Author

lucic71 commented May 22, 2026

pub struct opaque is enough, it doesn't have to be

#[repr(C)]
pub struct opaque {
    _opaque: [u8; 0],
}

@nunoplopes
Copy link
Copy Markdown
Contributor

But we take the whole program as input. Why is something undefined?

@lucic71
Copy link
Copy Markdown
Contributor Author

lucic71 commented May 23, 2026

But we take the whole program as input. Why is something undefined?

The following case is a valid C/C++ program:

struct S; // forward declaration

#ifdef FLAG_THAT_CAN_BE_DISABLED_AT_BUILD_TIME
struct S {
  ... definition of struct ...
}
#endif 

void foo(S* s) {}

This becomes:

fn foo(s: *mut S) {}

And errors because there is no definition of S (we don't generate code on struct S; // forward declaration because rust does not support forward declarations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants