[clang] Add Clang attribute to ensure that fields are initialized explicitly (PR #102040)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Mon Sep 30 06:47:15 PDT 2024


https://github.com/erichkeane commented:

There isn't a way to remove the 'request changes' without approval, but I did some debugging and see what I was assuming was wrong.  So I don't have any concerns on the approach.

However, in using it for the last few hours, I REALLY dislike the diagnostic that you get.  I think the additional effort (which is, IMO, fairly minor once you have a RecordDecl) of printing the first field is worth it, and necessary for me.  The function should be pretty easy though, and you mentioned not really having much time, so here's what it should look like more or less:

```
FieldDecl *getFirstExplicitInitField(RecordDecl *RD) {
  // Current class field seems worth it, and gives the best answer in 99% of uses. Other 1% is when there is just fields in bases.
  for (FieldDecl *FD : RD) {
    if (FD->hasAttr<ExplicitInitAttr>())
      return FD;
  }
  // DFS for bases, but it doesn't seem worth the effort to work much harder to make sure we do the 'shallowest' field, which, while better diagnostics, is comparatively rare.
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
    for (CXXBaseSpecifier BS : CXXRD->bases()) {
      CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
      if (Base->hasUninitializedExplicitInitFields())
        if (FieldDecl *FD = getFirstExplicitInitField(Base))
          return FD;
    }
    // TODO: Figure out whether `bases` contains virtual bases, and not just non-virtual bases.  If not, do the above on `RecordDecl::vbases`
  }
}
```

That should be within a bit of const-correctness/few typos from doing what you need.


THOUGH: that makes me wonder, have you played with virtual bases yet?  Are we 'sane' for those?

https://github.com/llvm/llvm-project/pull/102040


More information about the cfe-commits mailing list