[PATCH] D129570: [clang-tidy] Add new clang-tidy check to find implicit conversions from enum to integer.

Carlos Galvez via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 11 23:30:29 PST 2023


carlosgalvezp added inline comments.


================
Comment at: clang-tools-extra/clang-tidy/bugprone/EnumToIntCheck.cpp:45
+  } else {
+    Note << FixItHint::CreateInsertion(MatchedExpr->getBeginLoc(), "(int)");
+  }
----------------
pfultz2 wrote:
> carlosgalvezp wrote:
> > I don't think we can assume the type of the enum is `int`, see for example:
> > 
> > ```
> > enum Foo : unsigned int
> > {
> >     a,
> >     b
> > };
> > 
> > 
> > void f(unsigned int);
> > 
> > int main()
> > {
> >     f(a);
> > }
> > 
> > ```
> > 
> > Even if there is no explicit underlying type, isn't the underlying type implementation-defined?
> Since its an explicit cast then we should probably use the type that the function accepts(since thats what it will be eventually converted to)  rather than the type of the underling enum type.
I'm not sure that's correct either, and it could lead to narrowing conversion warnings being ignored, see example:

https://godbolt.org/z/PfPxEYPrj

The correct thing to do would be to cast to the underlying type of the enum. A user could do it like this, although it's quite unreadable:

  static_cast<std::underlying_type_t<MyEnum>>(enum_value)

But since in this context we have a lot more information from the AST, maybe we can automatically figure out the underlying type of the enum without having to call `std::underlying_type`?




CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D129570/new/

https://reviews.llvm.org/D129570



More information about the cfe-commits mailing list