[clang-tools-extra] 4c5818d - [clang-tidy] Fix potential assert in use-noexcept check

2020-05-25 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-24T14:40:58+01:00
New Revision: 4c5818dd8cd9336136a80a02b262b501b23f6492

URL: 
https://github.com/llvm/llvm-project/commit/4c5818dd8cd9336136a80a02b262b501b23f6492
DIFF: 
https://github.com/llvm/llvm-project/commit/4c5818dd8cd9336136a80a02b262b501b23f6492.diff

LOG: [clang-tidy] Fix potential assert in use-noexcept check

Summary: Fix a potential assert in use-noexcept check if there is an issue 
getting the `TypeSourceInfo` as well as a small clean up.

Reviewers: aaron.ballman, alexfh, gribozavr2

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D80371

Added: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
index bbda8d58f103..cc4bc05a35dd 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@ namespace clang {
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@ void 
UseNoexceptCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@ void UseNoexceptCheck::check(const MatchFinder::MatchResult 
&Result) {
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());

diff  --git a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
index 4f3ba321483e..b87d3e629ff6 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@ class UseNoexceptCheck : public ClangTidyCheck {
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
new file mode 100644
index ..9a80b075d65e
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]



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


[clang-tools-extra] 4411962 - [clang-tidy] RenamerClangTidyChecks ignore builtin and command line macros

2020-05-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-30T20:49:33+01:00
New Revision: 44119626dedfebe245fe6ce26487949201299d38

URL: 
https://github.com/llvm/llvm-project/commit/44119626dedfebe245fe6ce26487949201299d38
DIFF: 
https://github.com/llvm/llvm-project/commit/44119626dedfebe245fe6ce26487949201299d38.diff

LOG: [clang-tidy] RenamerClangTidyChecks ignore builtin and command line macros

Summary: Fixes [[ https://bugs.llvm.org/show_bug.cgi?id=42635 | 
readability-identifier-naming option MacroDefinitionCase should ignore macros 
passed as parameters. ]]

Reviewers: aaron.ballman, alexfh, gribozavr2, hokein

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D80631

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index dd05b3a45c0d..3301ba6343c7 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -73,6 +73,14 @@ class RenamerClangTidyCheckPPCallbacks : public PPCallbacks {
   /// MacroDefined calls checkMacro for macros in the main file
   void MacroDefined(const Token &MacroNameTok,
 const MacroDirective *MD) override {
+if (MD->getMacroInfo()->isBuiltinMacro())
+  return;
+if (PP->getSourceManager().isWrittenInBuiltinFile(
+MacroNameTok.getLocation()))
+  return;
+if (PP->getSourceManager().isWrittenInCommandLineFile(
+MacroNameTok.getLocation()))
+  return;
 Check->checkMacro(PP->getSourceManager(), MacroNameTok, 
MD->getMacroInfo());
   }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
index 7983bb30ca64..1bb435e02eb5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -80,7 +80,7 @@
 // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 
'l_'}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, 
value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, 
value: 'lc_'}, \
-// RUN:   ]}' -- -fno-delayed-template-parsing \
+// RUN:   ]}' -- -fno-delayed-template-parsing -Dbad_macro \
 // RUN:   -I%S/Inputs/readability-identifier-naming \
 // RUN:   -isystem %S/Inputs/readability-identifier-naming/system
 



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


[clang-tools-extra] f23ddbe - clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-31T16:01:41+01:00
New Revision: f23ddbe3c3ae5f40b99ba272afc3d16b800ba8b9

URL: 
https://github.com/llvm/llvm-project/commit/f23ddbe3c3ae5f40b99ba272afc3d16b800ba8b9
DIFF: 
https://github.com/llvm/llvm-project/commit/f23ddbe3c3ae5f40b99ba272afc3d16b800ba8b9.diff

LOG: clang-tidy and clang-query wont crash with invalid command line options

Summary: Motivated by [[ https://bugs.llvm.org/show_bug.cgi?id=46141 | 
clang-tidy crashed for unknown command line argument. ]]

Reviewers: aaron.ballman, alexfh

Reviewed By: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D80879

Added: 
clang-tools-extra/test/clang-query/invalid-command-line.cpp
clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Modified: 
clang-tools-extra/clang-query/tool/ClangQuery.cpp
clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp 
b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
index 5cfa0acf9120..0c471def2e14 100644
--- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@ bool runCommandsInFile(const char *ExeName, std::string 
const &FileName,
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@ int main(int argc, const char **argv) {
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;

diff  --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index 665d10026834..aca16b0d6d81 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@ getVfsFromFile(const std::string &OverlayFile,
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@ int clangTidyMain(int argc, const char **argv) {
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@ int clangTidyMain(int argc, const char **argv) {
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;

diff  --git a/clang-tools-extra/test/clang-query/invalid-command-line.cpp 
b/clang-tools-extra/test/clang-query/invalid-command-line.cpp
new file mode 100644
index ..10ab43198b4e
--- /dev/null
+++ b/clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [C

[clang-tools-extra] f4b0ebb - Revert "clang-tidy and clang-query wont crash with invalid command line options"

2020-05-31 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-31T16:40:09+01:00
New Revision: f4b0ebb89b3086a2bdd8c7dd1f5d142fa09ca728

URL: 
https://github.com/llvm/llvm-project/commit/f4b0ebb89b3086a2bdd8c7dd1f5d142fa09ca728
DIFF: 
https://github.com/llvm/llvm-project/commit/f4b0ebb89b3086a2bdd8c7dd1f5d142fa09ca728.diff

LOG: Revert "clang-tidy and clang-query wont crash with invalid command line 
options"

This reverts commit f23ddbe3c3ae5f40b99ba272afc3d16b800ba8b9.

Added: 


Modified: 
clang-tools-extra/clang-query/tool/ClangQuery.cpp
clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp

Removed: 
clang-tools-extra/test/clang-query/invalid-command-line.cpp
clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp



diff  --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp 
b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
index 0c471def2e14..5cfa0acf9120 100644
--- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,7 +35,6 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
-#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -87,14 +86,7 @@ bool runCommandsInFile(const char *ExeName, std::string 
const &FileName,
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  llvm::Expected OptionsParser =
-  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
-  llvm::cl::OneOrMore);
-
-  if (!OptionsParser) {
-llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
-return 1;
-  }
+  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -107,8 +99,8 @@ int main(int argc, const char **argv) {
 return 1;
   }
 
-  ClangTool Tool(OptionsParser->getCompilations(),
- OptionsParser->getSourcePathList());
+  ClangTool Tool(OptionsParser.getCompilations(),
+ OptionsParser.getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;

diff  --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index aca16b0d6d81..665d10026834 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,7 +23,6 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
-#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -334,14 +333,8 @@ getVfsFromFile(const std::string &OverlayFile,
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  llvm::Expected OptionsParser =
-  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
-  cl::ZeroOrMore);
-  if (!OptionsParser) {
-llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
-return 1;
-  }
-
+  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
+cl::ZeroOrMore);
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -372,7 +365,7 @@ int clangTidyMain(int argc, const char **argv) {
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser->getSourcePathList();
+  auto PathList = OptionsParser.getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -440,7 +433,7 @@ int clangTidyMain(int argc, const char **argv) {
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;

diff  --git a/clang-tools-extra/test/clang-query/invalid-command-line.cpp 
b/clang-tools-extra/test/clang-query/invalid-command-line.cpp
deleted file mode 100644
index 10ab43198b4e..
--- a/clang-tools-extra/test/clang-query/invalid-command-line.cpp
+++ /dev/null
@@ -1,4 +0,0 @@
-// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
-
-// CHECK: error: [CommonOptionsParser]: clang-query: Unknown command line 
argument '--invalid-arg'.  Try: 'clang-query --help'
-// CHECK-NEXT: clang-query: Did you mean '--extra-arg'?

diff  --git 
a/clang-tools-extra/test/clang-

[clang-tools-extra] 5952125 - clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-31T17:41:29+01:00
New Revision: 5952125691571de9bd817551fb1baabe270e73f9

URL: 
https://github.com/llvm/llvm-project/commit/5952125691571de9bd817551fb1baabe270e73f9
DIFF: 
https://github.com/llvm/llvm-project/commit/5952125691571de9bd817551fb1baabe270e73f9.diff

LOG: clang-tidy and clang-query wont crash with invalid command line options

Motivated by [[ https://bugs.llvm.org/show_bug.cgi?id=46141 | clang-tidy 
crashed for unknown command line argument. ]]

Reviewed By: aaron.ballman, thakis

Differential Revision: https://reviews.llvm.org/D80879

Added: 
clang-tools-extra/test/clang-query/invalid-command-line.cpp
clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Modified: 
clang-tools-extra/clang-query/tool/ClangQuery.cpp
clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp 
b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
index 5cfa0acf9120..0c471def2e14 100644
--- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@ bool runCommandsInFile(const char *ExeName, std::string 
const &FileName,
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@ int main(int argc, const char **argv) {
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;

diff  --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index 665d10026834..aca16b0d6d81 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@ getVfsFromFile(const std::string &OverlayFile,
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@ int clangTidyMain(int argc, const char **argv) {
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@ int clangTidyMain(int argc, const char **argv) {
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;

diff  --git a/clang-tools-extra/test/clang-query/invalid-command-line.cpp 
b/clang-tools-extra/test/clang-query/invalid-command-line.cpp
new file mode 100644
index ..901aad8c1f23
--- /dev/null
+++ b/clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query{{(\.exe)?}}: Unknown 
command line argumen

[clang] b6d23f2 - [ASTMatchers] Force c++ unittests to specify correct language standard

2020-05-31 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-01T07:52:01+01:00
New Revision: b6d23f2efc64c226d30094bcc4258e0b63029da8

URL: 
https://github.com/llvm/llvm-project/commit/b6d23f2efc64c226d30094bcc4258e0b63029da8
DIFF: 
https://github.com/llvm/llvm-project/commit/b6d23f2efc64c226d30094bcc4258e0b63029da8.diff

LOG: [ASTMatchers] Force c++ unittests to specify correct language standard

Force the unittests on c++ code for matchers to specify the correct standard.

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D80884

Added: 


Modified: 
clang/unittests/ASTMatchers/ASTMatchersTest.h
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTest.h 
b/clang/unittests/ASTMatchers/ASTMatchersTest.h
index 6af039e72058..8bf23a5aca19 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTest.h
+++ b/clang/unittests/ASTMatchers/ASTMatchersTest.h
@@ -153,7 +153,7 @@ matchesConditionally(const std::string &Code, const T 
&AMatcher,
   }
 
   for (auto Mode : LangModes) {
-std::string LangModeArg;
+StringRef LangModeArg;
 switch (Mode) {
 case LanguageMode::Cxx11:
   LangModeArg = "-std=c++11";
@@ -171,8 +171,10 @@ matchesConditionally(const std::string &Code, const T 
&AMatcher,
   llvm_unreachable("Invalid language mode");
 }
 
-auto Result =
-matchesConditionally(Code, AMatcher, ExpectMatch, LangModeArg);
+auto Result = matchesConditionally(Code, AMatcher, ExpectMatch,
+   {LangModeArg, 
"-Werror=c++14-extensions",
+"-Werror=c++17-extensions",
+"-Werror=c++20-extensions"});
 if (!Result)
   return Result;
   }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 6bd8fcf66498..93b0eefa676b 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -950,10 +950,14 @@ TEST(TemplateTypeParmDecl, 
VarTemplatePartialSpecializationDecl) {
   "template\n"
   "template\n"
   "int Struct::field = 123;\n";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2";
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T2")), 
LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U2")), 
LanguageMode::Cxx14));
 }
 
 TEST(TemplateTypeParmDecl, ClassTemplatePartialSpecializationDecl) {
@@ -2061,113 +2065,146 @@ void func14() {
 
 )cpp";
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- returnStmt(forFunction(functionDecl(hasName("func1"))),
-hasReturnValue(integerLiteral(equals(42)));
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   returnStmt(forFunction(functionDecl(hasName("func1"))),
+  hasReturnValue(integerLiteral(equals(42),
+  LanguageMode::Cxx2a));
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- integerLiteral(equals(42),
-hasParent(returnStmt(forFunction(
-functionDecl(hasName("func1");
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   integerLiteral(equals(42),
+  hasParent(returnStmt(forFunction(
+  functionDecl(hasName("func1"))),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
   Code,
   traverse(TK_IgnoreUnlessSpelledInSource,
returnStmt(forFunction(functionDecl(hasName("func2"))),
   hasReturnValue(cxxTemporaryObjectExpr(
-  hasArgument(0, integerLiteral(equals(42);
+  hasArgument(0, integerLiteral(equals(42))),
+  LanguageMode::Cxx2a));
   EXPECT_TRUE(matches(
   Code,
-  traverse(TK_IgnoreUnlessSpelledInSource,
-   integerLiteral(
-   equals(42),
-   hasParent(cxxTemporaryObjectExpr(hasParent(returnStmt(
-   forFunction(functionDecl(hasName("func2")));
+  tr

[clang] 26cb706 - [NFC][ASTMatchers] StringRef-ify and Twine-ify ASTMatchers tests.

2020-06-02 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-02T21:20:58+01:00
New Revision: 26cb70683bd4ffa49d94a8dad5ecfda549a673b0

URL: 
https://github.com/llvm/llvm-project/commit/26cb70683bd4ffa49d94a8dad5ecfda549a673b0
DIFF: 
https://github.com/llvm/llvm-project/commit/26cb70683bd4ffa49d94a8dad5ecfda549a673b0.diff

LOG: [NFC][ASTMatchers] StringRef-ify and Twine-ify ASTMatchers tests.

Added: 


Modified: 
clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
clang/unittests/ASTMatchers/ASTMatchersTest.h
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index 9f8538edb35b..80eebf227a31 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -19,7 +19,7 @@ namespace clang {
 namespace ast_matchers {
 
 TEST(IsExpandedFromMacro, ShouldMatchInFile) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 void Test() { MY_MACRO(4); }
   )cc";
@@ -27,7 +27,7 @@ TEST(IsExpandedFromMacro, ShouldMatchInFile) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchNested) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 #define WRAPPER(a) MY_MACRO(a)
 void Test() { WRAPPER(4); }
@@ -36,7 +36,7 @@ TEST(IsExpandedFromMacro, ShouldMatchNested) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchIntermediate) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define IMPL(a) (4 + (a))
 #define MY_MACRO(a) IMPL(a)
 #define WRAPPER(a) MY_MACRO(a)
@@ -46,7 +46,7 @@ TEST(IsExpandedFromMacro, ShouldMatchIntermediate) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchTransitive) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 #define WRAPPER(a) MY_MACRO(a)
 void Test() { WRAPPER(4); }
@@ -55,7 +55,7 @@ TEST(IsExpandedFromMacro, ShouldMatchTransitive) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchArgument) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 void Test() {
   int x = 5;
@@ -68,7 +68,7 @@ TEST(IsExpandedFromMacro, ShouldMatchArgument) {
 // Like IsExpandedFromMacroShouldMatchArgumentMacro, but the argument is itself
 // a macro.
 TEST(IsExpandedFromMacro, ShouldMatchArgumentMacroExpansion) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 #define IDENTITY(a) (a)
 void Test() {
@@ -79,7 +79,7 @@ TEST(IsExpandedFromMacro, ShouldMatchArgumentMacroExpansion) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchWhenInArgument) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 #define IDENTITY(a) (a)
 void Test() {
@@ -90,7 +90,7 @@ TEST(IsExpandedFromMacro, ShouldMatchWhenInArgument) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchObjectMacro) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define PLUS (2 + 2)
 void Test() {
   PLUS;
@@ -100,7 +100,7 @@ TEST(IsExpandedFromMacro, ShouldMatchObjectMacro) {
 }
 
 TEST(IsExpandedFromMacro, ShouldMatchFromCommandLine) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 void Test() { FOUR_PLUS_FOUR; }
   )cc";
   EXPECT_TRUE(matchesConditionally(input,
@@ -109,7 +109,7 @@ TEST(IsExpandedFromMacro, ShouldMatchFromCommandLine) {
 }
 
 TEST(IsExpandedFromMacro, ShouldNotMatchBeginOnly) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define ONE_PLUS 1+
   void Test() { ONE_PLUS 4; }
   )cc";
@@ -118,7 +118,7 @@ TEST(IsExpandedFromMacro, ShouldNotMatchBeginOnly) {
 }
 
 TEST(IsExpandedFromMacro, ShouldNotMatchEndOnly) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define PLUS_ONE +1
   void Test() { 4 PLUS_ONE; }
   )cc";
@@ -127,7 +127,7 @@ TEST(IsExpandedFromMacro, ShouldNotMatchEndOnly) {
 }
 
 TEST(IsExpandedFromMacro, ShouldNotMatchDifferentMacro) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define MY_MACRO(a) (4 + (a))
 void Test() { MY_MACRO(4); }
   )cc";
@@ -135,7 +135,7 @@ TEST(IsExpandedFromMacro, ShouldNotMatchDifferentMacro) {
 }
 
 TEST(IsExpandedFromMacro, ShouldNotMatchDifferentInstances) {
-  std::string input = R"cc(
+  StringRef input = R"cc(
 #define FOUR 4
 void Test() { FOUR + FOUR; }
   )cc";
@@ -966,8 +966,8 @@ TEST(Matcher, VarDecl_IsStaticLocal) {
 }
 
 TEST(Matcher, VarDecl_StorageDuration) {
-  std::string T =
-"void f() { int x; static int y; } int a;static int b;extern int c;";
+  StringRef T =
+  "void f() { int x; static int y; } int a;static int b;extern int c;";
 
   EXPECT_TRUE(matches(T, varDecl(hasName("x"), 
hasAutomaticStorageDuration(;
   EXPECT_TRUE(
@@ -1629,7 +1629,7 @@ TEST(Matcher, HasNameSupportsOuterClasses) {
 }
 
 TEST(Matcher, HasNameSupports

[clang-tools-extra] 65fa0a9 - [clang-tidy] Added MacroDefiniton docs for readability-identifier-naming

2020-06-03 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-03T09:23:32+01:00
New Revision: 65fa0a9f7f3e6090e335c14f9edea19358d87613

URL: 
https://github.com/llvm/llvm-project/commit/65fa0a9f7f3e6090e335c14f9edea19358d87613
DIFF: 
https://github.com/llvm/llvm-project/commit/65fa0a9f7f3e6090e335c14f9edea19358d87613.diff

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

Updates the docs to include `MacroDefinition` documentation. The docs are still 
missing `ObjCIVar` however I don't have a clue about how that looks in code. If 
someone wants to show the code block needed for the example I'll add that in 
too.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D80877

Added: 


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

Removed: 




diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst 
b/clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
index 3d0cbca69f6d..eefa5234fb21 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
@@ -62,6 +62,7 @@ The following options are describe below:
  - :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 @@ After:
 
 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


[clang-tools-extra] 13c9bbc - [clang-tidy] Refactor IncludeInserter

2020-07-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-27T12:48:55+01:00
New Revision: 13c9bbc28ef9cf9976a0962e6c930a7dfc52c877

URL: 
https://github.com/llvm/llvm-project/commit/13c9bbc28ef9cf9976a0962e6c930a7dfc52c877
DIFF: 
https://github.com/llvm/llvm-project/commit/13c9bbc28ef9cf9976a0962e6c930a7dfc52c877.diff

LOG: [clang-tidy] Refactor IncludeInserter

Simplified how `IncludeInserter` is used in Checks by abstracting away the 
SourceManager and PPCallbacks inside the method `registerPreprocessor`.
Changed checks that use `IncludeInserter` to no longer use a `std::unique_ptr`, 
instead the IncludeInserter is just a member of the class thats initialized 
with an `IncludeStyle`.
Saving an unnecessary allocation.

This results in the removal of the field `IncludeSorter::IncludeStyle` from the 
checks, as its wrapped in the `IncludeInserter`.
No longer need to create an instance of the `IncludeInserter` in the 
registerPPCallbacks, now that method only needs to contain:
```
Inserter.registerPreprocessor(PP);
```
Also added a helper method to `IncludeInserter` called 
`createMainFileInclusionInsertion`, purely sugar but does better express 
intentions.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D83680

Added: 


Modified: 
clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.h
clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.h
clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.h
clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
clang-tools-extra/clang-tidy/modernize/PassByValueCheck.h
clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.h
clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.h
clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.cpp
clang-tools-extra/clang-tidy/performance/MoveConstructorInitCheck.h
clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.h
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.h
clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
clang-tools-extra/clang-tidy/utils/IncludeInserter.h
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
index 11bbcbcb527f..e775fc21d2d0 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
@@ -26,8 +26,8 @@ 
StringFindStartswithCheck::StringFindStartswithCheck(StringRef Name,
 : ClangTidyCheck(Name, Context),
   StringLikeClasses(utils::options::parseStringList(
   Options.get("StringLikeClasses", "::std::basic_string"))),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-utils::IncludeSorter::IS_LLVM)),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM)),
   AbseilStringsMatchHeader(
   Options.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
 
@@ -105,23 +105,21 @@ void StringFindStartswithCheck::check(const 
MatchFinder::MatchResult &Result) {
 
   // Create a preprocessor #include FixIt hint (CreateIncludeInsertion checks
   // whether this already exists).
-  Diagnostic << IncludeInserter->CreateIncludeInsertion(
+  Diagnostic << IncludeInserter.createIncludeInsertion(
   Source.getFileID(ComparisonExpr->getBeginLoc()), 
AbseilStringsMatchHeader,
   false);
 }
 
 void StringFindStartswithCheck::registerPPCallbacks(
 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
-  IncludeInserter = std::make_unique(SM, getLangOpts(),
-  IncludeStyle);
-  PP->addPPCallbacks(IncludeInserter->CreatePPCallbacks());
+  IncludeInserter.registerPreprocessor(PP);
 }
 
 void StringFindStartswithCheck::storeOptions(
 ClangTidyOptions::Option

[clang-tools-extra] 7bae318 - [clang-tidy][NFC] Make OptionsView methods as const where missing

2020-07-28 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-28T14:52:43+01:00
New Revision: 7bae3188e08746566733148a4ceccdb3cf24e93b

URL: 
https://github.com/llvm/llvm-project/commit/7bae3188e08746566733148a4ceccdb3cf24e93b
DIFF: 
https://github.com/llvm/llvm-project/commit/7bae3188e08746566733148a4ceccdb3cf24e93b.diff

LOG: [clang-tidy][NFC] Make OptionsView methods as const where missing

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
clang-tools-extra/clang-tidy/ClangTidyCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index c24b8553999c..ffd5bf974ba2 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -168,10 +168,9 @@ void ClangTidyCheck::OptionsView::store(
   store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
 }
 
-llvm::Expected
-ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
-ArrayRef Mapping,
-bool CheckGlobal, bool IgnoreCase) {
+llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
+StringRef LocalName, ArrayRef Mapping, bool CheckGlobal,
+bool IgnoreCase) const {
   auto Iter = CheckGlobal
   ? findPriorityOption(CheckOptions, NamePrefix, LocalName)
   : CheckOptions.find((NamePrefix + LocalName).str());

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 54b725126752..4df8071c841e 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -330,7 +330,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// supply the mapping required to convert between ``T`` and a string.
 template 
 std::enable_if_t::value, llvm::Expected>
-get(StringRef LocalName, bool IgnoreCase = false) {
+get(StringRef LocalName, bool IgnoreCase = false) const {
   if (llvm::Expected ValueOr =
   getEnumInt(LocalName, typeEraseMapping(), false, IgnoreCase))
 return static_cast(*ValueOr);
@@ -349,7 +349,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// supply the mapping required to convert between ``T`` and a string.
 template 
 std::enable_if_t::value, T>
-get(StringRef LocalName, T Default, bool IgnoreCase = false) {
+get(StringRef LocalName, T Default, bool IgnoreCase = false) const {
   if (auto ValueOr = get(LocalName, IgnoreCase))
 return *ValueOr;
   else
@@ -370,8 +370,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// supply the mapping required to convert between ``T`` and a string.
 template 
 std::enable_if_t::value, llvm::Expected>
-getLocalOrGlobal(StringRef LocalName,
- bool IgnoreCase = false) {
+getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
   if (llvm::Expected ValueOr =
   getEnumInt(LocalName, typeEraseMapping(), true, IgnoreCase))
 return static_cast(*ValueOr);
@@ -391,7 +390,8 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// supply the mapping required to convert between ``T`` and a string.
 template 
 std::enable_if_t::value, T>
-getLocalOrGlobal(StringRef LocalName, T Default, bool IgnoreCase = false) {
+getLocalOrGlobal(StringRef LocalName, T Default,
+ bool IgnoreCase = false) const {
   if (auto ValueOr = getLocalOrGlobal(LocalName, IgnoreCase))
 return *ValueOr;
   else
@@ -420,7 +420,8 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// supply the mapping required to convert between ``T`` and a string.
 template 
 std::enable_if_t::value>
-store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, T Value) {
+store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+  T Value) const {
   ArrayRef> Mapping =
   OptionEnumMapping::getEnumMapping();
   auto Iter = llvm::find_if(
@@ -436,11 +437,11 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 
 llvm::Expected getEnumInt(StringRef LocalName,
ArrayRef Mapping,
-   bool CheckGlobal, bool IgnoreCase);
+   bool CheckGlobal, bool IgnoreCase) 
const;
 
 template 
 std::enable_if_t::value, std::vector>
-typeEraseMapping() {
+typeEraseMapping() const {
   ArrayRef> Mapping =
   OptionEnumMapping::getEnumMapping();
   std::vector Result;



___
cfe-commits mailing list
cfe-commit

[clang-tools-extra] b99630e - [clang-tidy] Fix RedundantStringCStrCheck with r values

2020-07-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-29T15:35:31+01:00
New Revision: b99630e432614d06b380afb15c45065eaa0a

URL: 
https://github.com/llvm/llvm-project/commit/b99630e432614d06b380afb15c45065eaa0a
DIFF: 
https://github.com/llvm/llvm-project/commit/b99630e432614d06b380afb15c45065eaa0a.diff

LOG: [clang-tidy] Fix RedundantStringCStrCheck with r values

The previous fix for this, https://reviews.llvm.org/D76761, Passed test cases 
but failed in the real world as std::string has a non trivial destructor so 
creates a CXXBindTemporaryExpr.

This handles that shortfall and updates the test case std::basic_string 
implementation to use a non trivial destructor to reflect real world behaviour.

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D84831

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
index bea02a6ba111..1f371eed2db8 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
@@ -92,16 +92,18 @@ void RedundantStringCStrCheck::registerMatchers(
 callee(memberExpr().bind("member")),
 callee(cxxMethodDecl(hasAnyName("c_str", "data"
   .bind("call");
-
+  const auto HasRValueTempParent =
+  hasParent(materializeTemporaryExpr(unless(isBoundToLValue(;
   // Detect redundant 'c_str()' calls through a string constructor.
   // If CxxConstructExpr is the part of some CallExpr we need to
   // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
   Finder->addMatcher(
-  traverse(ast_type_traits::TK_AsIs,
-   cxxConstructExpr(StringConstructorExpr,
-hasArgument(0, StringCStrCallExpr),
-unless(hasParent(materializeTemporaryExpr(
-unless(isBoundToLValue())),
+  traverse(
+  ast_type_traits::TK_AsIs,
+  cxxConstructExpr(
+  StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
+  unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
+HasRValueTempParent)),
   this);
 
   // Detect: 's == str.c_str()'  ->  's == str'

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
index 2561b81805bd..e1df810b 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
@@ -15,6 +15,8 @@ struct basic_string {
   basic_string();
   basic_string(const C *p, const A &a = A());
 
+  ~basic_string();
+
   const C *c_str() const;
   const C *data() const;
 



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


[clang-tools-extra] 62beb7c - [clang-tidy] Fix module options being registered with different priorities

2020-07-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-29T16:19:07+01:00
New Revision: 62beb7c6f4f2288793751740f06edc0dc25d01f6

URL: 
https://github.com/llvm/llvm-project/commit/62beb7c6f4f2288793751740f06edc0dc25d01f6
DIFF: 
https://github.com/llvm/llvm-project/commit/62beb7c6f4f2288793751740f06edc0dc25d01f6.diff

LOG: [clang-tidy] Fix module options being registered with different priorities

Not a bug that is ever likely to materialise, but still worth fixing

Reviewed By: DmitryPolukhin

Differential Revision: https://reviews.llvm.org/D84850

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyOptions.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 4c1f28673781..bb5a4b513967 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -114,11 +114,9 @@ ClangTidyOptions ClangTidyOptions::getDefaults() {
   Options.SystemHeaders = false;
   Options.FormatStyle = "none";
   Options.User = llvm::None;
-  unsigned Priority = 0;
   for (const ClangTidyModuleRegistry::entry &Module :
ClangTidyModuleRegistry::entries())
-Options =
-Options.mergeWith(Module.instantiate()->getModuleOptions(), 
++Priority);
+Options = Options.mergeWith(Module.instantiate()->getModuleOptions(), 0);
   return Options;
 }
 



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


[clang-tools-extra] bbc2dde - [clang-tidy] Handled insertion only fixits when determining conflicts.

2020-07-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-29T16:35:44+01:00
New Revision: bbc2ddecbd342d4502fe43466bd3658b89ddad7d

URL: 
https://github.com/llvm/llvm-project/commit/bbc2ddecbd342d4502fe43466bd3658b89ddad7d
DIFF: 
https://github.com/llvm/llvm-project/commit/bbc2ddecbd342d4502fe43466bd3658b89ddad7d.diff

LOG: [clang-tidy] Handled insertion only fixits when determining conflicts.

Handle insertion fix-its when removing incompatible errors by introducting a 
new EventType `ET_Insert`
This has lower prioirty than End events, but higher than begin.
Idea being If an insert is at the same place as a begin event, the insert 
should be processed first to reduce unnecessary conflicts.
Likewise if its at the same place as an end event, process the end event first 
for the same reason.

This also fixes https://bugs.llvm.org/show_bug.cgi?id=46511.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82898

Added: 

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp

Modified: 
clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 521e6ef549b9..1471301a3431 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -31,6 +31,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -590,6 +591,7 @@ void 
ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
 // An event can be either the begin or the end of an interval.
 enum EventType {
   ET_Begin = 1,
+  ET_Insert = 0,
   ET_End = -1,
 };
 
@@ -621,10 +623,17 @@ void 
ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
   //   one will be processed before, disallowing the second one, and the
   //   end point of the first one will also be processed before,
   //   disallowing the first one.
-  if (Type == ET_Begin)
+  switch (Type) {
+  case ET_Begin:
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
-  else
+break;
+  case ET_Insert:
+Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
+break;
+  case ET_End:
 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
+break;
+  }
 }
 
 bool operator<(const Event &Other) const {
@@ -662,19 +671,19 @@ void 
ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
   }
 
   // Build events from error intervals.
-  std::map> FileEvents;
+  llvm::StringMap> FileEvents;
   for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
   for (const auto &Replace : FileAndReplace.second) {
 unsigned Begin = Replace.getOffset();
 unsigned End = Begin + Replace.getLength();
-const std::string &FilePath = std::string(Replace.getFilePath());
-// FIXME: Handle empty intervals, such as those from insertions.
-if (Begin == End)
-  continue;
-auto &Events = FileEvents[FilePath];
-Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
-Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+auto &Events = FileEvents[Replace.getFilePath()];
+if (Begin == End) {
+  Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
+} else {
+  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
+  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+}
   }
 }
   }
@@ -686,14 +695,20 @@ void 
ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
 llvm::sort(Events);
 int OpenIntervals = 0;
 for (const auto &Event : Events) {
-  if (Event.Type == Event::ET_End)
---OpenIntervals;
-  // This has to be checked after removing the interval from the count if 
it
-  // is an end event, or before adding it if it is a begin event.
-  if (OpenIntervals != 0)
-Apply[Event.ErrorId] = false;
-  if (Event.Type == Event::ET_Begin)
-++OpenIntervals;
+  switch (Event.Type) {
+  case Event::ET_Begin:
+if (OpenIntervals++ != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_Insert:
+if (OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_End:
+if (--OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  }
 }
 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
   }

diff 

[clang-tools-extra] 45a720a - [clang-tidy] Use StringMap for ClangTidyOptions::OptionsMap

2020-07-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-30T10:31:13+01:00
New Revision: 45a720a864320bbbeb596abe412786fa91858980

URL: 
https://github.com/llvm/llvm-project/commit/45a720a864320bbbeb596abe412786fa91858980
DIFF: 
https://github.com/llvm/llvm-project/commit/45a720a864320bbbeb596abe412786fa91858980.diff

LOG: [clang-tidy] Use StringMap for ClangTidyOptions::OptionsMap

Ordering of options isn't important so an `llvm::StringMap` is a much better 
container for this purpose.

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D84868

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidy.cpp
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
clang-tools-extra/clang-tidy/ClangTidyOptions.h
clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index d6913dfd3c07..63c83a0b9954 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -329,12 +329,11 @@ static void setStaticAnalyzerCheckerOpts(const 
ClangTidyOptions &Opts,
  AnalyzerOptionsRef AnalyzerOptions) {
   StringRef AnalyzerPrefix(AnalyzerCheckNamePrefix);
   for (const auto &Opt : Opts.CheckOptions) {
-StringRef OptName(Opt.first);
-if (!OptName.startswith(AnalyzerPrefix))
+StringRef OptName(Opt.getKey());
+if (!OptName.consume_front(AnalyzerPrefix))
   continue;
 // Analyzer options are always local options so we can ignore priority.
-AnalyzerOptions->Config[OptName.substr(AnalyzerPrefix.size())] =
-Opt.second.Value;
+AnalyzerOptions->Config[OptName] = Opt.getValue().Value;
   }
 }
 

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index ffd5bf974ba2..737d85e092d9 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -72,7 +72,7 @@ llvm::Expected
 ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
   const auto &Iter = CheckOptions.find(NamePrefix + LocalName.str());
   if (Iter != CheckOptions.end())
-return Iter->second.Value;
+return Iter->getValue().Value;
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
@@ -85,7 +85,7 @@ findPriorityOption(const ClangTidyOptions::OptionMap 
&Options, StringRef NamePre
 return IterGlobal;
   if (IterGlobal == Options.end())
 return IterLocal;
-  if (IterLocal->second.Priority >= IterGlobal->second.Priority)
+  if (IterLocal->getValue().Priority >= IterGlobal->getValue().Priority)
 return IterLocal;
   return IterGlobal;
 }
@@ -94,7 +94,7 @@ llvm::Expected
 ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
   auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName);
   if (Iter != CheckOptions.end())
-return Iter->second.Value;
+return Iter->getValue().Value;
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
@@ -135,7 +135,7 @@ llvm::Expected
 ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const 
{
   auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName);
   if (Iter != CheckOptions.end())
-return getAsBool(Iter->second.Value, Iter->first);
+return getAsBool(Iter->getValue().Value, Iter->getKey());
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
@@ -177,7 +177,7 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   if (Iter == CheckOptions.end())
 return llvm::make_error((NamePrefix + 
LocalName).str());
 
-  StringRef Value = Iter->second.Value;
+  StringRef Value = Iter->getValue().Value;
   StringRef Closest;
   unsigned EditDistance = -1;
   for (const auto &NameAndEnum : Mapping) {
@@ -199,9 +199,9 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   }
   if (EditDistance < 3)
 return llvm::make_error(
-Iter->first, Iter->second.Value, std::string(Closest));
-  return llvm::make_error(Iter->first,
-  Iter->second.Value);
+Iter->getKey().str(), Iter->getValue().Value, Closest.str());
+  return llvm::make_error(Iter->getKey().str(),
+  Iter->getValue().Value);
 }
 
 void ClangTidyCheck::OptionsView::logErrToStdErr(llvm::Error &&Err) {

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index bb5a4b513967..19ba47f005dc 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -70,7 +70,7 @@ struct NOptionMap {
   NOptionMap(IO &, const ClangTidyOptions::OptionMa

[clang-tools-extra] 2c7ea1c - [clang-tidy] Address false positive in modernize-use-default-member-init

2020-04-03 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-03T19:43:46+01:00
New Revision: 2c7ea1c4c5f7dde562bac684a59ad67f1f062726

URL: 
https://github.com/llvm/llvm-project/commit/2c7ea1c4c5f7dde562bac684a59ad67f1f062726
DIFF: 
https://github.com/llvm/llvm-project/commit/2c7ea1c4c5f7dde562bac684a59ad67f1f062726.diff

LOG: [clang-tidy] Address false positive in modernize-use-default-member-init

Summary: Fixes [[ https://bugs.llvm.org/show_bug.cgi?id=45363 | incorrect 
warning emitted by "modernize-use-default-member-init" (new to 10.0.0) ]].

Reviewers: aaron.ballman, alexfh, gribozavr2

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77199

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index cb275ab58f1b..04cc7aa9d449 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -17,6 +17,12 @@ namespace clang {
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
+  return Node.getNumInits() == N;
+}
+} // namespace
+
 static StringRef getValueOfValueInit(const QualType InitType) {
   switch (InitType->getScalarTypeKind()) {
   case Type::STK_CPointer:
@@ -190,7 +196,7 @@ void UseDefaultMemberInitCheck::storeOptions(
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Init =
+  auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(integerLiteral())),
@@ -198,7 +204,13 @@ void 
UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-initListExpr(), declRefExpr(to(enumConstantDecl(;
+declRefExpr(to(enumConstantDecl(;
+
+  auto Init =
+  anyOf(initListExpr(anyOf(
+allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
+initCountIs(0))),
+InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
index 3570fcff4a5c..60344e06dc31 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -432,3 +432,17 @@ class FunctionTryBlock {
   // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: use default member initializer 
for 'k' [modernize-use-default-member-init]
   // CHECK-FIXES: int i{5}, k{8};
 };
+
+struct PR45363 {
+  // Ensure no warning is emitted here
+  PR45363(int i = 0) : m_i{i} {}
+  int m_i;
+};
+
+struct EmptyBracedIntDefault {
+  EmptyBracedIntDefault() : m_i{} {}
+  int m_i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'm_i' [modernize-use-default-member-init]
+  // CHECK-FIXES:  {{^  }}EmptyBracedIntDefault()  {}
+  // CHECK-FIXES-NEXT: {{^  }}int m_i{};
+};



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


[clang] 427c1dc - [ASTMatchers] Matchers that take enumerations args provide hints with invalid arguments

2020-04-06 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-06T20:00:30+01:00
New Revision: 427c1dc4f4248ec71e32a8f3832a4e6258446672

URL: 
https://github.com/llvm/llvm-project/commit/427c1dc4f4248ec71e32a8f3832a4e6258446672
DIFF: 
https://github.com/llvm/llvm-project/commit/427c1dc4f4248ec71e32a8f3832a4e6258446672.diff

LOG: [ASTMatchers] Matchers that take enumerations args provide hints with 
invalid arguments

Summary:
This adds support for giving hints when using dynamic matchers with enum args. 
Take this query, I couldn't figure out why the matcher wasn't working:
(Turns out it needed to be "IntegralToBoolean", but thats another bug itself)
```
clang-query> match implicitCastExpr(hasCastKind("CK_IntegralToBoolean"))
1:1: Error parsing argument 1 for matcher implicitCastExpr.
1:18: Error building matcher hasCastKind.
1:30: Incorrect type for arg 1. (Expected = string) != (Actual = String)
```
With this patch the new behaviour looks like this:
```
clang-query> match implicitCastExpr(hasCastKind("CK_IntegralToBoolean"))
1:1: Error parsing argument 1 for matcher implicitCastExpr.
1:18: Error building matcher hasCastKind.
1:30: Unknown value 'CK_IntegralToBoolean' for arg 1; did you mean 
'IntegralToBoolean'
```

There are no test cases for this yet as there simply isn't any infrastructure 
for testing errors reported when parsing args that I can see.

Reviewers: klimek, jdoerfert, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: aaron.ballman, dexonsmith, mgorny, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77499

Added: 
clang/lib/ASTMatchers/Dynamic/Marshallers.cpp

Modified: 
clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h 
b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
index 7dd304797c4f..f095dcdd60b0 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
@@ -65,6 +65,7 @@ class Diagnostics {
 ET_RegistryNotBindable = 4,
 ET_RegistryAmbiguousOverload = 5,
 ET_RegistryValueNotFound = 6,
+ET_RegistryUnknownEnumWithReplace = 7,
 
 ET_ParserStringError = 100,
 ET_ParserNoOpenParen = 101,

diff  --git a/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt 
b/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
index 10bd9c455eb4..1c6c1e68ce1e 100644
--- a/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
+++ b/clang/lib/ASTMatchers/Dynamic/CMakeLists.txt
@@ -14,9 +14,10 @@ endif()
 
 add_clang_library(clangDynamicASTMatchers
   Diagnostics.cpp
-  VariantValue.cpp
+  Marshallers.cpp
   Parser.cpp
   Registry.cpp
+  VariantValue.cpp
 
   LINK_LIBS
   clangAST

diff  --git a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp 
b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
index 8656bca870ec..969bd5f31789 100644
--- a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
@@ -98,6 +98,8 @@ static StringRef 
errorTypeToFormatString(Diagnostics::ErrorType Type) {
 return "Ambiguous matcher overload.";
   case Diagnostics::ET_RegistryValueNotFound:
 return "Value not found: $0";
+  case Diagnostics::ET_RegistryUnknownEnumWithReplace:
+return "Unknown value '$1' for arg $0; did you mean '$2'";
 
   case Diagnostics::ET_ParserStringError:
 return "Error parsing string token: <$0>";

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
new file mode 100644
index ..7e4e3ceb2b41
--- /dev/null
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
@@ -0,0 +1,89 @@
+#include "Marshallers.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include 
+
+static llvm::Optional
+getBestGuess(llvm::StringRef Search, llvm::ArrayRef Allowed,
+ llvm::StringRef DropPrefix = "", unsigned MaxEditDistance = 3) {
+  if (MaxEditDistance != ~0U)
+++MaxEditDistance;
+  llvm::StringRef Res;
+  for (const llvm::StringRef &Item : Allowed) {
+if (Item.equals_lower(Search)) {
+  assert(!Item.equals(Search) && "This should be handled earlier on.");
+  MaxEditDistance = 1;
+  Res = Item;
+  continue;
+}
+unsigned Distance = Item.edit_distance(Search);
+if (Distance < MaxEditDistance) {
+  MaxEditDistance = Distance;
+  Res = Item;
+}
+  }
+  if (!Res.empty())
+return Res.str();
+  if (!DropPrefix.empty()) {
+--MaxEditDistance; // Treat dropping the prefix as 1 edit
+for (const llvm::StringRef &Item : Allowed) {
+  auto NoPrefix = Item;
+  if (!NoPrefix.consume_front(DropPrefix))
+continue;
+  if (NoPrefix.equals_l

[clang] a473f0a - Fix mismatch from D77112 and D77499

2020-04-06 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-06T20:19:12+01:00
New Revision: a473f0a36c3f4117d8e77d3d8636303ff2f99d09

URL: 
https://github.com/llvm/llvm-project/commit/a473f0a36c3f4117d8e77d3d8636303ff2f99d09
DIFF: 
https://github.com/llvm/llvm-project/commit/a473f0a36c3f4117d8e77d3d8636303ff2f99d09.diff

LOG: Fix mismatch from D77112 and D77499

Added: 


Modified: 
clang/lib/ASTMatchers/Dynamic/Marshallers.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
index 7e4e3ceb2b41..64ff0dfb690e 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
@@ -79,8 +79,8 @@ llvm::Optional
 clang::ast_matchers::dynamic::internal::ArgTypeTraits<
 clang::OpenMPClauseKind>::getBestGuess(const VariantValue &Value) {
   static constexpr llvm::StringRef Allowed[] = {
-#define OPENMP_CLAUSE(TextualSpelling, Class) "OMPC_" #TextualSpelling,
-#include "clang/Basic/OpenMPKinds.def"
+#define OMP_CLAUSE_CLASS(Enum, Str, Class) #Enum,
+#include "llvm/Frontend/OpenMP/OMPKinds.def"
   };
   if (Value.isString())
 return ::getBestGuess(Value.getString(), llvm::makeArrayRef(Allowed),



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


[clang-tools-extra] 353a988 - [clangd] DefineOutline: removes static token from static CXXMethodDecl

2020-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-07T11:57:43+01:00
New Revision: 353a9883680e9d9666d02516a6692e8319af6d66

URL: 
https://github.com/llvm/llvm-project/commit/353a9883680e9d9666d02516a6692e8319af6d66
DIFF: 
https://github.com/llvm/llvm-project/commit/353a9883680e9d9666d02516a6692e8319af6d66.diff

LOG: [clangd] DefineOutline: removes static token from static CXXMethodDecl

Summary: Removes the `static` token when defining a function out of line if the 
function is a `CXXMethodDecl`

Reviewers: sammccall, kadircet, hokein

Reviewed By: kadircet

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang, #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D77534

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
clang-tools-extra/clangd/unittests/TweakTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index d9e07a001d23..c2d344a3a46e 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -239,21 +239,22 @@ getFunctionSourceCode(const FunctionDecl *FD, 
llvm::StringRef TargetNamespace,
   DelAttr(FD->getAttr());
   DelAttr(FD->getAttr());
 
-  if (FD->isVirtualAsWritten()) {
-SourceRange SpecRange{FD->getBeginLoc(), FD->getLocation()};
-bool HasErrors = true;
-
-// Clang allows duplicating virtual specifiers so check for multiple
-// occurrences.
-for (const auto &Tok : TokBuf.expandedTokens(SpecRange)) {
-  if (Tok.kind() != tok::kw_virtual)
+  auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
+bool FoundAny = false;
+for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
+  if (Tok.kind() != Kind)
 continue;
+  FoundAny = true;
   auto Spelling = TokBuf.spelledForExpanded(llvm::makeArrayRef(Tok));
   if (!Spelling) {
-HasErrors = true;
+Errors = llvm::joinErrors(
+std::move(Errors),
+llvm::createStringError(
+llvm::inconvertibleErrorCode(),
+llvm::formatv("define outline: couldn't remove `{0}` keyword.",
+  tok::getKeywordSpelling(Kind;
 break;
   }
-  HasErrors = false;
   CharSourceRange DelRange =
   syntax::Token::range(SM, Spelling->front(), Spelling->back())
   .toCharRange(SM);
@@ -261,13 +262,22 @@ getFunctionSourceCode(const FunctionDecl *FD, 
llvm::StringRef TargetNamespace,
   DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
 Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
 }
-if (HasErrors) {
+if (!FoundAny) {
   Errors = llvm::joinErrors(
   std::move(Errors),
-  llvm::createStringError(llvm::inconvertibleErrorCode(),
-  "define outline: Can't move out of line as "
-  "function has a macro `virtual` 
specifier."));
+  llvm::createStringError(
+  llvm::inconvertibleErrorCode(),
+  llvm::formatv(
+  "define outline: couldn't find `{0}` keyword to remove.",
+  tok::getKeywordSpelling(Kind;
 }
+  };
+
+  if (const auto *MD = dyn_cast(FD)) {
+if (MD->isVirtualAsWritten())
+  DelKeyword(tok::kw_virtual, {FD->getBeginLoc(), FD->getLocation()});
+if (MD->isStatic())
+  DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
   }
 
   if (Errors)

diff  --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp 
b/clang-tools-extra/clangd/unittests/TweakTests.cpp
index e91ff22d3533..979ee44f4474 100644
--- a/clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -2142,6 +2142,28 @@ TEST_F(DefineOutlineTest, ApplyTest) {
 };)cpp",
   "void B::foo()   {}\n",
   },
+  {
+  R"cpp(
+struct A {
+  static void fo^o() {}
+};)cpp",
+  R"cpp(
+struct A {
+  static void foo() ;
+};)cpp",
+  " void A::foo() {}\n",
+  },
+  {
+  R"cpp(
+struct A {
+  static static void fo^o() {}
+};)cpp",
+  R"cpp(
+struct A {
+  static static void foo() ;
+};)cpp",
+  "  void A::foo() {}\n",
+  },
   };
   for (const auto &Case : Cases) {
 SCOPED_TRACE(Case.Test);
@@ -2236,6 +2258,24 @@ TEST_F(DefineOutlineTest, HandleMacros) {
 STUPID_MACRO(sizeof sizeof int) void foo() ;
   };)cpp",
" void A::foo() {}\n"},
+  {R"cpp(#define STAT static
+  struct A {
+STAT void f^oo() {}
+ 

[clang] 3d1424b - Fixed licenses in dynamic ast matchers

2020-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-07T12:08:06+01:00
New Revision: 3d1424bc7a0e9a6f9887727e2bc93a10f50e1709

URL: 
https://github.com/llvm/llvm-project/commit/3d1424bc7a0e9a6f9887727e2bc93a10f50e1709
DIFF: 
https://github.com/llvm/llvm-project/commit/3d1424bc7a0e9a6f9887727e2bc93a10f50e1709.diff

LOG: Fixed licenses in dynamic ast matchers

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
clang/lib/ASTMatchers/Dynamic/VariantValue.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h 
b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index e317d3339e5b..e47b42a4f38c 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -1,4 +1,5 @@
-//===--- VariantValue.h - Polymorphic value type -*- C++ -*-===/
+//===--- VariantValue.h - Polymorphic value type *- C++ 
-*-===//
+//
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

diff  --git a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp 
b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
index 969bd5f31789..88c2279afb2e 100644
--- a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
@@ -1,4 +1,4 @@
-//===--- Diagnostics.cpp - Helper class for error diagnostics -*- C++ 
-*-===//
+//===--- Diagnostics.cpp - Helper class for error diagnostics ---*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
index 64ff0dfb690e..46312284e088 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
@@ -1,3 +1,11 @@
+//===--- Marshallers.cpp *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
 #include "Marshallers.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"

diff  --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp 
b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
index 7d0fb6ae2038..866e2d0e3491 100644
--- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
@@ -1,4 +1,4 @@
-//===--- VariantValue.cpp - Polymorphic value type -*- C++ -*-===/
+//===--- VariantValue.cpp - Polymorphic value type --*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.



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


[clang-tools-extra] fcf7cc2 - [clang-tidy] Added support for validating configuration options

2020-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-07T19:54:34+01:00
New Revision: fcf7cc268fe4560bc7cd751494beceff45f5dd10

URL: 
https://github.com/llvm/llvm-project/commit/fcf7cc268fe4560bc7cd751494beceff45f5dd10
DIFF: 
https://github.com/llvm/llvm-project/commit/fcf7cc268fe4560bc7cd751494beceff45f5dd10.diff

LOG: [clang-tidy] Added support for validating configuration options

Summary:
Adds support for `ClangTidyCheck::OptionsView` to deteremine:
  - If an option is found in the configuration.
  - If an integer option read from configuration is parsable to an integer.
  - Parse and Serialize enum configuration options directly using a mapping 
from `llvm::StringRef` to `EnumType`.
  - If an integer or enum option isn't parseable but there is a default value 
it will issue a warning to stderr that the config value hasn't been used.
  - If an enum option isn't parsable it can provide a hint if the value was a 
typo.

Reviewers: aaron.ballman, alexfh, gribozavr2

Reviewed By: aaron.ballman

Subscribers: xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D77085

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
clang-tools-extra/clang-tidy/ClangTidyCheck.h
clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index cc817d85dbcd..aadf372cda1a 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -7,10 +7,44 @@
 
//===--===//
 
 #include "ClangTidyCheck.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
 
 namespace clang {
 namespace tidy {
 
+char MissingOptionError::ID;
+char UnparseableEnumOptionError::ID;
+char UnparseableIntegerOptionError::ID;
+
+std::string MissingOptionError::message() const {
+  llvm::SmallString<128> Buffer;
+  llvm::raw_svector_ostream Output(Buffer);
+  Output << "option not found '" << OptionName << '\'';
+  return std::string(Buffer);
+}
+
+std::string UnparseableEnumOptionError::message() const {
+  llvm::SmallString<128> Buffer;
+  llvm::raw_svector_ostream Output(Buffer);
+  Output << "invalid configuration value '" << LookupValue << "' for option '"
+ << LookupName << '\'';
+  if (SuggestedValue)
+Output << "; did you mean '" << *SuggestedValue << "'?";
+  return std::string(Buffer);
+}
+
+std::string UnparseableIntegerOptionError::message() const {
+  llvm::SmallString<128> Buffer;
+  llvm::raw_svector_ostream Output(Buffer);
+  Output << "invalid configuration value '" << LookupValue << "' for option '"
+ << LookupName << "'; expected "
+ << (IsBoolean ? "a bool" : "an integer value");
+  return std::string(Buffer);
+}
+
 ClangTidyCheck::ClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
 : CheckName(CheckName), Context(Context),
   Options(CheckName, Context->getOptions().CheckOptions) {
@@ -34,17 +68,16 @@ ClangTidyCheck::OptionsView::OptionsView(StringRef 
CheckName,
  const ClangTidyOptions::OptionMap &CheckOptions)
 : NamePrefix(CheckName.str() + "."), CheckOptions(CheckOptions) {}
 
-std::string ClangTidyCheck::OptionsView::get(StringRef LocalName,
- StringRef Default) const {
+llvm::Expected
+ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
   const auto &Iter = CheckOptions.find(NamePrefix + LocalName.str());
   if (Iter != CheckOptions.end())
 return Iter->second;
-  return std::string(Default);
+  return llvm::make_error((NamePrefix + LocalName).str());
 }
 
-std::string
-ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName,
-  StringRef Default) const {
+llvm::Expected
+ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
   auto Iter = CheckOptions.find(NamePrefix + LocalName.str());
   if (Iter != CheckOptions.end())
 return Iter->second;
@@ -52,7 +85,65 @@ ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef 
LocalName,
   Iter = CheckOptions.find(LocalName.str());
   if (Iter != CheckOptions.end())
 return Iter->second;
-  return std::string(Default);
+  return llvm::make_error((NamePrefix + LocalName).str());
+}
+
+static llvm::Expected getAsBool(StringRef Value,
+  const llvm::Twine &LookupName) {
+  if (Value == "true")
+return true;
+  if (Value == "false")
+return false;
+  bool Result;
+  if (!Value.getAsInteger(10, Result))
+return Result;
+  return llvm::make_error(LookupName.str(),
+ Value.str(), true);
+}
+
+te

[clang-tools-extra] 9dff9ec - [clang-tidy] Change checks that take enum configurations to use a new access method.

2020-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-07T20:04:31+01:00
New Revision: 9dff9ecdd113ca57b8c548ebcdb14121bfd1840c

URL: 
https://github.com/llvm/llvm-project/commit/9dff9ecdd113ca57b8c548ebcdb14121bfd1840c
DIFF: 
https://github.com/llvm/llvm-project/commit/9dff9ecdd113ca57b8c548ebcdb14121bfd1840c.diff

LOG: [clang-tidy] Change checks that take enum configurations to use a new 
access method.

Summary: Change all checks that take enums as configuration to use enum 
specific methods in `ClangTidyCheck::OptionsView`.

Reviewers: aaron.ballman, alexfh

Reviewed By: aaron.ballman

Subscribers: wuzish, nemanjai, kbarton, arphaman, xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D76606

Added: 

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp

Modified: 
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/utils/IncludeSorter.cpp
clang-tools-extra/clang-tidy/utils/IncludeSorter.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
index 3f0ca4adb54c..513714e99cb8 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
@@ -26,8 +26,9 @@ 
StringFindStartswithCheck::StringFindStartswithCheck(StringRef Name,
 : ClangTidyCheck(Name, Context),
   StringLikeClasses(utils::options::parseStringList(
   Options.get("StringLikeClasses", "::std::basic_string"))),
-  IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
-  Options.getLocalOrGlobal("IncludeStyle", "llvm"))),
+  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::getMapping(),
+utils::IncludeSorter::IS_LLVM)),
   AbseilStringsMatchHeader(
   Options.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
 
@@ -121,8 +122,8 @@ void StringFindStartswithCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "StringLikeClasses",
 utils::options::serializeStringList(StringLikeClasses));
-  Options.store(Opts, "IncludeStyle",
-utils::IncludeSorter::toString(IncludeStyle));
+  Options.store(Opts, "IncludeStyle", IncludeStyle,
+utils::IncludeSorter::getMapping());
   Options.store(Opts, "AbseilStringsMatchHeader", AbseilStringsMatchHeader);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
index f616efb1db6b..a5756ff634bb 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -24,8 +24,9 @@ AST_MATCHER(VarDecl, isLocalVarDecl) { return 
Node.isLocalVarDecl(); }
 InitVariablesCheck::InitVariablesCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
-  Options.getLocalOrGlobal("IncludeStyle", "llvm"))),
+  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::getMapping(),
+utils::IncludeSorter::IS_LLVM)),
   MathHeader(Options.get("MathHeader", "math.h")) {}
 
 void InitVariablesCheck::registerMatchers(MatchFinder *Finder) {

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
index 56a8a8140271..b48511287f88 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -21,8 +21,9 @@ na

[clang-tools-extra] 0361798 - [clang-tidy] Fix buildbot failing with explicit specialization in class scope

2020-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-07T21:30:29+01:00
New Revision: 0361798dbeb6ead0a79ab7985f02da347fce988e

URL: 
https://github.com/llvm/llvm-project/commit/0361798dbeb6ead0a79ab7985f02da347fce988e
DIFF: 
https://github.com/llvm/llvm-project/commit/0361798dbeb6ead0a79ab7985f02da347fce988e.diff

LOG: [clang-tidy] Fix buildbot failing with explicit specialization in class 
scope

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index e90e92f6e136..84438c21a30b 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -312,41 +312,6 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   return Default;
 }
 
-/// Read a named option from the ``Context`` and parse it as a bool.
-///
-/// Reads the option with the check-local name \p LocalName from the
-/// ``CheckOptions``. If the corresponding key is not present, returns
-/// a ``MissingOptionError``. If the corresponding key can't be parsed as
-/// a bool, return an ``UnparseableIntegerOptionError``.
-template <> llvm::Expected get(StringRef LocalName) const;
-
-/// Read a named option from the ``Context`` and parse it as a bool.
-///
-/// Reads the option with the check-local name \p LocalName from the
-/// ``CheckOptions``. If the corresponding key is not present or it can't 
be
-/// parsed as a bool, returns \p Default.
-template <> bool get(StringRef LocalName, bool Default) const;
-
-/// Read a named option from the ``Context`` and parse it as a bool.
-///
-/// Reads the option with the check-local name \p LocalName from local or
-/// global ``CheckOptions``. Gets local option first. If local is not
-/// present, falls back to get global option. If global option is not
-/// present either, returns a ``MissingOptionError``. If the corresponding
-/// key can't be parsed as a bool, return an
-/// ``UnparseableIntegerOptionError``.
-template <>
-llvm::Expected getLocalOrGlobal(StringRef LocalName) const;
-
-/// Read a named option from the ``Context`` and parse it as a bool.
-///
-/// Reads the option with the check-local name \p LocalName from local or
-/// global ``CheckOptions``. Gets local option first. If local is not
-/// present, falls back to get global option. If global option is not
-/// present either or it can't be parsed as a bool, returns \p Default.
-template <>
-bool getLocalOrGlobal(StringRef LocalName, bool Default) const;
-
 /// Read a named option from the ``Context`` and parse it as an
 /// enum type ``T`` using the \p Mapping provided. If \p IgnoreCase is set,
 /// it will search the mapping ignoring the case.
@@ -488,6 +453,47 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   const LangOptions &getLangOpts() const { return Context->getLangOpts(); }
 };
 
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from the
+/// ``CheckOptions``. If the corresponding key is not present, returns
+/// a ``MissingOptionError``. If the corresponding key can't be parsed as
+/// a bool, return an ``UnparseableIntegerOptionError``.
+template <>
+llvm::Expected
+ClangTidyCheck::OptionsView::get(StringRef LocalName) const;
+
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from the
+/// ``CheckOptions``. If the corresponding key is not present or it can't be
+/// parsed as a bool, returns \p Default.
+template <>
+bool ClangTidyCheck::OptionsView::get(StringRef LocalName,
+bool Default) const;
+
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from local or
+/// global ``CheckOptions``. Gets local option first. If local is not
+/// present, falls back to get global option. If global option is not
+/// present either, returns a ``MissingOptionError``. If the corresponding
+/// key can't be parsed as a bool, return an
+/// ``UnparseableIntegerOptionError``.
+template <>
+llvm::Expected
+ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const;
+
+/// Read a named option from the ``Context`` and parse it as a bool.
+///
+/// Reads the option with the check-local name \p LocalName from local or
+/// global ``CheckOptions``. Gets local option first. If local is not
+/// present, falls back to get global option. If global option is not
+/// present either or it can't be parsed as a bool, returns \p Default.
+template <>
+bool ClangTidyCheck::OptionsView::getLocalOrG

[clang] bf968e2 - [ASTMatchers] Add support for dynamic matching of ofKind narrowing matcher

2020-04-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-09T14:33:04+01:00
New Revision: bf968e28ee82efce6a34a4dffd904c3c5df4eae4

URL: 
https://github.com/llvm/llvm-project/commit/bf968e28ee82efce6a34a4dffd904c3c5df4eae4
DIFF: 
https://github.com/llvm/llvm-project/commit/bf968e28ee82efce6a34a4dffd904c3c5df4eae4.diff

LOG: [ASTMatchers] Add support for dynamic matching of ofKind narrowing matcher

Summary: Adds support for using the ofKind in clang-query and other dynamic 
matcher use cases

Reviewers: klimek, aaron.ballman, jdoerfert

Reviewed By: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77791

Added: 


Modified: 
clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
index 46312284e088..de1a97814e42 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
@@ -95,3 +95,17 @@ clang::ast_matchers::dynamic::internal::ArgTypeTraits<
   "OMPC_");
   return llvm::None;
 }
+
+llvm::Optional
+clang::ast_matchers::dynamic::internal::ArgTypeTraits<
+clang::UnaryExprOrTypeTrait>::getBestGuess(const VariantValue &Value) {
+  static constexpr llvm::StringRef Allowed[] = {
+  "UETT_SizeOf",   "UETT_AlignOf",
+  "UETT_VecStep",  "UETT_OpenMPRequiredSimdAlign",
+  "UETT_PreferredAlignOf",
+  };
+  if (Value.isString())
+return ::getBestGuess(Value.getString(), llvm::makeArrayRef(Allowed),
+  "UETT_");
+  return llvm::None;
+}

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 3d36ed6ea187..288155217d5c 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -27,6 +27,7 @@
 #include "clang/Basic/AttrKinds.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/OpenMPKinds.h"
+#include "clang/Basic/TypeTraits.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
@@ -214,6 +215,35 @@ template <> struct ArgTypeTraits {
   static llvm::Optional getBestGuess(const VariantValue &Value);
 };
 
+template <> struct ArgTypeTraits {
+private:
+  static Optional
+  getUnaryOrTypeTraitKind(llvm::StringRef ClauseKind) {
+// FIXME: Type traits should probably be in a `.def` to make less error
+// prone.
+return llvm::StringSwitch>(ClauseKind)
+.Case("UETT_SizeOf", UETT_SizeOf)
+.Case("UETT_AlignOf", UETT_AlignOf)
+.Case("UETT_VecStep", UETT_VecStep)
+.Case("UETT_OpenMPRequiredSimdAlign", UETT_OpenMPRequiredSimdAlign)
+.Case("UETT_PreferredAlignOf", UETT_PreferredAlignOf)
+.Default(llvm::None);
+  }
+
+public:
+  static bool is(const VariantValue &Value) {
+return Value.isString() && getUnaryOrTypeTraitKind(Value.getString());
+  }
+
+  static UnaryExprOrTypeTrait get(const VariantValue &Value) {
+return *getUnaryOrTypeTraitKind(Value.getString());
+  }
+
+  static ArgKind getKind() { return ArgKind(ArgKind::AK_String); }
+
+  static llvm::Optional getBestGuess(const VariantValue &Value);
+};
+
 /// Matcher descriptor interface.
 ///
 /// Provides a \c create() method that constructs the matcher from the provided

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 259b81ab19f0..e7659feaf1e9 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -95,9 +95,6 @@ void RegistryMaps::registerMatcher(
 RegistryMaps::RegistryMaps() {
   // TODO: Here is the list of the missing matchers, grouped by reason.
   //
-  // Need Variant/Parser fixes:
-  // ofKind
-  //
   // Polymorphic + argument overload:
   // findAll
   //
@@ -458,6 +455,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(objcThrowStmt);
   REGISTER_MATCHER(objcTryStmt);
   REGISTER_MATCHER(ofClass);
+  REGISTER_MATCHER(ofKind);
   REGISTER_MATCHER(ompDefaultClause);
   REGISTER_MATCHER(ompExecutableDirective);
   REGISTER_MATCHER(on);

diff  --git a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp 
b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
index 71c2e3e5addf..1b553ffe73ed 100644
--- a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -242,6 +242,14 @@ TEST(ParserTest, FullParserTest) {
   EXPECT_TRUE(matches("void f(int a, int x);", M));
   EXPECT_FALSE(matches("void f(int x, int a);", M));
 
+  Code = "unaryExprOrTypeTraitExpr(ofKind(\"UETT_SizeOf\"))";
+  llvm::Optional UnaryExprSizeOf(
+  Parser::parseMatcherExpression(Code, nullptr, nullpt

[clang] db71354 - [ASTMatchers] Fixed CastKind being parsed incorrectly for dynamic matchers

2020-04-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-09T15:09:45+01:00
New Revision: db71354e4ff13e8f5c6ab38da6339c7583209be0

URL: 
https://github.com/llvm/llvm-project/commit/db71354e4ff13e8f5c6ab38da6339c7583209be0
DIFF: 
https://github.com/llvm/llvm-project/commit/db71354e4ff13e8f5c6ab38da6339c7583209be0.diff

LOG: [ASTMatchers] Fixed CastKind being parsed incorrectly for dynamic matchers

Summary: Requires hasCastKind arguments to have `CK_` prefixed to bring it in 
line with the documentation and other matchers that take enumerations.

Reviewers: klimek, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77503

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 7490ecd89186..f5106f0e0ba2 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -2790,7 +2790,7 @@ Narrowing Matchers
   int *p = 0;
 
 If the matcher is use from clang-query, CastKind parameter
-should be passed as a quoted string. e.g., ofKind("CK_NullToPointer").
+should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
 
 
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 9d7b4dcaacfd..070c38295ba7 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4913,7 +4913,7 @@ AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
 /// \endcode
 ///
 /// If the matcher is use from clang-query, CastKind parameter
-/// should be passed as a quoted string. e.g., ofKind("CK_NullToPointer").
+/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
   return Node.getCastKind() == Kind;
 }

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
index de1a97814e42..d45965d013cf 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.cpp
@@ -75,11 +75,12 @@ llvm::Optional
 clang::ast_matchers::dynamic::internal::ArgTypeTraits<
 clang::CastKind>::getBestGuess(const VariantValue &Value) {
   static constexpr llvm::StringRef Allowed[] = {
-#define CAST_OPERATION(Name) #Name,
+#define CAST_OPERATION(Name) "CK_" #Name,
 #include "clang/AST/OperationKinds.def"
   };
   if (Value.isString())
-return ::getBestGuess(Value.getString(), llvm::makeArrayRef(Allowed));
+return ::getBestGuess(Value.getString(), llvm::makeArrayRef(Allowed),
+  "CK_");
   return llvm::None;
 }
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 288155217d5c..582a060842b9 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -171,7 +171,7 @@ template <> struct ArgTypeTraits {
 private:
   static Optional getCastKind(llvm::StringRef AttrKind) {
 return llvm::StringSwitch>(AttrKind)
-#define CAST_OPERATION(Name) .Case( #Name, CK_##Name)
+#define CAST_OPERATION(Name) .Case("CK_" #Name, CK_##Name)
 #include "clang/AST/OperationKinds.def"
 .Default(llvm::None);
   }

diff  --git a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp 
b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
index 1b553ffe73ed..0d3a2d4ce776 100644
--- a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -221,6 +221,15 @@ TEST(ParserTest, FullParserTest) {
   EXPECT_FALSE(matches("int x = 1 - false;", M));
   EXPECT_FALSE(matches("int x = true - 1;", M));
 
+  Code = "implicitCastExpr(hasCastKind(\"CK_IntegralToBoolean\"))";
+  llvm::Optional implicitIntBooleanCast(
+  Parser::parseMatcherExpression(Code, nullptr, nullptr, &Error));
+  EXPECT_EQ("", Error.toStringFull());
+  Matcher MCastStmt =
+  implicitIntBooleanCast->unconditionalConvertTo();
+  EXPECT_TRUE(matches("bool X = 1;", MCastStmt));
+  EXPECT_FALSE(matches("bool X = true;", MCastStmt));
+
   Code = "functionDecl(hasParameter(1, hasName(\"x\")))";
   llvm::Optional HasParameter(
   Parser::parseMatcherExpression(Code, &Error));



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


[clang-tools-extra] 672207c - [clang-tidy] Convert config options that are bools to use the bool overload of get(GlobalOrLocal)?

2020-04-12 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-04-12T23:06:09+01:00
New Revision: 672207c319a06f20dc634bcd21678d5dbbe7a6b9

URL: 
https://github.com/llvm/llvm-project/commit/672207c319a06f20dc634bcd21678d5dbbe7a6b9
DIFF: 
https://github.com/llvm/llvm-project/commit/672207c319a06f20dc634bcd21678d5dbbe7a6b9.diff

LOG: [clang-tidy] Convert config options that are bools to use the bool 
overload of get(GlobalOrLocal)?

Summary: This was done with a script that looks for calls to 
Options.get(GlobalOrLocal) that take an integer for the second argument and the 
result is either compared not equal to 0 or implicitly converted to bool. There 
may be other occurances

Reviewers: aaron.ballman, alexfh, gribozavr2

Reviewed By: aaron.ballman

Subscribers: wuzish, nemanjai, xazax.hun, kbarton, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77831

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.h
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/MacroUsageCheck.h
clang-tools-extra/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.h
clang-tools-extra/clang-tidy/misc/UnusedParametersCheck.cpp
clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.h
clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.cpp
clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp

clang-tools-extra/clang-tidy/performance/InefficientStringConcatenationCheck.cpp
clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp

clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.h
clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
index 4da91d1162ac..5ec4c779d59a 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp
@@ -23,16 +23,16 @@ namespace bugprone {
 ArgumentCommentCheck::ArgumentCommentCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  StrictMode(Options.getLocalOrGlobal("StrictMode", 0) != 0),
-  IgnoreSingleArgument(Options.get("IgnoreSingleArgument", 0) != 0),
-  CommentBoolLiterals(Options.get("CommentBoolLiterals", 0) != 0),
-  CommentIntegerLiterals(Options.get("CommentIntegerLiterals", 0) != 0),
-  CommentFloatLiterals(Options.get("CommentFloatLiterals", 0) != 0),
-  CommentStringLiterals(Options.get("CommentStringLiterals", 0) != 0),
-  CommentUserDefinedLiterals(Options.get("CommentUserDefinedLiterals", 0) 
!=
- 0),
-  CommentCharacterLiterals(Options.get("CommentCharacterLiterals", 0) != 
0),
-  CommentNullPtrs(Options.get("CommentNullPtrs", 0) != 0),
+  StrictMode(Options.getLocalOrGlobal("StrictMode", false)),
+  IgnoreSingleArgument(Options.get("IgnoreSingleArgument", false)),
+  CommentBoolLiterals(Options.get("CommentBoolLiterals", false)),
+  CommentIntegerLiterals(Options.get("CommentIntegerLiterals", false)),
+  CommentFloatLiterals(Options.get("CommentFloatLiterals", false)),
+  CommentStringLiterals(Options.get("CommentStringLiterals", false)),
+  CommentUserDefinedLiterals(
+  Options.get("CommentUserDefinedLiterals", false)),
+  CommentCharacterLiterals(Options.get("CommentCharacterLiterals", false)),
+  CommentNullPtrs(Options.get("CommentNullPtrs", false)),
   IdentRE("^(/\\* 

[clang-tools-extra] 6780be4 - second attempt to fix build after add51e1

2020-06-03 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-03T15:16:36+01:00
New Revision: 6780be4c63e582466a35d7644c35e09ba85d4f67

URL: 
https://github.com/llvm/llvm-project/commit/6780be4c63e582466a35d7644c35e09ba85d4f67
DIFF: 
https://github.com/llvm/llvm-project/commit/6780be4c63e582466a35d7644c35e09ba85d4f67.diff

LOG: second attempt to fix build after add51e1

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/readability-use-anyofallof.cpp

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-use-anyofallof.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-use-anyofallof.cpp
index 5b19dd0b8db6..bf4fe0e58da9 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/readability-use-anyofallof.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/readability-use-anyofallof.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++14,c++17 %s readability-use-anyofallof %t
+// RUN: %check_clang_tidy -std=c++14,c++17 %s readability-use-anyofallof %t -- 
-- -fexceptions
 
 bool good_any_of() {
   int v[] = {1, 2, 3};



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


[clang-tools-extra] e21c3f2 - [clang-tidy] ignore builtin varargs from pro-type-vararg-check

2020-06-04 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-04T17:58:23+01:00
New Revision: e21c3f223a3537df0d9d02fce5038b3d7b98ab52

URL: 
https://github.com/llvm/llvm-project/commit/e21c3f223a3537df0d9d02fce5038b3d7b98ab52
DIFF: 
https://github.com/llvm/llvm-project/commit/e21c3f223a3537df0d9d02fce5038b3d7b98ab52.diff

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

Disables the check from warning on some built in vararg functions, Address [[ 
https://bugs.llvm.org/show_bug.cgi?id=45860 | Clang-tidy should not consider 
__builtin_constant_p a variadic function. ]]

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D80887

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp

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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
index 4509c934ddc5..f6aeb8321337 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ b/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 @@ namespace cppcoreguidelines {
 
 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 &Context = 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()),
+  hasType(qualType(
+  anyOf(isVAList(), 
decayedType(hasOriginalType(isVAList()))
+  .bind("va_list"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {
@@ -54,7 +116,7 @@ void ProTypeVarargCheck::check(const 
MatchFinder::MatchResult &Result) {
 
   if (const auto *Matched = Result.Nodes.getNodeAs("va_use")) {
 diag(Matched->getExprLoc(),
- "do not use va_start/va_arg to define c-style vararg functions; "
+ "do not use va_arg to define c-style vararg functions; "
  "use variadic templates instead");
   }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
index 021322aacb62..1e3b5ee036ca 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -39,13 +39,22 @@ void CallFooIfAvailable(T& t) {
 #includ

[clang-tools-extra] ce5fecb - Assignment and Inc/Dec operators wouldn't register as a mutation when Implicit Paren Casts were present

2020-06-09 Thread Nathan James via cfe-commits

Author: Tridacnid
Date: 2020-06-09T19:45:57+01:00
New Revision: ce5fecb7d0a12c27763afe3f89d1d7e8a1893dc0

URL: 
https://github.com/llvm/llvm-project/commit/ce5fecb7d0a12c27763afe3f89d1d7e8a1893dc0
DIFF: 
https://github.com/llvm/llvm-project/commit/ce5fecb7d0a12c27763afe3f89d1d7e8a1893dc0.diff

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

Add ignoringParenImpCasts to assignment and inc/dec mutation checks in 
ExprMutationAnalyzer to fix clang-tidy bug PR45490.
https://bugs.llvm.org/show_bug.cgi?id=45490

Reviewed By: njames93, aaron.ballman, gribozavr2

Differential Revision: https://reviews.llvm.org/D79912

Added: 


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

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
index 427b5f0272b9..8bd4df7cd844 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-infinite-loop.cpp
@@ -70,11 +70,25 @@ void simple_not_infinite1() {
 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 @@ void simple_not_infinite1() {
 
   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() {

diff  --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index cb5cabfd3089..2f80285f17b4 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -201,14 +201,15 @@ const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation(
 
 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.

diff  --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index 9b0a3dbda81e..9d26eeb6af73 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -112,11 +112,21 @@ TEST(ExprMutationAnalyzerTest, Trivial) {
 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 @@ TEST_P(IncDecTest, IncDecModifies) {
 }
 
 INSTANTIATE_TEST_CASE_P(AllIncDecOperators, IncDecTest,
-Values("++x", "--x", "x++"

[clang-tools-extra] 740575d - [clangd] Fix readability-else-after-return 'Adding a note without main diagnostic' crash

2020-06-16 Thread Nathan James via cfe-commits

Author: njames93
Date: 2020-06-16T12:01:56+01:00
New Revision: 740575dc232b25de0a4bedb41e825ee2e5a056ea

URL: 
https://github.com/llvm/llvm-project/commit/740575dc232b25de0a4bedb41e825ee2e5a056ea
DIFF: 
https://github.com/llvm/llvm-project/commit/740575dc232b25de0a4bedb41e825ee2e5a056ea.diff

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

Fix a crash in clangd caused by an (admittidly incorrect) Remark diagnositic 
being emitted from readability-else-after-return.
This crash doesn't occur in clang-tidy so there are no tests there for this.

Reviewed By: hokein

Differential Revision: https://reviews.llvm.org/D81785

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
index b3b4e0de2bf0..a13c172c7f76 100644
--- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -188,9 +188,8 @@ void ElseAfterReturnCheck::check(const 
MatchFinder::MatchResult &Result) {
 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


[clang-tools-extra] e1ba724 - [clang-tidy] simplify-bool-expr ignores template instantiations

2020-06-16 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-16T13:54:48+01:00
New Revision: e1ba7241c3efc3a36439a6f80a7367c26cc193b1

URL: 
https://github.com/llvm/llvm-project/commit/e1ba7241c3efc3a36439a6f80a7367c26cc193b1
DIFF: 
https://github.com/llvm/llvm-project/commit/e1ba7241c3efc3a36439a6f80a7367c26cc193b1.diff

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

Ignore template instantiations in the matchers, Addresses [[ 
https://bugs.llvm.org/show_bug.cgi?id=46226 | readability-simplify-boolean-expr 
false-positive for bool from template. ]]

Reviewed By: aaron.ballman, lebedev.ri

Differential Revision: https://reviews.llvm.org/D81336

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp

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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index fb33e50cb1ca..4c83499ff7ca 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -422,7 +422,7 @@ void 
SimplifyBooleanExprCheck::matchBoolCondition(MatchFinder *Finder,
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(isExpansionInMainFile(),
+  ifStmt(unless(isInTemplateInstantiation()),
  hasCondition(cxxBoolLiteral(equals(Value)).bind(BooleanId)))
   .bind(IfStmtId),
   this);
@@ -432,7 +432,7 @@ void 
SimplifyBooleanExprCheck::matchTernaryResult(MatchFinder *Finder,
   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::matchTernaryResult(MatchFinder *Finder,
 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 @@ void 
SimplifyBooleanExprCheck::matchIfAssignsBool(MatchFinder *Finder,
   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 @@ void 
SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
+  unless(isInTemplateInstantiation()),
   hasAnySubstatement(
   ifStmt(hasThen(returnsBool(Value)), unless(hasElse(stmt(),
   hasAnySubstatement(returnStmt(has(ignoringParenImpCasts(

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
index cd93c5d4be76..3f49eec4c88a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-s

[clang-tools-extra] ccd1270 - [clang-tidy] warnings-as-error no longer exits with ErrorCount

2020-06-17 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-17T14:35:37+01:00
New Revision: ccd127008aa2aa0a303c9a0a48f4080a5bb7cd0b

URL: 
https://github.com/llvm/llvm-project/commit/ccd127008aa2aa0a303c9a0a48f4080a5bb7cd0b
DIFF: 
https://github.com/llvm/llvm-project/commit/ccd127008aa2aa0a303c9a0a48f4080a5bb7cd0b.diff

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

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D81953

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index aca16b0d6d81..7f668345bbb1 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -478,7 +478,7 @@ int clangTidyMain(int argc, const char **argv) {
   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


[clang-tools-extra] 08c83ed - [clang-tidy][NFC] Remove the double look-up on IncludeInserter

2020-06-17 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-17T19:48:34+01:00
New Revision: 08c83ed75752169bdf27df8f5ea5978c53f2e258

URL: 
https://github.com/llvm/llvm-project/commit/08c83ed75752169bdf27df8f5ea5978c53f2e258
DIFF: 
https://github.com/llvm/llvm-project/commit/08c83ed75752169bdf27df8f5ea5978c53f2e258.diff

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

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82004

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp 
b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
index c267789c9412..f7201a9fdcfe 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
@@ -45,6 +45,19 @@ std::unique_ptr 
IncludeInserter::CreatePPCallbacks() {
   return std::make_unique(this);
 }
 
+IncludeSorter &IncludeInserter::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 &Entry = IncludeSorterByFile[FileID];
+  if (!Entry) {
+// If it wasn't found, Entry will be default constructed to nullptr.
+Entry = std::make_unique(
+&SourceMgr, &LangOpts, FileID,
+SourceMgr.getFilename(SourceMgr.getLocForStartOfFile(FileID)), Style);
+  }
+  return *Entry;
+}
+
 llvm::Optional
 IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,
 bool IsAngled) {
@@ -53,31 +66,14 @@ IncludeInserter::CreateIncludeInsertion(FileID FileID, 
StringRef Header,
   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(
-&SourceMgr, &LangOpts, 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(
-&SourceMgr, &LangOpts, FileID,
-SourceMgr.getFilename(HashLocation), Style)));
-  }
-  IncludeSorterByFile[FileID]->AddInclude(FileName, IsAngled, HashLocation,
-  EndLocation);
+  getOrCreate(FileID).AddInclude(FileName, IsAngled, HashLocation, 
EndLocation);
 }
 
 } // namespace utils

diff  --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h 
b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
index e39e002e97a2..35cbb6ce8568 100644
--- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
+++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h
@@ -71,6 +71,8 @@ class IncludeInserter {
   void AddInclude(StringRef FileName, bool IsAngled,
   SourceLocation HashLocation, SourceLocation EndLocation);
 
+  IncludeSorter &getOrCreate(FileID FileID);
+
   llvm::DenseMap> IncludeSorterByFile;
   llvm::DenseMap> InsertedHeaders;
   const SourceManager &SourceMgr;



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


[clang-tools-extra] d3bf1f3 - Revert "[clang-tidy] For `run-clang-tidy.py` escape the paths that are used for analysis."

2020-07-02 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-02T08:54:55+01:00
New Revision: d3bf1f3af2f26a7c100c3aa6b8ae93feb7034cb8

URL: 
https://github.com/llvm/llvm-project/commit/d3bf1f3af2f26a7c100c3aa6b8ae93feb7034cb8
DIFF: 
https://github.com/llvm/llvm-project/commit/d3bf1f3af2f26a7c100c3aa6b8ae93feb7034cb8.diff

LOG: Revert "[clang-tidy] For `run-clang-tidy.py` escape the paths that are 
used for analysis."

This reverts commit 068fa35746637fde29355a43d17d554a92b32cdf.

Based on a regression reported in https://bugs.llvm.org/show_bug.cgi?id=46536

Added: 


Modified: 
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 2b5e78b38f01..4272ae0957fe 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -277,7 +277,6 @@ def main():
 tmpdir = tempfile.mkdtemp()
 
   # Build up a big regexy filter from all command line arguments.
-  args.files = [re.escape(f) for f in args.files]
   file_name_re = re.compile('|'.join(args.files))
 
   return_code = 0



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


[clang] f51a319 - [ASTMatchers] Enhanced support for matchers taking Regex arguments

2020-07-02 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-02T14:52:25+01:00
New Revision: f51a319cacd44819b4fb9fa9f005c2445bcee984

URL: 
https://github.com/llvm/llvm-project/commit/f51a319cacd44819b4fb9fa9f005c2445bcee984
DIFF: 
https://github.com/llvm/llvm-project/commit/f51a319cacd44819b4fb9fa9f005c2445bcee984.diff

LOG: [ASTMatchers] Enhanced support for matchers taking Regex arguments

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.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82706

Added: 


Modified: 
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

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index ae90ba047df9..9c04322f0ae6 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -3007,7 +3007,7 @@ Narrowing Matchers
 
 
 
-MatcherDecl>isExpansionInFileMatchingstd::string
 RegExp
+MatcherDecl>isExpansionInFileMatchingStringRef
 RegExp, Regex::RegexFlags Flags = NoFlags
 Matches 
AST nodes that were expanded within files whose name is
 partially matching a given regex.
 
@@ -3019,6 +3019,10 @@ Narrowing Matchers
   class Y {};
 
 Usable as: MatcherDecl>, 
MatcherStmt>, 
MatcherTypeLoc>
+
+If the matcher is used in clang-query, RegexFlags parameter
+should be passed as a quoted string. e.g: "NoFlags".
+Flags can be combined with '|' example "IgnoreCase | BasicRegex"
 
 
 
@@ -3725,7 +3729,7 @@ Narrowing Matchers
 
 
 
-MatcherNamedDecl>matchesNamestd::string RegExp
+MatcherNamedDecl>matchesNameStringRef RegExp, 
Regex::RegexFlags Flags = NoFlags
 Matches NamedDecl nodes 
whose fully qualified names contain
 a substring matched by the given RegExp.
 
@@ -3738,6 +3742,10 @@ Narrowing Matchers
 
 Example matches X (regexp is one of "::X", "^foo::.*X", among others)
   namespace foo { namespace bar { class X; } }
+
+If the matcher is used in clang-query, RegexFlags parameter
+should be passed as a quoted string. e.g: "NoFlags".
+Flags can be combined with '|' example "IgnoreCase | BasicRegex"
 
 
 
@@ -3932,12 +3940,16 @@ Narrowing Matchers
 
 
 
-MatcherObjCMessageExpr>matchesSelectorstd::string 
RegExp
+MatcherObjCMessageExpr>matchesSelectorStringRef RegExp, 
Regex::RegexFlags Flags = NoFlags
 Matches ObjC 
selectors whose name contains
 a substring matched by the given RegExp.
  matcher = objCMessageExpr(matchesSelector("loadHTMLStringmatches the outer 
message expr in the code below, but NOT the message
  invocation for self.bodyView.
 [self.bodyView loadHTMLString:html baseURL:NULL];
+
+If the matcher is used in clang-query, RegexFlags parameter
+should be passed as a quoted string. e.g: "NoFlags".
+Flags can be combined with '|' example "IgnoreCase | BasicRegex"
 
 
 
@@ -4228,7 +4240,7 

[clang-tools-extra] e8158bf - [NFC] Clean up braces and anon namespace

2020-07-05 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-05T11:16:40+01:00
New Revision: e8158bf0e770e7a4cf73df91552af1e156a3ea17

URL: 
https://github.com/llvm/llvm-project/commit/e8158bf0e770e7a4cf73df91552af1e156a3ea17
DIFF: 
https://github.com/llvm/llvm-project/commit/e8158bf0e770e7a4cf73df91552af1e156a3ea17.diff

LOG: [NFC] Clean up braces and anon namespace

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
index 98ca34eb620c..9ad6fb737ec9 100644
--- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -19,7 +19,6 @@ namespace clang {
 namespace tidy {
 namespace readability {
 
-namespace {
 static const char ReturnStr[] = "return";
 static const char ContinueStr[] = "continue";
 static const char BreakStr[] = "break";
@@ -28,44 +27,40 @@ static const char WarningMessage[] = "do not use 'else' 
after '%0'";
 static const char WarnOnUnfixableStr[] = "WarnOnUnfixable";
 static const char WarnOnConditionVariablesStr[] = "WarnOnConditionVariables";
 
-const DeclRefExpr *findUsage(const Stmt *Node, int64_t DeclIdentifier) {
+static const DeclRefExpr *findUsage(const Stmt *Node, int64_t DeclIdentifier) {
   if (!Node)
 return nullptr;
   if (const auto *DeclRef = dyn_cast(Node)) {
-if (DeclRef->getDecl()->getID() == DeclIdentifier) {
+if (DeclRef->getDecl()->getID() == DeclIdentifier)
   return DeclRef;
-}
   } else {
 for (const Stmt *ChildNode : Node->children()) {
-  if (const DeclRefExpr *Result = findUsage(ChildNode, DeclIdentifier)) {
+  if (const DeclRefExpr *Result = findUsage(ChildNode, DeclIdentifier))
 return Result;
-  }
 }
   }
   return nullptr;
 }
 
-const DeclRefExpr *
+static const DeclRefExpr *
 findUsageRange(const Stmt *Node,
-   const llvm::iterator_range &DeclIdentifiers) {
+   const llvm::ArrayRef &DeclIdentifiers) {
   if (!Node)
 return nullptr;
   if (const auto *DeclRef = dyn_cast(Node)) {
-if (llvm::is_contained(DeclIdentifiers, DeclRef->getDecl()->getID())) {
+if (llvm::is_contained(DeclIdentifiers, DeclRef->getDecl()->getID()))
   return DeclRef;
-}
   } else {
 for (const Stmt *ChildNode : Node->children()) {
   if (const DeclRefExpr *Result =
-  findUsageRange(ChildNode, DeclIdentifiers)) {
+  findUsageRange(ChildNode, DeclIdentifiers))
 return Result;
-  }
 }
   }
   return nullptr;
 }
 
-const DeclRefExpr *checkInitDeclUsageInElse(const IfStmt *If) {
+static const DeclRefExpr *checkInitDeclUsageInElse(const IfStmt *If) {
   const auto *InitDeclStmt = dyn_cast_or_null(If->getInit());
   if (!InitDeclStmt)
 return nullptr;
@@ -82,25 +77,23 @@ const DeclRefExpr *checkInitDeclUsageInElse(const IfStmt 
*If) {
   return findUsageRange(If->getElse(), DeclIdentifiers);
 }
 
-const DeclRefExpr *checkConditionVarUsageInElse(const IfStmt *If) {
-  const VarDecl *CondVar = If->getConditionVariable();
-  return CondVar != nullptr ? findUsage(If->getElse(), CondVar->getID())
-: nullptr;
+static const DeclRefExpr *checkConditionVarUsageInElse(const IfStmt *If) {
+  if (const VarDecl *CondVar = If->getConditionVariable())
+return findUsage(If->getElse(), CondVar->getID());
+  return nullptr;
 }
 
-bool containsDeclInScope(const Stmt *Node) {
-  if (isa(Node)) {
+static bool containsDeclInScope(const Stmt *Node) {
+  if (isa(Node))
 return true;
-  }
-  if (const auto *Compound = dyn_cast(Node)) {
+  if (const auto *Compound = dyn_cast(Node))
 return llvm::any_of(Compound->body(), [](const Stmt *SubNode) {
   return isa(SubNode);
 });
-  }
   return false;
 }
 
-void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context,
+static void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context,
const Stmt *Else, SourceLocation ElseLoc) {
   auto Remap = [&](SourceLocation Loc) {
 return Context.getSourceManager().getExpansionLoc(Loc);
@@ -134,7 +127,6 @@ void removeElseAndBrackets(DiagnosticBuilder &Diag, 
ASTContext &Context,
 SourceRange(ElseExpandedLoc, EndLoc), Repl);
   }
 }
-} // namespace
 
 ElseAfterReturnCheck::ElseAfterReturnCheck(StringRef Name,
ClangTidyContext *Context)



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


[clang-tools-extra] fc3c693 - [clang-tidy] Added alias llvm-else-after-return.

2020-07-06 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-06T14:39:03+01:00
New Revision: fc3c693b617fc5fde8939a3aec7e7372ace07693

URL: 
https://github.com/llvm/llvm-project/commit/fc3c693b617fc5fde8939a3aec7e7372ace07693
DIFF: 
https://github.com/llvm/llvm-project/commit/fc3c693b617fc5fde8939a3aec7e7372ace07693.diff

LOG: [clang-tidy] Added alias llvm-else-after-return.

Added an alias llvm-else-after-return from readability-else-after-return to 
help enforce one of the llvm coding guidelines.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82825

Added: 
clang-tools-extra/docs/clang-tidy/checks/llvm-else-after-return.rst

Modified: 
clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst
clang-tools-extra/docs/clang-tidy/checks/readability-else-after-return.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp 
b/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
index 2aaf07639267..0310a8e07a2d 100644
--- a/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
@@ -9,6 +9,7 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "../readability/ElseAfterReturnCheck.h"
 #include "../readability/NamespaceCommentCheck.h"
 #include "../readability/QualifiedAutoCheck.h"
 #include "HeaderGuardCheck.h"
@@ -24,6 +25,8 @@ namespace llvm_check {
 class LLVMModule : public ClangTidyModule {
 public:
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
+CheckFactories.registerCheck(
+"llvm-else-after-return");
 CheckFactories.registerCheck("llvm-header-guard");
 CheckFactories.registerCheck("llvm-include-order");
 CheckFactories.registerCheck(
@@ -40,6 +43,9 @@ class LLVMModule : public ClangTidyModule {
   ClangTidyOptions getModuleOptions() override {
 ClangTidyOptions Options;
 Options.CheckOptions["llvm-qualified-auto.AddConstToQualified"] = "0";
+Options.CheckOptions["llvm-else-after-return.WarnOnUnfixable"] = "0";
+Options.CheckOptions["llvm-else-after-return.RefactorConditionVariables"] =
+"0";
 return Options;
   }
 };

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7593554d896d..c66d5eb6069e 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -192,6 +192,11 @@ New check aliases
   :doc:`bugprone-signed-char-misuse
   ` was added.
 
+- New alias :doc:`llvm-else-after-return
+  ` to
+  :doc:`readability-else-after-return
+  ` was added.
+
 Changes in existing checks
 ^^
 

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index baa142e28e7f..7356c585d20c 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -423,4 +423,5 @@ Clang-Tidy Checks
`hicpp-use-nullptr `_, `modernize-use-nullptr 
`_, "Yes"
`hicpp-use-override `_, `modernize-use-override 
`_, "Yes"
`hicpp-vararg `_, `cppcoreguidelines-pro-type-vararg 
`_,
+   `llvm-else-after-return `_, 
`readability-else-after-return `_, "Yes"
`llvm-qualified-auto `_, 
`readability-qualified-auto `_, "Yes"

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/llvm-else-after-return.rst 
b/clang-tools-extra/docs/clang-tidy/checks/llvm-else-after-return.rst
new file mode 100644
index ..f9af610fe50d
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/llvm-else-after-return.rst
@@ -0,0 +1,11 @@
+.. title:: clang-tidy - llvm-else-after-return
+.. meta::
+   :http-equiv=refresh: 5;URL=readability-else-after-return.html
+
+llvm-else-after-return
+==
+
+The llvm-else-after-return check is an alias, please see
+`readability-else-after-return `_
+for more information.
+

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/readability-else-after-return.rst 
b/clang-tools-extra/docs/clang-tidy/checks/readability-else-after-return.rst
index fccb01d0e6b2..4adcd7bbfa26 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/readability-else-after-return.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/readability-else-after-return.rst
@@ -77,3 +77,13 @@ Options
the ``if`` statement is the last statement in its parents scope.
Default value is `true`.
 
+
+LLVM alias
+--
+
+There is an alias of this check called llvm-else-after-return.
+In that version the options :option:`WarnOnUnfixable` and 
+:option:`WarnOnConditionVariables` are both set to `false` by default.
+
+This check helps to enforce this `LLVM Coding Standards recommendation
+`_.



_

[clang-tools-extra] 0196600 - [clang-tidy] Fix incorrect default option in fc3c693b61

2020-07-06 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-06T14:44:03+01:00
New Revision: 01966003674d49e06632495fec2a5a7b3fd58a80

URL: 
https://github.com/llvm/llvm-project/commit/01966003674d49e06632495fec2a5a7b3fd58a80
DIFF: 
https://github.com/llvm/llvm-project/commit/01966003674d49e06632495fec2a5a7b3fd58a80.diff

LOG: [clang-tidy] Fix incorrect default option in fc3c693b61

Added: 


Modified: 
clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp 
b/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
index 0310a8e07a2d..bf871e21f501 100644
--- a/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
@@ -44,7 +44,7 @@ class LLVMModule : public ClangTidyModule {
 ClangTidyOptions Options;
 Options.CheckOptions["llvm-qualified-auto.AddConstToQualified"] = "0";
 Options.CheckOptions["llvm-else-after-return.WarnOnUnfixable"] = "0";
-Options.CheckOptions["llvm-else-after-return.RefactorConditionVariables"] =
+Options.CheckOptions["llvm-else-after-return.WarnOnConditionVariables"] =
 "0";
 return Options;
   }



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


[clang] 41bbb87 - [NFC] Use hasAnyName matcher in place of anyOf(hasName()...)

2020-07-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-07T14:31:04+01:00
New Revision: 41bbb875e4da392ae37300d3a6282b6595f14503

URL: 
https://github.com/llvm/llvm-project/commit/41bbb875e4da392ae37300d3a6282b6595f14503
DIFF: 
https://github.com/llvm/llvm-project/commit/41bbb875e4da392ae37300d3a6282b6595f14503.diff

LOG: [NFC] Use hasAnyName matcher in place of anyOf(hasName()...)

Added: 


Modified: 
clang-tools-extra/clang-move/Move.cpp

clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp

clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp
clang-tools-extra/clang-tidy/cert/CommandProcessorCheck.cpp
clang-tools-extra/clang-tidy/cert/DontModifyStdNamespaceCheck.cpp
clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp
clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp

clang/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-move/Move.cpp 
b/clang-tools-extra/clang-move/Move.cpp
index 28184a0dce0c..3f09f68a8046 100644
--- a/clang-tools-extra/clang-move/Move.cpp
+++ b/clang-tools-extra/clang-move/Move.cpp
@@ -552,20 +552,22 @@ void 
ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
 
   // Match static functions/variable definitions which are defined in named
   // namespaces.
-  Optional> HasAnySymbolNames;
+  SmallVector QualNames;
+  QualNames.reserve(Context->Spec.Names.size());
   for (StringRef SymbolName : Context->Spec.Names) {
-llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
-const auto HasName = hasName(("::" + GlobalSymbolName).str());
-HasAnySymbolNames =
-HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
+QualNames.push_back(("::" + SymbolName.trim().ltrim(':')).str());
   }
 
-  if (!HasAnySymbolNames) {
+  if (QualNames.empty()) {
 llvm::errs() << "No symbols being moved.\n";
 return;
   }
+
+  ast_matchers::internal::Matcher HasAnySymbolNames =
+  hasAnyName(SmallVector(QualNames.begin(), 
QualNames.end()));
+
   auto InMovedClass =
-  hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
+  hasOutermostEnclosingClass(cxxRecordDecl(HasAnySymbolNames));
 
   // Matchers for helper declarations in old.cc.
   auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
@@ -612,17 +614,17 @@ void 
ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
   // Create a MatchCallback for class declarations.
   MatchCallbacks.push_back(std::make_unique(this));
   // Match moved class declarations.
-  auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
-  isDefinition(), TopLevelDecl)
-.bind("moved_class");
+  auto MovedClass =
+  cxxRecordDecl(InOldFiles, HasAnySymbolNames, isDefinition(), 
TopLevelDecl)
+  .bind("moved_class");
   Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
   // Match moved class methods (static methods included) which are defined
   // outside moved class declaration.
-  Finder->addMatcher(
-  cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
-isDefinition())
-  .bind("class_method"),
-  MatchCallbacks.back().get());
+  Finder->addMatcher(cxxMethodDecl(InOldFiles,
+   
ofOutermostEnclosingClass(HasAnySymbolNames),
+   isDefinition())
+ .bind("class_method"),
+ MatchCallbacks.back().get());
   // Match static member variable definition of the moved class.
   Finder->addMatcher(
   varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
@@ -630,20 +632,20 @@ void 
ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
   MatchCallbacks.back().get());
 
   MatchCallbacks.push_back(std::make_unique(this));
-  Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
+  Finder->addMatcher(functionDecl(InOldFiles, HasAnySymbolNames, TopLevelDecl)
  .bind("function"),
  MatchCallbacks.back().get());
 
   MatchCallbacks.push_back(std::make_unique(this));
   Finder->addMatcher(
-  varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
+  varDecl(InOldFiles, HasAnySymbolNames, TopLevelDecl).bind("var"),
   MatchCallbacks.back().get());
 
   // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
   // will not be moved for now no matter whether they are used or not.
   MatchCallbacks.push_back(std::make_unique(this));
   Finder->addMatcher(
-  enumDecl(InOldHead

[clang] b0d3ea1 - [ASTMatchers] Added hasDirectBase Matcher

2020-07-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-07T16:05:11+01:00
New Revision: b0d3ea171bd56b3b079be9213935925e1499df15

URL: 
https://github.com/llvm/llvm-project/commit/b0d3ea171bd56b3b079be9213935925e1499df15
DIFF: 
https://github.com/llvm/llvm-project/commit/b0d3ea171bd56b3b079be9213935925e1499df15.diff

LOG: [ASTMatchers] Added hasDirectBase Matcher

Adds a matcher called `hasDirectBase` for matching the `CXXBaseSpecifier` of a 
class that directly derives from another class.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D81552

Added: 


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

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 9c04322f0ae6..2256cbf71869 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -5658,7 +5658,7 @@ AST Traversal Matchers
 Matches C++ classes that 
have a direct or indirect base matching BaseSpecMatcher.
 
 Example:
-matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase")
+matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"
   class Foo;
   class Bar : Foo {};
   class Baz : Bar {};
@@ -5670,6 +5670,20 @@ AST Traversal Matchers
 
 
 
+MatcherCXXRecordDecl>hasDirectBaseMatcherCXXBaseSpecifier>
 BaseSpecMatcher
+Matches C++ classes 
that have a direct base matching BaseSpecMatcher.
+
+Example:
+matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"
+  class Foo;
+  class Bar : Foo {};
+  class Baz : Bar {};
+  class SpecialBase;
+  class Proxy : SpecialBase {};  // matches Proxy
+  class IndirectlyDerived : Proxy {};  // doesn't match
+
+
+
 MatcherCXXRecordDecl>hasMethodMatcherCXXMethodDecl>
 InnerMatcher
 Matches the first method 
of a class or struct that satisfies InnerMatcher.
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 153b51753085..f16fb876cdd3 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2862,7 +2862,7 @@ AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
 /// BaseSpecMatcher.
 ///
 /// Example:
-/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase")
+/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"
 /// \code
 ///   class Foo;
 ///   class Bar : Foo {};
@@ -2878,6 +2878,26 @@ AST_MATCHER_P(CXXRecordDecl, hasAnyBase, 
internal::Matcher,
   return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
 }
 
+/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
+///
+/// Example:
+/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"
+/// \code
+///   class Foo;
+///   class Bar : Foo {};
+///   class Baz : Bar {};
+///   class SpecialBase;
+///   class Proxy : SpecialBase {};  // matches Proxy
+///   class IndirectlyDerived : Proxy {};  // doesn't match
+/// \endcode
+AST_MATCHER_P(CXXRecordDecl, hasDirectBase, 
internal::Matcher,
+  BaseSpecMatcher) {
+  return Node.hasDefinition() &&
+ llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
+   return BaseSpecMatcher.matches(Base, Finder, Builder);
+ });
+}
+
 /// Similar to \c isDerivedFrom(), but also matches classes that directly
 /// match \c Base.
 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index f01c68a518d9..a0a65092a92b 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -278,6 +278,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(hasDefinition);
   REGISTER_MATCHER(hasDescendant);
   REGISTER_MATCHER(hasDestinationType);
+  REGISTER_MATCHER(hasDirectBase);
   REGISTER_MATCHER(hasDynamicExceptionSpec);
   REGISTER_MATCHER(hasEitherOperand);
   REGISTER_MATCHER(hasElementType);

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index fa7f75b58b4e..aeb4fd098d22 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -3125,5 +3125,44 @@ TEST(IsVirtual, NoVirtualBase) {
  cxxRecordDecl(hasAnyBase(isVirtual();
 }
 
+TEST(BaseSpecifier, hasDirectBase) {
+  EXPECT_TRUE(matches(
+  R"cc(
+class Base {};
+clas

[clang-tools-extra] 6a3b10e - [change-namespace][NFC] Clean up joinNamespaces

2020-07-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-09T11:29:49+01:00
New Revision: 6a3b10e294feceb94064f32450de5c068a13dd03

URL: 
https://github.com/llvm/llvm-project/commit/6a3b10e294feceb94064f32450de5c068a13dd03
DIFF: 
https://github.com/llvm/llvm-project/commit/6a3b10e294feceb94064f32450de5c068a13dd03.diff

LOG: [change-namespace][NFC] Clean up joinNamespaces

Added: 


Modified: 
clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp 
b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
index e2a70db4102b..61ae7c4cc703 100644
--- a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
+++ b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
@@ -19,14 +19,8 @@ namespace change_namespace {
 
 namespace {
 
-inline std::string
-joinNamespaces(const llvm::SmallVectorImpl &Namespaces) {
-  if (Namespaces.empty())
-return "";
-  std::string Result(Namespaces.front());
-  for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
-Result += ("::" + *I).str();
-  return Result;
+inline std::string joinNamespaces(ArrayRef Namespaces) {
+  return llvm::join(Namespaces, "::");
 }
 
 // Given "a::b::c", returns {"a", "b", "c"}.



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


[clang-tools-extra] a25487f - [clang-tidy] Use Options priority in enum options where it was missing

2020-07-10 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-10T12:27:08+01:00
New Revision: a25487fd8cb91f99cfc1db1d4159184ac2a816a9

URL: 
https://github.com/llvm/llvm-project/commit/a25487fd8cb91f99cfc1db1d4159184ac2a816a9
DIFF: 
https://github.com/llvm/llvm-project/commit/a25487fd8cb91f99cfc1db1d4159184ac2a816a9.diff

LOG: [clang-tidy] Use Options priority in enum options where it was missing

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 7ddf054a21a9..780a3569afdb 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -76,16 +76,25 @@ ClangTidyCheck::OptionsView::get(StringRef LocalName) const 
{
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
+static ClangTidyOptions::OptionMap::const_iterator
+findPriorityOption(const ClangTidyOptions::OptionMap &Options, StringRef 
NamePrefix,
+  StringRef LocalName) {
+  auto IterLocal = Options.find((NamePrefix + LocalName).str());
+  auto IterGlobal = Options.find(LocalName.str());
+  if (IterLocal == Options.end())
+return IterGlobal;
+  if (IterGlobal == Options.end())
+return IterLocal;
+  if (IterLocal->second.Priority >= IterGlobal->second.Priority)
+return IterLocal;
+  return IterGlobal;
+}
+
 llvm::Expected
 ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
-  auto IterLocal = CheckOptions.find(NamePrefix + LocalName.str());
-  auto IterGlobal = CheckOptions.find(LocalName.str());
-  if (IterLocal != CheckOptions.end() &&
-  (IterGlobal == CheckOptions.end() ||
-   IterLocal->second.Priority >= IterGlobal->second.Priority))
-return IterLocal->second.Value;
-  if (IterGlobal != CheckOptions.end())
-return IterGlobal->second.Value;
+  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName);
+  if (Iter != CheckOptions.end())
+return Iter->second.Value;
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
@@ -124,14 +133,9 @@ bool ClangTidyCheck::OptionsView::get(StringRef 
LocalName,
 template <>
 llvm::Expected
 ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const 
{
-  auto IterLocal = CheckOptions.find(NamePrefix + LocalName.str());
-  auto IterGlobal = CheckOptions.find(LocalName.str());
-  if (IterLocal != CheckOptions.end() &&
-  (IterGlobal == CheckOptions.end() ||
-   IterLocal->second.Priority >= IterGlobal->second.Priority))
-return getAsBool(IterLocal->second.Value, NamePrefix + LocalName);
-  if (IterGlobal != CheckOptions.end())
-return getAsBool(IterGlobal->second.Value, llvm::Twine(LocalName));
+  auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName);
+  if (Iter != CheckOptions.end())
+return getAsBool(Iter->second.Value, Iter->first);
   return llvm::make_error((NamePrefix + LocalName).str());
 }
 
@@ -160,9 +164,8 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
 llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
 StringRef LocalName, ArrayRef> Mapping,
 bool CheckGlobal, bool IgnoreCase) {
-  auto Iter = CheckOptions.find((NamePrefix + LocalName).str());
-  if (CheckGlobal && Iter == CheckOptions.end())
-Iter = CheckOptions.find(LocalName.str());
+  auto Iter = CheckGlobal ? findPriorityOption(CheckOptions, NamePrefix, 
LocalName)
+  : CheckOptions.find((NamePrefix + LocalName).str());
   if (Iter == CheckOptions.end())
 return llvm::make_error((NamePrefix + 
LocalName).str());
 



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


[clang-tools-extra] c3bdc98 - [clang-tidy] Reworked enum options handling(again)

2020-07-11 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-11T10:13:20+01:00
New Revision: c3bdc9814d947946bf8e1062f6bf41b7f8813f80

URL: 
https://github.com/llvm/llvm-project/commit/c3bdc9814d947946bf8e1062f6bf41b7f8813f80
DIFF: 
https://github.com/llvm/llvm-project/commit/c3bdc9814d947946bf8e1062f6bf41b7f8813f80.diff

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

Reland b9306fd after fixing the issue causing mac builds to fail unittests.

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.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82188

Added: 


Modified: 
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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 780a3569afdb..e149978bcdea 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -161,11 +161,13 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
   store(Options, LocalName, llvm::itostr(Value));
 }
 
-llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
-StringRef LocalName, ArrayRef> Mapping,
-bool CheckGlobal, bool IgnoreCase) {
-  auto Iter = CheckGlobal ? findPriorityOption(CheckOptions, NamePrefix, 
LocalName)
-  : CheckOptions.find((NamePrefix + LocalName).str());
+llvm::Expected
+ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
+ArrayRef Mapping,
+bool CheckGlobal, bool IgnoreCase) {
+  auto Iter = CheckGlobal
+  ? findPriorityOption(CheckOptions, NamePrefix, LocalName)
+  : CheckOptions.find((NamePrefix + LocalName).str());
   if (Iter == CheckOptions.end())
 return llvm::make_error((NamePrefix + 
LocalName).str());
 
@@ -174,19 +176,19 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   unsigned EditDistance = -1;
   for (const auto &NameAndEnum : Mapping) {
 if (IgnoreCase) {
-  if (Value.equals_lower(NameAndEnum.first))
-return NameAndEnum.second;
-} else if (Value.equals(NameAndEnum.first)) {
-  return NameAndEnum.second;
-} else if (Value.equals_lower(NameAndEnum.first)) {
-  Closest = NameAndEnum.first;
+  if (Value.equals_lower(NameAndEnum.second))
+return NameAndEnum.first;
+} else if (Value.equals(NameAndEnum.second)) {
+  return NameAndEnum.first;
+} else if (Value.equals_lower(NameAndEnum.second)) {
+  Closest = NameAndEnum.second;
   EditDistance = 0;
   continue;
 }
-unsigned Distance = Value.edit_distance(NameAndEnum.first);
+unsigned Distance = Value.edit_distance(NameAndEnum.second);
 if (Distance < EditDistance) {
   EditDistance = Distance;
-  Closest = NameAndEnum.first;
+  Closest = NameAndEnum.second;
 }
   }
   if (EditDistance < 3)

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index dfe01a8aaa30..3c625ee0cb79 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -26,6 +26,13 @@ class SourceManager;
 
 namespace tidy {
 
+/// This class should be specialized by any enum type that needs to be 
converted
+/// to and from an \ref llvm::StringRef.
+template  struct OptionEnumMapping {
+  // Specializations of this struct must implement this function.
+  static Arra

[clang-tools-extra] fcf0f75 - [clang-tidy] OptionsView::store specialized on bool

2020-07-14 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-14T22:19:37+01:00
New Revision: fcf0f75a59fb565e57d71c29f3e820828301c7e2

URL: 
https://github.com/llvm/llvm-project/commit/fcf0f75a59fb565e57d71c29f3e820828301c7e2
DIFF: 
https://github.com/llvm/llvm-project/commit/fcf0f75a59fb565e57d71c29f3e820828301c7e2.diff

LOG: [clang-tidy] OptionsView::store specialized on bool

Following on fcf7cc268fe and 672207c319a which granted checks the ability to 
read boolean configuration arguments as `true` or `false`.
This enables storing the options back to the configuration file using `true` 
and `false`.
This is in line with how clang-format dumps boolean options in its style config.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D83053

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
clang-tools-extra/clang-tidy/ClangTidyCheck.h
clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index e149978bcdea..c24b8553999c 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -155,12 +155,19 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
   Options[NamePrefix + LocalName.str()] = Value;
 }
 
-void ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
-StringRef LocalName,
-int64_t Value) const {
+void ClangTidyCheck::OptionsView::storeInt(ClangTidyOptions::OptionMap 
&Options,
+   StringRef LocalName,
+   int64_t Value) const {
   store(Options, LocalName, llvm::itostr(Value));
 }
 
+template <>
+void ClangTidyCheck::OptionsView::store(
+ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+bool Value) const {
+  store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
+}
+
 llvm::Expected
 ClangTidyCheck::OptionsView::getEnumInt(StringRef LocalName,
 ArrayRef Mapping,

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 3c625ee0cb79..54b725126752 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -405,9 +405,13 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
StringRef Value) const;
 
 /// Stores an option with the check-local name \p LocalName with
-/// ``int64_t`` value \p Value to \p Options.
-void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
-   int64_t Value) const;
+/// integer value \p Value to \p Options.
+template 
+std::enable_if_t::value>
+store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+  T Value) const {
+  storeInt(Options, LocalName, Value);
+}
 
 /// Stores an option with the check-local name \p LocalName as the string
 /// representation of the Enum \p Value to \p Options.
@@ -448,6 +452,9 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   return Result;
 }
 
+void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+  int64_t Value) const;
+
 static void logErrToStdErr(llvm::Error &&Err);
 
 std::string NamePrefix;
@@ -509,6 +516,13 @@ template <>
 bool ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName,
  bool Default) const;
 
+/// Stores an option with the check-local name \p LocalName with
+/// bool value \p Value to \p Options.
+template <>
+void ClangTidyCheck::OptionsView::store(
+ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+bool Value) const;
+
 } // namespace tidy
 } // namespace clang
 

diff  --git a/clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp 
b/clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
index ee1ed49472ba..d2a0a8c2a150 100644
--- a/clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ b/clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -18,13 +18,13 @@
 // 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: 'true'
 // CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
 // CHECK-CHILD4-NEXT: value: '20'
 // CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
 // CHECK-CHILD4-NEXT: v

[clang-tools-extra] 850bb88 - [clang-tidy] RenamerClangTidy group redecls into 1 warning.

2020-06-18 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-18T15:50:16+01:00
New Revision: 850bb889a56ccf3252792c6d3db59542e94753ae

URL: 
https://github.com/llvm/llvm-project/commit/850bb889a56ccf3252792c6d3db59542e94753ae
DIFF: 
https://github.com/llvm/llvm-project/commit/850bb889a56ccf3252792c6d3db59542e94753ae.diff

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

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.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82059

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 03bece233240..e90ab1782b4b 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -168,7 +168,7 @@ void RenamerClangTidyCheck::addUsage(
 
 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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 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()) {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
index 1bb435e02eb5..3a3bfecc01fc 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -214,17 +214,16 @@ class my_class {
 // 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  struct a {
 
 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 @@ void QualifiedTypeLocTest(const THIS___Structure &);
 // 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();

[clang-tools-extra] d9b8aad - [clang-tidy] Add --use-color command line option and UseColor option to control colors in diagnostics

2020-06-18 Thread Nathan James via cfe-commits

Author: hyd-dev
Date: 2020-06-18T16:16:14+01:00
New Revision: d9b8aada8288ca4aff4a1d70bf5eb4d579c79036

URL: 
https://github.com/llvm/llvm-project/commit/d9b8aada8288ca4aff4a1d70bf5eb4d579c79036
DIFF: 
https://github.com/llvm/llvm-project/commit/d9b8aada8288ca4aff4a1d70bf5eb4d579c79036.diff

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

This patch adds `--use-color` command line option and `UseColor` option to 
clang-tidy to control colors in diagnostics. With these options, users can 
force colorful output. This is useful when using clang-tidy with 
parallelization command line tools (like ninja and GNU parallel), as they often 
pipe clang-tidy's standard output and make the colors disappear.

Reviewed By: njames93

Differential Revision: https://reviews.llvm.org/D79477

Added: 
clang-tools-extra/test/clang-tidy/infrastructure/use-color.cpp

Modified: 
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/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index 367fa3dda5cf..d9b4b01e7161 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -106,7 +106,8 @@ class ErrorReporter {
   DiagPrinter),
 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes),
 TotalFixes(0), AppliedFixes(0), WarningsAsErrors(0) {
-DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
+DiagOpts->ShowColors = Context.getOptions().UseColor.getValueOr(
+llvm::sys::Process::StandardOutHasColors());
 DiagPrinter->BeginSourceFile(LangOpts);
   }
 

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 74d528e08642..bf146385e4ff 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -96,6 +96,7 @@ template <> struct MappingTraits {
 IO.mapOptional("ExtraArgs", Options.ExtraArgs);
 IO.mapOptional("ExtraArgsBefore", Options.ExtraArgsBefore);
 IO.mapOptional("InheritParentConfig", Options.InheritParentConfig);
+IO.mapOptional("UseColor", Options.UseColor);
   }
 };
 
@@ -154,6 +155,7 @@ ClangTidyOptions ClangTidyOptions::mergeWith(const 
ClangTidyOptions &Other,
   overrideValue(Result.SystemHeaders, Other.SystemHeaders);
   overrideValue(Result.FormatStyle, Other.FormatStyle);
   overrideValue(Result.User, Other.User);
+  overrideValue(Result.UseColor, Other.UseColor);
   mergeVectors(Result.ExtraArgs, Other.ExtraArgs);
   mergeVectors(Result.ExtraArgsBefore, Other.ExtraArgsBefore);
 

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.h 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
index cd5a8a15a96e..3eb2fa607cbf 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.h
@@ -126,6 +126,9 @@ struct ClangTidyOptions {
   /// apply this config file on top of the parent one. 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.
+  llvm::Optional UseColor;
 };
 
 /// Abstract interface for retrieving various ClangTidy options.

diff  --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index 7f668345bbb1..cb1352a7edff 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -230,6 +230,15 @@ over the real file system.
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 @@ static std::unique_ptr 
createOptionsProvider(
 OverrideOptions.SystemHeaders = SystemHeaders;
   if (FormatStyle.getNumOccurrences() > 0)
 OverrideOptions.FormatStyle = FormatStyle;
+  if (UseColor.getNumOccurrences() > 0)
+OverrideOptions.UseColor = UseColor;
 
   if (!Config.empty()) {
 if (llvm::ErrorOr ParsedConfig =

diff  --git a/clang-tools-extra/test/clang-tidy/infrastructure/use-color.cpp 
b/clang-tools-extra/test/clang-tidy/infrastructure/use-color.

[clang-tools-extra] 8b0df1c - [NFC] Refactor Registry loops to range for

2020-06-18 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-19T00:40:10+01:00
New Revision: 8b0df1c1a992d203212901c1139665261e0bbc1c

URL: 
https://github.com/llvm/llvm-project/commit/8b0df1c1a992d203212901c1139665261e0bbc1c
DIFF: 
https://github.com/llvm/llvm-project/commit/8b0df1c1a992d203212901c1139665261e0bbc1c.diff

LOG: [NFC] Refactor Registry loops to range for

Added: 


Modified: 
clang-tools-extra/clang-doc/Generators.cpp
clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
clang-tools-extra/clangd/URI.cpp
clang/lib/Frontend/FrontendAction.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
clang/lib/Lex/Pragma.cpp
clang/lib/Tooling/CompilationDatabase.cpp
clang/lib/Tooling/Execution.cpp
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-doc/Generators.cpp 
b/clang-tools-extra/clang-doc/Generators.cpp
index 3b7dcf93411a..591d43322342 100644
--- a/clang-tools-extra/clang-doc/Generators.cpp
+++ b/clang-tools-extra/clang-doc/Generators.cpp
@@ -15,11 +15,10 @@ namespace doc {
 
 llvm::Expected>
 findGeneratorByName(llvm::StringRef Format) {
-  for (auto I = GeneratorRegistry::begin(), E = GeneratorRegistry::end();
-   I != E; ++I) {
-if (I->getName() != Format)
+  for (const auto &Generator : GeneratorRegistry::entries()) {
+if (Generator.getName() != Format)
   continue;
-return I->instantiate();
+return Generator.instantiate();
   }
   return createStringError(llvm::inconvertibleErrorCode(),
"can't find generator: " + Format);

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index bf146385e4ff..76cb663c8e2e 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -115,11 +115,10 @@ ClangTidyOptions ClangTidyOptions::getDefaults() {
   Options.FormatStyle = "none";
   Options.User = llvm::None;
   unsigned Priority = 0;
-  for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
- E = ClangTidyModuleRegistry::end();
-   I != E; ++I)
+  for (const ClangTidyModuleRegistry::entry &Module :
+   ClangTidyModuleRegistry::entries())
 Options =
-Options.mergeWith(I->instantiate()->getModuleOptions(), ++Priority);
+Options.mergeWith(Module.instantiate()->getModuleOptions(), 
++Priority);
   return Options;
 }
 

diff  --git a/clang-tools-extra/clangd/URI.cpp 
b/clang-tools-extra/clangd/URI.cpp
index 1a125e73a0ca..2061a5601c58 100644
--- a/clang-tools-extra/clangd/URI.cpp
+++ b/clang-tools-extra/clangd/URI.cpp
@@ -63,11 +63,10 @@ findSchemeByName(llvm::StringRef Scheme) {
   if (Scheme == "file")
 return std::make_unique();
 
-  for (auto I = URISchemeRegistry::begin(), E = URISchemeRegistry::end();
-   I != E; ++I) {
-if (I->getName() != Scheme)
+  for (const auto &URIScheme : URISchemeRegistry::entries()) {
+if (URIScheme.getName() != Scheme)
   continue;
-return I->instantiate();
+return URIScheme.instantiate();
   }
   return make_string_error("Can't find scheme: " + Scheme);
 }

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index dc361b2fdd24..59a968b5c709 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -157,10 +157,9 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
   bool FoundAllPlugins = true;
   for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
 bool Found = false;
-for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
-  ie = FrontendPluginRegistry::end();
- it != ie; ++it) {
-  if (it->getName() == Arg)
+for (const FrontendPluginRegistry::entry &Plugin :
+ FrontendPluginRegistry::entries()) {
+  if (Plugin.getName() == Arg)
 Found = true;
 }
 if (!Found) {
@@ -183,26 +182,24 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
   // or after it (in AfterConsumers)
   std::vector> Consumers;
   std::vector> AfterConsumers;
-  for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
-ie = FrontendPluginRegistry::end();
-   it != ie; ++it) {
-std::unique_ptr P = it->instantiate();
+  for (const FrontendPluginRegistry::entry &Plugin :
+   FrontendPluginRegistry::entries()) {
+std::unique_ptr P = Plugin.instantiate();
 PluginASTAction::ActionType ActionType = P->getActionType();
 if (ActionType == PluginASTAction::Cmdline) {
   // This is O(|plugins| * |add_plugins|), but since both numbers are
   // way below 50 in practice, that's ok.
-  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
- 

[clang] 8b0df1c - [NFC] Refactor Registry loops to range for

2020-06-18 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-19T00:40:10+01:00
New Revision: 8b0df1c1a992d203212901c1139665261e0bbc1c

URL: 
https://github.com/llvm/llvm-project/commit/8b0df1c1a992d203212901c1139665261e0bbc1c
DIFF: 
https://github.com/llvm/llvm-project/commit/8b0df1c1a992d203212901c1139665261e0bbc1c.diff

LOG: [NFC] Refactor Registry loops to range for

Added: 


Modified: 
clang-tools-extra/clang-doc/Generators.cpp
clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
clang-tools-extra/clangd/URI.cpp
clang/lib/Frontend/FrontendAction.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
clang/lib/Lex/Pragma.cpp
clang/lib/Tooling/CompilationDatabase.cpp
clang/lib/Tooling/Execution.cpp
llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-doc/Generators.cpp 
b/clang-tools-extra/clang-doc/Generators.cpp
index 3b7dcf93411a..591d43322342 100644
--- a/clang-tools-extra/clang-doc/Generators.cpp
+++ b/clang-tools-extra/clang-doc/Generators.cpp
@@ -15,11 +15,10 @@ namespace doc {
 
 llvm::Expected>
 findGeneratorByName(llvm::StringRef Format) {
-  for (auto I = GeneratorRegistry::begin(), E = GeneratorRegistry::end();
-   I != E; ++I) {
-if (I->getName() != Format)
+  for (const auto &Generator : GeneratorRegistry::entries()) {
+if (Generator.getName() != Format)
   continue;
-return I->instantiate();
+return Generator.instantiate();
   }
   return createStringError(llvm::inconvertibleErrorCode(),
"can't find generator: " + Format);

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index bf146385e4ff..76cb663c8e2e 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -115,11 +115,10 @@ ClangTidyOptions ClangTidyOptions::getDefaults() {
   Options.FormatStyle = "none";
   Options.User = llvm::None;
   unsigned Priority = 0;
-  for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
- E = ClangTidyModuleRegistry::end();
-   I != E; ++I)
+  for (const ClangTidyModuleRegistry::entry &Module :
+   ClangTidyModuleRegistry::entries())
 Options =
-Options.mergeWith(I->instantiate()->getModuleOptions(), ++Priority);
+Options.mergeWith(Module.instantiate()->getModuleOptions(), 
++Priority);
   return Options;
 }
 

diff  --git a/clang-tools-extra/clangd/URI.cpp 
b/clang-tools-extra/clangd/URI.cpp
index 1a125e73a0ca..2061a5601c58 100644
--- a/clang-tools-extra/clangd/URI.cpp
+++ b/clang-tools-extra/clangd/URI.cpp
@@ -63,11 +63,10 @@ findSchemeByName(llvm::StringRef Scheme) {
   if (Scheme == "file")
 return std::make_unique();
 
-  for (auto I = URISchemeRegistry::begin(), E = URISchemeRegistry::end();
-   I != E; ++I) {
-if (I->getName() != Scheme)
+  for (const auto &URIScheme : URISchemeRegistry::entries()) {
+if (URIScheme.getName() != Scheme)
   continue;
-return I->instantiate();
+return URIScheme.instantiate();
   }
   return make_string_error("Can't find scheme: " + Scheme);
 }

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index dc361b2fdd24..59a968b5c709 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -157,10 +157,9 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
   bool FoundAllPlugins = true;
   for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
 bool Found = false;
-for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
-  ie = FrontendPluginRegistry::end();
- it != ie; ++it) {
-  if (it->getName() == Arg)
+for (const FrontendPluginRegistry::entry &Plugin :
+ FrontendPluginRegistry::entries()) {
+  if (Plugin.getName() == Arg)
 Found = true;
 }
 if (!Found) {
@@ -183,26 +182,24 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
   // or after it (in AfterConsumers)
   std::vector> Consumers;
   std::vector> AfterConsumers;
-  for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
-ie = FrontendPluginRegistry::end();
-   it != ie; ++it) {
-std::unique_ptr P = it->instantiate();
+  for (const FrontendPluginRegistry::entry &Plugin :
+   FrontendPluginRegistry::entries()) {
+std::unique_ptr P = Plugin.instantiate();
 PluginASTAction::ActionType ActionType = P->getActionType();
 if (ActionType == PluginASTAction::Cmdline) {
   // This is O(|plugins| * |add_plugins|), but since both numbers are
   // way below 50 in practice, that's ok.
-  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
- 

[clang-tools-extra] 4836188 - [clang-tidy] Extend InheritParentConfig to CommandLineConfig

2020-06-19 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-19T12:02:19+01:00
New Revision: 4836188ad9b3334b0c1e055d45ccaa54ed797e4b

URL: 
https://github.com/llvm/llvm-project/commit/4836188ad9b3334b0c1e055d45ccaa54ed797e4b
DIFF: 
https://github.com/llvm/llvm-project/commit/4836188ad9b3334b0c1e055d45ccaa54ed797e4b.diff

LOG: [clang-tidy] Extend InheritParentConfig to CommandLineConfig

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.

Reviewed By: DmitryPolukhin

Differential Revision: https://reviews.llvm.org/D81949

Added: 


Modified: 
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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
index 76cb663c8e2e..4fa78e2803f1 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -194,14 +194,27 @@ ConfigOptionsProvider::ConfigOptionsProvider(
 const ClangTidyGlobalOptions &GlobalOptions,
 const ClangTidyOptions &DefaultOptions,
 const ClangTidyOptions &ConfigOptions,
-const ClangTidyOptions &OverrideOptions)
-: DefaultOptionsProvider(GlobalOptions, DefaultOptions),
-  ConfigOptions(ConfigOptions), OverrideOptions(OverrideOptions) {}
+const ClangTidyOptions &OverrideOptions,
+llvm::IntrusiveRefCntPtr FS)
+: FileOptionsBaseProvider(GlobalOptions, DefaultOptions, OverrideOptions,
+  FS),
+  ConfigOptions(ConfigOptions) {}
 
 std::vector
 ConfigOptionsProvider::getRawOptions(llvm::StringRef FileName) {
   std::vector RawOptions =
   DefaultOptionsProvider::getRawOptions(FileName);
+  if (ConfigOptions.InheritParentConfig.getValueOr(false)) {
+LLVM_DEBUG(llvm::dbgs()
+   << "Getting options for file " << FileName << "...\n");
+assert(FS && "FS must be set.");
+
+llvm::SmallString<128> AbsoluteFilePath(FileName);
+
+if (!FS->makeAbsolute(AbsoluteFilePath)) {
+  addRawFileOptions(AbsoluteFilePath, RawOptions);
+}
+  }
   RawOptions.emplace_back(ConfigOptions,
   OptionsSourceTypeConfigCommandLineOption);
   RawOptions.emplace_back(OverrideOptions,
@@ -209,7 +222,7 @@ ConfigOptionsProvider::getRawOptions(llvm::StringRef 
FileName) {
   return RawOptions;
 }
 
-FileOptionsProvider::FileOptionsProvider(
+FileOptionsBaseProvider::FileOptionsBaseProvider(
 const ClangTidyGlobalOptions &GlobalOptions,
 const ClangTidyOptions &DefaultOptions,
 const ClangTidyOptions &OverrideOptions,
@@ -221,36 +234,21 @@ FileOptionsProvider::FileOptionsProvider(
   ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration);
 }
 
-FileOptionsProvider::FileOptionsProvider(
+FileOptionsBaseProvider::FileOptionsBaseProvider(
 const ClangTidyGlobalOptions &GlobalOptions,
 const ClangTidyOptions &DefaultOptions,
 const ClangTidyOptions &OverrideOptions,
-const FileOptionsProvider::ConfigFileHandlers &ConfigHandlers)
+const FileOptionsBaseProvider::ConfigFileHandlers &ConfigHandlers)
 : DefaultOptionsProvider(GlobalOptions, DefaultOptions),
   OverrideOptions(OverrideOptions), ConfigHandlers(ConfigHandlers) {}
 
-// FIXME: This method has some common logic with clang::format::getStyle().
-// Consider pulling out common bits to a findParentFileWithName function or
-// similar.
-std::vector
-FileOptionsProvider::getRawOptions(StringRef FileName) {
-  LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName
-  << "...\n");
-  assert(FS && "FS must be set.");
-
-  llvm::SmallString<128> AbsoluteFilePath(FileName);
+void FileOptionsBaseProvider::addRawFileOptions(
+llvm::StringRef AbsolutePath, std::vector &CurOptions) {
+  auto CurSize = CurOptions.size();
 
-  if (FS->makeAbsolute(AbsoluteFilePath))
-return {};
-
-  std::vector RawOptions =
-  DefaultOptionsProvider::getRawOptions(AbsoluteFilePath.str());
-  OptionsSource CommandLineOptions(OverrideOptions,
-   OptionsSourceTypeCheckCommandLineOption);
-  size_t FirstFileConfig = RawOptions.size();
   // Look for a suitable configuration file in all parent directories of the
   // file. Start with the immediate parent directory and move up.
-  StringRef Path = llvm::sys::path::parent_path(AbsoluteFilePath.str());
+  StringRef Path = llvm::sys::path::parent_path(A

[clang-tools-extra] c3b4486 - [NFC] Simplify IncludeInsertions appending to diagnostics

2020-06-19 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-19T13:22:49+01:00
New Revision: c3b4486a57f6105bd5d96ec2e736f567aa4a0e35

URL: 
https://github.com/llvm/llvm-project/commit/c3b4486a57f6105bd5d96ec2e736f567aa4a0e35
DIFF: 
https://github.com/llvm/llvm-project/commit/c3b4486a57f6105bd5d96ec2e736f567aa4a0e35.diff

LOG: [NFC] Simplify IncludeInsertions appending to diagnostics

Added: 


Modified: 
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/TypePromotionInMathFnCheck.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
index 633f3781f4d8..ed1a1a26bb62 100644
--- a/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
@@ -217,14 +217,11 @@ void PassByValueCheck::check(const 
MatchFinder::MatchResult &Result) {
   // Use std::move in the initialization list.
   Diag << FixItHint::CreateInsertion(Initializer->getRParenLoc(), ")")
<< FixItHint::CreateInsertion(
-  Initializer->getLParenLoc().getLocWithOffset(1), "std::move(");
-
-  if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
-  Result.SourceManager->getFileID(Initializer->getSourceLocation()),
-  "utility",
-  /*IsAngled=*/true)) {
-Diag << *IncludeFixit;
-  }
+  Initializer->getLParenLoc().getLocWithOffset(1), "std::move(")
+   << Inserter->CreateIncludeInsertion(
+  
Result.SourceManager->getFileID(Initializer->getSourceLocation()),
+  "utility",
+  /*IsAngled=*/true);
 }
 
 } // namespace modernize

diff  --git a/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
index 515b2146f06c..295be200bca6 100644
--- a/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
@@ -148,14 +148,12 @@ void ReplaceAutoPtrCheck::check(const 
MatchFinder::MatchResult &Result) {
 if (Range.isInvalid())
   return;
 
-auto Diag = diag(Range.getBegin(), "use std::move to transfer ownership")
-<< FixItHint::CreateInsertion(Range.getBegin(), "std::move(")
-<< FixItHint::CreateInsertion(Range.getEnd(), ")");
-
-if (auto Fix =
-Inserter->CreateIncludeInsertion(SM.getMainFileID(), "utility",
- /*IsAngled=*/true))
-  Diag << *Fix;
+auto Diag =
+diag(Range.getBegin(), "use std::move to transfer ownership")
+<< FixItHint::CreateInsertion(Range.getBegin(), "std::move(")
+<< FixItHint::CreateInsertion(Range.getEnd(), ")")
+<< Inserter->CreateIncludeInsertion(SM.getMainFileID(), "utility",
+/*IsAngled=*/true);
 
 return;
   }

diff  --git 
a/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
index 550772972923..9cfbd87239dc 100644
--- a/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
@@ -94,13 +94,10 @@ void ReplaceRandomShuffleCheck::check(const 
MatchFinder::MatchResult &Result) {
 
   Diag << FixItHint::CreateRemoval(MatchedDecl->getSourceRange());
   Diag << FixItHint::CreateInsertion(MatchedDecl->getBeginLoc(), NewName);
-
-  if (Optional IncludeFixit =
-  IncludeInserter->CreateIncludeInsertion(
-  Result.Context->getSourceManager().getFileID(
-  MatchedCallExpr->getBeginLoc()),
-  "random", /*IsAngled=*/true))
-Diag << IncludeFixit.getValue();
+  Diag << IncludeInserter->CreateIncludeInsertion(
+  Result.Context->getSourceManager().getFileID(
+  MatchedCallExpr->getBeginLoc()),
+  "random", /*IsAngled=*/true);
 }
 
 } // namespace modernize

diff  --git 
a/clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
index 1d7ee4baae93..d08cec1a2c3c 100644
--- a/clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
@@ -193,10 +193,9 @@ void TypePromotionInMathFnCheck::check(const 
MatchFinder::MatchResult &Result) {
   // , because the functions we're sugge

[clang-tools-extra] af4f2eb - [clang-tidy] remove duplicate fixes of alias checkers

2020-06-19 Thread Nathan James via cfe-commits

Author: Daniel
Date: 2020-06-19T20:40:59+01:00
New Revision: af4f2eb476361e6da42d6f66a68cada763625c32

URL: 
https://github.com/llvm/llvm-project/commit/af4f2eb476361e6da42d6f66a68cada763625c32
DIFF: 
https://github.com/llvm/llvm-project/commit/af4f2eb476361e6da42d6f66a68cada763625c32.diff

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

when both a check and its alias are enabled, we should only take the fixes of 
one of them and not both.
This patch fixes bug 45577
https://bugs.llvm.org/show_bug.cgi?id=45577

Reviewed By: aaron.ballman, njames93

Differential Revision: https://reviews.llvm.org/D80753

Added: 

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

Modified: 
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-reports.cpp
llvm/include/llvm/ADT/StringMap.h
llvm/unittests/ADT/StringMapTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index d9b4b01e7161..163aad2ec378 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -122,6 +122,8 @@ class ErrorReporter {
 {
   auto Level = static_cast(Error.DiagLevel);
   std::string Name = Error.DiagnosticName;
+  if (!Error.EnabledDiagnosticAliases.empty())
+Name += "," + llvm::join(Error.EnabledDiagnosticAliases, ",");
   if (Error.IsWarningAsError) {
 Name += ",-warnings-as-errors";
 Level = DiagnosticsEngine::Error;

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 9742cd08d9c3..5c23323b03f0 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/Support/FormatVariadic.h"
 #include 
 #include 
 using namespace clang;
@@ -634,6 +635,8 @@ void 
ClangTidyDiagnosticConsumer::removeIncompatibleErrors() {
 std::tuple Priority;
   };
 
+  removeDuplicatedDiagnosticsOfAliasCheckers();
+
   // Compute error sizes.
   std::vector Sizes;
   std::vector<
@@ -728,3 +731,59 @@ std::vector 
ClangTidyDiagnosticConsumer::take() {
 removeIncompatibleErrors();
   return std::move(Errors);
 }
+
+namespace {
+struct LessClangTidyErrorWithoutDiagnosticName {
+  bool operator()(const ClangTidyError *LHS, const ClangTidyError *RHS) const {
+const tooling::DiagnosticMessage &M1 = LHS->Message;
+const tooling::DiagnosticMessage &M2 = RHS->Message;
+
+return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
+   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
+  }
+};
+} // end anonymous namespace
+
+void ClangTidyDiagnosticConsumer::removeDuplicatedDiagnosticsOfAliasCheckers() 
{
+  using UniqueErrorSet =
+  std::set;
+  UniqueErrorSet UniqueErrors;
+
+  auto IT = Errors.begin();
+  while (IT != Errors.end()) {
+ClangTidyError &Error = *IT;
+std::pair Inserted =
+UniqueErrors.insert(&Error);
+
+// Unique error, we keep it and move along.
+if (Inserted.second) {
+  ++IT;
+} else {
+  ClangTidyError &ExistingError = **Inserted.first;
+  const llvm::StringMap &CandidateFix =
+  Error.Message.Fix;
+  const llvm::StringMap &ExistingFix =
+  (*Inserted.first)->Message.Fix;
+
+  if (CandidateFix != ExistingFix) {
+
+// In case of a conflict, don't suggest any fix-it.
+ExistingError.Message.Fix.clear();
+ExistingError.Notes.emplace_back(
+llvm::formatv("cannot apply fix-it because an alias checker has "
+  "suggested a 
diff erent fix-it; please remove one of "
+  "the checkers ('{0}', '{1}') or "
+  "ensure they are both configured the same",
+  ExistingError.DiagnosticName, Error.DiagnosticName)
+.str());
+  }
+
+  if (Error.IsWarningAsError)
+ExistingError.IsWarningAsError = true;
+
+  // Since it is the same error, we should take it as alias and remove it.
+  
ExistingError.EnabledDiagnosticAliases.emplace_back(Error.DiagnosticName);
+  IT = Errors.erase(IT);
+}
+  }
+}

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
index 2bb3296b150d..90cc4da3021f 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsum

[clang-tools-extra] db90d31 - [clang-tidy] Implement storeOptions for checks missing it.

2020-06-21 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-21T19:01:11+01:00
New Revision: db90d315706b5d5a06cb79607cef1a8d581d0ba8

URL: 
https://github.com/llvm/llvm-project/commit/db90d315706b5d5a06cb79607cef1a8d581d0ba8
DIFF: 
https://github.com/llvm/llvm-project/commit/db90d315706b5d5a06cb79607cef1a8d581d0ba8.diff

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

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82223

Added: 


Modified: 
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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
index be5a4697e94b..06332af92e37 100644
--- a/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
@@ -30,8 +30,7 @@ static constexpr llvm::StringLiteral LoopIncrementName =
 TooSmallLoopVariableCheck::TooSmallLoopVariableCheck(StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  MagnitudeBitsUpperLimit(Options.get(
-  "MagnitudeBitsUpperLimit", 16)) {}
+  MagnitudeBitsUpperLimit(Options.get("MagnitudeBitsUpperLimit", 16U)) {}
 
 void TooSmallLoopVariableCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
index a5756ff634bb..608df8a0ab44 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -29,6 +29,12 @@ InitVariablesCheck::InitVariablesCheck(StringRef Name,
 utils::IncludeSorter::IS_LLVM)),
   MathHeader(Options.get("MathHeader", "math.h")) {}
 
+void InitVariablesCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", IncludeStyle,
+utils::IncludeSorter::getMapping());
+  Options.store(Opts, "MathHeader", MathHeader);
+}
+
 void InitVariablesCheck::registerMatchers(MatchFinder *Finder) {
   std::string BadDecl = "badDecl";
   Finder->addMatcher(
@@ -102,7 +108,6 @@ void InitVariablesCheck::check(const 
MatchFinder::MatchResult &Result) {
 }
   }
 }
-
 } // namespace cppcoreguidelines
 } // namespace tidy
 } // namespace clang

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
index 0cacf9e533cf..61521b118a99 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.h
@@ -24,6 +24,7 @@ namespace cppcoreguidelines {
 class InitVariablesCheck : public ClangTidyCheck {
 public:
   InitVariablesCheck(StringRef Name, Clan

[clang] c2b22c5 - Fixed ASTMatchers registry and regen ast docs

2020-06-22 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-22T10:56:20+01:00
New Revision: c2b22c57fc1394f2566d20369ae29877eb7df1a1

URL: 
https://github.com/llvm/llvm-project/commit/c2b22c57fc1394f2566d20369ae29877eb7df1a1
DIFF: 
https://github.com/llvm/llvm-project/commit/c2b22c57fc1394f2566d20369ae29877eb7df1a1.diff

LOG: Fixed ASTMatchers registry and regen ast docs

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index bb5e4984fcdf..ae90ba047df9 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -1226,6 +1226,11 @@ Node Matchers
 
 
 
+MatcherStmt>fixedPointLiteralMatcherFixedPointLiteral>...
+Matches fixed 
point literals
+
+
+
 MatcherStmt>floatLiteralMatcherFloatingLiteral>...
 Matches float literals 
of all sizes / encodings, e.g.
 1.0, 1.0f, 1.0L and 1e10.
@@ -4016,6 +4021,23 @@ Narrowing Matchers
 
 
 
+MatcherParmVarDecl>isAtPositionunsigned N
+Matches the 
ParmVarDecl nodes that are at the N'th position in the parameter
+list. The parameter list could be that of either a block, function, or
+objc-method.
+
+
+Given
+
+void f(int a, int b, int c) {
+}
+
+``parmVarDecl(isAtPosition(0))`` matches ``int a``.
+
+``parmVarDecl(isAtPosition(1))`` matches ``int b``.
+
+
+
 MatcherQualType>asStringstd::string Name
 Matches if the matched 
type is represented by the given string.
 
@@ -4755,23 +4777,6 @@ Narrowing Matchers
 Usable as: MatcherFunctionDecl>,
 MatcherVarDecl>,
 MatcherCXXRecordDecl>
 
 
-
-MatcherisAtPositionunsigned N
-Matches the 
ParmVarDecl nodes that are at the N'th position in the parameter
-list. The parameter list could be that of either a block, function, or
-objc-method.
-
-
-Given
-
-void f(int a, int b, int c) {
-}
-
-``parmVarDecl(isAtPosition(0))`` matches ``int a``.
-
-``parmVarDecl(isAtPosition(1))`` matches ``int b``.
-
-
 
 
 
@@ -5632,13 +5637,14 @@ AST Traversal Matchers
 MatcherCXXRecordDecl>hasAnyBaseMatcherCXXBaseSpecifier>
 BaseSpecMatcher
 Matches C++ classes that 
have a direct or indirect base matching BaseSpecMatcher.
 
-Example matches DirectlyDerived, IndirectlyDerived (BaseSpecMatcher ==
-hasType(cxxRecordDecl(hasName("SpecialBase" class Foo;
+Example:
+matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase")
+  class Foo;
   class Bar : Foo {};
   class Baz : Bar {};
   class SpecialBase;
-  class DirectlyDerived : SpecialBase {};  // directly derived
-  class IndirectlyDerived : DirectlyDerived {};  // indirectly derived
+  class Proxy : SpecialBase {};  // matches Proxy
+  class IndirectlyDerived : Proxy {};  //matches IndirectlyDerived
 
 FIXME: Refactor this and isDerivedFrom to reuse implementation.
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 6dbcc01442ed..4d5e4230302b 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4323,7 +4323,7 @@ AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
 /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
 ///
 /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
-AST_MATCHER_P(clang::ParmVarDecl, isAtPosition, unsigned, N) {
+AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
   const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
 
   if (const auto *Decl = dyn_cast_or_null(Context))

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 950a56f79551..c7f151f61355 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -151,6 +151,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(characterLiteral);
   REGISTER_MATCHER(chooseExpr);
   REGISTER_MATCHER(classTemplateDecl);
+  REGISTER_MATCHER(classTemplatePartialSpecializationDecl);
   REGISTER_MATCHER(classTemplateSpecializationDecl);
   REGISTER_MATCHER(complexType);
   REGISTER_MATCHER(compoundLiteralExpr);
@@ -219,7 +220

[clang-tools-extra] 2306329 - [clang-tidy] Improved accuracy of check list updater script

2020-06-22 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-22T11:07:24+01:00
New Revision: 23063296b539feb405fb3ce61711a3c1cc1c94d0

URL: 
https://github.com/llvm/llvm-project/commit/23063296b539feb405fb3ce61711a3c1cc1c94d0
DIFF: 
https://github.com/llvm/llvm-project/commit/23063296b539feb405fb3ce61711a3c1cc1c94d0.diff

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

 - Added `FixItHint` comments to Check files 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.

Reviewed By: sylvestre.ledru

Differential Revision: https://reviews.llvm.org/D81932

Added: 


Modified: 
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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
index f60ce2000766..87af9ea6cd5a 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
@@ -15,6 +15,9 @@
 #include "clang/Tooling/Transformer/RewriteRule.h"
 #include "clang/Tooling/Transformer/Stencil.h"
 
+// FixItHint - Hint to check documentation script to mark this check as
+// providing a FixIt.
+
 using namespace clang::ast_matchers;
 
 namespace clang {

diff  --git a/clang-tools-extra/clang-tidy/add_new_check.py 
b/clang-tools-extra/clang-tidy/add_new_check.py
index 454d128a5dcb..231f43c0b8f3 100755
--- a/clang-tools-extra/clang-tidy/add_new_check.py
+++ b/clang-tools-extra/clang-tidy/add_new_check.py
@@ -289,6 +289,19 @@ def write_test(module_path, module, check_name, 
test_extension):
 """ % {'check_name_dashes': check_name_dashes})
 
 
+def get_actual_filename(dirname, filename):
+  if not os.path.isdir(dirname): 
+return ""
+  name = os.path.join(dirname, filename)
+  if (os.path.isfile(name)):
+return name
+  caselessname = filename.lower()
+  for file in os.listdir(dirname):
+if (file.lower() == caselessname):
+  return os.path.join(dirname, file)
+  return ""
+
+
 # Recreates the list of checks in the docs/clang-tidy/checks directory.
 def update_checks_list(clang_tidy_path):
   docs_dir = os.path.join(clang_tidy_path, '../docs/clang-tidy/checks')
@@ -304,7 +317,8 @@ def update_checks_list(clang_tidy_path):
   def has_auto_fix(check_name):
 dirname, _, check_name = check_name.partition("-")
 
-checkerCode = os.path.join(dirname, get_camel_name(check_name)) + ".cpp"
+checkerCode = get_actual_filename(dirname,
+  get_camel_name(check_name) + '.cpp')
 
 if not os.path.isfile(checkerCode):
   return ""

diff  --git 
a/clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp 
b/clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
index 4a19b5359d4f..91842b4719c4 100644
--- a/clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp
+++ b/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 {

diff  --git a/clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
index 11d24432edaf..5ab3f3e26be2 100644
--- a/clang-tools-extra/clang-tidy/modernize/MakeSharedCheck.cpp
+++ b/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 {

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 17331605aa64..baa142e28e7f 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -133,6 +133,7 @@ Clang-Tidy Checks
`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 @@ Clang-Tidy Checks
`llvm-pref

[clang-tools-extra] 6ae0f5f - [clang-tidy] RenamerClangTidy wont emit fixes in scratch space

2020-06-22 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-22T18:26:18+01:00
New Revision: 6ae0f5f3e1d465e6a663a50f2cc077671bc6d097

URL: 
https://github.com/llvm/llvm-project/commit/6ae0f5f3e1d465e6a663a50f2cc077671bc6d097
DIFF: 
https://github.com/llvm/llvm-project/commit/6ae0f5f3e1d465e6a663a50f2cc077671bc6d097.diff

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

Prevent fixes being displayed if usages are found in the scratch buffer.
See [[ https://bugs.llvm.org/show_bug.cgi?id=46219 | 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.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82162

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index e90ab1782b4b..040378d980f1 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -156,14 +156,17 @@ void RenamerClangTidyCheck::addUsage(
   // is already in there
   RenamerClangTidyCheck::NamingCheckFailure &Failure =
   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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 // 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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 // further TypeLocs handled below
 
 if (Decl) {
-  addUsage(Decl, Loc->getSourceRange());
+  addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
 
@@ -300,7 +305,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 if (const auto &Ref =
 Loc->getAs()) {
   if (const TagDecl *Decl = Ref.getTypePtr()->getAsTagDecl())
-addUsage(Decl, Loc->getSourceRange());
+addUsage(Decl, Loc->getSourceRange(), Result.SourceManager);
   return;
 }
   }
@@ -317,7 +322,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   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 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 
   if (const auto *Decl = Result.Nodes.ge

[clang-tools-extra] 9a8b041 - [clang-tidy] llvm-twine-local ignores parameters

2020-06-22 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-22T18:25:45+01:00
New Revision: 9a8b0411448062e7231a0ee26bd14a3d1c097e9e

URL: 
https://github.com/llvm/llvm-project/commit/9a8b0411448062e7231a0ee26bd14a3d1c097e9e
DIFF: 
https://github.com/llvm/llvm-project/commit/9a8b0411448062e7231a0ee26bd14a3d1c097e9e.diff

LOG: [clang-tidy] llvm-twine-local ignores parameters

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82281

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp 
b/clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
index 63a9314a49e5..907bdcb264bf 100644
--- a/clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
+++ b/clang-tools-extra/clang-tidy/llvm/TwineLocalCheck.cpp
@@ -19,8 +19,10 @@ namespace llvm_check {
 
 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 &Result) {

diff  --git a/clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
index 06eb7613d439..3dcf6abe0c22 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/llvm-twine-local.cpp
@@ -13,6 +13,7 @@ class Twine {
 using namespace llvm;
 
 void foo(const Twine &x);
+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



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


[clang-tools-extra] 42a5158 - Fix build errors after b9306fd0

2020-06-28 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-28T11:02:19+01:00
New Revision: 42a51587c79a673045aec3586f4070630e5e7af3

URL: 
https://github.com/llvm/llvm-project/commit/42a51587c79a673045aec3586f4070630e5e7af3
DIFF: 
https://github.com/llvm/llvm-project/commit/42a51587c79a673045aec3586f4070630e5e7af3.diff

LOG: Fix build errors after b9306fd0

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
index 038814e21fb3..369ebe42715a 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
@@ -76,7 +76,7 @@ class IdentifierNamingCheck final : public 
RenamerClangTidyCheck {
 
 } // namespace readability
 template <>
-struct ::clang::tidy::OptionEnumMapping<
+struct OptionEnumMapping<
 readability::IdentifierNamingCheck::CaseType> {
   static llvm::ArrayRef<
   std::pair>



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


[clang-tools-extra] b9306fd - [clang-tidy] Reworked enum options handling(again)

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-28T10:18:33+01:00
New Revision: b9306fd042ce1c11d84f05d2124dfdc65b8331fe

URL: 
https://github.com/llvm/llvm-project/commit/b9306fd042ce1c11d84f05d2124dfdc65b8331fe
DIFF: 
https://github.com/llvm/llvm-project/commit/b9306fd042ce1c11d84f05d2124dfdc65b8331fe.diff

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

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.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82188

Added: 


Modified: 
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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 7ddf054a21a9..39c049948809 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -158,7 +158,7 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
 }
 
 llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
-StringRef LocalName, ArrayRef> Mapping,
+StringRef LocalName, ArrayRef> Mapping,
 bool CheckGlobal, bool IgnoreCase) {
   auto Iter = CheckOptions.find((NamePrefix + LocalName).str());
   if (CheckGlobal && Iter == CheckOptions.end())
@@ -171,19 +171,19 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   unsigned EditDistance = -1;
   for (const auto &NameAndEnum : Mapping) {
 if (IgnoreCase) {
-  if (Value.equals_lower(NameAndEnum.first))
-return NameAndEnum.second;
-} else if (Value.equals(NameAndEnum.first)) {
-  return NameAndEnum.second;
-} else if (Value.equals_lower(NameAndEnum.first)) {
-  Closest = NameAndEnum.first;
+  if (Value.equals_lower(NameAndEnum.second))
+return NameAndEnum.first;
+} else if (Value.equals(NameAndEnum.second)) {
+  return NameAndEnum.first;
+} else if (Value.equals_lower(NameAndEnum.second)) {
+  Closest = NameAndEnum.second;
   EditDistance = 0;
   continue;
 }
-unsigned Distance = Value.edit_distance(NameAndEnum.first);
+unsigned Distance = Value.edit_distance(NameAndEnum.second);
 if (Distance < EditDistance) {
   EditDistance = Distance;
-  Closest = NameAndEnum.first;
+  Closest = NameAndEnum.second;
 }
   }
   if (EditDistance < 3)

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 84438c21a30b..84ad16c9eea8 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -27,6 +27,13 @@ class CompilerInstance;
 
 namespace tidy {
 
+/// This class should be specialized by any enum type that needs to be 
converted
+/// to and from an \ref llvm::StringRef.
+template  struct OptionEnumMapping {
+  // Specializations of this struct must implement this function.
+  static ArrayRef> getEnumMapping() = delete;
+};
+
 template  class OptionError : public llvm::ErrorInfo {
   std::error_code convertToErrorCode() const override {
 return llvm::inconvertibleErrorCode();
@@ -313,36 +320,38 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 }
 
 /// Read a named option from the ``Context`` and parse it as an
-/// enum type ``T`` using the \p Mapping provided. If \p IgnoreCase is set,
-/// it will search the mapping ignoring the case.
+/// enum type ``T``.
 ///
 /// Reads the option with the check-local name \p LocalName from the
 ///

[clang-tools-extra] bfd99be - [clang-tidy] Update lang restrictions on perf module

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-28T15:18:08+01:00
New Revision: bfd99be0fc58fe644aff76d180b333e6d840126a

URL: 
https://github.com/llvm/llvm-project/commit/bfd99be0fc58fe644aff76d180b333e6d840126a
DIFF: 
https://github.com/llvm/llvm-project/commit/bfd99be0fc58fe644aff76d180b333e6d840126a.diff

LOG: [clang-tidy] Update lang restrictions on perf module

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h
clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h
clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
index bb0a02f06fc6..a6216b230911 100644
--- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
@@ -59,9 +59,6 @@ void 
FasterStringFindCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void FasterStringFindCheck::registerMatchers(MatchFinder *Finder) {
-  if (!getLangOpts().CPlusPlus)
-return;
-
   const auto SingleChar =
   expr(ignoringParenCasts(stringLiteral(hasSize(1)).bind("literal")));
   const auto StringFindFunctions =

diff  --git a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h 
b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h
index 7d46d06c375c..71a45705f1e8 100644
--- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h
@@ -27,6 +27,9 @@ namespace performance {
 class FasterStringFindCheck : public ClangTidyCheck {
 public:
   FasterStringFindCheck(StringRef Name, ClangTidyContext *Context);
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{
+return LangOpts.CPlusPlus;
+  }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;

diff  --git a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h 
b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h
index 3745c7bb4681..71f662ba5544 100644
--- a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h
@@ -22,6 +22,9 @@ namespace performance {
 class ForRangeCopyCheck : public ClangTidyCheck {
 public:
   ForRangeCopyCheck(StringRef Name, ClangTidyContext *Context);
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{
+return LangOpts.CPlusPlus11;
+  }
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;

diff  --git 
a/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h 
b/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h
index b372003a8002..4b271366f0f6 100644
--- a/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h
@@ -22,6 +22,9 @@ class ImplicitConversionInLoopCheck : public ClangTidyCheck {
 public:
   ImplicitConversionInLoopCheck(StringRef Name, ClangTidyContext *Context)
   : ClangTidyCheck(Name, Context) {}
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const 
override{
+return LangOpts.CPlusPlus11;
+  }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
 

diff  --git 
a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h 
b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
index e224dcc90685..533b30dc32b0 100644
--- a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h
@@ -26,6 +26,9 @@ namespace performance {
 class InefficientVectorOperationCheck : public ClangTidyCheck {
 public:
   InefficientVectorOperationCheck(StringRef Name, ClangTidyContext *Context);
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{
+return LangOpts.CPlusPlus;
+  }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
   void storeOptions(ClangTidyOptions::OptionMap &

[clang] abafb65 - [clang][docs] Remove untracked files from formatted status

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-28T09:49:39+01:00
New Revision: abafb655c85d92c02c19c8723ef9ecc5d48574bf

URL: 
https://github.com/llvm/llvm-project/commit/abafb655c85d92c02c19c8723ef9ecc5d48574bf
DIFF: 
https://github.com/llvm/llvm-project/commit/abafb655c85d92c02c19c8723ef9ecc5d48574bf.diff

LOG: [clang][docs] Remove untracked files from formatted status

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 
`.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D82707

Added: 


Modified: 
clang/docs/tools/generate_formatted_state.py

Removed: 




diff  --git a/clang/docs/tools/generate_formatted_state.py 
b/clang/docs/tools/generate_formatted_state.py
index 1b620a84ac0b..41d5cd9d4004 100755
--- a/clang/docs/tools/generate_formatted_state.py
+++ b/clang/docs/tools/generate_formatted_state.py
@@ -72,6 +72,8 @@ def get_style(count, passed):
  - {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 @@ def get_style(count, passed):
 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


[clang-tools-extra] 37cc4fa - [clang-tidy] relanding b9306fd

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-29T09:29:39+01:00
New Revision: 37cc4fa2eaa3d03ca8cd4947eb0d4c60e3c9b45c

URL: 
https://github.com/llvm/llvm-project/commit/37cc4fa2eaa3d03ca8cd4947eb0d4c60e3c9b45c
DIFF: 
https://github.com/llvm/llvm-project/commit/37cc4fa2eaa3d03ca8cd4947eb0d4c60e3c9b45c.diff

LOG: [clang-tidy] relanding b9306fd

Added some sanity checks to figure out the cause of a (seemingly unrelated) 
test failure on mac.
These can be removed should no issues arise on that platform again.

Added: 


Modified: 
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/ClangTidyDiagnosticConsumerTest.cpp
clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 7ddf054a21a9..39c049948809 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -158,7 +158,7 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
 }
 
 llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
-StringRef LocalName, ArrayRef> Mapping,
+StringRef LocalName, ArrayRef> Mapping,
 bool CheckGlobal, bool IgnoreCase) {
   auto Iter = CheckOptions.find((NamePrefix + LocalName).str());
   if (CheckGlobal && Iter == CheckOptions.end())
@@ -171,19 +171,19 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   unsigned EditDistance = -1;
   for (const auto &NameAndEnum : Mapping) {
 if (IgnoreCase) {
-  if (Value.equals_lower(NameAndEnum.first))
-return NameAndEnum.second;
-} else if (Value.equals(NameAndEnum.first)) {
-  return NameAndEnum.second;
-} else if (Value.equals_lower(NameAndEnum.first)) {
-  Closest = NameAndEnum.first;
+  if (Value.equals_lower(NameAndEnum.second))
+return NameAndEnum.first;
+} else if (Value.equals(NameAndEnum.second)) {
+  return NameAndEnum.first;
+} else if (Value.equals_lower(NameAndEnum.second)) {
+  Closest = NameAndEnum.second;
   EditDistance = 0;
   continue;
 }
-unsigned Distance = Value.edit_distance(NameAndEnum.first);
+unsigned Distance = Value.edit_distance(NameAndEnum.second);
 if (Distance < EditDistance) {
   EditDistance = Distance;
-  Closest = NameAndEnum.first;
+  Closest = NameAndEnum.second;
 }
   }
   if (EditDistance < 3)

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 84438c21a30b..84ad16c9eea8 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -27,6 +27,13 @@ class CompilerInstance;
 
 namespace tidy {
 
+/// This class should be specialized by any enum type that needs to be 
converted
+/// to and from an \ref llvm::StringRef.
+template  struct OptionEnumMapping {
+  // Specializations of this struct must implement this function.
+  static ArrayRef> getEnumMapping() = delete;
+};
+
 template  class OptionError : public llvm::ErrorInfo {
   std::error_code convertToErrorCode() const override {
 return llvm::inconvertibleErrorCode();
@@ -313,36 +320,38 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 }
 
 /// Read a named option from the ``Context`` and parse it as an
-/// enum type ``T`` using the \p Mapping provided. If \p IgnoreCase is set,
-/// it will search the mapping ignoring the case.
+/// enum type ``T``.
 ///
 /// Reads the option with the check-local name \p LocalName from the
 /// ``CheckOptions``. If the corresponding key is not present, returns a
 /// ``Missing

[clang-tools-extra] e34523c - Revert "[clang-tidy] relanding b9306fd"

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-29T09:44:11+01:00
New Revision: e34523c87c3f1cfabcf741568dede026bbb12d3a

URL: 
https://github.com/llvm/llvm-project/commit/e34523c87c3f1cfabcf741568dede026bbb12d3a
DIFF: 
https://github.com/llvm/llvm-project/commit/e34523c87c3f1cfabcf741568dede026bbb12d3a.diff

LOG: Revert "[clang-tidy] relanding b9306fd"

This reverts commit 37cc4fa2eaa3d03ca8cd4947eb0d4c60e3c9b45c. More 
investigation needed

Added: 


Modified: 
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/ClangTidyDiagnosticConsumerTest.cpp
clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 39c049948809..7ddf054a21a9 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -158,7 +158,7 @@ void 
ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options,
 }
 
 llvm::Expected ClangTidyCheck::OptionsView::getEnumInt(
-StringRef LocalName, ArrayRef> Mapping,
+StringRef LocalName, ArrayRef> Mapping,
 bool CheckGlobal, bool IgnoreCase) {
   auto Iter = CheckOptions.find((NamePrefix + LocalName).str());
   if (CheckGlobal && Iter == CheckOptions.end())
@@ -171,19 +171,19 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   unsigned EditDistance = -1;
   for (const auto &NameAndEnum : Mapping) {
 if (IgnoreCase) {
-  if (Value.equals_lower(NameAndEnum.second))
-return NameAndEnum.first;
-} else if (Value.equals(NameAndEnum.second)) {
-  return NameAndEnum.first;
-} else if (Value.equals_lower(NameAndEnum.second)) {
-  Closest = NameAndEnum.second;
+  if (Value.equals_lower(NameAndEnum.first))
+return NameAndEnum.second;
+} else if (Value.equals(NameAndEnum.first)) {
+  return NameAndEnum.second;
+} else if (Value.equals_lower(NameAndEnum.first)) {
+  Closest = NameAndEnum.first;
   EditDistance = 0;
   continue;
 }
-unsigned Distance = Value.edit_distance(NameAndEnum.second);
+unsigned Distance = Value.edit_distance(NameAndEnum.first);
 if (Distance < EditDistance) {
   EditDistance = Distance;
-  Closest = NameAndEnum.second;
+  Closest = NameAndEnum.first;
 }
   }
   if (EditDistance < 3)

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 84ad16c9eea8..84438c21a30b 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -27,13 +27,6 @@ class CompilerInstance;
 
 namespace tidy {
 
-/// This class should be specialized by any enum type that needs to be 
converted
-/// to and from an \ref llvm::StringRef.
-template  struct OptionEnumMapping {
-  // Specializations of this struct must implement this function.
-  static ArrayRef> getEnumMapping() = delete;
-};
-
 template  class OptionError : public llvm::ErrorInfo {
   std::error_code convertToErrorCode() const override {
 return llvm::inconvertibleErrorCode();
@@ -320,38 +313,36 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 }
 
 /// Read a named option from the ``Context`` and parse it as an
-/// enum type ``T``.
+/// enum type ``T`` using the \p Mapping provided. If \p IgnoreCase is set,
+/// it will search the mapping ignoring the case.
 ///
 /// Reads the option with the check-local name \p LocalName from the
 /// ``CheckOptions``. If the corresponding key is not present, returns a
 /// ``MissingOptionError``. If the key can't be parsed as a ``T`` returns a
 

[clang-tools-extra] 1f228e5 - [clang-tidy] Fix hicpp-named-paramater

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-29T15:28:09+01:00
New Revision: 1f228e572da238c656958bf7f85b371d773eb588

URL: 
https://github.com/llvm/llvm-project/commit/1f228e572da238c656958bf7f85b371d773eb588
DIFF: 
https://github.com/llvm/llvm-project/commit/1f228e572da238c656958bf7f85b371d773eb588.diff

LOG: [clang-tidy] Fix hicpp-named-paramater

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82711

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp 
b/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
index ad367dcfed38..253c3893f0d4 100644
--- a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
+++ b/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 @@ class HICPPModule : public ClangTidyModule {
 "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


[clang-tools-extra] 860aefd - [clang-tidy][NFC] Remove unnecessary includes throughout clang-tidy header files

2020-06-29 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-29T16:05:52+01:00
New Revision: 860aefd0784ed05ffc0d56f36b0d56009776002a

URL: 
https://github.com/llvm/llvm-project/commit/860aefd0784ed05ffc0d56f36b0d56009776002a
DIFF: 
https://github.com/llvm/llvm-project/commit/860aefd0784ed05ffc0d56f36b0d56009776002a.diff

LOG: [clang-tidy][NFC] Remove unnecessary includes throughout clang-tidy header 
files

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82661

Added: 


Modified: 
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/UpgradeG

[clang-tools-extra] 60cde47 - [clang-tidy][docs] Fix malformed link in ReleaseNotes

2020-06-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-30T09:17:48+01:00
New Revision: 60cde47893476581218c380921e5489c98be40ce

URL: 
https://github.com/llvm/llvm-project/commit/60cde47893476581218c380921e5489c98be40ce
DIFF: 
https://github.com/llvm/llvm-project/commit/60cde47893476581218c380921e5489c98be40ce.diff

LOG: [clang-tidy][docs] Fix malformed link in ReleaseNotes

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index bd898de446b9..1ef0bdffa730 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -195,7 +195,7 @@ New check aliases
 Changes in existing checks
 ^^
 
-- Improved :doc:'readability-identifier-naming
+- Improved :doc:`readability-identifier-naming
   ` check.
 
   Now able to rename member references in class template definitions with 



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


[clang-tools-extra] 833273a - [clang-tidy] Sanity checks in ClangTidyTest header.

2020-06-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-30T16:19:15+01:00
New Revision: 833273a81250213d3ba85ca5419d03155604ada2

URL: 
https://github.com/llvm/llvm-project/commit/833273a81250213d3ba85ca5419d03155604ada2
DIFF: 
https://github.com/llvm/llvm-project/commit/833273a81250213d3ba85ca5419d03155604ada2.diff

LOG: [clang-tidy] Sanity checks in ClangTidyTest header.

Motivated by a suspicously failing build, but also good to have anyway in 
general.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82815

Added: 


Modified: 
clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h

Removed: 




diff  --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h 
b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
index 6166af3c42e7..b8ee9972f6f8 100644
--- a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
+++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
@@ -19,7 +19,6 @@
 #include "clang/Tooling/Core/Replacement.h"
 #include "clang/Tooling/Refactoring.h"
 #include "clang/Tooling/Tooling.h"
-#include "llvm/ADT/Optional.h"
 #include "llvm/Support/Path.h"
 #include 
 #include 
@@ -67,7 +66,9 @@ class TestClangTidyAction : public ASTFrontendAction {
 // that check constructors can access the context (for example, through
 // `getLangOpts()`).
 CheckFactory::createChecks(&Context, Checks);
+assert(!Checks.empty() && "No checks created");
 for (auto &Check : Checks) {
+  assert(Check.get() && "Checks can't be null");
   if (!Check->isLanguageVersionSupported(Context.getLangOpts()))
 continue;
   Check->registerMatchers(&Finder);
@@ -89,6 +90,7 @@ runCheckOnCode(StringRef Code, std::vector 
*Errors = nullptr,
const ClangTidyOptions &ExtraOptions = ClangTidyOptions(),
std::map PathsToContent =
std::map()) {
+  static_assert(sizeof...(CheckTypes) > 0, "No checks specified");
   ClangTidyOptions Options = ExtraOptions;
   Options.Checks = "*";
   ClangTidyContext Context(std::make_unique(
@@ -120,7 +122,7 @@ runCheckOnCode(StringRef Code, std::vector 
*Errors = nullptr,
   llvm::IntrusiveRefCntPtr Files(
   new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
-  SmallVector, 1> Checks;
+  SmallVector, sizeof...(CheckTypes)> Checks;
   tooling::ToolInvocation Invocation(
   Args,
   std::make_unique>(Checks, Finder,



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


[clang-tools-extra] 2efba0e - [clang-tidy] performance-faster-string-find string-view

2020-06-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-30T16:45:59+01:00
New Revision: 2efba0e8122aeca29f878c0e3056a4552d20c720

URL: 
https://github.com/llvm/llvm-project/commit/2efba0e8122aeca29f878c0e3056a4552d20c720
DIFF: 
https://github.com/llvm/llvm-project/commit/2efba0e8122aeca29f878c0e3056a4552d20c720.diff

LOG: [clang-tidy] performance-faster-string-find string-view

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D82720

Added: 


Modified: 
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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
index a6216b230911..0d2efb31b774 100644
--- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp
@@ -51,7 +51,8 @@ FasterStringFindCheck::FasterStringFindCheck(StringRef Name,
  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 &Opts) {
   Options.store(Opts, "StringLikeClasses",

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1ef0bdffa730..c92e18a57821 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -195,6 +195,11 @@ New check aliases
 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.
 

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst 
b/clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
index 8d7265e68bee..443da597506a 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/performance-faster-string-find.rst
@@ -23,6 +23,8 @@ Options
 .. 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 check will only consider member functions named ``find``, ``rfind``, 
+   ``find_first_of``, ``find_first_not_of``, ``find_last_of``, or 
+   ``find_last_not_of`` within these classes.
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp
index b36e32301f5d..d26cd2c8ca30 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance-faster-string-find.cpp
+++ 
b/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 @@ struct basic_string {
 
 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 @@ void StringFind() {
   // 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: 'f

[clang] 8ba4867 - [CodeComplete] Tweak completion for else.

2020-06-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-06-30T16:48:24+01:00
New Revision: 8ba4867c27000ee029ab70a1194050d884fce6c7

URL: 
https://github.com/llvm/llvm-project/commit/8ba4867c27000ee029ab70a1194050d884fce6c7
DIFF: 
https://github.com/llvm/llvm-project/commit/8ba4867c27000ee029ab70a1194050d884fce6c7.diff

LOG: [CodeComplete] Tweak completion for else.

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.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D82626

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/patterns.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 24ceceeb69d0..77eda3b25c83 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11980,7 +11980,7 @@ class Sema final {
   void CodeCompleteDesignator(const QualType BaseType,
   llvm::ArrayRef InitExprs,
   const Designation &D);
-  void CodeCompleteAfterIf(Scope *S);
+  void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
 
   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool 
EnteringContext,
bool IsUsingDeclaration, QualType BaseType,

diff  --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp
index 773c31ff3aec..3299a059c437 100644
--- a/clang/lib/Parse/ParseStmt.cpp
+++ b/clang/lib/Parse/ParseStmt.cpp
@@ -1348,6 +1348,8 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   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 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   //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 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
 // 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()) {

diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index a96ea1e69bcc..26d127e1262f 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -5759,7 +5759,7 @@ void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
   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));
@@ -5776,15 +5776,25 @@ void Sema::CodeCompleteAfterIf(Scope *S) {
   // "else" block
   CodeCompletionBuilder Builder(Results.getAllocator(),
 Results.getCodeCompletionTUInfo());
+
+  auto AddElseBodyPattern = [&] {
+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 {
+  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddPlaceholderChunk("statement");
+  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
+}
+  };
   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(CodeCompletionSt

[clang-tools-extra] c23ae3f - [clang-tidy][NFC] Use StringMap for ClangTidyCheckFactories::FacoryMap

2020-07-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-30T22:57:33+01:00
New Revision: c23ae3f18ee3ff11671f4c62ffc66d150b1bcdc2

URL: 
https://github.com/llvm/llvm-project/commit/c23ae3f18ee3ff11671f4c62ffc66d150b1bcdc2
DIFF: 
https://github.com/llvm/llvm-project/commit/c23ae3f18ee3ff11671f4c62ffc66d150b1bcdc2.diff

LOG: [clang-tidy][NFC] Use StringMap for ClangTidyCheckFactories::FacoryMap

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D84926

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidy.cpp
clang-tools-extra/clang-tidy/ClangTidyModule.cpp
clang-tools-extra/clang-tidy/ClangTidyModule.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index 63c83a0b9954e..90b39347bc9ac 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -449,8 +449,8 @@ ClangTidyASTConsumerFactory::CreateASTConsumer(
 std::vector ClangTidyASTConsumerFactory::getCheckNames() {
   std::vector CheckNames;
   for (const auto &CheckFactory : *CheckFactories) {
-if (Context.isCheckEnabled(CheckFactory.first))
-  CheckNames.push_back(CheckFactory.first);
+if (Context.isCheckEnabled(CheckFactory.getKey()))
+  CheckNames.emplace_back(CheckFactory.getKey());
   }
 
 #if CLANG_ENABLE_STATIC_ANALYZER

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyModule.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyModule.cpp
index e9031d498eeff..c72bcd3e188ce 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -18,15 +18,15 @@ namespace tidy {
 
 void ClangTidyCheckFactories::registerCheckFactory(StringRef Name,
CheckFactory Factory) {
-  Factories[std::string(Name)] = std::move(Factory);
+  Factories.insert_or_assign(Name, std::move(Factory));
 }
 
 std::vector>
 ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
-if (Context->isCheckEnabled(Factory.first))
-  Checks.emplace_back(Factory.second(Factory.first, Context));
+if (Context->isCheckEnabled(Factory.getKey()))
+  Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
   }
   return Checks;
 }

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyModule.h 
b/clang-tools-extra/clang-tidy/ClangTidyModule.h
index 31cf4774a885a..7fd16c2a7b3c7 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -69,7 +69,7 @@ class ClangTidyCheckFactories {
   std::vector>
   createChecks(ClangTidyContext *Context);
 
-  typedef std::map FactoryMap;
+  typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
   FactoryMap::const_iterator end() const { return Factories.end(); }
   bool empty() const { return Factories.empty(); }



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


[clang-tools-extra] 1fd2049 - [clang-tidy][NFC] Added convienence methods for getting optional options

2020-07-31 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-01T01:45:34+01:00
New Revision: 1fd2049e38daf0992f63883d68609b85dfb9cb26

URL: 
https://github.com/llvm/llvm-project/commit/1fd2049e38daf0992f63883d68609b85dfb9cb26
DIFF: 
https://github.com/llvm/llvm-project/commit/1fd2049e38daf0992f63883d68609b85dfb9cb26.diff

LOG: [clang-tidy][NFC] Added convienence methods for getting optional options

These methods abstract away Error handling when trying to read options that 
can't be parsed by logging the error automatically and returning None.

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D84812

Added: 


Modified: 
clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
clang-tools-extra/clang-tidy/ClangTidyCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
index 737d85e092d9..c99931e0aa3a 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -10,6 +10,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace clang {
@@ -126,7 +127,7 @@ bool ClangTidyCheck::OptionsView::get(StringRef 
LocalName,
   llvm::Expected ValueOr = get(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -145,7 +146,7 @@ bool 
ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName,
   llvm::Expected ValueOr = getLocalOrGlobal(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -204,13 +205,33 @@ llvm::Expected 
ClangTidyCheck::OptionsView::getEnumInt(
   Iter->getValue().Value);
 }
 
-void ClangTidyCheck::OptionsView::logErrToStdErr(llvm::Error &&Err) {
-  llvm::logAllUnhandledErrors(
-  llvm::handleErrors(std::move(Err),
- [](const MissingOptionError &) -> llvm::Error {
-   return llvm::Error::success();
- }),
-  llvm::errs(), "warning: ");
+void ClangTidyCheck::OptionsView::logIfOptionParsingError(llvm::Error &&Err) {
+  if (auto RemainingErrors =
+  llvm::handleErrors(std::move(Err), [](const MissingOptionError &) 
{}))
+llvm::logAllUnhandledErrors(std::move(RemainingErrors),
+llvm::WithColor::warning());
 }
+
+template <>
+Optional ClangTidyCheck::OptionsView::getOptional(
+StringRef LocalName) const {
+  if (auto ValueOr = get(LocalName))
+return *ValueOr;
+  else
+consumeError(ValueOr.takeError());
+  return llvm::None;
+}
+
+template <>
+Optional
+ClangTidyCheck::OptionsView::getOptionalLocalOrGlobal(
+StringRef LocalName) const {
+  if (auto ValueOr = getLocalOrGlobal(LocalName))
+return *ValueOr;
+  else
+consumeError(ValueOr.takeError());
+  return llvm::None;
+}
+
 } // namespace tidy
 } // namespace clang

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 4df8071c841e..6237e216656b 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -268,7 +268,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   if (llvm::Expected ValueOr = get(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -314,7 +314,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   if (llvm::Expected ValueOr = getLocalOrGlobal(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -353,7 +353,7 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   if (auto ValueOr = get(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -395,10 +395,35 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   if (auto ValueOr = getLocalOrGlobal(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
+/// Returns the value for the option \p LocalName represented as a ``T``.
+/// If the option is missing returns None, if the option can't be parsed
+/// as a ``T``, log that to st

[clang-tools-extra] 4888c9c - [clang-tidy] readability-identifier-naming checks configs for included files

2020-08-01 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-01T10:35:32+01:00
New Revision: 4888c9ce97d8c20d988212b10f1045e3c4022b8e

URL: 
https://github.com/llvm/llvm-project/commit/4888c9ce97d8c20d988212b10f1045e3c4022b8e
DIFF: 
https://github.com/llvm/llvm-project/commit/4888c9ce97d8c20d988212b10f1045e3c4022b8e.diff

LOG: [clang-tidy] readability-identifier-naming checks configs for included 
files

When checking for the style of a decl that isn't in the main file, the check 
will now search for the configuration that the included files uses to gather 
the style for its decls.

This can be useful to silence warnings in header files that follow a different 
naming convention without using header-filter to silence all warnings(even from 
other checks) in the header file.

Reviewed By: aaron.ballman, gribozavr2

Differential Revision: https://reviews.llvm.org/D84814

Added: 

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style-disabled/.clang-tidy

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style-disabled/header.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index c885aac89072..e004ce6fbd20 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "IdentifierNamingCheck.h"
 
+#include "../GlobList.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
@@ -15,7 +16,8 @@
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Error.h"
-#include "llvm/Support/Format.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
 
 #define DEBUG_TYPE "clang-tidy"
@@ -119,41 +121,47 @@ static StringRef const StyleNames[] = {
 #undef NAMING_KEYS
 // clang-format on
 
+static std::vector>
+getNamingStyles(const ClangTidyCheck::OptionsView &Options) {
+  std::vector> Styles;
+  Styles.reserve(StyleNames->size());
+  for (auto const &StyleName : StyleNames) {
+auto CaseOptional = Options.getOptional(
+(StyleName + "Case").str());
+auto Prefix = Options.get((StyleName + "Prefix").str(), "");
+auto Postfix = Options.get((StyleName + "Suffix").str(), "");
+
+if (CaseOptional || !Prefix.empty() || !Postfix.empty())
+  Styles.emplace_back(IdentifierNamingCheck::NamingStyle{
+  std::move(CaseOptional), std::move(Prefix), std::move(Postfix)});
+else
+  Styles.emplace_back(llvm::None);
+  }
+  return Styles;
+}
+
 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
  ClangTidyContext *Context)
-: RenamerClangTidyCheck(Name, Context),
+: RenamerClangTidyCheck(Name, Context), Context(Context), CheckName(Name),
+  GetConfigPerFile(Options.get("GetConfigPerFile", true)),
   IgnoreFailedSplit(Options.get("IgnoreFailedSplit", false)),
   IgnoreMainLikeFunctions(Options.get("IgnoreMainLikeFunctions", false)) {
 
-  for (auto const &Name : StyleNames) {
-auto CaseOptional = [&]() -> llvm::Optional {
-  auto ValueOr = Options.get((Name + "Case").str());
-  if (ValueOr)
-return *ValueOr;
-  llvm::logAllUnhandledErrors(
-  llvm::handleErrors(ValueOr.takeError(),
- [](const MissingOptionError &) -> llvm::Error {
-   return llvm::Error::success();
- }),
-  llvm::errs(), "warning: ");
-  return llvm::None;
-}();
-
-auto prefix = Options.get((Name + "Prefix").str(), "");
-auto postfix = Options.get((Name + "Suffix").str(), "");
-
-if (CaseOptional || !prefix.empty() || !postfix.empty()) {
-  NamingStyles.push_back(NamingStyle(CaseOptional, prefix, postfix));
-} else {
-  NamingStyles.push_back(llvm::None);
-}
-  }
+  auto IterAndInserted 

[clang-tools-extra] 9f21947 - [clang-tidy][NFC] Small refactor

2020-08-01 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-01T11:04:29+01:00
New Revision: 9f21947a331203ee2579db87f1d1ec22a949e20a

URL: 
https://github.com/llvm/llvm-project/commit/9f21947a331203ee2579db87f1d1ec22a949e20a
DIFF: 
https://github.com/llvm/llvm-project/commit/9f21947a331203ee2579db87f1d1ec22a949e20a.diff

LOG: [clang-tidy][NFC] Small refactor

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index e004ce6fbd20..e7fe25d8e221 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -162,17 +162,16 @@ void 
IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   RenamerClangTidyCheck::storeOptions(Opts);
   ArrayRef> NamingStyles =
   getStyleForFile(Context->getCurrentFile());
-  for (size_t i = 0; i < SK_Count; ++i) {
-if (NamingStyles[i]) {
-  if (NamingStyles[i]->Case) {
-Options.store(Opts, (StyleNames[i] + "Case").str(),
-  *NamingStyles[i]->Case);
-  }
-  Options.store(Opts, (StyleNames[i] + "Prefix").str(),
-NamingStyles[i]->Prefix);
-  Options.store(Opts, (StyleNames[i] + "Suffix").str(),
-NamingStyles[i]->Suffix);
-}
+  for (size_t I = 0; I < SK_Count; ++I) {
+if (!NamingStyles[I])
+  continue;
+if (NamingStyles[I]->Case)
+  Options.store(Opts, (StyleNames[I] + "Case").str(),
+*NamingStyles[I]->Case);
+Options.store(Opts, (StyleNames[I] + "Prefix").str(),
+  NamingStyles[I]->Prefix);
+Options.store(Opts, (StyleNames[I] + "Suffix").str(),
+  NamingStyles[I]->Suffix);
   }
   Options.store(Opts, "GetConfigPerFile", GetConfigPerFile);
   Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
@@ -191,14 +190,9 @@ static bool matchesStyle(StringRef Name,
   llvm::Regex("^[a-z]([a-z0-9]*(_[A-Z])?)*"),
   };
 
-  if (Name.startswith(Style.Prefix))
-Name = Name.drop_front(Style.Prefix.size());
-  else
+  if (!Name.consume_front(Style.Prefix))
 return false;
-
-  if (Name.endswith(Style.Suffix))
-Name = Name.drop_back(Style.Suffix.size());
-  else
+  if (!Name.consume_back(Style.Suffix))
 return false;
 
   // Ensure the name doesn't have any extra underscores beyond those specified
@@ -221,9 +215,10 @@ static std::string fixupWithCase(StringRef Name,
   Name.split(Substrs, "_", -1, false);
 
   SmallVector Words;
+  SmallVector Groups;
   for (auto Substr : Substrs) {
 while (!Substr.empty()) {
-  SmallVector Groups;
+  Groups.clear();
   if (!Splitter.match(Substr, &Groups))
 break;
 
@@ -241,12 +236,12 @@ static std::string fixupWithCase(StringRef Name,
   }
 
   if (Words.empty())
-return std::string(Name);
+return Name.str();
 
-  std::string Fixup;
+  SmallString<128> Fixup;
   switch (Case) {
   case IdentifierNamingCheck::CT_AnyCase:
-Fixup += Name;
+return Name.str();
 break;
 
   case IdentifierNamingCheck::CT_LowerCase:
@@ -267,7 +262,7 @@ static std::string fixupWithCase(StringRef Name,
 
   case IdentifierNamingCheck::CT_CamelCase:
 for (auto const &Word : Words) {
-  Fixup += Word.substr(0, 1).upper();
+  Fixup += toupper(Word.front());
   Fixup += Word.substr(1).lower();
 }
 break;
@@ -277,7 +272,7 @@ static std::string fixupWithCase(StringRef Name,
   if (&Word == &Words.front()) {
 Fixup += Word.lower();
   } else {
-Fixup += Word.substr(0, 1).upper();
+Fixup += toupper(Word.front());
 Fixup += Word.substr(1).lower();
   }
 }
@@ -287,7 +282,7 @@ static std::string fixupWithCase(StringRef Name,
 for (auto const &Word : Words) {
   if (&Word != &Words.front())
 Fixup += "_";
-  Fixup += Word.substr(0, 1).upper();
+  Fixup += toupper(Word.front());
   Fixup += Word.substr(1).lower();
 }
 break;
@@ -296,16 +291,16 @@ static std::string fixupWithCase(StringRef Name,
 for (auto const &Word : Words) {
   if (&Word != &Words.front()) {
 Fixup += "_";
-Fixup += Word.substr(0, 1).upper();
+Fixup += toupper(Word.front());
   } else {
-Fixup += Word.substr(0, 1).lower();
+Fixup += tolower(Word.front());
   }
   Fixup += Word.substr(1).lower();
 }
 break;
   }
 
-  return Fixup;
+  return Fixup.str().str();
 }
 
 static bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl,
@@ -715,8 +710,8 @@ RenamerClangTidyCheck::DiagInfo
 IdentifierNamingCheck::GetDiagInfo(const NamingCheckId &ID,
const NamingCheckFailure &Failure) const {
   return DiagInfo{"invali

[clang-tools-extra] 3b44b6c - [clang-tidy][NFC] Use correct size call for reserve

2020-08-03 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-04T00:31:19+01:00
New Revision: 3b44b6c900d1b71e6a6590e376d11dc303ac5159

URL: 
https://github.com/llvm/llvm-project/commit/3b44b6c900d1b71e6a6590e376d11dc303ac5159
DIFF: 
https://github.com/llvm/llvm-project/commit/3b44b6c900d1b71e6a6590e376d11dc303ac5159.diff

LOG: [clang-tidy][NFC] Use correct size call for reserve

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index e7fe25d8e221..c2a32474b2a8 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -124,7 +124,7 @@ static StringRef const StyleNames[] = {
 static std::vector>
 getNamingStyles(const ClangTidyCheck::OptionsView &Options) {
   std::vector> Styles;
-  Styles.reserve(StyleNames->size());
+  Styles.reserve(array_lengthof(StyleNames));
   for (auto const &StyleName : StyleNames) {
 auto CaseOptional = Options.getOptional(
 (StyleName + "Case").str());



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


[clang-tools-extra] 7c4782c - [clang-tidy] Fix regression in RenamerClangTidy

2020-08-04 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-04T09:27:01+01:00
New Revision: 7c4782ce91d66a8447a851362b99bb86a42b7c08

URL: 
https://github.com/llvm/llvm-project/commit/7c4782ce91d66a8447a851362b99bb86a42b7c08
DIFF: 
https://github.com/llvm/llvm-project/commit/7c4782ce91d66a8447a851362b99bb86a42b7c08.diff

LOG: [clang-tidy] Fix regression in RenamerClangTidy

See bug https://bugs.llvm.org/show_bug.cgi\?id\=46976

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 040378d980f1a..2d67ca4a16180 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -157,6 +157,9 @@ void RenamerClangTidyCheck::addUsage(
   RenamerClangTidyCheck::NamingCheckFailure &Failure =
   NamingCheckFailures[Decl];
 
+  if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
+return;
+
   if (!Failure.ShouldFix())
 return;
 
@@ -165,8 +168,6 @@ void RenamerClangTidyCheck::addUsage(
 
   if (!utils::rangeCanBeFixed(Range, SourceMgr))
 Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
-
-  Failure.RawUsageLocs.insert(FixLocation.getRawEncoding());
 }
 
 void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
index 24c1c4270dec8..fed362bbecdec 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -578,3 +578,8 @@ void Foo() {
 #undef M1
 #undef DUP
 } // namespace scratchspace
+
+template
+auto GetRes(type_t& Param) -> decltype(Param.res());
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: invalid case style for parameter 
'Param'
+// CHECK-FIXES: auto GetRes(type_t& a_param) -> decltype(a_param.res());



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


[clang-tools-extra] 01bc708 - [NFC] Replace hasName in loop for hasAnyName

2020-08-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-07T10:22:45+01:00
New Revision: 01bc708126c55c94495d0b55cb2003f67b9b24bf

URL: 
https://github.com/llvm/llvm-project/commit/01bc708126c55c94495d0b55cb2003f67b9b24bf
DIFF: 
https://github.com/llvm/llvm-project/commit/01bc708126c55c94495d0b55cb2003f67b9b24bf.diff

LOG: [NFC] Replace hasName in loop for hasAnyName

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index ecdef6a1bc68..04dc61f02df1 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -119,16 +119,11 @@ AST_MATCHER_P(QualType, isSugarFor, Matcher, 
SugarMatcher) {
 /// \endcode
 ///
 /// namedDecl(hasStdIteratorName()) matches \c I and \c CI.
-AST_MATCHER(NamedDecl, hasStdIteratorName) {
-  static const char *const IteratorNames[] = {"iterator", "reverse_iterator",
-  "const_iterator",
-  "const_reverse_iterator"};
-
-  for (const char *Name : IteratorNames) {
-if (hasName(Name).matches(Node, Finder, Builder))
-  return true;
-  }
-  return false;
+Matcher hasStdIteratorName() {
+  static const StringRef IteratorNames[] = {"iterator", "reverse_iterator",
+"const_iterator",
+"const_reverse_iterator"};
+  return hasAnyName(IteratorNames);
 }
 
 /// Matches named declarations that have one of the standard container
@@ -143,26 +138,21 @@ AST_MATCHER(NamedDecl, hasStdIteratorName) {
 ///
 /// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list
 /// but not \c my_vec.
-AST_MATCHER(NamedDecl, hasStdContainerName) {
-  static const char *const ContainerNames[] = {
-  "array", "deque",
-  "forward_list",  "list",
-  "vector",
+Matcher hasStdContainerName() {
+  static StringRef ContainerNames[] = {"array", "deque",
+   "forward_list",  "list",
+   "vector",
 
-  "map",   "multimap",
-  "set",   "multiset",
+   "map",   "multimap",
+   "set",   "multiset",
 
-  "unordered_map", "unordered_multimap",
-  "unordered_set", "unordered_multiset",
+   "unordered_map", "unordered_multimap",
+   "unordered_set", "unordered_multiset",
 
-  "queue", "priority_queue",
-  "stack"};
+   "queue", "priority_queue",
+   "stack"};
 
-  for (const char *Name : ContainerNames) {
-if (hasName(Name).matches(Node, Finder, Builder))
-  return true;
-  }
-  return false;
+  return hasAnyName(ContainerNames);
 }
 
 /// Matches declarations whose declaration context is the C++ standard library



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


[clang-tools-extra] 8c9ffe3 - [NFC][clang-tidy] Put abseil headers in alphabetical order

2020-08-18 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-08-18T15:52:47+01:00
New Revision: 8c9ffe34d932e2e17cbcf351d6e37783ea5453ae

URL: 
https://github.com/llvm/llvm-project/commit/8c9ffe34d932e2e17cbcf351d6e37783ea5453ae
DIFF: 
https://github.com/llvm/llvm-project/commit/8c9ffe34d932e2e17cbcf351d6e37783ea5453ae.diff

LOG: [NFC][clang-tidy] Put abseil headers in alphabetical order

Added: 


Modified: 
clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h 
b/clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h
index f58ff5bc44b2..335c333573f4 100644
--- a/clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h
+++ b/clang-tools-extra/clang-tidy/abseil/AbseilMatcher.h
@@ -47,14 +47,18 @@ AST_POLYMORPHIC_MATCHER(
   if (PrefixPosition == StringRef::npos)
 return false;
   Path = Path.drop_front(PrefixPosition + AbslPrefix.size());
-  static const char *AbseilLibraries[] = {
-  "algorithm", "base", "container",   "debugging", "flags",
-  "hash",  "iterator", "memory",  "meta",  "numeric",
-  "random","strings",  "synchronization", "status","time",
-  "types", "utility"};
-  return std::any_of(
-  std::begin(AbseilLibraries), std::end(AbseilLibraries),
-  [&](const char *Library) { return Path.startswith(Library); });
+  static const char *AbseilLibraries[] = {"algorithm", "base",
+  "container", "debugging",
+  "flags", "hash",
+  "iterator",  "memory",
+  "meta",  "numeric",
+  "random","status",
+  "strings",   "synchronization",
+  "time",  "types",
+  "utility"};
+  return llvm::any_of(AbseilLibraries, [&](const char *Library) {
+return Path.startswith(Library);
+  });
 }
 
 } // namespace ast_matchers



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


[clang-tools-extra] 82ddae0 - [clang-tidy] RenamerClangTidy now renames dependent member expr when the member can be resolved

2020-05-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-09T16:21:49+01:00
New Revision: 82ddae061b4ba11895756004d559160cbd519fff

URL: 
https://github.com/llvm/llvm-project/commit/82ddae061b4ba11895756004d559160cbd519fff
DIFF: 
https://github.com/llvm/llvm-project/commit/82ddae061b4ba11895756004d559160cbd519fff.diff

LOG: [clang-tidy] RenamerClangTidy now renames dependent member expr when the 
member can be resolved

Summary:
Sometimes in templated code Member references are reported as 
`DependentScopeMemberExpr` because that's what the standard dictates, however 
in many trivial cases it is easy to resolve the reference to its actual Member.
Take this code:
```
template
class A{
  int value;
  A& operator=(const A& Other){
value = Other.value;
this->value = Other.value;
return *this;
  }
};
```
When ran with `clang-tidy file.cpp -checks=readability-identifier-naming 
--config="{CheckOptions: [{key: readability-identifier-naming.MemberPrefix, 
value: m_}]}" -fix`
Current behaviour:
```
template
class A{
  int m_value;
  A& operator=(const A& Other){
m_value = Other.value;
this->value = Other.value;
return *this;
  }
};
```
As `this->value` and `Other.value` are Dependent they are ignored when creating 
the fix-its, however this can easily be resolved.
Proposed behaviour:
```
template
class A{
  int m_value;
  A& operator=(const A& Other){
m_value = Other.m_value;
this->m_value = Other.m_value;
return *this;
  }
};
```

Reviewers: aaron.ballman, JonasToth, alexfh, hokein, gribozavr2

Reviewed By: aaron.ballman

Subscribers: merge_guards_bot, xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra

Differential Revision: https://reviews.llvm.org/D73052

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
index d562d8c3d213..9619524a0c03 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp
@@ -47,6 +47,7 @@ ReservedIdentifierCheck::ReservedIdentifierCheck(StringRef 
Name,
   Options.get("AllowedIdentifiers", ""))) {}
 
 void ReservedIdentifierCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  RenamerClangTidyCheck::storeOptions(Opts);
   Options.store(Opts, "Invert", Invert);
   Options.store(Opts, "AllowedIdentifiers",
 utils::options::serializeStringList(AllowedIdentifiers));

diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 9146e7356c9c..7c7de74a0c9e 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -170,6 +170,7 @@ IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
 IdentifierNamingCheck::~IdentifierNamingCheck() = default;
 
 void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  RenamerClangTidyCheck::storeOptions(Opts);
   for (size_t i = 0; i < SK_Count; ++i) {
 if (NamingStyles[i]) {
   if (NamingStyles[i]->Case) {

diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 3523cf5dcf16..d8bdbcc8c25e 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -14,8 +14,7 @@
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMapInfo.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/Format.h"
+#include "llvm/ADT/PointerIntPair.h"
 
 #define DEBUG_TYPE "clang-tidy"
 
@@ -93,9 +92,16 @@ class RenamerClangTidyCheckPPCallbacks : public PPCallbacks {
 
 RenamerClangTidyCheck::RenamerClangTidyCheck(StringRef CheckName,
  ClangTidyContext *Context)
-: ClangTidyCheck(CheckName, Context) {}
+: ClangTidyCheck(CheckName, Context),
+  AggressiveDependentMemberLookup(
+  Options.getLocalOrGlobal("AggressiveDependentMemberLookup", false)) 
{}
 RenamerClangTidyCheck::~RenamerClangTidyCheck() = default;
 
+void RenamerClangTidyCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "AggressiveDependentMemberL

[clang-tools-extra] 0e49ac7 - [NFC] Small rework to RenamerClangTidyCheck addUsage

2020-05-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-09T18:57:05+01:00
New Revision: 0e49ac73eaf554ad4135f51b03ea4eadaebf0466

URL: 
https://github.com/llvm/llvm-project/commit/0e49ac73eaf554ad4135f51b03ea4eadaebf0466
DIFF: 
https://github.com/llvm/llvm-project/commit/0e49ac73eaf554ad4135f51b03ea4eadaebf0466.diff

LOG: [NFC] Small rework to RenamerClangTidyCheck addUsage

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index d8bdbcc8c25e..56a4c08b7cbc 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -127,9 +127,9 @@ void RenamerClangTidyCheck::registerPPCallbacks(
  this));
 }
 
-static void addUsage(RenamerClangTidyCheck::NamingCheckFailureMap &Failures,
- const RenamerClangTidyCheck::NamingCheckId &Decl,
- SourceRange Range, SourceManager *SourceMgr = nullptr) {
+void RenamerClangTidyCheck::addUsage(
+const RenamerClangTidyCheck::NamingCheckId &Decl, SourceRange Range,
+SourceManager *SourceMgr) {
   // Do nothing if the provided range is invalid.
   if (Range.isInvalid())
 return;
@@ -146,7 +146,8 @@ static void 
addUsage(RenamerClangTidyCheck::NamingCheckFailureMap &Failures,
 
   // Try to insert the identifier location in the Usages map, and bail out if 
it
   // is already in there
-  RenamerClangTidyCheck::NamingCheckFailure &Failure = Failures[Decl];
+  RenamerClangTidyCheck::NamingCheckFailure &Failure =
+  NamingCheckFailures[Decl];
   if (!Failure.RawUsageLocs.insert(FixLocation.getRawEncoding()).second)
 return;
 
@@ -157,12 +158,10 @@ static void 
addUsage(RenamerClangTidyCheck::NamingCheckFailureMap &Failures,
 Failure.FixStatus = RenamerClangTidyCheck::ShouldFixStatus::InsideMacro;
 }
 
-/// Convenience method when the usage to be added is a NamedDecl
-static void addUsage(RenamerClangTidyCheck::NamingCheckFailureMap &Failures,
- const NamedDecl *Decl, SourceRange Range,
- SourceManager *SourceMgr = nullptr) {
-  return addUsage(Failures,
-  RenamerClangTidyCheck::NamingCheckId(Decl->getLocation(),
+void RenamerClangTidyCheck::addUsage(const NamedDecl *Decl, SourceRange Range,
+ SourceManager *SourceMgr) {
+
+  return addUsage(RenamerClangTidyCheck::NamingCheckId(Decl->getLocation(),

Decl->getNameAsString()),
   Range, SourceMgr);
 }
@@ -243,15 +242,13 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   if (const auto *Decl =
   Result.Nodes.getNodeAs("classRef")) {
 
-addUsage(NamingCheckFailures, Decl->getParent(),
- Decl->getNameInfo().getSourceRange());
+addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange());
 
 for (const auto *Init : Decl->inits()) {
   if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
   if (const FieldDecl *FD = Init->getAnyMember())
-addUsage(NamingCheckFailures, FD,
- SourceRange(Init->getMemberLocation()));
+addUsage(FD, SourceRange(Init->getMemberLocation()));
   // Note: delegating constructors and base class initializers are handled
   // via the "typeLoc" matcher.
 }
@@ -268,7 +265,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 // we want instead to replace the next token, that will be the identifier.
 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
 
-addUsage(NamingCheckFailures, Decl->getParent(), Range);
+addUsage(Decl->getParent(), Range);
 return;
   }
 
@@ -286,7 +283,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 // further TypeLocs handled below
 
 if (Decl) {
-  addUsage(NamingCheckFailures, Decl, Loc->getSourceRange());
+  addUsage(Decl, Loc->getSourceRange());
   return;
 }
 
@@ -297,7 +294,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
   SourceRange Range(Ref.getTemplateNameLoc(), Ref.getTemplateNameLoc());
   if (const auto *ClassDecl = dyn_cast(Decl)) {
 if (const NamedDecl *TemplDecl = ClassDecl->getTemplatedDecl())
-  addUsage(NamingCheckFailures, TemplDecl, Range);
+  addUsage(TemplDecl, Range);
 return;
   }
 }
@@ -305,7 +302,7 @@ void RenamerClangTidyCheck::check(const 
MatchFinder::MatchResult &Result) {
 if (const auto &Ref =
 Loc->getAs()) {
   if (const TagD

[clang-tools-extra] aef778d - [clang-tidy] Fix assertion in RenamerClangTidyChecks

2020-05-15 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-15T12:15:35+01:00
New Revision: aef778d4d38e45fd413e7e95919fbb72cde42488

URL: 
https://github.com/llvm/llvm-project/commit/aef778d4d38e45fd413e7e95919fbb72cde42488
DIFF: 
https://github.com/llvm/llvm-project/commit/aef778d4d38e45fd413e7e95919fbb72cde42488.diff

LOG: [clang-tidy] Fix assertion in RenamerClangTidyChecks

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
index 56a4c08b7cbc..dd05b3a45c0d 100644
--- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -207,6 +207,8 @@ class NameLookup {
 /// flag indicating the multiple resolutions.
 NameLookup findDeclInBases(const CXXRecordDecl &Parent, StringRef DeclName,
bool AggressiveTemplateLookup) {
+  if (!Parent.hasDefinition())
+return NameLookup(nullptr);
   if (const NamedDecl *InClassRef = findDecl(Parent, DeclName))
 return NameLookup(InClassRef);
   const NamedDecl *Found = nullptr;



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


[clang-tools-extra] 7af0c85 - [clang-tidy] Transformer checks now store IncludeStyle option

2020-05-15 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-16T01:14:55+01:00
New Revision: 7af0c8559b6d9426dd5e977370516d2baa4c206f

URL: 
https://github.com/llvm/llvm-project/commit/7af0c8559b6d9426dd5e977370516d2baa4c206f
DIFF: 
https://github.com/llvm/llvm-project/commit/7af0c8559b6d9426dd5e977370516d2baa4c206f.diff

LOG: [clang-tidy] Transformer checks now store IncludeStyle option

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
index 3f7edd659c63..a15c429b696f 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -112,6 +112,12 @@ void TransformerClangTidyCheck::check(
   }
 }
 
+void TransformerClangTidyCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeStyle", IncludeStyle,
+IncludeSorter::getMapping());
+}
+
 } // namespace utils
 } // namespace tidy
 } // namespace clang

diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
index 796222373eb5..d99f927a7973 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -67,6 +67,10 @@ class TransformerClangTidyCheck : public ClangTidyCheck {
   void registerMatchers(ast_matchers::MatchFinder *Finder) final;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) final;
 
+  /// Derived classes that override this function should call this method from
+  /// the overridden method.
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+
 private:
   Optional Rule;
   const IncludeSorter::IncludeStyle IncludeStyle;



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


[clang] 74bcb00 - [ASTMatchers] Added BinaryOperator hasOperands matcher

2020-05-17 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-17T19:54:14+01:00
New Revision: 74bcb00e00f3ef971e4c584a124e99289f2ebf34

URL: 
https://github.com/llvm/llvm-project/commit/74bcb00e00f3ef971e4c584a124e99289f2ebf34
DIFF: 
https://github.com/llvm/llvm-project/commit/74bcb00e00f3ef971e4c584a124e99289f2ebf34.diff

LOG: [ASTMatchers] Added BinaryOperator hasOperands matcher

Summary: Adds a matcher called `hasOperands` for `BinaryOperator`'s when you 
need to match both sides but the order isn't important, usually on commutative 
operators.

Reviewers: klimek, aaron.ballman, gribozavr2, alexfh

Reviewed By: aaron.ballman

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D80054

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index f5106f0e0ba2..f57352389e4c 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -5033,6 +5033,18 @@ AST Traversal Matchers
 
 
 
+MatcherBinaryOperator>hasOperandsMatcherExpr>  
Matcher1, MatcherExpr>  
Matcher2
+Matches if both 
matchers match with opposite sides of the binary operator.
+
+Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
+ integerLiteral(equals(2)))
+  1 + 2 // Match
+  2 + 1 // Match
+  1 + 1 // No match
+  2 + 2 // No match
+
+
+
 MatcherBinaryOperator>hasRHSMatcherExpr> 
InnerMatcher
 Matches the right hand side 
of binary operator expressions.
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index ce702bc44edd..460962d9e73b 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -4869,6 +4869,23 @@ inline internal::Matcher 
hasEitherOperand(
   return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
 }
 
+/// Matches if both matchers match with opposite sides of the binary operator.
+///
+/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
+///  integerLiteral(equals(2)))
+/// \code
+///   1 + 2 // Match
+///   2 + 1 // Match
+///   1 + 1 // No match
+///   2 + 2 // No match
+/// \endcode
+inline internal::Matcher
+hasOperands(const internal::Matcher &Matcher1,
+const internal::Matcher &Matcher2) {
+  return anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
+   allOf(hasLHS(Matcher2), hasRHS(Matcher1)));
+}
+
 /// Matches if the operand of a unary operator matches.
 ///
 /// Example matches true (matcher = hasUnaryOperand(

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index e7659feaf1e9..0a7d09e55c88 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -294,6 +294,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(hasName);
   REGISTER_MATCHER(hasNullSelector);
   REGISTER_MATCHER(hasObjectExpression);
+  REGISTER_MATCHER(hasOperands);
   REGISTER_MATCHER(hasOperatorName);
   REGISTER_MATCHER(hasOverloadedOperatorName);
   REGISTER_MATCHER(hasParameter);

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 2972fc91b908..0c9a3d9eb1ed 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -1160,6 +1160,17 @@ TEST(MatchBinaryOperator, HasEitherOperand) {
   EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
 }
 
+TEST(MatchBinaryOperator, HasOperands) {
+  StatementMatcher HasOperands = binaryOperator(
+  hasOperands(integerLiteral(equals(1)), integerLiteral(equals(2;
+  EXPECT_TRUE(matches("void x() { 1 + 2; }", HasOperands));
+  EXPECT_TRUE(matches("void x() { 2 + 1; }", HasOperands));
+  EXPECT_TRUE(notMatches("void x() { 1 + 1; }", HasOperands));
+  EXPECT_TRUE(notMatches("void x() { 2 + 2; }", HasOperands));
+  EXPECT_TRUE(notMatches("void x() { 0 + 0; }", HasOperands));
+  EXPECT_TRUE(notMatches("void x() { 0 + 1; }", HasOperands));
+}
+
 TEST(Matcher, BinaryOperatorTypes) {
   // Integration test that verifies the AST provides all binary operators in
   // a way we expect.



___
cfe-com

[clang-tools-extra] 4f0cc10 - [NFC][clang-tidy] use hasOperands in place of hasEitherOperand

2020-05-18 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-05-18T10:11:22+01:00
New Revision: 4f0cc10bf5d0009a9d00565fedb34933c2adf8f6

URL: 
https://github.com/llvm/llvm-project/commit/4f0cc10bf5d0009a9d00565fedb34933c2adf8f6
DIFF: 
https://github.com/llvm/llvm-project/commit/4f0cc10bf5d0009a9d00565fedb34933c2adf8f6.diff

LOG: [NFC][clang-tidy] use hasOperands in place of hasEitherOperand

Added: 


Modified: 
clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp
clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp 
b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
index 513714e99cb8..9539e28cd790 100644
--- a/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
+++ b/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
@@ -52,8 +52,8 @@ void StringFindStartswithCheck::registerMatchers(MatchFinder 
*Finder) {
   // Match [=!]= with a zero on one side and a string.find on the other.
   binaryOperator(
   hasAnyOperatorName("==", "!="),
-  hasEitherOperand(ignoringParenImpCasts(ZeroLiteral)),
-  hasEitherOperand(ignoringParenImpCasts(StringFind.bind("findexpr"
+  hasOperands(ignoringParenImpCasts(ZeroLiteral),
+  ignoringParenImpCasts(StringFind.bind("findexpr"
   .bind("expr"),
   this);
 }

diff  --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index ecaee65b2ea6..39526dab79ae 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -163,10 +163,10 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
   if (WarnOnSizeOfCompareToConstant) {
 Finder->addMatcher(
 binaryOperator(matchers::isRelationalOperator(),
-   hasEitherOperand(ignoringParenImpCasts(SizeOfExpr)),
-   hasEitherOperand(ignoringParenImpCasts(
-   anyOf(integerLiteral(equals(0)),
- integerLiteral(isBiggerThan(0x8))
+   hasOperands(ignoringParenImpCasts(SizeOfExpr),
+   ignoringParenImpCasts(anyOf(
+   integerLiteral(equals(0)),
+   
integerLiteral(isBiggerThan(0x8))
 .bind("sizeof-compare-constant"),
 this);
   }
@@ -205,10 +205,11 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 
   Finder->addMatcher(
   binaryOperator(hasOperatorName("*"),
- hasEitherOperand(ignoringParenImpCasts(SizeOfExpr)),
- hasEitherOperand(ignoringParenImpCasts(binaryOperator(
- hasOperatorName("*"),
- 
hasEitherOperand(ignoringParenImpCasts(SizeOfExpr))
+ hasOperands(ignoringParenImpCasts(SizeOfExpr),
+ ignoringParenImpCasts(binaryOperator(
+ hasOperatorName("*"),
+ hasEitherOperand(
+ ignoringParenImpCasts(SizeOfExpr))
   .bind("sizeof-multiply-sizeof"),
   this);
 
@@ -232,12 +233,12 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
   Finder->addMatcher(
   binaryOperator(
   hasAnyOperatorName("==", "!=", "<", "<=", ">", ">=", "+", "-"),
-  hasEitherOperand(expr(anyOf(
-  ignoringParenImpCasts(SizeOfExpr),
-  ignoringParenImpCasts(binaryOperator(
-  hasOperatorName("*"),
-  hasEitherOperand(ignoringParenImpCasts(SizeOfExpr))),
-  hasEitherOperand(ignoringParenImpCasts(PtrDiffExpr)))
+  hasOperands(expr(anyOf(ignoringParenImpCasts(SizeOfExpr),
+ ignoringParenImpCasts(binaryOperator(
+ hasOperatorName("*"),
+ hasEitherOperand(
+ 
ignoringParenImpCasts(SizeOfExpr)),
+  ignoringParenImpCasts(PtrDiffExpr)))
   .bind("sizeof-in-ptr-arithmetic-mul"),
   this);
 

diff  --git 
a/clang-tools-extr

[clang-tools-extra] 69c20a1 - [clang-tidy] Move bugprone-assignment-in-if-condition check to correct folder

2022-08-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-27T11:24:57+01:00
New Revision: 69c20a1f49aa5e19ed8ad291598caa1ec3b4d8f5

URL: 
https://github.com/llvm/llvm-project/commit/69c20a1f49aa5e19ed8ad291598caa1ec3b4d8f5
DIFF: 
https://github.com/llvm/llvm-project/commit/69c20a1f49aa5e19ed8ad291598caa1ec3b4d8f5.diff

LOG: [clang-tidy] Move bugprone-assignment-in-if-condition check to correct 
folder

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp

Modified: 


Removed: 

clang-tools-extra/test/clang-tidy/checkers/bugprone-assignment-in-if-condition.cpp



diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-assignment-in-if-condition.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp
similarity index 100%
rename from 
clang-tools-extra/test/clang-tidy/checkers/bugprone-assignment-in-if-condition.cpp
rename to 
clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp



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


[clang-tools-extra] 6bd98b4 - [clang-tidy] Fix a false positive in bugprone-assignment-in-if-condition

2022-08-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-27T19:55:08+01:00
New Revision: 6bd98b4f2df02955b72343038ecf20cdfd23e01e

URL: 
https://github.com/llvm/llvm-project/commit/6bd98b4f2df02955b72343038ecf20cdfd23e01e
DIFF: 
https://github.com/llvm/llvm-project/commit/6bd98b4f2df02955b72343038ecf20cdfd23e01e.diff

LOG: [clang-tidy] Fix a false positive in bugprone-assignment-in-if-condition

Fixed a false positive where a lambda expression in the condition which 
contained an assignement would trigger a warning.
Fixes #56729

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D132786

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
index e4f52191e0b00..590505c1f47ba 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
@@ -17,23 +17,50 @@ namespace tidy {
 namespace bugprone {
 
 void AssignmentInIfConditionCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(ifStmt(hasCondition(forEachDescendant(
- binaryOperator(isAssignmentOperator())
- .bind("assignment_in_if_statement",
- this);
-  Finder->addMatcher(ifStmt(hasCondition(forEachDescendant(
- cxxOperatorCallExpr(isAssignmentOperator())
- .bind("assignment_in_if_statement",
- this);
+  Finder->addMatcher(translationUnitDecl(), this);
 }
 
 void AssignmentInIfConditionCheck::check(
-const MatchFinder::MatchResult &Result) {
-  const auto *MatchedDecl =
-  Result.Nodes.getNodeAs("assignment_in_if_statement");
-  if (!MatchedDecl) {
-return;
-  }
+const ast_matchers::MatchFinder::MatchResult &Result) {
+  class Visitor : public RecursiveASTVisitor {
+AssignmentInIfConditionCheck &Check;
+
+  public:
+explicit Visitor(AssignmentInIfConditionCheck &Check) : Check(Check) {}
+bool VisitIfStmt(IfStmt *If) {
+  class ConditionVisitor : public RecursiveASTVisitor {
+AssignmentInIfConditionCheck &Check;
+
+  public:
+explicit ConditionVisitor(AssignmentInIfConditionCheck &Check)
+: Check(Check) {}
+
+// Dont traverse into any lambda expressions.
+bool TraverseLambdaExpr(LambdaExpr *, DataRecursionQueue * = nullptr) {
+  return true;
+}
+
+bool VisitBinaryOperator(BinaryOperator *BO) {
+  if (BO->isAssignmentOp())
+Check.report(BO);
+  return true;
+}
+
+bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *OCE) {
+  if (OCE->isAssignmentOp())
+Check.report(OCE);
+  return true;
+}
+  };
+
+  ConditionVisitor(Check).TraverseStmt(If->getCond());
+  return true;
+}
+  };
+  Visitor(*this).TraverseAST(*Result.Context);
+}
+
+void AssignmentInIfConditionCheck::report(const Expr *MatchedDecl) {
   diag(MatchedDecl->getBeginLoc(),
"an assignment within an 'if' condition is bug-prone");
   diag(MatchedDecl->getBeginLoc(),

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
index 8e57f1a7ca80d..f84ae93ed2ebf 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
@@ -25,6 +25,7 @@ class AssignmentInIfConditionCheck : public ClangTidyCheck {
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void report(const Expr *E);
 };
 
 } // namespace bugprone

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1656debda1368..1734f4acf6865 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -116,6 +116,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Fixed a false positive in :doc:`bugprone-assignment-in-if-condition
+  ` check when there
+  was an assignement in a lambda found in the condition of an ``if``.
+
 - Improved :doc:`bugprone-signal-handler
   ` check. Partial
   support for C++14 signal handler rules was added. Bug report generation was

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-i

[clang-tools-extra] 2a0870c - [clang-tidy] Add missing header from 6bd98b4f2d

2022-08-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-27T19:59:16+01:00
New Revision: 2a0870c9d38d034b39d7cfa2a9929ff2819ecebd

URL: 
https://github.com/llvm/llvm-project/commit/2a0870c9d38d034b39d7cfa2a9929ff2819ecebd
DIFF: 
https://github.com/llvm/llvm-project/commit/2a0870c9d38d034b39d7cfa2a9929ff2819ecebd.diff

LOG: [clang-tidy] Add missing header from 6bd98b4f2d

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
index 590505c1f47b..05f0ae74282e 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "AssignmentInIfConditionCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 
 using namespace clang::ast_matchers;



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


[clang-tools-extra] 32d8823 - [clang-tidy] Tweak diagnostics for bugprone-assign-in-if-condition

2022-08-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-28T00:21:40+01:00
New Revision: 32d88239ae654239f16b516ee81ee9ff88b0ce07

URL: 
https://github.com/llvm/llvm-project/commit/32d88239ae654239f16b516ee81ee9ff88b0ce07
DIFF: 
https://github.com/llvm/llvm-project/commit/32d88239ae654239f16b516ee81ee9ff88b0ce07.diff

LOG: [clang-tidy] Tweak diagnostics for bugprone-assign-in-if-condition

Currently the diagnostic is printed at the start of the assignment expression, 
This can be misleading.
Having the location for the diagnostic be the location of the assignment 
operator is much more intuitive.

Reviewed By: gribozavr2

Differential Revision: https://reviews.llvm.org/D132795

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h

clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
index 05f0ae74282e..47a82e3c09e2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.cpp
@@ -61,14 +61,18 @@ void AssignmentInIfConditionCheck::check(
   Visitor(*this).TraverseAST(*Result.Context);
 }
 
-void AssignmentInIfConditionCheck::report(const Expr *MatchedDecl) {
-  diag(MatchedDecl->getBeginLoc(),
-   "an assignment within an 'if' condition is bug-prone");
-  diag(MatchedDecl->getBeginLoc(),
+void AssignmentInIfConditionCheck::report(const Expr *AssignmentExpr) {
+  SourceLocation OpLoc =
+  isa(AssignmentExpr)
+  ? cast(AssignmentExpr)->getOperatorLoc()
+  : cast(AssignmentExpr)->getOperatorLoc();
+
+  diag(OpLoc, "an assignment within an 'if' condition is bug-prone")
+  << AssignmentExpr->getSourceRange();
+  diag(OpLoc,
"if it should be an assignment, move it out of the 'if' condition",
DiagnosticIDs::Note);
-  diag(MatchedDecl->getBeginLoc(),
-   "if it is meant to be an equality check, change '=' to '=='",
+  diag(OpLoc, "if it is meant to be an equality check, change '=' to '=='",
DiagnosticIDs::Note);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
index f84ae93ed2eb..f49dda24c9a9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/AssignmentInIfConditionCheck.h
@@ -25,7 +25,7 @@ class AssignmentInIfConditionCheck : public ClangTidyCheck {
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
-  void report(const Expr *E);
+  void report(const Expr *AssignmentExpr);
 };
 
 } // namespace bugprone

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp
index 20c30d73516b..ad0d360d99fe 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assignment-in-if-condition.cpp
@@ -3,7 +3,7 @@
 void f(int arg) {
   int f = 3;
   if ((f = arg) || (f == (arg + 1)))
-  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
   {
 f = 5;
   }
@@ -12,7 +12,7 @@ void f(int arg) {
 void f1(int arg) {
   int f = 3;
   if ((f == arg) || (f = (arg + 1)))
-  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
   {
 f = 5;
   }
@@ -21,7 +21,7 @@ void f1(int arg) {
 void f2(int arg) {
   int f = 3;
   if (f = arg)
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
   {
 f = 5;
   }
@@ -32,7 +32,7 @@ volatile int v = 32;
 void f3(int arg) {
   int f = 3;
   if ((f == arg) || ((arg + 6 < f) && (f = v)))
-  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: an assignment within an 'if' 
condition is bug-prone [bugprone-assignment-in-if-condition]
+  // CHECK-MESSAGES: :[[@LINE-1]]:42: warni

[clang-tools-extra] 495d984 - [clang-tidy] Fix modernize-use-emplace to support alias cases

2022-08-31 Thread Nathan James via cfe-commits

Author: corona10
Date: 2022-08-31T10:21:10+01:00
New Revision: 495d984e14bd8367017ffdea8183840c8267cbbf

URL: 
https://github.com/llvm/llvm-project/commit/495d984e14bd8367017ffdea8183840c8267cbbf
DIFF: 
https://github.com/llvm/llvm-project/commit/495d984e14bd8367017ffdea8183840c8267cbbf.diff

LOG: [clang-tidy] Fix modernize-use-emplace to support alias cases

Fix modernize-use-emplace to support alias cases

Reviewed By: njames93

Differential Revision: https://reviews.llvm.org/D132640

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index abf5ba918d89f..1b7853d781ce9 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -134,22 +134,25 @@ void UseEmplaceCheck::registerMatchers(MatchFinder 
*Finder) {
   // + match for emplace calls that should be replaced with insertion
   auto CallPushBack = cxxMemberCallExpr(
   hasDeclaration(functionDecl(hasName("push_back"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPushBack);
+  on(hasType(hasCanonicalType(
+  
hasDeclaration(cxxRecordDecl(hasAnyName(ContainersWithPushBack)));
 
-  auto CallPush = cxxMemberCallExpr(
-  hasDeclaration(functionDecl(hasName("push"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPush);
+  auto CallPush =
+  cxxMemberCallExpr(hasDeclaration(functionDecl(hasName("push"))),
+on(hasType(hasCanonicalType(hasDeclaration(
+cxxRecordDecl(hasAnyName(ContainersWithPush)));
 
   auto CallPushFront = cxxMemberCallExpr(
   hasDeclaration(functionDecl(hasName("push_front"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPushFront);
+  on(hasType(hasCanonicalType(hasDeclaration(
+  cxxRecordDecl(hasAnyName(ContainersWithPushFront)));
 
   auto CallEmplacy = cxxMemberCallExpr(
   hasDeclaration(
   functionDecl(hasAnyNameIgnoringTemplates(EmplacyFunctions))),
-  on(hasType(cxxRecordDecl(has(typedefNameDecl(
+  on(hasType(hasCanonicalType(hasDeclaration(has(typedefNameDecl(
   hasName("value_type"), hasType(type(hasUnqualifiedDesugaredType(
- recordType().bind("value_type"));
+ recordType().bind("value_type")));
 
   // We can't replace push_backs of smart pointer because
   // if emplacement fails (f.e. bad_alloc in vector) we will have leak of

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1734f4acf6865..9bd3a5fc799cf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -129,13 +129,17 @@ Changes in existing checks
   ` when warnings
   would be emitted for uninitialized members of an anonymous union despite
   there being an initializer for one of the other members.
-  
+
 - Improved `modernize-use-emplace 
`_ check.
 
   The check now supports detecting inefficient invocations of ``push`` and
   ``push_front`` on STL-style containers and replacing them with ``emplace``
   or ``emplace_front``.
 
+  The check now supports detecting alias cases of ``push_back`` ``push`` and
+  ``push_front`` on STL-style containers and replacing them with 
``emplace_back``,
+  ``emplace`` or ``emplace_front``.
+
 - Improved `modernize-use-equals-default 
`_ check.
 
   The check now skips unions since in this case a default constructor with 
empty body

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
index 29ba88117b5f7..04ff0775d285c 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
@@ -1061,6 +1061,82 @@ void testAllSTLEmplacyFunctions() {
   // CHECK-FIXES: priority_queue.emplace(13);
 }
 
+void test_AliasEmplacyFunctions() {
+  typedef std::list L;
+  using DQ = std::deque;
+  L l;
+  l.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unnecessary temporary object 
created while calling emplace_back
+  // CHECK-FIXES: l.emplace_back(3);
+
+  DQ dq;
+  dq.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: unnecessary temporary object 
created while calling emplace_back
+  // CHECK-FIXES: dq.emplace_back(3);
+
+  typedef std::stack STACK;
+  using PQ = std::priority_queue;
+  STACK stack;
+  stack.emplace(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: unnecessary te

[clang-tools-extra] cc09b81 - [CTE][docs] Fix bad links in ReleaseNotes

2022-09-01 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-09-01T12:10:53+01:00
New Revision: cc09b81265e9543b9b78a2687e7b5c818a137a59

URL: 
https://github.com/llvm/llvm-project/commit/cc09b81265e9543b9b78a2687e7b5c818a137a59
DIFF: 
https://github.com/llvm/llvm-project/commit/cc09b81265e9543b9b78a2687e7b5c818a137a59.diff

LOG: [CTE][docs] Fix bad links in ReleaseNotes

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 9bd3a5fc799cf..55c8c341bff3a 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -130,7 +130,8 @@ Changes in existing checks
   would be emitted for uninitialized members of an anonymous union despite
   there being an initializer for one of the other members.
 
-- Improved `modernize-use-emplace 
`_ check.
+- Improved :doc:`modernize-use-emplace 
`
+  check.
 
   The check now supports detecting inefficient invocations of ``push`` and
   ``push_front`` on STL-style containers and replacing them with ``emplace``
@@ -140,7 +141,8 @@ Changes in existing checks
   ``push_front`` on STL-style containers and replacing them with 
``emplace_back``,
   ``emplace`` or ``emplace_front``.
 
-- Improved `modernize-use-equals-default 
`_ check.
+- Improved :doc:`modernize-use-equals-default 
`
+  check.
 
   The check now skips unions since in this case a default constructor with 
empty body
   is not equivalent to the explicitly defaulted one.



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


[clang] 54f57d3 - [clang] Add a fixit for warn-self-assign if LHS is a field with the same name as parameter on RHS

2022-07-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-07-09T08:28:07+01:00
New Revision: 54f57d3847c00d0233e287ebb5283d04e6083062

URL: 
https://github.com/llvm/llvm-project/commit/54f57d3847c00d0233e287ebb5283d04e6083062
DIFF: 
https://github.com/llvm/llvm-project/commit/54f57d3847c00d0233e287ebb5283d04e6083062.diff

LOG: [clang] Add a fixit for warn-self-assign if LHS is a field with the same 
name as parameter on RHS

Add a fix-it for the common case of setters/constructors using parameters with 
the same name as fields
```lang=c++
struct A{
  int X;
  A(int X) { /*this->*/X = X; }
  void setX(int X) { /*this->*/X = X;
};
```

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D129202

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/warn-self-assign-builtin.cpp
clang/test/SemaCXX/warn-self-assign-field-builtin.cpp
clang/test/SemaCXX/warn-self-move.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c6d36568099b4..5dae6205efa05 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -279,6 +279,9 @@ Improvements to Clang's diagnostics
   unevaluated operands of a ``typeid`` expression, as they are now
   modeled correctly in the CFG. This fixes
   `Issue 21668 `_.
+- ``-Wself-assign``, ``-Wself-assign-overloaded`` and ``-Wself-move`` will 
+  suggest a fix if the decl being assigned is a parameter that shadows a data
+  member of the contained class.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index fd10bd9c70e6a..0d25c718d09e9 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6610,13 +6610,16 @@ def warn_addition_in_bitshift : Warning<
   "'%1' will be evaluated first">, InGroup;
 
 def warn_self_assignment_builtin : Warning<
-  "explicitly assigning value of variable of type %0 to itself">,
+  "explicitly assigning value of variable of type %0 to itself%select{|; did "
+  "you mean to assign to member %2?}1">,
   InGroup, DefaultIgnore;
 def warn_self_assignment_overloaded : Warning<
-  "explicitly assigning value of variable of type %0 to itself">,
+  "explicitly assigning value of variable of type %0 to itself%select{|; did "
+  "you mean to assign to member %2?}1">,
   InGroup, DefaultIgnore;
 def warn_self_move : Warning<
-  "explicitly moving variable of type %0 to itself">,
+  "explicitly moving variable of type %0 to itself%select{|; did you mean to "
+  "move to member %2?}1">,
   InGroup, DefaultIgnore;
 
 def err_builtin_move_forward_unsupported : Error<

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4fc53a0697a5c..75a2e7eb31d19 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -5170,6 +5170,11 @@ class Sema final {
   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
 SourceLocation OpLoc);
 
+  /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
+  /// SelfAssigned when inside a CXXMethodDecl.
+  const FieldDecl *
+  getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
+
   /// Warn if we're implicitly casting from a _Nullable pointer type to a
   /// _Nonnull one.
   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 3ed745c5634c8..d3929361213ad 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16830,9 +16830,15 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const 
Expr *RHSExpr,
 RHSDeclRef->getDecl()->getCanonicalDecl())
   return;
 
-Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
-<< LHSExpr->getSourceRange()
-<< RHSExpr->getSourceRange();
+auto D = Diag(OpLoc, diag::warn_self_move)
+ << LHSExpr->getType() << LHSExpr->getSourceRange()
+ << RHSExpr->getSourceRange();
+if (const FieldDecl *F =
+getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl()))
+  D << 1 << F
+<< FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
+else
+  D << 0;
 return;
   }
 
@@ -16867,16 +16873,16 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, 
const Expr *RHSExpr,
 RHSDeclRef->getDecl()->getCanonicalDecl())
   return;
 
-Diag(OpLoc, diag::warn_self_move) << LH

[clang] b97f260 - Reland "[ASTMatchers] Output currently processing match and nodes on crash"

2022-03-25 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-25T17:53:58Z
New Revision: b97f26083bd04ccbdd63b0c726e047496e5b847a

URL: 
https://github.com/llvm/llvm-project/commit/b97f26083bd04ccbdd63b0c726e047496e5b847a
DIFF: 
https://github.com/llvm/llvm-project/commit/b97f26083bd04ccbdd63b0c726e047496e5b847a.diff

LOG: Reland "[ASTMatchers] Output currently processing match and nodes on crash"

This reverts commit cff34ccb605aa78030cd51cfe44362ed1c1fb80b.

This relands commit d89f9e963e4979466193dc6a15fe091bf7ca5c47

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b54fca707eda8..282cf1d0a4cc1 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,6 +96,9 @@ The improvements are...
 Improvements to clang-tidy
 --
 
+- Added trace code to help narrow down any checks and the relevant source code
+  that result in crashes.
+
 New checks
 ^^
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index b19a7fe3be04c..70598460151ae 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Timer.h"
 #include 
 #include 
@@ -760,11 +761,67 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+  class TraceReporter : llvm::PrettyStackTraceEntry {
+  public:
+TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
+void print(raw_ostream &OS) const override {
+  if (!MV.CurMatched) {
+OS << "ASTMatcher: Not currently matching\n";
+return;
+  }
+  assert(MV.ActiveASTContext &&
+ "ActiveASTContext should be set if there is a matched callback");
+
+  OS << "ASTMatcher: Processing '" << MV.CurMatched->getID() << "'\n";
+  const BoundNodes::IDToNodeMap &Map = MV.CurBoundNodes->getMap();
+  if (Map.empty()) {
+OS << "No bound nodes\n";
+return;
+  }
+  OS << "--- Bound Nodes Begin ---\n";
+  for (const auto &Item : Map) {
+OS << "" << Item.first << " - { ";
+if (const auto *D = Item.second.get()) {
+  OS << D->getDeclKindName() << "Decl ";
+  if (const auto *ND = dyn_cast(D)) {
+ND->printQualifiedName(OS);
+OS << " : ";
+  } else
+OS << ": ";
+  D->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *S = Item.second.get()) {
+  OS << S->getStmtClassName() << " : ";
+  S->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *T = Item.second.get()) {
+  OS << T->getTypeClassName() << "Type : ";
+  QualType(T, 0).print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else if (const auto *QT = Item.second.get()) {
+  OS << "QualType : ";
+  QT->print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else {
+  OS << Item.second.getNodeKind().asStringRef() << " : ";
+  Item.second.getSourceRange().print(
+  OS, MV.ActiveASTContext->getSourceManager());
+}
+OS << " }\n";
+  }
+  OS << "--- Bound Nodes End ---\n";
+}
+
+  private:
+const MatchASTVisitor &MV;
+  };
+
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
+  const MatchCallback *CurMatched = nullptr;
+  const BoundNodes *CurBoundNodes = nullptr;
+
   struct ASTNodeNotSpelledInSourceScope {
 ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
 : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
@@ -831,7 +888,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Timer.setBucket(&TimeByBucket[MP.second->getID()]);
   BoundNodesTreeBuilder Builder;
   if (MP.first.matches(Node, this, &Builder)) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);
   }
 }
@@ -863,7 +920,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   }
 
   if (MP.first.matches(DynNode, this, &Builder)) {
-MatchVisitor Visitor(ActiveASTContext, MP.second);
+MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);

[clang] 6e33e45 - [ASTMatchers] Output currently matching node on crash

2022-03-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-30T17:14:00+01:00
New Revision: 6e33e45b943061f79ab6de1b60d04d4c6f32f8f9

URL: 
https://github.com/llvm/llvm-project/commit/6e33e45b943061f79ab6de1b60d04d4c6f32f8f9
DIFF: 
https://github.com/llvm/llvm-project/commit/6e33e45b943061f79ab6de1b60d04d4c6f32f8f9.diff

LOG: [ASTMatchers] Output currently matching node on crash

Extend D120185 to also log the node being matched on in case of a crash.
This can help if a matcher is causing a crash or there are not enough 
interesting nodes bound.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D122529

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 70598460151ae..e4141232d1c6f 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -761,53 +761,166 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+private:
+  bool TraversingASTNodeNotSpelledInSource = false;
+  bool TraversingASTNodeNotAsIs = false;
+  bool TraversingASTChildrenNotSpelledInSource = false;
+
+  class CurMatchData {
+  public:
+CurMatchData() = default;
+
+template 
+void SetCallbackAndRawNode(const MatchCallback *CB, const NodeType &N) {
+  assertEmpty();
+  Callback = CB;
+  MatchingNode = &N;
+}
+
+const MatchCallback *getCallback() const { return Callback; }
+
+void SetBoundNodes(const BoundNodes &BN) {
+  assertHoldsState();
+  BNodes = &BN;
+}
+
+void clearBoundNodes() {
+  assertHoldsState();
+  BNodes = nullptr;
+}
+
+template  const T *getNode() const {
+  assertHoldsState();
+  return MatchingNode.dyn_cast();
+}
+
+const BoundNodes *getBoundNodes() const {
+  assertHoldsState();
+  return BNodes;
+}
+
+void reset() {
+  assertHoldsState();
+  Callback = nullptr;
+  MatchingNode = nullptr;
+}
+
+  private:
+void assertHoldsState() const {
+  assert(Callback != nullptr && !MatchingNode.isNull());
+}
+
+void assertEmpty() const {
+  assert(Callback == nullptr && MatchingNode.isNull() && BNodes == 
nullptr);
+}
+
+const MatchCallback *Callback = nullptr;
+const BoundNodes *BNodes = nullptr;
+
+llvm::PointerUnion<
+const QualType *, const TypeLoc *, const NestedNameSpecifier *,
+const NestedNameSpecifierLoc *, const CXXCtorInitializer *,
+const TemplateArgumentLoc *, const Attr *, const DynTypedNode *>
+MatchingNode;
+  } CurMatchState;
+
+  struct CurMatchRAII {
+template 
+CurMatchRAII(MatchASTVisitor &MV, const MatchCallback *CB,
+ const NodeType &NT)
+: MV(MV) {
+  MV.CurMatchState.SetCallbackAndRawNode(CB, NT);
+}
+
+~CurMatchRAII() { MV.CurMatchState.reset(); }
+
+  private:
+MatchASTVisitor &MV;
+  };
+
+public:
   class TraceReporter : llvm::PrettyStackTraceEntry {
+static void dumpNode(const ASTContext &Ctx, const DynTypedNode &Node,
+ raw_ostream &OS) {
+  if (const auto *D = Node.get()) {
+OS << D->getDeclKindName() << "Decl ";
+if (const auto *ND = dyn_cast(D)) {
+  ND->printQualifiedName(OS);
+  OS << " : ";
+} else
+  OS << ": ";
+D->getSourceRange().print(OS, Ctx.getSourceManager());
+  } else if (const auto *S = Node.get()) {
+OS << S->getStmtClassName() << " : ";
+S->getSourceRange().print(OS, Ctx.getSourceManager());
+  } else if (const auto *T = Node.get()) {
+OS << T->getTypeClassName() << "Type : ";
+QualType(T, 0).print(OS, Ctx.getPrintingPolicy());
+  } else if (const auto *QT = Node.get()) {
+OS << "QualType : ";
+QT->print(OS, Ctx.getPrintingPolicy());
+  } else {
+OS << Node.getNodeKind().asStringRef() << " : ";
+Node.getSourceRange().print(OS, Ctx.getSourceManager());
+  }
+}
+
+static void dumpNodeFromState(const ASTContext &Ctx,
+  const CurMatchData &State, raw_ostream &OS) {
+  if (const DynTypedNode *MatchNode = State.getNode()) {
+dumpNode(Ctx, *MatchNode, OS);
+  } else if (const auto *QT = State.getNode()) {
+dumpNode(Ctx, DynTypedNode::create(*QT), OS);
+  } else if (const auto *TL = State.getNode()) {
+dumpNode(Ctx, DynTypedNode::create(*TL), OS);
+  } else if (const auto *NNS = State.getNode()) {
+dumpNode(Ctx, DynTypedNode::create(*NNS), OS);
+  } else if (const auto *NNSL = State.getNode()) {
+dumpNode(Ctx, DynTypedNode::create(*NNSL), OS);
+  } else if (const auto *CtorInit = State.getNode()) {
+dumpNode(Ctx, DynTypedNode::create(*

[clang] 61d67c8 - Revert "[ASTMatchers] Output currently matching node on crash"

2022-03-30 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-30T18:10:48+01:00
New Revision: 61d67c8eecd2547bc690f9a6bba61b9ba814c71b

URL: 
https://github.com/llvm/llvm-project/commit/61d67c8eecd2547bc690f9a6bba61b9ba814c71b
DIFF: 
https://github.com/llvm/llvm-project/commit/61d67c8eecd2547bc690f9a6bba61b9ba814c71b.diff

LOG: Revert "[ASTMatchers] Output currently matching node on crash"

This reverts commit 6e33e45b943061f79ab6de1b60d04d4c6f32f8f9.

Fails to build on 32bit machines due to PointerUnion limitations

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index e4141232d1c6f..70598460151ae 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -761,166 +761,53 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
-private:
-  bool TraversingASTNodeNotSpelledInSource = false;
-  bool TraversingASTNodeNotAsIs = false;
-  bool TraversingASTChildrenNotSpelledInSource = false;
-
-  class CurMatchData {
-  public:
-CurMatchData() = default;
-
-template 
-void SetCallbackAndRawNode(const MatchCallback *CB, const NodeType &N) {
-  assertEmpty();
-  Callback = CB;
-  MatchingNode = &N;
-}
-
-const MatchCallback *getCallback() const { return Callback; }
-
-void SetBoundNodes(const BoundNodes &BN) {
-  assertHoldsState();
-  BNodes = &BN;
-}
-
-void clearBoundNodes() {
-  assertHoldsState();
-  BNodes = nullptr;
-}
-
-template  const T *getNode() const {
-  assertHoldsState();
-  return MatchingNode.dyn_cast();
-}
-
-const BoundNodes *getBoundNodes() const {
-  assertHoldsState();
-  return BNodes;
-}
-
-void reset() {
-  assertHoldsState();
-  Callback = nullptr;
-  MatchingNode = nullptr;
-}
-
-  private:
-void assertHoldsState() const {
-  assert(Callback != nullptr && !MatchingNode.isNull());
-}
-
-void assertEmpty() const {
-  assert(Callback == nullptr && MatchingNode.isNull() && BNodes == 
nullptr);
-}
-
-const MatchCallback *Callback = nullptr;
-const BoundNodes *BNodes = nullptr;
-
-llvm::PointerUnion<
-const QualType *, const TypeLoc *, const NestedNameSpecifier *,
-const NestedNameSpecifierLoc *, const CXXCtorInitializer *,
-const TemplateArgumentLoc *, const Attr *, const DynTypedNode *>
-MatchingNode;
-  } CurMatchState;
-
-  struct CurMatchRAII {
-template 
-CurMatchRAII(MatchASTVisitor &MV, const MatchCallback *CB,
- const NodeType &NT)
-: MV(MV) {
-  MV.CurMatchState.SetCallbackAndRawNode(CB, NT);
-}
-
-~CurMatchRAII() { MV.CurMatchState.reset(); }
-
-  private:
-MatchASTVisitor &MV;
-  };
-
-public:
   class TraceReporter : llvm::PrettyStackTraceEntry {
-static void dumpNode(const ASTContext &Ctx, const DynTypedNode &Node,
- raw_ostream &OS) {
-  if (const auto *D = Node.get()) {
-OS << D->getDeclKindName() << "Decl ";
-if (const auto *ND = dyn_cast(D)) {
-  ND->printQualifiedName(OS);
-  OS << " : ";
-} else
-  OS << ": ";
-D->getSourceRange().print(OS, Ctx.getSourceManager());
-  } else if (const auto *S = Node.get()) {
-OS << S->getStmtClassName() << " : ";
-S->getSourceRange().print(OS, Ctx.getSourceManager());
-  } else if (const auto *T = Node.get()) {
-OS << T->getTypeClassName() << "Type : ";
-QualType(T, 0).print(OS, Ctx.getPrintingPolicy());
-  } else if (const auto *QT = Node.get()) {
-OS << "QualType : ";
-QT->print(OS, Ctx.getPrintingPolicy());
-  } else {
-OS << Node.getNodeKind().asStringRef() << " : ";
-Node.getSourceRange().print(OS, Ctx.getSourceManager());
-  }
-}
-
-static void dumpNodeFromState(const ASTContext &Ctx,
-  const CurMatchData &State, raw_ostream &OS) {
-  if (const DynTypedNode *MatchNode = State.getNode()) {
-dumpNode(Ctx, *MatchNode, OS);
-  } else if (const auto *QT = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*QT), OS);
-  } else if (const auto *TL = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*TL), OS);
-  } else if (const auto *NNS = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*NNS), OS);
-  } else if (const auto *NNSL = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*NNSL), OS);
-  } else if (const auto *CtorInit = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*CtorInit), OS);
-  } else if (const auto *TAL = State.getNode()) {
-dumpNode(Ctx, DynTypedNode::create(*T

[clang] b4ad3c3 - Reland "[ASTMatchers] Output currently matching node on crash"

2022-04-05 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-04-05T21:47:16+01:00
New Revision: b4ad3c3891e550b04db3aca73e1f34007e94eaa8

URL: 
https://github.com/llvm/llvm-project/commit/b4ad3c3891e550b04db3aca73e1f34007e94eaa8
DIFF: 
https://github.com/llvm/llvm-project/commit/b4ad3c3891e550b04db3aca73e1f34007e94eaa8.diff

LOG: Reland "[ASTMatchers] Output currently matching node on crash"

Extend D120185 to also log the node being matched on in case of a crash.
This can help if a matcher is causing a crash or there are not enough 
interesting nodes bound.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D122529

This reverts commit 61d67c8eecd2547bc690f9a6bba61b9ba814c71b.

This relands commit 6e33e45b943061f79ab6de1b60d04d4c6f32f8f9.

Fixing the build issue on 32bit machines due to not enough free bits in the 
PointerUnion.

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 70598460151ae..5d245d3fc9b76 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -761,53 +761,189 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+private:
+  bool TraversingASTNodeNotSpelledInSource = false;
+  bool TraversingASTNodeNotAsIs = false;
+  bool TraversingASTChildrenNotSpelledInSource = false;
+
+  class CurMatchData {
+// We don't have enough free low bits in 32bit builds to discriminate 8 pointer
+// types in PointerUnion. so split the union in 2 using a free bit from the
+// callback pointer.
+#define CMD_TYPES_0
\
+  const QualType *, const TypeLoc *, const NestedNameSpecifier *,  
\
+  const NestedNameSpecifierLoc *
+#define CMD_TYPES_1
\
+  const CXXCtorInitializer *, const TemplateArgumentLoc *, const Attr *,   
\
+  const DynTypedNode *
+
+#define IMPL(Index)
\
+  template  
\
+  typename std::enable_if_t<   
\
+  llvm::is_one_of::value> 
\
+  SetCallbackAndRawNode(const MatchCallback *CB, const NodeType &N) {  
\
+assertEmpty(); 
\
+Callback.setPointerAndInt(CB, Index);  
\
+Node##Index = &N;  
\
+  }
\
+   
\
+  template 
\
+  typename std::enable_if_t<   
\
+  llvm::is_one_of::value, const T *> 
\
+  getNode() const {
\
+assertHoldsState();
\
+return Callback.getInt() == (Index) ? Node##Index.dyn_cast()
\
+: nullptr; 
\
+  }
+
+  public:
+CurMatchData() : Node0(nullptr) {}
+
+IMPL(0)
+IMPL(1)
+
+const MatchCallback *getCallback() const { return Callback.getPointer(); }
+
+void SetBoundNodes(const BoundNodes &BN) {
+  assertHoldsState();
+  BNodes = &BN;
+}
+
+void clearBoundNodes() {
+  assertHoldsState();
+  BNodes = nullptr;
+}
+
+const BoundNodes *getBoundNodes() const {
+  assertHoldsState();
+  return BNodes;
+}
+
+void reset() {
+  assertHoldsState();
+  Callback.setPointerAndInt(nullptr, 0);
+  Node0 = nullptr;
+}
+
+  private:
+void assertHoldsState() const {
+  assert(Callback.getPointer() != nullptr && !Node0.isNull());
+}
+
+void assertEmpty() const {
+  assert(Callback.getPointer() == nullptr && Node0.isNull() &&
+ BNodes == nullptr);
+}
+
+llvm::PointerIntPair Callback;
+union {
+  llvm::PointerUnion Node0;
+  llvm::PointerUnion Node1;
+};
+const BoundNodes *BNodes = nullptr;
+
+#undef CMD_TYPES_0
+#undef CMD_TYPES_1
+#undef IMPL
+  } CurMatchState;
+
+  struct CurMatchRAII {
+template 
+CurMatchRAII(MatchASTVisitor &MV, const MatchCallback *CB,
+ const NodeType &NT)
+: MV(MV) {
+  MV.CurMatchState.SetCallbackAndRawNode(CB, NT);
+}
+
+~CurMatchRAII() { MV.CurMatchState.reset(); }
+
+  private:
+MatchASTVisitor &MV;
+  };
+
+public:
   class TraceReporter : llvm::PrettyStackTraceEntry {
+static void dumpNode(const 

[clang-tools-extra] 61c422f - [clang-tidy] Add execute perms back to add_new_check script

2022-07-27 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-07-27T10:41:34+01:00
New Revision: 61c422f274a07bcf2af9ebbb24f9fde879a8cc30

URL: 
https://github.com/llvm/llvm-project/commit/61c422f274a07bcf2af9ebbb24f9fde879a8cc30
DIFF: 
https://github.com/llvm/llvm-project/commit/61c422f274a07bcf2af9ebbb24f9fde879a8cc30.diff

LOG: [clang-tidy] Add execute perms back to add_new_check script

Added: 


Modified: 
clang-tools-extra/clang-tidy/add_new_check.py

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/add_new_check.py 
b/clang-tools-extra/clang-tidy/add_new_check.py
old mode 100644
new mode 100755



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


[clang-tools-extra] 4c106c9 - [clangd] Change the url for clang-tidy check documentation

2022-08-05 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-05T08:42:52+01:00
New Revision: 4c106c93eb68f8f9f201202677cd31e326c16823

URL: 
https://github.com/llvm/llvm-project/commit/4c106c93eb68f8f9f201202677cd31e326c16823
DIFF: 
https://github.com/llvm/llvm-project/commit/4c106c93eb68f8f9f201202677cd31e326c16823.diff

LOG: [clangd] Change the url for clang-tidy check documentation

In 
https://github.com/llvm/llvm-project/commit/6e566bc5523f743bc34a7e26f050f1f2b4d699a8,
 The directory structure of the documentation for clang-tidy checks was 
changed, however clangd wasn't updated.
Now all the links generated will point to old dead pages.
This updated clangd to use the new page structure.

Reviewed By: sammccall, kadircet

Differential Revision: https://reviews.llvm.org/D128379

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.cpp
clang-tools-extra/clangd/test/diagnostics-tidy.test

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index e70d45769fe46..031192f763e6e 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -918,9 +918,19 @@ llvm::Optional 
getDiagnosticDocURI(Diag::DiagSource Source,
 // information to be worth linking.
 // https://clang.llvm.org/docs/DiagnosticsReference.html
 break;
-  case Diag::ClangTidy:
-return {("https://clang.llvm.org/extra/clang-tidy/checks/"; + Name + 
".html")
-.str()};
+  case Diag::ClangTidy: {
+StringRef Module, Check;
+// This won't correctly get the module for clang-analyzer checks, but as we
+// don't link in the analyzer that shouldn't be an issue.
+// This would also need updating if anyone decides to create a module with 
a
+// '-' in the name.
+std::tie(Module, Check) = Name.split('-');
+if (Module.empty() || Check.empty())
+  return llvm::None;
+return ("https://clang.llvm.org/extra/clang-tidy/checks/"; + Module + "/" +
+Check + ".html")
+.str();
+  }
   case Diag::Clangd:
 if (Name == "unused-includes")
   return {"https://clangd.llvm.org/guides/include-cleaner"};

diff  --git a/clang-tools-extra/clangd/test/diagnostics-tidy.test 
b/clang-tools-extra/clangd/test/diagnostics-tidy.test
index c7e79b0c6d5f5..a100c9f4359d1 100644
--- a/clang-tools-extra/clangd/test/diagnostics-tidy.test
+++ b/clang-tools-extra/clangd/test/diagnostics-tidy.test
@@ -9,7 +9,7 @@
 # CHECK-NEXT:  {
 # CHECK-NEXT:"code": "bugprone-sizeof-expression",
 # CHECK-NEXT:"codeDescription": {
-# CHECK-NEXT:  "href": 
"https://clang.llvm.org/extra/clang-tidy/checks/bugprone-sizeof-expression.html";
+# CHECK-NEXT:  "href": 
"https://clang.llvm.org/extra/clang-tidy/checks/bugprone/sizeof-expression.html";
 # CHECK-NEXT:},
 # CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 
'K'?",
 # CHECK-NEXT:"range": {



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


[clang] 7042417 - [NFC][clang] Bring `and_present` and `if_present` casting functions to clang namespace

2022-08-08 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-08-08T08:38:50+01:00
New Revision: 7042417ef11ce34300908c53ee9659bf8f2ab9ec

URL: 
https://github.com/llvm/llvm-project/commit/7042417ef11ce34300908c53ee9659bf8f2ab9ec
DIFF: 
https://github.com/llvm/llvm-project/commit/7042417ef11ce34300908c53ee9659bf8f2ab9ec.diff

LOG: [NFC][clang] Bring `and_present` and `if_present` casting functions to 
clang namespace

This should enable simpler migration when the `and_nonnull` and `or_null` 
functions are deprecated.

Added: 


Modified: 
clang/include/clang/Basic/LLVM.h

Removed: 




diff  --git a/clang/include/clang/Basic/LLVM.h 
b/clang/include/clang/Basic/LLVM.h
index 4ac2d744af3c3..955299504ece7 100644
--- a/clang/include/clang/Basic/LLVM.h
+++ b/clang/include/clang/Basic/LLVM.h
@@ -58,10 +58,13 @@ namespace clang {
   // Casting operators.
   using llvm::isa;
   using llvm::isa_and_nonnull;
+  using llvm::isa_and_present;
   using llvm::cast;
   using llvm::dyn_cast;
   using llvm::dyn_cast_or_null;
+  using llvm::dyn_cast_if_present;
   using llvm::cast_or_null;
+  using llvm::cast_if_present;
 
   // ADT's.
   using llvm::ArrayRef;



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


[clang] d89f9e9 - [ASTMatchers] Output currently processing match and nodes on crash

2022-03-21 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-21T19:13:36Z
New Revision: d89f9e963e4979466193dc6a15fe091bf7ca5c47

URL: 
https://github.com/llvm/llvm-project/commit/d89f9e963e4979466193dc6a15fe091bf7ca5c47
DIFF: 
https://github.com/llvm/llvm-project/commit/d89f9e963e4979466193dc6a15fe091bf7ca5c47.diff

LOG: [ASTMatchers] Output currently processing match and nodes on crash

Create a PrettyStackTraceEvent that will dump the current `MatchCallback` id as 
well as the `BoundNodes` if the 'run' method of a `MatchCallback` results in a 
crash.
The purpose of this is sometimes clang-tidy checks can crash in the `check` 
method. And in a large codebase with alot of checks enabled and in a release 
build, it can be near impossible to figure out which check as well as the 
source code that caused the crash. Without that information a reproducer is 
very hard to create.
This is a more generalised version of D118520 which has a nicer integration and 
should be useful to clients other than clang-tidy.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D120185

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 551e36dea0937..ca4aea676eda3 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,6 +96,9 @@ The improvements are...
 Improvements to clang-tidy
 --
 
+- Added trace code to help narrow down any checks and the relevant source code
+  that result in crashes.
+
 New checks
 ^^
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index b19a7fe3be04c..70598460151ae 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Timer.h"
 #include 
 #include 
@@ -760,11 +761,67 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
+  class TraceReporter : llvm::PrettyStackTraceEntry {
+  public:
+TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
+void print(raw_ostream &OS) const override {
+  if (!MV.CurMatched) {
+OS << "ASTMatcher: Not currently matching\n";
+return;
+  }
+  assert(MV.ActiveASTContext &&
+ "ActiveASTContext should be set if there is a matched callback");
+
+  OS << "ASTMatcher: Processing '" << MV.CurMatched->getID() << "'\n";
+  const BoundNodes::IDToNodeMap &Map = MV.CurBoundNodes->getMap();
+  if (Map.empty()) {
+OS << "No bound nodes\n";
+return;
+  }
+  OS << "--- Bound Nodes Begin ---\n";
+  for (const auto &Item : Map) {
+OS << "" << Item.first << " - { ";
+if (const auto *D = Item.second.get()) {
+  OS << D->getDeclKindName() << "Decl ";
+  if (const auto *ND = dyn_cast(D)) {
+ND->printQualifiedName(OS);
+OS << " : ";
+  } else
+OS << ": ";
+  D->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *S = Item.second.get()) {
+  OS << S->getStmtClassName() << " : ";
+  S->getSourceRange().print(OS,
+MV.ActiveASTContext->getSourceManager());
+} else if (const auto *T = Item.second.get()) {
+  OS << T->getTypeClassName() << "Type : ";
+  QualType(T, 0).print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else if (const auto *QT = Item.second.get()) {
+  OS << "QualType : ";
+  QT->print(OS, MV.ActiveASTContext->getPrintingPolicy());
+} else {
+  OS << Item.second.getNodeKind().asStringRef() << " : ";
+  Item.second.getSourceRange().print(
+  OS, MV.ActiveASTContext->getSourceManager());
+}
+OS << " }\n";
+  }
+  OS << "--- Bound Nodes End ---\n";
+}
+
+  private:
+const MatchASTVisitor &MV;
+  };
+
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
+  const MatchCallback *CurMatched = nullptr;
+  const BoundNodes *CurBoundNodes = nullptr;
+
   struct ASTNodeNotSpelledInSourceScope {
 ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
 : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
@@ -831,7 +888,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Timer.setBucket(&TimeByBucket[MP.second->getID()]);
   

[clang] cff34cc - Revert "[ASTMatchers] Output currently processing match and nodes on crash"

2022-03-21 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-03-21T22:29:22Z
New Revision: cff34ccb605aa78030cd51cfe44362ed1c1fb80b

URL: 
https://github.com/llvm/llvm-project/commit/cff34ccb605aa78030cd51cfe44362ed1c1fb80b
DIFF: 
https://github.com/llvm/llvm-project/commit/cff34ccb605aa78030cd51cfe44362ed1c1fb80b.diff

LOG: Revert "[ASTMatchers] Output currently processing match and nodes on crash"

This reverts commit d89f9e963e4979466193dc6a15fe091bf7ca5c47.

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ca4aea676eda3..551e36dea0937 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,9 +96,6 @@ The improvements are...
 Improvements to clang-tidy
 --
 
-- Added trace code to help narrow down any checks and the relevant source code
-  that result in crashes.
-
 New checks
 ^^
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 70598460151ae..b19a7fe3be04c 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -21,7 +21,6 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Timer.h"
 #include 
 #include 
@@ -761,67 +760,11 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 D);
   }
 
-  class TraceReporter : llvm::PrettyStackTraceEntry {
-  public:
-TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
-void print(raw_ostream &OS) const override {
-  if (!MV.CurMatched) {
-OS << "ASTMatcher: Not currently matching\n";
-return;
-  }
-  assert(MV.ActiveASTContext &&
- "ActiveASTContext should be set if there is a matched callback");
-
-  OS << "ASTMatcher: Processing '" << MV.CurMatched->getID() << "'\n";
-  const BoundNodes::IDToNodeMap &Map = MV.CurBoundNodes->getMap();
-  if (Map.empty()) {
-OS << "No bound nodes\n";
-return;
-  }
-  OS << "--- Bound Nodes Begin ---\n";
-  for (const auto &Item : Map) {
-OS << "" << Item.first << " - { ";
-if (const auto *D = Item.second.get()) {
-  OS << D->getDeclKindName() << "Decl ";
-  if (const auto *ND = dyn_cast(D)) {
-ND->printQualifiedName(OS);
-OS << " : ";
-  } else
-OS << ": ";
-  D->getSourceRange().print(OS,
-MV.ActiveASTContext->getSourceManager());
-} else if (const auto *S = Item.second.get()) {
-  OS << S->getStmtClassName() << " : ";
-  S->getSourceRange().print(OS,
-MV.ActiveASTContext->getSourceManager());
-} else if (const auto *T = Item.second.get()) {
-  OS << T->getTypeClassName() << "Type : ";
-  QualType(T, 0).print(OS, MV.ActiveASTContext->getPrintingPolicy());
-} else if (const auto *QT = Item.second.get()) {
-  OS << "QualType : ";
-  QT->print(OS, MV.ActiveASTContext->getPrintingPolicy());
-} else {
-  OS << Item.second.getNodeKind().asStringRef() << " : ";
-  Item.second.getSourceRange().print(
-  OS, MV.ActiveASTContext->getSourceManager());
-}
-OS << " }\n";
-  }
-  OS << "--- Bound Nodes End ---\n";
-}
-
-  private:
-const MatchASTVisitor &MV;
-  };
-
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
   bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
-  const MatchCallback *CurMatched = nullptr;
-  const BoundNodes *CurBoundNodes = nullptr;
-
   struct ASTNodeNotSpelledInSourceScope {
 ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
 : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
@@ -888,7 +831,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Timer.setBucket(&TimeByBucket[MP.second->getID()]);
   BoundNodesTreeBuilder Builder;
   if (MP.first.matches(Node, this, &Builder)) {
-MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
+MatchVisitor Visitor(ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);
   }
 }
@@ -920,7 +863,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   }
 
   if (MP.first.matches(DynNode, this, &Builder)) {
-MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
+MatchVisitor Visitor(ActiveASTContext, MP.second);
 Builder.visitMatches(&Visitor);
   }
 }
@@ -1106,36 +1049,18 @@ class MatchASTVisitor 

[clang-tools-extra] d0fcbb3 - [clang-tidy] Fix invalid fix-it for cppcoreguidelines-prefer-member-initializer

2022-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-04-07T19:13:50+01:00
New Revision: d0fcbb37838a653c1c3f8d6ac83e64714c407b19

URL: 
https://github.com/llvm/llvm-project/commit/d0fcbb37838a653c1c3f8d6ac83e64714c407b19
DIFF: 
https://github.com/llvm/llvm-project/commit/d0fcbb37838a653c1c3f8d6ac83e64714c407b19.diff

LOG: [clang-tidy] Fix invalid fix-it for 
cppcoreguidelines-prefer-member-initializer

Fixes https://github.com/llvm/llvm-project/issues/53515.

Reviewed By: LegalizeAdulthood

Differential Revision: https://reviews.llvm.org/D118927

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
index 169b828a3c926..4ff362476a0c3 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -201,30 +201,42 @@ void PreferMemberInitializerCheck::check(
 diag(S->getBeginLoc(), "%0 should be initialized in an in-class"
" default member initializer")
 << Field;
-if (!InvalidFix) {
-  CharSourceRange StmtRange =
-  CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
-
-  SmallString<128> Insertion(
-  {UseAssignment ? " = " : "{",
-   Lexer::getSourceText(
-   CharSourceRange(InitValue->getSourceRange(), true),
-   *Result.SourceManager, getLangOpts()),
-   UseAssignment ? "" : "}"});
-
-  Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
-   << FixItHint::CreateRemoval(StmtRange);
-}
+if (InvalidFix)
+  continue;
+CharSourceRange StmtRange =
+CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
+
+SmallString<128> Insertion(
+{UseAssignment ? " = " : "{",
+ Lexer::getSourceText(
+ CharSourceRange(InitValue->getSourceRange(), true),
+ *Result.SourceManager, getLangOpts()),
+ UseAssignment ? "" : "}"});
+
+Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
+ << FixItHint::CreateRemoval(StmtRange);
+
   } else {
 StringRef InsertPrefix = "";
+bool HasInitAlready = false;
 SourceLocation InsertPos;
+SourceRange ReplaceRange;
 bool AddComma = false;
 bool InvalidFix = false;
 unsigned Index = Field->getFieldIndex();
 const CXXCtorInitializer *LastInListInit = nullptr;
 for (const CXXCtorInitializer *Init : Ctor->inits()) {
-  if (!Init->isWritten())
+  if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
+  if (Init->getMember() == Field) {
+HasInitAlready = true;
+if (isa(Init->getInit()))
+  InsertPos = Init->getRParenLoc();
+else {
+  ReplaceRange = Init->getInit()->getSourceRange();
+}
+break;
+  }
   if (Init->isMemberInitializer() &&
   Index < Init->getMember()->getFieldIndex()) {
 InsertPos = Init->getSourceLocation();
@@ -235,30 +247,38 @@ void PreferMemberInitializerCheck::check(
   }
   LastInListInit = Init;
 }
-if (InsertPos.isInvalid()) {
-  if (LastInListInit) {
-InsertPos = Lexer::getLocForEndOfToken(
-LastInListInit->getRParenLoc(), 0, *Result.SourceManager,
-getLangOpts());
-// Inserting after the last constructor initializer, so we need a
-// comma.
-InsertPrefix = ", ";
-  } else {
-InsertPos = Lexer::getLocForEndOfToken(
-Ctor->getTypeSourceInfo()
-->getTypeLoc()
-.getAs()
-.getLocalRangeEnd(),
-0, *Result.SourceManager, getLangOpts());
-
-// If this is first time in the loop, there are no initializers so
-// `:` declares member initialization list. If this is a subsequent
-// pass then we have already inserted a `:` so continue with a
-// comma.
-InsertPrefix = FirstToCtorInits ? " : " : ", ";
+if (HasInitAlready) {
+  if (InsertPos.isValid())
+InvalidFix |= InsertPos.isMacroID();
+  else
+InvalidFix |= ReplaceRange.getBegin().isMacroID() ||
+  ReplaceRange.getEnd().is

[clang-tools-extra] 0e0b0fe - [clang-tidy] Make performance-inefficient-vector-operation work on members

2022-04-08 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-04-08T14:17:41+01:00
New Revision: 0e0b0feff194358e5e68bf36f5a563d269fa8e88

URL: 
https://github.com/llvm/llvm-project/commit/0e0b0feff194358e5e68bf36f5a563d269fa8e88
DIFF: 
https://github.com/llvm/llvm-project/commit/0e0b0feff194358e5e68bf36f5a563d269fa8e88.diff

LOG: [clang-tidy] Make performance-inefficient-vector-operation work on members

Fixes https://llvm.org/PR50157

Adds support for when the container being read from in a range-for is a member 
of a struct.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D101624

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-vector-operation.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
index a12d403d6ba09..e8c895e683c4e 100644
--- 
a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp
@@ -68,6 +68,10 @@ ast_matchers::internal::Matcher 
supportedContainerTypesMatcher() {
   "::std::unordered_map", "::std::array", "::std::deque")));
 }
 
+AST_MATCHER(Expr, hasSideEffects) {
+  return Node.HasSideEffects(Finder->getASTContext());
+}
+
 } // namespace
 
 InefficientVectorOperationCheck::InefficientVectorOperationCheck(
@@ -145,7 +149,10 @@ void InefficientVectorOperationCheck::addMatcher(
   // FIXME: Support more complex range-expressions.
   Finder->addMatcher(
   cxxForRangeStmt(
-  hasRangeInit(declRefExpr(supportedContainerTypesMatcher())),
+  hasRangeInit(
+  anyOf(declRefExpr(supportedContainerTypesMatcher()),
+memberExpr(hasObjectExpression(unless(hasSideEffects())),
+   supportedContainerTypesMatcher(,
   HasInterestingLoopBody, InInterestingCompoundStmt)
   .bind(RangeLoopName),
   this);

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 58ddb116f9840..11ed0e3ed2b66 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -127,6 +127,10 @@ New check aliases
 Changes in existing checks
 ^^
 
+- Improved :doc:`performance-inefficient-vector-operation 
+  ` to work when
+  the vector is a member of a structure.
+
 - Fixed a false positive in :doc:`readability-non-const-parameter
   ` when the parameter is 
referenced by an lvalue
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-vector-operation.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-vector-operation.cpp
index c603cf83df238..105d276562175 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-vector-operation.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-vector-operation.cpp
@@ -44,7 +44,7 @@ class vector {
   void reserve(size_t n);
   void resize(size_t n);
 
-  size_t size();
+  size_t size() const;
   const_reference operator[] (size_type) const;
   reference operator[] (size_type);
 
@@ -359,3 +359,31 @@ void f(std::vector& t) {
 }
   }
 }
+
+struct StructWithFieldContainer {
+  std::vector Numbers;
+  std::vector getNumbers() const {
+std::vector Result;
+// CHECK-FIXES: Result.reserve(Numbers.size());
+for (auto Number : Numbers) {
+  Result.push_back(Number);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: 'push_back' is called
+}
+return Result;
+  }
+};
+
+StructWithFieldContainer getStructWithField();
+
+void foo(const StructWithFieldContainer &Src) {
+  std::vector A;
+  // CHECK-FIXES: A.reserve(Src.Numbers.size());
+  for (auto Number : Src.Numbers) {
+A.push_back(Number);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'push_back' is called
+  }
+  std::vector B;
+  for (auto Number : getStructWithField().Numbers) {
+B.push_back(Number);
+  }
+}



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


[clang-tools-extra] b859c39 - [clang-tidy] Add a Standalone diagnostics mode to clang-tidy

2022-04-16 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-04-16T09:53:35+01:00
New Revision: b859c39c40a79ff74033f67d807a18130b9afe30

URL: 
https://github.com/llvm/llvm-project/commit/b859c39c40a79ff74033f67d807a18130b9afe30
DIFF: 
https://github.com/llvm/llvm-project/commit/b859c39c40a79ff74033f67d807a18130b9afe30.diff

LOG: [clang-tidy] Add a Standalone diagnostics mode to clang-tidy

Adds a flag to `ClangTidyContext` that is used to indicate to checks that fixes 
will only be applied one at a time.
This is to indicate to checks that each fix emitted should not depend on any 
other fixes emitted across the translation unit.
I've currently implemented the `IncludeInserter`, `LoopConvertCheck` and 
`PreferMemberInitializerCheck` to use these support these modes.

Reasoning behind this is in use cases like `clangd` it's only possible to apply 
one fix at a time.
For include inserter checks, the include is only added once for the first 
diagnostic that requires it, this will result in subsequent fixes not having 
the included needed.

A similar issue is seen in the `PreferMemberInitializerCheck` where the `:` 
will only be added for the first member that needs fixing.

Fixes emitted in `StandaloneDiagsMode` will likely result in malformed code if 
they are applied all together, conversely fixes currently emitted may result in 
malformed code if they are applied one at a time.
For this reason invoking `clang-tidy` from the binary will always with 
`StandaloneDiagsMode` disabled, However using it as a library its possible to 
select the mode you wish to use, `clangd` always selects `StandaloneDiagsMode`.

This is an example of the current behaviour failing
```lang=c++
struct Foo {
  int A, B;
  Foo(int D, int E) {
A = D;
B = E; // Fix Here
  }
};
```
Incorrectly transformed to:
```lang=c++
struct Foo {
  int A, B;
  Foo(int D, int E), B(E) {
A = D;
 // Fix Here
  }
};
```
In `StandaloneDiagsMode`, it gets transformed to:
```lang=c++
struct Foo {
  int A, B;
  Foo(int D, int E) : B(E) {
A = D;
 // Fix Here
  }
};
```

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D97121

Added: 


Modified: 
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/abseil/StringFindStartswithCheck.cpp

clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.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/TypePromotionInMathFnCheck.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
clang-tools-extra/clang-tidy/utils/IncludeInserter.h
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h 
b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
index 9b41e5836de73..33f84a15b8441 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -417,6 +417,11 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
   StringRef getCurrentMainFile() const { return Context->getCurrentFile(); }
   /// Returns the language options from the context.
   const LangOptions &getLangOpts() const { return Context->getLangOpts(); }
+  /// Returns true when the check is run in a use case when only 1 fix will be
+  /// applied at a time.
+  bool areDiagsSelfContained() const {
+return Context->areDiagsSelfContained();
+  }
 };
 
 /// Read a named option from the ``Context`` and parse it as a bool.

diff  --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 04721a2d3a020..d455473673b09 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -162,7 +162,8 @@ ClangTidyContext::ClangTidyContext(
  

  1   2   3   4   5   >