[PATCH] D82004: [clang-tidy][NFC] Remove the double look-up on IncludeInserter

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: klimek, gribozavr2, aaron.ballman, alexfh.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Refactor out the double lookup in `IncludeInserter` when trying to get the 
`IncludeSorter` for a specified `FileID`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82004

Files:
  clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeInserter.h


Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.h
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -71,6 +71,8 @@
   void AddInclude(StringRef FileName, bool IsAngled,
   SourceLocation HashLocation, SourceLocation EndLocation);
 
+  IncludeSorter (FileID File);
+
   llvm::DenseMap> IncludeSorterByFile;
   llvm::DenseMap> InsertedHeaders;
   const SourceManager 
Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "IncludeInserter.h"
+#include "IncludeSorter.h"
 #include "clang/Lex/Token.h"
 
 namespace clang {
@@ -45,6 +46,19 @@
   return std::make_unique(this);
 }
 
+IncludeSorter ::getOrCreate(FileID FileID) {
+  // std::unique_ptr is cheap to construct, so force a construction now to save
+  // the lookup needed if we were to insert into the map.
+  std::unique_ptr  = IncludeSorterByFile[FileID];
+  if (!Entry) {
+// If it wasn't found, Entry will be default constructed to nullptr.
+Entry = std::make_unique(
+, , FileID,
+SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), Style);
+  }
+  return *Entry;
+}
+
 llvm::Optional
 IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,
 bool IsAngled) {
@@ -53,31 +67,14 @@
   if (!InsertedHeaders[FileID].insert(std::string(Header)).second)
 return llvm::None;
 
-  if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {
-// This may happen if there have been no preprocessor directives in this
-// file.
-IncludeSorterByFile.insert(std::make_pair(
-FileID,
-std::make_unique(
-, , FileID,
-SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)),
-Style)));
-  }
-  return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled);
+  return getOrCreate(FileID).CreateIncludeInsertion(Header, IsAngled);
 }
 
 void IncludeInserter::AddInclude(StringRef FileName, bool IsAngled,
  SourceLocation HashLocation,
  SourceLocation EndLocation) {
   FileID FileID = SourceMgr.getFileID(HashLocation);
-  if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {
-IncludeSorterByFile.insert(std::make_pair(
-FileID, std::make_unique(
-, , FileID,
-SourceMgr.getFilename(HashLocation), Style)));
-  }
-  IncludeSorterByFile[FileID]->AddInclude(FileName, IsAngled, HashLocation,
-  EndLocation);
+  getOrCreate(FileID).AddInclude(FileName, IsAngled, HashLocation, 
EndLocation);
 }
 
 } // namespace utils


Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.h
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -71,6 +71,8 @@
   void AddInclude(StringRef FileName, bool IsAngled,
   SourceLocation HashLocation, SourceLocation EndLocation);
 
+  IncludeSorter (FileID File);
+
   llvm::DenseMap> IncludeSorterByFile;
   llvm::DenseMap> InsertedHeaders;
   const SourceManager 
Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "IncludeInserter.h"
+#include "IncludeSorter.h"
 #include "clang/Lex/Token.h"
 
 namespace clang {
@@ -45,6 +46,19 @@
   return std::make_unique(this);
 }
 
+IncludeSorter ::getOrCreate(FileID FileID) {
+  // std::unique_ptr is cheap to construct, so force a construction now to save
+  // the lookup needed if we were to insert into the map.
+  std::unique_ptr  = IncludeSorterByFile[FileID];
+  if (!Entry) {
+// If it wasn't found, Entry will be default constructed to nullptr.
+Entry = std::make_unique(
+

[PATCH] D81975: [clangd] Add command line option for ClangTidyConfig

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Gotta say it's not hugely pressing.
The reason for it is clangd lets you specify some checks to run but it doesn't 
let you specify the options for those checks. Effectively forcing each project 
to require a .clang-tidy configuration file if you want to use checks where you 
require some configuration.
This isn't an issue on large scale established projects, but when starting out 
on small scale projects, it would be nice if clangd(tidy) was already set up 
how you like it without going through the need of setting up a `.clang-tidy` 
file.
Once D81949  lands it will also be useful on 
large scale projects that enforce certain tidy checks, but locally a developer 
may want extra configurable checks running in their editor.

Having said all of that your proposal does appear to do what this patch aims 
just in a much more user friendly way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81975



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82004: [clang-tidy][NFC] Remove the double look-up on IncludeInserter

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG08c83ed75752: [clang-tidy][NFC] Remove the double look-up on 
IncludeInserter (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D82004?vs=271334=271432#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82004

Files:
  clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeInserter.h


Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.h
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -71,6 +71,8 @@
   void AddInclude(StringRef FileName, bool IsAngled,
   SourceLocation HashLocation, SourceLocation EndLocation);
 
+  IncludeSorter (FileID FileID);
+
   llvm::DenseMap> IncludeSorterByFile;
   llvm::DenseMap> InsertedHeaders;
   const SourceManager 
Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -45,6 +45,19 @@
   return std::make_unique(this);
 }
 
+IncludeSorter ::getOrCreate(FileID FileID) {
+  // std::unique_ptr is cheap to construct, so force a construction now to save
+  // the lookup needed if we were to insert into the map.
+  std::unique_ptr  = IncludeSorterByFile[FileID];
+  if (!Entry) {
+// If it wasn't found, Entry will be default constructed to nullptr.
+Entry = std::make_unique(
+, , FileID,
+SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), Style);
+  }
+  return *Entry;
+}
+
 llvm::Optional
 IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,
 bool IsAngled) {
@@ -53,31 +66,14 @@
   if (!InsertedHeaders[FileID].insert(std::string(Header)).second)
 return llvm::None;
 
-  if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {
-// This may happen if there have been no preprocessor directives in this
-// file.
-IncludeSorterByFile.insert(std::make_pair(
-FileID,
-std::make_unique(
-, , FileID,
-SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)),
-Style)));
-  }
-  return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled);
+  return getOrCreate(FileID).CreateIncludeInsertion(Header, IsAngled);
 }
 
 void IncludeInserter::AddInclude(StringRef FileName, bool IsAngled,
  SourceLocation HashLocation,
  SourceLocation EndLocation) {
   FileID FileID = SourceMgr.getFileID(HashLocation);
-  if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {
-IncludeSorterByFile.insert(std::make_pair(
-FileID, std::make_unique(
-, , FileID,
-SourceMgr.getFilename(HashLocation), Style)));
-  }
-  IncludeSorterByFile[FileID]->AddInclude(FileName, IsAngled, HashLocation,
-  EndLocation);
+  getOrCreate(FileID).AddInclude(FileName, IsAngled, HashLocation, 
EndLocation);
 }
 
 } // namespace utils


Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.h
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -71,6 +71,8 @@
   void AddInclude(StringRef FileName, bool IsAngled,
   SourceLocation HashLocation, SourceLocation EndLocation);
 
+  IncludeSorter (FileID FileID);
+
   llvm::DenseMap> IncludeSorterByFile;
   llvm::DenseMap> InsertedHeaders;
   const SourceManager 
Index: clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
===
--- clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -45,6 +45,19 @@
   return std::make_unique(this);
 }
 
+IncludeSorter ::getOrCreate(FileID FileID) {
+  // std::unique_ptr is cheap to construct, so force a construction now to save
+  // the lookup needed if we were to insert into the map.
+  std::unique_ptr  = IncludeSorterByFile[FileID];
+  if (!Entry) {
+// If it wasn't found, Entry will be default constructed to nullptr.
+Entry = std::make_unique(
+, , FileID,
+SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), Style);
+  }
+  return *Entry;
+}
+
 llvm::Optional
 IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,
 bool IsAngled) {
@@ -53,31 +66,14 @@
   if (!InsertedHeaders[FileID].insert(std::string(Header)).second)
 return 

[PATCH] D81953: [clang-tidy] warnings-as-error no longer exits with ErrorCount

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGccd127008aa2: [clang-tidy] warnings-as-error no longer exits 
with ErrorCount (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81953

Files:
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -478,7 +478,7 @@
   llvm::errs() << WErrorCount << " warning" << Plural << " treated as 
error"
<< Plural << "\n";
 }
-return WErrorCount;
+return 1;
   }
 
   if (FoundErrors) {


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -478,7 +478,7 @@
   llvm::errs() << WErrorCount << " warning" << Plural << " treated as error"
<< Plural << "\n";
 }
-return WErrorCount;
+return 1;
   }
 
   if (FoundErrors) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: alexfh, Eugene.Zelenko, angelgarcia, aaron.ballman, 
klimek.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Enables support for transforming loops of the form

  for (auto I = Cont.rbegin(), E = Cont.rend(); I != E;++I)

This is done automatically in C++20 mode using `std::ranges::reverse_view` but 
there are options to specify a different function to reverse iterator over a 
container.
This is the first step, down the line I'd like to possibly extend this support 
for array based loops

  for (unsigned I = Arr.size() - 1;I >=0;--I) Arr[I]...

Currently if you pass a reversing function with no header in the options it 
will just assume that the function exists, however as we have the ASTContext it 
may be as wise to check before applying, or at least lower the confidence level 
if we can't find it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, Disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use 

[PATCH] D80753: [clang-tidy] remove duplicate fixes of alias checkers

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.

LG, I have nothing else to add here.


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

https://reviews.llvm.org/D80753



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82059: [clang-tidy] RenamerClangTidy group redecls into 1 warning.

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG850bb889a56c: [clang-tidy] RenamerClangTidy group redecls 
into 1 warning. (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D82059?vs=271509=271722#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82059

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 
'my_class'
+// No warning needed here as this is tied to the previous declaration.
+// Just make sure the fix is applied.
 // CHECK-FIXES: {{^}}class CMyClass;{{$}}
 
 class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
-// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class 
constant 'classConstant'
 // CHECK-FIXES: {{^}}const int CMyClass::kClassConstant = 4;{{$}}
 
 int my_class::ClassMember_2 = 5;
-// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for class 
member 'ClassMember_2'
 // CHECK-FIXES: {{^}}int CMyClass::ClassMember2 = 5;{{$}}
 
 class my_derived_class : public virtual my_class {};
@@ -500,7 +499,6 @@
 
 template
 char const a::MyConstClass_string[] = "123";
-// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: invalid case style for class 
constant 'MyConstClass_string'
 // CHECK-FIXES: {{^}}char const a::kMyConstClassString[] = "123";{{$}}
 
 template  class A> struct b { A c; };
@@ -545,3 +543,22 @@
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
 void QualifiedTypeLocTest(volatile THIS___Structure &);
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}
+
+namespace redecls {
+// We only want the warning to show up once here for the first decl.
+// CHECK-MESSAGES: :[[@LINE+1]]:6: warning: invalid case style for global 
function 'badNamedFunction'
+void badNamedFunction();
+void badNamedFunction();
+void badNamedFunction(){}
+//  CHECK-FIXES: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction(){}
+void ReferenceBadNamedFunction() {
+  auto l_Ptr = badNamedFunction;
+  // CHECK-FIXES: {{^}}  auto l_Ptr = BadNamedFunction;
+  l_Ptr();
+  badNamedFunction();
+  // CHECK-FIXES: {{^}}  BadNamedFunction();
+}
+
+} // namespace redecls
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -168,7 +168,7 @@
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
  SourceManager *SourceMgr) {
-
+  Decl = cast(Decl->getCanonicalDecl());
   return addUsage(RenamerClangTidyCheck::NamingCheckId(Decl->getLocation(),

Decl->getNameAsString()),
   Range, SourceMgr);
@@ -376,6 +376,12 @@
 if (!Decl->getIdentifier() || Decl->getName().empty() || 
Decl->isImplicit())
   return;
 
+const auto *Canonical = cast(Decl->getCanonicalDecl());
+if (Canonical != Decl) {
+  addUsage(Canonical, Decl->getLocation());
+  return;
+}
+
 // Fix type aliases in value declarations.
 if (const auto *Value = Result.Nodes.getNodeAs("decl")) {
   if (const Type *TypePtr = Value->getType().getTypePtrOrNull()) {


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_class'
+// No warning needed here as this is tied to the previous declaration.
+// Just make sure the fix is applied.
 // CHECK-FIXES: {{^}}class CMyClass;{{$}}
 
 class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
-// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class constant 'classConstant'
 // CHECK-FIXES: {{^}}const int 

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271723.
njames93 marked 4 inline comments as done.
njames93 added a comment.

Address reviewer comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.crbegin(), E = Numbers.crend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+
+  // Ensure these bad loops aren't transformed.
+  for (auto I = Numbers.rbegin(), E = Numbers.end(); I != E; ++I) {
+observe(*I);
+  }
+  for (auto I 

[PATCH] D79477: [clang-tidy] Add --use-color command line option and UseColor option to control colors in diagnostics

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd9b8aada8288: [clang-tidy] Add --use-color command line 
option and UseColor option to control… (authored by hyd-dev, committed by 
njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79477

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/use-color.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -76,6 +76,7 @@
   User: user1
   ExtraArgs: ['arg1', 'arg2']
   ExtraArgsBefore: ['arg-before1', 'arg-before2']
+  UseColor: false
   )");
   ASSERT_TRUE(!!Options1);
   llvm::ErrorOr Options2 = parseConfiguration(R"(
@@ -85,6 +86,7 @@
   User: user2
   ExtraArgs: ['arg3', 'arg4']
   ExtraArgsBefore: ['arg-before3', 'arg-before4']
+  UseColor: true
   )");
   ASSERT_TRUE(!!Options2);
   ClangTidyOptions Options = Options1->mergeWith(*Options2, 0);
@@ -98,6 +100,8 @@
   EXPECT_EQ("arg-before1,arg-before2,arg-before3,arg-before4",
 llvm::join(Options.ExtraArgsBefore->begin(),
Options.ExtraArgsBefore->end(), ","));
+  ASSERT_TRUE(Options.UseColor.hasValue());
+  EXPECT_TRUE(*Options.UseColor);
 }
 
 class TestCheck : public ClangTidyCheck {
Index: clang-tools-extra/test/clang-tidy/infrastructure/use-color.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/use-color.cpp
@@ -0,0 +1,28 @@
+// RUN: clang-tidy -dump-config | FileCheck %s
+// RUN: clang-tidy -dump-config -use-color | FileCheck -check-prefix=CHECK-CONFIG-COLOR %s
+// RUN: clang-tidy -dump-config -use-color=false | FileCheck -check-prefix=CHECK-CONFIG-NO-COLOR %s
+// RUN: clang-tidy -config='UseColor: true' -dump-config | FileCheck -check-prefix=CHECK-CONFIG-COLOR %s
+// RUN: clang-tidy -config='UseColor: false' -dump-config | FileCheck -check-prefix=CHECK-CONFIG-NO-COLOR %s
+// RUN: clang-tidy -help | FileCheck -check-prefix=CHECK-OPT-PRESENT %s
+
+// REQUIRES: ansi-escape-sequences
+// RUN: clang-tidy -checks='-*, modernize-use-override' -extra-arg=-std=c++11 -use-color=false %s | FileCheck -check-prefix=CHECK-NO-COLOR %s
+// RUN: clang-tidy -checks='-*, modernize-use-override' -extra-arg=-std=c++11 %s | FileCheck -check-prefix=CHECK-NO-COLOR %s
+// RUN: clang-tidy -checks='-*, modernize-use-override' -extra-arg=-std=c++11 -use-color %s | FileCheck -check-prefix=CHECK-COLOR %s
+
+// CHECK-NOT: UseColor
+// CHECK-CONFIG-NO-COLOR: UseColor: false
+// CHECK-CONFIG-COLOR: UseColor: true
+// CHECK-OPT-PRESENT: --use-color
+
+class Base {
+public:
+  virtual ~Base() = 0;
+};
+
+class Delivered : public Base {
+public:
+  virtual ~Delivered() = default;
+  // CHECK-NO-COLOR: warning: prefer using 'override' or (rarely) 'final' instead of 'virtual' [modernize-use-override]
+  // CHECK-COLOR: {{.\[0;1;35m}}warning: {{.\[0m}}{{.\[1m}}prefer using 'override' or (rarely) 'final' instead of 'virtual' [modernize-use-override]
+};
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -230,6 +230,15 @@
cl::value_desc("filename"),
cl::cat(ClangTidyCategory));
 
+static cl::opt UseColor("use-color", cl::desc(R"(
+Use colors in diagnostics. If not set, colors
+will be used if the terminal connected to
+standard output supports colors.
+This option overrides the 'UseColor' option in
+.clang-tidy file, if any.
+)"),
+  cl::init(false), cl::cat(ClangTidyCategory));
+
 namespace clang {
 namespace tidy {
 
@@ -292,6 +301,8 @@
 OverrideOptions.SystemHeaders = SystemHeaders;
   if (FormatStyle.getNumOccurrences() > 0)
 OverrideOptions.FormatStyle = FormatStyle;
+  if (UseColor.getNumOccurrences() > 0)
+OverrideOptions.UseColor = UseColor;
 
   if (!Config.empty()) {
 if (llvm::ErrorOr ParsedConfig =
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.h
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -126,6 +126,9 @@
   /// apply this config file on top of the parent one. If false or missing,
   /// only this 

[PATCH] D79477: [clang-tidy] Add --use-color command line option and UseColor option to control colors in diagnostics

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D79477



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82059: [clang-tidy] RenamerClangTidy group redecls into 1 warning.

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh, jbcoe, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

This changes the behavious of `RenamerClangTidyCheck` based checks by grouping 
declarations of the same thing into 1 warning where it is first declared.
This cleans up clang-tidy output and prevents issues where 1 fix-it couldn't be 
applied, yet all other warnings(and fix-its) for the same declaration would be 
applied.
The old behaviour of forward declaring a class without defining it isn't 
affected, i.e. no warnings will be emitted for that case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82059

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 
'my_class'
+// No warning needed here as this is tied to the previous declaration.
+// Just make sure the fix is applied.
 // CHECK-FIXES: {{^}}class CMyClass;{{$}}
 
 class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
-// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class 
constant 'classConstant'
 // CHECK-FIXES: {{^}}const int CMyClass::kClassConstant = 4;{{$}}
 
 int my_class::ClassMember_2 = 5;
-// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for class 
member 'ClassMember_2'
 // CHECK-FIXES: {{^}}int CMyClass::ClassMember2 = 5;{{$}}
 
 class my_derived_class : public virtual my_class {};
@@ -500,7 +499,6 @@
 
 template
 char const a::MyConstClass_string[] = "123";
-// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: invalid case style for class 
constant 'MyConstClass_string'
 // CHECK-FIXES: {{^}}char const a::kMyConstClassString[] = "123";{{$}}
 
 template  class A> struct b { A c; };
@@ -545,3 +543,22 @@
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
 void QualifiedTypeLocTest(volatile THIS___Structure &);
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}
+
+namespace redecls {
+// We only want the warning to show up once here for the first decl.
+// CHECK-MESSAGES: :[[@LINE+1]]:6: warning: invalid case style for global 
function 'badNamedFunction'
+void badNamedFunction();
+void badNamedFunction();
+void badNamedFunction(){}
+//  CHECK-FIXES: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction(){}
+void ReferenceBadNamedFunction() {
+  auto l_Ptr = badNamedFunction;
+  // CHECK-FIXES: {{^}}  auto l_Ptr = BadNamedFunction;
+  l_Ptr();
+  badNamedFunction();
+  // CHECK-FIXES: {{^}}  BadNamedFunction();
+}
+
+} // namespace redecls
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -168,7 +168,7 @@
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
  SourceManager *SourceMgr) {
-
+  Decl = cast(Decl->getCanonicalDecl());
   return addUsage(RenamerClangTidyCheck::NamingCheckId(Decl->getLocation(),

Decl->getNameAsString()),
   Range, SourceMgr);
@@ -380,6 +380,14 @@
 if (!Decl->getIdentifier() || Decl->getName().empty() || 
Decl->isImplicit())
   return;
 
+{
+  const auto *Canonical = cast(Decl->getCanonicalDecl());
+  if (Canonical != Decl) {
+addUsage(Canonical, Decl->getLocation());
+return;
+  }
+}
+
 // Fix type aliases in value declarations.
 if (const auto *Value = Result.Nodes.getNodeAs("decl")) {
   if (const Type *TypePtr = Value->getType().getTypePtrOrNull()) {


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_class'
+// No warning needed here as this is tied to the 

[PATCH] D82059: [clang-tidy] RenamerClangTidy group redecls into 1 warning.

2020-06-17 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271509.
njames93 added a comment.

New line...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82059

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 
'my_class'
+// No warning needed here as this is tied to the previous declaration.
+// Just make sure the fix is applied.
 // CHECK-FIXES: {{^}}class CMyClass;{{$}}
 
 class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
-// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class 
constant 'classConstant'
 // CHECK-FIXES: {{^}}const int CMyClass::kClassConstant = 4;{{$}}
 
 int my_class::ClassMember_2 = 5;
-// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for class 
member 'ClassMember_2'
 // CHECK-FIXES: {{^}}int CMyClass::ClassMember2 = 5;{{$}}
 
 class my_derived_class : public virtual my_class {};
@@ -500,7 +499,6 @@
 
 template
 char const a::MyConstClass_string[] = "123";
-// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: invalid case style for class 
constant 'MyConstClass_string'
 // CHECK-FIXES: {{^}}char const a::kMyConstClassString[] = "123";{{$}}
 
 template  class A> struct b { A c; };
@@ -545,3 +543,22 @@
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(const this_structure &);{{$}}
 void QualifiedTypeLocTest(volatile THIS___Structure &);
 // CHECK-FIXES: {{^}}void QualifiedTypeLocTest(volatile this_structure &);{{$}}
+
+namespace redecls {
+// We only want the warning to show up once here for the first decl.
+// CHECK-MESSAGES: :[[@LINE+1]]:6: warning: invalid case style for global 
function 'badNamedFunction'
+void badNamedFunction();
+void badNamedFunction();
+void badNamedFunction(){}
+//  CHECK-FIXES: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction();
+// CHECK-FIXES-NEXT: {{^}}void BadNamedFunction(){}
+void ReferenceBadNamedFunction() {
+  auto l_Ptr = badNamedFunction;
+  // CHECK-FIXES: {{^}}  auto l_Ptr = BadNamedFunction;
+  l_Ptr();
+  badNamedFunction();
+  // CHECK-FIXES: {{^}}  BadNamedFunction();
+}
+
+} // namespace redecls
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -168,7 +168,7 @@
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
  SourceManager *SourceMgr) {
-
+  Decl = cast(Decl->getCanonicalDecl());
   return addUsage(RenamerClangTidyCheck::NamingCheckId(Decl->getLocation(),

Decl->getNameAsString()),
   Range, SourceMgr);
@@ -380,6 +380,14 @@
 if (!Decl->getIdentifier() || Decl->getName().empty() || 
Decl->isImplicit())
   return;
 
+{
+  const auto *Canonical = cast(Decl->getCanonicalDecl());
+  if (Canonical != Decl) {
+addUsage(Canonical, Decl->getLocation());
+return;
+  }
+}
+
 // Fix type aliases in value declarations.
 if (const auto *Value = Result.Nodes.getNodeAs("decl")) {
   if (const Type *TypePtr = Value->getType().getTypePtrOrNull()) {


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@
 // CHECK-FIXES: {{^}}static int ClassMember2;{{$}}
 };
 class my_class;
-// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for class 'my_class'
+// No warning needed here as this is tied to the previous declaration.
+// Just make sure the fix is applied.
 // CHECK-FIXES: {{^}}class CMyClass;{{$}}
 
 class my_forward_declared_class; // No warning should be triggered.
 
 const int my_class::classConstant = 4;
-// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for class constant 'classConstant'
 // CHECK-FIXES: {{^}}const int CMyClass::kClassConstant = 4;{{$}}
 
 int my_class::ClassMember_2 = 5;
-// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for class member 

[PATCH] D82162: [clang-tidy] RenamerClangTidy wont emit fixes in scratch space

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Prevent fixes being displayed if usages are found in the scratch buffer.
See Fix-It hints are being generated in the ScratchBuffer 
.
It may be wise down the line to put in a general fix in clang-tidy to prevent 
ScratchBuffer replacements being applied, but for now this will help.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82162

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -562,3 +562,19 @@
 }
 
 } // namespace redecls
+
+namespace scratchspace {
+#define DUP(Tok) Tok
+#define M1(Tok) DUP(badName##Tok())
+
+// We don't want a warning here as the call to this in Foo is in a scratch
+// buffer so its fix-it wouldn't be applied, resulting in invalid code.
+void badNameWarn();
+
+void Foo() {
+  M1(Warn);
+}
+
+#undef M1
+#undef DUP
+} // namespace scratchspace
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -156,14 +156,17 @@
   // is already in there
   RenamerClangTidyCheck::NamingCheckFailure  =
   NamingCheckFailures[Decl];
-  if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
-return;
 
   if (!Failure.ShouldFix())
 return;
 
+  if (SourceMgr && SourceMgr->isWrittenInScratchSpace(FixLocation))
+Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
+
   if (!utils::rangeCanBeFixed(Range, SourceMgr))
 Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
+
+  Failure.RawUsageLocs.insert(FixLocation.getRawEncoding());
 }
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
@@ -248,13 +251,15 @@
   if (const auto *Decl =
   Result.Nodes.getNodeAs("classRef")) {
 
-addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange());
+addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange(),
+ Result.SourceManager);
 
 for (const auto *Init : Decl->inits()) {
   if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
   if (const FieldDecl *FD = Init->getAnyMember())
-addUsage(FD, SourceRange(Init->getMemberLocation()));
+addUsage(FD, SourceRange(Init->getMemberLocation()),
+ Result.SourceManager);
   // Note: delegating constructors and base class initializers are handled
   // via the "typeLoc" matcher.
 }
@@ -271,7 +276,7 @@
 // we want instead to replace the next token, that will be the identifier.
 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
 
-addUsage(Decl->getParent(), Range);
+addUsage(Decl->getParent(), Range, Result.SourceManager);
 return;
   }
 
@@ -289,7 +294,7 @@
 // further TypeLocs handled below
 
 if (Decl) {
-  addUsage(Decl, Loc->getSourceRange());
+  addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
 
@@ -300,7 +305,7 @@
   SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
   if (const auto *ClassDecl = dyn_cast(Decl)) {
 if (const NamedDecl *TemplDecl = ClassDecl->getTemplatedDecl())
-  addUsage(TemplDecl, Range);
+  addUsage(TemplDecl, Range, Result.SourceManager);
 return;
   }
 }
@@ -308,7 +313,7 @@
 if (const auto  =
 Loc->getAs()) {
   if (const TagDecl *Decl = Ref.getTypePtr()->getAsTagDecl())
-addUsage(Decl, Loc->getSourceRange());
+addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
   }
@@ -317,7 +322,7 @@
   Result.Nodes.getNodeAs("nestedNameLoc")) {
 if (const NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
   if (const NamespaceDecl *Decl = Spec->getAsNamespace()) {
-addUsage(Decl, Loc->getLocalSourceRange());
+addUsage(Decl, Loc->getLocalSourceRange(), Result.SourceManager);
 return;
   }
 }
@@ -325,7 +330,8 @@
 
   if (const auto *Decl = Result.Nodes.getNodeAs("using")) {
 for (const auto *Shadow : Decl->shadows())
-  addUsage(Shadow->getTargetDecl(), Decl->getNameInfo().getSourceRange());
+  addUsage(Shadow->getTargetDecl(), Decl->getNameInfo().getSourceRange(),
+   

[PATCH] D81975: [clangd] Add command line option for ClangTidyConfig

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272009.
njames93 added a comment.

Small rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81975

Files:
  clang-tools-extra/clangd/test/clang-tidy-config.test
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -151,6 +151,15 @@
 init(""),
 };
 
+opt ClangTidyConfig{
+"clang-tidy-config",
+cat(Features),
+desc("Specifies a YAML/JSON configuration for when running clang-tidy "
+ "checks (this will override clang-tidy files). Only meaningful when "
+ "-clang-tidy flag is on"),
+init(""),
+};
+
 opt CodeCompletionParse{
 "completion-parse",
 cat(Features),
@@ -716,10 +725,24 @@
 tidy::ClangTidyOptions OverrideClangTidyOptions;
 if (!ClangTidyChecks.empty())
   OverrideClangTidyOptions.Checks = ClangTidyChecks;
-ClangTidyOptProvider = std::make_unique(
-tidy::ClangTidyGlobalOptions(),
-/* Default */ EmptyDefaults,
-/* Override */ OverrideClangTidyOptions, TFS.view(/*CWD=*/llvm::None));
+if (ClangTidyConfig.empty()) {
+  ClangTidyOptProvider = std::make_unique(
+  tidy::ClangTidyGlobalOptions(),
+  /* Default */ EmptyDefaults,
+  /* Override */ OverrideClangTidyOptions,
+  TFS.view(/*CWD=*/llvm::None));
+} else {
+  llvm::ErrorOr ParsedConfig =
+  tidy::parseConfiguration(ClangTidyConfig);
+  if (!ParsedConfig) {
+elog("Invalid -clang-tidy-config: {0}",
+ ParsedConfig.getError().message());
+return 1;
+  }
+  ClangTidyOptProvider = std::make_unique(
+  tidy::ClangTidyGlobalOptions(), EmptyDefaults, *ParsedConfig,
+  OverrideClangTidyOptions, TFS.view(/*CWD*/ llvm::None));
+}
 Opts.GetClangTidyOptions = [&](llvm::vfs::FileSystem &,
llvm::StringRef File) {
   // This function must be thread-safe and tidy option providers are not.
Index: clang-tools-extra/clangd/test/clang-tidy-config.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/clang-tidy-config.test
@@ -0,0 +1,40 @@
+# RUN: clangd -lit-test -clang-tidy-config="{CheckOptions: [{key: 
readability-identifier-naming.FunctionCase, value: camelBack}], Checks: 
'-*,readability-identifier-naming' }" < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","text":"void
 BadName();"}}}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"code": "readability-identifier-naming",
+# CHECK-NEXT:"message": "Invalid case style for function 'BadName' 
(fix available)",
+# CHECK-NEXT:"range": {
+# CHECK-NEXT:  "end": {
+# CHECK-NEXT:"character": 12,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "start": {
+# CHECK-NEXT:"character": 5,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  }
+# CHECK-NEXT:},
+# CHECK-NEXT:"severity": 2,
+# CHECK-NEXT:"source": "clang-tidy"
+# CHECK-NEXT:  }
+# CHECK-NEXT:],
+# CHECK-NEXT:"uri": "file://{{.*}}/foo.c",
+# CHECK-NEXT:"version": 0
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":2,"method":"sync","params":null}
+---
+{"jsonrpc":"2.0","method":"textDocument/didClose","params":{"textDocument":{"uri":"test:///foo.c"}}}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [],
+# CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -151,6 +151,15 @@
 init(""),
 };
 
+opt ClangTidyConfig{
+"clang-tidy-config",
+cat(Features),
+desc("Specifies a YAML/JSON configuration for when running clang-tidy "
+ "checks (this will override clang-tidy files). Only meaningful when "
+ "-clang-tidy flag is on"),
+init(""),
+};
+
 opt CodeCompletionParse{
 "completion-parse",
 cat(Features),
@@ -716,10 +725,24 @@
 tidy::ClangTidyOptions OverrideClangTidyOptions;
 if (!ClangTidyChecks.empty())
   

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272034.
njames93 added a comment.

Add documentation about the include style optione


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.crbegin(), E = Numbers.crend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+
+  // Ensure these bad loops aren't transformed.
+  for (auto I = Numbers.rbegin(), E = Numbers.end(); I != E; ++I) {
+observe(*I);
+  }
+  for (auto I = Numbers.begin(), E 

[PATCH] D81923: [clang-tidy] Add modernize-use-ranges check.

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272033.
njames93 added a comment.

- Updated Docs and set HandleReverseRanges default to false


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81923

Files:
  clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-ranges.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/algorithm
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/execution
  clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/vector
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
@@ -0,0 +1,135 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- --config="{CheckOptions: [ \
+// RUN: {key: modernize-use-ranges.HandleReverseRanges, value: true}]}" \
+// RUN: -- -isystem %S/Inputs/modernize-use-ranges
+
+// Ensure no warnings are generated when not in c++20 mode
+// RUN: clang-tidy %s -checks=-*,modernize-use-ranges --warnings-as-errors=modernize-use-ranges -- -nostdinc++ -std=c++17 -isystem %S/Inputs/modernize-use-ranges
+
+#include 
+#include 
+#include 
+// CHECK-FIXES: #include 
+
+template 
+class smart_pointer {
+public:
+  T *();
+  T *operator->();
+};
+
+void goodBeginEndCalls(const std::vector ) {
+  std::find(Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(Vec.cbegin(), Vec.cend(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::begin(Vec), std::end(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::cbegin(Vec), std::cend(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::execution::parallel_policy(), Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+
+  // CHECK-FIXES:  std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(std::execution::parallel_policy(), Vec, 1);
+  // CHECK-FIXES-NEXT: //
+}
+
+void badBeginEndCalls(const std::vector ,
+  const std::vector ) {
+  // end, begin.
+  std::find(Vec.end(), Vec.begin(), 1);
+  std::find(Vec.cend(), Vec.cbegin(), 1);
+  std::find(std::end(Vec), std::begin(Vec), 1);
+  std::find(std::cend(Vec), std::cbegin(Vec), 1);
+
+  // begin, begin.
+  std::find(Vec.begin(), Vec.begin(), 1);
+  // end, end.
+  std::find(Vec.end(), Vec.end(), 1);
+
+  // Different containers, definitely bad, but not what this check is for.
+  std::find(Vec.begin(), Vec2.end(), 1);
+}
+
+void maybeDualArg(const std::vector , std::vector ) {
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(std::execution::sequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(std::execution::unsequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+
+  // CHECK-FIXES:  std::ranges::equal(Vec1, Vec2.begin());
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(Vec1, Vec2);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(std::execution::sequenced_policy(), Vec1, Vec2.begin());
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(std::execution::unsequenced_policy(), Vec1, Vec2);
+  // CHECK-FIXES-NEXT: //
+}
+
+void dualArg(const std::vector , const std::vector ) {
+  std::includes(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace includes with std::ranges::includes
+  std::includes(std::execution::parallel_unsequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin(), 

[PATCH] D81949: [clang-tidy] Extend InheritParentConfig to CommandLineConfig

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4836188ad9b3: [clang-tidy] Extend InheritParentConfig to 
CommandLineConfig (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D81949?vs=271134=272004#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81949

Files:
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -18,7 +18,7 @@
 // RUN: clang-tidy -dump-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD4
 // CHECK-CHILD4: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto
 // CHECK-CHILD4: - key: llvm-qualified-auto.AddConstToQualified
-// CHECK-CHILD4-NEXT: value: '1
+// CHECK-CHILD4-NEXT: value: '1'
 // CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
 // CHECK-CHILD4-NEXT: value: '20'
 // CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
@@ -30,3 +30,23 @@
 // CHECK-EXPLAIN: 'llvm-qualified-auto' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}44{{[/\\]}}.clang-tidy.
 // CHECK-EXPLAIN: 'modernize-loop-convert' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}.clang-tidy.
 // CHECK-EXPLAIN: 'modernize-use-using' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}.clang-tidy.
+
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{InheritParentConfig: true, \
+// RUN: Checks: -llvm-qualified-auto, \
+// RUN: CheckOptions: [{key: modernize-loop-convert.MaxCopySize, value: 21}]}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD5
+// CHECK-CHILD5: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto,-llvm-qualified-auto
+// CHECK-CHILD5: - key: modernize-loop-convert.MaxCopySize
+// CHECK-CHILD5-NEXT: value: '21'
+// CHECK-CHILD5: - key: modernize-loop-convert.MinConfidence
+// CHECK-CHILD5-NEXT: value: reasonable
+// CHECK-CHILD5: - key: modernize-use-using.IgnoreMacros
+// CHECK-CHILD5-NEXT: value: '0'
+
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{InheritParentConfig: false, \
+// RUN: Checks: -llvm-qualified-auto}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD6
+// CHECK-CHILD6: Checks: {{.*}}-llvm-qualified-auto
+// CHECK-CHILD6-NOT: - key: modernize-use-using.IgnoreMacros
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -310,7 +310,7 @@
   return std::make_unique(
   GlobalOptions,
   ClangTidyOptions::getDefaults().mergeWith(DefaultOptions, 0),
-  *ParsedConfig, OverrideOptions);
+  *ParsedConfig, OverrideOptions, std::move(FS));
 } else {
   llvm::errs() << "Error: invalid configuration specified.\n"
<< ParsedConfig.getError().message() << "\n";
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.h
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -121,10 +121,13 @@
   /// Add extra compilation arguments to the start of the list.
   llvm::Optional ExtraArgsBefore;
 
-  /// Only used in the FileOptionsProvider. If true, FileOptionsProvider will
-  /// take a configuration file in the parent directory (if any exists) and
-  /// apply this config file on top of the parent one. If false or missing,
-  /// only this configuration file will be used.
+  /// Only used in the FileOptionsProvider and ConfigOptionsProvider. If true
+  /// and using a FileOptionsProvider, it will take a configuration file in the
+  /// parent directory (if any exists) and apply this config file on top of the
+  /// parent one. IF true and using a ConfigOptionsProvider, it will apply this
+  /// config on top of any configuation file it finds in the directory using the
+  /// same logic as FileOptionsProvider. If false or missing, only this
+  /// configuration file will be used.
   llvm::Optional InheritParentConfig;
 
   /// Use colors in diagnostics. If missing, it will be auto detected.
@@ -180,30 +183,7 @@
   ClangTidyOptions DefaultOptions;
 };
 
-/// Implementation of ClangTidyOptions interface, which is used for
-/// '-config' command-line option.
-class ConfigOptionsProvider : 

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272030.
njames93 added a comment.

- Set and store the IncludeStyle


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.crbegin(), E = Numbers.crend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+
+  // Ensure these bad loops aren't transformed.
+  for (auto I = Numbers.rbegin(), E = Numbers.end(); I != E; ++I) {
+observe(*I);
+  }
+  for (auto I = Numbers.begin(), E = 

[PATCH] D81975: [clangd] Add command line option for ClangTidyConfig

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 abandoned this revision.
njames93 added a comment.

Abandoned in favour of the proposed clangd-config 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81975



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80202: [ASTMatchers] Performance optimization for memoization

2020-06-22 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272470.
njames93 added a comment.

Fix checks failing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80202

Files:
  clang/lib/ASTMatchers/ASTMatchFinder.cpp

Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -74,6 +74,35 @@
   }
 };
 
+/// Performance optimization for querying the memoized map without the expensive
+/// copy of the \c BoundNodesTreeBuilder and to a lesser extent the \c
+/// DynTypedNode.
+struct MatchKeyRef {
+  const DynTypedMatcher::MatcherIDType MatcherID;
+  const DynTypedNode 
+  const BoundNodesTreeBuilder 
+  const TraversalKind Traversal;
+  MatchType Type;
+
+  MatchKey toKey() const {
+return MatchKey{MatcherID, Node, BoundNodes, Traversal, Type};
+  }
+};
+
+bool operator<(const MatchKey , const MatchKeyRef ) {
+  return std::tie(LHS.Traversal, LHS.Type, LHS.MatcherID, LHS.Node,
+  LHS.BoundNodes) < std::tie(RHS.Traversal, RHS.Type,
+ RHS.MatcherID, RHS.Node,
+ RHS.BoundNodes);
+}
+
+bool operator<(const MatchKeyRef , const MatchKey ) {
+  return std::tie(LHS.Traversal, LHS.Type, LHS.MatcherID, LHS.Node,
+  LHS.BoundNodes) < std::tie(RHS.Traversal, RHS.Type,
+ RHS.MatcherID, RHS.Node,
+ RHS.BoundNodes);
+}
+
 // Used to store the result of a match and possibly bound nodes.
 struct MemoizedMatchResult {
   bool ResultOfMatch;
@@ -457,14 +486,12 @@
   return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
 Bind);
 
-MatchKey Key;
-Key.MatcherID = Matcher.getID();
-Key.Node = Node;
 // Note that we key on the bindings *before* the match.
-Key.BoundNodes = *Builder;
-Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
-Key.Type = MatchType::Descendants;
-MemoizationMap::iterator I = ResultCache.find(Key);
+MatchKeyRef KeyRef = {Matcher.getID(), Node, *Builder,
+  Ctx.getParentMapContext().getTraversalKind(),
+  MatchType::Descendants};
+
+MemoizationMap::iterator I = ResultCache.find(KeyRef);
 if (I != ResultCache.end()) {
   *Builder = I->second.Nodes;
   return I->second.ResultOfMatch;
@@ -475,11 +502,10 @@
 Result.ResultOfMatch = matchesRecursively(Node, Matcher, ,
   MaxDepth, Traversal, Bind);
 
-MemoizedMatchResult  = ResultCache[Key];
-CachedResult = std::move(Result);
-
-*Builder = CachedResult.Nodes;
-return CachedResult.ResultOfMatch;
+auto Cached = ResultCache.emplace(KeyRef.toKey(), std::move(Result));
+assert(Cached.second && "Emplace should succeed");
+*Builder = Cached.first->second.Nodes;
+return Cached.first->second.ResultOfMatch;
   }
 
   // Matches children or descendants of 'Node' with 'BaseMatcher'.
@@ -705,16 +731,14 @@
   return matchesAncestorOfRecursively(Node, Ctx, Matcher, Builder,
   MatchMode);
 
-MatchKey Key;
-Key.MatcherID = Matcher.getID();
-Key.Node = Node;
-Key.BoundNodes = *Builder;
-Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
-Key.Type = MatchType::Ancestors;
+// Note that we key on the bindings *before* the match.
+MatchKeyRef KeyRef = {Matcher.getID(), Node, *Builder,
+  Ctx.getParentMapContext().getTraversalKind(),
+  MatchType::Ancestors};
 
 // Note that we cannot use insert and reuse the iterator, as recursive
 // calls to match might invalidate the result cache iterators.
-MemoizationMap::iterator I = ResultCache.find(Key);
+MemoizationMap::iterator I = ResultCache.find(KeyRef);
 if (I != ResultCache.end()) {
   *Builder = I->second.Nodes;
   return I->second.ResultOfMatch;
@@ -725,11 +749,10 @@
 Result.ResultOfMatch = matchesAncestorOfRecursively(
 Node, Ctx, Matcher, , MatchMode);
 
-MemoizedMatchResult  = ResultCache[Key];
-CachedResult = std::move(Result);
-
-*Builder = CachedResult.Nodes;
-return CachedResult.ResultOfMatch;
+auto Cached = ResultCache.emplace(KeyRef.toKey(), std::move(Result));
+assert(Cached.second && "Emplace should succeed");
+*Builder = Cached.first->second.Nodes;
+return Cached.first->second.ResultOfMatch;
   }
 
   bool matchesAncestorOfRecursively(const DynTypedNode , ASTContext ,
@@ -878,7 +901,7 @@
   CompatibleAliases;
 
   // Maps (matcher, node) -> the match result for memoization.
-  typedef std::map MemoizationMap;
+  typedef std::map> MemoizationMap;
   

[PATCH] D81932: [clang-tidy] Improved accuracy of check list updater script

2020-06-22 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG23063296b539: [clang-tidy] Improved accuracy of check list 
updater script (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81932

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
  clang-tools-extra/docs/clang-tidy/checks/list.rst

Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -133,6 +133,7 @@
`clang-analyzer-valist.Uninitialized `_,
`clang-analyzer-valist.Unterminated `_,
`cppcoreguidelines-avoid-goto `_,
+   `cppcoreguidelines-avoid-non-const-global-variables `_,
`cppcoreguidelines-init-variables `_, "Yes"
`cppcoreguidelines-interfaces-global-init `_,
`cppcoreguidelines-macro-usage `_,
@@ -189,7 +190,7 @@
`llvm-prefer-isa-or-dyn-cast-in-conditionals `_, "Yes"
`llvm-prefer-register-over-unsigned `_, "Yes"
`llvm-twine-local `_, "Yes"
-   `llvmlibc-callee-namespace `_,
+   `llvmlibc-callee-namespace `_,
`llvmlibc-implementation-in-namespace `_,
`llvmlibc-restrict-system-libc-headers `_, "Yes"
`misc-definitions-in-headers `_, "Yes"
@@ -291,7 +292,7 @@
`readability-redundant-member-init `_, "Yes"
`readability-redundant-preprocessor `_,
`readability-redundant-smartptr-get `_, "Yes"
-   `readability-redundant-string-cstr `_,
+   `readability-redundant-string-cstr `_, "Yes"
`readability-redundant-string-init `_, "Yes"
`readability-simplify-boolean-expr `_, "Yes"
`readability-simplify-subscript-expr `_, "Yes"
@@ -300,7 +301,7 @@
`readability-string-compare `_, "Yes"
`readability-uniqueptr-delete-release `_, "Yes"
`readability-uppercase-literal-suffix `_, "Yes"
-   `readability-use-anyofallof`_, "No"
+   `readability-use-anyofallof `_,
`zircon-temporary-objects `_,
 
 
@@ -390,7 +391,6 @@
`clang-analyzer-unix.cstring.NullArg `_, `Clang Static Analyzer `_,
`cppcoreguidelines-avoid-c-arrays `_, `modernize-avoid-c-arrays `_,
`cppcoreguidelines-avoid-magic-numbers `_, `readability-magic-numbers `_,
-   `cppcoreguidelines-avoid-non-const-global-variables `_, , , ""
`cppcoreguidelines-c-copy-assignment-signature `_, `misc-unconventional-assign-operator `_,
`cppcoreguidelines-explicit-virtual-functions `_, `modernize-use-override `_, "Yes"
`cppcoreguidelines-non-private-member-variables-in-classes `_, `misc-non-private-member-variables-in-classes `_,
@@ -410,7 +410,7 @@
`hicpp-new-delete-operators `_, `misc-new-delete-overloads `_,
`hicpp-no-array-decay `_, `cppcoreguidelines-pro-bounds-array-to-pointer-decay `_,
`hicpp-no-malloc `_, `cppcoreguidelines-no-malloc `_,
-   `hicpp-noexcept-move `_, `performance-noexcept-move-constructor `_,
+   `hicpp-noexcept-move `_, `performance-noexcept-move-constructor `_, "Yes"
`hicpp-special-member-functions `_, `cppcoreguidelines-special-member-functions `_,
`hicpp-static-assert `_, `misc-static-assert `_, "Yes"
`hicpp-undelegated-constructor `_, `bugprone-undelegated-constructor `_,
@@ -424,4 +424,3 @@
`hicpp-use-override `_, `modernize-use-override `_, "Yes"
`hicpp-vararg `_, `cppcoreguidelines-pro-type-vararg `_,
`llvm-qualified-auto `_, `readability-qualified-auto `_, "Yes"
-
Index: clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
@@ -8,6 +8,9 @@
 
 #include "MakeSharedCheck.h"
 
+// FixItHint - Hint to check documentation script to mark this check as
+// providing a FixIt.
+
 using namespace clang::ast_matchers;
 
 namespace clang {
Index: clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
+++ clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
@@ -12,6 +12,9 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 
+// FixItHint - Hint to check documentation script to mark this check as
+// providing a FixIt.
+
 namespace clang {
 namespace tidy {
 namespace llvm_libc {
Index: clang-tools-extra/clang-tidy/add_new_check.py
===
--- clang-tools-extra/clang-tidy/add_new_check.py
+++ 

[PATCH] D80202: [ASTMatchers] Performance optimization for memoization

2020-06-22 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272433.
njames93 added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80202

Files:
  clang/lib/ASTMatchers/ASTMatchFinder.cpp

Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -74,6 +74,35 @@
   }
 };
 
+/// Performance optimization for querying the memoized map without the expensive
+/// copy of the \c BoundNodesTreeBuilder and to a lesser extent the \c
+/// DynTypedNode.
+struct MatchKeyRef {
+  const DynTypedMatcher::MatcherIDType MatcherID;
+  const DynTypedNode 
+  const BoundNodesTreeBuilder 
+  const TraversalKind Traversal;
+  MatchType Type;
+
+  MatchKey toKey() const {
+return MatchKey{MatcherID, Node, BoundNodes, Traversal, Type};
+  }
+};
+
+bool operator<(const MatchKey , const MatchKeyRef ) {
+  return std::tie(LHS.Traversal, LHS.Type, LHS.MatcherID, LHS.Node,
+  LHS.BoundNodes) < std::tie(RHS.Traversal, RHS.Type,
+ RHS.MatcherID, RHS.Node,
+ RHS.BoundNodes);
+}
+
+bool operator<(const MatchKeyRef , const MatchKey ) {
+  return std::tie(LHS.Traversal, LHS.Type, LHS.MatcherID, LHS.Node,
+  LHS.BoundNodes) < std::tie(RHS.Traversal, RHS.Type,
+ RHS.MatcherID, RHS.Node,
+ RHS.BoundNodes);
+}
+
 // Used to store the result of a match and possibly bound nodes.
 struct MemoizedMatchResult {
   bool ResultOfMatch;
@@ -457,14 +486,11 @@
   return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
 Bind);
 
-MatchKey Key;
-Key.MatcherID = Matcher.getID();
-Key.Node = Node;
 // Note that we key on the bindings *before* the match.
-Key.BoundNodes = *Builder;
-Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
-Key.Type = MatchType::Descendants;
-MemoizationMap::iterator I = ResultCache.find(Key);
+MatchKeyRef KeyRef = {Matcher.getID(), Node, *Builder,
+  Ctx.getParentMapContext().getTraversalKind()};
+
+MemoizationMap::iterator I = ResultCache.find(KeyRef);
 if (I != ResultCache.end()) {
   *Builder = I->second.Nodes;
   return I->second.ResultOfMatch;
@@ -475,11 +501,10 @@
 Result.ResultOfMatch = matchesRecursively(Node, Matcher, ,
   MaxDepth, Traversal, Bind);
 
-MemoizedMatchResult  = ResultCache[Key];
-CachedResult = std::move(Result);
-
-*Builder = CachedResult.Nodes;
-return CachedResult.ResultOfMatch;
+auto Cached = ResultCache.emplace(KeyRef.toKey(), std::move(Result));
+assert(Cached.second && "Emplace should succeed");
+*Builder = Cached.first->second.Nodes;
+return Cached.first->second.ResultOfMatch;
   }
 
   // Matches children or descendants of 'Node' with 'BaseMatcher'.
@@ -705,16 +730,13 @@
   return matchesAncestorOfRecursively(Node, Ctx, Matcher, Builder,
   MatchMode);
 
-MatchKey Key;
-Key.MatcherID = Matcher.getID();
-Key.Node = Node;
-Key.BoundNodes = *Builder;
-Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
-Key.Type = MatchType::Ancestors;
+// Note that we key on the bindings *before* the match.
+MatchKeyRef KeyRef = {Matcher.getID(), Node, *Builder,
+  Ctx.getParentMapContext().getTraversalKind()};
 
 // Note that we cannot use insert and reuse the iterator, as recursive
 // calls to match might invalidate the result cache iterators.
-MemoizationMap::iterator I = ResultCache.find(Key);
+MemoizationMap::iterator I = ResultCache.find(KeyRef);
 if (I != ResultCache.end()) {
   *Builder = I->second.Nodes;
   return I->second.ResultOfMatch;
@@ -725,11 +747,10 @@
 Result.ResultOfMatch = matchesAncestorOfRecursively(
 Node, Ctx, Matcher, , MatchMode);
 
-MemoizedMatchResult  = ResultCache[Key];
-CachedResult = std::move(Result);
-
-*Builder = CachedResult.Nodes;
-return CachedResult.ResultOfMatch;
+auto Cached = ResultCache.emplace(KeyRef.toKey(), std::move(Result));
+assert(Cached.second && "Emplace should succeed");
+*Builder = Cached.first->second.Nodes;
+return Cached.first->second.ResultOfMatch;
   }
 
   bool matchesAncestorOfRecursively(const DynTypedNode , ASTContext ,
@@ -878,7 +899,7 @@
   CompatibleAliases;
 
   // Maps (matcher, node) -> the match result for memoization.
-  typedef std::map MemoizationMap;
+  typedef std::map> MemoizationMap;
   MemoizationMap ResultCache;
 };
 
___
cfe-commits mailing list

[PATCH] D82162: [clang-tidy] RenamerClangTidy wont emit fixes in scratch space

2020-06-22 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6ae0f5f3e1d4: [clang-tidy] RenamerClangTidy wont emit fixes 
in scratch space (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82162

Files:
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -562,3 +562,19 @@
 }
 
 } // namespace redecls
+
+namespace scratchspace {
+#define DUP(Tok) Tok
+#define M1(Tok) DUP(badName##Tok())
+
+// We don't want a warning here as the call to this in Foo is in a scratch
+// buffer so its fix-it wouldn't be applied, resulting in invalid code.
+void badNameWarn();
+
+void Foo() {
+  M1(Warn);
+}
+
+#undef M1
+#undef DUP
+} // namespace scratchspace
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -156,14 +156,17 @@
   // is already in there
   RenamerClangTidyCheck::NamingCheckFailure  =
   NamingCheckFailures[Decl];
-  if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
-return;
 
   if (!Failure.ShouldFix())
 return;
 
+  if (SourceMgr && SourceMgr->isWrittenInScratchSpace(FixLocation))
+Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
+
   if (!utils::rangeCanBeFixed(Range, SourceMgr))
 Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
+
+  Failure.RawUsageLocs.insert(FixLocation.getRawEncoding());
 }
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
@@ -248,13 +251,15 @@
   if (const auto *Decl =
   Result.Nodes.getNodeAs("classRef")) {
 
-addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange());
+addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange(),
+ Result.SourceManager);
 
 for (const auto *Init : Decl->inits()) {
   if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
   if (const FieldDecl *FD = Init->getAnyMember())
-addUsage(FD, SourceRange(Init->getMemberLocation()));
+addUsage(FD, SourceRange(Init->getMemberLocation()),
+ Result.SourceManager);
   // Note: delegating constructors and base class initializers are handled
   // via the "typeLoc" matcher.
 }
@@ -271,7 +276,7 @@
 // we want instead to replace the next token, that will be the identifier.
 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
 
-addUsage(Decl->getParent(), Range);
+addUsage(Decl->getParent(), Range, Result.SourceManager);
 return;
   }
 
@@ -289,7 +294,7 @@
 // further TypeLocs handled below
 
 if (Decl) {
-  addUsage(Decl, Loc->getSourceRange());
+  addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
 
@@ -300,7 +305,7 @@
   SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
   if (const auto *ClassDecl = dyn_cast(Decl)) {
 if (const NamedDecl *TemplDecl = ClassDecl->getTemplatedDecl())
-  addUsage(TemplDecl, Range);
+  addUsage(TemplDecl, Range, Result.SourceManager);
 return;
   }
 }
@@ -308,7 +313,7 @@
 if (const auto  =
 Loc->getAs()) {
   if (const TagDecl *Decl = Ref.getTypePtr()->getAsTagDecl())
-addUsage(Decl, Loc->getSourceRange());
+addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
   }
@@ -317,7 +322,7 @@
   Result.Nodes.getNodeAs("nestedNameLoc")) {
 if (const NestedNameSpecifier *Spec = Loc->getNestedNameSpecifier()) {
   if (const NamespaceDecl *Decl = Spec->getAsNamespace()) {
-addUsage(Decl, Loc->getLocalSourceRange());
+addUsage(Decl, Loc->getLocalSourceRange(), Result.SourceManager);
 return;
   }
 }
@@ -325,7 +330,8 @@
 
   if (const auto *Decl = Result.Nodes.getNodeAs("using")) {
 for (const auto *Shadow : Decl->shadows())
-  addUsage(Shadow->getTargetDecl(), Decl->getNameInfo().getSourceRange());
+  addUsage(Shadow->getTargetDecl(), Decl->getNameInfo().getSourceRange(),
+   Result.SourceManager);
 return;
   }
 
@@ -371,14 +377,14 @@
 // Fix using namespace declarations.
 if (const auto *UsingNS = dyn_cast(Decl))
   addUsage(UsingNS->getNominatedNamespaceAsWritten(),
-   

[PATCH] D82281: [clang-tidy] llvm-twine-local ignores parameters

2020-06-22 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9a8b04114480: [clang-tidy] llvm-twine-local ignores 
parameters (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82281

Files:
  clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
@@ -13,6 +13,7 @@
 using namespace llvm;
 
 void foo(const Twine );
+void bar(Twine x);
 
 static Twine Moo = Twine("bark") + "bah";
 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: twine variables are prone to 
use-after-free bugs
Index: clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -19,8 +19,10 @@
 
 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
   auto TwineType =
-  qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine";
-  Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
+  qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine";
+  Finder->addMatcher(
+  varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
+  this);
 }
 
 void TwineLocalCheck::check(const MatchFinder::MatchResult ) {


Index: clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
@@ -13,6 +13,7 @@
 using namespace llvm;
 
 void foo(const Twine );
+void bar(Twine x);
 
 static Twine Moo = Twine("bark") + "bah";
 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: twine variables are prone to use-after-free bugs
Index: clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -19,8 +19,10 @@
 
 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
   auto TwineType =
-  qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine";
-  Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
+  qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine";
+  Finder->addMatcher(
+  varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
+  this);
 }
 
 void TwineLocalCheck::check(const MatchFinder::MatchResult ) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272306.
njames93 added a comment.

Update doc comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -6,6 +6,20 @@
 
 namespace clang {
 namespace tidy {
+
+enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
+
+template <> struct OptionEnumMapping {
+  static llvm::ArrayRef> getEnumMapping() {
+static constexpr std::pair Mapping[] = {
+{Colours::Red, "Red"},   {Colours::Orange, "Orange"},
+{Colours::Yellow, "Yellow"}, {Colours::Green, "Green"},
+{Colours::Blue, "Blue"}, {Colours::Indigo, "Indigo"},
+{Colours::Violet, "Violet"}};
+return makeArrayRef(Mapping);
+  }
+};
+
 namespace test {
 
 TEST(ParseLineFilter, EmptyFilter) {
@@ -209,15 +223,6 @@
 }
 
 TEST(ValidConfiguration, ValidEnumOptions) {
-
-  enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
-  static constexpr std::pair Mapping[] = {
-  {"Red", Colours::Red},   {"Orange", Colours::Orange},
-  {"Yellow", Colours::Yellow}, {"Green", Colours::Green},
-  {"Blue", Colours::Blue}, {"Indigo", Colours::Indigo},
-  {"Violet", Colours::Violet}};
-  static const auto Map = makeArrayRef(Mapping);
-
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
 
@@ -237,29 +242,30 @@
 #define CHECK_ERROR_ENUM(Name, Expected)   \
   CHECK_ERROR(Name, UnparseableEnumOptionError, Expected)
 
-  CHECK_VAL(TestCheck.getLocal("Valid", Map), Colours::Red);
-  CHECK_VAL(TestCheck.getGlobal("GlobalValid", Map), Colours::Violet);
-  CHECK_VAL(TestCheck.getLocal("ValidWrongCase", Map, /*IgnoreCase*/ true),
-Colours::Red);
+  CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
   CHECK_VAL(
-  TestCheck.getGlobal("GlobalValidWrongCase", Map, /*IgnoreCase*/ true),
-  Colours::Violet);
-  CHECK_ERROR_ENUM(TestCheck.getLocal("Invalid", Map),
+  TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
+  Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
+/*IgnoreCase*/ true),
+Colours::Violet);
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("Invalid"),
"invalid configuration value "
"'Scarlet' for option 'test.Invalid'");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("ValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("ValidWrongCase"),
"invalid configuration value 'rED' for option "
"'test.ValidWrongCase'; did you mean 'Red'?");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("NearMiss", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("NearMiss"),
"invalid configuration value 'Oragne' for option "
"'test.NearMiss'; did you mean 'Orange'?");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalInvalid", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalInvalid"),
"invalid configuration value "
"'Purple' for option 'GlobalInvalid'");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalValidWrongCase"),
"invalid configuration value 'vIOLET' for option "
  

[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh, gribozavr2.
Herald added subscribers: cfe-commits, arphaman, kbarton, xazax.hun, nemanjai.
Herald added a project: clang.

Following on from D77085 , I was never happy 
with the passing a mapping to the option get/store functions. This patch 
addresses this by using explicit specializations to handle the serializing and 
deserializing of enum options.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82188

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -6,6 +6,20 @@
 
 namespace clang {
 namespace tidy {
+
+enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
+
+template <> struct OptionEnumMapping {
+  static llvm::ArrayRef> getEnumMapping() {
+static constexpr std::pair Mapping[] = {
+{Colours::Red, "Red"},   {Colours::Orange, "Orange"},
+{Colours::Yellow, "Yellow"}, {Colours::Green, "Green"},
+{Colours::Blue, "Blue"}, {Colours::Indigo, "Indigo"},
+{Colours::Violet, "Violet"}};
+return makeArrayRef(Mapping);
+  }
+};
+
 namespace test {
 
 TEST(ParseLineFilter, EmptyFilter) {
@@ -209,15 +223,6 @@
 }
 
 TEST(ValidConfiguration, ValidEnumOptions) {
-
-  enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
-  static constexpr std::pair Mapping[] = {
-  {"Red", Colours::Red},   {"Orange", Colours::Orange},
-  {"Yellow", Colours::Yellow}, {"Green", Colours::Green},
-  {"Blue", Colours::Blue}, {"Indigo", Colours::Indigo},
-  {"Violet", Colours::Violet}};
-  static const auto Map = makeArrayRef(Mapping);
-
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
 
@@ -237,29 +242,30 @@
 #define CHECK_ERROR_ENUM(Name, Expected)   \
   CHECK_ERROR(Name, UnparseableEnumOptionError, Expected)
 
-  CHECK_VAL(TestCheck.getLocal("Valid", Map), Colours::Red);
-  CHECK_VAL(TestCheck.getGlobal("GlobalValid", Map), Colours::Violet);
-  CHECK_VAL(TestCheck.getLocal("ValidWrongCase", Map, /*IgnoreCase*/ true),
-Colours::Red);
+  CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
   CHECK_VAL(
-  TestCheck.getGlobal("GlobalValidWrongCase", Map, /*IgnoreCase*/ true),
-  Colours::Violet);
-  CHECK_ERROR_ENUM(TestCheck.getLocal("Invalid", Map),
+  TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
+  Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
+/*IgnoreCase*/ true),
+Colours::Violet);
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("Invalid"),
"invalid configuration value "
"'Scarlet' for option 'test.Invalid'");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("ValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("ValidWrongCase"),
"invalid configuration value 'rED' for option "
"'test.ValidWrongCase'; did you mean 'Red'?");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("NearMiss", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("NearMiss"),
"invalid configuration value 'Oragne' for option "
"'test.NearMiss'; did you mean 'Orange'?");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalInvalid", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalInvalid"),
"invalid 

[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.
Herald added a subscriber: wuzish.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp:30
   Options.store(Opts, "GslHeader", GslHeader);
   Options.store(Opts, "IncludeStyle", IncludeStyle);
 }

As a side bonus, this originally incorrect code would cast IncludeStyle to an 
int, then store that value. Now it will store it as the correct enum. Any other 
enums passed to store will error out if there is no mapping specialization for 
them, forcing you to either declare the mapping or cast it to an integer type


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81769: [clang-tidy] Repair various issues with modernize-avoid-bind

2020-06-23 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp:243
+  if ((std::distance(ME->child_begin(), ME->child_end()) == 1) &&
+  isa(*ME->children().begin())) {
+// reference to data member without explicit "this"

jaafar wrote:
> aaron.ballman wrote:
> > jaafar wrote:
> > > Is there a better way to express this? "a single child of type ThisExpr" 
> > > was what I was going for...
> > `if (isa(ME->getBase()))` -- `MemberExpr::children()` only 
> > considers the base anyway, so there's only ever one child node to begin 
> > with.
> Could there be zero? I'm just worried about dereferencing 
> `ME->children().begin()` before verifying there is at least one...
> 
The child nodes in `MemberExpr` just point to one node, its base, which should 
never be null. Is it not simpler to just use this?
```
if (isa(ME->getBase())) {
```


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

https://reviews.llvm.org/D81769



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82626: [CodeComplete] Tweak completion for else.

2020-06-26 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: sammccall, kadircet.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If an `if` statement uses braces for its `then` block, suggest braces for the 
`else` and `else if` completion blocks, Otherwise don't suggest them.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82626

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaCodeComplete.cpp

Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5743,7 +5743,7 @@
   CodeCompleteExpression(S, Data);
 }
 
-void Sema::CodeCompleteAfterIf(Scope *S) {
+void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
 CodeCompleter->getCodeCompletionTUInfo(),
 mapCodeCompletionContext(*this, PCC_Statement));
@@ -5760,15 +5760,28 @@
   // "else" block
   CodeCompletionBuilder Builder(Results.getAllocator(),
 Results.getCodeCompletionTUInfo());
+
+  auto AddCodePatterns = [&] {
+if (IsBracedThen) {
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
+  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+  Builder.AddPlaceholderChunk("statements");
+  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+} else {
+  // HorizontalSpace so the hint looks like 'else statement' instead of
+  // 'elsestatement'.
+  // FIXME, would be nicer if there was a CK_IndentationSpace option that
+  // would add the correct number of tabs/spaces.
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+  Builder.AddPlaceholderChunk("statement");
+}
+  };
   Builder.AddTypedTextChunk("else");
-  if (Results.includeCodePatterns()) {
-Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
-Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
-Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-Builder.AddPlaceholderChunk("statements");
-Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-Builder.AddChunk(CodeCompletionString::CK_RightBrace);
-  }
+  if (Results.includeCodePatterns())
+AddCodePatterns();
   Results.AddResult(Builder.TakeString());
 
   // "else if" block
@@ -5781,12 +5794,7 @@
 Builder.AddPlaceholderChunk("expression");
   Builder.AddChunk(CodeCompletionString::CK_RightParen);
   if (Results.includeCodePatterns()) {
-Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
-Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
-Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-Builder.AddPlaceholderChunk("statements");
-Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+AddCodePatterns();
   }
   Results.AddResult(Builder.TakeString());
 
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -1348,6 +1348,8 @@
   if (IsConstexpr)
 ConstexprCondition = Cond.getKnownValue();
 
+  bool IsBracedThen = Tok.is(tok::l_brace);
+
   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
   // there is no compound stmt.  C90 does not have this clause.  We only do this
   // if the body isn't a compound statement to avoid push/pop in common cases.
@@ -1366,7 +1368,7 @@
   //would have to notify ParseStatement not to create a new scope. It's
   //simpler to let it create a new scope.
   //
-  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
+  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
 
   MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
 
@@ -1427,7 +1429,7 @@
 // Pop the 'else' scope if needed.
 InnerScope.Exit();
   } else if (Tok.is(tok::code_completion)) {
-Actions.CodeCompleteAfterIf(getCurScope());
+Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
 cutOffParsing();
 return StmtError();
   } else if (InnerStatementTrailingElseLoc.isValid()) {
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -11922,7 +11922,7 @@
   void CodeCompleteDesignator(const QualType BaseType,
   llvm::ArrayRef InitExprs,
   const Designation );
-  void CodeCompleteAfterIf(Scope *S);
+  void CodeCompleteAfterIf(Scope *S, bool 

[PATCH] D82661: [clang-tidy][NFC} Remove unnecessary includes throughout clang-tidy header files

2020-06-26 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 273792.
njames93 added a comment.
Herald added subscribers: usaxena95, kadircet, jkorous.

Fix some issues with tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82661

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/ClangTidyModule.cpp
  clang-tools-extra/clang-tidy/ClangTidyModule.h
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/ClangTidyProfiling.h
  clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationUnnecessaryConversionCheck.h
  clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.h
  clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h
  clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.h
  clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h
  clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h
  clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.h
  
clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
  
clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InterfacesGlobalInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NoMallocCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeConstCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeReinterpretCastCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
  clang-tools-extra/clang-tidy/fuchsia/DefaultArgumentsDeclarationsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidUnderscoreInGoogletestNameCheck.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h
  clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.h
  

[PATCH] D82706: [ASTMatchers] Enhanced support for matchers taking Regex arguments

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 273960.
njames93 added a comment.

Moved the code to build and verify the regex out of the macro


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82706

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/tools/dump_ast_matchers.py
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/include/clang/ASTMatchers/ASTMatchersMacros.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
  clang/lib/ASTMatchers/Dynamic/Marshallers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
  clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
  llvm/include/llvm/Support/Regex.h
  llvm/lib/Support/Regex.cpp

Index: llvm/lib/Support/Regex.cpp
===
--- llvm/lib/Support/Regex.cpp
+++ llvm/lib/Support/Regex.cpp
@@ -26,7 +26,7 @@
 
 Regex::Regex() : preg(nullptr), error(REG_BADPAT) {}
 
-Regex::Regex(StringRef regex, unsigned Flags) {
+Regex::Regex(StringRef regex, RegexFlags Flags) {
   unsigned flags = 0;
   preg = new llvm_regex();
   preg->re_endp = regex.end();
@@ -39,6 +39,9 @@
   error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
 }
 
+Regex::Regex(StringRef regex, unsigned Flags)
+: Regex(regex, static_cast(Flags)) {}
+
 Regex::Regex(Regex &) {
   preg = regex.preg;
   error = regex.error;
Index: llvm/include/llvm/Support/Regex.h
===
--- llvm/include/llvm/Support/Regex.h
+++ llvm/include/llvm/Support/Regex.h
@@ -16,6 +16,7 @@
 #ifndef LLVM_SUPPORT_REGEX_H
 #define LLVM_SUPPORT_REGEX_H
 
+#include "llvm/ADT/BitmaskEnum.h"
 #include 
 
 struct llvm_regex;
@@ -26,20 +27,22 @@
 
   class Regex {
   public:
-enum {
-  NoFlags=0,
+enum RegexFlags : unsigned {
+  NoFlags = 0,
   /// Compile for matching that ignores upper/lower case distinctions.
-  IgnoreCase=1,
+  IgnoreCase = 1,
   /// Compile for newline-sensitive matching. With this flag '[^' bracket
   /// expressions and '.' never match newline. A ^ anchor matches the
   /// null string after any newline in the string in addition to its normal
   /// function, and the $ anchor matches the null string before any
   /// newline in the string in addition to its normal function.
-  Newline=2,
+  Newline = 2,
   /// By default, the POSIX extended regular expression (ERE) syntax is
   /// assumed. Pass this flag to turn on basic regular expressions (BRE)
   /// instead.
-  BasicRegex=4
+  BasicRegex = 4,
+
+  LLVM_MARK_AS_BITMASK_ENUM(BasicRegex)
 };
 
 Regex();
@@ -47,7 +50,8 @@
 ///
 /// \param Regex - referenced string is no longer needed after this
 /// constructor does finish.  Only its compiled form is kept stored.
-Regex(StringRef Regex, unsigned Flags = NoFlags);
+Regex(StringRef Regex, RegexFlags Flags = NoFlags);
+Regex(StringRef Regex, unsigned Flags);
 Regex(const Regex &) = delete;
 Regex =(Regex regex) {
   std::swap(preg, regex.preg);
Index: clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
===
--- clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -259,6 +259,15 @@
   EXPECT_TRUE(matches("unsigned X = sizeof(int);", MStmt));
   EXPECT_FALSE(matches("unsigned X = alignof(int);", MStmt));
 
+  Code =
+  R"query(namedDecl(matchesName("^::[ABC]*$", "IgnoreCase | BasicRegex")))query";
+  llvm::Optional MatchesName(
+  Parser::parseMatcherExpression(Code, nullptr, nullptr, ));
+  EXPECT_EQ("", Error.toStringFull());
+  M = MatchesName->unconditionalConvertTo();
+  EXPECT_TRUE(matches("unsigned AAACCBB;", M));
+  EXPECT_TRUE(matches("unsigned aaaccbb;", M));
+
   Code = "hasInitializer(\nbinaryOperator(hasLHS(\"A\")))";
   EXPECT_TRUE(!Parser::parseMatcherExpression(Code, ).hasValue());
   EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
@@ -348,6 +357,26 @@
 "1:14: Incorrect type for arg 1. (Expected = string) != (Actual = "
 "String)",
 ParseMatcherWithError(R"query(decl(hasAttr("unrelated")))query"));
+  EXPECT_EQ("1:1: Error parsing argument 1 for matcher namedDecl.\n"
+"1:11: Error building matcher matchesName.\n"
+"1:33: Incorrect type for arg 2. (Expected = string) != (Actual = "
+"String)",
+ParseMatcherWithError(
+R"query(namedDecl(matchesName("[ABC]*", "Ignorecase")))query"));
+  EXPECT_EQ(
+  "1:1: Error parsing argument 1 for matcher namedDecl.\n"
+  "1:11: Error building matcher matchesName.\n"
+  "1:33: Incorrect type for arg 2. (Expected = string) != 

[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb9306fd042ce: [clang-tidy] Reworked enum options 
handling(again) (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -6,6 +6,20 @@
 
 namespace clang {
 namespace tidy {
+
+enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
+
+template <> struct OptionEnumMapping {
+  static llvm::ArrayRef> getEnumMapping() {
+static constexpr std::pair Mapping[] = {
+{Colours::Red, "Red"},   {Colours::Orange, "Orange"},
+{Colours::Yellow, "Yellow"}, {Colours::Green, "Green"},
+{Colours::Blue, "Blue"}, {Colours::Indigo, "Indigo"},
+{Colours::Violet, "Violet"}};
+return makeArrayRef(Mapping);
+  }
+};
+
 namespace test {
 
 TEST(ParseLineFilter, EmptyFilter) {
@@ -209,15 +223,6 @@
 }
 
 TEST(ValidConfiguration, ValidEnumOptions) {
-
-  enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
-  static constexpr std::pair Mapping[] = {
-  {"Red", Colours::Red},   {"Orange", Colours::Orange},
-  {"Yellow", Colours::Yellow}, {"Green", Colours::Green},
-  {"Blue", Colours::Blue}, {"Indigo", Colours::Indigo},
-  {"Violet", Colours::Violet}};
-  static const auto Map = makeArrayRef(Mapping);
-
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
 
@@ -237,29 +242,30 @@
 #define CHECK_ERROR_ENUM(Name, Expected)   \
   CHECK_ERROR(Name, UnparseableEnumOptionError, Expected)
 
-  CHECK_VAL(TestCheck.getLocal("Valid", Map), Colours::Red);
-  CHECK_VAL(TestCheck.getGlobal("GlobalValid", Map), Colours::Violet);
-  CHECK_VAL(TestCheck.getLocal("ValidWrongCase", Map, /*IgnoreCase*/ true),
-Colours::Red);
+  CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
   CHECK_VAL(
-  TestCheck.getGlobal("GlobalValidWrongCase", Map, /*IgnoreCase*/ true),
-  Colours::Violet);
-  CHECK_ERROR_ENUM(TestCheck.getLocal("Invalid", Map),
+  TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
+  Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
+/*IgnoreCase*/ true),
+Colours::Violet);
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("Invalid"),
"invalid configuration value "
"'Scarlet' for option 'test.Invalid'");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("ValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("ValidWrongCase"),
"invalid configuration value 'rED' for option "
"'test.ValidWrongCase'; did you mean 'Red'?");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("NearMiss", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("NearMiss"),
"invalid configuration value 'Oragne' for option "
"'test.NearMiss'; did you mean 'Orange'?");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalInvalid", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalInvalid"),
"invalid configuration value "
"'Purple' for option 'GlobalInvalid'");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalValidWrongCase"),
  

[PATCH] D82720: [clang-tidy] performance-faster-string-find string-view

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2, sbenza, alexfh.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Extend the default string like classes to include `std::basic_string_view`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82720

Files:
  clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
  clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp
@@ -1,7 +1,8 @@
-// RUN: %check_clang_tidy %s performance-faster-string-find %t -- \
+// RUN: %check_clang_tidy %s performance-faster-string-find %t
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s performance-faster-string-find %t -- \
 // RUN:   -config="{CheckOptions: \
 // RUN: [{key: performance-faster-string-find.StringLikeClasses, \
-// RUN:   value: 'std::basic_string; ::llvm::StringRef;'}]}" --
+// RUN:   value: '::llvm::StringRef;'}]}"
 
 namespace std {
 template 
@@ -17,6 +18,20 @@
 
 typedef basic_string string;
 typedef basic_string wstring;
+
+template 
+struct basic_string_view {
+  int find(const Char *, int = 0) const;
+  int find(const Char *, int, int) const;
+  int rfind(const Char *) const;
+  int find_first_of(const Char *) const;
+  int find_first_not_of(const Char *) const;
+  int find_last_of(const Char *) const;
+  int find_last_not_of(const Char *) const;
+};
+
+typedef basic_string_view string_view;
+typedef basic_string_view wstring_view;
 }  // namespace std
 
 namespace llvm {
@@ -75,11 +90,25 @@
   // CHECK-MESSAGES: [[@LINE-1]]:13: warning: 'find' called with a string literal
   // CHECK-FIXES: Str.find(L'\x3A9');
 
+  // std::string_view and std::wstring_view should work.
+  std::string_view StrView;
+  StrView.find("n");
+  // CHECK-MESSAGES: [[@LINE-1]]:16: warning: 'find' called with a string literal
+  // CHECK-FIXES: StrView.find('n');
+  std::wstring_view WStrView;
+
+  WStrView.find(L"n");
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: 'find' called with a string literal
+  // CHECK-FIXES: WStrView.find(L'n');
+  WStrView.find(L"\x3A9");
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: 'find' called with a string literal
+  // CHECK-FIXES: WStrView.find(L'\x3A9');
+
   // Also with other types, but only if it was specified in the options.
   llvm::StringRef sr;
   sr.find("x");
-  // CHECK-MESSAGES: [[@LINE-1]]:11: warning: 'find' called with a string literal
-  // CHECK-FIXES: sr.find('x');
+  // CHECK-MESSAGES-CUSTOM: [[@LINE-1]]:11: warning: 'find' called with a string literal
+  // CHECK-FIXES-CUSTOM: sr.find('x');
   NotStringRef nsr;
   nsr.find("x");
 }
Index: clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
+++ clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
@@ -23,6 +23,6 @@
 .. option:: StringLikeClasses
 
Semicolon-separated list of names of string-like classes. By default only
-   ``std::basic_string`` is considered. The list of methods to consired is
-   fixed.
+   ``::std::basic_string`` and ``::std::basic_string_view`` are considered. 
+   The list of methods to consired is fixed.
 
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -195,6 +195,11 @@
 Changes in existing checks
 ^^
 
+- Improved :doc:'performance-faster-string-find
+  ` check.
+
+  Now checks ``std::basic_string_view`` by default.
+
 - Improved :doc:'readability-identifier-naming
   ` check.
 
Index: clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
@@ -51,7 +51,8 @@
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   StringLikeClasses(utils::options::parseStringList(
-  Options.get("StringLikeClasses", "std::basic_string"))) {}
+  Options.get("StringLikeClasses",
+  "::std::basic_string;::std::basic_string_view"))) {}
 
 void FasterStringFindCheck::storeOptions(ClangTidyOptions::OptionMap ) {
   Options.store(Opts, "StringLikeClasses",

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 273913.
njames93 added a comment.

Rebased inline with new enum handling added in D82188 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.crbegin(), E = Numbers.crend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+
+  // Ensure these bad loops aren't transformed.
+  for (auto I = Numbers.rbegin(), E = Numbers.end(); I != E; ++I) {
+observe(*I);
+ 

[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D82188#2118885 , @thakis wrote:

> It's the only change on the blame list, things pass consistently before the 
> change, and fail consistently after it.


Do you happen to have a proper build log for the failing build. That bot 
doesn't show what happened when building, in fact it says there was no work to 
do when building which seems to confuse me. My best guess for the fail is 
infrastructure related.

Edit: http://45.33.8.238/mac/16282/log.txt this is the log I want. It shows the 
failure and that this is the cause, but I'm still struggling to see what the 
actual cause is?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I've relanded this with some sanity checks in 
37cc4fa2eaa3d03ca8cd4947eb0d4c60e3c9b45c 
. If it 
fails again without those asserts I'll go back to the drawing board


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D82188#2118769 , @thakis wrote:

> This breaks chevk-clang-tools in mac: http://45.33.8.238/mac/16292/step_8.txt
>
> Please take a look and revert for now if it takes a while to fix.


Are you sure that this is the offending patch? I don't touch the diagnostics 
consumer in this patch and this is essentially NFC.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82707: [clang][docs] Remove untracked files from formatted status

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D82707#2118772 , @MyDeveloperDay 
wrote:

> The net result is an actual reduction in the overall %
>
> F12256151: image.png 


Is that a bad thing?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82707



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82707: [clang][docs] Remove untracked files from formatted status

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGabafb655c85d: [clang][docs] Remove untracked files from 
formatted status (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82707

Files:
  clang/docs/tools/generate_formatted_state.py


Index: clang/docs/tools/generate_formatted_state.py
===
--- clang/docs/tools/generate_formatted_state.py
+++ clang/docs/tools/generate_formatted_state.py
@@ -72,6 +72,8 @@
  - {style2}`{percent}%`
 """
 
+FNULL = open(os.devnull, 'w')
+
 with open(DOC_FILE, 'wb') as output:
 sha = get_git_revision_short_hash()
 today = datetime.now().strftime("%B %d, %Y %H:%M:%S")
@@ -85,14 +87,22 @@
 for subdir in subdirs:
 if any(sd == subdir for sd in skipped_dirs):
 subdirs.remove(subdir)
+else:
+act_sub_dir = os.path.join(root, subdir)
+# Check the git index to see if the directory contains tracked
+# files. Reditect the output to a null descriptor as we aren't
+# interested in it, just the return code.
+git_check = subprocess.Popen(
+["git", "ls-files", "--error-unmatch", act_sub_dir],
+stdout=FNULL,
+stderr=FNULL)
+if git_check.wait() != 0:
+print("Skipping directory: ", act_sub_dir)
+subdirs.remove(subdir)
 
 path = os.path.relpath(root, TOP_DIR)
 path = path.replace('\\', '/')
 
-head, _ = os.path.split(root)
-while head:
-head, _ = os.path.split(head)
-
 file_count = 0
 file_pass = 0
 file_fail = 0


Index: clang/docs/tools/generate_formatted_state.py
===
--- clang/docs/tools/generate_formatted_state.py
+++ clang/docs/tools/generate_formatted_state.py
@@ -72,6 +72,8 @@
  - {style2}`{percent}%`
 """
 
+FNULL = open(os.devnull, 'w')
+
 with open(DOC_FILE, 'wb') as output:
 sha = get_git_revision_short_hash()
 today = datetime.now().strftime("%B %d, %Y %H:%M:%S")
@@ -85,14 +87,22 @@
 for subdir in subdirs:
 if any(sd == subdir for sd in skipped_dirs):
 subdirs.remove(subdir)
+else:
+act_sub_dir = os.path.join(root, subdir)
+# Check the git index to see if the directory contains tracked
+# files. Reditect the output to a null descriptor as we aren't
+# interested in it, just the return code.
+git_check = subprocess.Popen(
+["git", "ls-files", "--error-unmatch", act_sub_dir],
+stdout=FNULL,
+stderr=FNULL)
+if git_check.wait() != 0:
+print("Skipping directory: ", act_sub_dir)
+subdirs.remove(subdir)
 
 path = os.path.relpath(root, TOP_DIR)
 path = path.replace('\\', '/')
 
-head, _ = os.path.split(root)
-while head:
-head, _ = os.path.split(head)
-
 file_count = 0
 file_pass = 0
 file_fail = 0
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82706: [ASTMatchers] Enhanced support for matchers taking Regex arguments

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 273957.
njames93 added a comment.

Include matcher name in error message when failing to build a regex


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82706

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/tools/dump_ast_matchers.py
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersMacros.h
  clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
  clang/lib/ASTMatchers/Dynamic/Marshallers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
  clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
  llvm/include/llvm/Support/Regex.h
  llvm/lib/Support/Regex.cpp

Index: llvm/lib/Support/Regex.cpp
===
--- llvm/lib/Support/Regex.cpp
+++ llvm/lib/Support/Regex.cpp
@@ -26,7 +26,7 @@
 
 Regex::Regex() : preg(nullptr), error(REG_BADPAT) {}
 
-Regex::Regex(StringRef regex, unsigned Flags) {
+Regex::Regex(StringRef regex, RegexFlags Flags) {
   unsigned flags = 0;
   preg = new llvm_regex();
   preg->re_endp = regex.end();
@@ -39,6 +39,9 @@
   error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
 }
 
+Regex::Regex(StringRef regex, unsigned Flags)
+: Regex(regex, static_cast(Flags)) {}
+
 Regex::Regex(Regex &) {
   preg = regex.preg;
   error = regex.error;
Index: llvm/include/llvm/Support/Regex.h
===
--- llvm/include/llvm/Support/Regex.h
+++ llvm/include/llvm/Support/Regex.h
@@ -16,6 +16,7 @@
 #ifndef LLVM_SUPPORT_REGEX_H
 #define LLVM_SUPPORT_REGEX_H
 
+#include "llvm/ADT/BitmaskEnum.h"
 #include 
 
 struct llvm_regex;
@@ -26,20 +27,22 @@
 
   class Regex {
   public:
-enum {
-  NoFlags=0,
+enum RegexFlags : unsigned {
+  NoFlags = 0,
   /// Compile for matching that ignores upper/lower case distinctions.
-  IgnoreCase=1,
+  IgnoreCase = 1,
   /// Compile for newline-sensitive matching. With this flag '[^' bracket
   /// expressions and '.' never match newline. A ^ anchor matches the
   /// null string after any newline in the string in addition to its normal
   /// function, and the $ anchor matches the null string before any
   /// newline in the string in addition to its normal function.
-  Newline=2,
+  Newline = 2,
   /// By default, the POSIX extended regular expression (ERE) syntax is
   /// assumed. Pass this flag to turn on basic regular expressions (BRE)
   /// instead.
-  BasicRegex=4
+  BasicRegex = 4,
+
+  LLVM_MARK_AS_BITMASK_ENUM(BasicRegex)
 };
 
 Regex();
@@ -47,7 +50,8 @@
 ///
 /// \param Regex - referenced string is no longer needed after this
 /// constructor does finish.  Only its compiled form is kept stored.
-Regex(StringRef Regex, unsigned Flags = NoFlags);
+Regex(StringRef Regex, RegexFlags Flags = NoFlags);
+Regex(StringRef Regex, unsigned Flags);
 Regex(const Regex &) = delete;
 Regex =(Regex regex) {
   std::swap(preg, regex.preg);
Index: clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
===
--- clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -259,6 +259,15 @@
   EXPECT_TRUE(matches("unsigned X = sizeof(int);", MStmt));
   EXPECT_FALSE(matches("unsigned X = alignof(int);", MStmt));
 
+  Code =
+  R"query(namedDecl(matchesName("^::[ABC]*$", "IgnoreCase | BasicRegex")))query";
+  llvm::Optional MatchesName(
+  Parser::parseMatcherExpression(Code, nullptr, nullptr, ));
+  EXPECT_EQ("", Error.toStringFull());
+  M = MatchesName->unconditionalConvertTo();
+  EXPECT_TRUE(matches("unsigned AAACCBB;", M));
+  EXPECT_TRUE(matches("unsigned aaaccbb;", M));
+
   Code = "hasInitializer(\nbinaryOperator(hasLHS(\"A\")))";
   EXPECT_TRUE(!Parser::parseMatcherExpression(Code, ).hasValue());
   EXPECT_EQ("1:1: Error parsing argument 1 for matcher hasInitializer.\n"
@@ -348,6 +357,26 @@
 "1:14: Incorrect type for arg 1. (Expected = string) != (Actual = "
 "String)",
 ParseMatcherWithError(R"query(decl(hasAttr("unrelated")))query"));
+  EXPECT_EQ("1:1: Error parsing argument 1 for matcher namedDecl.\n"
+"1:11: Error building matcher matchesName.\n"
+"1:33: Incorrect type for arg 2. (Expected = string) != (Actual = "
+"String)",
+ParseMatcherWithError(
+R"query(namedDecl(matchesName("[ABC]*", "Ignorecase")))query"));
+  EXPECT_EQ(
+  "1:1: Error parsing argument 1 for matcher namedDecl.\n"
+  "1:11: Error building matcher matchesName.\n"
+  "1:33: Incorrect type for arg 2. (Expected = string) != (Actual = "
+  "String)",
+  ParseMatcherWithError(
+  

[PATCH] D82711: [clang-tidy] Fix hicpp-named-paramater

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, jbcoe.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Currently this alias instantiates the readability-identifier-naming check, just 
swap it out to use the readability-named-paramater check.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82711

Files:
  clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp


Index: clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
+++ clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "../bugprone/UndelegatedConstructorCheck.h"
 #include "../bugprone/UseAfterMoveCheck.h"
 #include "../cppcoreguidelines/AvoidGotoCheck.h"
 #include "../cppcoreguidelines/NoMallocCheck.h"
@@ -20,7 +21,6 @@
 #include "../google/ExplicitConstructorCheck.h"
 #include "../misc/NewDeleteOverloadsCheck.h"
 #include "../misc/StaticAssertCheck.h"
-#include "../bugprone/UndelegatedConstructorCheck.h"
 #include "../modernize/AvoidCArraysCheck.h"
 #include "../modernize/DeprecatedHeadersCheck.h"
 #include "../modernize/UseAutoCheck.h"
@@ -34,7 +34,7 @@
 #include "../performance/NoexceptMoveConstructorCheck.h"
 #include "../readability/BracesAroundStatementsCheck.h"
 #include "../readability/FunctionSizeCheck.h"
-#include "../readability/IdentifierNamingCheck.h"
+#include "../readability/NamedParameterCheck.h"
 #include "../readability/UppercaseLiteralSuffixCheck.h"
 #include "ExceptionBaseclassCheck.h"
 #include "MultiwayPathsCoveredCheck.h"
@@ -65,7 +65,7 @@
 "hicpp-explicit-conversions");
 CheckFactories.registerCheck(
 "hicpp-function-size");
-CheckFactories.registerCheck(
+CheckFactories.registerCheck(
 "hicpp-named-parameter");
 CheckFactories.registerCheck(
 "hicpp-invalid-access-moved");


Index: clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
+++ clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "../bugprone/UndelegatedConstructorCheck.h"
 #include "../bugprone/UseAfterMoveCheck.h"
 #include "../cppcoreguidelines/AvoidGotoCheck.h"
 #include "../cppcoreguidelines/NoMallocCheck.h"
@@ -20,7 +21,6 @@
 #include "../google/ExplicitConstructorCheck.h"
 #include "../misc/NewDeleteOverloadsCheck.h"
 #include "../misc/StaticAssertCheck.h"
-#include "../bugprone/UndelegatedConstructorCheck.h"
 #include "../modernize/AvoidCArraysCheck.h"
 #include "../modernize/DeprecatedHeadersCheck.h"
 #include "../modernize/UseAutoCheck.h"
@@ -34,7 +34,7 @@
 #include "../performance/NoexceptMoveConstructorCheck.h"
 #include "../readability/BracesAroundStatementsCheck.h"
 #include "../readability/FunctionSizeCheck.h"
-#include "../readability/IdentifierNamingCheck.h"
+#include "../readability/NamedParameterCheck.h"
 #include "../readability/UppercaseLiteralSuffixCheck.h"
 #include "ExceptionBaseclassCheck.h"
 #include "MultiwayPathsCoveredCheck.h"
@@ -65,7 +65,7 @@
 "hicpp-explicit-conversions");
 CheckFactories.registerCheck(
 "hicpp-function-size");
-CheckFactories.registerCheck(
+CheckFactories.registerCheck(
 "hicpp-named-parameter");
 CheckFactories.registerCheck(
 "hicpp-invalid-access-moved");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp:31
+  ~TestCheck() {
+assert(DidRegister && "Check never registered");
+assert(DidFire && "Check never fired");

This assert is failing on the mac builds - 
http://45.33.8.238/mac/16309/step_8.txt yet I can see no logical reason for it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82707: [clang][docs] Remove untracked files from formatted status

2020-06-29 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D82707#2119303 , @MyDeveloperDay 
wrote:

> In D82707#2118796 , @njames93 wrote:
>
> > Is that a bad thing?
>
>
> Not really, just a little disappointed ;-(


I'm gonna hazard a guess the removal of these directories is the reason the % 
went down F12260876: image.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82707



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81785: [clangd] Fix readability-else-after-return 'Adding a note without main diagnostic' crash

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG740575dc232b: [clangd] Fix readability-else-after-return 
Adding a note without main… (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81785

Files:
  clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp


Index: clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -188,9 +188,8 @@
 if (IsLastInScope) {
   // If the if statement is the last statement its enclosing statements
   // scope, we can pull the decl out of the if statement.
-  DiagnosticBuilder Diag =
-  diag(ElseLoc, WarningMessage, clang::DiagnosticIDs::Level::Remark)
-  << ControlFlowInterruptor;
+  DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
+   << ControlFlowInterruptor;
   if (checkInitDeclUsageInElse(If) != nullptr) {
 Diag << tooling::fixit::createReplacement(
 SourceRange(If->getIfLoc()),


Index: clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -188,9 +188,8 @@
 if (IsLastInScope) {
   // If the if statement is the last statement its enclosing statements
   // scope, we can pull the decl out of the if statement.
-  DiagnosticBuilder Diag =
-  diag(ElseLoc, WarningMessage, clang::DiagnosticIDs::Level::Remark)
-  << ControlFlowInterruptor;
+  DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
+   << ControlFlowInterruptor;
   if (checkInitDeclUsageInElse(If) != nullptr) {
 Diag << tooling::fixit::createReplacement(
 SourceRange(If->getIfLoc()),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271047.
njames93 added a comment.

Removed `isExpansionInMainFile` check as per original authors comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantiate() {
+  // Just make sure the check isn't fooled by template instantiations.
+  ignoreInstantiations();
+  ignoreInstantiations();
+}
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -432,7 +432,7 @@
   bool Value,
   StringRef TernaryId) {
   Finder->addMatcher(
-  conditionalOperator(isExpansionInMainFile(),
+  conditionalOperator(unless(isInTemplateInstantiation()),
   hasTrueExpression(cxxBoolLiteral(equals(Value))),
   hasFalseExpression(cxxBoolLiteral(equals(!Value
   .bind(TernaryId),
@@ -442,13 +442,13 @@
 void SimplifyBooleanExprCheck::matchIfReturnsBool(MatchFinder *Finder,
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
@@ -474,12 +474,16 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  hasThen(Then), hasElse(Else))
+   .bind(Id),
+   this);
   else
-Finder->addMatcher(
-ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
-.bind(Id),
-this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  unless(hasParent(ifStmt())), hasThen(Then),
+  hasElse(Else))
+   .bind(Id),
+   this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -487,6 +491,7 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(


Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void 

[PATCH] D81923: [clang-tidy] Add modernize-use-ranges check.

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh, gribozavr2.
Herald added subscribers: cfe-commits, mgrang, xazax.hun, mgorny.
Herald added a project: clang.

Flags and replaces calls to standard library algorithms that could be converted 
to use the `std::ranges` algorithms introduced in c++20.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81923

Files:
  clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-ranges.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
@@ -0,0 +1,156 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t
+
+// Ensure no warnings are generated when not in c++20 mode
+// RUN: clang-tidy %s -checks=-*,modernize-use-ranges --warnings-as-errors=modernize-use-ranges --extra-arg=-std=c++17
+
+namespace std {
+
+class sequenced_policy {};
+class parallel_policy {};
+class parallel_unsequenced_policy {};
+class unsequenced_policy {};
+
+template 
+auto begin(Container ) -> decltype(C.begin());
+template 
+auto cbegin(Container ) -> decltype(C.cbegin());
+
+template 
+auto end(Container ) -> decltype(C.end());
+template 
+auto cend(Container ) -> decltype(C.cend());
+
+template 
+T *begin(T ()[N]) noexcept;
+
+template 
+T *end(T ()[N]) noexcept;
+
+template 
+class vector {
+public:
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  const_iterator begin() const;
+  const_iterator cbegin() const;
+
+  iterator end();
+  const_iterator end() const;
+  const_iterator cend() const;
+};
+
+template 
+InputIt find(InputIt First, InputIt Last, const T );
+
+template 
+ForwardIt find(ExecutionPolicy &, ForwardIt First, ForwardIt Last, const T );
+
+template 
+bool equal(InputIt1 First1, InputIt1 Last1,
+   InputIt2 First2);
+template 
+bool equal(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+   ForwardIt2 First2);
+template 
+bool equal(InputIt1 First1, InputIt1 Last1,
+   InputIt2 First2, InputIt2 Last2);
+template 
+bool equal(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+   ForwardIt2 First2, ForwardIt2 Last2);
+
+template 
+bool includes(InputIt1 First1, InputIt1 Last1,
+  InputIt2 First2, InputIt2 Last2);
+template 
+bool includes(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+  ForwardIt2 First2, ForwardIt2 Last2);
+
+} // namespace std
+
+void goodBeginEndCalls(const std::vector ) {
+  std::find(Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(Vec.cbegin(), Vec.cend(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::begin(Vec), std::end(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::cbegin(Vec), std::cend(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::parallel_policy(), Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+
+  // CHECK-FIXES:  std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(std::parallel_policy(), Vec, 1);
+  // CHECK-FIXES-NEXT: //
+}
+
+void badBeginEndCalls(const std::vector ,
+  const std::vector ) {
+  // end, begin.
+  std::find(Vec.end(), Vec.begin(), 1);
+  std::find(Vec.cend(), Vec.cbegin(), 1);
+  std::find(std::end(Vec), std::begin(Vec), 1);
+  std::find(std::cend(Vec), std::cbegin(Vec), 1);
+
+  // begin, begin.
+  std::find(Vec.begin(), Vec.begin(), 1);
+  // end, end.
+  std::find(Vec.end(), Vec.end(), 1);
+
+  // Different containers, definitely bad, but not what this check is for.
+  std::find(Vec.begin(), Vec2.end(), 1);
+}
+
+void maybeDualArg(const std::vector , std::vector ) {
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  

[PATCH] D81932: [clang-tidy] Improved accuracy of check list updater script

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2, Eugene.Zelenko.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

- Added a file `FixItHint` comments to Check files to for the script to mark 
those checks as offering fix-its when the fix-its are generated in another file.
- Case insensitive file searching when looking for the file a checker code 
resides in.

Also regenerated the list, sphinx had no issue generating the docs after this.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81932

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
  clang-tools-extra/clang-tidy/add_new_check.py
  clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
  clang-tools-extra/docs/clang-tidy/checks/list.rst

Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -133,6 +133,7 @@
`clang-analyzer-valist.Uninitialized `_,
`clang-analyzer-valist.Unterminated `_,
`cppcoreguidelines-avoid-goto `_,
+   `cppcoreguidelines-avoid-non-const-global-variables `_,
`cppcoreguidelines-init-variables `_, "Yes"
`cppcoreguidelines-interfaces-global-init `_,
`cppcoreguidelines-macro-usage `_,
@@ -189,7 +190,7 @@
`llvm-prefer-isa-or-dyn-cast-in-conditionals `_, "Yes"
`llvm-prefer-register-over-unsigned `_, "Yes"
`llvm-twine-local `_, "Yes"
-   `llvmlibc-callee-namespace `_,
+   `llvmlibc-callee-namespace `_,
`llvmlibc-implementation-in-namespace `_,
`llvmlibc-restrict-system-libc-headers `_, "Yes"
`misc-definitions-in-headers `_, "Yes"
@@ -291,7 +292,7 @@
`readability-redundant-member-init `_, "Yes"
`readability-redundant-preprocessor `_,
`readability-redundant-smartptr-get `_, "Yes"
-   `readability-redundant-string-cstr `_,
+   `readability-redundant-string-cstr `_, "Yes"
`readability-redundant-string-init `_, "Yes"
`readability-simplify-boolean-expr `_, "Yes"
`readability-simplify-subscript-expr `_, "Yes"
@@ -300,7 +301,7 @@
`readability-string-compare `_, "Yes"
`readability-uniqueptr-delete-release `_, "Yes"
`readability-uppercase-literal-suffix `_, "Yes"
-   `readability-use-anyofallof`_, "No"
+   `readability-use-anyofallof `_,
`zircon-temporary-objects `_,
 
 
@@ -390,7 +391,6 @@
`clang-analyzer-unix.cstring.NullArg `_, `Clang Static Analyzer `_,
`cppcoreguidelines-avoid-c-arrays `_, `modernize-avoid-c-arrays `_,
`cppcoreguidelines-avoid-magic-numbers `_, `readability-magic-numbers `_,
-   `cppcoreguidelines-avoid-non-const-global-variables `_, , , ""
`cppcoreguidelines-c-copy-assignment-signature `_, `misc-unconventional-assign-operator `_,
`cppcoreguidelines-explicit-virtual-functions `_, `modernize-use-override `_, "Yes"
`cppcoreguidelines-non-private-member-variables-in-classes `_, `misc-non-private-member-variables-in-classes `_,
@@ -410,7 +410,7 @@
`hicpp-new-delete-operators `_, `misc-new-delete-overloads `_,
`hicpp-no-array-decay `_, `cppcoreguidelines-pro-bounds-array-to-pointer-decay `_,
`hicpp-no-malloc `_, `cppcoreguidelines-no-malloc `_,
-   `hicpp-noexcept-move `_, `performance-noexcept-move-constructor `_,
+   `hicpp-noexcept-move `_, `performance-noexcept-move-constructor `_, "Yes"
`hicpp-special-member-functions `_, `cppcoreguidelines-special-member-functions `_,
`hicpp-static-assert `_, `misc-static-assert `_, "Yes"
`hicpp-undelegated-constructor `_, `bugprone-undelegated-constructor `_,
@@ -424,4 +424,3 @@
`hicpp-use-override `_, `modernize-use-override `_, "Yes"
`hicpp-vararg `_, `cppcoreguidelines-pro-type-vararg `_,
`llvm-qualified-auto `_, `readability-qualified-auto `_, "Yes"
-
Index: clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
@@ -8,6 +8,9 @@
 
 #include "MakeSharedCheck.h"
 
+// FixItHint - Hint to check documentation script to mark this check as
+// providing a FixIt.
+
 using namespace clang::ast_matchers;
 
 namespace clang {
Index: clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
+++ clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
@@ -12,6 +12,9 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 
+// FixItHint - Hint to check documentation script to mark this check as
+// providing a FixIt.
+
 namespace clang {
 

[PATCH] D81923: [clang-tidy] Add modernize-use-ranges check.

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp:77
+  MatchCallTo((ID + "Begin").str(), namedDecl().bind(Range),
+  hasAnyName("::std::begin", "::std::cbegin"),
+  hasAnyName("begin", "cbegin"))),

JonasToth wrote:
> i would at `rbegin()` and the likes, too.
How should `rbegin` be handled
`std::(std::rbegin(X), std::rbegin(X))` -> 
`std::ranges::(std::ranges::reverse_view(X))` I almost think that looks 
less pleasing, but thats just my opinion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81923



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe1ba7241c3ef: [clang-tidy] simplify-bool-expr ignores 
template instantiations (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantiate() {
+  // Just make sure the check isn't fooled by template instantiations.
+  ignoreInstantiations();
+  ignoreInstantiations();
+}
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -432,7 +432,7 @@
   bool Value,
   StringRef TernaryId) {
   Finder->addMatcher(
-  conditionalOperator(isExpansionInMainFile(),
+  conditionalOperator(unless(isInTemplateInstantiation()),
   hasTrueExpression(cxxBoolLiteral(equals(Value))),
   hasFalseExpression(cxxBoolLiteral(equals(!Value
   .bind(TernaryId),
@@ -442,13 +442,13 @@
 void SimplifyBooleanExprCheck::matchIfReturnsBool(MatchFinder *Finder,
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
@@ -474,12 +474,16 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  hasThen(Then), hasElse(Else))
+   .bind(Id),
+   this);
   else
-Finder->addMatcher(
-ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
-.bind(Id),
-this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  unless(hasParent(ifStmt())), hasThen(Then),
+  hasElse(Else))
+   .bind(Id),
+   this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -487,6 +491,7 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(


Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // 

[PATCH] D81949: [clang-tidy] Extend InheritParentConfig to CommandLineConfig

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: DmitryPolukhin, alexfh, gribozavr2, klimek, hokein, 
aaron.ballman.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Extend the `InheritParentConfig` support introduced in D75184 
 for the command line option `--config`.
The current behaviour of `--config` is to when set, disable looking for 
`.clang-tidy` configuration files.
This new behaviour lets you set `InheritParentConfig` to true in the command 
line to then look for `.clang-tidy` configuration files to be merged with 
what's been specified on the command line.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81949

Files:
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -18,7 +18,7 @@
 // RUN: clang-tidy -dump-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD4
 // CHECK-CHILD4: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto
 // CHECK-CHILD4: - key: llvm-qualified-auto.AddConstToQualified
-// CHECK-CHILD4-NEXT: value: '1
+// CHECK-CHILD4-NEXT: value: '1'
 // CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
 // CHECK-CHILD4-NEXT: value: '20'
 // CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
@@ -30,3 +30,23 @@
 // CHECK-EXPLAIN: 'llvm-qualified-auto' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}44{{[/\\]}}.clang-tidy.
 // CHECK-EXPLAIN: 'modernize-loop-convert' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}.clang-tidy.
 // CHECK-EXPLAIN: 'modernize-use-using' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}.clang-tidy.
+
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{InheritParentConfig: true, \
+// RUN: Checks: -llvm-qualified-auto, \
+// RUN: CheckOptions: [{key: modernize-loop-convert.MaxCopySize, value: 21}]}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD5
+// CHECK-CHILD5: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto,-llvm-qualified-auto
+// CHECK-CHILD5: - key: modernize-loop-convert.MaxCopySize
+// CHECK-CHILD5-NEXT: value: '21'
+// CHECK-CHILD5: - key: modernize-loop-convert.MinConfidence
+// CHECK-CHILD5-NEXT: value: reasonable
+// CHECK-CHILD5: - key: modernize-use-using.IgnoreMacros
+// CHECK-CHILD5-NEXT: value: '0'
+
+// RUN: clang-tidy -dump-config \
+// RUN: --config='{InheritParentConfig: false, \
+// RUN: Checks: -llvm-qualified-auto}' \
+// RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD6
+// CHECK-CHILD6: Checks: {{.*}}-llvm-qualified-auto
+// CHECK-CHILD6-NOT: - key: modernize-use-using.IgnoreMacros
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -292,14 +292,13 @@
 OverrideOptions.SystemHeaders = SystemHeaders;
   if (FormatStyle.getNumOccurrences() > 0)
 OverrideOptions.FormatStyle = FormatStyle;
-
   if (!Config.empty()) {
 if (llvm::ErrorOr ParsedConfig =
 parseConfiguration(Config)) {
   return std::make_unique(
   GlobalOptions,
   ClangTidyOptions::getDefaults().mergeWith(DefaultOptions, 0),
-  *ParsedConfig, OverrideOptions);
+  *ParsedConfig, OverrideOptions, std::move(FS));
 } else {
   llvm::errs() << "Error: invalid configuration specified.\n"
<< ParsedConfig.getError().message() << "\n";
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.h
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -177,30 +177,7 @@
   ClangTidyOptions DefaultOptions;
 };
 
-/// Implementation of ClangTidyOptions interface, which is used for
-/// '-config' command-line option.
-class ConfigOptionsProvider : public DefaultOptionsProvider {
-public:
-  ConfigOptionsProvider(const ClangTidyGlobalOptions ,
-const ClangTidyOptions ,
-const ClangTidyOptions ,
-const ClangTidyOptions );
-  std::vector getRawOptions(llvm::StringRef FileName) override;
-
-private:
-  ClangTidyOptions ConfigOptions;
-  ClangTidyOptions OverrideOptions;
-};
-
-/// Implementation of the \c ClangTidyOptionsProvider interface, 

[PATCH] D81953: [clang-tidy] warnings-as-error no longer exits with ErrorCount

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: alexfh, jroelofs, aaron.ballman.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

When using `-warnings-as-errors`, If there are any warnings promoted to errors, 
clang-tidy exits with the number of warnings. This really isn't needed and can 
cause issues when the number of warnings doesn't fit into 8 bits as POSIX 
terminals aren't designed to handle more than that.
This addresses https://bugs.llvm.org/show_bug.cgi?id=46305.

Bug originally added in D15528 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81953

Files:
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -478,7 +478,7 @@
   llvm::errs() << WErrorCount << " warning" << Plural << " treated as 
error"
<< Plural << "\n";
 }
-return WErrorCount;
+return 1;
   }
 
   if (FoundErrors) {


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -478,7 +478,7 @@
   llvm::errs() << WErrorCount << " warning" << Plural << " treated as error"
<< Plural << "\n";
 }
-return WErrorCount;
+return 1;
   }
 
   if (FoundErrors) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81953: [clang-tidy] warnings-as-error no longer exits with ErrorCount

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D81953#2096388 , @aaron.ballman 
wrote:

> LGTM unless @jroelofs has a reason why the code was originally written that 
> way, but can you add test coverage for it?


How would you suggest I add test coverage for this, afaik llvm-lit doesn't seem 
to handle checking specific exit codes, only whether is was 0 or not. 
There are already test cases for a non-zero exit code with 
`-warnings-as-errors`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81953



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81923: [clang-tidy] Add modernize-use-ranges check.

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271191.
njames93 marked 4 inline comments as done.
njames93 added a comment.

Tweaked documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81923

Files:
  clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-ranges.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
@@ -0,0 +1,156 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t
+
+// Ensure no warnings are generated when not in c++20 mode
+// RUN: clang-tidy %s -checks=-*,modernize-use-ranges --warnings-as-errors=modernize-use-ranges --extra-arg=-std=c++17
+
+namespace std {
+
+class sequenced_policy {};
+class parallel_policy {};
+class parallel_unsequenced_policy {};
+class unsequenced_policy {};
+
+template 
+auto begin(Container ) -> decltype(C.begin());
+template 
+auto cbegin(Container ) -> decltype(C.cbegin());
+
+template 
+auto end(Container ) -> decltype(C.end());
+template 
+auto cend(Container ) -> decltype(C.cend());
+
+template 
+T *begin(T ()[N]) noexcept;
+
+template 
+T *end(T ()[N]) noexcept;
+
+template 
+class vector {
+public:
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  const_iterator begin() const;
+  const_iterator cbegin() const;
+
+  iterator end();
+  const_iterator end() const;
+  const_iterator cend() const;
+};
+
+template 
+InputIt find(InputIt First, InputIt Last, const T );
+
+template 
+ForwardIt find(ExecutionPolicy &, ForwardIt First, ForwardIt Last, const T );
+
+template 
+bool equal(InputIt1 First1, InputIt1 Last1,
+   InputIt2 First2);
+template 
+bool equal(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+   ForwardIt2 First2);
+template 
+bool equal(InputIt1 First1, InputIt1 Last1,
+   InputIt2 First2, InputIt2 Last2);
+template 
+bool equal(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+   ForwardIt2 First2, ForwardIt2 Last2);
+
+template 
+bool includes(InputIt1 First1, InputIt1 Last1,
+  InputIt2 First2, InputIt2 Last2);
+template 
+bool includes(ExecutionPolicy &, ForwardIt1 First1, ForwardIt1 Last1,
+  ForwardIt2 First2, ForwardIt2 Last2);
+
+} // namespace std
+
+void goodBeginEndCalls(const std::vector ) {
+  std::find(Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(Vec.cbegin(), Vec.cend(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::begin(Vec), std::end(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::cbegin(Vec), std::cend(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::parallel_policy(), Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+
+  // CHECK-FIXES:  std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(std::parallel_policy(), Vec, 1);
+  // CHECK-FIXES-NEXT: //
+}
+
+void badBeginEndCalls(const std::vector ,
+  const std::vector ) {
+  // end, begin.
+  std::find(Vec.end(), Vec.begin(), 1);
+  std::find(Vec.cend(), Vec.cbegin(), 1);
+  std::find(std::end(Vec), std::begin(Vec), 1);
+  std::find(std::cend(Vec), std::cbegin(Vec), 1);
+
+  // begin, begin.
+  std::find(Vec.begin(), Vec.begin(), 1);
+  // end, end.
+  std::find(Vec.end(), Vec.end(), 1);
+
+  // Different containers, definitely bad, but not what this check is for.
+  std::find(Vec.begin(), Vec2.end(), 1);
+}
+
+void maybeDualArg(const std::vector , std::vector ) {
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(std::sequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace 

[PATCH] D80753: [clang-tidy] remove duplicate fixes of alias checkers

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaf4f2eb47636: [clang-tidy] remove duplicate fixes of alias 
checkers (authored by Daniel599, committed by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80753

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  
clang-tools-extra/test/clang-tidy/infrastructure/duplicate-conflicted-fixes-of-alias-checkers.cpp
  
clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/duplicate-reports.cpp
  llvm/include/llvm/ADT/StringMap.h
  llvm/unittests/ADT/StringMapTest.cpp

Index: llvm/unittests/ADT/StringMapTest.cpp
===
--- llvm/unittests/ADT/StringMapTest.cpp
+++ llvm/unittests/ADT/StringMapTest.cpp
@@ -387,6 +387,70 @@
   ASSERT_EQ(B.count("x"), 0u);
 }
 
+TEST_F(StringMapTest, EqualEmpty) {
+  StringMap A;
+  StringMap B;
+  ASSERT_TRUE(A == B);
+  ASSERT_FALSE(A != B);
+  ASSERT_TRUE(A == A); // self check
+}
+
+TEST_F(StringMapTest, EqualWithValues) {
+  StringMap A;
+  A["A"] = 1;
+  A["B"] = 2;
+  A["C"] = 3;
+  A["D"] = 3;
+
+  StringMap B;
+  B["A"] = 1;
+  B["B"] = 2;
+  B["C"] = 3;
+  B["D"] = 3;
+
+  ASSERT_TRUE(A == B);
+  ASSERT_TRUE(B == A);
+  ASSERT_FALSE(A != B);
+  ASSERT_FALSE(B != A);
+  ASSERT_TRUE(A == A); // self check
+}
+
+TEST_F(StringMapTest, NotEqualMissingKeys) {
+  StringMap A;
+  A["A"] = 1;
+  A["B"] = 2;
+
+  StringMap B;
+  B["A"] = 1;
+  B["B"] = 2;
+  B["C"] = 3;
+  B["D"] = 3;
+
+  ASSERT_FALSE(A == B);
+  ASSERT_FALSE(B == A);
+  ASSERT_TRUE(A != B);
+  ASSERT_TRUE(B != A);
+}
+
+TEST_F(StringMapTest, NotEqualWithDifferentValues) {
+  StringMap A;
+  A["A"] = 1;
+  A["B"] = 2;
+  A["C"] = 100;
+  A["D"] = 3;
+
+  StringMap B;
+  B["A"] = 1;
+  B["B"] = 2;
+  B["C"] = 3;
+  B["D"] = 3;
+
+  ASSERT_FALSE(A == B);
+  ASSERT_FALSE(B == A);
+  ASSERT_TRUE(A != B);
+  ASSERT_TRUE(B != A);
+}
+
 struct Countable {
   int 
   int Number;
Index: llvm/include/llvm/ADT/StringMap.h
===
--- llvm/include/llvm/ADT/StringMap.h
+++ llvm/include/llvm/ADT/StringMap.h
@@ -248,6 +248,26 @@
 return count(MapEntry.getKey());
   }
 
+  /// equal - check whether both of the containers are equal.
+  bool operator==(const StringMap ) const {
+if (size() != RHS.size())
+  return false;
+
+for (const auto  : *this) {
+  auto FindInRHS = RHS.find(KeyValue.getKey());
+
+  if (FindInRHS == RHS.end())
+return false;
+
+  if (!(KeyValue.getValue() == FindInRHS->getValue()))
+return false;
+}
+
+return true;
+  }
+
+  bool operator!=(const StringMap ) const { return !(*this == RHS); }
+
   /// insert - Insert the specified key/value pair into the map.  If the key
   /// already exists in the map, return false and ignore the request, otherwise
   /// insert it and return true.
Index: clang-tools-extra/test/clang-tidy/infrastructure/duplicate-reports.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/duplicate-reports.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/duplicate-reports.cpp
@@ -2,8 +2,7 @@
 
 void alwaysThrows() {
   int ex = 42;
-  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err09-cpp]
-  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err61-cpp]
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err09-cpp,cert-err61-cpp]
   throw ex;
 }
 
Index: clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp
@@ -0,0 +1,39 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init,hicpp-member-init,modernize-use-emplace,hicpp-use-emplace %t
+
+namespace std {
+
+template 
+class vector {
+public:
+  void push_back(const T &) {}
+  void push_back(T &&) {}
+
+  template 
+  void emplace_back(Args &&... args){};
+};
+} // namespace std
+
+class Foo {
+public:
+  Foo() : _num1(0)
+  // CHECK-MESSAGES: warning: constructor does not initialize these fields: _num2 [cppcoreguidelines-pro-type-member-init,hicpp-member-init]
+  {
+_num1 = 10;
+  }
+
+  int use_the_members() const {
+return _num1 + _num2;
+  }
+
+private:
+  int _num1;
+  int _num2;
+  // CHECK-FIXES: _num2{};
+};
+
+int should_use_emplace(std::vector ) {
+  v.push_back(Foo());
+  // CHECK-FIXES: v.emplace_back();
+  // 

[PATCH] D82223: [clang-tidy] Implement storeOptions for checks missing it.

2020-06-19 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, Eugene.Zelenko.
Herald added subscribers: cfe-commits, kbarton, xazax.hun, nemanjai.
Herald added a project: clang.

Just adds the storeOptions for Checks that weren't already storing their 
options.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82223

Files:
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/clang-tidy/misc/NonPrivateMemberVariablesInClassesCheck.cpp
  clang-tools-extra/clang-tidy/misc/NonPrivateMemberVariablesInClassesCheck.h
  clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp
  clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.h
  clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h
  clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
  clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
  clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
  clang-tools-extra/clang-tidy/utils/HeaderGuard.h

Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.h
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.h
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.h
@@ -34,6 +34,7 @@
HeaderFileExtensions,
utils::defaultFileExtensionDelimiters());
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerPPCallbacks(const SourceManager , Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
 
Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
@@ -266,6 +266,10 @@
 };
 } // namespace
 
+void HeaderGuardCheck::storeOptions(ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
+}
+
 void HeaderGuardCheck::registerPPCallbacks(const SourceManager ,
Preprocessor *PP,
Preprocessor *ModuleExpanderPP) {
@@ -285,7 +289,6 @@
 std::string HeaderGuardCheck::formatEndIf(StringRef HeaderGuard) {
   return "endif // " + HeaderGuard.str();
 }
-
 } // namespace utils
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
===
--- clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
+++ clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
@@ -25,7 +25,7 @@
   StaticAccessedThroughInstanceCheck(StringRef Name, ClangTidyContext *Context)
   : ClangTidyCheck(Name, Context),
 NameSpecifierNestingThreshold(
-Options.get("NameSpecifierNestingThreshold", 3)) {}
+Options.get("NameSpecifierNestingThreshold", 3U)) {}
 
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
Index: clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
@@ -22,6 +22,7 @@
 class RedundantDeclarationCheck : public ClangTidyCheck {
 public:
   RedundantDeclarationCheck(StringRef Name, ClangTidyContext *Context);
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) 

[PATCH] D82281: [clang-tidy] llvm-twine-local ignores parameters

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: bkramer, alexfh, aaron.ballman.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Ignore paramater declarations of type `::llvm::Twine`, These don't suffer the 
same use after free risks as local twines.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82281

Files:
  clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
@@ -13,6 +13,7 @@
 using namespace llvm;
 
 void foo(const Twine );
+void bar(Twine x);
 
 static Twine Moo = Twine("bark") + "bah";
 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: twine variables are prone to 
use-after-free bugs
Index: clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -19,8 +19,10 @@
 
 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
   auto TwineType =
-  qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine";
-  Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
+  qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine";
+  Finder->addMatcher(
+  varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
+  this);
 }
 
 void TwineLocalCheck::check(const MatchFinder::MatchResult ) {


Index: clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
@@ -13,6 +13,7 @@
 using namespace llvm;
 
 void foo(const Twine );
+void bar(Twine x);
 
 static Twine Moo = Twine("bark") + "bah";
 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: twine variables are prone to use-after-free bugs
Index: clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -19,8 +19,10 @@
 
 void TwineLocalCheck::registerMatchers(MatchFinder *Finder) {
   auto TwineType =
-  qualType(hasDeclaration(recordDecl(hasName("::llvm::Twine";
-  Finder->addMatcher(varDecl(hasType(TwineType)).bind("variable"), this);
+  qualType(hasDeclaration(cxxRecordDecl(hasName("::llvm::Twine";
+  Finder->addMatcher(
+  varDecl(unless(parmVarDecl()), hasType(TwineType)).bind("variable"),
+  this);
 }
 
 void TwineLocalCheck::check(const MatchFinder::MatchResult ) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82162: [clang-tidy] RenamerClangTidy wont emit fixes in scratch space

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp:570
+
+// We don't want a warning here as the call to this in Foo is in a scratch
+// buffer so its fix-it wouldn't be applied, resulting in invalid code.

aaron.ballman wrote:
> I may be misunderstanding the comment here. I can understand not wanting to 
> generate fixits into the scratch buffer (that would not do good things), but 
> I think we still want a warning were it not for the macro, right? Just 
> verifying that this is not changing warning behaviors, only fix-it behaviors.
You're absolutely right, however right now this fix just marks it as being 
`InsideMacro`. The reason diagnostics aren't emitted is becuase somewhere in 
this checks life someone decided to not emit warnings for declarations with 
usages inside macros. If that behaviour is to be changed a separate patch would 
be required.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82162



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272317.
njames93 marked 2 inline comments as done.
njames93 added a comment.

Use `= delete` for getEnumMapping in template definition.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -6,6 +6,20 @@
 
 namespace clang {
 namespace tidy {
+
+enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
+
+template <> struct OptionEnumMapping {
+  static llvm::ArrayRef> getEnumMapping() {
+static constexpr std::pair Mapping[] = {
+{Colours::Red, "Red"},   {Colours::Orange, "Orange"},
+{Colours::Yellow, "Yellow"}, {Colours::Green, "Green"},
+{Colours::Blue, "Blue"}, {Colours::Indigo, "Indigo"},
+{Colours::Violet, "Violet"}};
+return makeArrayRef(Mapping);
+  }
+};
+
 namespace test {
 
 TEST(ParseLineFilter, EmptyFilter) {
@@ -209,15 +223,6 @@
 }
 
 TEST(ValidConfiguration, ValidEnumOptions) {
-
-  enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
-  static constexpr std::pair Mapping[] = {
-  {"Red", Colours::Red},   {"Orange", Colours::Orange},
-  {"Yellow", Colours::Yellow}, {"Green", Colours::Green},
-  {"Blue", Colours::Blue}, {"Indigo", Colours::Indigo},
-  {"Violet", Colours::Violet}};
-  static const auto Map = makeArrayRef(Mapping);
-
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
 
@@ -237,29 +242,30 @@
 #define CHECK_ERROR_ENUM(Name, Expected)   \
   CHECK_ERROR(Name, UnparseableEnumOptionError, Expected)
 
-  CHECK_VAL(TestCheck.getLocal("Valid", Map), Colours::Red);
-  CHECK_VAL(TestCheck.getGlobal("GlobalValid", Map), Colours::Violet);
-  CHECK_VAL(TestCheck.getLocal("ValidWrongCase", Map, /*IgnoreCase*/ true),
-Colours::Red);
+  CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
   CHECK_VAL(
-  TestCheck.getGlobal("GlobalValidWrongCase", Map, /*IgnoreCase*/ true),
-  Colours::Violet);
-  CHECK_ERROR_ENUM(TestCheck.getLocal("Invalid", Map),
+  TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
+  Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
+/*IgnoreCase*/ true),
+Colours::Violet);
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("Invalid"),
"invalid configuration value "
"'Scarlet' for option 'test.Invalid'");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("ValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("ValidWrongCase"),
"invalid configuration value 'rED' for option "
"'test.ValidWrongCase'; did you mean 'Red'?");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("NearMiss", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("NearMiss"),
"invalid configuration value 'Oragne' for option "
"'test.NearMiss'; did you mean 'Orange'?");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalInvalid", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalInvalid"),
"invalid configuration value "
"'Purple' for option 'GlobalInvalid'");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalValidWrongCase"),
 

[PATCH] D82223: [clang-tidy] Implement storeOptions for checks missing it.

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdb90d315706b: [clang-tidy] Implement storeOptions for checks 
missing it. (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82223

Files:
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/clang-tidy/misc/NonPrivateMemberVariablesInClassesCheck.cpp
  clang-tools-extra/clang-tidy/misc/NonPrivateMemberVariablesInClassesCheck.h
  clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp
  clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.h
  clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h
  clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
  clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
  clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
  clang-tools-extra/clang-tidy/utils/HeaderGuard.h

Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.h
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.h
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.h
@@ -34,6 +34,7 @@
HeaderFileExtensions,
utils::defaultFileExtensionDelimiters());
   }
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerPPCallbacks(const SourceManager , Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
 
Index: clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
===
--- clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
+++ clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp
@@ -266,6 +266,10 @@
 };
 } // namespace
 
+void HeaderGuardCheck::storeOptions(ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
+}
+
 void HeaderGuardCheck::registerPPCallbacks(const SourceManager ,
Preprocessor *PP,
Preprocessor *ModuleExpanderPP) {
@@ -285,7 +289,6 @@
 std::string HeaderGuardCheck::formatEndIf(StringRef HeaderGuard) {
   return "endif // " + HeaderGuard.str();
 }
-
 } // namespace utils
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
===
--- clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
+++ clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
@@ -25,7 +25,7 @@
   StaticAccessedThroughInstanceCheck(StringRef Name, ClangTidyContext *Context)
   : ClangTidyCheck(Name, Context),
 NameSpecifierNestingThreshold(
-Options.get("NameSpecifierNestingThreshold", 3)) {}
+Options.get("NameSpecifierNestingThreshold", 3U)) {}
 
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
Index: clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.h
@@ -22,6 +22,7 @@
 class RedundantDeclarationCheck : public ClangTidyCheck {
 public:
   RedundantDeclarationCheck(StringRef Name, ClangTidyContext *Context);
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
 
Index: 

[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/ClangTidyCheck.h:31-32
+template  struct OptionEnumMapping {
+  // Must provide:
+  // static ArrayRef> getEnumMapping();
+};

aaron.ballman wrote:
> Any reason not to do:
> ```
> static ArrayRef> getEnumMapping() = delete;
> ```
> so you get a nice error if you instantiate something without the required 
> definition?
I need to read the c++ standard, never even realised you could delete static 
functions like that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82188: [clang-tidy] Reworked enum options handling(again)

2020-06-21 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 272336.
njames93 added a comment.

- Fix compilation failure on rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82188

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -6,6 +6,20 @@
 
 namespace clang {
 namespace tidy {
+
+enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
+
+template <> struct OptionEnumMapping {
+  static llvm::ArrayRef> getEnumMapping() {
+static constexpr std::pair Mapping[] = {
+{Colours::Red, "Red"},   {Colours::Orange, "Orange"},
+{Colours::Yellow, "Yellow"}, {Colours::Green, "Green"},
+{Colours::Blue, "Blue"}, {Colours::Indigo, "Indigo"},
+{Colours::Violet, "Violet"}};
+return makeArrayRef(Mapping);
+  }
+};
+
 namespace test {
 
 TEST(ParseLineFilter, EmptyFilter) {
@@ -209,15 +223,6 @@
 }
 
 TEST(ValidConfiguration, ValidEnumOptions) {
-
-  enum class Colours { Red, Orange, Yellow, Green, Blue, Indigo, Violet };
-  static constexpr std::pair Mapping[] = {
-  {"Red", Colours::Red},   {"Orange", Colours::Orange},
-  {"Yellow", Colours::Yellow}, {"Green", Colours::Green},
-  {"Blue", Colours::Blue}, {"Indigo", Colours::Indigo},
-  {"Violet", Colours::Violet}};
-  static const auto Map = makeArrayRef(Mapping);
-
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
 
@@ -237,29 +242,30 @@
 #define CHECK_ERROR_ENUM(Name, Expected)   \
   CHECK_ERROR(Name, UnparseableEnumOptionError, Expected)
 
-  CHECK_VAL(TestCheck.getLocal("Valid", Map), Colours::Red);
-  CHECK_VAL(TestCheck.getGlobal("GlobalValid", Map), Colours::Violet);
-  CHECK_VAL(TestCheck.getLocal("ValidWrongCase", Map, /*IgnoreCase*/ true),
-Colours::Red);
+  CHECK_VAL(TestCheck.getIntLocal("Valid"), Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValid"), Colours::Violet);
   CHECK_VAL(
-  TestCheck.getGlobal("GlobalValidWrongCase", Map, /*IgnoreCase*/ true),
-  Colours::Violet);
-  CHECK_ERROR_ENUM(TestCheck.getLocal("Invalid", Map),
+  TestCheck.getIntLocal("ValidWrongCase", /*IgnoreCase*/ true),
+  Colours::Red);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalValidWrongCase",
+/*IgnoreCase*/ true),
+Colours::Violet);
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("Invalid"),
"invalid configuration value "
"'Scarlet' for option 'test.Invalid'");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("ValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("ValidWrongCase"),
"invalid configuration value 'rED' for option "
"'test.ValidWrongCase'; did you mean 'Red'?");
-  CHECK_ERROR_ENUM(TestCheck.getLocal("NearMiss", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntLocal("NearMiss"),
"invalid configuration value 'Oragne' for option "
"'test.NearMiss'; did you mean 'Orange'?");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalInvalid", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalInvalid"),
"invalid configuration value "
"'Purple' for option 'GlobalInvalid'");
-  CHECK_ERROR_ENUM(TestCheck.getGlobal("GlobalValidWrongCase", Map),
+  CHECK_ERROR_ENUM(TestCheck.getIntGlobal("GlobalValidWrongCase"),
"invalid configuration value 'vIOLET' for option "
   

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D82089#2100802 , @Eugene.Zelenko 
wrote:

> It'll be interesting to run improved check over LLVM code base.


I haven't tried running it over llvm, but I have had success using it with 
clangd in my editor, every loop I've tried seems to work a charm.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81923: [clang-tidy] Add modernize-use-ranges check.

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271855.
njames93 added a comment.

Added `IncludeInserter` to include the `` header.
Added support for reverse iteration controlled by config.
Added support for begin/end calls via pointers.
Made the begin/end call matcher more robust if other checks want to use it down 
the line.
Moved the std lib parts out of the test case into header files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81923

Files:
  clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseRangesCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-use-ranges.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/algorithm
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/execution
  clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-use-ranges/vector
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-ranges.cpp
@@ -0,0 +1,133 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t -- -- -isystem %S/Inputs/modernize-use-ranges
+
+// Ensure no warnings are generated when not in c++20 mode
+// RUN: clang-tidy %s -checks=-*,modernize-use-ranges --warnings-as-errors=modernize-use-ranges -- -nostdinc++ -std=c++17 -isystem %S/Inputs/modernize-use-ranges
+
+#include 
+#include 
+#include 
+// CHECK-FIXES: #include 
+
+template 
+class smart_pointer {
+public:
+  T *();
+  T *operator->();
+};
+
+void goodBeginEndCalls(const std::vector ) {
+  std::find(Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(Vec.cbegin(), Vec.cend(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::begin(Vec), std::end(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::cbegin(Vec), std::cend(Vec), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+  std::find(std::execution::parallel_policy(), Vec.begin(), Vec.end(), 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace find with std::ranges::find
+
+  // CHECK-FIXES:  std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(Vec, 1);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::find(std::execution::parallel_policy(), Vec, 1);
+  // CHECK-FIXES-NEXT: //
+}
+
+void badBeginEndCalls(const std::vector ,
+  const std::vector ) {
+  // end, begin.
+  std::find(Vec.end(), Vec.begin(), 1);
+  std::find(Vec.cend(), Vec.cbegin(), 1);
+  std::find(std::end(Vec), std::begin(Vec), 1);
+  std::find(std::cend(Vec), std::cbegin(Vec), 1);
+
+  // begin, begin.
+  std::find(Vec.begin(), Vec.begin(), 1);
+  // end, end.
+  std::find(Vec.end(), Vec.end(), 1);
+
+  // Different containers, definitely bad, but not what this check is for.
+  std::find(Vec.begin(), Vec2.end(), 1);
+}
+
+void maybeDualArg(const std::vector , std::vector ) {
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(std::execution::sequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+  std::equal(std::execution::unsequenced_policy(), Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace equal with std::ranges::equal
+
+  // CHECK-FIXES:  std::ranges::equal(Vec1, Vec2.begin());
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(Vec1, Vec2);
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(std::execution::sequenced_policy(), Vec1, Vec2.begin());
+  // CHECK-FIXES-NEXT: //
+  // CHECK-FIXES-NEXT: std::ranges::equal(std::execution::unsequenced_policy(), Vec1, Vec2);
+  // CHECK-FIXES-NEXT: //
+}
+
+void dualArg(const std::vector , const std::vector ) {
+  std::includes(Vec1.begin(), Vec1.end(), Vec2.begin(), Vec2.end());
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: replace includes 

[PATCH] D82089: [clang-tidy] modernize-loop-convert reverse iteration support

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 271856.
njames93 added a comment.

- Change default c++20 include to `ranges` instead of `algorithm`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.h
  clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/modernize-loop-convert.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-reverse.cpp
@@ -0,0 +1,120 @@
+// RUN: %check_clang_tidy -std=c++20 -check-suffix=RANGES %s modernize-loop-convert %t
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'llvm::reverse'}, \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'llvm/ADT/STLExtras.h'}]}"
+
+// Ensure the check doesn't transform reverse loops when not in c++20 mode or
+// when UseCxx20ReverseRanges has been disabled
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -- -std=c++17 | count 0
+
+// RUN: clang-tidy %s -checks=-*,modernize-loop-convert -config="{CheckOptions: \
+// RUN: [{key: modernize-loop-convert.UseCxx20ReverseRanges, value: 'false'}] \
+// RUN: }" -- -std=c++20 | count 0
+
+// RUN: %check_clang_tidy -check-suffix=CUSTOM-NO-HEADER %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeFunction, value: 'globalReverse'}]}"
+
+// Ensure we get a warning if we only supply one of the required reverse range arguments.
+// RUN: %check_clang_tidy -check-suffix=BAD-CUSTOM %s modernize-loop-convert %t -- \
+// RUN:   -config="{CheckOptions: [ \
+// RUN:   {key: modernize-loop-convert.MakeReverseRangeHeader, value: 'ranges/v3/views/reverse.hpp'}]}"
+
+// CHECK-MESSAGES-BAD-CUSTOM: warning: modernize-loop-convert: 'MakeReverseRangeHeader' is set but 'MakeReverseRangeFunction' is not, disabling reverse loop transformation
+
+// Make sure appropiate headers are included
+// CHECK-FIXES-RANGES: #include 
+// CHECK-FIXES-CUSTOM: #include "llvm/ADT/STLExtras.h"
+
+// Make sure no header is included in this example
+// CHECK-FIXES-CUSTOM-NO-HEADER-NOT: #include
+
+template 
+struct reversable {
+  using iterator = T *;
+  using const_iterator = const T *;
+
+  iterator begin();
+  iterator end();
+  iterator rbegin();
+  iterator rend();
+
+  const_iterator begin() const;
+  const_iterator end() const;
+  const_iterator rbegin() const;
+  const_iterator rend() const;
+
+  const_iterator cbegin() const;
+  const_iterator cend() const;
+  const_iterator crbegin() const;
+  const_iterator crend() const;
+};
+
+template 
+void observe(const T &);
+template 
+void mutate(T &);
+
+void constContainer(const reversable ) {
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.rbegin(), E = Numbers.rend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+  // CHECK-MESSAGES-RANGES: :[[@LINE+3]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM: :[[@LINE+2]]:3: warning: use range-based for loop instead
+  // CHECK-MESSAGES-CUSTOM-NO-HEADER: :[[@LINE+1]]:3: warning: use range-based for loop instead
+  for (auto I = Numbers.crbegin(), E = Numbers.crend(); I != E; ++I) {
+observe(*I);
+//  CHECK-FIXES-RANGES: for (int Number : std::ranges::reverse_view(Numbers)) {
+// CHECK-FIXES-RANGES-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM: for (int Number : llvm::reverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NEXT: observe(Number);
+//  CHECK-FIXES-CUSTOM-NO-HEADER: for (int Number : globalReverse(Numbers)) {
+// CHECK-FIXES-CUSTOM-NO-HEADER-NEXT: observe(Number);
+  }
+
+  // Ensure these bad loops aren't transformed.
+  for (auto I = Numbers.rbegin(), E = Numbers.end(); I != E; ++I) {
+observe(*I);
+  }
+  for (auto I = 

[PATCH] D82661: [clang-tidy][NFC} Remove unnecessary includes throughout clang-tidy header files

2020-06-28 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 273894.
njames93 retitled this revision from "[clang-tidy][NFC] Remove unnecessary 
includes throughout clang-tidy header files" to "[clang-tidy][NFC} Remove 
unnecessary includes throughout clang-tidy header files".
njames93 edited the summary of this revision.
njames93 added a comment.

Remove the changes to `std::map` -> `llvm::StringMap<...>`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82661

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/ClangTidyModule.cpp
  clang-tools-extra/clang-tidy/ClangTidyModule.h
  clang-tools-extra/clang-tidy/ClangTidyProfiling.h
  clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationUnnecessaryConversionCheck.h
  clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.h
  clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h
  clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.h
  clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h
  clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h
  clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.h
  
clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
  
clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InterfacesGlobalInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NoMallocCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeConstCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeReinterpretCastCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
  clang-tools-extra/clang-tidy/fuchsia/DefaultArgumentsDeclarationsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidUnderscoreInGoogletestNameCheck.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h
  

[PATCH] D81917: [clang-tidy] For `run-clang-tidy.py` escape the paths that are used for analysis.

2020-06-28 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.

Looks good


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81917



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82626: [CodeComplete] Tweak completion for else.

2020-06-28 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I'm still unsure what is the best behaviour here.
Would suggesting both patterns, but sort them based on what the then branch 
uses be best
Example with:

  if (...) {
// Statements
  }

Suggestions:

  - else { // Statements }
  - else if (...) { // Statements }
  - else // Statement
  - else if (...) // Statement

---

With:

  if (...) 
// Statement
  }

Suggestions:

  - else // Statement
  - else if (...) // Statement
  - else { // Statements }
  - else if (...) { // Statements }

Or is it best keeping with the behaviour of this patch where only 1 suggestion 
appears based on whether braces are used or not??


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82626



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82706: [ASTMatchers] Enhanced support for matchers taking Regex arguments

2020-06-28 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: klimek, aaron.ballman.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya.
Herald added projects: clang, LLVM.

Added new Macros `AST(_POLYMORPHIC)_MATCHER_REGEX(_OVERLOAD)` that define a 
matchers that take a regular expression string and optionally regular 
expression flags. This lets users match against nodes while ignoring the case 
without having to manually use `[Aa]` or `[A-Fa-f]` in their regex. The other 
point this addresses is in the current state, matchers that use regular 
expressions have to compile them for each node they try to match on, Now the 
regular expression is compiled once when you define the matcher and used for 
every node that it tries to match against. If there is an error while compiling 
the regular expression an error will be logged to stderr showing the bad regex 
string and the reason it couldn't be compiled. The old behaviour of this was 
down to the Matcher implementation and some would assert, whereas others just 
would never match. Support for this has been added to the documentation script 
as well. Support for this has been added to dynamic matchers ensuring 
functionality is the same between the 2 use cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82706

Files:
  clang/docs/LibASTMatchersReference.html
  clang/docs/tools/dump_ast_matchers.py
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersMacros.h
  clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
  clang/lib/ASTMatchers/Dynamic/Marshallers.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
  clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
  llvm/include/llvm/Support/Regex.h
  llvm/lib/Support/Regex.cpp

Index: llvm/lib/Support/Regex.cpp
===
--- llvm/lib/Support/Regex.cpp
+++ llvm/lib/Support/Regex.cpp
@@ -26,7 +26,7 @@
 
 Regex::Regex() : preg(nullptr), error(REG_BADPAT) {}
 
-Regex::Regex(StringRef regex, unsigned Flags) {
+Regex::Regex(StringRef regex, RegexFlags Flags) {
   unsigned flags = 0;
   preg = new llvm_regex();
   preg->re_endp = regex.end();
@@ -39,6 +39,9 @@
   error = llvm_regcomp(preg, regex.data(), flags|REG_PEND);
 }
 
+Regex::Regex(StringRef regex, unsigned Flags)
+: Regex(regex, static_cast(Flags)) {}
+
 Regex::Regex(Regex &) {
   preg = regex.preg;
   error = regex.error;
Index: llvm/include/llvm/Support/Regex.h
===
--- llvm/include/llvm/Support/Regex.h
+++ llvm/include/llvm/Support/Regex.h
@@ -16,6 +16,7 @@
 #ifndef LLVM_SUPPORT_REGEX_H
 #define LLVM_SUPPORT_REGEX_H
 
+#include "llvm/ADT/BitmaskEnum.h"
 #include 
 
 struct llvm_regex;
@@ -26,20 +27,22 @@
 
   class Regex {
   public:
-enum {
-  NoFlags=0,
+enum RegexFlags : unsigned {
+  NoFlags = 0,
   /// Compile for matching that ignores upper/lower case distinctions.
-  IgnoreCase=1,
+  IgnoreCase = 1,
   /// Compile for newline-sensitive matching. With this flag '[^' bracket
   /// expressions and '.' never match newline. A ^ anchor matches the
   /// null string after any newline in the string in addition to its normal
   /// function, and the $ anchor matches the null string before any
   /// newline in the string in addition to its normal function.
-  Newline=2,
+  Newline = 2,
   /// By default, the POSIX extended regular expression (ERE) syntax is
   /// assumed. Pass this flag to turn on basic regular expressions (BRE)
   /// instead.
-  BasicRegex=4
+  BasicRegex = 4,
+
+  LLVM_MARK_AS_BITMASK_ENUM(BasicRegex)
 };
 
 Regex();
@@ -47,7 +50,8 @@
 ///
 /// \param Regex - referenced string is no longer needed after this
 /// constructor does finish.  Only its compiled form is kept stored.
-Regex(StringRef Regex, unsigned Flags = NoFlags);
+Regex(StringRef Regex, RegexFlags Flags = NoFlags);
+Regex(StringRef Regex, unsigned Flags);
 Regex(const Regex &) = delete;
 Regex =(Regex regex) {
   std::swap(preg, regex.preg);
Index: clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
===
--- clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -259,6 +259,15 @@
   EXPECT_TRUE(matches("unsigned X = sizeof(int);", MStmt));
   EXPECT_FALSE(matches("unsigned X = alignof(int);", MStmt));
 
+  Code =
+  R"query(namedDecl(matchesName("^::[ABC]*$", "IgnoreCase | BasicRegex")))query";
+  llvm::Optional MatchesName(
+  Parser::parseMatcherExpression(Code, nullptr, nullptr, ));
+  EXPECT_EQ("", Error.toStringFull());
+  M = MatchesName->unconditionalConvertTo();
+  EXPECT_TRUE(matches("unsigned AAACCBB;", M));
+  EXPECT_TRUE(matches("unsigned aaaccbb;", M));
+
   Code = "hasInitializer(\n  

[PATCH] D82707: [clang][docs] Remove untracked files from formatted status

2020-06-28 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: krasimir, JakeMerdichAMD, sammccall, curdeius, bollu, 
alexshap, jdoerfert, DavidTruby, sscalpone, MyDeveloperDay.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently on http://clang.llvm.org/docs/ClangFormattedStatus.html there are 
format stats on files no actually inside the tree but generated by build 
scripts. These are usually copied from somewhere else. Right now for example 
there are files from `llvm/utils/release/llvm-package...`. Adding these files 
bloats the list while not giving an accurate representation of how formatted 
the repo is.
This addresses this issue by checking the git index and ignoring any folder 
that doesn't contain tracked files.

I'm still unsure whether it would be better to just do away with the `os.walk` 
method and just check over every file returned from `git ls-index 
`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82707

Files:
  clang/docs/tools/generate_formatted_state.py


Index: clang/docs/tools/generate_formatted_state.py
===
--- clang/docs/tools/generate_formatted_state.py
+++ clang/docs/tools/generate_formatted_state.py
@@ -72,6 +72,8 @@
  - {style2}`{percent}%`
 """
 
+FNULL = open(os.devnull, 'w')
+
 with open(DOC_FILE, 'wb') as output:
 sha = get_git_revision_short_hash()
 today = datetime.now().strftime("%B %d, %Y %H:%M:%S")
@@ -85,14 +87,22 @@
 for subdir in subdirs:
 if any(sd == subdir for sd in skipped_dirs):
 subdirs.remove(subdir)
+else:
+act_sub_dir = os.path.join(root, subdir)
+# Check the git index to see if the directory contains tracked
+# files. Reditect the output to a null descriptor as we aren't
+# interested in it, just the return code.
+git_check = subprocess.Popen(
+["git", "ls-files", "--error-unmatch", act_sub_dir],
+stdout=FNULL,
+stderr=FNULL)
+if git_check.wait() != 0:
+print("Skipping directory: ", act_sub_dir)
+subdirs.remove(subdir)
 
 path = os.path.relpath(root, TOP_DIR)
 path = path.replace('\\', '/')
 
-head, _ = os.path.split(root)
-while head:
-head, _ = os.path.split(head)
-
 file_count = 0
 file_pass = 0
 file_fail = 0


Index: clang/docs/tools/generate_formatted_state.py
===
--- clang/docs/tools/generate_formatted_state.py
+++ clang/docs/tools/generate_formatted_state.py
@@ -72,6 +72,8 @@
  - {style2}`{percent}%`
 """
 
+FNULL = open(os.devnull, 'w')
+
 with open(DOC_FILE, 'wb') as output:
 sha = get_git_revision_short_hash()
 today = datetime.now().strftime("%B %d, %Y %H:%M:%S")
@@ -85,14 +87,22 @@
 for subdir in subdirs:
 if any(sd == subdir for sd in skipped_dirs):
 subdirs.remove(subdir)
+else:
+act_sub_dir = os.path.join(root, subdir)
+# Check the git index to see if the directory contains tracked
+# files. Reditect the output to a null descriptor as we aren't
+# interested in it, just the return code.
+git_check = subprocess.Popen(
+["git", "ls-files", "--error-unmatch", act_sub_dir],
+stdout=FNULL,
+stderr=FNULL)
+if git_check.wait() != 0:
+print("Skipping directory: ", act_sub_dir)
+subdirs.remove(subdir)
 
 path = os.path.relpath(root, TOP_DIR)
 path = path.replace('\\', '/')
 
-head, _ = os.path.split(root)
-while head:
-head, _ = os.path.split(head)
-
 file_count = 0
 file_pass = 0
 file_fail = 0
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82661: [clang-tidy] Remove unnecessary includes throughout clang-tidy header files

2020-06-26 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh.
Herald added subscribers: cfe-commits, lebedev.ri, arphaman, dexonsmith, 
steven_wu, kbarton, hiraditya, xazax.hun, nemanjai.
Herald added a reviewer: lebedev.ri.
Herald added a project: clang.

Plus replacing a few std::map with llvm::StringMap


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D82661

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/ClangTidyModule.cpp
  clang-tools-extra/clang-tidy/ClangTidyModule.h
  clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
  clang-tools-extra/clang-tidy/ClangTidyOptions.h
  clang-tools-extra/clang-tidy/ClangTidyProfiling.h
  clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp
  clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/DurationUnnecessaryConversionCheck.h
  clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.h
  clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h
  clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.h
  clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h
  clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.h
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp
  clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp
  clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h
  clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.h
  
clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
  
clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InterfacesGlobalInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/NoMallocCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/OwningMemoryCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeConstCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeCstyleCastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeReinterpretCastCheck.h
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
  clang-tools-extra/clang-tidy/fuchsia/DefaultArgumentsDeclarationsCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp
  clang-tools-extra/clang-tidy/google/AvoidUnderscoreInGoogletestNameCheck.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  

[PATCH] D82002: [clangd] Drop FS usage in ClangTidyOpts

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:495-498
+bool HasChecks = false;
+for (const auto  : Sources)
+  HasChecks |= Source.first.Checks.hasValue();
+if (!HasChecks)

`if (llvm::none_of(Sources, [](const auto ) { return 
Source.first.Checks.hasValue(); }))`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82002



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81785: [clangd] Fix readability-else-after-return 'Adding a note without main diagnostic' crash

2020-06-15 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 270759.
njames93 marked an inline comment as done.
njames93 added a comment.

- Remove clangd test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81785

Files:
  clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp


Index: clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -188,9 +188,8 @@
 if (IsLastInScope) {
   // If the if statement is the last statement its enclosing statements
   // scope, we can pull the decl out of the if statement.
-  DiagnosticBuilder Diag =
-  diag(ElseLoc, WarningMessage, clang::DiagnosticIDs::Level::Remark)
-  << ControlFlowInterruptor;
+  DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
+   << ControlFlowInterruptor;
   if (checkInitDeclUsageInElse(If) != nullptr) {
 Diag << tooling::fixit::createReplacement(
 SourceRange(If->getIfLoc()),


Index: clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -188,9 +188,8 @@
 if (IsLastInScope) {
   // If the if statement is the last statement its enclosing statements
   // scope, we can pull the decl out of the if statement.
-  DiagnosticBuilder Diag =
-  diag(ElseLoc, WarningMessage, clang::DiagnosticIDs::Level::Remark)
-  << ControlFlowInterruptor;
+  DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
+   << ControlFlowInterruptor;
   if (checkInitDeclUsageInElse(If) != nullptr) {
 Diag << tooling::fixit::createReplacement(
 SourceRange(If->getIfLoc()),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81785: [clangd] Fix readability-else-after-return 'Adding a note without main diagnostic' crash

2020-06-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp:191
   // scope, we can pull the decl out of the if statement.
-  DiagnosticBuilder Diag =
-  diag(ElseLoc, WarningMessage, clang::DiagnosticIDs::Level::Remark)
-  << ControlFlowInterruptor;
+  DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
+   << ControlFlowInterruptor;

hokein wrote:
> this would change the output of the check, I suppose this is not covered in 
> `readability-else-after-return.cpp` lit test (that test only tests `warning` 
> messages), could you add a test there? then we don't need a test case in 
> clangd.
For some reason, I don't know why, it doesn't appear to. I changed all diags in 
the check to use remark, yet the outputs all said warning. not sure why though. 
There is a test case already for this specific case in the check that looks for 
warning. maybe I should just remove the clangd test case though, its not 
terribly important for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81785



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81975: [clangd] Add command line option for ClangTidyConfig

2020-06-16 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: sammccall, kadircet, hokein.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

Adds a command line flag `clang-tidy-config` for specifing configuration of 
checks, in much the same way that clang-tidy does.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81975

Files:
  clang-tools-extra/clangd/test/clang-tidy-config.test
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -149,6 +149,15 @@
 init(""),
 };
 
+opt ClangTidyConfig{
+"clang-tidy-config",
+cat(Features),
+desc("Specifies a YAML/JSON configuration for when running clang-tidy "
+ "checks (this will override clang-tidy files). Only meaningful when "
+ "-clang-tidy flag is on"),
+init(""),
+};
+
 opt CodeCompletionParse{
 "completion-parse",
 cat(Features),
@@ -714,10 +723,23 @@
 tidy::ClangTidyOptions OverrideClangTidyOptions;
 if (!ClangTidyChecks.empty())
   OverrideClangTidyOptions.Checks = ClangTidyChecks;
-ClangTidyOptProvider = std::make_unique(
-tidy::ClangTidyGlobalOptions(),
-/* Default */ EmptyDefaults,
-/* Override */ OverrideClangTidyOptions, FSProvider.getFileSystem());
+if (ClangTidyConfig.empty()) {
+  ClangTidyOptProvider = std::make_unique(
+  tidy::ClangTidyGlobalOptions(),
+  /* Default */ EmptyDefaults,
+  /* Override */ OverrideClangTidyOptions, FSProvider.getFileSystem());
+} else {
+  llvm::ErrorOr ParsedConfig =
+  tidy::parseConfiguration(ClangTidyConfig);
+  if (!ParsedConfig) {
+elog("Invalid -clang-tidy-config: {0}",
+ ParsedConfig.getError().message());
+return 1;
+  }
+  ClangTidyOptProvider = std::make_unique(
+  tidy::ClangTidyGlobalOptions(), EmptyDefaults, *ParsedConfig,
+  OverrideClangTidyOptions);
+}
 Opts.GetClangTidyOptions = [&](llvm::vfs::FileSystem &,
llvm::StringRef File) {
   // This function must be thread-safe and tidy option providers are not.
Index: clang-tools-extra/clangd/test/clang-tidy-config.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/clang-tidy-config.test
@@ -0,0 +1,40 @@
+# RUN: clangd -lit-test -clang-tidy-config="{CheckOptions: [{key: 
readability-identifier-naming.FunctionCase, value: camelBack}], Checks: 
'-*,readability-identifier-naming' }" < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.c","languageId":"c","text":"void
 BadName();"}}}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"code": "readability-identifier-naming",
+# CHECK-NEXT:"message": "Invalid case style for function 'BadName' 
(fix available)",
+# CHECK-NEXT:"range": {
+# CHECK-NEXT:  "end": {
+# CHECK-NEXT:"character": 12,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "start": {
+# CHECK-NEXT:"character": 5,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  }
+# CHECK-NEXT:},
+# CHECK-NEXT:"severity": 2,
+# CHECK-NEXT:"source": "clang-tidy"
+# CHECK-NEXT:  }
+# CHECK-NEXT:],
+# CHECK-NEXT:"uri": "file://{{.*}}/foo.c",
+# CHECK-NEXT:"version": 0
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":2,"method":"sync","params":null}
+---
+{"jsonrpc":"2.0","method":"textDocument/didClose","params":{"textDocument":{"uri":"test:///foo.c"}}}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [],
+# CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -149,6 +149,15 @@
 init(""),
 };
 
+opt ClangTidyConfig{
+"clang-tidy-config",
+cat(Features),
+desc("Specifies a YAML/JSON configuration for when running clang-tidy "
+ "checks (this will override clang-tidy files). Only meaningful when "
+ "-clang-tidy flag is on"),
+init(""),
+};
+
 opt CodeCompletionParse{
 

[PATCH] D75184: [clang-tidy] Optional inheritance of file configs from parent directories 

2020-06-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

As an afterthought, Would you think it a good idea to extend this logic to the 
`ConfigOptionsProvider` That way you can use something along the lines of:

  clang-tidy --config='{InheritParentConfig: true, CheckOptions: []}'

clang-tidy would then go to read the .clang-tidy configuration files in much 
the same was as is done here. This would let you set custom configuration 
options on the command line on top of whats in configuration files.
Obviously is `InheritParentConfig` is unset or `false` then we wouldn't go 
looking for .clang-tidy files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75184



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82002: [clangd] Drop FS usage in ClangTidyOpts

2020-06-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I'm of the idea that rather than having `ClangdTidyOptionsProvider` inherit 
form `tidy::ClangTidyOptionsProvider`, just have it as its own class. We don't 
need the interface offered by clang tidy here. It would solve the `must be 
threadsafe` comment issue as well as reduce the need for some unnecessary code 
in there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82002



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 269076.
njames93 added a comment.

Added back isExpansionInMainFile check

Should put a follow up to query removing this check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantiate() {
+  // Just make sure the check isn't fooled by template instantiations.
+  ignoreInstantiations();
+  ignoreInstantiations();
+}
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(isExpansionInMainFile(), unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -433,6 +433,7 @@
   StringRef TernaryId) {
   Finder->addMatcher(
   conditionalOperator(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   hasTrueExpression(cxxBoolLiteral(equals(Value))),
   hasFalseExpression(cxxBoolLiteral(equals(!Value
   .bind(TernaryId),
@@ -443,12 +444,14 @@
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
 Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
 Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+  unless(isInTemplateInstantiation()),
   unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
@@ -474,12 +477,16 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  hasThen(Then), hasElse(Else))
+   .bind(Id),
+   this);
   else
-Finder->addMatcher(
-ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
-.bind(Id),
-this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  unless(hasParent(ifStmt())), hasThen(Then),
+  hasElse(Else))
+   .bind(Id),
+   this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -487,6 +494,7 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(


Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void 

[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

aaron.ballman wrote:
> njames93 wrote:
> > aaron.ballman wrote:
> > > This is changing the behavior so that now it will diagnose in header 
> > > files, no? Why is the correct change to replace this with 
> > > `unless(isInTemplateInstantiation())` instead of adding the new matcher?
> > It's changing behaviour that arguably shouldn't have been in the first 
> > place. But perhaps that change should go on a new patch or update the 
> > description of this one
> I'll admit that the original code seems a bit suspect to me. I sort of wonder 
> if it was being used to suppress diagnosing macros unless they're considered 
> to be under the user's control. e.g., macros in headers may not be plausible 
> to change but macros in source files are.
> 
> If changes should be made here, I don't have strong opinions on whether it 
> requires a separate patch or can be done in this one, but I'd like to better 
> understand why the original code was incorrect (if it is in fact incorrect).
So having a look in the archives shows this condition was on the [[ 
https://reviews.llvm.org/D7648?id=19976 | first draft for this check. ]] But I 
couldn't see any discussion about it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-07 Thread Nathan James via Phabricator via cfe-commits
njames93 marked an inline comment as done.
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp:425
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))

aaron.ballman wrote:
> This is changing the behavior so that now it will diagnose in header files, 
> no? Why is the correct change to replace this with 
> `unless(isInTemplateInstantiation())` instead of adding the new matcher?
It's changing behaviour that arguably shouldn't have been in the first place. 
But perhaps that change should go on a new patch or update the description of 
this one


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81336



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79912: Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

2020-06-09 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D79912#2083477 , @Tridacnid wrote:

> Bug report has been closed. I'm seeing some build failures in my inbox but 
> eyeballing them doesn't make me think this change is related. What is the 
> expectation for me in this scenario? Will I get an email letting me know once 
> the build has been fixed?


If you get those emails often it means your patch was included in a bunch of 
patches where one caused the failed build, usually its obvious if your changes 
are causing the build failure. If it is your patch you will need to push a 
quick fix for it, or revert if it turns out to be more complicated (As you 
don't have commit access you can just ask someone else to do it for you). If 
someone else spots that a patch is causing build failures they may leave a 
comment in the review to point you in the right direction.
If you do decide to get commit access, its also a good idea to run `ninja 
check-` before you push, with component being the part of the repo 
your patch touches, to reduce the chances of failures. In this case I ran 
`check-clang` and `check-clang-tools`, This isn't fool proof as some of the 
build slaves run of different platforms which have slight subtleties of how 
they handle certain things but will certainly increase your chance of success


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79912



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81552: [ASTMatchers] Added hasDirectBase and hasClass Matchers

2020-06-10 Thread Nathan James via Phabricator via cfe-commits
njames93 marked 2 inline comments as done.
njames93 added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:2888-2890
+///   class Foo;
+///   class Bar : Foo {};
+///   class Baz : Bar {};

aaron.ballman wrote:
> It seems like these aren't really part of the example?
They are, just not directly. Shows it won't match any old base specifier.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:3537
 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
-hasType,
-AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
-CXXBaseSpecifier),
+hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
 internal::Matcher, InnerMatcher, 1) {

aaron.ballman wrote:
> This is undoing a change that was just added less than two weeks ago, so I 
> think the potential for breaking code is small. That said, can you explain 
> why you think `hasClass` is a better approach than `hasType`?
Yeah, as that change hasn't reached landed onto a release branch breaking code 
shouldn't be an issue, If it was I'd leave it in.

- `hasType` is very generic, whereas `hasClass` is specific to what a 
`CXXBaseSpecifier` supports.
- It makes the matchers marginally simpler.
  `hasDirectBase(hasType(cxxRecordDecl(hasName("Base"` vs 
`hasDirectBase(hasClass(hasName("Base")))`
- In the documentation it also specifies that `hasClass` takes a 
`Matcher, making it more user friendly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81552



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81552: [ASTMatchers] Added hasDirectBase and hasClass Matchers

2020-06-10 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: klimek, aaron.ballman, jkorous.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Adds a matcher called `hasDirectBase` for matching the `CXXBaseSpecifier` of a 
class that directly derives from another class.
Adds a matcher called `hasClass` that matches on the class that a 
`CXXBaseSpecifier` refers to.
Also removed the `CXXBaseSpecifier` overload for the `hasType` Matcher in 
favour of this `hasClass` matcher.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81552

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2997,26 +2997,24 @@
 }
 
 TEST(HasAnyBase, DirectBase) {
-  EXPECT_TRUE(matches(
-  "struct Base {};"
-  "struct ExpectedMatch : Base {};",
-  cxxRecordDecl(hasName("ExpectedMatch"),
-hasAnyBase(hasType(cxxRecordDecl(hasName("Base")));
+  EXPECT_TRUE(matches("struct Base {};"
+  "struct ExpectedMatch : Base {};",
+  cxxRecordDecl(hasName("ExpectedMatch"),
+hasAnyBase(hasClass(hasName("Base"));
 }
 
 TEST(HasAnyBase, IndirectBase) {
-  EXPECT_TRUE(matches(
-  "struct Base {};"
-  "struct Intermediate : Base {};"
-  "struct ExpectedMatch : Intermediate {};",
-  cxxRecordDecl(hasName("ExpectedMatch"),
-hasAnyBase(hasType(cxxRecordDecl(hasName("Base")));
+  EXPECT_TRUE(matches("struct Base {};"
+  "struct Intermediate : Base {};"
+  "struct ExpectedMatch : Intermediate {};",
+  cxxRecordDecl(hasName("ExpectedMatch"),
+hasAnyBase(hasClass(hasName("Base"));
 }
 
 TEST(HasAnyBase, NoBase) {
   EXPECT_TRUE(notMatches("struct Foo {};"
  "struct Bar {};",
- cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl());
+ cxxRecordDecl(hasAnyBase(hasClass(cxxRecordDecl());
 }
 
 TEST(IsPublicBase, Public) {
@@ -3117,5 +3115,57 @@
  cxxRecordDecl(hasAnyBase(isVirtual();
 }
 
+TEST(BaseSpecifier, hasDirectBase) {
+  EXPECT_TRUE(matches(
+  R"cc(
+class Base {};
+class Derived : Base{};
+)cc",
+  cxxRecordDecl(hasName("Derived"),
+hasDirectBase(hasClass(hasName("Base"));
+
+  StringRef MultiDerived = R"cc(
+class Base {};
+class Base2 {};
+class Derived : Base, Base2{};
+)cc";
+
+  EXPECT_TRUE(matches(MultiDerived,
+  cxxRecordDecl(hasName("Derived"),
+hasDirectBase(hasClass(hasName("Base"));
+  EXPECT_TRUE(matches(
+  MultiDerived, cxxRecordDecl(hasName("Derived"),
+  hasDirectBase(hasClass(hasName("Base2"));
+
+  StringRef Indirect = R"cc(
+class Base {};
+class Intermediate : Base {};
+class Derived : Intermediate{};
+)cc";
+
+  EXPECT_TRUE(
+  matches(Indirect,
+  cxxRecordDecl(hasName("Derived"),
+hasDirectBase(hasClass(hasName("Intermediate"));
+  EXPECT_TRUE(notMatches(
+  Indirect, cxxRecordDecl(hasName("Derived"),
+  hasDirectBase(hasClass(hasName("Base"));
+
+  // Only really here to make sure the asserts don't fire
+  EXPECT_FALSE(
+  matches(R"cc(
+class Base {};
+class Derived : BAse {};
+  )cc",
+  cxxRecordDecl(hasDirectBase(hasClass(hasName("Base"));
+
+  EXPECT_FALSE(
+  matches(R"cc(
+using Base = int;
+class Derived : Base {};
+  )cc",
+  cxxRecordDecl(hasDirectBase(hasClass(hasName("Base"));
+}
+
 } // namespace ast_matchers
 } // namespace clang
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -261,6 +261,7 @@
   REGISTER_MATCHER(hasCanonicalType);
   REGISTER_MATCHER(hasCaseConstant);
   REGISTER_MATCHER(hasCastKind);
+  REGISTER_MATCHER(hasClass);
   REGISTER_MATCHER(hasCondition);
   REGISTER_MATCHER(hasConditionVariableStatement);
   REGISTER_MATCHER(hasDecayedType);
@@ -271,6 +272,7 @@
   REGISTER_MATCHER(hasDefinition);
   REGISTER_MATCHER(hasDescendant);
   REGISTER_MATCHER(hasDestinationType);
+  REGISTER_MATCHER(hasDirectBase);
   REGISTER_MATCHER(hasDynamicExceptionSpec);
   

[PATCH] D81396: [clang-tidy] New util `Aliasing` factored out from `bugprone-infinite-loop`

2020-06-10 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.

LGTM, but with one more nit




Comment at: clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp:16
 using namespace clang::ast_matchers;
+using clang::tidy::utils::hasPtrOrReferenceInFunc;
 

This function is only used once in the file, so may as well remove this line 
and just qualify its call further down.



Comment at: clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp:60
 
   return hasPtrOrReferenceInFunc(Func, Var) ||
  isChanged(LoopStmt, Var, Context);

here.


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

https://reviews.llvm.org/D81396



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81396: [clang-tidy] New util `Aliasing` factored out from `bugprone-infinite-loop`

2020-06-10 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/utils/Aliasing.cpp:17
+
+/// Return whether `S` is a reference to the declaration of `Var`.
+static bool isAccessForVar(const Stmt *S, const VarDecl *Var) {

Ditto `\p `.



Comment at: clang-tools-extra/clang-tidy/utils/Aliasing.cpp:25
+
+/// Return whether `Var` has a pointer or reference in `S`.
+static bool isPtrOrReferenceForVar(const Stmt *S, const VarDecl *Var) {

Ditto.



Comment at: clang-tools-extra/clang-tidy/utils/Aliasing.cpp:43
+
+/// Return whether `Var` has a pointer or reference in `S`.
+static bool hasPtrOrReferenceInStmt(const Stmt *S, const VarDecl *Var) {

Ditto.



Comment at: clang-tools-extra/clang-tidy/utils/Aliasing.h:18
+
+/// Returns whether ``Var`` has a pointer or reference in ``Func``.
+///

Don't use double ticks for param names, instead use `\p `.


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

https://reviews.llvm.org/D81396



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81075: [ASTMatchers] Fix crash with HasName and HasAnyName

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 268142.
njames93 added a comment.

Fix clang-format error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81075

Files:
  clang/include/clang/AST/PrettyPrinter.h
  clang/lib/AST/Decl.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -1665,7 +1665,7 @@
   StringRef code =
   "namespace a { void F(int a) { struct S { int m; }; int i; } }";
   EXPECT_TRUE(matches(code, varDecl(hasName("i";
-  EXPECT_FALSE(matches(code, varDecl(hasName("F()::i";
+  EXPECT_FALSE(matches(code, varDecl(hasName("F(int)::i";
 
   EXPECT_TRUE(matches(code, fieldDecl(hasName("m";
   EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m";
@@ -1674,6 +1674,31 @@
   EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m";
 }
 
+TEST(Matcher, HasNameSupportsFunctionScopeRecordDecl) {
+  StringRef FuncCode = R"cc(
+void A() {
+  struct B {};
+})cc";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("B";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("A()::B";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("::A()::B";
+  EXPECT_TRUE(notMatches(FuncCode, cxxRecordDecl(hasName("::B";
+
+  StringRef MethodCode = R"cc(
+struct A {
+  void B() {
+struct C {};
+  }
+};)cc";
+
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("C";
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("B()::C";
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("A::B()::C";
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("::A::B()::C";
+  EXPECT_TRUE(notMatches(MethodCode, cxxRecordDecl(hasName("::C";
+  EXPECT_TRUE(notMatches(MethodCode, cxxRecordDecl(hasName("::B()::C";
+}
+
 TEST(Matcher, HasNameQualifiedSupportsLinkage) {
   // https://bugs.llvm.org/show_bug.cgi?id=42193
   StringRef code = R"cpp(namespace foo { extern "C" void test(); })cpp";
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -571,7 +571,7 @@
   // We are allowed to skip anonymous and inline namespaces if they don't match.
   const DeclContext *Ctx = Node.getDeclContext();
 
-  if (Ctx->isFunctionOrMethod())
+  if (Ctx->isFunctionOrMethod() && !isa(Node))
 return Patterns.foundMatch(/*AllowFullyQualified=*/false);
 
   for (; Ctx; Ctx = Ctx->getParent()) {
@@ -616,13 +616,10 @@
 llvm::SmallString<128> NodeName = StringRef("::");
 llvm::raw_svector_ostream OS(NodeName);
 
-if (SkipUnwritten) {
-  PrintingPolicy Policy = Node.getASTContext().getPrintingPolicy();
-  Policy.SuppressUnwrittenScope = true;
-  Node.printQualifiedName(OS, Policy);
-} else {
-  Node.printQualifiedName(OS);
-}
+PrintingPolicy Policy = Node.getASTContext().getPrintingPolicy();
+Policy.PrintFunctionQualifiedRecords = true;
+Policy.SuppressUnwrittenScope = SkipUnwritten;
+Node.printQualifiedName(OS, Policy);
 
 const StringRef FullName = OS.str();
 
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1540,7 +1540,8 @@
 
 void NamedDecl::printQualifiedName(raw_ostream ,
const PrintingPolicy ) const {
-  if (getDeclContext()->isFunctionOrMethod()) {
+  if (getDeclContext()->isFunctionOrMethod() &&
+  !(P.PrintFunctionQualifiedRecords && isa(this))) {
 // We do not print '(anonymous)' for function parameters without name.
 printName(OS);
 return;
@@ -1583,7 +1584,8 @@
   Ctx = CI;
   }
 
-  if (Ctx->isFunctionOrMethod())
+  if (Ctx->isFunctionOrMethod() &&
+  !(P.PrintFunctionQualifiedRecords && isa(this)))
 return;
 
   using ContextsTy = SmallVector;
Index: clang/include/clang/AST/PrettyPrinter.h
===
--- clang/include/clang/AST/PrettyPrinter.h
+++ clang/include/clang/AST/PrettyPrinter.h
@@ -63,7 +63,8 @@
 MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
 MSVCFormatting(false), ConstantsAsWritten(false),
 SuppressImplicitBase(false), FullyQualifiedName(false),
-PrintCanonicalTypes(false), PrintInjectedClassNameWithArguments(true) {}
+PrintCanonicalTypes(false), PrintInjectedClassNameWithArguments(true),
+PrintFunctionQualifiedRecords(false) {}
 
   /// Adjust this printing policy for cases where it's known that we're
   

[PATCH] D80887: [clang-tidy] ignore builtin varargs from pro-type-vararg-check

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 268116.
njames93 added a comment.

Included more builtins.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function 
taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,60 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+// Disable formatting to prevent squashing the list.
+// clang-format off
+"__builtin_isgreater", 
+"__builtin_isgreaterequal", 
+"__builtin_isless",
+"__builtin_islessequal", 
+"__builtin_islessgreater", 
+"__builtin_isunordered",
+"__builtin_fpclassify", 
+"__builtin_isfinite", 
+"__builtin_isinf",
+"__builtin_isinf_sign", 
+"__builtin_isnan", 
+"__builtin_isnormal",
+"__builtin_signbit", 
+"__builtin_constant_p", 
+"__builtin_classify_type",
+// "__builtin_va_start",
+// "__builtin_stdarg_start",
+"__builtin_assume_aligned", // Documented as variadic to support 
overloading
+// "__builtin_fprintf",
+// "__builtin_printf",
+// "__builtin_snprintf",
+// "__builtin___snprintf_chk",
+// "__builtin___sprintf_chk",
+// "__builtin___fprintf_chk",
+// "__builtin___printf_chk",
+"__builtin_prefetch",  // Documented as variadic to support overloading
+"__builtin_shufflevector", // Documented as variadic but with a defined
+   // number of args based on vector size.
+"__builtin_convertvector", 
+"__builtin_call_with_static_chain",
+"__builtin_annotation", 
+"__builtin_add_overflow", 
+"__builtin_sub_overflow",
+"__builtin_mul_overflow", 
+"__builtin_preserve_access_index",
+"__builtin_nontemporal_store", 
+"__builtin_nontemporal_load",
+// "__builtin_os_log_format_buffer_size",
+// "__builtin_os_log_format",
+// "__builtin_ms_va_start",
+// clang-format on
+};
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,60 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+// Disable formatting to prevent squashing the list.
+// clang-format off
+"__builtin_isgreater", 
+"__builtin_isgreaterequal", 
+"__builtin_isless",
+"__builtin_islessequal", 
+"__builtin_islessgreater", 
+"__builtin_isunordered",
+"__builtin_fpclassify", 
+"__builtin_isfinite", 
+ 

[PATCH] D80877: [clang-tidy] Added MacroDefiniton docs for readability-identifier-naming

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG65fa0a9f7f3e: [clang-tidy] Added MacroDefiniton docs for 
readability-identifier-naming (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80877

Files:
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst


Index: 
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
@@ -62,6 +62,7 @@
  - :option:`LocalConstantPointerCase`, :option:`LocalConstantPointerPrefix`, 
:option:`LocalConstantPointerSuffix`
  - :option:`LocalPointerCase`, :option:`LocalPointerPrefix`, 
:option:`LocalPointerSuffix`
  - :option:`LocalVariableCase`, :option:`LocalVariablePrefix`, 
:option:`LocalVariableSuffix`
+ - :option:`MacroDefinitionCase`, :option:`MacroDefinitionPrefix`, 
:option:`MacroDefinitionSuffix`
  - :option:`MemberCase`, :option:`MemberPrefix`, :option:`MemberSuffix`
  - :option:`MethodCase`, :option:`MethodPrefix`, :option:`MethodSuffix`
  - :option:`NamespaceCase`, :option:`NamespacePrefix`, 
:option:`NamespaceSuffix`
@@ -1076,6 +1077,44 @@
 
 void foo() { int pre_local_constant_post; }
 
+.. option:: MacroDefinitionCase
+
+When defined, the check will ensure macro definitions conform to the
+selected casing.
+
+.. option:: MacroDefinitionPrefix
+
+When defined, the check will ensure macro definitions will add the
+prefixed with the given value (regardless of casing).
+
+.. option:: MacroDefinitionSuffix
+
+When defined, the check will ensure macro definitions will add the
+suffix with the given value (regardless of casing).
+
+For example using values of:
+
+   - MacroDefinitionCase of ``lower_case``
+   - MacroDefinitionPrefix of ``pre_``
+   - MacroDefinitionSuffix of ``_post``
+
+Identifies and/or transforms macro definitions as follows:
+
+Before:
+
+.. code-block:: c
+
+#define MY_MacroDefinition
+
+After:
+
+.. code-block:: c
+
+#define pre_my_macro_definition_post
+
+Note: This will not warn on builtin macros or macros defined on the command 
line
+using the ``-D`` flag.
+
 .. option:: MemberCase
 
 When defined, the check will ensure member names conform to the


Index: clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
@@ -62,6 +62,7 @@
  - :option:`LocalConstantPointerCase`, :option:`LocalConstantPointerPrefix`, :option:`LocalConstantPointerSuffix`
  - :option:`LocalPointerCase`, :option:`LocalPointerPrefix`, :option:`LocalPointerSuffix`
  - :option:`LocalVariableCase`, :option:`LocalVariablePrefix`, :option:`LocalVariableSuffix`
+ - :option:`MacroDefinitionCase`, :option:`MacroDefinitionPrefix`, :option:`MacroDefinitionSuffix`
  - :option:`MemberCase`, :option:`MemberPrefix`, :option:`MemberSuffix`
  - :option:`MethodCase`, :option:`MethodPrefix`, :option:`MethodSuffix`
  - :option:`NamespaceCase`, :option:`NamespacePrefix`, :option:`NamespaceSuffix`
@@ -1076,6 +1077,44 @@
 
 void foo() { int pre_local_constant_post; }
 
+.. option:: MacroDefinitionCase
+
+When defined, the check will ensure macro definitions conform to the
+selected casing.
+
+.. option:: MacroDefinitionPrefix
+
+When defined, the check will ensure macro definitions will add the
+prefixed with the given value (regardless of casing).
+
+.. option:: MacroDefinitionSuffix
+
+When defined, the check will ensure macro definitions will add the
+suffix with the given value (regardless of casing).
+
+For example using values of:
+
+   - MacroDefinitionCase of ``lower_case``
+   - MacroDefinitionPrefix of ``pre_``
+   - MacroDefinitionSuffix of ``_post``
+
+Identifies and/or transforms macro definitions as follows:
+
+Before:
+
+.. code-block:: c
+
+#define MY_MacroDefinition
+
+After:
+
+.. code-block:: c
+
+#define pre_my_macro_definition_post
+
+Note: This will not warn on builtin macros or macros defined on the command line
+using the ``-D`` flag.
+
 .. option:: MemberCase
 
 When defined, the check will ensure member names conform to the
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80536: [clang-tidy][modernize-loop-convert] Make loop var type human readable

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80536



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81075: [ASTMatchers] Fix crash with HasName and HasAnyName

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: klimek, sbenza.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes crashes caused by matching fully qualified RecordDecls inside Function 
bodies.
See https://bugs.llvm.org/show_bug.cgi?id=43639.
I'm still unsure if this is the desired behaviour though.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81075

Files:
  clang/include/clang/AST/PrettyPrinter.h
  clang/lib/AST/Decl.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -1665,7 +1665,7 @@
   StringRef code =
   "namespace a { void F(int a) { struct S { int m; }; int i; } }";
   EXPECT_TRUE(matches(code, varDecl(hasName("i";
-  EXPECT_FALSE(matches(code, varDecl(hasName("F()::i";
+  EXPECT_FALSE(matches(code, varDecl(hasName("F(int)::i";
 
   EXPECT_TRUE(matches(code, fieldDecl(hasName("m";
   EXPECT_TRUE(matches(code, fieldDecl(hasName("S::m";
@@ -1674,6 +1674,34 @@
   EXPECT_TRUE(matches(code, fieldDecl(hasName("::a::F(int)::S::m";
 }
 
+TEST(Matcher, HasNameSupportsFunctionScopeRecordDecl) {
+  StringRef FuncCode = R"cc(
+void A() {
+  struct B {};
+})cc";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("B";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("A()::B";
+  EXPECT_TRUE(matches(FuncCode, cxxRecordDecl(hasName("::A()::B";
+  EXPECT_TRUE(notMatches(FuncCode, cxxRecordDecl(hasName("::B";
+
+  StringRef MethodCode = R"cc(
+struct A {
+  void B() {
+struct C {};
+  }
+};)cc";
+
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("C";
+  EXPECT_TRUE(matches(MethodCode, cxxRecordDecl(hasName("B()::C";
+  EXPECT_TRUE(
+  matches(MethodCode, cxxRecordDecl(hasName("A::B()::C";
+  EXPECT_TRUE(
+  matches(MethodCode, cxxRecordDecl(hasName("::A::B()::C";
+  EXPECT_TRUE(notMatches(MethodCode, cxxRecordDecl(hasName("::C";
+  EXPECT_TRUE(
+  notMatches(MethodCode, cxxRecordDecl(hasName("::B()::C";
+}
+
 TEST(Matcher, HasNameQualifiedSupportsLinkage) {
   // https://bugs.llvm.org/show_bug.cgi?id=42193
   StringRef code = R"cpp(namespace foo { extern "C" void test(); })cpp";
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -571,7 +571,7 @@
   // We are allowed to skip anonymous and inline namespaces if they don't match.
   const DeclContext *Ctx = Node.getDeclContext();
 
-  if (Ctx->isFunctionOrMethod())
+  if (Ctx->isFunctionOrMethod() && !isa(Node))
 return Patterns.foundMatch(/*AllowFullyQualified=*/false);
 
   for (; Ctx; Ctx = Ctx->getParent()) {
@@ -616,13 +616,10 @@
 llvm::SmallString<128> NodeName = StringRef("::");
 llvm::raw_svector_ostream OS(NodeName);
 
-if (SkipUnwritten) {
-  PrintingPolicy Policy = Node.getASTContext().getPrintingPolicy();
-  Policy.SuppressUnwrittenScope = true;
-  Node.printQualifiedName(OS, Policy);
-} else {
-  Node.printQualifiedName(OS);
-}
+PrintingPolicy Policy = Node.getASTContext().getPrintingPolicy();
+Policy.PrintFunctionQualifiedRecords = true;
+Policy.SuppressUnwrittenScope = SkipUnwritten;
+Node.printQualifiedName(OS, Policy);
 
 const StringRef FullName = OS.str();
 
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1540,7 +1540,8 @@
 
 void NamedDecl::printQualifiedName(raw_ostream ,
const PrintingPolicy ) const {
-  if (getDeclContext()->isFunctionOrMethod()) {
+  if (getDeclContext()->isFunctionOrMethod() &&
+  !(P.PrintFunctionQualifiedRecords && isa(this))) {
 // We do not print '(anonymous)' for function parameters without name.
 printName(OS);
 return;
@@ -1583,7 +1584,8 @@
   Ctx = CI;
   }
 
-  if (Ctx->isFunctionOrMethod())
+  if (Ctx->isFunctionOrMethod() &&
+  !(P.PrintFunctionQualifiedRecords && isa(this)))
 return;
 
   using ContextsTy = SmallVector;
Index: clang/include/clang/AST/PrettyPrinter.h
===
--- clang/include/clang/AST/PrettyPrinter.h
+++ clang/include/clang/AST/PrettyPrinter.h
@@ -63,7 +63,8 @@
 MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
 MSVCFormatting(false), ConstantsAsWritten(false),
 SuppressImplicitBase(false), FullyQualifiedName(false),
-PrintCanonicalTypes(false), PrintInjectedClassNameWithArguments(true) {}
+

[PATCH] D79912: Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.

LGTM, but I wouldn't say no to a test case using `(Limit) -= 1`.


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

https://reviews.llvm.org/D79912



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81150: Use libClangTesting in the unittest for AST matchers

2020-06-04 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang/unittests/ASTMatchers/ASTMatchersTest.h:62
+inline ArrayRef langCxx11OrLater() {
+  static std::vector Result = {Lang_CXX11, Lang_CXX14, 
Lang_CXX17,
+ Lang_CXX20};

Bit late, but surely these should have been const arrays instead of vectors.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81150



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80887: [clang-tidy] ignore builtin varargs from pro-type-vararg-check

2020-06-04 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe21c3f223a35: [clang-tidy] ignore builtin varargs from 
pro-type-vararg-check (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -39,13 +39,22 @@
 #include 
 void my_printf(const char* format, ...) {
   va_list ap;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare variables of type va_list; use variadic templates instead
   va_start(ap, format);
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not call c-style vararg functions
   va_list n;
-  va_copy(n, ap); // Don't warn, va_copy is anyway useless without va_start
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare variables of type va_list; use variadic templates instead
+  va_copy(n, ap);
   int i = va_arg(ap, int);
-  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use va_start/va_arg to define c-style vararg functions; use variadic templates instead
-  va_end(ap); // Don't warn, va_end is anyway useless without va_start
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use va_arg to define c-style vararg functions; use variadic templates instead
+  va_end(ap);
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -9,6 +9,7 @@
 #include "ProTypeVarargCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 
 using namespace clang::ast_matchers;
 
@@ -18,11 +19,72 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+// clang-format off
+"__builtin_isgreater", 
+"__builtin_isgreaterequal", 
+"__builtin_isless",
+"__builtin_islessequal", 
+"__builtin_islessgreater", 
+"__builtin_isunordered",
+"__builtin_fpclassify", 
+"__builtin_isfinite", 
+"__builtin_isinf",
+"__builtin_isinf_sign", 
+"__builtin_isnan", 
+"__builtin_isnormal",
+"__builtin_signbit", 
+"__builtin_constant_p", 
+"__builtin_classify_type",
+"__builtin_va_start",
+"__builtin_assume_aligned", // Documented as variadic to support default 
+// parameters.
+"__builtin_prefetch",   // Documented as variadic to support default
+// parameters.
+"__builtin_shufflevector",  // Documented as variadic but with a defined
+// number of args based on vector size.
+"__builtin_convertvector", 
+"__builtin_call_with_static_chain",
+"__builtin_annotation", 
+"__builtin_add_overflow", 
+"__builtin_sub_overflow",
+"__builtin_mul_overflow", 
+"__builtin_preserve_access_index",
+"__builtin_nontemporal_store", 
+"__builtin_nontemporal_load",
+"__builtin_ms_va_start",
+// clang-format on
+};
+
+namespace {
+AST_MATCHER(QualType, isVAList) {
+  ASTContext  = Finder->getASTContext();
+  QualType Desugar = Node.getDesugaredType(Context);
+  return Context.getBuiltinVaListType().getDesugaredType(Context) == Desugar ||
+ Context.getBuiltinMSVaListType().getDesugaredType(Context) == Desugar;
+}
+
+AST_MATCHER_P(AdjustedType, hasOriginalType,
+  ast_matchers::internal::Matcher, InnerType) {
+  return InnerType.matches(Node.getOriginalType(), Finder, Builder);
+}
+} // namespace
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
+
+  Finder->addMatcher(
+  varDecl(unless(parmVarDecl()),
+  

[PATCH] D81272: [clang-tidy] New check `misc-redundant-condition`

2020-06-05 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I feel the refactoring of Aliasing should be in its own PR, with this being a 
child of it.




Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:38
+  ifStmt(hasCondition(anyOf(
+ declRefExpr(hasDeclaration(varDecl().bind("cond_var"))),
+ binaryOperator(hasOperatorName("&&"),

Small nit, but using string literals for bound nodes is error prone. may I 
suggest defining some static strings and using those to prevent any typos.



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:39
+ declRefExpr(hasDeclaration(varDecl().bind("cond_var"))),
+ binaryOperator(hasOperatorName("&&"),
+hasEitherOperand(declRefExpr(hasDeclaration(

Recursive matchers are a pain, but this will miss:
 ```
if (A && B && ... Y && Z)
```




Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:63
+  // Non-local variables may be changed by any call.
+  if (!CondVar->isLocalVarDeclOrParm())
+return;

This logic can be moved to the matcher.
```
varDecl(anyOf(parmVarDecl(), hasLocalStorage()))
```



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:67
+  // Volatile variables may be changed by another thread.
+  if (CondVar->getType().isVolatileQualified())
+return;

Ditto:
```
varDecl(hasType(isVolatileQualified()))```



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:71
+  // Class instances may be tricky, so restrict ourselves to integers.
+  if (!CondVar->getType().getTypePtr()->isIntegerType())
+return;

Ditto, you get the point



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:87-88
+  if (isa(InnerIf->getCond()->IgnoreParenImpCasts()) ||
+  (isa(InnerIf->getCond()) &&
+   cast(InnerIf->getCond())->getOpcode() == BO_LOr)) {
+SourceLocation IfBegin = InnerIf->getBeginLoc();

use `llvm::dyn_cast`.



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:97
+  CharSourceRange::getCharRange(IfBegin, IfEnd))
+   << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
+  Body->getEndLoc(), Body->getEndLoc().getLocWithOffset(1)));

Again `CharSourceRange::getTokenRange(Body->getEndLoc())`



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:109
+const auto *CondOp = cast(InnerIf->getCond());
+if (isa(CondOp->getLHS()->IgnoreParenImpCasts()) &&
+cast(CondOp->getLHS()->IgnoreParenImpCasts())->getDecl() 
==

use `llvm::dyn_cast`.



Comment at: clang-tools-extra/clang-tidy/misc/RedundantConditionCheck.cpp:115
+} else {
+  // For some reason the end location of identifiers is identical to their
+  // begin location so add their length instead.

That's because you are getting the character range, if you get the token range 
it'll get the correct range: `CharSourceRange::getTokenRange`



Comment at: clang-tools-extra/docs/clang-tidy/checks/list.rst:135
`cppcoreguidelines-avoid-goto `_,
+   `cppcoreguidelines-avoid-non-const-global-variables 
`_,
`cppcoreguidelines-init-variables 
`_, "Yes"

baloghadamsoftware wrote:
> What are these changes? I surely did not make them? Maybe the check adder 
> Python script?
Yeah, just undo those unrelated changes, maybe one day the python script will 
get sorted


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81272



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80753: [clang-tidy] remove duplicate fixes of alias checkers

2020-06-06 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp:777
+  "or make sure they are both configured the same. "
+  "Aliased checkers: '{0}', '{1}'",
+  ExistingError.DiagnosticName, Error.DiagnosticName)

You don't really need the Aliased checkers note as that is wrapped in the 
initial diagnostic message. 
Also if there was a check that could spew out 3 different fix-its for the same 
diagnostic, this would result in the duplication note being made twice, maybe 
the notes should be cleared too?


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

https://reviews.llvm.org/D80753



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80896: [clang-tidy][misc-redundant-expression] Support for CXXFoldExpr

2020-06-05 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

How are you landing these changes, because the commit message isn't lining up 
with the PR name?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80896



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81336: [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-06 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh, lebedev.ri, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.

Ignore template instantiations in the matchers, Addresses 
readability-simplify-boolean-expr false-positive for bool from template. 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81336

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ -948,3 +948,18 @@
 }
 // CHECK-MESSAGES: :[[@LINE-4]]:12: warning: {{.*}} in conditional return
 // CHECK-FIXES: S == (A)S;{{$}}
+
+template 
+void ignoreInstantiations() {
+  if (B) {
+return;
+  } else {
+return;
+  }
+}
+
+void instantiate() {
+  // Just make sure the check isn't fooled by template instantiations.
+  ignoreInstantiations();
+  ignoreInstantiations();
+}
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -432,7 +432,7 @@
   bool Value,
   StringRef TernaryId) {
   Finder->addMatcher(
-  conditionalOperator(isExpansionInMainFile(),
+  conditionalOperator(unless(isInTemplateInstantiation()),
   hasTrueExpression(cxxBoolLiteral(equals(Value))),
   hasFalseExpression(cxxBoolLiteral(equals(!Value
   .bind(TernaryId),
@@ -442,13 +442,13 @@
 void SimplifyBooleanExprCheck::matchIfReturnsBool(MatchFinder *Finder,
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
-Finder->addMatcher(ifStmt(isExpansionInMainFile(),
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
   unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
@@ -474,12 +474,16 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  hasThen(Then), hasElse(Else))
+   .bind(Id),
+   this);
   else
-Finder->addMatcher(
-ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
-.bind(Id),
-this);
+Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
+  unless(hasParent(ifStmt())), hasThen(Then),
+  hasElse(Else))
+   .bind(Id),
+   this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -487,6 +491,7 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(


Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
@@ 

[PATCH] D81272: [clang-tidy] New check `misc-redundant-condition`

2020-06-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

These test cases don't show it, from what i can see this will erroneously match:

  if (onFire) {
tryPutFireOut();
  } else {
if (isHot && onFire) {
  scream();
}
  } 

It appears that this will change the second if to:

  if (isHot) {
scream();
  }

Rather than simply deleting the if as it will always evaluate to false. To fix 
this you could wrap the `hasDescendant` matcher inside a `hasThen` matcher.

Another case is if the condition variable is on the RHS of a redundant inner if 
condition, you can't delete the inner if when the LHS potentially has side 
effects.

  if (onFire) {
if (callTheFD() || onFire) {
  scream();
}
  }

If `callTheFD` has side effects this can't be replaced with this:

  if (onFire) {
scream();
  }

You could however replace it with:

  if (onFire) {
callTheFD();
scream();
  }

For this simply check if the LHS has side effects.


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

https://reviews.llvm.org/D81272



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79912: Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

2020-06-09 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce5fecb7d0a1: Assignment and Inc/Dec operators wouldnt 
register as a mutation when Implicit… (authored by Tridacnid, committed by 
njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79912

Files:
  clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -112,11 +112,21 @@
 class AssignmentTest : public ::testing::TestWithParam {};
 
 TEST_P(AssignmentTest, AssignmentModifies) {
-  const std::string ModExpr = "x " + GetParam() + " 10";
-  const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
-  const auto Results =
-  match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
-  EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  {
+const std::string ModExpr = "x " + GetParam() + " 10";
+const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  {
+const std::string ModExpr = "(x) " + GetParam() + " 10";
+const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
 }
 
 INSTANTIATE_TEST_CASE_P(AllAssignmentOperators, AssignmentTest,
@@ -134,7 +144,8 @@
 }
 
 INSTANTIATE_TEST_CASE_P(AllIncDecOperators, IncDecTest,
-Values("++x", "--x", "x++", "x--"), );
+Values("++x", "--x", "x++", "x--", "++(x)", "--(x)",
+   "(x)++", "(x)--"), );
 
 TEST(ExprMutationAnalyzerTest, NonConstMemberFunc) {
   const auto AST = buildASTFromCode(
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -201,14 +201,15 @@
 
 const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) {
   // LHS of any assignment operators.
-  const auto AsAssignmentLhs =
-  binaryOperator(isAssignmentOperator(),
- hasLHS(maybeEvalCommaExpr(equalsNode(Exp;
+  const auto AsAssignmentLhs = binaryOperator(
+  isAssignmentOperator(),
+  hasLHS(maybeEvalCommaExpr(ignoringParenImpCasts(equalsNode(Exp);
 
   // Operand of increment/decrement operators.
   const auto AsIncDecOperand =
   unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
-hasUnaryOperand(maybeEvalCommaExpr(equalsNode(Exp;
+hasUnaryOperand(maybeEvalCommaExpr(
+ignoringParenImpCasts(equalsNode(Exp);
 
   // Invoking non-const member function.
   // A member function is assumed to be non-const when it is unresolved.
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
@@ -70,11 +70,25 @@
 i++;
   }
 
+  while ((Limit)--) {
+// Not an error since 'Limit' is updated.
+i++;
+  }
+
+  while ((Limit) -= 1) {
+// Not an error since 'Limit' is updated.
+  }
+
   while (int k = Limit) {
 // Not an error since 'Limit' is updated.
 Limit--;
   }
 
+  while (int k = Limit) {
+// Not an error since 'Limit' is updated
+(Limit)--;
+  }
+
   while (int k = Limit--) {
 // Not an error since 'Limit' is updated.
 i++;
@@ -86,6 +100,15 @@
 
   for (i = 0; i < Limit; Limit--) {
   }
+
+  for (i = 0; i < Limit; (Limit) = Limit - 1) {
+  }
+
+  for (i = 0; i < Limit; (Limit) -= 1) {
+  }
+
+  for (i = 0; i < Limit; --(Limit)) {
+  }
 }
 
 void simple_not_infinite2() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79912: Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

2020-06-09 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D79912#2082337 , @Tridacnid wrote:

> tridac...@gmail.com
>
> https://github.com/Tridacnid
>
> Thanks!


I've commited 

 it on your behalf, would you be able to close the bug report.


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

https://reviews.llvm.org/D79912



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80887: [clang-tidy] ignore builtin varargs from pro-type-vararg-check

2020-06-03 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 268256.
njames93 added a comment.

- Detect va_list type VarDecls to warn on


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -39,13 +39,22 @@
 #include 
 void my_printf(const char* format, ...) {
   va_list ap;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare variables of type va_list; use variadic templates instead
   va_start(ap, format);
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not call c-style vararg functions
   va_list n;
-  va_copy(n, ap); // Don't warn, va_copy is anyway useless without va_start
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare variables of type va_list; use variadic templates instead
+  va_copy(n, ap);
   int i = va_arg(ap, int);
-  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use va_start/va_arg to define c-style vararg functions; use variadic templates instead
-  va_end(ap); // Don't warn, va_end is anyway useless without va_start
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use va_arg to define c-style vararg functions; use variadic templates instead
+  va_end(ap);
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -9,6 +9,7 @@
 #include "ProTypeVarargCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 
 using namespace clang::ast_matchers;
 
@@ -18,11 +19,62 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+// clang-format off
+"__builtin_isgreater", 
+"__builtin_isgreaterequal", 
+"__builtin_isless",
+"__builtin_islessequal", 
+"__builtin_islessgreater", 
+"__builtin_isunordered",
+"__builtin_fpclassify", 
+"__builtin_isfinite", 
+"__builtin_isinf",
+"__builtin_isinf_sign", 
+"__builtin_isnan", 
+"__builtin_isnormal",
+"__builtin_signbit", 
+"__builtin_constant_p", 
+"__builtin_classify_type",
+"__builtin_va_start",
+"__builtin_assume_aligned", // Documented as variadic to support default 
+// parameters.
+"__builtin_prefetch",   // Documented as variadic to support default
+// parameters.
+"__builtin_shufflevector",  // Documented as variadic but with a defined
+// number of args based on vector size.
+"__builtin_convertvector", 
+"__builtin_call_with_static_chain",
+"__builtin_annotation", 
+"__builtin_add_overflow", 
+"__builtin_sub_overflow",
+"__builtin_mul_overflow", 
+"__builtin_preserve_access_index",
+"__builtin_nontemporal_store", 
+"__builtin_nontemporal_load",
+"__builtin_ms_va_start",
+// clang-format on
+};
+
+namespace {
+AST_MATCHER(QualType, isVAList) {
+  ASTContext  = Finder->getASTContext();
+  QualType Desugar = Node.getDesugaredType(Context);
+  return Context.getBuiltinVaListType().getDesugaredType(Context) == Desugar ||
+ Context.getBuiltinMSVaListType().getDesugaredType(Context) == Desugar;
+}
+} // namespace
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
+
+  Finder->addMatcher(varDecl(hasType(isVAList())).bind("va_list"), this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {
@@ -54,7 +106,7 @@
 
   if (const auto *Matched = Result.Nodes.getNodeAs("va_use")) {
 diag(Matched->getExprLoc(),
- "do not use va_start/va_arg to define c-style vararg 

<    3   4   5   6   7   8   9   10   11   12   >