[PATCH] D22069: clang-tidy modernize-loop-convert: preserve type of alias declaration (bug 28341)

Matthias Gehre via cfe-commits cfe-commits at lists.llvm.org
Wed Jul 6 14:04:49 PDT 2016


mgehre created this revision.
mgehre added reviewers: alexfh, klimek.
mgehre added a subscriber: cfe-commits.

Previoly, the added test failed with the fillowing fixit:

     char v[5];

-    for(size_t i = 0; i < 5; ++i)
+    for(char value : v)
     {
-        unsigned char value = v[i];
         if (value > 127)

i.e. the variable 'value' changes from unsigned char to signed char. And
thus the following 'if' does not work anymore.

With this commit, the fixit is changed to:
     char v[5];

-    for(size_t i = 0; i < 5; ++i)
+    for(unsigned char value : v)
     {
-        unsigned char value = v[i];
         if (value > 127)

http://reviews.llvm.org/D22069

Files:
  clang-tidy/modernize/LoopConvertCheck.cpp
  test/clang-tidy/modernize-loop-convert-extra.cpp

Index: test/clang-tidy/modernize-loop-convert-extra.cpp
===================================================================
--- test/clang-tidy/modernize-loop-convert-extra.cpp
+++ test/clang-tidy/modernize-loop-convert-extra.cpp
@@ -1060,3 +1060,15 @@
 }
 
 } // namespace InitLists
+
+void bug28341() {
+  char v[5];
+  for(int i = 0; i < 5; ++i) {
+      unsigned char value = v[i];
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: use range-based for loop instead
+  // CHECK-FIXES: for(unsigned char value : v)
+  // CHECK-FIXES-NOT: unsigned char value = v[i];
+      if (value > 127)
+        ;
+  }
+}
Index: clang-tidy/modernize/LoopConvertCheck.cpp
===================================================================
--- clang-tidy/modernize/LoopConvertCheck.cpp
+++ clang-tidy/modernize/LoopConvertCheck.cpp
@@ -517,6 +517,15 @@
   if (VarNameFromAlias) {
     const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
     VarName = AliasVar->getName().str();
+
+    // Use the type of the alias if it's not the same
+    QualType DeclarationType = AliasVar->getType();
+    if (!DeclarationType.isNull() && DeclarationType->isReferenceType())
+      DeclarationType = DeclarationType.getNonReferenceType();
+    if (Descriptor.ElemType.isNull() || DeclarationType.isNull() ||
+        !Context->hasSameUnqualifiedType(DeclarationType, Descriptor.ElemType))
+      Descriptor.ElemType = AliasVar->getType();
+
     AliasVarIsRef = AliasVar->getType()->isReferenceType();
 
     // We keep along the entire DeclStmt to keep the correct range here.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D22069.62960.patch
Type: text/x-patch
Size: 1565 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20160706/c8900155/attachment.bin>


More information about the cfe-commits mailing list